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.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
feat(model-apps): SDK uptake, silent-failure fixes, genpage input contract, 2.5.0 (#458)
Akshay Maloo451de6eb3546
diff --git a/evals/model-apps/app-builder/evals.json b/evals/model-apps/app-builder/evals.jsonindex 4ab9de3bd..60c26a07f 100644--- a/evals/model-apps/app-builder/evals.json+++ b/evals/model-apps/app-builder/evals.json@@ -24,6 +24,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: authored directEntry survives unchanged","teardown: every declared dashboard has a teardown step","teardown: every declared command bar has a teardown step","ui: enriched default views keep parent lookups and drop createdon",diff --git a/evals/model-apps/app-builder/fixtures/2-orders-multipage/app-spec.json b/evals/model-apps/app-builder/fixtures/2-orders-multipage/app-spec.jsonindex c462f5144..af363c84a 100644--- a/evals/model-apps/app-builder/fixtures/2-orders-multipage/app-spec.json+++ b/evals/model-apps/app-builder/fixtures/2-orders-multipage/app-spec.json@@ -138,6 +138,10 @@"data": {"orderId": "string"}+ },+ "directEntry": {+ "behavior": "selector",+ "note": "Opened from the nav with no orderId, show an order picker and then render the chosen order."}}],diff --git a/evals/model-apps/app-builder/lib/assertions.js b/evals/model-apps/app-builder/lib/assertions.jsindex eab0455ce..21d9c3db0 100644--- a/evals/model-apps/app-builder/lib/assertions.js+++ b/evals/model-apps/app-builder/lib/assertions.js@@ -279,6 +279,17 @@ ASSERTIONS.set('round-trip: the sitemap round-trips with the same subareas', ({: fail(`sitemap drift: authored [${facts.roundTrip.origSubareaTargets}] hydrated [${facts.roundTrip.hydratedSubareaTargets}]`);});+// Hydration DEFAULTS a missing `directEntry` for back-compat with apps deployed before the field+// existed. That default must never overwrite an AUTHORED value — otherwise a round-trip silently+// changes app behaviour while every other losslessness assertion stays green, which is exactly what+// this eval exists to catch.+ASSERTIONS.set('round-trip: authored directEntry survives unchanged', ({ facts }) => {+ if (facts.roundTrip.error) return fail(`hydrate threw: ${facts.roundTrip.error}`);+ const before = JSON.stringify(facts.roundTrip.origDirectEntry || {});+ const after = JSON.stringify(facts.roundTrip.hydratedDirectEntry || {});+ return before === after ? PASS : fail(`directEntry drift: authored ${before} hydrated ${after}`);+});+ASSERTIONS.set('round-trip: generative pages preserve their keys', ({ facts, spec }) => {if (facts.roundTrip.error) return fail(`hydrate threw: ${facts.roundTrip.error}`);const expKeys = sorted((spec.pages || []).map((p) => p.key || p.name));diff --git a/evals/model-apps/app-builder/lib/facts.js b/evals/model-apps/app-builder/lib/facts.jsindex 1d12d179a..4b8ba4313 100644--- a/evals/model-apps/app-builder/lib/facts.js+++ b/evals/model-apps/app-builder/lib/facts.js@@ -306,6 +306,11 @@ function buildDeployedReader(spec) {...(p.dataSources ? { dataSources: p.dataSources } : {}),...(p.navigatesTo ? { navigatesTo: p.navigatesTo } : {}),...(p.pageInput !== undefined ? { pageInput: p.pageInput } : {}),+ // The manifest carries `directEntry` alongside `pageInput` (page-manifest.js), so the synthetic+ // reader must too. Omitting it let hydration's back-compat default silently rewrite an authored+ // `selector` to `emptyState` while the losslessness assertion below stayed green — the eval+ // proving a round-trip it was not actually checking.+ ...(p.directEntry !== undefined ? { directEntry: p.directEntry } : {}),codeFile: `pages/gp-${p.key || p.name}/page.tsx`,})),entities: async () => (spec.entities || []).map((e) => ({ schemaName: e.schemaName, primaryAttribute: e.primaryAttribute, columns: [] })),@@ -329,9 +334,24 @@ async function roundTripFacts(spec) {pageKeys: (hydrated.pages || []).map((p) => p.key || p.name).sort(),origSubareaTargets: subareaTargets(spec.appShell),hydratedSubareaTargets: subareaTargets(hydrated.appShell),+ // Exposed so a losslessness assertion can actually SEE this field. Hydration defaults a missing+ // `directEntry` for back-compat, so a fact set that never projected it could not tell a preserved+ // value from a silently rewritten one.+ origDirectEntry: directEntryByKey(spec.pages),+ hydratedDirectEntry: directEntryByKey(hydrated.pages),};}+// key -> directEntry.behavior, for pages that declare one. Sorted-key object so a comparison is+// order-independent.+function directEntryByKey(pages) {+ const out = {};+ for (const p of pages || []) {+ if (p && p.directEntry && p.directEntry.behavior) out[p.key || p.name] = p.directEntry.behavior;+ }+ return out;+}+// security: per-persona role facts from the pure spec->SDK mapper (personaRoleSpecFor). For each persona// it exposes: the injected app-module read flag (so the app opens) unless the persona opts out; the// DECLARED privilege union (author intent, from the raw spec) and the GRANTED union (what the role willdiff --git a/plugins/model-apps/.claude-plugin/plugin.json b/plugins/model-apps/.claude-plugin/plugin.jsonindex 3d3125105..315fb7ff7 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.4.4",+ "version": "2.5.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.jsonindex 3d3125105..315fb7ff7 100644--- a/plugins/model-apps/.plugin/plugin.json+++ b/plugins/model-apps/.plugin/plugin.json@@ -1,6 +1,6 @@{"name": "model-apps",- "version": "2.4.4",+ "version": "2.5.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.mdindex 3a4801fd3..589d334e1 100644--- a/plugins/model-apps/AGENTS.md+++ b/plugins/model-apps/AGENTS.md@@ -44,7 +44,7 @@ able to tell what moved from the docs alone):|-----|---------------|--------------|| `AGENTS.md` (this file — `CLAUDE.md` symlinks to it) | Per-component behavioral specs, the canonical file tree, conventions, build/test | You add/rename a script, change a component's behavior, or change how to build/test || [`docs/architecture.md`](docs/architecture.md) | Wiring / flow **diagrams** for both skills (`/genpage` + `/app-builder`) | You change the orchestration, phase pipeline, or how the pieces connect |-| [`docs/app-builder-roadmap.md`](docs/app-builder-roadmap.md) | `/app-builder` **roadmap / TODO** (Complete + Pending by phase) | You ship or reprioritize an app-builder capability |+| [`docs/app-builder-capabilities.md`](docs/app-builder-capabilities.md) | `/app-builder` **capabilities** — what ships today, with the evidence for each | You ship an app-builder capability || [`docs/app-builder-design.md`](docs/app-builder-design.md) | `/app-builder` **design record** — Part I staged-flow architecture (**cited from code by section number — never renumber**), Part II the `--changed-only` contract | You change the staged flow or the partial-apply contract || [`CHANGELOG.md`](CHANGELOG.md) | Keep-a-Changelog — concise bullets (detail lives in PRs/docs) | Any user-visible change || [`references/app-spec-schema.md`](references/app-spec-schema.md) | The App Spec contract | You change the App Spec shape or validation |@@ -118,7 +118,14 @@ the pipeline and delegates each script's **behavioral spec** to the entries beloMEMBERSHIP (the app's sitemap `GenPageId` set, read fail-closed via `fetchSitemap` in`scripts/lib/sitemap-pages.js` — drives placement, download enumeration, and verify; a read failureHALTs). All page matching is by id. Every `pages[]` entry must be sitemap-placed (validation rejects- headless pages). The build halts on safety violations (`pages-removed`, `pages-shared-across-apps`,+ headless pages) — because the sitemap is download's ONLY membership oracle, so a page reached only+ by `navigatesTo` is invisible to download and gets re-created as a duplicate on the next build.+ The corollary is that a detail page is reachable from the nav with **no input**, so a page+ declaring `pageInput` must also declare **`directEntry`** (`selector` | `emptyState`) saying what+ that renders; `page-plan` passes it to the generator and the page manifest carries it through+ download. Every `pageInput.data` key must also be produced by an incoming `navigatesTo[].data`+ edge. See `references/app-spec-schema.md` → *the input contract*.+ The build halts on safety violations (`pages-removed`, `pages-shared-across-apps`,identity conflicts, read failures). The cross-app shared-page scan (`fetchAppsForPages`) enumerates every app via the vendored SDK's`@odata.nextLink` pagination (`queryRecords({ paginate:true })`), so it verifies EVERY app in theenvironment rather than one 5000-row page; a pagination fault (the SDK's repeated-nextLink guard) still@@ -132,6 +139,12 @@ the pipeline and delegates each script's **behavioral spec** to the entries belodefault; `--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 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+ this looked unavailable for a long time. Best-effort: the feature rolls out by tenant, so a failure+ warns and records `created.newLook: false` rather than failing an otherwise-good build or reporting+ a silent success.**DATA-MODEL Dataverse labels are stamped with the ORGANIZATION's base language, not a hardcoded1033.** `resolveLanguageCode` (`scripts/lib/entity-provision.js`) reads `organization.languagecode`once per build and threads it into every label-emitting SDK call in that phase (tables, columns,@@ -142,17 +155,34 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo([#447](https://github.com/microsoft/power-platform-skills/issues/447)) — and confusingly only on*some* column types, because (observed 2026-08) Dataverse tolerates an unprovisioned LCID on`EntityMetadata` and `PicklistAttributeMetadata` but rejects it on `DateTime`/`Memo`. Every fallback- to 1033 warns, as does an explicitly supplied LCID that had to be discarded. Note+ to 1033 warns, as does an explicitly supplied LCID that had to be discarded.+ An **explicitly supplied** LCID is additionally checked against `RetrieveProvisionedLanguages`+ (`readProvisionedLanguages`, `scripts/lib/dataverse-auth.js`, injected as `deps.provisionedLanguages`)+ and halts the data-model phase before any write if the org does not have it — because of the+ split behaviour above, the alternative is a table created with silently-wrong labels followed by a+ failure on the first `DateTime`/`Memo` column. Only *explicit* overrides are probed; the org's base+ language is provisioned by definition. The probe is best-effort — an unreachable or non-2xx+ `RetrieveProvisionedLanguages` resolves to `null` ("unknown") and the build proceeds unchanged, so+ the diagnostic can never itself break a build. Note`updateTable(logical, { quickCreateEnabled })` deliberately passes no language: it only builds aLabel when a `displayName`/`pluralName`/`description` is supplied, and otherwise round-tripsDataverse's own labels under `MSCRM.MergeLabels`.- **Scope — this does NOT extend to the `forms`, `dashboards` or `app-shell` phases.** Those go- through the vendored SDK's artifact serializers, which hardcode `1033` into FormXML+ **Scope — this now extends to the `forms`, `dashboards` and `app-shell` phases too.** Those go+ through the vendored SDK's artifact serializers, which used to hardcode `1033` into FormXML(`<label languagecode="1033">`), SiteMap XML (`<Title LCID="1033">`) and dashboard XML with **no- caller override**, so the plugin cannot pass a language even though it has one. That is an SDK-side- gap tracked in [#455](https://github.com/microsoft/power-platform-skills/issues/455). It is not- known to fail a build — the #447 reporter's full build completed once the data-model phase was- fixed — but in a non-1033 org those labels are stored tagged with a language the org lacks.+ caller override** ([#455](https://github.com/microsoft/power-platform-skills/issues/455)). The SDK+ now takes the authoring LCID as a **construction-time** option (`MakerSdkOptions.languageCode`),+ which is why `main()` resolves the language over the transport hatch (`resolveAuthoringLanguage`,+ `scripts/lib/entity-provision.js`) **before** calling `makeSdk`, and passes the identical value on+ as `opts.preResolvedLanguageCode` so the data-model phase cannot resolve a different one. Both SDK+ instances get the same LCID deliberately: `pushArtifact` refuses a push whose stored artifact+ language disagrees with the SDK performing it (`ARTIFACT_LANGUAGE_MISMATCH`, for registrations+ marked `languageSensitive` — App, Form, Dashboard). Passing nothing preserves the SDK's own 1033+ default exactly, so the option is opt-in rather than a silent re-labelling.+ Note the SDK deliberately does **not** language-parameterize BusinessRule: its mapper's language+ parameter is the *environment base* language, a different concept.+ Guarded by `scripts/tests/lcid-real-bundle.test.js`, which drives the REAL vendored bundle — a mock+ would keep passing against a bundle that ignored the option.`--verify` (opt-in) auto-runs the read-only reconcile after a successful apply and exits non-zero on a silent partial build (the samecheck `verify-model-app.js` runs standalone). Recovery from a halted build is a full rerun (idempotent).**`--changed-only`** (Preview, off by default) is a fail-closed SAFE partial apply: after a FRESH@@ -249,8 +279,9 @@ the pipeline and delegates each script's **behavioral spec** to the entries belowith no sitemap subarea does not become an app component at all (LIVE-verified: declaring `task` in`entities[]` without nav left the app's component set unchanged), so for an app-builder-built appthe sitemap set already IS the complete set. This union therefore only adds tables for apps built- or edited in the maker. **ADO 6603388 (download) is still open**, and a live attempt to construct- the hidden component it describes did not succeed: pinning `task` via `AddAppComponents` with the+ or edited in the maker. **Download does not recover an entity component that has no sitemap subarea**+ (ADO 6603388), and a live attempt to construct the hidden component it describes did not succeed:+ pinning `task` via `AddAppComponents` with thenow-correct reference shape returned 204 but wrote no row, before or after publish. So thedownload-side fix cannot currently be verified end to end — do not implement it speculatively.The component read is best-effort: a failure degrades@@ -410,7 +441,7 @@ feature-flags.json ← Default-OFF feature flags (currently connecto.claude-plugin/plugin.json ← Legacy plugin metadata mirrordocs/architecture.md ← Wiring/flow diagrams for BOTH skills (/genpage + /app-builder)- app-builder-roadmap.md ← /app-builder roadmap / TODO (Complete + Pending by phase)+ app-builder-capabilities.md ← /app-builder capabilities (what ships today, with evidence)app-builder-design.md ← /app-builder design record (Part I staged flow · Part II --changed-only)agents/ ← Agent definitions (invoked by skills via Task tool)genpage-planner.md ← Requirements, discovery, plan doc, user approval (create flow)@@ -816,8 +847,19 @@ edit produces a byte-identical `lib/*.js`, so the bundle only needs rebuilding wchanges.**Vendored-SDK contract invariants (regression net).** When you bump the SDK and re-vendor, the-skill relies on behaviors that must survive. Three test files lock them — run all against every-rebuilt bundle:+skill relies on behaviors that must survive. Four test files lock them — run all against every+rebuilt bundle.++**Re-vendor from a COMMIT, and check the recorded provenance.** `scripts/_vendor-build/build.js`+writes `scripts/vendor/PROVENANCE.json` next to the bundle: the upstream SHA and subject, whether+that package had uncommitted changes, and the bundle's own sha256. Two things make this+load-bearing rather than bookkeeping. First, the bundler consumes the SDK's **gitignored `lib/`**,+a build output that can be arbitrarily older than `src/` — a bundle shipped in this repo was once+built from a stale `lib/` several commits behind its nominal source, and nothing could reveal it.+The bundler now **refuses** (exit 3) when `lib/index.js` predates the newest `.ts` under `src/`.+Second, "built from master" is not provenance, because master moves; the SHA is what lets a+reviewer reproduce the artifact. Re-running the build on the same inputs must reproduce the same+sha256 — check it.`scripts/tests/sdk-surface-contract.test.js` — the **method-presence** guard. Asserts every SDKmethod the engines call (`SKILL_SDK_SURFACE`, kept in sync with the `provision.*` / `sdk.*` call@@ -856,6 +898,18 @@ public `createMakerSdk` factory — the `MakerSdk`/`AppAdapter` classes are no lexplicit **`matchOn`** key (it NEVER falls back to the primary display name — `buildSeedGroup`supplies `matchOn` from a single-column alternate key or the primary name, validated non-empty).+`scripts/tests/sdk-async-surface.test.js` — the **sync-vs-async** guard, and the one to read first+after a re-vendor. The SDK's generic surface is asynchronous (`addElement`, `findElements`,+`getArtifact`, `moveElement`, `queryTree`, `removeElement`, `updateElement` all return Promises; a+read may revalidate against the server before serving its cached copy). Forgetting an `await` does+**not** throw: a Promise is truthy, so the engine's `|| {}` fallbacks stay dormant and the pure+helpers silently receive a Promise — `hasSubgrid` → `false` (duplicate sub-grid), `formFieldLogicals`+→ `[]` (every field looks missing), `findFieldCellPointer` → `null` (a removal never happens). Wrong+artifacts, 2xx statuses, green build. The test therefore does two things: a **source scan** that+fails on any un-awaited `provision.*`/`sdk.*` call to those methods (annotate a deliberate one with+`sdk-async-ok`), and a **dynamic check** that the real bundle still returns Promises for exactly that+list — so if a future SDK makes one synchronous again, the scan can't go on enforcing a dead rule.+**Live end-to-end (app-builder — writes to a real Dataverse env; optional).** All build/verify/teardown scripts are **dry-run by default**; add `--apply` to write.@@ -865,11 +919,17 @@ az account set --subscription <sub-id>node scripts/check-auth.js --env <envUrl> # az token + WhoAmI preflight (pac optional; --require-pac for genpage)node scripts/build-model-app.js --env <envUrl> --spec @<dir>/app-spec.json [--sample-data --publish] --apply --verifynode scripts/verify-model-app.js --env <envUrl> --spec @<dir>/app-spec.json-node scripts/teardown-model-app.js --env <envUrl> --spec @<dir>/app-spec.json --apply+node scripts/teardown-model-app.js --env <envUrl> --spec @<dir>/app-spec.json --apply --allow-destructive```AI features are **admin-gated** — preflight readiness with `node scripts/ai-preflight.js --env <envUrl>`.-Prefer a scratch env; always tear down probes (`teardown-model-app.js --apply`) to leave 0 leftovers.+Prefer a scratch env; always tear down probes so nothing app-owned is left behind. Teardown needs+`--allow-destructive` as well as `--apply` — with `--apply` alone it refuses and exits — and it+deliberately leaves **one** thing behind: the **publisher**. A publisher can own other solutions in+the environment, so deleting it is not this app's decision to make — the same fail-safe reasoning+that keeps an `external` web resource. Expect a clean environment afterwards *except* for+`<prefix>publisher`; if a probe must restore the environment exactly, remove that row yourself after+confirming it owns no other solution.**After modifying the plugin also:** run `claude --debug` to confirm the plugin loads, exercise theskill (`/genpage` or `/app-builder`), and for genpage verify Playwright browser checksdiff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.mdindex f3ed73fe6..831c0c36b 100644--- a/plugins/model-apps/CHANGELOG.md+++ b/plugins/model-apps/CHANGELOG.md@@ -1,580 +1,369 @@-# Changelog--All notable changes to the **model-apps** plugin.--## [Unreleased] — 2.4.4--Adds plugin update notices, proves what persona roles actually grant, makes-jobs-to-be-done surfaces checkable, fixes four crash paths, and corrects a-smoke-eval assertion that could never pass live.--### Added-- **Dataverse labels now use the organization's own language instead of a hardcoded- `1033`** ([#447](https://github.com/microsoft/power-platform-skills/issues/447)).- In an organization that has not provisioned 1033, `data-model` halted with- `The language code 1033 is not a valid language for this organization`. The build- resolves `organization.languagecode` once per run and threads it into every- label-emitting call (tables, columns, customer columns, global choices, status- reasons, alternate keys, relationships), and warns whenever it has to fall back.-- Precedence: `--language-code` / `--languageCode` → App Spec `languageCode` (or- `languageCode` in the `provision-entities.js` input JSON) → the organization's- base language → 1033. Both CLIs accept the flag.-- Two things worth knowing if you hit this. The failure is **not** all-or-nothing:- Dataverse accepts an unprovisioned LCID on `EntityMetadata` and- `PicklistAttributeMetadata` but rejects it on `DateTime` and `Memo`, so the table- and its Choice columns are created and the build fails a few steps later — which- reads like an environment problem rather than a defect. And this covers the- **data-model phase only**; form, dashboard and sitemap labels still come from SDK- serializers that hardcode 1033 with no caller override- ([#455](https://github.com/microsoft/power-platform-skills/issues/455)).--- **`verify` now proves what a persona security role GRANTS, not just that it- exists.** The `role` check only asserted a role row carrying the SDK ownership- marker, so a role built with the wrong access — or one whose privilege write- failed after the row landed — verified clean. The new `role-privileges` check- resolves every declared `(entity, access)` to its Dataverse `PrivilegeId` from- the same metadata source the SDK writes against, and asserts the role holds it- at **at least** the declared depth. A **subset** check by design: extra- privileges are never a finding, because `appAccess` injects `appmodule` read,- unioned jobs escalate a shared entity+access to the max declared scope, and- distinct entities can share one Dataverse privilege. Fails **closed** on an- unreadable role or table. Reader-gated, so existence-only callers are unchanged.-- **`personas[].jobs[].surfaces[]` is checked instead of documentary.** Each entry- is now resolved against the spec's own views, forms, pages, dashboards, tables- and sitemap titles. `spec-lint` **warns** when a surface matches nothing — a- warning, not an error, because a surface may legitimately name an out-of-the-box- artifact this spec never authors. `verify` adds a `job-surface` rollup that- reports a deployed failure as the job it broke ("persona P can no longer do job- J"), rather than only "view X is missing".-- **Automatic plugin update notice.** Every user-invocable skill now runs the- non-blocking `scripts/check-version.js` preflight, which compares the installed- Model Apps version with `origin/main` and shows update commands for the active- GitHub Copilot CLI or Claude Code host when a newer version is available.--### Fixed-- **A sitemap subarea that targets a custom web resource now round-trips**- ([#430](https://github.com/microsoft/power-platform-skills/issues/430)).- The Site Map Designer writes `$webresource:<name>` into a URL subarea; the http(s)- guard rejected it, so the downloaded spec failed validation and **no spec file was- written at all** — blocking the whole download → edit → rebuild flow for the app over- a single unrelated nav entry. The reference now passes validation as-is (the same- policy platform icon refs already use), and `download-model-app.js` additionally- captures the page's **content** into `webResources[]` when it can safely do so — as- `navRefs`, kept separate from icon refs because the icon path is image-only by design- and such a page is `html`. A managed or foreign resource stays a bare reference; it- exists in the target environment. A `javascript:`/`file:`/malformed url is still- rejected and dropped.-- **Malformed specs now produce validation errors instead of raw `TypeError`s.** `validateAppSpec()`- and `lintAppSpec()` crashed on a `null` spec, an object- or string-shaped collection- (`entities: {}`), and `null` entries inside a collection; `preview-app` crashed when a persona- privilege's `access` was a scalar rather than an array. These are work-in-progress shapes an author- hits constantly, and a crash killed the authoring flow instead of reporting the problem. Coverage- is now a single recursive descriptor shared by both gates (`lib/spec-shape.js`), reaching nested- collections too — `entities[].columns`, `views[].filters`, `forms[].tabs[].sections`,- `pages[].dataSources`, `commands[].buttons[].children`, and the `appShell.areas → groups →- subAreas` chain — and errors name the exact path (`appShell.areas[0].groups must be an array`).-- **A malformed collection can no longer pass validation and then crash mid-build.** Validation- inspects a normalized copy while the caller keeps the original, so a silently-repaired- `appShell.areas: [null]` reported PASS and then threw inside the build — *after* the solution and- data model had been written to Dataverse. A null entry is now a blocking error, so the failure- happens at the gate with nothing deployed.-- **`migrateAppSpec` no longer crashes ahead of the gate.** Every CLI entry point migrates the spec- it just read *before* validating it, so a malformed collection threw a raw `TypeError` before the- validator that exists to report it ever ran. Migration is now defensive but does **not** repair —- repairing would hand the gate a clean spec and the real problem would vanish.-- **`verify-model-app` no longer surfaces a raw Dataverse HTTP 400 for a missing table.** A declared- table that does not exist makes the saved-view query 400 (`returnedtypecode` names an unknown- entity); the read error is now captured and reported as a structured missing-artifact finding.- Both the verify CLI and the build's verify step now print the failure `detail`, so a read that- failed (throttling, auth expiry, a 5xx) is distinguishable from an artifact that is genuinely- absent instead of both rendering as a bare `✗ view: <name>`.-- **The live smoke eval asserted an outcome the builder never produces.** Its spec put a bare Fluent- `vectorIcon` ("Grid") on an *entity* subarea — the one shape the builder deliberately drops,- because it breaks the modern app-designer property pane — while asserting the deployed sitemap- contained `VectorIcon="Grid"`. The offline test hid it by hand-writing the sitemap XML it wanted to- see. The spec now uses an emittable `/WebResources/<name>.svg` reference and keeps the bare token- as a negative control; assertions are scoped to the `<SubArea>` that declared the icon (the spec- reuses one icon on the parent `<Area>`, which a document-wide scan let satisfy every subarea check)- and their expected values stay independent of the builder, so a builder that stops emitting the- icon makes the eval FAIL rather than silently invert into an absence check.--### Changed-- **`download-model-app.js --app` now accepts a display name**, not just an id or `uniquename`. It- resolves in identity order (id → `uniquename` → display name) and **fails closed** when a display- name matches more than one app, listing the candidate unique names instead of guessing. A display- name previously hit a dead-end "app 'x' not found", even though that is the only name the maker- portal shows.--### Tests-- A contract test drives the **real vendored SDK** and asserts the serialized sitemap bytes: a- platform-ref `VectorIcon` reaches the XML on an Entity subarea, and the bundle does **not** filter a- bare Fluent token — pinning that `appDef` is the only guard, so the drop cannot be delegated to the- SDK.--## [2.4.2]--Fixes a malformed app module: generated apps did not actually contain their tables.--### Fixed-- **Generated apps contained invalid `entity` table components instead of their real tables**- (ADO 6612527). An exported app read `<AppModuleComponent type="1" schemaName="entity" />` where it- should have listed `account`, `contact`, `activitypointer` — and the malformed app then broke- unrelated app-processing and metadata-discovery paths. Tables are now pinned by OData **reference**- (`{ '@odata.id': '<EntitySetName>(<MetadataId>)' }`) instead of as an `@odata.type` instance:- `Microsoft.Dynamics.CRM.entity` names a real Dataverse table (metadata-as-data), so the old payload- pinned the `entity` table exactly as asked. The reference form is also the only one that can express- an abstract EDM table such as `activitypointer`.-- **A table that cannot be resolved now halts the build, naming it.** One bad component fails the- whole `AddAppComponents` call, so a silently-skipped table previously emptied the app's component- list rather than degrading it.-- **App components are read back and verified after the write.** `AddAppComponents` returned 204 for- every corrupt app — a 2xx means the request was accepted, not which rows it wrote — and- `ValidateApp` reported success too. The build now asserts every declared table has a- `componenttype: 1` row carrying that table's MetadataId, and fails closed if it cannot check.--### Changed-- **Re-vendored `cds-maker-sdk`** with the above.--### Tests-- `app-entity-components-real-bundle.test.js` drives the shipped bundle: tables sent as references,- an unresolvable table refused, the read-back catching both a missing component and the exact- 6612527 corruption (rows present but pointing at `entity`). 6 of its 7 tests fail against the- previous bundle.--### Known limitations-- **ADO 6603388 (download drops entity components not in the sitemap) is still open.** A live attempt- to construct the hidden component it describes did not succeed — pinning a table with no sitemap- entry returned 204 but wrote no row, before or after publish — so the download-side change cannot- be verified end to end yet.--### Eval harness-- **A value-less or malformed runner flag is now rejected instead of silently changing scope.**- `argv[++i]` is `undefined` for a trailing flag and `undefined` is falsy, so `--tier` alone became- "no tier filter" and `--fixtures` alone fell back to the built-in fixtures — the run then reported- PASS for a scope the caller never asked for. `--eval 1.5` was truncated to fixture `1` and graded- the wrong one; an unknown `--tier` produced "no fixtures matched the filter", blaming the fixtures- rather than the argument. All three runners (app-builder + genpage layers 1/2) shipped a- byte-identical copy of this parser, so it is now shared at `evals/model-apps/lib/eval-args.js`.-- **A malformed fixture names the fixture.** A bare `JSON.parse` reported only a character offset,- which tells an operator running a corpus nothing about which fixture to fix. A UTF-8 BOM (the- Windows editor default) no longer fails an otherwise-valid file, and a spec that is `null`, an- array, a string or a number is rejected up front instead of surfacing later as an opaque- stage-facts error.--## 2.4.1--Bug fixes for apps built on **out-of-the-box** tables, and the matching `cds-maker-sdk` uptake.-No change to any skill's public surface.--### Fixed-- **AI app features had no effect on a newly built app** — an app-scope setting write is a no-op- until the app is published, so the build wrote nothing while reporting success. The write is now- re-issued after publish.-- **`--verify` PASSed when AI features were skipped or never applied** — it now proves an app-scope- override row in `appsettings`. Reading the setting back is unsound: `RetrieveSetting` falls back- to the environment value when an app has no override.-- **`ai.appFeatures` could not express non-boolean values** such as `2` ("on for everyone") — a- value may now be a boolean or an integer `0..1000000`.-- **Download invented primary-name columns** (`account_name`, `contact_name` — neither exists) —- now read from Dataverse metadata, never synthesized. Because a spec *requires* `primaryAttribute`,- a table whose metadata does not supply one can no longer be emitted: a table reached from the app's- **navigation** now **fails** the download naming it (`--allow-lossy-download` drops it instead),- while a table found only as a hidden component is dropped with a warning.-- **Download replaced the solution's publisher prefix with `new`** — now read from the solution's- owning publisher.-- **Download dropped tables with no sitemap entry** — the entity set is now the sitemap set unioned- with tables owned by the app's view/chart/form components.-- **Teardown could permanently burn an app's unique name** — an app is two rows (`appmodule` +- `sitemaps`) with no server-side cascade, so deleting only the app module stranded the sitemap and- reserved its name forever. Both rows are now deleted atomically in one OData `$batch`, and any- delete that cannot be proven refuses rather than guessing.-- **An unreadable app produced a raw SDK throw** instead of the download's documented- `{ ok: false, error }`.--### Changed-- **Re-vendored `cds-maker-sdk`.** An injected `HttpClient` must now implement `postRaw` (verbatim- multipart body out, raw response string back) for the atomic `$batch`; without it app deletion- fails with `APP_DELETE_NOT_ATOMIC`. The plugin's client implements it and does not retry a- `$batch` — it carries record deletes, and a racing retry wedges the row.--### Tests-- 1266 → 1340 tests; coverage 92.7 → 93.9% line, 82.7 → 83.6% branch.-- **model-apps now runs in CI** (`model-apps-script-tests`, ubuntu × windows × macos, Node 20 × 22,- plus the offline evals) — previously every test workflow was scoped to `plugins/power-pages/**`,- so this suite never ran on a PR.-- Real-bundle suites (`ai-app-features-real-bundle`, `app-delete-real-bundle`) drive the shipped- vendored bundle, including one test that wires the real HTTP transport to it — the SDK's own Jest- suite cannot run here (Node-20-ABI `canvas`).--### Known limitations-- **Table (`entity`) app components cannot be pinned via `AddAppComponents`** — the documented shape- returns 204 but records a component pointing at the metadata table named `entity`. Platform defect- **AB#39140211**; until it is fixed a table with no sitemap entry cannot be added to an app.--## 2.4.0--A new **`/app-builder`** skill (Preview) that builds and edits whole model-driven apps,-plus local-dev ergonomics, sample coverage, and an automated eval suite. Builds on v2.3;-no breaking changes.--### Added-- **Table icons are described before they are drawn** — each custom table proposes what its glyph- will **depict** in plain language (`entities[].iconDescription`, e.g. "an outlined clipboard with- a checkmark"), shown in `model-app-plan.md` for approval before any SVG is authored. A Fluent- token name is rejected: the SVG is drawn fresh, so a token the user has never seen describes- nothing. Also valid on sitemap areas, groups and non-entity subareas.-- **Jobs-to-be-done drive the design** — authoring now starts at Level (a0) by asking who uses the- app and what each of them needs to get done, *before* the data model, and carries those jobs- through to the surfaces that satisfy them (`personas[].jobs[].surfaces[]`). Previously jobs were- only asked for at the end, to size security roles — and the playbook contradicted the skill by- declaring roles out of scope, so they were never enumerated at all.-- **`scripts/write-app-spec-doc.js`** — renders `model-app-plan.md`, a readable design document- (jobs → surfaces traceability, data model, every surface, navigation, access model, sample data)- from the spec. It replaces a hand-written counts summary, so it is complete, always agrees with- what will build, and is regenerable after any edit.-- **Design-gap warnings at the lint gate** — jobs with no covering surface, an app with no- generative pages, or no personas at all are now surfaced as warnings instead of passing silently.-- **`/app-builder` skill (Preview)** — natural-language intent → deployed model-driven app: tables,- columns, relationships, adaptive forms with sub-grids, views, Choice-column charts, dashboards,- generative pages, app + sitemap, and sample data, via the headless vendored `cds-maker-sdk`.-- **Security roles per persona (`personas[]`)** — one role per persona, sized to the privileges its- jobs declare (unioned, max scope wins). Injects `appmodule` read and associates the app so it opens- for non-admins (`appAccess: false` opts out). Idempotent and converging; fail-closed on a same-name- role the builder did not author.-- **`--changed-only` partial apply (Preview, off by default)** — after a fresh baseline, a page-only- `.tsx` edit re-runs just the pages phase; any other change falls back to a full build.-- **AI-first features** (`ai` block → `ai-features` phase) — form fill, NL search, NL charts, M365- Copilot and row summaries, admin-gated via `ai-preflight.js`.-- **Table icons** (`entities[].vectorIcon` / `icon`), plus a semantic default icon per table from the- authoring flow instead of the stock cube.-- **Opt-in auto sub-grids** (`forms[].autoSubgrids: true`) — a sub-grid on the parent form per 1:N child.-- **Form edits can REMOVE a field**, not just add one; forms and views now update in place on edit.-- **The app shows your form, not the blank stock form** — a built main form becomes the entity default.-- **Parent lookups surface in views** — 1:N lookups appear in auto-layout, authored, and built-in- default views.-- **Fail-closed page deployment + verification** — `PAGEREF_<key>` navigation is resolved to real page- ids before upload and an unresolved token halts the build; a manifest-aware download round-trips pages.-- **`scripts/preview-app.js`** — renders the whole app design (data model, sitemap, forms, page intents)- for review before building.-- **Page generation reuses the `/genpage` worker via a plan adapter** — `write-page-plan.js`- projects the App Spec into the `genpage-plan.md` the page-builder actually reads, so an intent page- can no longer silently fail to become `.tsx`. Untrusted spec text (including download-derived) is- neutralised so it cannot forge plan sections.-- **`promote-intent-pages.js`** — validates every generated page (written, structurally a module,- `PAGEREF_` tokens in exact parity with `navigatesTo`) and flips them all `intent → tsx` in one- atomic write, or exits 3 leaving the spec untouched.-- **Eval suites** — an offline `/app-builder` structural harness (`evals/model-apps/app-builder/`) and- the genpage Layer 1/2 TAP runners with shipping fixtures.-- **`check-auth.js --env` support** — SDK builds accept `--env <url>` or a positional URL, treat a- missing PAC login as a warning, and reserve `--require-pac` for genpage.-- **`/app-builder` is covered by the v2.3 hooks + telemetry** — tracked-skill discovery is derived from- `skills/*/SKILL.md`, and the write-safety and icon-import guards now recognise app-builder working dirs.-- **Docs + marketplace metadata cover both skills** — `/app-builder` is documented as Preview in the- plugin and repository READMEs.--### Changed-- **The connectors feature flag is re-probed before code generation** — the result is passed as- `Connectors: enabled|disabled` in every page-builder dispatch and overrides the plan, so a plan- authored while the flag was ON can no longer emit connector calls the run never binds.-- **Surface classification is explicit** — the authoring flow now enumerates every surface each job- needs and classifies it (record CRUD → form + view; overview/dashboard/analytics/wizard/composite- → generative page), and states each call out loud. Pages were previously one item in a long list- behind a "never force-add it" hedge, so they were routinely skipped.-- **Forms resolve by `(entity, name, type)`** — a table's same-named Main/Quick View/Card forms no- longer block an edit, and teardown no longer over-deletes them.-- **Views are identified by `entity|name`** — same-named views on different tables no longer cross-wire- a dashboard tile, sub-grid, or snapshot entry to the wrong view.-- **App identity round-trips by its real uniquename** — no duplicate app on rebuild.-- **Nav icons round-trip** — custom icon web resources are re-declared on download (portable across- environments) and entity-subarea sitemap icons survive a download→build cycle.-- **Pre-existing duplicate page names no longer block an unrelated build** — the check only errors when- a new page collides.-- **Staged-flow authoring** — design-only authoring, an explicit generate-pages step, a `--stage`- selector, and fewer approval gates with checks run earlier and automatically.-- **Sample-data idempotency is explicit** (`seedRecordGraph.matchOn`), and every artifact push is- verified (`requireSuccessfulPush`).-- **Re-vendored `cds-maker-sdk`** — backlog capability fills (pagination, quick create, idempotent- global choice, authored column width), shared input-safety boundaries, and the `hardening-2` bundle.--### Fixed-- **Teardown leaves nothing behind** — the table icon and generated app-icon web resources are removed- (web resources delete after tables), cascade cleanup failures are reported instead of silently- orphaning rows, and reused/system tables are skipped with a reason rather than erroring.-- **Command-bar teardown is fail-closed** — only the bar for a table this spec created is deleted, so a- command on an existing table can never remove another app's buttons.-- **Exported solutions are self-contained** — the app icon and sitemap are added to the solution, so- import no longer fails on missing components.-- **Relationships to a standard/system table no longer halt the build** — the schema name auto-prepends- the publisher prefix.-- **System tables keep their default sitemap icon** — the transparent-spacer placeholder is stripped.-- **Editing an existing app updates the sitemap for page-less apps too.**-- **Sub-grids pass `targetEntity` to the SDK** — prevents empty `<TargetEntityType/>` output and- edit-time validation failures.-- **Classic dashboards round-trip** through download/edit with id-passthrough tiles, and dashboard tiles- render in a 2-column grid.-- **AI row summaries errored on every record** — the prompt filtered on the primary name column instead- of the primary key.-- **CLI flags fail loudly instead of silently** — a value-less flag no longer passes the usage guard;- notably `--apply --only` (with no phase list) used to run a *full* apply.-- **The Dataverse token is never sent to another origin** — the HTTP client requires an absolute- `https` org URL and refuses any request outside it.-- **A lossy download fails instead of reporting success** — unmapped sitemap subareas are named and the- spec is validated before it is written (`--allow-lossy-download` opts in).-- **Assorted robustness** — temp workspaces cannot leak on a failed SDK init, `%` in prompts survives- cmd.exe, an omitted column `type` defaults to `Text`, `vectorIcon` is verified in the sitemap, and- entity-subarea `vectorIcon` no longer breaks the app designer.--### Tests-- Plugin unit tests (+ optional vendored SDK suite): `node scripts/run-tests.js --with-sdk <ppux>`- from `plugins/model-apps/`.-- Eval fixtures run separately, from the repo root: `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`.-- **Vendored-SDK contract tests** lock OData filter encoding, name-based identifiers, and sitemap- free-text XML escaping.--### Removed-- **Standalone entity/solution scripts, consolidated into the SDK** — `create-table.js`,- `add-column.js`, `create-relationship.js`, `create-record.js`, `create-solution.js` and- `add-to-solution.js` are replaced by `provision-entities.js` and `provision-solution.js`.--### Known limitations-- **App EDIT does not re-pin a new chart** as an explicit app component — a chart added to an existing- app needs a manual pin or a rebuild.--## 2.3.0 — 2026-07-23--Plugin observability + authoring guardrails: default-on (but ship-disabled)-anonymous telemetry with a local diagnostic log, PostToolUse validators, and a-hardened Playwright launcher. No breaking changes.--### Added-- **Anonymous 1DS telemetry (default-on, ships `disabled` until provisioned).**- Copied the shared telemetry library into `scripts/lib/telemetry/lib` with a- plugin-owned `ikey.json` (Tier-1 static key; ships `disabled: true` until go-live).- Emits `skill_started` via PreToolUse(Skill) + UserPromptSubmit hooks and writes- a local diagnostic mirror at- `~/.power-platform-skills/telemetry/model-apps/sessions/<id>/events.jsonl`. New- `/model-apps:telemetry on|off|status` control skill; CI/automation opt-out via- `POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT=1`. Fail-closed throughout —- never changes a skill's exit code. Carries **no user-level identifier** (no Entra- object id) — only org/tenant GUIDs when signed in.-- **PostToolUse validators (`hooks/hooks.json`).** A per-skill validator runner- plus an `@fluentui/react-icons` allowlist check that validates every genpage- `.tsx` write against `references/verified-icons.txt`, automating the- page-builder's manual icon-grep step (hallucinated or sized icon names are- blocked at write time).-- **PreToolUse write-safety guard.** **Flags (non-blocking, exit 1)**- Write/Edit/MultiEdit outside the cwd, and only during an active genpage session- (a `genpage-plan.md` at/under cwd) — so a globally-installed plugin never blocks- or interferes with unrelated work. Silence with `MODEL_APPS_SKIP_WRITE_GUARD=1`.--### Fixed-- **Generated-page double-fetch / render flash on open.** Generated data pages- could fetch twice and re-flash the spinner because (1) the webplayer host- double-mounts the page on open (a cache-bypassing app relaunch ~300ms after- the first mount re-runs the data effect — confirmed via network capture: two- `POST .../powerapps/apps/<app>/launch`, the second `bypass-cache=true`), and- (2) `dataApi` is a new reference each render, so listing it in a `useEffect`- dep array re-fires the effect every render. Reworked the data-fetch guidance- (`references/data-caching.md`, `rules.md` Rule 15) and every exemplar- (samples 3/9/10/11, `localization.md`) to use an **in-flight-promise de-dupe +- `window` cache** (concurrent mounts share one round-trip; later mounts paint- from cache with no spinner) and a **readiness boolean** dependency —- `dataApi` is now forbidden in any dependency array. The de-dupe applies to any- page that fetches on mount, including single-visit overviews/dashboards- (previously excluded from caching); `Needs caching:` in the plan schema now- means "fetches on mount." The host relaunch itself is a platform-side issue- tracked separately.-- **Playwright MCP launcher.** `scripts/launch-playwright-mcp.js` now exports- `launch()` — satisfying the `.mcp.json` contract instead of relying on a- require-time side-effect — adds `-y` (avoids the npx first-run prompt hang),- opens the browser fullscreen via `playwright-mcp-fullscreen.config.json`, and- quotes the config path so Windows paths with spaces work. Browser detection- extracted to the reusable `scripts/lib/detect-browser.js`.-- Eval fixture `18-sharepoint-connectors-on`: relabel the connector-only page- `Data mode: mock + connectors` to match the page-builder contract (connectors- are orthogonal to the Dataverse axis).--### Tests-- New `node:test` coverage for the launcher, `modelapps-hook-utils`, the- icon-import and write-safety validators, and the telemetry pretool hook.--## 2.2.0--Local-dev ergonomics, sample coverage, and an automated eval suite with-real and synthetic fixtures. Builds on v2.1; no breaking changes.--### Added-- **Phase 0.5 — local-dev manifest.** Working dirs now get `package.json`- and `genpage.d.ts` so `npm install` + editor IntelliSense work after- generation. Versions in `references/supported-dependencies.md`.-- **Eval suite runners.** `run-layer-1.js` (workflow assertions) and- `run-layer-2.js` (code assertions) emit TAP v13. `EVAL_GUIDE.md` covers- types, tiers, capture flow.-- **10 fixtures** under `evals/.../fixtures/` (6 synthetic + 4 real- captures; all green under the tightened v2.2 spec).-- `scripts/capture-fixture.js` — copies `/genpage` working dirs into- fixtures and runs both layers.-- `samples/11-kanban-with-dnd.tsx` — native HTML5 drag-and-drop sample.-- `samples/12-dialog-form-overlay.tsx` + **Dialogs and Overlays** guidance- (rules.md rules 16–18 and Special Patterns section, plus a troubleshooting- entry): confine portalled Fluent surfaces (`Dialog`, `Popover`, `Menu`,- `Tooltip`, `Combobox`/`Dropdown`) to the page via `mountNode` +- `contain: layout`, default dialogs to `modalType="non-modal"`, and never nest- dialogs — so a modal can't escape the preview and cover the designer /- coding-agent panel.-- **Feature-flag gate for connectors (default OFF).** `feature-flags.json` at the- plugin root plus `scripts/lib/feature-flags.js` gate connector support so the- skill can ship ahead of its cross-repo dependencies (pac connector verbs, the- GenUX authoring control, and the maker/admin setting) reaching PROD. When OFF,- the planner skips connector discovery and records `No connector bindings.`, and- the connector scripts (`list-connections.js`, `create-connection-reference.js`)- fail closed with exit 3. Precedence: env `GENPAGE_ENABLE_CONNECTORS` overrides- the committed file; default is OFF (fail-closed). Flip the file to `true` once- the dependencies are GA.-- **`genpage-connector-builder` agent — single owner of connector work.** Connector- discovery, connection-reference creation, the feature gate, and the- `## Connector Bindings` contract now live in one agent invoked from **both** the- create flow (planner) and the edit flow (edit-planner) — so edits can add/replace- connectors (previously only preserve/clear worked) and the gate can't drift across- markdown. Hardened per review: deploy (SKILL Phase 4.5) **re-probes** the flag and- treats an absent/malformed `## Connector Bindings` as no bindings; the page-builder- emits connector code only for an actual binding table; the `--connection-refs`- branch of `add-page-to-solution.js` is gated; scripts share `exitIfConnectorsDisabled()`;- and `feature-flags.js` gains `--list`, `describe()`, and config validation.--### Changed-- Spec tightening so workflow-logs are command-verbatim and `pageInput`- destructure is required even on mock pages (planner, page-builder,- SKILL.md Phase 6 + Phase 8).-- 8 runner regex relaxations to accept functionally-equivalent agent- patterns (typed `(window as any).Xrm` aliases, `pac solution list`,- local enum mapping, etc.) — no rule loosening.--### Fixed-- **Synthetic fixtures + sample 11 now follow Rule 11 (queryTable returns- DataTable, not an array).** 7 files were iterating `result` directly- (`setTasks(result)`, `result.map(...)`) instead of `result.rows`,- producing `X.map is not a function` at runtime. Fixed in- `samples/11-kanban-with-dnd.tsx` and 6 fixture `.tsx` files.- New Layer 2 assertion catches this pattern going forward: any Dataverse- file calling `dataApi.queryTable` must access `.rows` somewhere.--### Tests-- 215 passing across `scripts/tests/` + `evals/.../tests/`.--## 2.1.0 — 2026-05-13--Replaces the Dataverse MCP server + Python SDK fallback with Node.js Web API-scripts. Adds solution selection, prefix discipline, and a consolidated auth-pre-flight. Trim of ~27K tokens on hot-path page-builder runs.--### Breaking-- **Azure CLI (`az`) is now required** for entity creation. The `az` identity- must have access to the target Dataverse env (same as the active `pac` profile).-- **Dataverse Skills plugin is no longer required.** Soft dep removed.-- `.env`, `scripts/auth.py`, and device-code prompts from the Dataverse Skills- plugin no longer used.--### Added-- Node.js Web API scripts under `plugins/model-apps/scripts/`:- `check-auth.js`, `dataverse-request.js`, `create-table.js`, `add-column.js`,- `create-relationship.js`, `create-record.js` (with `$batch` bulk),- `create-solution.js`, `add-to-solution.js`, `lib/dataverse-auth.js`.-- Solution selection in planner with prefix-conflict warnings.-- Transactional log at `<working-dir>/entity-creation-log.md`.-- `node --test` coverage under `scripts/tests/` (47 tests).--### Fixed-- **Prefix drift made structurally impossible.** Plan stores logical-name- suffixes only; entity-builder constructs `${prefix}_${suffix}` from the- single `Publisher Prefix:` source of truth.-- **`pac model create` always passes `--solution`.** Default value is `Default`.- The CLI's "active solution" fallback errors in practice.-- **`--prompt` is now scoped per upload role**: full description on create,- delta only on every subsequent upload (PAGEREF, fix re-deploy, edit flow).-- **Bulk-insert partial failure** emits structured JSON to stdout (not- `[object Object]`).-- entity-builder bash snippets no longer mix JS template literals.-- planner no longer shells `grep`/`awk`/`sed` (Windows-incompatible).--### Performance-- Page-builder no longer loads `verified-icons.txt` upfront (~26K tokens- saved per run). Validation switched to post-write `Grep` only.-- `rules.md` trimmed −98 lines: dropped duplicated DataAPI- type definitions (canonical source is `RuntimeTypes.ts`); tightened usage- examples.-- `rules.md` Page Input section trimmed −25 lines: pure prose tighten.-- Phase 7 (browser verification) extracted to `skills/genpage/verify-flow.md`,- loaded only when the user opts in. SKILL.md trimmed an additional −95 lines.-- Reference docs renamed for consistency:- `genpage-rules-reference.md` → `rules.md`,- `genpage-plan-schema.md` → `plan-schema.md`,- `genpage-localization-reference.md` → `localization.md`,- `data-caching-pattern.md` → `data-caching.md`.-- Removed stale `samples/3-poa-revocation-wizard.tsx` (327 lines, redundant- with `2-wizard-multi-step.tsx` for the wizard pattern; the DataGrid /- file-upload / multiselect patterns it composed are covered by other- samples). Renumbered 4–8 → 3–7 to close the gap.--### Added (samples)-- `samples/8-dashboard-with-charts.tsx` — KPI cards + two D3 charts (area +- donut) with the animation guard from rules.md. Covers the dashboard page- type and the D3 chart pattern that evals 2 and 6 expect.-- `samples/9-list-with-caching.tsx` — list page using Rule 15's window cache- + inline async IIFE pattern. Cross-page navigation to the detail sample via- `PAGEREF_` placeholder.-- `samples/10-detail-with-pageinput.tsx` — detail page paired with the list.- Receives `pageInput.recordId` synchronously, initial `loading: true` on- frame 0, `Map<recordId, row>` cache on `window`. Demonstrates the- formatted-value lookup for `_parentcustomerid_value`.-- Added scope headers to `rules.md` "Common Errors" (generation-time- anti-patterns) and `troubleshooting.md` (deployment/runtime/env) so readers- can pick the right one without scanning.--### Migration from 2.0-1. `az login` (use the same identity as `pac auth who`).-2. Uninstall the Dataverse Skills plugin if it was only for `/genpage`.-3. No code/page changes needed; existing pages keep working.-------## 2.0.0 — 2026-05-12--Major refactor of `/genpage` into an agent-orchestrated architecture.--### Breaking-- **PAC CLI ≥ 2.7.0** required (for `pac model create`, `pac model list-tables --search`).-- Skill output now lives in a per-invocation working directory- (`genpage-plan.md`, `RuntimeTypes.ts`, one `.tsx` per page, `workflow-log.md`).-- Plan-mode approval is mandatory; no skip/auto-accept.--### Added-- Four specialist agents: `genpage-planner`, `genpage-entity-builder`,- `genpage-page-builder`, `genpage-edit-planner`.-- Multi-page parallel generation; cross-page navigation via `PAGEREF_<filename>`- placeholders resolved in Phase 6.5.-- `pac model create` inline app provisioning.-- Plan schema contract at `references/plan-schema.md`.-- Verified Fluent icon list at `references/verified-icons.txt` (~5000 names).-- Eval suite: 16 evals across smoke/full/stress tiers + runbook.--### Changed-- Entity detection uses native `pac model list-tables --search` with exact- logical-name match.-- Component template destructures `pageInput` in addition to `dataApi`.-- Rules reference adds Rule 14 (batched async state) and Rule 15 (data-fetching- IIFE + cache guard).--### Migration from 1.x-1. `dotnet tool update --global Microsoft.PowerApps.CLI.Tool` (to ≥ 2.7.0).-2. Existing deployed pages keep working — only local workflow/layout changed.-------## 1.0.6 — earlier in 2026--PageInput support, FluentProvider flicker fix, lookup `$select` rule, data-caching pattern. See git history for details.+# Changelog++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.5.0++Takes up the current maker SDK, adds modern-shell and navigation controls, labels Dataverse+metadata in the organization's own language instead of a hardcoded 1033, makes persona roles+and jobs-to-be-done checkable, and fixes a class of failures that were silent.++### Added+- **`businessRules[]` — declarative form logic, no code.** Show/hide, lock/unlock, set-required and+ set-value, gated on a condition over the record; compiled to classic workflow XAML and activated on+ create. Every field is checked against the rule's own entity, because a rule naming a column that+ does not exist is accepted by the platform and then simply never fires. Operators `Equals` ·+ `DoesNotEqual`. Additive on rebuild, torn down with the app, and a new `business-rules` build+ phase (15 now).+- **Custom grid rendering (preview) — `entities[].columns[].visualization`.** Render a column as a+ radial dial, line chart, heat map or star rating in every grid and view that shows it. Per-column,+ so it is declared once rather than per view. Where the platform has not provisioned the preview the+ build skips it and everything else still deploys.+- **`app.newLook` — opt into the modern ("new look") shell.** Writes the per-app+ `NewLookAlwaysOn` setting, so the result is deterministic rather than a per-user preference.+ Scoped to the app and solution so it travels on export/import. Best-effort: a tenant without+ the definition still gets a working app on the classic shell, with a warning.+- **`app.headerNavigationRefresh` — control the Wave 2 header and navigation refresh.** A+ **separate, independent** setting from `app.newLook`; enabling one does not enable the other.+ The platform default is **ON**, so this exists as much to turn the refresh off as on — `false`+ is written actively rather than treated as "do nothing".+- **Labels honour the authoring language everywhere**+ ([#447](https://github.com/microsoft/power-platform-skills/issues/447),+ [#455](https://github.com/microsoft/power-platform-skills/issues/455)). Tables, columns,+ choices, **form, dashboard and sitemap labels** all use one resolved LCID. Previously only the+ data-model phase respected it, so `--language-code 1031` produced German columns and English+ form labels. Precedence: `--language-code` / `--languageCode` → App Spec `languageCode` → the+ organization's base language → 1033. Omit it and behaviour is unchanged.+- **An unprovisioned `languageCode` stops the build before any label is written**+ ([#456](https://github.com/microsoft/power-platform-skills/issues/456)), naming the LCID you+ asked for and the ones the organization actually has. Dataverse otherwise fails *inconsistently*+ here — it accepts an unprovisioned LCID on tables and choices and rejects it on `DateTime` and+ `Memo` — so the build died phases away from the flag that caused it.+- **A hand-pinned `languageCode` survives download.** Download still never reads the LCID from+ Dataverse (that would make the spec non-portable), but a value you wrote is carried over.+- **`directEntry` on `pages[]`.** Every page is a sitemap subarea, so a **detail** page is+ reachable from navigation with no input. A page declaring `pageInput` must now say what happens+ then: `{ "behavior": "selector" }` (show a picker) or `{ "behavior": "emptyState" }`. Every key+ in `pageInput.data` must also be supplied by an incoming `navigatesTo[].data` edge.+- **`verify` proves what a persona security role GRANTS**, not just that the role exists — every+ declared `(entity, access)` is resolved to its Dataverse privilege and checked at **at least**+ the declared depth. A subset check by design; fails closed on an unreadable role or table.+- **`personas[].jobs[].surfaces[]` is checked, not documentary.** `spec-lint` warns when a surface+ matches nothing in the spec, and `verify` reports a deployed failure as the job it broke+ ("persona P can no longer do job J") rather than only "view X is missing".+- **Automatic plugin update notice** — a non-blocking preflight tells you when a newer Model Apps+ version is available, with the update command for your host.++### Fixed+- **Command buttons now actually run.** A JS command was created with no on-click parameters, so the+ function was invoked with no arguments — the near-universal `function doThing(primaryControl)` shape+ threw on its first property access and the button silently did nothing. Nothing server-side showed+ it: the build, the deployed rows and `--verify` all looked correct, and the error appeared only in+ the browser console. Buttons now receive the standard parameters for their location+ (`MainTab` → PrimaryControl; grid/subgrid → SelectedControl), overridable via `parameters`.+- **Business rules no longer mistake the platform's activated copy for a duplicate.** Activating a+ rule makes Dataverse create a second `workflows` row (`type 2`, parented to the definition) — normal+ for any activated process. Build, verify and teardown queried without `type eq 1`, so the build+ tried to delete that copy (which the platform refuses, 405) and warned about a duplicate that did+ not exist, teardown failed on it, and verify would have reported every active rule as duplicated.+ All three now select definitions only.+- **AI preflight no longer reports a running feature as disabled.** The readiness gate and a+ feature's actual setting are different rows, so a gate reading off did not mean the feature was+ off — NL search and NL charts were reported as unavailable while both were in effect. Preflight now+ resolves the effective value (app override → environment → default), says which scope enabled it,+ and stops emitting an admin action for a feature that is already on.+- **Rebuilds no longer duplicate sub-grids or skip field removals.** The vendored SDK's artifact+ surface became **asynchronous** upstream (`getArtifact`, `addElement`, `updateElement`,+ `removeElement`, `moveElement`, `findElements`, `queryTree`). Un-awaited, that fails *silently*:+ a promise is truthy, so guards never fire and the form helpers see a promise instead of a form —+ producing duplicate sub-grids and quick-views, re-added fields, and field removals that never+ land, all behind `2xx` responses and a green build. All 40 call sites are fixed, and two nets now+ guard the class (a source scan, and test mocks that actually yield).+- **Dashboard chart tiles no longer fail the `dashboards` phase.** A tile emitted `ChartId`, which+ the platform's FormXML schema rejects; the correct name is `VisualizationId`. Found by a live+ build — the mock-based test had asserted the wrong name, so the suite agreed with the bug.+- **Publish failures are no longer silent.** The SDK moved `publishArtifact` from throwing to+ reporting by value and all nine call sites discarded the result, so a failed `PublishXml`+ produced `ok: true` with nothing logged — and the transient-retry path for 429 / 503 /+ customization-lock had become unreachable.+- **A partially-wrong push no longer reads as a clean success.** `PushResult.warnings[]` were+ dropped at all eleven sites — including the case where an app's system-administrator role+ assignment fails, which yields an app nobody can open.+- **A 412 version conflict could be swallowed.** The SDK renamed `PushResult.success` to `saved`;+ the guard still read `success === false` and simply stopped firing, dropping a concurrent Maker+ edit with no error. It now reads either spelling and fails closed.+- **A sitemap subarea targeting a custom web resource round-trips**+ ([#430](https://github.com/microsoft/power-platform-skills/issues/430)). `$webresource:<name>`+ was rejected by the URL guard, so the downloaded spec failed validation and **no spec file was+ written at all** — blocking the whole download → edit → rebuild flow over one nav entry.+- **Malformed specs produce validation errors instead of raw `TypeError`s**, and can no longer pass+ validation and then crash mid-build *after* the solution and data model were written. Errors name+ the exact path (`appShell.areas[0].groups must be an array`).+- **`verify-model-app` reports a missing table as a finding**, not a raw Dataverse HTTP 400, and+ prints the failure detail so a failed *read* is distinguishable from a genuinely absent artifact.+- **The live smoke eval asserted an outcome the builder never produces** — it used the one icon+ shape the builder deliberately drops, and the offline test hid it by hand-writing the XML it+ wanted to see.++### Known limitations+- **A classic dashboard does not survive `download-model-app.js`.** Build and teardown work, but the+ vendored SDK's `fetchArtifact('dashboard', …)` throws while deserializing the `<parameters>` block+ it itself serialized, so no tiles are recovered and the dashboard's sitemap subarea is dropped —+ failing the whole download unless `--allow-lossy-download` is passed. Live-verified, and reproduced+ on the previous bundle too, so it is **not** a regression from this release's SDK uptake. Download+ now names the cause instead of dropping the subarea silently. Tracked upstream.++### Changed+- **Business rules are authorable — the vendored SDK now compiles them to classic workflow XAML.**+ They were unauthorable because the supported bound member faults (`400 0x80040216`) on our tenants;+ the SDK now falls back to a plain `workflows` row carrying compiled WWF XAML. The fallback is+ narrow on purpose — only that code, or a `404` — so an ambiguous failure can never write the rule+ twice. Live-verified end to end, and pinned against the shipped bundle in+ `sdk-uptake-contract.test.js`. **The App Spec does not expose business rules yet;** this makes them+ possible, not authorable from a spec.++- **Column data visualizations for grids** (`getColumnVisualization` / `setColumnVisualization`)+ are available on the vendored SDK (preview). Not yet surfaced in the App Spec.++- **An app now requires an image icon.** `appmodule.webresourceid` is required, and the SDK's+ auto-resolve now demands an **image** web resource, failing with `APP_ICON_UNRESOLVED` when the+ environment has none — it previously fell back to any unmanaged web resource, including a+ **JavaScript** file, which the platform then rejected opaquely. No change for `/app-builder`: it+ always generates or resolves an icon and passes it explicitly.++- **Vendored SDK re-taken from its merged `master`, and it now records its provenance.**+ `scripts/vendor/PROVENANCE.json` carries the upstream SHA, build mode and the bundle's own+ sha256, and the bundler **refuses** a stale, dirty or unidentifiable source. "Built from master"+ is not provenance: the previously shipped bundle was built from a stale build output several+ commits behind its nominal source, and nothing in the repo could reveal it.+- **Three SDK contract changes are user-visible**: `deleteAppCascade` no longer deletes generative+ pages (they are *referenced* by an app, not owned by one, so they are reported in `retained[]`);+ unconditional artifact writes are refused (`ARTIFACT_UPDATE_NO_ETAG`); and `pushArtifact` /+ `publishArtifact` report failure by value instead of throwing.+- **`download-model-app.js --app` accepts a display name**, not just an id or `uniquename`, and+ fails closed when a display name matches more than one app.++### Tests+- ~1600 plugin tests + 159 eval tests; 94% line coverage.+- **The mocks no longer lie about the SDK contract.** Every mock returned plain values while the+ real SDK returns promises, so a missing `await` behaved identically under test — leaving ~1500+ tests structurally blind to the class above. They are now `async` *and* yield.+- **Rebuild idempotence is asserted.** Reconcile tests started from an *empty* deployed form, where+ "re-add everything" and "add only what's missing" produce identical call logs.+- **Concurrency stress against the real bundle**, and contract tests that pin the SDK's async+ surface, its serialized sitemap bytes, and the committed bundle against its provenance record.++## [2.4.2]++Fixes a malformed app module: generated apps did not actually contain their tables.++### Fixed+- **Generated apps contained an invalid `entity` table component instead of their real tables**+ (ADO 6612527), which also broke unrelated app-processing paths. The documented `@odata.type`+ shape returns 204 and then records a component pointing at the metadata table literally named+ `entity` (platform defect **AB#39140211**). Tables are now pinned by OData **reference** — the+ only form that can also express an abstract table such as `activitypointer`.+- **An unresolvable table halts the build, naming it.** One bad component fails the whole+ `AddAppComponents` call, so a silently-skipped table used to empty the app's component list.+- **App components are read back and verified after the write** — `AddAppComponents` returned 204+ for every corrupt app, and `ValidateApp` reported success too.++### Changed+- Re-vendored `cds-maker-sdk` with the above.++### Eval harness+- **A value-less or malformed runner flag is rejected** instead of silently changing scope — a bare+ `--tier` became "no tier filter", and the run then reported PASS for a scope nobody asked for.+ The parser is now shared at `evals/model-apps/lib/eval-args.js`.+- **A malformed fixture names the fixture**, tolerates a UTF-8 BOM, and rejects a non-object spec+ up front.++### Known limitations+- **Download still drops entity components not in the sitemap** (ADO 6603388) — the hidden+ component it describes could not be constructed live, so the download-side fix is unverified.++## 2.4.1++Bug fixes for apps built on **out-of-the-box** tables, and the matching SDK uptake. No change to+any skill's public surface.++### Fixed+- **AI app features had no effect on a newly built app** — an app-scope setting write is a no-op+ until the app is published, so the build wrote nothing while reporting success.+- **`--verify` passed when AI features were never applied** — it now proves an app-scope override+ row, because reading the setting back falls through to the environment value.+- **`ai.appFeatures` accepts non-boolean values** such as `2` ("on for everyone").+- **Download invented primary-name columns**, **replaced the solution's publisher prefix with+ `new`**, and **dropped tables with no sitemap entry** — all three now read from Dataverse.+- **Teardown could permanently burn an app's unique name** — an app is two rows with no server-side+ cascade, so deleting only the app module stranded the sitemap and reserved its name forever. Both+ rows are now deleted atomically in one OData `$batch`.++### Changed+- Re-vendored `cds-maker-sdk`. An injected `HttpClient` must now implement `postRaw` for the atomic+ `$batch`.++### Tests+- 1266 → 1340 tests; coverage 92.7 → 93.9% line.+- **model-apps now runs in CI** (ubuntu × windows × macos, Node 20 × 22, plus the offline evals) —+ previously every test workflow was scoped to another plugin, so this suite never ran on a PR.++## 2.4.0++A new **`/app-builder`** skill (Preview) that builds and edits whole model-driven apps, plus+local-dev ergonomics, sample coverage, and an automated eval suite. No breaking changes.++### Added+- **`/app-builder` (Preview)** — natural-language intent → deployed model-driven app: tables,+ columns, relationships, adaptive forms with sub-grids, views, charts, dashboards, generative+ pages, app + sitemap, and sample data, via the headless vendored `cds-maker-sdk`.+- **Jobs-to-be-done drive the design** — authoring starts by asking who uses the app and what each+ of them needs to get done, *before* the data model, and carries those jobs through to the+ surfaces that satisfy them.+- **Security roles per persona (`personas[]`)** — one role per persona, sized to the privileges its+ jobs declare, associated with the app so it opens for non-admins.+- **`model-app-plan.md`** — a readable, regenerable design document rendered from the spec, plus+ design-gap warnings at the lint gate (a job with no covering surface, an app with no pages).+- **Table icons are described before they are drawn** — each table proposes what its glyph will+ *depict* in plain language, shown for approval before any SVG is authored.+- **AI-first features** (`ai` block) — form fill, NL search, NL charts, M365 Copilot and row+ summaries, admin-gated by a preflight.+- **`--changed-only` partial apply (Preview, off by default)** — a page-only `.tsx` edit re-runs+ just the pages phase; anything else falls back to a full build.+- **`scripts/preview-app.js`** to review the whole design before building, and an offline eval+ suite for `/app-builder` alongside the genpage TAP runners.++### Changed+- **Edits are first-class**: forms and views update in place, a form edit can *remove* a field, a+ built main form becomes the entity default, and editing an existing app updates the sitemap for+ page-less apps too.+- **Identity is unambiguous** — forms resolve by `(entity, name, type)`, views by `entity|name`,+ and an app round-trips by its real `uniquename`, so a rebuild cannot duplicate or cross-wire.+- **Page generation reuses the `/genpage` worker** through a plan adapter, so an intent page can no+ longer silently fail to become `.tsx`; untrusted spec text cannot forge plan sections.+- Re-vendored `cds-maker-sdk` (pagination, quick create, idempotent global choice, authored column+ width, shared input-safety boundaries).++### Fixed+- **Teardown removes everything the app owns** — icon and app-icon web resources are removed, cascade+ failures are reported rather than silently orphaning rows, and reused/system tables are skipped+ with a reason. Command-bar teardown is fail-closed. The **publisher** is deliberately left behind:+ it can own other solutions, so removing it is not this app's decision.+- **Exported solutions are self-contained** — the app icon and sitemap are added to the solution.+- **The Dataverse token is never sent to another origin** — the HTTP client refuses any request+ outside the absolute `https` org URL.+- **A lossy download fails instead of reporting success** (`--allow-lossy-download` opts in), and+ **CLI flags fail loudly** — notably `--apply --only` with no phase list used to run a *full* apply.+- Assorted: relationships to system tables, classic dashboard round-trip, AI row summaries, and+ sub-grid `targetEntity`.++### Removed+- Standalone entity/solution scripts, consolidated into `provision-entities.js` and+ `provision-solution.js`.++### Known limitations+- **App EDIT does not re-pin a new chart** as an explicit app component — a chart added to an+ existing app needs a manual pin or a rebuild.++## 2.3.0 — 2026-07-23++Plugin observability and authoring guardrails. No breaking changes.++### Added+- **Anonymous 1DS telemetry** (default-on, ships `disabled` until provisioned) with a local+ diagnostic mirror, a `/model-apps:telemetry on|off|status` control skill, and a CI opt-out via+ `POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT=1`. Fail-closed throughout, and carries **no+ user-level identifier**.+- **PostToolUse validators**, including a `@fluentui/react-icons` allowlist check that blocks a+ hallucinated icon name at write time.+- **PreToolUse write-safety guard** — flags writes outside the cwd during an active genpage+ session only, so a globally-installed plugin never interferes with unrelated work.++### Fixed+- **Generated-page double-fetch / render flash on open.** The webplayer host double-mounts a page,+ and `dataApi` is a new reference each render, so a `useEffect` dep on it re-fires forever.+ Guidance and every exemplar now use an in-flight-promise de-dupe plus a window cache and a+ readiness boolean; `dataApi` is forbidden in any dependency array.+- **Playwright MCP launcher** — exports `launch()` per the `.mcp.json` contract, avoids the npx+ first-run prompt hang, and quotes config paths so Windows paths with spaces work.++## 2.2.0++Local-dev ergonomics, sample coverage, and an automated eval suite. No breaking changes.++### Added+- **Local-dev manifest** — working dirs get `package.json` and `genpage.d.ts`, so `npm install` and+ editor IntelliSense work after generation.+- **Eval suite** — TAP v13 runners for workflow and code assertions, 10 shipping fixtures, and+ `capture-fixture.js` to turn a real `/genpage` run into one.+- **Dialog and overlay guidance** plus samples — portalled Fluent surfaces are confined to the page+ so a modal cannot escape the preview and cover the designer.+- **Feature-flag gate for connectors (default OFF)**, with all connector work owned by a single+ `genpage-connector-builder` agent invoked from both the create and edit flows.++### Fixed+- **`queryTable` returns a `DataTable`, not an array** — 7 samples and fixtures iterated the result+ directly, producing `X.map is not a function` at runtime. A new assertion catches it going forward.++## 2.1.0 — 2026-05-13++Replaces the Dataverse MCP server + Python SDK fallback with Node.js Web API scripts. Adds solution+selection, prefix discipline, and a consolidated auth pre-flight.++### Breaking+- **Azure CLI (`az`) is now required** for entity creation, with access to the target environment.+- **The Dataverse Skills plugin is no longer required.**++### Added+- Node.js Web API scripts under `scripts/` (auth, request, table/column/relationship/record+ creation with `$batch` bulk, solution management).+- Solution selection with prefix-conflict warnings, and a transactional creation log.++### Fixed+- **Prefix drift is structurally impossible** — the plan stores logical-name suffixes only, and the+ full name is constructed from one source of truth.+- **`pac model create` always passes `--solution`** — the CLI's "active solution" fallback errors+ in practice.++### Performance+- ~27K tokens saved per page-builder run (icon list is no longer loaded upfront; reference docs and+ the opt-in browser-verification flow were extracted or trimmed).++### Added (samples)+- Dashboard with D3 charts, a list page using the window-cache pattern, and its paired detail page+ demonstrating `pageInput` and the formatted-value lookup.++### Migration from 2.0+1. `az login` (use the same identity as `pac auth who`).+2. Uninstall the Dataverse Skills plugin if it was only for `/genpage`.+3. No code or page changes needed; existing pages keep working.++---++## 2.0.0 — 2026-05-12++Major refactor of `/genpage` into an agent-orchestrated architecture.++### Breaking+- **PAC CLI ≥ 2.7.0** required.+- Skill output now lives in a per-invocation working directory.+- Plan-mode approval is mandatory; no skip or auto-accept.++### Added+- Four specialist agents (planner, entity-builder, page-builder, edit-planner).+- Multi-page parallel generation with cross-page navigation via `PAGEREF_<filename>` placeholders.+- A plan schema contract, a verified Fluent icon list, and a 16-eval suite across three tiers.++### Migration from 1.x+1. `dotnet tool update --global Microsoft.PowerApps.CLI.Tool` (to ≥ 2.7.0).+2. Existing deployed pages keep working — only the local workflow and layout changed.++---++## 1.0.6 — earlier in 2026++PageInput support, FluentProvider flicker fix, lookup `$select` rule, data caching pattern. See git+history for details.diff --git a/plugins/model-apps/agents/genpage-entity-builder.md b/plugins/model-apps/agents/genpage-entity-builder.mdindex 74bf50d4e..f789ae414 100644--- a/plugins/model-apps/agents/genpage-entity-builder.md+++ b/plugins/model-apps/agents/genpage-entity-builder.md@@ -167,11 +167,19 @@ it only to deliberately author labels in a *different* provisioned language. Itinteger LCID up to 65535 (`1031`, not `"de-DE"`); an invalid value is rejected before any Dataversewrite. `--language-code` / `--languageCode <lcid>` overrides it for one run.-**If provisioning fails with `The language code N is not a valid language for this organization`,**-that is this setting — the organization does not have LCID N. Re-run with `--language-code <an LCID-the org actually has>`. Note the failure is *not* all-or-nothing: the table and any Choice columns-are created first and it fails on the first `DateTime`/`Memo` column, so it can look like an-environment fault. A `⚠ could not determine the organization's base language …` warning on stderr+**If you pass an LCID the organization has not provisioned,** provisioning now stops at the start of+the data-model step, before any label is written, and lists the languages the org does have.+(The solution and publisher may already exist by then — they carry no language, so nothing lands+mislabelled.) Previously this failed *partway through*:+Dataverse accepts table and Choice labels in an unprovisioned language (silently storing them under+the org's base language) but rejects `DateTime` and `Memo` columns with `The language code N is not a+valid language for this organization` — so the table and Choice columns were created first and it+died on the first `DateTime`/`Memo` column, which looked like an environment fault. Re-run with+`--language-code <an LCID the org actually has>`; list them with+`node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET RetrieveProvisionedLanguages`. The+check is best-effort: if that read fails, provisioning proceeds unchanged.++A `⚠ could not determine the organization's base language …` warning on stderrmeans discovery failed and 1033 was assumed — pass the flag explicitly.The input JSON follows the App Spec format. Build it with:diff --git a/plugins/model-apps/docs/app-builder-capabilities.md b/plugins/model-apps/docs/app-builder-capabilities.mdnew file mode 100644index 000000000..aa6d9df6d--- /dev/null+++ b/plugins/model-apps/docs/app-builder-capabilities.md@@ -0,0 +1,138 @@+# app-builder — capabilities++What the `/app-builder` skill can do today, and how far each capability has been proven. The build+engine is [`../scripts/lib/sdk-build.js`](../scripts/lib/sdk-build.js); the App Spec contract is+[`../references/app-spec-schema.md`](../references/app-spec-schema.md); the wiring diagrams are in+[`architecture.md`](architecture.md).++This file records **shipped** behaviour only. Planned and unbuilt work is tracked in GitHub issues —+the carried-over backlog is+[#480](https://github.com/microsoft/power-platform-skills/issues/480). A roadmap committed alongside+the code goes stale silently and states intent the code does not yet support, so the two are kept+apart deliberately.++**Evidence legend**+- ✅ **verified live** — built end-to-end on a real Dataverse environment and torn down clean.+- 🧪 **tested** — has automated (unit / golden / real-bundle) coverage, not exercised on a live org.+- ⚠ **not live-verified** — plumbed through and unit-tested, awaiting a live shakeout.++### Authoring & build framework — ✅ verified live+- Interactive levelled authoring in the **main loop** — jobs-to-be-done first, then data model,+ artifacts + page-intents, then access (env select, App Spec, lint gate, plan-mode approval).+- Deterministic, **idempotent** build engine — discovers via the SDK (`findTables`/`findColumns`/`fetchEntityMetadata`) and creates only what's missing; new / existing / mixed envs all work.+- **All Dataverse access via the vendored headless SDK**; metadata cached under `<app-folder>/.maker-workspace/` for reuse.+- Phase selection (`--only`/`--skip`/`--from`/`--to`), `[n/total]` narration, `BuildHalt` gate, dry-run by default, `--sample-data` / `--publish` opt-in.+- Bounded-concurrency for independent ops; one publish round-trip per entity + the app. `az`-token HttpClient with transient (429 / 5xx) retry.+- Guardrail lint (`spec-lint.js`) + hard validator (`app-spec.js`). 🧪 full `node:test` suite + the vendored SDK's Jest suite green (`node scripts/run-tests.js --with-sdk <ppux>`).++### Data model (Tier 1) — ✅ verified live+- All column types: Text · Memo · Choice · MultiChoice · Boolean · Money · DateTime · Integer · BigInt · Decimal · Double · File · Image · AutoNumber · Customer (with per-type options), incl. AutoNumber primary columns.+- Global option sets, status reasons (idempotent, deterministic pinned values), alternate keys (idempotent).+- Relationships: OneToMany (lookup) **and** ManyToMany; Customer (polymorphic) columns.+- Sample data: Choice/MultiChoice label→int resolution (inline **and** global choices), `$parent`/`$parents` lookup binds (incl. junction rows with both sides), custom status reasons; resolve-by-name idempotency via the SDK's `seedRecordGraph`.+- ⚠ Calculated / Rollup formula columns — `source` + `formula` plumbed through, **not live-verified**.+- **Table icons** (`entities[].vectorIcon` = SVG web resource → `IconVectorName`; `entities[].icon` = raster web resource → `IconMediumName`) — sets a custom table's own icon (what the modern designer + nav render). Applied after the web-resources phase via the SDK's `setEntityIcon`; hard-validated against declared web resources so an unresolvable value can't break the designer (glimmer). Live-verified: `IconVectorName` set to a published SVG web resource.++### Business rules — ✅ verified live+- `businessRules[]` — declarative form logic with no code: show/hide (`SetVisibility`), lock/unlock+ (`LockUnlock`), set-required (`SetBusinessRequired`) and set-value (`SetFieldValue`), gated on a+ condition over the record (`Equals` · `DoesNotEqual`). `ContainsData`/`DoesNotContainData` are+ rejected at the spec gate — the XAML they compile to makes the platform 500 on activation.+- Compiled to classic workflow XAML by the vendored SDK and activated on create. The supported slice+ is exactly what that compiler accepts; every field is validated against the rule's own entity, so a+ rule naming a column that does not exist is rejected up front rather than deploying and never firing.+- Additive on rebuild (matched by `entity` + `name`, reused if present); torn down with the app.+- **Activating a rule creates a second `workflows` row, and that is normal.** Dataverse keeps the+ definition (`type 1`, no parent) and an activated copy (`type 2`, parented to it). Live-measured: a+ Draft create yields one row, a plain `PATCH` to `statecode 1` yields two — and a PATCH cannot create+ anything, so the platform makes it. Every business-rule query in build, verify and teardown filters+ `type eq 1`; omitting it made the build attempt to delete the copy (405), warn about a duplicate+ that did not exist, and would have made `--verify` fail every active rule.+- Live-verified end to end through the App Spec: rules authored from `businessRules[]` deployed,+ activated, and the platform's own generated `clientdata` named the authored columns.++### Forms, views & charts — ✅ verified live+- Adaptive main forms (auto + explicit tabs/sections), related-record sub-grids (1:N **and** N:N), Notes/timeline section.+- Quick-create + quick-view forms (`forms[].formType`); quick-view **placement** on a host form via a lookup (`forms[].quickViews[]`).+- Form JS event handlers (`onload`/`onsave`/`onchange`) wired via web resources.+- Views with rich filters (`eq-userid`/`this-week`/`in`/`not-in`/… + Choice-label resolution); default Active/Inactive view **column enrichment** via the SDK's `enrichDefaultViews`.+- Choice-column charts.++### Custom grid rendering (preview) — ✅ SDK live-verified, environment-gated+- `entities[].columns[].visualization` — render a column as a `RadialDial`, `LineChart`, `HeatMap`+ or `StarRating` in **every** grid and view that shows it, instead of plain text. `None` clears it.+ Per-*column* metadata (a `controlconfiguration` row bound to the attribute), so it is declared once+ on the column rather than on each view.+- Type-only: the renderers use built-in defaults (dial 0–100, stars 0–5) with no tuning parameters.+ Column-type compatibility is **not** validated — the platform does not enforce a clean "numeric+ only" rule (`LineChart` is documented for a *text* column of comma-separated numbers), so guessing+ a constraint would reject valid specs. Guidance lives in the schema doc.+- Re-asserted on every build, for pre-existing columns as well as new ones, converging to a single+ configuration row. Omitting the field leaves a deployed renderer alone; `"None"` is how a spec+ actively clears one.+- **Environment-gated preview.** Where the platform has not provisioned it, the backing+ `controlconfigurations` table is absent and every call 404s; the build **skips** the step (the+ column and all other artifacts still deploy) and verify reports no divergence. Live-measured: the+ table was present on **1 of 18** test environments, so a missing renderer is an environment+ question first, not a spec bug.+- Live-verified on a provisioned environment: set from scratch, updated in place (the rebuild path),+ re-asserted without duplicating the config row, all four renderers accepted, and cleared with+ `None` — 6/6.++### App shell & navigation — ✅ verified live+- App module + sitemap; **multi-area sitemaps** — every `appShell.areas[]` maps to its own `<Area>` (icon + groups + subareas; order follows array order). The app is **self-contained for export/import**: its **sitemap** is added to the solution (componenttype 62), and its **tile icon** is an in-solution web resource — `app.icon` (a declared image web resource) or a generated default SVG — never an arbitrary external/managed icon.+- Generative pages (**genpage-first**) for overview / dashboard surfaces — uploaded via `pac model genpage upload`; the SDK finalizes the sitemap with `GenPage` subareas.+- Dashboards (chart / list / iframe / webresource tiles) with **sitemap placement** (auto-pinned as an app component). Tiles render in a **multi-column grid** (2-wide) rather than one stacked full-width column.+- Modern command-bar buttons — functional **JS on-click** + static hidden/disabled, incl. **flyout / split-button menus**.+- Web resources (JS / HTML / CSS) shipped + added to the solution; idempotent (reuse by name).++### Generative-page management — three-authority, id-based — 🧪 tested+- **Three-authority page identity.** IDENTITY = durable `<app>_pagemanifest` (key→pageId map), outranked by the spec's own `pages[].pageId` for a downloaded (edit-snapshot) spec. EXISTENCE = env-wide `pac model genpage list` — decides create-vs-reuse for crash-safe convergence (`enumerateEnv`, no `--app-id`). MEMBERSHIP = the app's sitemap `GenPageId` set, read fail-closed via `fetchSitemap` (`scripts/lib/sitemap-pages.js`) — drives placement, download enumeration, and verify. All page matching is by id, never by display name.+- **Edit-snapshot `pageId`.** Download keeps each page's deployed `GenPageId` as `pages[].pageId` in the emitted spec. On rebuild, this highest-authority id is confirmed against EXISTENCE and reused — so a downloaded app (including Maker-added pages) rebuilds without creating duplicates.+- **Validation: every page must be sitemap-placed.** A `pages[]` entry absent from the `appShell` sitemap is rejected; navigation-only (headless) pages are not supported. A "detail" page is a normal sitemap page receiving input via `pageInput`.+- **Safety HALTs:** `pages-removed` (live page dropped from spec — re-add or `--allow-destructive` detaches the nav SubArea, page left deployed), `pages-shared-across-apps` (`--allow-destructive` does NOT bypass; detach in Maker), `pages-identity-conflict`, `pages-manifest-corrupt`, `pages-existence-failed`, `pages-sitemap-read-failed`, `pages-shared-check-failed`.+- **Verify and download** match by id with exact set-equality (EXISTENCE + MEMBERSHIP); a manifest-uncorrelatable page surfaces `unableToRun`.++### AI-first features — ✅ verified live+- `ai` block → `ai-features` phase: form-fill, NL search, NL charts, M365 Copilot, and per-table Copilot **row summaries** with tailored `GptDynamicPrompt-2` prompts (auto-selected candidate tables; skips lookup/config/junction + D365-owned incident/lead/opportunity).+- **Admin-gated**: preflights each setting (`RetrieveSetting`), skips/warns when off, never fails the build. NL grid search is **environment-gated** (`EnableNLGridSearch`), not per-app. Standalone reporter `scripts/ai-preflight.js`.+- **The readiness gate is not the whole truth, and the report now says so.** A feature's gate and its+ actual setting are *different rows*, and a gate can read off while the feature is switched on at+ environment scope — so it runs in every app on that org. Live-measured: gate `EnableNLGridSearch`+ = `false` while `NLGridSearchSetting` = `2` at environment scope (NL search on), and+ `NLChartDataVisualizationSetting` = `1` by default (NL charts on). Preflight resolves the+ effective value per feature — app-scope override → environment → default — reports those as+ *in effect via the environment/default setting*, and **suppresses the admin action**, so nobody is+ sent to the admin centre to switch on something already running. A value it cannot read never+ counts as in effect, so a genuine action is never hidden.+- **Form fill is a real "off", not a naming mix-up** (measured 2026-08-28). Unlike NL search, the+ gate and the per-app setting share one name — `FormFillBarUXEnabled` — confirmed against the+ SDK's own `AI_GATE`/per-app maps, so there is no second setting hiding a different answer. It+ reads `0` at org *and* app scope, and it is `0` on **all 161** orgs in the test tenant.+- **`formFill` is the assist TOOLBAR only, and the report now says so.** "AI form fill assistance"+ is a family; `FormFillBarUXEnabled` governs one member of it. Three siblings are neither covered+ by that flag nor exposed by the App Spec: `FormFillFileUploadEnabled` (file upload),+ `FormPredictSmartPasteEnabled` (smart paste) and `FormPredictEnabled` (edit-form predictions).+ Calling the flag "Form fill" overclaimed in both directions — it reported the feature unavailable+ to someone who may have had smart paste working, and implied enabling it turned the family on. All+ four members were measured off across 40 orgs, so nothing is silently on here; exposing the+ siblings would be a feature (new spec keys plus live verification), not a rename.+- **The setting names are now pinned against the bundle.** Nothing previously did: every test+ hardcoded the same strings the source does, so an upstream rename would have left the suite green+ while the build wrote to a setting that no longer exists — the same shape as the+ `success`→`saved` rename that silently disarmed the 412 guard. `sdk-uptake-contract.test.js`+ compares `AI_APP_SETTING` to the SDK's map and asserts the gate/per-app names stay distinct.++### 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 does not currently work end to end:** live-verified 2026-08-27, the vendored SDK's `fetchArtifact('dashboard', …)` throws `Cannot read properties of null (reading 'length')` while deserializing the `<parameters>` block it itself serialized, so no tiles are recovered and the subarea is dropped — which then fails the whole download unless `--allow-lossy-download` is passed. Reproduced on the current **and** the previous bundle, so it is not a regression from the SDK uptake; tracked upstream. Download now names the cause instead of silently dropping the subarea. **Round-trip scope (not yet "complete"):** tables, sitemap/appShell, generative pages, icons, and solution round-trip; **dashboards, 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.+- 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 name) and matching the sitemap's `DefaultDashboard` — so a value reused elsewhere can't produce a false pass. **Multi-area sitemaps** and the dashboard-subarea path were re-verified live (positive + negative).++### Teardown — ✅ verified live+- `teardown-model-app.js` deletes exactly what an App Spec declares, in dependency-safe order (app → dashboards → commands → forms → charts → views → relationships → AI row summaries → tables [children-first] → web-resources → global choices → solution). Forms/charts/views/relationships are removed **before** tables (a table delete doesn't reliably cascade cross-references); **web resources are removed AFTER tables** (a table's icon web resource is referenced by the table).+- **Classifier-safe** (every id resolved from a spec-declared name via an exact-match, entity-scoped filter), dry-run by default, best-effort continue, not-found aware, undeletable (system/managed) artifacts recorded as `skipped`. A **restricted system solution** (`Active`/`Default`/`Basic`) is skipped rather than attempted (Dataverse 400s any delete of one), so a downloaded spec that defaulted its solution to `Default` tears down cleanly. An already-gone relationship (Dataverse 400 *"…but 0 were found"*) is tolerated as deleted, like the table not-found case.++### Tooling & internals — ✅ verified live+- ASCII **form wireframe** preview (`preview-form.js`); phase-grouped build log with per-step status glyphs (`✓`/`⊘`/`✗`) + a closing summary.+- **SDK consolidation** — the SDK owns the Dataverse mechanics (`seedRecordGraph`, `enrichDefaultViews`, AI settings/row-summaries, artifact `resolveArtifact`/`findArtifact`/`deleteAppCascade`); the plugin keeps the judgment (spec validation, choice/status resolution, `$parent`→bind translation, candidate selection).+diff --git a/plugins/model-apps/docs/app-builder-design.md b/plugins/model-apps/docs/app-builder-design.mdindex 8b657167d..1b7eb95f9 100644--- a/plugins/model-apps/docs/app-builder-design.md+++ b/plugins/model-apps/docs/app-builder-design.md@@ -11,7 +11,7 @@ The two design records the `/app-builder` engine cites, in one file. They were ppartial-apply mode built on top of Part I. Read it before touching that mode.Current status of shipped/pending capabilities lives in-[`app-builder-roadmap.md`](./app-builder-roadmap.md) — this file is the "why", the roadmap is the+[`app-builder-capabilities.md`](./app-builder-capabilities.md) — this file is the "why", the capabilities doc is the"what/where". Wiring and flow diagrams live in [`architecture.md`](./architecture.md).---@@ -27,8 +27,8 @@ Current status of shipped/pending capabilities lives in> when trimming (§16 and §17 were removed without shifting anything else, which is why the numbering> skips them).>-> **Current status of shipped/pending capabilities lives in [`app-builder-roadmap.md`](./app-builder-roadmap.md)**-> (the canonical roadmap), not here — this doc is the "why", the roadmap is the "what/where". The+> **Current status of shipped/pending capabilities lives in [`app-builder-capabilities.md`](./app-builder-capabilities.md)**+> (the canonical capability record), not here — this doc is the "why", the capabilities doc is the "what/where". The> `--changed-only` partial-apply mode built ON TOP of this staged flow has its own contract in> **Part II** below.>@@ -38,7 +38,7 @@ Current status of shipped/pending capabilities lives in## 1. Why> *This section is the original motivation (pre-implementation). All five problems below were-> addressed by the design that landed — see the roadmap for current status.*+> addressed by the design that landed — see the capabilities doc for current status.*The build engine is sound — spec-driven, idempotent, `create == edit`, a large regression suite, aparity oracle. But the **flow around it** had five concrete problems:@@ -542,7 +542,7 @@ four and additive-SKIPS the rest, which then incur sticky debt). The user-facingfast path re-uploads only the *changed* pages, so an unchanged page is never clobbered; a page you editin both the spec and Maker is overwritten by the spec (the intended deploy). Documented as a follow-up.-## Deferred to follow-ups (v1 does NOT implement; tracked in the roadmap)+## Deferred to follow-ups (v1 does NOT implement; tracked in the capabilities doc)Pre-mutation live page-content drift verifier; `expectedSitemap` population + pre/post sitemap projectionequality (sitemap fast shape unwired in v1); a `clearDebtMatching` production caller (v1 clears debt onlyvia teardown+rebuild); unifying `contentPath` confinement between hashing and the build; view/form/sitemap@@ -640,7 +640,7 @@ contract/deferred sections). 8. ✅ **Live regression PASSED** (a scratch enviroUPDATE, new measured deployedSha, verify 9/9, snapshot **re-blessed eligible**); (3) chart edit →`--apply --changed-only` → **full-build fallback**, verify 9/9, snapshot **INELIGIBLE** with sticky`chart-edit-not-convergent` + `uncertified-baseline` debt; (4) `teardown --apply` → app cascade removed,-snapshot **tombstoned then deleted** (0 leftovers). 9. ✅ Docs — design + roadmap + CHANGELOG + AGENTS.md.+snapshot **tombstoned then deleted** (0 leftovers). 9. ✅ Docs — design + capabilities + CHANGELOG + AGENTS.md.## Build-time notes (from the final Sol pass)- Live-absence verification covers the UNION of prior-snapshot identities, current spec, generateddiff --git a/plugins/model-apps/docs/app-builder-roadmap.md b/plugins/model-apps/docs/app-builder-roadmap.mddeleted file mode 100644index eb5c4592c..000000000--- a/plugins/model-apps/docs/app-builder-roadmap.md+++ /dev/null@@ -1,290 +0,0 @@-# app-builder — Roadmap--What the `/app-builder` skill can do today, what's still pending (grouped by phase), and what's-intentionally deferred (with the *why*). The build engine is `scripts/lib/sdk-build.js`; the App Spec-contract is [`../references/app-spec-schema.md`](../references/app-spec-schema.md); the wiring diagrams-are in [`architecture.md`](architecture.md).--**Status legend**-- ✅ **verified live** — built end-to-end on a real Dataverse env and torn down clean.-- 🧪 **tested** — has automated (unit / golden) coverage, not exercised on a live org.-- ⚠ **not live-verified** — plumbed through and unit-tested, awaiting a live shakeout.-------## ✅ Complete--### Authoring & build framework — ✅ verified live-- Interactive levelled authoring in the **main loop** — jobs-to-be-done first, then data model,- artifacts + page-intents, then access (env select, App Spec, lint gate, plan-mode approval).-- Deterministic, **idempotent** build engine — discovers via the SDK (`findTables`/`findColumns`/`fetchEntityMetadata`) and creates only what's missing; new / existing / mixed envs all work.-- **All Dataverse access via the vendored headless SDK**; metadata cached under `<app-folder>/.maker-workspace/` for reuse.-- Phase selection (`--only`/`--skip`/`--from`/`--to`), `[n/total]` narration, `BuildHalt` gate, dry-run by default, `--sample-data` / `--publish` opt-in.-- Bounded-concurrency for independent ops; one publish round-trip per entity + the app. `az`-token HttpClient with transient (429 / 5xx) retry.-- Guardrail lint (`spec-lint.js`) + hard validator (`app-spec.js`). 🧪 full `node:test` suite + the vendored SDK's Jest suite green (`node scripts/run-tests.js --with-sdk <ppux>`).--### Data model (Tier 1) — ✅ verified live-- All column types: Text · Memo · Choice · MultiChoice · Boolean · Money · DateTime · Integer · BigInt · Decimal · Double · File · Image · AutoNumber · Customer (with per-type options), incl. AutoNumber primary columns.-- Global option sets, status reasons (idempotent, deterministic pinned values), alternate keys (idempotent).-- Relationships: OneToMany (lookup) **and** ManyToMany; Customer (polymorphic) columns.-- Sample data: Choice/MultiChoice label→int resolution (inline **and** global choices), `$parent`/`$parents` lookup binds (incl. junction rows with both sides), custom status reasons; resolve-by-name idempotency via the SDK's `seedRecordGraph`.-- ⚠ Calculated / Rollup formula columns — `source` + `formula` plumbed through, **not live-verified**.-- **Table icons** (`entities[].vectorIcon` = SVG web resource → `IconVectorName`; `entities[].icon` = raster web resource → `IconMediumName`) — sets a custom table's own icon (what the modern designer + nav render). Applied after the web-resources phase via the SDK's `setEntityIcon`; hard-validated against declared web resources so an unresolvable value can't break the designer (glimmer). Live-verified: `IconVectorName` set to a published SVG web resource.--### Forms, views & charts — ✅ verified live-- Adaptive main forms (auto + explicit tabs/sections), related-record sub-grids (1:N **and** N:N), Notes/timeline section.-- Quick-create + quick-view forms (`forms[].formType`); quick-view **placement** on a host form via a lookup (`forms[].quickViews[]`).-- Form JS event handlers (`onload`/`onsave`/`onchange`) wired via web resources.-- Views with rich filters (`eq-userid`/`this-week`/`in`/`not-in`/… + Choice-label resolution); default Active/Inactive view **column enrichment** via the SDK's `enrichDefaultViews`.-- Choice-column charts.--### App shell & navigation — ✅ verified live-- App module + sitemap; **multi-area sitemaps** — every `appShell.areas[]` maps to its own `<Area>` (icon + groups + subareas; order follows array order). The app is **self-contained for export/import**: its **sitemap** is added to the solution (componenttype 62), and its **tile icon** is an in-solution web resource — `app.icon` (a declared image web resource) or a generated default SVG — never an arbitrary external/managed icon.-- Generative pages (**genpage-first**) for overview / dashboard surfaces — uploaded via `pac model genpage upload`; the SDK finalizes the sitemap with `GenPage` subareas.-- Dashboards (chart / list / iframe / webresource tiles) with **sitemap placement** (auto-pinned as an app component). Tiles render in a **multi-column grid** (2-wide) rather than one stacked full-width column.-- Modern command-bar buttons — functional **JS on-click** + static hidden/disabled, incl. **flyout / split-button menus**.-- Web resources (JS / HTML / CSS) shipped + added to the solution; idempotent (reuse by name).--### Generative-page management — three-authority, id-based — 🧪 tested-- **Three-authority page identity.** IDENTITY = durable `<app>_pagemanifest` (key→pageId map), outranked by the spec's own `pages[].pageId` for a downloaded (edit-snapshot) spec. EXISTENCE = env-wide `pac model genpage list` — decides create-vs-reuse for crash-safe convergence (`enumerateEnv`, no `--app-id`). MEMBERSHIP = the app's sitemap `GenPageId` set, read fail-closed via `fetchSitemap` (`scripts/lib/sitemap-pages.js`) — drives placement, download enumeration, and verify. All page matching is by id, never by display name.-- **Edit-snapshot `pageId`.** Download keeps each page's deployed `GenPageId` as `pages[].pageId` in the emitted spec. On rebuild, this highest-authority id is confirmed against EXISTENCE and reused — so a downloaded app (including Maker-added pages) rebuilds without creating duplicates.-- **Validation: every page must be sitemap-placed.** A `pages[]` entry absent from the `appShell` sitemap is rejected; navigation-only (headless) pages are not supported. A "detail" page is a normal sitemap page receiving input via `pageInput`.-- **Safety HALTs:** `pages-removed` (live page dropped from spec — re-add or `--allow-destructive` detaches the nav SubArea, page left deployed), `pages-shared-across-apps` (`--allow-destructive` does NOT bypass; detach in Maker), `pages-identity-conflict`, `pages-manifest-corrupt`, `pages-existence-failed`, `pages-sitemap-read-failed`, `pages-shared-check-failed`.-- **Verify and download** match by id with exact set-equality (EXISTENCE + MEMBERSHIP); a manifest-uncorrelatable page surfaces `unableToRun`.--### AI-first features — ✅ verified live-- `ai` block → `ai-features` phase: form-fill, NL search, NL charts, M365 Copilot, and per-table Copilot **row summaries** with tailored `GptDynamicPrompt-2` prompts (auto-selected candidate tables; skips lookup/config/junction + D365-owned incident/lead/opportunity).-- **Admin-gated**: preflights each setting (`RetrieveSetting`), skips/warns when off, never fails the build. NL grid search is **environment-gated** (`EnableNLGridSearch`), not per-app. Standalone reporter `scripts/ai-preflight.js`.--### 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 round-trip** too: 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. **Round-trip scope (not yet "complete"):** tables, sitemap/appShell, generative pages, dashboards, icons, 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 four 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.-- 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 name) and matching the sitemap's `DefaultDashboard` — so a value reused elsewhere can't produce a false pass. **Multi-area sitemaps** and the dashboard-subarea path were re-verified live (positive + negative).--### Teardown — ✅ verified live-- `teardown-model-app.js` deletes exactly what an App Spec declares, in dependency-safe order (app → dashboards → commands → forms → charts → views → relationships → AI row summaries → tables [children-first] → web-resources → global choices → solution). Forms/charts/views/relationships are removed **before** tables (a table delete doesn't reliably cascade cross-references); **web resources are removed AFTER tables** (a table's icon web resource is referenced by the table).-- **Classifier-safe** (every id resolved from a spec-declared name via an exact-match, entity-scoped filter), dry-run by default, best-effort continue, not-found aware, undeletable (system/managed) artifacts recorded as `skipped`. A **restricted system solution** (`Active`/`Default`/`Basic`) is skipped rather than attempted (Dataverse 400s any delete of one), so a downloaded spec that defaulted its solution to `Default` tears down cleanly. An already-gone relationship (Dataverse 400 *"…but 0 were found"*) is tolerated as deleted, like the table not-found case.--### Tooling & internals — ✅ verified live-- ASCII **form wireframe** preview (`preview-form.js`); phase-grouped build log with per-step status glyphs (`✓`/`⊘`/`✗`) + a closing summary.-- **SDK consolidation** — the SDK owns the Dataverse mechanics (`seedRecordGraph`, `enrichDefaultViews`, AI settings/row-summaries, artifact `resolveArtifact`/`findArtifact`/`deleteAppCascade`); the plugin keeps the judgment (spec validation, choice/status resolution, `$parent`→bind translation, candidate selection).-------## 🎯 MVP gaps--Assessed 2026-08-12. **9 of 10 core P0 _primitives_ are ✅ complete** — roles + JTBDs as first-class planning outputs,-data model + sample data, auto-number + dedup, Active/Inactive + authored views, main forms, charts,-gen-page landings, custom SVG sitemap icons, in-app agents (`ai.appFeatures` = formFill/nlSearch/nlChart),-Insight Card summaries (`ai.summaries`), and-the dedup/verify quality gates. The open MVP items:--- 🔲 **Wave 2 (header/navigation refresh) enabled by default** (P0) — set the app-module header/nav- refresh flag on new apps, and turn it on when editing an app that isn't on it yet. Not set today.-- ✅ **Roles + JTBD as first-class planning outputs** (P0) — the Level-(c) design flow now models- **personas** and their **jobs-to-be-done**: the author declares the entity access each job needs, the builder- unions it into one security role per persona, and the plan/preview surfaces the proposed roles for review. Built- on the SDK security surface (`createPersonaRole`). JTBD-driven view/summary/sitemap coherence (below) still builds- further on this.-- 🔲 **Default-on + coherence wiring** — the AI agents, Insight Card summaries, and (once added) Wave 2 exist as- primitives, but the SKILL flow must **enable them by default** and author **JTBD-quality** content (entity-specific- summary prompts, the _right_ view columns). A ✅ primitive is necessary but not sufficient for a coherent app.--Important, P1 (not MVP-gating; tracked here for visibility):-- ✅ **Security roles per persona** — `personas[]` authors one security role per persona,- sized from its jobs-to-be-done, and grants the app to each role so it **opens for non-admins**, not just sysadmins.- Idempotent + converging (replace-privileges), fail-closed on a foreign same-name role, torn down with the app.- **Column-level (field) security** and **access teams / hierarchy security** remain a tracked SDK- follow-up.-- 🔲 **Rich AI descriptions on every artifact** · **quick-find / relevance-search config** ·- **custom app theme + logo** (the `design` block styles gen pages, not the app theme).--P0.5 stretch (not built): **modern grid visualizations by default** (contingent on the SDK grid-customizer)-and **MCP server + Catalyst by default**.-------## 🔜 Pending — by phase--### Phase: Edit & lifecycle-- 🔲 **Delta / diff-based edit (full desired-state convergence)** — today the build is **additive**: it creates what's missing and reuses what exists, but does NOT re-apply an edit to an already-deployed artifact (changed column type, removed view column, edited form/command/dashboard) and never removes an artifact dropped from the spec. The converging edit path today is **teardown + rebuild-fresh**; `--verify` now catches unapplied edits via content checks (view column set, relationship + command existence) so divergence is loud, not silent. The future increment: spec-diff against the deployed app and apply only the *changed* delta (SDK `updateColumn`/`deleteColumn`/`updateTable`/`deleteRelationship`/`updateWebResource`, `fetchArtifact` snapshots, `diffArtifact`) instead of a full re-apply — driven by real edit-workflow usage. (Deliberately NOT a per-resource `managed`/`additive`/`reference` mode system: that's backward-compat machinery for a prod tool; this is pre-prod, so convergence-by-default is the likely direction when it lands.)-- 🔲 **Form events on existing forms** — fetch an existing form, add/replace handlers, publish (current wiring assumes a freshly built form).-- 🔲 **`--dry-run` diff view** — show the spec-vs-deployed delta before apply (precursor to delta-based edit).--### Phase: Governance & breadth (Tier 3)-- 🔲 **Business rules** (`businessRules[]`) — ⚠ org-gated + Power-Fx-flavored; build behind a capability flag (see Deferred).-- 🔲 **Standard system views** (All Records / Active / Inactive / Lookup / Associated) auto-generated per table.-- 🔲 **Security roles, environment variables, connection references.**-- 🔲 **Solution packaging** — `exportSolution` / `importSolution` for hand-off / source control (managed / unmanaged).--### Phase: Build engine & correctness-- ✅ **Global option-set find-by-name** — DONE. The vendored `createGlobalOptionSet` is now IDEMPOTENT (probe `GlobalOptionSetDefinitions(Name=…)` → REUSE the existing `MetadataId` instead of a duplicate-`Name` POST). `entity-provision.js` captures the returned id on a rebuild so a `globalChoice` column binds to it (`globalChoiceMetadataId`) instead of falling back to inline options; a genuine create failure now surfaces as a clean phase halt (previously ALL errors were swallowed). Locked by `vendor-sdk-smoke.test.js` (idempotent reuse, no duplicate POST) + `entity-provision.test.js`.-- 🔲 **Solution-component idempotency** — query existing solution components instead of assuming reused web resources are already present.-- 🔲 **Live-verify Calculated / Rollup** formula columns end-to-end.-- 🔲 **Publish granularity** — optionally publish web resources separately from entity customizations.-- 🔲 **Richer `BuildHalt` recovery** — skip-phase / retry-step / edit-spec-and-resume prompts.-- ✅ **Entity-subarea sitemap icons round-trip** — DONE. The sitemap writer no longer DROPS a custom- `vectorIcon` on an entity nav subarea, and validation no longer REJECTS a platform/OOB icon reference the- download itself wrote. New shared `isPlatformIconRef` (a value starting with `/` or `$webresource:` is a- platform reference the platform resolves directly, vs a bare declared-web-resource NAME): `checkIcon`- passes platform refs through (a bare NAME still must be a declared image WR); `subAreaJson` emits a valid- platform `vectorIcon` on ANY subarea incl. Entity (a bare Fluent token is still dropped — it breaks the- modern app-designer — but now with a `warnings[]` entry, not silently) and preserves icon paths VERBATIM- (case-sensitive; only bare names are lower-cased); `collectSitemap` skips platform-path icons. So- download→edit→rebuild on a real app with custom/OOB nav icons no longer fails validation or silently- loses the icon. Adversarially reviewed (Sol + Opus — Opus caught a residual area-icon case-corruption,- fixed); **live-verified** (entity-subarea `VectorIcon` lands in the deployed sitemap- XML; the reporter's exact OOB `…/CDSEntity` icon rebuilds `ok:true`; round-trip clean). **Follow-up- (now resolved — see below):** deploying a `/WebResources/<pub>/icons/x.svg` reference to a DIFFERENT env- originally rendered a broken icon (the WR was assumed pre-existing).-- ✅ **Custom nav-icon web resources are portable across environments** — DONE. Resolves the follow-up- above. A sitemap nav icon that references a custom image web resource **by path**- (`/WebResources/<pub>/icons/x.svg` or `$webresource:<name>`) previously round-tripped only the- *reference*, so a rebuild into a **fresh** env rendered a broken icon. Now **download re-declares** the- referenced web resource into `webResources[]` (base64 content) so the build recreates it cross-env —- gated to be safe: only a WR that is (a) **owned by this app** (name starts with the app's real publisher- prefix — see the identity round-trip below), (b) **custom** (unmanaged), and (c) an **image** type. A path- ref processed BEFORE bare names so an overlap keeps `external`; a **foreign-prefix / managed / OOB**- reference is left as a bare reference (recreating a foreign prefix on a fresh env would BuildHalt). A- re-declared entry is flagged **`external: true`**: the idempotent web-resources phase creates-if-missing /- reuses-if-present, and **teardown skips `external` WRs** (including the derived generated-icon/manifest- cleanup, which now honors a declared-name collision) so a shared publisher WR is never deleted (fail-safe,- mirrors `existing: true` on downloaded tables). An own-prefix icon that can't be captured (absent on- source, or read failure) is surfaced as a **download warning**; the build adds a non-blocking- **portability warning** for an own-prefix path-ref icon missing from `webResources[]`. Adversarially- re-reviewed across four rounds (Sol + Opus, high effort); full offline coverage (re-declare / skip-foreign- / skip-managed / overlap-external / unresolved + teardown-skip).-- ✅ **App identity round-trips by its real uniquename (no duplicate app on rebuild)** — DONE. A downloaded- spec captures the app module's **real, immutable** `uniquename` in `app.uniqueName`; `appUniqueName(spec)`- (the single identity chokepoint for build's existing-app `findArtifact` AND teardown's app resolution)- returns it verbatim instead of re-deriving `<publisherPrefix>_<appName>` from the **mutable display name**.- So **renaming** an app then rebuilding no longer misses the existing app and **creates a duplicate**. The- publisher prefix (which scopes safe-to-re-declare custom icons and recreates the app's own solution) is- derived from the app's **own** uniquename — parsed **before** the solution-recovery I/O (a failure can't- lose it) and validated as a real `<prefix>_<name>` shape — **not** from an arbitrary unmanaged solution- membership (an app can belong to several, under different publishers). `recoverAppSolution` returns only- the real solution uniquename (teardown container); the transient prefix-trust signal is stripped from the- persisted spec. This resolved 4 adversarial-review findings (3 High + 1 Medium, Sol); full offline- coverage (identity-over-rename, prefix-from-uniquename-not-solution, malformed-shape rejection).-- ✅ **Pre-existing duplicate page names don't block an unrelated build** — DONE. Two-layer, fail-closed:- (1) `validateAppSpec` scopes the case-insensitive page-name uniqueness rule to pages the run CREATES- (no `pageId`): a NEW collision is rejected (prevention), a collision purely among PRE-EXISTING pages- (all carry a deployed `pageId`) is a warning (tolerated) so a form-only edit on a downloaded app with- two identically-named pages still builds. (2) Because a spec `pageId` is only a CLAIM, the pages phase- re-checks after `reconcilePageIds`: if a tolerated dup-name group has any member whose id reconciles as- ABSENT (a stale snapshot — e.g. the page was deleted in Maker since download), the build would- re-materialize the duplicate, so it HALTs (`pages-duplicate-name-create`) BEFORE any write instead of- creating it and only failing verify after. The pages phase is otherwise id/key-matched (never- name-matched — `genpage-cli.js` `enumerateEnv` is id-keyed), so distinct-id same-name pages build fine.- `validateAppSpec` gained a `warnings[]` channel; `build-model-app.js` narrates + attaches them.- **Follow-up:** enforce name-uniqueness at `/genpage`-native page creation too (the app got into the- dupe state via non-app-builder tooling).-- ✅ **Same-named forms (Main/Quick View/Card) no longer block a form edit** — DONE. A Dataverse form name- is unique only per `(entity, type)`, so a table's auto-created Main (2), Quick View (6), and Card (11)- forms are commonly ALL named "Information". The build resolved a form by `(entity, name)` only, so a- name-only lookup matched multiple rows → the SDK's `AmbiguousArtifactError` → the fail-closed preflight- HALTED, blocking a `formType:"Main"` edit entirely (author had to hand-patch formxml by id). New shared- `resolveExistingFormId` scopes by TYPE (`FORM_TYPE_CODE` → `type eq <code>`) so a Main edit reconciles- ONLY the Main form; applied CONSISTENTLY across the form phase (`buildArtifact`), the preflight- `discoverOpDiffState`, the spec **verifier** (`verify-spec.js` no longer false-passes a Main when only a- same-named Quick View exists), and **teardown** (which previously deleted EVERY same-named match — a- data-loss risk on same-named Quick View / Card siblings; now deletes exactly the intended form, skips on- absent, halts on a residual collision). The residual `(entity, type, name)` collision errors with- actionable guidance; new optional **`forms[].formId`** pins the exact form (GUID-validated in- `validateAppSpec` + re-checked at resolve — the id is interpolated unquoted into an Edm.Guid filter — and- verified to match the target table, TYPE, AND name; a stale pin fails loud instead of minting duplicate- forms).- Quick-view form references are keyed by `(targetEntity, QuickView, name)` so same-named Quick View forms- on different entities — or a same-named Main on the target entity — don't cross-wire (build map,- `validateAppSpec`, `spec-lint`, and teardown dependency ordering all consistent); verify reuses- `resolveExistingFormId` for the same identity. `FORM_TYPE_CODE`/`FORM_GUID_RE` live in the shared- `app-spec.js`. `artifactIdentityQuery('form')` is also type-scoped. Reviewed adversarially across three- rounds (Sol — the name-only-identity flaw was pervasive; all High/Medium findings fixed). Live-repro- `zava_javavendor` (three "Information" forms) unblocked; **live-verified end-to-end** (build a- table → it gets 3 same-named "Information" forms → edit the Main without a halt → the edit lands on the- Main ONLY, Quick View/Card untouched → teardown resolves the Main type-scoped). Locked by resolver /- preflight / verify / teardown / validation unit tests. **Follow-up:** a quick-view control already- cross-wired by the OLD global-name bug is not auto-repaired on a rebuild (`hasQuickView` matches only the- lookup field, not the embedded form id) — a rare pre-existing-state edge that self-heals on teardown +- rebuild.-- ✅ **Env-wide appmodule pagination** — DONE. The vendored `queryRecords({ paginate:true })` now follows the OData `@odata.nextLink` to completion. The cross-app shared-page scan (`sitemap-pages.js` `fetchAppsForPages`) enumerates EVERY app instead of one ~5000-row page, so it no longer fails closed at the cap (`apps-truncated` removed). Fail-closed is preserved on: an enumeration throw, a pagination-abort (repeated-nextLink guard), AND an **empty** result (a live env always has ≥1 appmodule, so empty ⇒ a malformed/partial read ⇒ `apps-enumeration-empty` halt). Locked by `vendor-sdk-smoke.test.js` (paginate follows nextLink; rejects paginate+top / paginate+fetchXml) + `sitemap-pages.test.js`.-- ✅ **Paginate throw-on-malformed-page (SDK hardening)** — DONE. The vendored `queryRecords({ paginate:true })` now THROWS a `ConnectionError` (carrying the page URL + HTTP status) when a paginated page's `value` is not an array (missing/null/object — previously coerced to empty, silently dropping rows; a bare-string `value` was iterated char-by-char, fabricating single-char rows) or when `@odata.nextLink` is a truthy non-string. The single-page (non-paginate) path stays lenient; `queryAllRecords` inherits the guard by delegation. The cross-app scan's `fetchAppsForPages` try/catch catches this → fail-closed at the source (the plugin's empty-enumeration guard remains as defense-in-depth). Locked by `vendor-sdk-smoke.test.js` ("THROWS on a malformed page"); re-vendored from `cds-maker-sdk` hardening-3 (`f066a644`).-- 🔲 **Conditional `updateTable` (If-Match / skip-if-unchanged)** — the SDK's `updateTable` does an unconditional GET→PUT of the whole `EntityDefinitions` row (strips `@odata.etag`, no `If-Match`), so a concurrent Maker edit to another property of the SAME table in the GET→PUT window is last-writer-wins. This is pre-existing (icons/audit already use `updateTable`); the quick-create flag adds one more caller. Follow-ups: preserve the ETag + conditional PUT (retry/surface 412), and skip the PUT when the requested flag is already set (avoids a redundant write on every opted-in rebuild). Same class as the build's `requireSuccessfulPush` 412 posture for artifacts.--### Phase: Forms, views & data-load polish (from the 2026-07-15 V1↔V2 comparison review)-From a review comparing two generated Project Management apps plus a sample data-load. **Status 2026-07-27: all 8 addressed — the "Allow quick create" table flag (#8) now ships; auto-GENERATING the Quick Create form's field layout remains a follow-up (see below).** Severity as assessed in that review.-- ✅ **[High] Validate lookup binds; stop silent data-load lookup failures** — DONE. `validateAppSpec` now validates `$parents` (junction) the same as `$parent` and flags a `$parent`/`$parents.match` that resolves to no parent sample row (the bind would be dropped and the lookup left unset); `buildSeedGroup` THROWS (fail loud) on an unresolvable parent instead of silently skipping. Runs inside `runner.run` (clean phase failure). `app-spec.js` sampleData validation + `entity-provision.js` buildSeedGroup.-- ✅ **[Medium] Don't truncate parent lookups in default-view enrichment** — DONE. `defaultViewColumns` now reserves the parent-lookup slots up front and caps *scalar* columns at the remaining budget, then appends every lookup — so a lookup-heavy table never drops a parent link (`sdk-build.js`). Teardown's `{ includeLookups:false }` reset path unchanged.-- ✅ **[Medium] Normalize N:N relationship schema-name ordering** — DONE. `manyToManySchemaName` sorts the two entity logical names alphabetically before composing, so the N:N name is stable regardless of `entity1`/`entity2` declaration order (`app-spec.js`). 1:N keeps its semantic `referenced_referencing` order; explicit `schemaName` still wins.-- ✅ **[Medium] Resolve Choice values; lint sample data** — lint part DONE. `validateAppSpec` flags a Choice/MultiChoice sample value (per comma token for MultiChoice) that is not a declared option label; raw numeric option values still pass. (The live-metadata label→int *resolution* at load time is still spec-positional — tracked separately if cross-env option drift becomes a real problem.)-- ✅ **[Medium] Sub-grid placement + titling** — DONE. Each sub-grid now lands in its **own 1-column full-width section** (`subgridSectionIntent` + `firstColumnSectionsPointer`) instead of a half-width cell in a field section, and the title defaults to the child's `pluralName`→`displayName` (not the logical name), with `forms[].subgrids[].label` overriding (`sdk-build.js` forms phase).-- ✅ **[Medium] Handle the stock "Information" form** — DONE (opt-in). New `forms[].deactivateOtherMainForms` flag: when set, after promoting our form default the build deactivates every OTHER active main form on the entity (the stock Information form). OFF by default; gated to our own custom table; a flagged form must be the only Main form declared for its entity, and deactivation is skipped if the promote failed. Teardown's `restoreStockMainForm` reactivates a stock main form to ENABLE deletion — a delete-enabler, not a faithful restore of pre-build activation state (see the deferred follow-up below). `promoteDefaultForm` in `sdk-build.js`.-- ✅ **[Low–Med] Drop "Created On" from enriched default views** — DONE (already the SDK's behavior; now locked). Traced the vendored `enrichDefaultViews`: `updateElement('/columns')` is a REPLACE (not a union) and the view serializer reconciles the fetchxml+grid to exactly our column set (which never contains `createdon`), removing the stock Created On. Locked with a real-bundle regression test (`default-view-createdon.test.js`).-- ✅ **[Medium] Enable "Allow quick create" on key tables (#8, flag)** — DONE. The vendored `updateTable` now supports `quickCreateEnabled` (→ `IsQuickCreateEnabled`), so the build enables "Allow quick create" on a table when the spec opts in — either an explicit `entities[].quickCreate: true` OR an authored `formType: "QuickCreate"` form (auto-derived via `quickCreateEnabledFor`, so an authored Quick Create form is actually reachable from the inline "+ New"). Idempotent (applied to fresh AND reused tables). `entity-provision.js` data-model phase + `planFor` step; locked by `vendor-sdk-smoke.test.js` (PUT sends `IsQuickCreateEnabled`), `entity-provision.test.js`, `app-spec.test.js`, and eval #4. **Follow-up (open):** auto-GENERATE the Quick Create form's field layout (primary + required + parent lookups) for lookup-target / sub-grid-child tables so the maker doesn't hand-author it — the flag + a hand-authored `formType:"QuickCreate"` form work today; the auto-layout does not yet.-- ✅ **[Low–Med] Authored form column full width** — DONE (SDK safety net). hardening-3's `FormAdapter.normalizeColumn` defaults a synthesized (authored) column's `width` to `100%` when undefined, so a reconcile-added field can never emit invalid formxml ("required attribute 'width' is missing"). The plugin still sets width explicitly for exact control; locked by `hardening2-real-bundle.test.js` (a width-stripped authored column serializes `width="100%"`).--### Phase: Authoring intelligence-- 🔲 **Planner enrichment** — proactively propose the *full* surface (status model, dashboard, validation, default views, security), not just forms/views/charts.-- 🔲 **Form-JS scaffolding** — generate small, real onload/onchange handlers from intent (e.g. "warn when priority is High") instead of empty stubs.-- 🔲 **Spec templates** — domain starters (support desk, CRM, asset tracking) as one-shot scaffolds.--### Phase: Quality & docs-- ✅ **Security-role and jobs-to-be-done verification (2026-08-14)** — both **metadata-only**:- - **`verify` now proves what a persona role GRANTS, not just that it exists.** The `role` check- only asserted a row carrying the SDK marker, so a role built with the wrong access — or one whose- privilege write failed after the row landed — verified clean. The new `role-privileges` check- resolves each declared `(entity, access)` to its Dataverse `PrivilegeId` from the **same- metadata source the SDK writes against** and asserts the role holds it at **at least** the- declared depth. Deliberately a **subset** check (`lib/role-privileges.js` explains why equality- would false-fail on `appAccess` injection, max-scope union, and shared privileges), and- **fail-closed** on an unreadable role or table.- - **`surfaces[]` is no longer documentary.** `lib/surface-resolver.js` resolves every- `personas[].jobs[].surfaces[]` entry against the spec's own views/forms/pages/dashboards/tables- /sitemap titles; `spec-lint` **warns** when one matches nothing (a warning, not an error — a- surface may legitimately name an OOB artifact), and `verify` adds a `job-surface` rollup that- reports a *deployed* failure as the job it broke ("persona P can no longer do job J") rather- than only "view X is missing".-- ✅ **Sample-run UX fixes (2026-07-27, from a live Property-Listings build).**- - ✅ **#1 live build status.** A long build now writes `<workspace>/.maker-workspace/build-status.json` (a single-object snapshot — `state`/`steps`/`lastPhase`/`lastLabel` — overwritten every step) alongside the `build-log.jsonl` trace, and prints a `▸ live progress:` path at start. So a multi-minute build is observable even when the launching shell buffers stdout. SKILL.md now tells the agent to stream (Tee, not Select-Object) and read the status file.- - ✅ **#2 wireframes shown.** SKILL.md Phase-1 preview step now REQUIRES pasting the `preview-app.js`/`preview-form.js` wireframe output to the user (not summarizing "looks right") before the approval gate — the user must see the forms/sitemap/pages they approve.- - ✅ **#3 (foundation) track the diff.** After a successful full apply the CLI persists `last-applied.json`; a later dry-run prints `▸ Changed since last apply: <phases>` (pure `phase-diff.js`, stable-stringify deep-equal). **Still open (tracked below): actually running ONLY the changed phases on `--apply`.**- - ✅ **#5 auto-number reseed lint.** `spec-lint` now WARNS that sampleData for a table whose primary is auto-numbered with no single-column alternate key will DUPLICATE on every re-run (and blocks refreshing data with `--sample-data` on an edit) — nudging a natural alternate key.-- 🔄 **#3 execution / #7 — SAFE `--changed-only` partial apply (Preview; implemented + review-hardened + LIVE-VERIFIED).** Design **design-reviewed** + implementation **adversarially reviewed** all Critical/High fixed with tests + **live regression PASSED** (baseline→eligible, page edit→fast pages-only, chart edit→full fallback+debt, teardown→snapshot deleted). Canonical spec [`docs/app-builder-design.md`](./app-builder-design.md) (read its **v1 scope + contract**). Because the engine is ADDITIVE-not-convergent, the partial apply is **fail-closed**: identity-bound schema-3 snapshot (live orgId/env/app match, appId required), a durable eligibility state machine + sticky debt + teardown tombstone + generation-fenced CAS. **v1 wires ONE shape end-to-end — page-content re-upload**: `--apply --changed-only` after a FRESH baseline runs ONLY the pages phase for a `.tsx` byte edit (uploads just the changed keys — never clobbers an unchanged page — skips the sitemap finalize, records the measured deployed hash, re-blesses only when page verify passes); anything else falls back to a full build. Deliverables ①–⑨ ✅ (919 offline tests green + live regression). Off by default; opt in with `--changed-only`. **Follow-ups (deferred): pre-mutation live page-content drift verifier; view/sitemap/form fast submodes + `expectedSitemap` gating; `clearDebtMatching` production caller; unify `contentPath` confinement.**-- 🔲 **#4 page visual preview before deploy.** The generated `.tsx` is only structurally grep-checked; the user never *sees* the page (they hit the double-render live). Add a page preview/screenshot gate before the page is uploaded.-- 🔲 **#6 lifecycle status modeling.** The skill authored "Listing/Offer/Showing Status" as plain Choices, so the record `statecode` (Active/Inactive) is disconnected from business status (a "Sold" row is still an "active record", and `activeOnly` views need an extra Choice filter to compensate). Steer lifecycle fields toward Dataverse `statusReasons` (statecode/statuscode), which the App Spec already supports.-- 🔲 **#8 approval gate shows artifacts, not counts.** The plan gate presents a phase-count table; the user approves counts, not the reviewable data model / wireframes. Fold the wireframe (#2) + a data-model summary into the approval gate.-- 🔲 **app-builder eval fixtures** — the offline harness now has a `4-hardening` fixture + `ui` oracles that grade the 2026-07-15 fixes (default-view lookups #2 / no createdon #7, N:N ordering #3, sub-grid section+title #5, valid relational sample data #1/#4). Further spec→expected-plan/calls cases still welcome.-- 🔲 **Workspace reuse** — load `.maker-workspace/` metadata to skip re-discovery on iterative runs.-- 🔲 **Worked samples** — a Form-JS spec (web resource + onchange handler) and a dashboard spec in `samples/`.-- 🔲 **Refresh `authoring-flow.md`** Level (a) column-type list (still shows the pre-Tier-1 short list).-- 🔲 **KNOWN BEHAVIOR — an authored view named identically to a stock default view unions onto it.** An authored `views[]` entry whose name equals the Dataverse stock default ("Active/Inactive <PluralName>") is matched by `findArtifact('view', {name,entity})` and **reconciled (unioned) onto that stock default** rather than created as a new view. `reconcileView` (`sdk-build.js`) updates only `/columns`, so the authored **filters and sort are silently ignored** and the stock `createdon` is kept. Live-observed on `a scratch environment` (2026-07). **Mitigated:** `spec-lint` now WARNS when a view name matches the stock-default pattern (recommending a distinct name). **Still to decide (design call):** whether to also (a) fully reconcile a detected default view (columns + filters + sort) or (b) hard-reject the collision — deferred pending a decision; the warning makes it loud in the meantime.-- 🔲 **Review follow-ups deferred from the 2026-07-27 Sol PROD-readiness review (pre-prod-acceptable, documented here so they aren't lost).**- - **Existing old-style sub-grid migration.** `addSubgrids` is idempotent by relationship (`hasSubgrid`), so a rebuild does NOT move a sub-grid that a *previous, pre-#5 build* placed as a half-width cell into the new full-width section, nor re-apply a changed label/view. No deployed apps predate #5 (the skill is pre-prod and the edit path is teardown+rebuild-fresh), so there is nothing to migrate today; this is consistent with the documented additive-build limitation (edits aren't re-applied in place). Revisit if in-place convergence lands.- - **Self-referential / cyclic sample-data binds.** A sample row that `$parent`-binds to its own entity can't be seeded (the record-graph seeder resolves `@odata.bind` before the current group's ids exist). Not yet rejected at lint — needs SDK confirmation before a hard reject so a case the SDK *can* handle isn't blocked. Rare; document + revisit.- - **Choice wire-type normalization.** The lint catches typo labels, but a numeric STRING for a single Choice stays a string and a numeric VALUE for a MultiChoice stays an Int32 (which Dataverse rejects for the multi-select CSV). Related edge: a MultiChoice option **label that itself contains a comma** passes whole-label validation but is split on the comma at resolve time (`resolveChoiceValue`), so it mis-resolves. Authors are steered to plain labels, so these are narrow edges; normalize-or-reject is a follow-up.- - **Teardown activation-state restore.** `restoreStockMainForm` reactivates a stock main form to *enable deletion*, not to perfectly restore pre-build activation state (a form inactive before the build may be left active after teardown), and it runs for reused-table forms too. Acceptable for cleanup; a faithful save/restore is a follow-up.-- 🔲 **KNOWN ISSUE — /genpage vs /app-builder subagent-interaction contradiction** (design review F10): `/app-builder`'s SKILL says a `Task` subagent is headless (`AskUserQuestion`/plan-mode do not reach the user from inside one), while `/genpage` Phase 1 **mandates** `AskUserQuestion` + plan-mode *inside* the `genpage-planner` subagent (`skills/genpage/SKILL.md:92-124`, `agents/genpage-planner.md`). One is wrong about the host runtime. Portable fix: run interactive steps in the main loop and use the planner subagent only for headless prereq/auth/detection that returns data — align `/genpage` to `/app-builder`. Needs host-behavior confirmation before restructuring.-------## ⛔ Deferred / blocked--Intentionally punted (a real blocker, not just "not done yet"), with the *why*, so we don't-re-litigate. Two hard blockers dominate: **(A)** anything needing **Power Fx + a component library**-can't be authored headlessly; **(B)** **PCF control bindings** need **solution-import** delivery the-SDK doesn't package.--- 🔴 **PCF custom-control bindings** — the SDK emits correct formxml, but a plain `pushArtifact` strips the control `uniqueid`, so the binding persists **only via solution import** (export → unzip → patch `customizations.xml` → rezip → import). The SDK exposes no artifact→zip packaging, and it needs a pre-deployed control to bind to. **Unblock:** an SDK helper that packages a form artifact (with its `$meta.formxml`) into an importable solution zip.-- 🔴 **Conditional (rule-based) command visibility** — modern commands express this **only** as Power Fx (component-library bind) → blocker A. Static `hidden`/`disabled` **ships**.-- 🔴 **Power Fx command on-click** — same component-library blocker (A). **JavaScript** on-click **ships**.-- 🟡 **Titled command groups** — a titled group needs a parent command-bar row the adapter doesn't synthesize for from-scratch commands (re-confirmed live: Dataverse 400 "Group button must have parentappactionid"). Buttons emit as loose controls; **flyout / split-button menus do work**. **Unblock:** SDK synthesis of the parent group rows.-- 🟡 **Interactive (type 10) dashboards** — different formxml machinery (streams/tiles keyed by cell id); the tile generator targets Standard (type 0). **Unblock:** an interactive-dashboard tile generator.-- ⚠ **Business-rule validation** — org-gated on the available test orgs (missing the `*ProcessWithWfomJson` action) so it can't be live-verified here, and the modern path is Power-Fx-flavored. Build behind a capability flag once an org supports it.-- 🟡 **Explicit app-component re-pin on an app EDIT** — a NEW chart added to an ALREADY-DEPLOYED app on an edit rebuild is not re-pinned as an explicit app component: the SDK's generic surface can't add a missing `components` object to a fetched app (`setAppDefinition` was retired). Low impact — the chart is still added to the solution and shows on its table's chart pane; rebuild the app fresh, or surface the chart via a dashboard/sitemap subarea, if it must be an explicit component. **Unblock:** an SDK component-set API for a fetched app, or fetch populating `components`.-------## Notes for the next implementer-- New artifact types reuse the `buildArtifact(type, def)` helper (createArtifact → optional pre-push tweaks → pushArtifact → addSolutionComponent) plus a new `COMPONENT_TYPE` entry.-- Add a phase to `PHASES`, a `planFor` branch, a `spec-lint` / `app-spec` validation block, schema-doc + skill notes, and **both** a mock-SDK engine test **and** a `vendor-sdk-smoke` assertion against the real bundle.-- Rebundle the SDK (`node scripts/_vendor-build/build.js --sdk <ppux>`) only when pulling new SDK methods. See [`../AGENTS.md`](../AGENTS.md) → *Building & Testing*.diff --git a/plugins/model-apps/docs/architecture.md b/plugins/model-apps/docs/architecture.mdindex b5379ab83..c70d0ea82 100644--- a/plugins/model-apps/docs/architecture.md+++ b/plugins/model-apps/docs/architecture.md@@ -6,8 +6,8 @@ The **wiring / flow reference** for both skills, as one page of ASCII diagrams.stage of the other; document order is not a pipeline. For **per-component behavioral specs**, the canonical file tree, conventions, andbuild/test, see [`../AGENTS.md`](../AGENTS.md). The App Spec contract is[`../references/app-spec-schema.md`](../references/app-spec-schema.md); the app-builder skill is-[`../skills/app-builder/SKILL.md`](../skills/app-builder/SKILL.md); the roadmap/TODO is-[`app-builder-roadmap.md`](app-builder-roadmap.md).+[`../skills/app-builder/SKILL.md`](../skills/app-builder/SKILL.md); the capabilities doc/TODO is+[`app-builder-capabilities.md`](app-builder-capabilities.md).## /genpage — high-level flowdiff --git a/plugins/model-apps/references/app-spec-schema.md b/plugins/model-apps/references/app-spec-schema.mdindex cf9c231db..630e15069 100644--- a/plugins/model-apps/references/app-spec-schema.md+++ b/plugins/model-apps/references/app-spec-schema.md@@ -68,27 +68,67 @@ sample data (incl. multi-parent junction links + status reasons), and publish.**Omit it** and the build generates a simple default SVG icon **inside the solution** — eitherway the app never depends on an arbitrary external/managed icon (which would fail to import intoa new environment). The app's **sitemap** is also added to the solution automatically.+- **`app.newLook`** *(optional, default off)* — opt into the **modern ("new look") shell** for this app.+ Writes the per-app `NewLookAlwaysOn` setting, which Dataverse describes as enabling the new look and+ **hiding the user switch** — so the result is deterministic rather than a per-user preference. It is+ a *setting*, not an appmodule column: `navigationtype` is Single/Multi **session** and unrelated, and+ the other new-look definitions (`NewLookOptOut`, `NewLookModernExperienceOct2023`) both default to+ true and are user-facing toggles, so writing them would not give the author a dependable result.+ Scoped to the app **and** the solution, so it travels on export/import.+ **Best-effort:** this is a platform feature that rolls out by tenant. If the setting cannot be+ written the build still succeeds — the app is fully functional on the classic shell — but it warns+ and reports `created.newLook: false`, so a failure is never mistaken for success.+- **`app.headerNavigationRefresh`** *(optional)* — control the **Wave 2 header and+ navigation refresh** (public preview) for this app.+ **The platform default is ON, not off.** Verified against the real vendored bundle (offline, by+ capturing the writes a push issues): the SDK defaults the app artifact's+ `headerAndNavigationRefresh` to `true` and pushing a **new** app writes the setting to its ON value+ unprompted. So set this to `false` if you want the classic header and navigation — omitting it+ leaves whatever the platform chose, which for a new app is on.+ Both values are honoured: `true` writes ON, `false` actively writes OFF. Treating `false` as "do+ nothing" would silently leave the feature on for an author who asked for it off.+ This is a **different setting from `app.newLook`** and the two are independent: `newLook` writes+ `NewLookAlwaysOn` (the new-look shell), while this writes `HeaderAndNavigationRefresh` (the header+ and navigation redesign). Enabling one does **not** enable the other.+ Written through the SDK's dedicated API rather than a raw setting write, because the encoding is a+ trap: it is a Number **tri-state where ON is `'2'`, not `'1'`**, and writing `'1'` is *accepted by+ the API and then silently fails to enable the feature*. Delegating means the plugin cannot get it+ wrong.+ **Best-effort**, like `newLook`: a tenant without the setting definition still gets a fully working+ app, with a warning and `created.headerNavigationRefresh: "unknown"` — never a silent success, and+ never a claim about a value that was not written. On success+ `created.headerNavigationRefreshOutcome` records `created` / `updated` / `unchanged`.- **`app.uniqueName`** *(optional, download-emitted)* — the app module's **real, immutable** Dataverseuniquename (e.g. `crba3_supportdesk`). A **downloaded** spec carries it so a rebuild resolves the**existing** app by identity — even after you **rename** the display `app.name` — instead of creating a**duplicate** app. You normally never hand-author this: an authored create-fresh spec omits it, and thebuild derives the uniquename deterministically from `solution.publisherPrefix` + `app.name`.- **`languageCode`** *(optional)* — the [LCID](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-lcid/)- stamped on the Dataverse labels the **data-model phase** creates (table, column, choice, status- reason, relationship and alternate-key display names). It does **not** reach form, dashboard or- sitemap labels — those go through SDK serializers that hardcode 1033 with no caller override- ([#455](https://github.com/microsoft/power-platform-skills/issues/455)).+ stamped on the Dataverse labels the build creates: data-model labels (table, column, choice, status+ reason, relationship and alternate-key display names) **and** form, dashboard and sitemap labels.+ The serializers used to hardcode 1033 with no caller override+ ([#455](https://github.com/microsoft/power-platform-skills/issues/455)); they now take the+ authoring language, so a non-English build no longer produces translated columns next to English+ form labels.**Normally omit it**: the build reads the organization's base language(`organization.languagecode`) and uses that, which is always a language the org has provisioned.Set it only to deliberately author labels in a *different* provisioned language than the orgdefault; `--language-code <lcid>` overrides it for a single run.+ If the organization has **not** provisioned the LCID you pin, the build stops at the start of the+ data-model phase and lists the ones it does have — Dataverse would otherwise accept the table and+ Choice labels (silently storing them under the org's base language) and then reject the first+ `DateTime` or `Memo` column, leaving a half-built data model. The check is best-effort: if+ `RetrieveProvisionedLanguages` cannot be read, the build proceeds unchanged.Must be a positive integer LCID up to 65535 — `1031`, not `"de-DE"` and not `true`. An invalidvalue is rejected by validation, and a caller that bypasses validation gets a warning naming thediscarded value rather than a silent fall-through.- **Not emitted by `download-model-app.js`**, and that is deliberate: an LCID copied out of the- source org would be re-applied verbatim when the spec is rebuilt somewhere else, which is exactly- how a spec starts failing in an org that lacks that language. Leaving it absent lets every target- org resolve its own base language. If you pinned one by hand, re-add it after a download.+ **Emitted by `download-model-app.js` only if you pinned it yourself.** It is deliberately never+ read from Dataverse: an LCID copied out of the source org would be re-applied verbatim when the+ spec is rebuilt somewhere else, which is exactly how a spec starts failing in an org that lacks+ that language. Leaving it absent lets every target org resolve its own base language. But a value+ **you** wrote is carried across a download from the previous `app-spec.json` at that path, so a+ pin is not silently lost — losing it would leave newly created columns in the org default while+ the existing ones keep the pinned language, with no error anywhere.## entities[]```jsonc@@ -139,7 +179,9 @@ sample data (incl. multi-parent junction links + status reasons), and publish.// "primaryAttribute": { "schemaName": "new_ordernumber", "displayName": "Order Number", "autoNumberFormat": "WO-{SEQNUM:5}" },"columns": [{ "schemaName": "new_priority", "displayName": "Priority", "type": "Choice", "options": ["Low","High"] },- { "schemaName": "new_duedate", "displayName": "Due Date", "type": "DateTime" }+ { "schemaName": "new_duedate", "displayName": "Due Date", "type": "DateTime" },+ { "schemaName": "new_score", "displayName": "Score", "type": "Integer",+ "visualization": "RadialDial" } // optional — CUSTOM GRID RENDERING (preview), below]}```@@ -156,6 +198,34 @@ sample data (incl. multi-parent junction links + status reasons), and publish.- **AutoNumber** can also be the **primary** column — put `autoNumberFormat` on `primaryAttribute`(above) instead of adding a separate column, so the generated number is the record identity.+### `visualization` — custom grid rendering (optional, PREVIEW)++Renders the column's value as a small graphic instead of plain text, in **every grid and view that+shows the column** — it is per-*column* metadata, not per-view, so you set it once here rather than+on each `views[]` entry.++| Value | Renders as | Best for |+|---|---|---|+| `RadialDial` | circular gauge filled to a percentage | a number over a known range (0–100) |+| `LineChart` | sparkline across several points | a **text** column of comma-separated numbers |+| `HeatMap` | horizontal bar coloured by value | a single number, or a choice value |+| `StarRating` | row of stars filled to the value | a whole number (0–5 by default) |+| `None` | plain text | explicitly **clearing** a renderer |++- **Type-only.** The renderers use built-in defaults (dial 0–100, stars 0–5); there are no tuning+ parameters. Column-type compatibility is **not** validated — the pairings above are guidance, and+ the platform does not enforce a clean "numeric only" rule (`LineChart` is documented for a text+ column). A nonsensical pairing deploys and simply renders nothing useful.+- **Omitting is not the same as `None`.** An omitted column is left exactly as deployed; use+ `"None"` to actively clear a renderer set by an earlier build or by a maker in the portal.+- **Rebuild-safe.** The value is re-asserted on every build, including for columns that already+ exist, and converges to a single configuration row.+- **PREVIEW — not provisioned everywhere.** Where the platform has not enabled it, the build+ **skips** the visualization step (the column and everything else still deploy) and `verify`+ reports no divergence. Live-measured: the backing `controlconfigurations` table was present on+ only 1 of 18 test environments. If a renderer does not appear, check the environment first — the+ same spec succeeds unchanged on a provisioned org.+### entity sub-sections (optional)```jsonc"statusReasons": [ { "label": "In Review", "state": "Active" } ], // custom status values@@ -196,6 +266,7 @@ Reference from a column via `"globalChoice": "new_priority"` (built before the crecommended pattern for "Technician ↔ Work Order with a Role".## webResources[] (optional — client-side logic)+```jsonc[ { "name": "new_ticket.js", "displayName": "Ticket Scripts", "type": "js","content": "var Ticket={onLoad:function(ctx){},onPriority:function(ctx){}};" } ]@@ -205,6 +276,21 @@ Reference from a column via `"globalChoice": "new_priority"` (built before the c- Source comes from **one** of: `content` (inline text), `contentPath` (a file read relative to theapp folder at build time), or `contentBase64` (for binary types).- Built **before** forms and added to the solution; reference one from a form `events[]` handler.+- **Content edits are NOT applied on rebuild.** Like commands, the phase is discover-then-skip: a web+ resource that already exists is reused as-is, so changing `content` and rebuilding deploys nothing+ and the old script keeps running. Delete the web resource (or tear down) and rebuild to change it —+ note it cannot be deleted while a command or form handler still references it.+- **Never hardcode Choice (option-set) values in the script.** Values like `100000003` are assigned+ per publisher, so a literal that is correct in one environment silently selects nothing in another —+ and a `setValue` with an unknown value fails quietly. Resolve by label instead:+ ```js+ function setChoiceByLabel(formCtx, attr, label) {+ var a = formCtx.getAttribute(attr);+ var hit = (a.getOptions() || []).filter(function (o) { return o.text === label; })[0];+ if (hit) { a.setValue(hit.value); }+ return !!hit;+ }+ ```- **`external`** *(optional, download-emitted)* — set `true` on an entry that **download** re-declaredbecause a sitemap nav icon referenced a custom image web resource **by path** (see appShell iconsbelow). The build **creates it if missing, reuses it if present** (idempotent, no overwrite), so the@@ -302,7 +388,11 @@ Reference from a column via `"globalChoice": "new_priority"` (built before the c- **`events[]`** wire client-side JS: `event` is `onload`/`onsave`/`onchange` (`onchange` needs an`attribute`), `library` references a declared `webResources[]` name (lint-enforced), `function` isthe JS function. Optional `enabled` (default true), `passExecutionContext` (default true),- `parameters`. The build fetches the pushed form, injects the handlers, then publishes it.+ `parameters` (a comma-separated argument list). All three are **honoured** — an authored+ `"enabled": false` really does deploy a disabled handler. `enabled` and `passExecutionContext` must+ be booleans and `parameters` a string; a string `"false"` is rejected rather than coerced, because it+ is truthy in JS and would silently enable a handler you meant to disable.+ The build fetches the pushed form, injects the handlers, then publishes it.## commands[] (optional — modern command-bar buttons)```jsonc@@ -316,8 +406,24 @@ Reference from a column via `"globalChoice": "new_priority"` (built before the c{ "label": "Reject", "library": "new_order.js", "function": "Order.reject" } ] }```- A button's on-click calls `function` in the declared `library` web resource (both lint-enforced) —- this is what makes it **functional** (not a structural-only button). `parameters` (optional) passes a- raw arg string.+ this is what makes it **functional** (not a structural-only button).+- **Your function is handed the record automatically.** The build passes the standard command+ parameters for the button's location, so the usual handler shape works as written:+ ```js+ function escalate(primaryControl) {+ primaryControl.getAttribute('new_priority').setValue(100000003);+ primaryControl.data.save();+ }+ ```+ Defaults by location — `MainTab` → `PrimaryControl`; `ContextualTab` → `SelectedControl`;+ `HomeTab` → `SelectedControl` + `SelectedControlSelectedItemIds`. Override with `parameters`+ (a raw JSON string, e.g. `'[{"type":5,"value":null}]'`); pass `""` for a function that genuinely+ takes no arguments. **Without a parameter the function is invoked with no arguments**, so+ `primaryControl` is `undefined` and the button appears to do nothing — the error is visible only+ in the browser console, and the build, the deployed rows and `--verify` all still look correct.+- **Button edits are not applied on rebuild.** The command phase is discover-then-skip: it creates a+ bar only when none exists. To change a deployed button, delete the entity's commands (or tear down)+ and rebuild.- **`location`** is `MainTab` (default — the entity form/grid command bar), `HomeTab`, or `ContextualTab`.- **`hidden`** / **`disabled`** set *static* visibility/enablement. **Conditional (rule-based)visibility is not supported** — it's Power Fx-only on modern commands and needs a component library@@ -328,6 +434,42 @@ Reference from a column via `"globalChoice": "new_priority"` (built before the csupported (it needs a parent command-bar row the SDK doesn't synthesize from scratch). The commandlands in the Default solution but is entity-scoped, so it shows on the entity's command bar.+## businessRules[] (optional — declarative form logic, no code)++```jsonc+{ "entity": "new_ticket", "name": "Hide notes on closed tickets",+ "scope": "Entity", // only Entity today+ "status": "Active", // Active (default) | Draft — a Draft rule is deployed but inert+ "conditions": [ // ALL must hold (ANDed)+ { "field": "new_status", "operator": "Equals", "value": "100000001", "dataType": "Picklist" }+ ], "actions": [+ { "type": "SetVisibility", "field": "new_notes", "visible": false },+ { "type": "LockUnlock", "field": "new_owner", "lock": true },+ { "type": "SetBusinessRequired", "field": "new_reason", "required": true },+ { "type": "SetFieldValue", "field": "new_owner", "value": "unassigned" }+ ] }+```++- **Operators**: `Equals` · `DoesNotEqual`, and both must carry a `value`.+ `ContainsData` / `DoesNotContainData` are **rejected**: the SDK compiles them to XAML the platform+ answers with `HTTP 500 — Error generating UiData`, live-measured on every column type and in both+ directions, while the two comparison operators succeed in the same run. Tracked as+ [#481](https://github.com/microsoft/power-platform-skills/issues/481); to test presence, compare+ the field to the value you care about instead.+- **Actions**: `SetVisibility` (`visible`) · `LockUnlock` (`lock`) · `SetBusinessRequired`+ (`required`) · `SetFieldValue` (`value`). The three boolean payloads must be **real booleans** — a+ string `"false"` is truthy and would invert the intent, so it is rejected.+- **`dataType`** (optional, default `String`) is how the platform should read the literal:+ `String` · `Picklist` · `Boolean` · `Integer` · `Decimal` · `Money` · `DateTime` · `Memo`. For a+ Choice column use `Picklist` and give the option's **integer value**, not its label.+- Every `field` must be a column on the rule's own `entity` (its own columns, its primary name, or a+ lookup a relationship creates). A rule naming a column that does not exist is accepted by the+ platform and then simply **never fires**, so this is validated up front.+- Why this slice and not more: the vendored SDK compiles rules to classic workflow XAML, and these+ four actions plus four operators are what that compiler supports. Anything else throws mid-build.+- **Rebuild behaviour is additive** — a rule is matched by `(entity, name)` and reused if present;+ edits are **not** re-applied. Recreate the rule to change it.+## dashboards[] (optional — chart/list/iframe/web-resource tiles)```jsonc{ "name": "Operations", "tiles": [@@ -349,13 +491,34 @@ Reference from a column via `"globalChoice": "new_priority"` (built before the c"dataSources": ["new_order", "new_customer"],"source": { "kind": "intent" }, // design-time; generate-pages fills the .tsx"navigatesTo": [{ "targetKey": "detail", "data": { "orderId": "string" } }],- "pageInput": { "data": { "orderId": "string" } } } ]+ "pageInput": { "data": { "orderId": "string" } },+ "directEntry": { "behavior": "selector" } } ]// after generate-pages: "source": { "kind": "tsx", "codeFile": "overview.tsx" }```- **Genpage-first policy** is unchanged. A page's implementation state is an explicit discriminated`source`: `{ "kind": "intent" }` (declared but not yet coded) or `{ "kind": "tsx", "codeFile": "…" }`(the `.tsx` the build uploads). A **legacy** top-level `"codeFile"` (no `schemaVersion`) is stillaccepted and treated as an implemented tsx page.+- **`pageInput` + `directEntry` — the input contract.** These two rules used to conflict with no way+ for an author to satisfy both, so this spells out the resolution:+ - Every page **must** be a sitemap subarea (see the membership invariant below). The sitemap is the+ download's only membership oracle, so a page reached *only* by `navigatesTo` is invisible to+ download and gets re-created as a **duplicate** on the next build.+ - A detail page therefore lives in the app navigation, which means a user can open it **with no+ input at all** — the `orderId` its `pageInput` declares simply is not there.+ - So a page that declares `pageInput` must also declare **`directEntry`**, which is what that state+ renders: `{ "behavior": "selector" }` (show a picker, then the record) or+ `{ "behavior": "emptyState" }` (explain, and render nothing broken). An optional `note` is passed+ to the generator verbatim. Without this the generated page read `undefined` context on a path a+ user reaches by clicking the nav entry.+ - Every key in `pageInput.data` must be **produced by an incoming `navigatesTo[].data`** edge. An+ input nothing supplies is either a typo or a page that can only ever be entered directly; both+ generate a page reading a key no caller ever sets.++ The alternative — allowing navigation-only pages — was rejected: it would need the sitemap to stop+ being the membership oracle, and the duplicate-page bug it prevents is worse than the extra nav+ entry. `directEntry` also survives download (it is carried in the page manifest), because a spec+ that lost it would fail its own validation on the next build.- Validation is **profile-scoped**: `design`/`plan` accept intent pages; a `deploy` build (the default)requires every page implemented.- **`key`** (schemaVersion 2, required, unique) is the page's **single stable identity** — used bydiff --git a/plugins/model-apps/scripts/_vendor-build/build.js b/plugins/model-apps/scripts/_vendor-build/build.jsindex 8eafc8738..fd08fa66f 100644--- a/plugins/model-apps/scripts/_vendor-build/build.js+++ b/plugins/model-apps/scripts/_vendor-build/build.js@@ -3,6 +3,11 @@* or set POWER_PLATFORM_UX_SDK_ROOT=<path-to-ppux>* Not shipped. Re-run only when the SDK source changes.*+ * After rebuilding, run the vendored-SDK contract tests against the new bundle:+ * scripts/tests/{sdk-surface-contract,sdk-async-surface,hardening2-real-bundle,vendor-sdk-smoke}.test.js+ * sdk-async-surface is the one to read first: it pins which SDK methods are asynchronous, and an+ * upstream change to that set is both silent and corrupting (see that file's header).+ ** esbuild is pinned to an EXACT version in package.json (no `^`) on purpose. The stub plugin below* depends on esbuild's *internal* import-interop codegen (`__toESM` / `__copyProps`) — an* implementation detail with no compatibility guarantee, not a public API. That codegen does change@@ -27,6 +32,7 @@ if (!argSdk) {}const SDK_ENTRY = path.join(argSdk, 'packages/cds-maker-sdk/lib/index.js');const OUTFILE = path.resolve(__dirname, '../vendor/cds-maker-sdk.cjs');+const PROVENANCE = path.resolve(__dirname, '../vendor/PROVENANCE.json');const esbuild = require('esbuild');if (!fs.existsSync(SDK_ENTRY)) {@@ -34,6 +40,111 @@ if (!fs.existsSync(SDK_ENTRY)) {process.exit(2);}+/* Record WHICH upstream source produced the committed bundle.+ *+ * Without this the artifact is unreproducible in practice, and that is not hypothetical: the bundle+ * committed before this was built from a stale, gitignored `lib/` several commits behind its+ * nominal source, and nothing in the repo could reveal that. "Built from master" is not provenance —+ * master moves, and `lib/` is a build output that can be arbitrarily old relative to `src/`.+ *+ * So capture the resolved SHA, and flag a dirty or stale checkout rather than silently baking it in.+ * The `git` calls here are best-effort and record null on failure; the CALLER below decides what+ * that means, and it REFUSES unless --allow-unreproducible is passed, because a source that cannot+ * be identified cannot be audited.+ */+/* Strip merge-tool prefixes from an upstream commit subject before it is committed here.+ * See ./sanitize-subject.js for why, and why it lives in its own module. */+const { sanitizeSubject } = require('./sanitize-subject.js');++function sdkProvenance(root) {+ const git = (args) => {+ try {+ return require('node:child_process')+ .execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] })+ .trim();+ } catch {+ return null;+ }+ };+ const commit = git(['rev-parse', 'HEAD']);+ // `--porcelain` limited to the SDK package: unrelated dirt elsewhere in a large monorepo must not+ // be reported as "this bundle came from modified SDK sources".+ //+ // `null` means the git call FAILED (not a checkout, git missing, permissions) and is kept+ // distinct from `0`. Conflating "unknown" with "clean" is what makes a provenance record lie, so+ // the two are recorded differently and treated differently below.+ const dirtyRaw = git(['status', '--porcelain', '--', 'packages/cds-maker-sdk']);+ const entryMtime = fs.statSync(SDK_ENTRY).mtime.toISOString();+ // A `lib/` older than the newest `src/` file means tsc was not re-run — the exact stale-build trap.+ //+ // LIMIT, stated because it is not obvious: mtime is a heuristic, not proof. A fresh clone or a+ // `git checkout` rewrites source mtimes to NOW, so an already-correct `lib/` will look stale and+ // the build will refuse until the SDK is rebuilt. That is the SAFE direction — it costs one+ // rebuild and never ships an unverified artifact — but it does mean the check is conservative+ // rather than exact. It also cannot see a `lib/` that was copied in with a fresh mtime, so it+ // catches the accident (forgot to rebuild), not a determined mistake.+ let newestSrc = null;+ const srcDir = path.join(root, 'packages/cds-maker-sdk/src');+ const walk = (d) => {+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {+ const f = path.join(d, e.name);+ if (e.isDirectory()) walk(f);+ else if (e.name.endsWith('.ts')) {+ const m = fs.statSync(f).mtime;+ if (!newestSrc || m > newestSrc) newestSrc = m;+ }+ }+ };+ try { walk(srcDir); } catch { /* no src tree: an export-based build, nothing to compare */ }+ return {+ commit,+ subject: sanitizeSubject(git(['log', '-1', '--format=%s'])),+ // null = could not determine (see above); a number = that many modified paths.+ dirtySdkPackage: dirtyRaw === null ? null : dirtyRaw.split('\n').filter(Boolean).length,+ libBuiltAt: entryMtime,+ newestSrcAt: newestSrc ? newestSrc.toISOString() : null,+ libIsStale: !!(newestSrc && newestSrc > fs.statSync(SDK_ENTRY).mtime),+ // NOSTUB materially changes the OUTPUT (it disables the stub plugin, pulling the real shell/UI+ // packages into the bundle), so a record that omitted it could not explain a hash difference.+ nostub: !!process.env.NOSTUB,+ esbuildVersion: require('esbuild/package.json').version,+ nodeVersion: process.version,+ builtAt: new Date().toISOString(),+ };+}++const prov = sdkProvenance(argSdk);+if (prov.libIsStale) {+ console.error(`REFUSING: ${SDK_ENTRY} is OLDER than the newest .ts under packages/cds-maker-sdk/src`);+ console.error(` lib built : ${prov.libBuiltAt}`);+ console.error(` newest src : ${prov.newestSrcAt}`);+ console.error(' Rebuild the SDK (its own `build` script) before vendoring, or the bundle will not');+ console.error(' match the source it claims to come from. This exact trap shipped once already.');+ process.exit(3);+}+// A bundle whose inputs cannot be identified is not reproducible, and a reviewer has no way to tell+// that from one that is. So these FAIL rather than warn — `--allow-unreproducible` exists for the+// legitimate "I am iterating locally" case and records the fact in the provenance file.+const ALLOW_UNREPRODUCIBLE = process.argv.includes('--allow-unreproducible');+if (prov.commit === null && !ALLOW_UNREPRODUCIBLE) {+ console.error('REFUSING: could not read a commit from the SDK source tree.');+ console.error(' Without a commit the bundle cannot be reproduced or audited.');+ console.error(' Vendor from a git checkout, or pass --allow-unreproducible for a local experiment.');+ process.exit(4);+}+if (prov.dirtySdkPackage !== 0 && !ALLOW_UNREPRODUCIBLE) {+ const what = prov.dirtySdkPackage === null+ ? 'could not determine whether packages/cds-maker-sdk is clean'+ : `packages/cds-maker-sdk has ${prov.dirtySdkPackage} uncommitted change(s)`;+ console.error(`REFUSING: ${what}.`);+ console.error(` The bundle would NOT be reproducible from commit ${prov.commit || '(unknown)'}.`);+ console.error(' Commit the SDK changes first, or pass --allow-unreproducible for a local experiment.');+ process.exit(5);+}+if (ALLOW_UNREPRODUCIBLE) {+ console.warn('WARNING: --allow-unreproducible — this bundle must NOT be committed.');+}+// Transitive deps that are pulled in by the cds-* designer packages (which the headless SDK DOES// use for form/app/command serialization) but that are themselves pure UI / routing / telemetry /// localization infra never executed on our headless serialize/push path. They read browser globals@@ -137,7 +248,21 @@ esbuild}).then(() => {const kb = (fs.statSync(OUTFILE).size / 1024).toFixed(0);+ // Hash the artifact so a reviewer can tell two bundles apart without diffing 600KB of minified+ // output, and so a rebuild from the same inputs is checkable rather than assumed.+ // Hash the LF-NORMALISED content so the recorded value is platform-independent: git's+ // end-of-line normalisation would otherwise make the same commit hash differently on a Windows+ // checkout than on Linux. (vendor/.gitattributes also marks the bundle `-text`; this is the+ // belt to that pair of braces — either alone would do, and both together survive one being+ // dropped by accident.)+ const raw = fs.readFileSync(OUTFILE);+ const normalised = Buffer.from(raw.toString('utf8').replace(/\r\n/g, '\n'), 'utf8');+ const sha256 = require('node:crypto').createHash('sha256').update(normalised).digest('hex');+ fs.writeFileSync(PROVENANCE, `${JSON.stringify({ ...prov, allowUnreproducible: ALLOW_UNREPRODUCIBLE || undefined, bundleSha256: sha256, bundleBytes: normalised.length }, null, 2)}\n`);console.log(`BUNDLE OK -> ${OUTFILE} (${kb} KB)`);+ console.log(` sdk commit : ${prov.commit || '(not a git checkout)'}`);+ console.log(` sha256 : ${sha256}`);+ console.log(` provenance -> ${PROVENANCE}`);}).catch(() => {console.error('BUNDLE FAILED');diff --git a/plugins/model-apps/scripts/_vendor-build/sanitize-subject.js b/plugins/model-apps/scripts/_vendor-build/sanitize-subject.jsnew file mode 100644index 000000000..cc2b23a3e--- /dev/null+++ b/plugins/model-apps/scripts/_vendor-build/sanitize-subject.js@@ -0,0 +1,77 @@+/* Strip merge-tool prefixes from an upstream commit subject before it is recorded in+ * vendor/PROVENANCE.json.+ *+ * The SDK's history is squash-merged by a server-side tool that prepends its own PR id, e.g.+ * "Merged PR 12345678: feat(cds-maker-sdk): configurable authoring LCID, command bind fixes"+ * "Merge pull request #4312 from someone/some-branch"+ * (Both example ids here are synthetic. Quoting a real one would reintroduce exactly the identifier+ * this function exists to remove.)+ *+ * That id is unresolvable from THIS repository, and PROVENANCE.json is committed to a public one,+ * so the prefix is noise that also advertises a tracker nobody reading it can open. The part that+ * carries the "why" is the description after the prefix, so keep exactly that. The upstream SHA is+ * recorded separately and is the field that actually identifies the source.+ *+ * CONTRACT: the return value must NEVER match one of the prefix patterns below. That is stronger+ * than "strip a prefix" and is the property the committed-provenance test asserts. An earlier+ * version broke it — when stripping consumed the whole subject it returned the ORIGINAL, putting+ * the identifier straight back and emitting a value that failed that very test.+ *+ * Lives in its own module rather than inside build.js so it can be unit-tested: build.js is a CLI+ * that resolves its --sdk argument and calls process.exit at load time, so requiring it from a test+ * would terminate the test runner.+ */++// Only a LEADING, well-formed prefix is removed. Anchoring matters: a subject that merely mentions+// "merged PR 42" mid-sentence is prose, not a tool prefix, and must survive untouched.+//+// Each pattern ends with `(?::\s*|$)` — a colon OR end-of-string. Requiring the colon left a hole:+// `"Merged PR 123"` (prefix, no description, no colon) was returned UNCHANGED, and the property test+// could not see it because that test uses these same patterns as its oracle. Matching end-of-string+// too means a bare prefix is recognized and replaced by the placeholder.+//+// The alternation does NOT weaken the prose guard: `"Merged PR 99 rollback"` still fails to match,+// because after the digits the next thing must be a colon or the end, and `rollback` is neither.+const MERGE_PREFIXES = [+ // Azure DevOps / TFS squash-merge subject. `#` is optional: not every tool emits it.+ /^\s*Merged\s+PR\s+#?\d+\s*(?::\s*|$)/i,+ // GitHub merge-commit subject. `#` is optional for the same reason.+ //+ // The branch ref is `[^:\s]+`, NOT `\S+`. A greedy `\S+` swallows any colon in the ref AND the+ // one that ends it, so "…from owner/ref:fix(sdk): tolerate x" sanitized to just "tolerate x" —+ // silently deleting the part of the description that says what changed.+ /^\s*Merge\s+pull\s+request\s+#?\d+\s+from\s+[^:\s]+\s*(?::\s*|$)/i,+];++// Returned when a recognized prefix consumed the entire subject (GitHub puts the description on the+// body line, so a bare merge subject is all prefix). A neutral, resolvable-by-nobody string is the+// honest answer: it satisfies the contract above, and unlike an empty string it does not read as+// "provenance could not be determined", which is a different and more alarming claim.+const NO_DESCRIPTION = '(merge commit; upstream subject carried no description)';++function sanitizeSubject(subject) {+ if (typeof subject !== 'string') return subject;+ let out = subject;+ let matched = false;+ // Strip to a FIXED POINT, not a fixed NUMBER of passes. A single anchored `replace` removes one+ // prefix, so a merge of a merge kept the rest and returned a value that still matched a pattern.+ //+ // An earlier attempt capped this at 8 passes, which was worse than useless: it looked defensive+ // while silently reintroducing the same bug for any subject with 9 or more nested prefixes. The+ // cap is gone because the loop provably terminates without one — every pattern above must match at+ // least the literal `Merged PR` / `Merge pull request` plus a digit, so a successful replacement+ // strictly shortens the string and no pattern can match empty. `out === before` is therefore+ // reached in at most `subject.length + 1` passes (the +1 is the final unchanged pass that breaks).+ for (;;) {+ const before = out;+ for (const re of MERGE_PREFIXES) {+ if (re.test(out)) { matched = true; out = out.replace(re, ''); }+ }+ if (out === before) break;+ }+ out = out.trim();+ if (out) return out;+ return matched ? NO_DESCRIPTION : subject.trim();+}++module.exports = { sanitizeSubject, MERGE_PREFIXES, NO_DESCRIPTION };diff --git a/plugins/model-apps/scripts/ai-preflight.js b/plugins/model-apps/scripts/ai-preflight.jsindex 051f98d6f..7cea960af 100644--- a/plugins/model-apps/scripts/ai-preflight.js+++ b/plugins/model-apps/scripts/ai-preflight.js@@ -9,6 +9,7 @@const { parseArgs, emitResult } = require('./lib/dataverse-auth.js');const { createAzHttpClient } = require('./lib/sdk-http-client.js');+const { AI_APP_SETTING, resolveAppModuleId, effectiveSettingValue, settingIsOn } = require('./lib/ai-app-settings.js');const fs = require('node:fs');const os = require('node:os');const path = require('node:path');@@ -16,8 +17,15 @@ const path = require('node:path');// Human-readable label + admin-action hint for each feature key returned by getAiReadiness.const FEATURE_META = {formFill: {- label: 'Form fill',- action: (f) => `Enable "Form fill" (setting: ${f.setting}) in Power Platform Admin Center → Environments → Settings → Product → Features.`,+ // Deliberately NOT "Form fill". `FormFillBarUXEnabled` governs only the form fill assist+ // TOOLBAR — one capability of AI form fill assistance. The SDK's own type docs name three+ // siblings this flag does not touch: `FormFillFileUploadEnabled` (file upload),+ // `FormPredictSmartPasteEnabled` (smart paste) and `FormPredictEnabled` (edit-form+ // predictions). Labelling it "Form fill" overclaims in both directions — it reports a feature+ // as unavailable when a user may well have smart paste working, and it implies enabling it+ // turns the whole family on.+ label: 'Form fill assist toolbar',+ action: (f) => `Enable "Form fill assist toolbar" (setting: ${f.setting}) in Power Platform Admin Center → Environments → Settings → Product → Features. Note this is the toolbar only — smart paste (FormPredictSmartPasteEnabled), file upload (FormFillFileUploadEnabled) and edit-form predictions (FormPredictEnabled) are separate settings this does not enable.`,},nlSearch: {label: 'Natural language search',@@ -39,18 +47,38 @@ const FEATURE_META = {/*** Pure: given the getAiReadiness result, produce a structured preflight report.+ *+ * `effective` (optional) maps a feature key to `{ value, scope, on }` for that feature's PER-APP+ * setting, as resolved by `effectiveSettingValue`. It exists because the readiness gate and the+ * feature's actual setting are different rows: a gate can read false while the feature is switched+ * on at environment scope and therefore running in every app. Without this, the report tells an+ * operator to go and enable something that is already on.+ *+ * A feature that is IN EFFECT gets no admin action, because there is nothing for an admin to do.+ ** @param {{ formFill, nlSearch, nlChart, summaries, m365 }} readiness- * @returns {{ features: Array<{feature, enabled, setting}>, adminActions: string[] }}+ * @param {Record<string, {value?: string, scope?: string, on?: boolean, error?: string}>} [effective]+ * @returns {{ features: Array<{feature, enabled, setting, inEffect?, effectiveValue?, effectiveScope?}>, adminActions: string[] }}*/-function runPreflight(readiness) {+function runPreflight(readiness, effective = {}) {const features = [];const adminActions = [];for (const [key, meta] of Object.entries(FEATURE_META)) {const f = readiness[key];if (!f) continue;- features.push({ feature: key, enabled: f.enabled, setting: f.setting });- if (!f.enabled) {+ const eff = effective[key] || {};+ // Only a POSITIVE reading counts. `eff.error` (could not look, or the setting is not+ // provisioned here) must never be read as "in effect" — that would suppress a real admin action.+ const inEffect = eff.on === true;+ features.push({+ feature: key,+ enabled: f.enabled,+ setting: f.setting,+ ...(eff.value !== undefined ? { effectiveValue: eff.value, effectiveScope: eff.scope } : {}),+ ...(inEffect ? { inEffect: true } : {}),+ });+ if (!f.enabled && !inEffect) {adminActions.push(meta.action(f));}}@@ -83,12 +111,43 @@ async function main() {sdk.initWorkspace();const readinessOpts = app ? { appUniqueName: app } : {};const readiness = await sdk.getAiReadiness(readinessOpts);- report = runPreflight(readiness);++ // Resolve each feature's ACTUAL setting alongside the gate. The gate only decides whether a+ // build would write an app-scope override; the feature can already be switched on at+ // environment scope (or on by default), in which case reporting it as disabled — and telling an+ // admin to go enable it — is simply wrong. Best-effort: any lookup failure leaves the feature+ // reported from the gate alone, which is the previous behaviour.+ const read = { queryRecords: (entity, opts) => sdk.queryRecords(entity, opts) };+ // If `--app` was supplied but the app cannot be resolved, the app-scope layer is UNKNOWN, not+ // absent. Falling through to the environment value would be actively harmful: an app that+ // overrides a feature to "0" while the environment holds "2" would be reported as in effect,+ // and the admin action for a genuinely disabled feature would be suppressed. So a failed+ // resolution makes every effective value indeterminate instead.+ const appLookup = app ? await resolveAppModuleId(read, app) : { appModuleId: null };+ const appModuleId = appLookup.appModuleId || null;+ const effective = {};+ for (const key of Object.keys(FEATURE_META)) {+ const setting = AI_APP_SETTING[key];+ if (!setting) continue; // `summaries` is not a per-app on/off setting+ if (appLookup.error) { effective[key] = { error: `app scope unknown: ${appLookup.error}` }; continue; }+ const res = await effectiveSettingValue(read, appModuleId, setting);+ effective[key] = res.error ? { error: res.error } : { value: res.value, scope: res.scope, on: settingIsOn(res.value) };+ }+ if (appLookup.error) {+ process.stderr.write(`\nWarning: could not resolve app '${app}' (${appLookup.error}); reporting readiness gates only.\n`);+ }+ report = runPreflight(readiness, effective);process.stderr.write('\nAI Feature Readiness\n');process.stderr.write('====================\n');for (const f of report.features) {- process.stderr.write(` ${f.enabled ? '✓' : '✗'} ${FEATURE_META[f.feature]?.label || f.feature} (${f.setting})\n`);+ const label = FEATURE_META[f.feature]?.label || f.feature;+ if (f.inEffect && !f.enabled) {+ // The distinction that matters: running, but not because of anything this app declares.+ process.stderr.write(` ✓ ${label} (${f.setting}) — in effect via the ${f.effectiveScope} setting (value "${f.effectiveValue}"), though the readiness gate reads off\n`);+ } else {+ process.stderr.write(` ${f.enabled ? '✓' : '✗'} ${label} (${f.setting})\n`);+ }}if (report.adminActions.length) {process.stderr.write('\nAdmin actions required:\n');@@ -96,7 +155,7 @@ async function main() {process.stderr.write(` • ${a}\n`);}} else {- process.stderr.write('\nAll AI features are enabled.\n');+ process.stderr.write('\nAll AI features are available (enabled, or already in effect).\n');}} finally {// emitResult() calls process.exit(), so clean up the throwaway workspace BEFORE emitting.diff --git a/plugins/model-apps/scripts/build-model-app.js b/plugins/model-apps/scripts/build-model-app.jsindex aa4824d73..7455466d7 100644--- a/plugins/model-apps/scripts/build-model-app.js+++ b/plugins/model-apps/scripts/build-model-app.js@@ -16,8 +16,11 @@ const path = require('node:path');const { validateAppSpec, migrateAppSpec, normalizePageSource, normalizeLanguageCode } = require('./lib/app-spec.js');const { runSdkBuild, planFor, appUniqueName, compileFormIntent, resolveExistingFormId } = 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.+const { resolveAuthoringLanguage } = require('./lib/entity-provision.js');const { createAzHttpClient } = require('./lib/sdk-http-client.js');-const { parseArgs, readJsonArg, emitResult, dataverseRequest } = require('./lib/dataverse-auth.js');+const { parseArgs, readAliasedFlag, readJsonArg, emitResult, dataverseRequest, readProvisionedLanguages } = require('./lib/dataverse-auth.js');const { openJournal } = require('./lib/build-journal.js');const { diffPhases, summarizeDiff } = require('./lib/phase-diff.js');const { annotateContentHashes } = require('./lib/content-hash.js');@@ -39,7 +42,7 @@ const { makeGenpageCli } = require('./lib/genpage-cli.js');// (findTables/findColumns/fetchEntityMetadata) and every artifact// (views/charts/forms/app) lands here, so the app folder accumulates the// metadata for reuse/edits. Construction is offline (no token until first call).-function makeSdk(env, spec, workspaceDir) {+function makeSdk(env, spec, workspaceDir, languageCode) {const { createMakerSdk } = require('./vendor/cds-maker-sdk.cjs');const httpClient = createAzHttpClient(env);const sdkTempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'model-app-'));@@ -48,9 +51,21 @@ function makeSdk(env, spec, workspaceDir) {instanceUrl: env,httpClient,solutionUniqueName: spec.solution && spec.solution.uniqueName,+ // #455: the App, Form and Dashboard adapters bake this in at construction, so it is the ONLY+ // way to stop sitemap titles and FormXML labels being written at a hardcoded 1033. Omitted+ // (undefined) means the SDK's own DEFAULT_LCID, which preserves the previous behaviour exactly.+ ...(languageCode ? { languageCode } : {}),});fs.mkdirSync(workspaceDir, { recursive: true });- const provisionSdk = createMakerSdk({ workspacePath: workspaceDir, instanceUrl: env, httpClient });+ const provisionSdk = createMakerSdk({+ workspacePath: workspaceDir,+ instanceUrl: env,+ httpClient,+ // Must match the `sdk` instance above: `pushArtifact` refuses a push whose stored artifact+ // language disagrees with the SDK performing it (for language-sensitive registrations), so two+ // instances at different LCIDs would make every push of a fetched artifact fail.+ ...(languageCode ? { languageCode } : {}),+ });provisionSdk.initWorkspace();const cleanup = () => {fs.rmSync(sdkTempDir, { recursive: true, force: true });@@ -124,7 +139,7 @@ async function discoverOpDiffState(spec, provision) {const id = await resolveExistingFormId(provision, def);if (!id) continue; // not deployed yet → nothing to pruneawait provision.fetchArtifact('form', id); // seed the workspace copy so getArtifact can read it- forms.push({ label: `form "${f.name || f.entity}" (${String(f.entity).toLowerCase()})`, deployedForm: provision.getArtifact('form', id) || {}, def });+ forms.push({ label: `form "${f.name || f.entity}" (${String(f.entity).toLowerCase()})`, deployedForm: await provision.getArtifact('form', id) || {}, def });}// Sitemap removals only make sense when the app already exists (a fresh app has no deployed sitemap).let sitemap = null;@@ -132,7 +147,7 @@ async function discoverOpDiffState(spec, provision) {const appId = await provision.findArtifact('app', { uniqueName: collision.appUnique });if (appId) {await provision.fetchArtifact('app', appId);- const deployed = provision.getArtifact('app', appId) || {};+ const deployed = await provision.getArtifact('app', appId) || {};sitemap = { deployedTargets: sitemapTargets(deployed.siteMap || {}), wantTargets: sitemapTargets(spec.appShell) };}}@@ -265,6 +280,13 @@ async function buildModelApp(spec, opts, deps) {appDir: opts.appDir, // resolves web-resource `contentPath` relative to the app folderenv: opts.env, // for the pages phase (pac model genpage upload --environment)languageCode: opts.languageCode,+ // Forwarded explicitly because this is a fresh literal, not a spread of `opts`: without it+ // the data-model phase re-resolves, and on a transient org-read failure that fallback lands+ // on 1033 while the SDK is already baked at the resolved LCID — the exact split-language+ // build (translated FormXML, English columns) this threading exists to prevent.+ preResolvedLanguageCode: opts.preResolvedLanguageCode,+ // Injected so the pure lib stays free of transport. Only consulted for an EXPLICIT override.+ provisionedLanguages: deps.provisionedLanguages,warn: deps.warn,genpageCli: deps.genpageCli, // injectable seam for tests; else constructed from envworkspaceDir: opts.workspaceDir, // lease/staging live under the real workspace dir@@ -388,6 +410,10 @@ function list(v) {return typeof v === 'string' ? v.split(',').map((s) => s.trim()).filter(Boolean) : undefined;}+// Read the language flag from either spelling, rejecting a conflicting pair rather than silently+// preferring one.+const readLanguageFlag = (flags) => readAliasedFlag(flags, 'language-code', 'languageCode');+function parseLanguageCode(value) {if (value === undefined) return undefined;// Shares app-spec's normalizer so the CLI flag, the App Spec field and the resolver can never@@ -433,13 +459,30 @@ async function main() {const specPath = path.resolve(specArg.startsWith('@') ? specArg.slice(1) : specArg);const spec = migrateAppSpec(readJsonArg('@' + specPath));const workspaceDir = flags.workspace || path.join(path.dirname(specPath), '.maker-workspace');- const languageCode = parseLanguageCode(flags['language-code'] ?? flags.languageCode);+ const languageCode = parseLanguageCode(readLanguageFlag(flags));+ const phases = stagePhasesOrResolve({ stage: flags.stage, only: list(flags.only), skip: list(flags.skip), from: flags.from, to: flags.to });+ // Phases that stamp an authoring language onto something. `data-model` writes Dataverse label+ // objects; `forms`, `dashboards` and `app-shell` write FormXML `<labels>` and sitemap+ // `<Titles><Title LCID=…>` through the SDK, which since #455 takes the LCID as a construction+ // option. Anything else (views, pages, web-resources, publish, sample-data) creates no labels.+ //+ // This list must stay in step with what actually consumes the language. When it drifted before,+ // the warning told users the flag was ignored on `--stage ui` at the same time as the build was+ // faithfully applying it — worse than no warning, because it stops them investigating.+ const LANGUAGE_CONSUMING_PHASES = ['data-model', 'forms', 'dashboards', 'app-shell'];+ // A selector that excludes ALL of them makes the flag a genuine no-op. Say so rather than accept+ // it silently: a user who passed --language-code believes their labels are being pinned, and+ // finding out otherwise means re-running the whole build.+ if (languageCode !== undefined && Array.isArray(phases) && phases.length+ && !phases.some((p) => LANGUAGE_CONSUMING_PHASES.includes(p))) {+ process.stderr.write(`⚠ --language-code ${languageCode} has no effect for the selected phases (${phases.join('·')}) — none of them create labels (${LANGUAGE_CONSUMING_PHASES.join(', ')} do).\n`);+ }const opts = {apply: flags.apply === true,sampleData: flags['sample-data'] === true,publish: flags.publish === true,verify: flags.verify === true,- phases: stagePhasesOrResolve({ stage: flags.stage, only: list(flags.only), skip: list(flags.skip), from: flags.from, to: flags.to }),+ phases,profile: (flags.apply === true && flags.stage !== 'data') ? 'deploy' : 'plan',allowDestructive: flags['allow-destructive'] === true,nonInteractive: flags['non-interactive'] === true || envTruthy(process.env.POWER_PLATFORM_SKILLS_NONINTERACTIVE),@@ -448,9 +491,29 @@ async function main() {env,workspaceDir,};+ // #455: the App, Form and Dashboard adapters bake the authoring LCID in at CONSTRUCTION, so it+ // has to be resolved before the SDK exists — which is why this reads over the transport hatch+ // rather than through `provision.queryRecords`. Resolving here also means the provisioned-language+ // halt fires once, before anything is constructed or written. Dry runs skip it: they perform no+ // writes, and a language read is a round trip a plan does not need.+ //+ // Resolution is best-effort in its *fallback* direction: an unreadable organization language, a+ // failed probe, or a missing value all degrade to the 1033 default with a warning rather than+ // failing the build. It is deliberately NOT best-effort in one direction — an EXPLICIT+ // `--language-code` / spec `languageCode` that the organization has not provisioned halts here+ // (#456), before the SDK is constructed and before any label is written. That halt is the point:+ // Dataverse would otherwise accept some labels under the wrong language and reject others+ // mid-build, phases away from the flag that caused it.+ const authoringLanguageCode = opts.apply+ ? await resolveAuthoringLanguage({ envUrl: env, languageCode, spec, warn: (m) => process.stderr.write(`⚠ ${m}\n`) })+ : undefined;+ // Reuse the SAME resolved value for the data-model phase instead of repeating the org read and the+ // provisioned-languages probe. A disagreement between the two would label columns in one language+ // and FormXML/sitemap titles in another — assigned after resolution because `opts` is built above.+ opts.preResolvedLanguageCode = authoringLanguageCode;// Construct for both dry-run and apply: proves the vendored bundle + adapter wire up// (offline), and apply needs it. A spec validation error short-circuits before any write.- const { sdk, provisionSdk, httpClient, cleanup } = makeSdk(env, spec, workspaceDir);+ const { sdk, provisionSdk, httpClient, cleanup } = makeSdk(env, spec, workspaceDir, authoringLanguageCode);// Durable build journal (apply runs only): a per-run record of steps + where a run halted,// written to <workspace>/build-log.jsonl. Resume = re-run the same command (idempotent).const journal = opts.apply@@ -464,7 +527,7 @@ async function main() {}// #3 (track the diff): on a DRY-RUN, if a prior apply left a snapshot, report which phases changed// since — so a small edit is visibly "only pages changed", not a re-read of the whole plan. Advisory- // only (it does not yet gate --apply; see docs/app-builder-roadmap.md). Never fatal.+ // only (it does not yet gate --apply; see docs/app-builder-capabilities.md). Never fatal.const lastAppliedPath = path.join(workspaceDir, 'last-applied.json');// #2 (content-aware diff): resolve a page codeFile / web-resource contentPath the SAME way the build// engine does — relative to the app folder (opts.appDir) — and return its bytes, or null when it can't@@ -511,6 +574,9 @@ async function main() {// clean PASS having never checked what any persona's role actually grants. Caught live —// standalone verify ran 10 checks against the same app where the build's inline verify ran 8.verify: (s) => verifySpec(s, readerFor(provisionSdk, appUniqueName(s), { genpageCli: makeGenpageCli(env), workspaceDir, httpClient, envUrl: env })),+ // The set of LCIDs this organization actually has. Injected so the pure lib stays free of+ // transport, and only consulted for an EXPLICIT `--language-code` / spec `languageCode`.+ provisionedLanguages: () => readProvisionedLanguages(env),};if (changedOnly && opts.apply) {// #changed-only: the flow decides fast (pages-only via the sdk-build seams) vs full, gated on thediff --git a/plugins/model-apps/scripts/download-model-app.js b/plugins/model-apps/scripts/download-model-app.jsindex 7f3693cc1..00c6ded79 100644--- a/plugins/model-apps/scripts/download-model-app.js+++ b/plugins/model-apps/scripts/download-model-app.js@@ -17,7 +17,7 @@ const { parseManifestBase64, manifestResourceName, reconcilePageIds } = require(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 } = require('./lib/app-spec.js');+const { isPlatformIconRef, webResourceNameFromRef, validateAppSpec, normalizeLanguageCode } = require('./lib/app-spec.js');// webresourcetype (int) -> app-spec web-resource type.const WR_TYPE = { 1: 'html', 2: 'css', 3: 'js', 4: 'xml', 5: 'png', 6: 'jpg', 7: 'gif', 8: 'xap', 9: 'xsl', 10: 'ico', 11: 'svg', 12: 'resx' };@@ -26,7 +26,12 @@ const WR_TYPE = { 1: 'html', 2: 'css', 3: 'js', 4: 'xml', 5: 'png', 6: 'jpg', 7:// dashboards[] entries. Each tile is reconstructed with ID PASSTHROUGH — it carries the deployed// view/chart ids (+ target entity) directly, so a rebuild recreates the dashboard against the// EXISTING views/charts without needing views[]/charts[] declared (which would else duplicate them).-async function readDashboards(sdk, app) {+// `warn` is optional and injected so the CLI can report WHY a dashboard could not be reconstructed.+// Without it this function swallowed every per-dashboard failure (`catch { continue }`) and returned+// a short list, so the subarea silently dropped and download failed downstream with "could not be+// round-tripped" and no cause. That is a diagnosis dead-end: live, the real reason was an SDK+// deserialization bug several layers down, and nothing surfaced it.+async function readDashboards(sdk, app, warn) {const strip = (g) => String(g || '').replace(/[{}]/g, '') || undefined;const ids = new Map(); // dashboardId -> subarea title (fallback name)for (const a of (app.siteMap && app.siteMap.areas) || []) {@@ -39,7 +44,12 @@ async function readDashboards(sdk, app) {const out = [];for (const [id, title] of ids) {let art;- try { art = await sdk.fetchArtifact('dashboard', id); } catch { continue; }+ // Keep going on a single unreadable dashboard — one bad artifact must not sink the whole+ // download — but SAY SO. A dropped subarea with no stated cause is what made this untraceable.+ try { art = await sdk.fetchArtifact('dashboard', id); } catch (e) {+ if (typeof warn === 'function') warn(`dashboard '${title || id}' (${id}) could not be read: ${e && e.message}`);+ continue;+ }let name = title || id;try { const rows = await sdk.queryRecords('systemform', { select: ['name'], filter: `formid eq ${id}`, top: 1 }); if (rows && rows[0] && rows[0].name) name = rows[0].name; } catch { /* keep fallback */ }const tiles = [];@@ -52,7 +62,13 @@ async function readDashboards(sdk, app) {else if (c.type === 'iframe' && p.Url) tiles.push({ type: 'iframe', name: c.name, url: p.Url });else if (c.type === 'webresource' && p.WebResourceName) tiles.push({ type: 'webresource', name: c.name, webResource: p.WebResourceName });}+ // A dashboard that read cleanly but yielded no usable tile is ALSO a silent drop — the subarea+ // disappears with nothing said. Distinguish it from the unreadable case above.if (tiles.length) out.push({ id, name, tiles });+ else if (typeof warn === 'function') {+ warn(`dashboard '${name}' (${id}) read OK but produced no recognizable tiles `+ + `(${(art.components || []).length} component(s)); its sitemap subarea will be dropped.`);+ }}return out;}@@ -730,8 +746,15 @@ async function runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLos// Dashboards (declared as DashBoard sitemap subareas) — reconstructed with id-passthrough tiles.let dashboards = [];let dashboardReconstructionError = null;+ // Per-dashboard failures are collected rather than swallowed. They are the usual cause of a+ // "subarea could not be round-tripped" error further down, and without them that error names the+ // subarea but not the reason, which makes it undiagnosable without a debugger.+ const dashboardWarnings = [];try {- dashboards = await readDashboards(sdk, app);+ dashboards = await readDashboards(sdk, app, (m) => {+ dashboardWarnings.push(m);+ process.stderr.write(`WARNING: ${m}\n`);+ });} catch (e) {dashboardReconstructionError = e.message;process.stderr.write(`(dashboards reconstruction skipped: ${e.message})\n`);@@ -753,7 +776,7 @@ async function runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLosconst spec = await hydrateSpec(read);const droppedSubareas = typeof spec.droppedSubareas === 'number' ? spec.droppedSubareas : droppedSubareaCount(app, spec);const droppedSubareaDetails = Array.isArray(spec.droppedSubareaDetails) ? spec.droppedSubareaDetails : [];- return { ok: true, spec, pages, entities, webResources, droppedSubareas, droppedSubareaDetails, dashboardReconstructionError };+ return { ok: true, spec, pages, entities, webResources, droppedSubareas, droppedSubareaDetails, dashboardReconstructionError, dashboardWarnings };}async function main() {@@ -789,32 +812,87 @@ async function main() {const result = await runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLossy: allowLossyDownload });if (!result.ok) { emitResult(false, result); return; }- const { spec, pages, entities, webResources, droppedSubareas, droppedSubareaDetails, dashboardReconstructionError } = result;+ const { spec, pages, entities, webResources, droppedSubareas, droppedSubareaDetails, dashboardReconstructionError, dashboardWarnings } = result;if (droppedSubareas > 0 || dashboardReconstructionError) {const droppedList = (droppedSubareaDetails || []).map((d) => `${d.type}${d.id ? `:${d.id}` : ''}${d.title ? ` (${d.title})` : ''}`).join(', ');const dashboardMessage = dashboardReconstructionError ? ` Dashboard reconstruction failed: ${dashboardReconstructionError}.` : '';- const message = `${droppedSubareas} sitemap subarea(s) could not be round-tripped${droppedList ? `: ${droppedList}` : ''}.${dashboardMessage} A rebuild from this spec will DROP them from the app nav.`;+ // Per-dashboard reasons, when there are any. Naming the subarea without saying WHY it dropped+ // sends the reader looking at their sitemap when the cause is an unreadable artifact.+ const causeMessage = (dashboardWarnings && dashboardWarnings.length)+ ? ` Cause: ${dashboardWarnings.join('; ')}.`+ : '';+ const message = `${droppedSubareas} sitemap subarea(s) could not be round-tripped${droppedList ? `: ${droppedList}` : ''}.${dashboardMessage}${causeMessage} A rebuild from this spec will DROP them from the app nav.`;if (!allowLossyDownload) {process.stderr.write(`ERROR: ${message}\nPass --allow-lossy-download to write the partial spec anyway.\n`);- emitResult(false, { ok: false, error: message, droppedSubareas, droppedSubareaDetails, dashboardReconstructionError });+ emitResult(false, { ok: false, error: message, droppedSubareas, droppedSubareaDetails, dashboardReconstructionError, ...(dashboardWarnings && dashboardWarnings.length ? { dashboardWarnings } : {}) });return;}process.stderr.write(`WARNING: ${message}\n`);}- const validation = validateAppSpec(spec, { profile: 'plan' });+ // `reconstructed: true` — this spec was rebuilt from a DEPLOYED app, not authored. Authoring-only+ // rules become warnings, because refusing to write a description of an app that already exists+ // leaves the author with no artifact at all (see the pageInput producer rule).+ const validation = validateAppSpec(spec, { profile: 'plan', reconstructed: true });if (!validation.ok) {emitResult(false, { ok: false, error: 'downloaded App Spec failed validation', errors: validation.errors });return;}+ for (const w of validation.warnings || []) process.stderr.write(`WARNING: ${w}\n`);+ // A defaulted `directEntry` must not be silent. hydrateSpec injects a conservative `emptyState` for+ // pages that predate the field (otherwise this download would have hard-failed above and written no+ // spec at all), but the author has to know a behaviour was chosen for them so they can change it.+ const defaulted = spec.directEntryDefaulted || [];+ if (defaulted.length) {+ process.stderr.write(+ `WARNING: ${defaulted.length} page(s) declare pageInput but predate directEntry — defaulted to `+ + `{ "behavior": "emptyState" }: ${defaulted.join(', ')}.\n`+ + ' Review each: change to "selector" if opening the page from the navigation should show a record picker.\n'+ );+ }const specPath = path.join(outDir, 'app-spec.json');+ preserveAuthoredLanguageCode(spec, specPath);fs.writeFileSync(specPath, JSON.stringify(spec, null, 2));- emitResult(true, { ok: true, spec: specPath, pages: pages.length, entities: entities.length, webResources: webResources.length, droppedSubareas });+ emitResult(true, { ok: true, spec: specPath, pages: pages.length, entities: entities.length, webResources: webResources.length, droppedSubareas, ...(defaulted.length ? { directEntryDefaulted: defaulted } : {}) });+}++// Carry an AUTHOR-PINNED `languageCode` across a download, and only from the spec already on disk.+//+// Download deliberately does not read `languageCode` from Dataverse. An LCID copied out of the source+// org would be re-applied verbatim when the spec is rebuilt somewhere else, which is exactly how a+// spec starts failing in an org that has not provisioned that language (#447) — leaving it absent lets+// every target org resolve its own base language, which is the right default.+//+// But silently dropping a value the author WROTE is its own bug, and a quiet one: the next build+// resolves the org default, so newly created columns get one language while the ones from the pinned+// build keep another. A mixed-language app, no error anywhere. So the value is restored from the+// previous spec at this path — the author's own file — and never synthesized from the environment.+//+// Best-effort by design: a missing, unreadable or malformed previous spec just means there is nothing+// to preserve. Failing the download over it would be worse than the wart this fixes. Only a value that+// would itself pass validation is restored — carrying a broken one forward would fail the next build+// for a reason the operator did not cause on this run.+// Exported for tests.+function preserveAuthoredLanguageCode(spec, specPath, deps = {}) {+ const readFileSync = deps.readFileSync || fs.readFileSync;+ const existsSync = deps.existsSync || fs.existsSync;+ if (!spec || spec.languageCode !== undefined) return spec;+ try {+ if (!existsSync(specPath)) return spec;+ const prior = JSON.parse(readFileSync(specPath, 'utf8'));+ // Assign the NORMALIZED value, not the raw one. `"1031"` and `" 1031 "` both validate, but a+ // downloaded spec is a generated artifact and should be canonical — writing the author's+ // whitespace or string form back out makes the file's diff noisy and its type inconsistent with+ // every other numeric field the download emits.+ const lcid = prior ? normalizeLanguageCode(prior.languageCode) : null;+ if (lcid !== null) spec.languageCode = lcid;+ } catch { /* no previous spec, or not parseable — nothing to preserve */ }+ return spec;}if (require.main === module) {main().catch((err) => emitResult(false, err));}-module.exports = { resolveAppId, collectSitemap, appComponentEntities, parseDownloadedPages, assignPageKeys, missingDownloads, entityFromMetadata, iconWebResources, readDashboards, droppedSubareaCount, recoverAppSolution, runDownload };+module.exports = { resolveAppId, collectSitemap, appComponentEntities, parseDownloadedPages, assignPageKeys, missingDownloads, entityFromMetadata, iconWebResources, readDashboards, droppedSubareaCount, recoverAppSolution, runDownload, preserveAuthoredLanguageCode };diff --git a/plugins/model-apps/scripts/lib/ai-app-settings.js b/plugins/model-apps/scripts/lib/ai-app-settings.jsindex ad3f1503e..4b170e911 100644--- a/plugins/model-apps/scripts/lib/ai-app-settings.js+++ b/plugins/model-apps/scripts/lib/ai-app-settings.js@@ -24,6 +24,12 @@ const { odataLit } = require('./odata.js');// Keep in sync with the vendored SDK; `sdk-surface-contract.test.js` guards the method surface and// `verify-spec.test.js` pins these names.const AI_APP_SETTING = {+ // `FormFillBarUXEnabled` is the form fill assist TOOLBAR only — one capability of AI form fill+ // assistance, per the SDK's own type docs. Three siblings are NOT covered by this flag and are not+ // exposed by the App Spec: `FormFillFileUploadEnabled` (file upload),+ // `FormPredictSmartPasteEnabled` (smart paste) and `FormPredictEnabled` (edit-form predictions).+ // Do not silently repoint this key at a sibling — exposing those is a feature (new keys plus live+ // verification), not a rename.formFill: 'FormFillBarUXEnabled',nlSearch: 'NLGridSearchSetting',nlChart: 'NLChartDataVisualizationSetting',@@ -155,6 +161,71 @@ async function proveAppOverride(read, appModuleId, setting, opts = {}) {return last;}+/**+ * Resolve the EFFECTIVE value of a per-app AI setting: the most specific scope that holds a value+ * wins — app-scope override, then the ENVIRONMENT-scope value, then the definition's default.+ *+ * This exists because the org READINESS GATE and the feature's actual setting are different rows,+ * and reading only the gate is actively misleading. Live-measured on a real environment:+ * gate `EnableNLGridSearch` = "false" ← what the readiness report shows+ * setting `NLGridSearchSetting` = "2" at ENVIRONMENT scope ← the feature is ON for every app+ * Reporting that feature as simply "disabled" sends an operator to the admin centre to switch on+ * something already in effect. The gate governs only whether the BUILD will write an app-scope+ * override; it does not decide whether the feature runs.+ *+ * `appModuleId` may be null (no app in scope) — the app layer is then skipped and the answer is the+ * environment/default value, which is exactly what a not-yet-created app would inherit.+ *+ * Returns `{ value, scope }` where scope is 'app' | 'environment' | 'default', or `{ error }` when+ * the lookup could not be RUN. Never conflates "could not look" with "not set".+ */+async function effectiveSettingValue(read, appModuleId, setting) {+ let def;+ try {+ const defs = await read.queryRecords('settingdefinition', { select: ['settingdefinitionid', 'defaultvalue'], filter: `uniquename eq '${odataLit(setting)}'`, top: 1 });+ def = defs && defs[0];+ } catch (e) {+ return { error: `the setting definition could not be read: ${e && e.message}` };+ }+ if (!def || !def.settingdefinitionid) {+ // Not provisioned in this environment at all — distinct from "set to off".+ return { error: `no setting definition named '${setting}' exists in this environment`, unsupported: true };+ }++ if (appModuleId) {+ try {+ const rows = await read.queryRecords('appsetting', { select: ['value'], filter: `_parentappmoduleid_value eq ${odataGuid(appModuleId)} and _settingdefinitionid_value eq ${odataGuid(def.settingdefinitionid)}`, top: 1 });+ if (rows && rows.length) return { value: rows[0].value, scope: 'app' };+ } catch (e) {+ return { error: `the app-scope override row could not be read: ${e && e.message}` };+ }+ }++ try {+ const rows = await read.queryRecords('organizationsetting', { select: ['value'], filter: `_settingdefinitionid_value eq ${odataGuid(def.settingdefinitionid)}`, top: 1 });+ if (rows && rows.length) return { value: rows[0].value, scope: 'environment' };+ } catch (e) {+ return { error: `the environment-scope value could not be read: ${e && e.message}` };+ }++ return { value: def.defaultvalue, scope: 'default' };+}++/**+ * Is a setting value "on"? Values are stored as STRINGS ("0"/"1"/"2"/"true"/"false"), so plain JS+ * truthiness is wrong twice over — it calls the string "0" true, and it calls "false" true. A+ * non-zero number or the literal `true` means on; anything unparseable returns undefined so a+ * caller can say "indeterminate" rather than guess.+ */+function settingIsOn(value) {+ if (value === undefined || value === null || value === '') return undefined;+ const s = String(value).trim().toLowerCase();+ if (s === 'true') return true;+ if (s === 'false') return false;+ const n = Number(s);+ return Number.isNaN(n) ? undefined : n !== 0;+}+/*** Normalize a GUID for use as an UNQUOTED OData lookup comparand. Dataverse returns bare GUIDs, but* a caller-supplied id can arrive `{braced}` (the form `normalizeGuid` also accepts); interpolating@@ -176,5 +247,7 @@ module.exports = {sameSettingValue,resolveAppModuleId,proveAppOverride,+ effectiveSettingValue,+ settingIsOn,odataGuid,};diff --git a/plugins/model-apps/scripts/lib/app-spec.js b/plugins/model-apps/scripts/lib/app-spec.jsindex d469ed62e..932b9dd6e 100644--- a/plugins/model-apps/scripts/lib/app-spec.js+++ b/plugins/model-apps/scripts/lib/app-spec.js@@ -358,6 +358,68 @@ function resolveChoiceValue(byLabel, v, isMulti) {// See docs/app-builder-design.md §7.1.const VALIDATION_PROFILES = ['design', 'plan', 'deploy', 'structural'];+// What a page does when a user opens it straight from the app navigation with no caller input.+// Every page is sitemap-placed, so this state is always reachable for a page that declares+// `pageInput`; these are the two honest answers.+// selector — render a picker/list so the user can choose the record the page needs.+// emptyState — render an explanatory empty state ("open a row from X to see its detail").+const DIRECT_ENTRY_BEHAVIORS = ['selector', 'emptyState'];++// Per-column grid data visualization (PREVIEW). MIRRORS the vendored SDK's `ColumnVisualizationType`+// (types/schema.ts) exactly — widening here without widening there produces a mid-build throw.+//+// Semantics are per COLUMN, not per view: the platform renders the graphic in EVERY grid and view+// that shows the column, which is why this lives on `entities[].columns[]` rather than on `views[]`.+// Persisted as a `controlconfiguration` row bound to the attribute.+//+// `None` is the platform default (plain text) and is accepted so a spec can explicitly CLEAR a+// visualization set by an earlier build or by a maker in the portal. OMITTING the field is NOT the+// same as `None`: an omitted column is left exactly as deployed, because converging every undeclared+// column to "plain text" would cost one extra read per column on every build to find out whether+// there was anything to clear.+const COLUMN_VISUALIZATIONS = ['None', 'RadialDial', 'LineChart', 'HeatMap', 'StarRating'];++// Business rules. These MIRROR the vendored SDK's supported slice — but NARROWER, and the gap is+// deliberate: the SDK advertises four operators and only two of them survive contact with the+// platform.+//+// LIVE-MEASURED 2026-08-27. `ContainsData` and `DoesNotContainData` compile to XAML the platform+// cannot process: every attempt answers+// HTTP 500 ... Error generating UiData for workflow: <name>+// Isolated across six probes on a real org — it fails on a Text column and on a Memo column, with+// the action on the same field or a different one, and in both directions (`DoesNotContainData`+// too). `Equals` and `DoesNotEqual` succeed in the same probes, so it is the presence operators+// specifically, not the rule shape. Offering an operator that reliably 500s is worse than not+// offering it, so they are rejected at the spec gate with a message pointing at the tracking issue.+// Re-widen here (and in the schema doc) once the compiler is fixed upstream.+const BUSINESS_RULE_OPERATORS = ['Equals', 'DoesNotEqual'];+// Recognised by the SDK but not usable: kept separate so validation can explain WHY rather than+// just listing them as unknown.+const BUSINESS_RULE_BLOCKED_OPERATORS = new Set(['ContainsData', 'DoesNotContainData']);+// Operators that take NO value: they test presence, so a `value` would be meaningless. Retained+// because the mapper still handles them correctly — only the platform side is broken.+const BUSINESS_RULE_VALUELESS_OPERATORS = new Set(['ContainsData', 'DoesNotContainData']);+// action type -> the field carrying its payload. `null` = no payload (none currently).+const BUSINESS_RULE_ACTIONS = { SetVisibility: 'visible', LockUnlock: 'lock', SetBusinessRequired: 'required', SetFieldValue: 'value' };+const BUSINESS_RULE_ACTION_TYPES = Object.keys(BUSINESS_RULE_ACTIONS);+// Boolean-payload actions, so a string "false" (truthy in JS) is rejected rather than silently+// inverting the author's intent — the same trap `app.newLook` validation exists to close.+const BUSINESS_RULE_BOOLEAN_ACTIONS = new Set(['SetVisibility', 'LockUnlock', 'SetBusinessRequired']);+// `valueWorkflowType` in SDK terms: how the platform should interpret the literal. Named `dataType`+// in the App Spec because `valueType` in the SDK means something else (Value vs Field vs Lookup),+// and only `Value` is supported — so exposing that name would invite a distinction authors cannot use.+//+// This list MIRRORS the compiler's literal-type map exactly (the `Q5`/type table in the vendored+// bundle). It previously included `DateTime`, which the compiler does NOT have: such a spec passed+// validation and then threw a ValidationError from inside the push — the worst place for it, because+// the bound member may already have committed a workflow row (#482), leaving an orphan behind a+// "failed" build. `column-visualization`-style drift protection is in business-rules.test.js, which+// pins this list against the bundle's own map.+const BUSINESS_RULE_DATA_TYPES = ['String', 'Memo', 'Picklist', 'State', 'Status', 'Boolean', 'Integer', 'Double', 'Decimal', 'Money'];+// Only entity scope is supported. A form-scoped rule needs `processtriggerscope 1` plus a form id,+// which cannot be resolved before the forms phase has run.+const BUSINESS_RULE_SCOPES = ['Entity'];+// Normalize a Dataverse language identifier (LCID) to a positive integer, or null if it is not one.//// This is the SINGLE definition used by all three entry points an LCID can arrive from, so they can@@ -453,6 +515,19 @@ function validateAppSpec(spec, opts = {}) {if (!spec.app || !spec.app.name) {errors.push('app.name is required');}+ // The modern ("new look") shell is an opt-in per-app SETTING, not an appmodule column —+ // `navigationtype` only selects Single/Multi session and is unrelated. Boolean-only: a string+ // "false" is truthy in JS and would silently turn the new look ON for an author who meant to+ // disable it.+ if (spec.app && spec.app.newLook !== undefined && typeof spec.app.newLook !== 'boolean') {+ errors.push('app.newLook must be a boolean');+ }+ // The Wave 2 header/navigation refresh is a SEPARATE public-preview setting from the new look;+ // enabling one does not enable the other. Boolean-only for the same reason as newLook — a string+ // "false" is truthy and would silently turn the feature ON for an author who meant to disable it.+ if (spec.app && spec.app.headerNavigationRefresh !== undefined && typeof spec.app.headerNavigationRefresh !== 'boolean') {+ errors.push('app.headerNavigationRefresh must be a boolean');+ }if (spec.languageCode !== undefined && normalizeLanguageCode(spec.languageCode) === null) {errors.push('languageCode must be a positive integer LCID');}@@ -481,6 +556,14 @@ function validateAppSpec(spec, opts = {}) {if ((c.type === 'Choice' || c.type === 'MultiChoice') && !(Array.isArray(c.options) && c.options.length) && !c.globalChoice) {errors.push(`column ${c.schemaName}: ${c.type} needs options[] or a globalChoice reference`);}+ // Grid data visualization (preview). Only the enum is enforced. Column-TYPE compatibility is+ // deliberately NOT enforced: the SDK does not constrain it either, and the sensible pairings+ // are not a clean "numeric only" rule (LineChart is documented for a TEXT column holding+ // comma-separated numbers). Guessing a constraint the platform does not have would reject+ // valid specs, so type guidance lives in the schema doc instead.+ if (c.visualization !== undefined && !COLUMN_VISUALIZATIONS.includes(c.visualization)) {+ errors.push(`entity ${e.schemaName}: column ${c.schemaName} has unknown visualization '${c.visualization}' — must be one of ${COLUMN_VISUALIZATIONS.join('|')}`);+ }}}if (!entityNames.size) {@@ -560,6 +643,18 @@ function validateAppSpec(spec, opts = {}) {else if (!webResourceNames.has(String(ev.library).toLowerCase())) errors.push(`form ${f.entity}: ${ev.event} handler references undeclared web resource '${ev.library}'`);if (!ev.function) errors.push(`form ${f.entity}: ${ev.event} handler is missing a function name`);if (ev.event === 'onchange' && !ev.attribute) errors.push(`form ${f.entity}: onchange handler requires an attribute (column logical name)`);+ // These three are documented as optional with defaults, and are now actually honoured by the+ // build (they used to be hardcoded and the authored value discarded). Validate the types so a+ // string "false" — which is truthy in JS and would silently enable a handler the author meant+ // to disable — is rejected rather than coerced.+ for (const flagKey of ['enabled', 'passExecutionContext']) {+ if (ev[flagKey] !== undefined && typeof ev[flagKey] !== 'boolean') {+ errors.push(`form ${f.entity}: ${ev.event} handler ${flagKey} must be a boolean (got ${JSON.stringify(ev[flagKey])})`);+ }+ }+ if (ev.parameters !== undefined && typeof ev.parameters !== 'string') {+ errors.push(`form ${f.entity}: ${ev.event} handler parameters must be a string (a comma-separated argument list)`);+ }}for (const qv of f.quickViews || []) {if (!qv || !qv.lookup) { errors.push(`form ${f.entity}: a quickView is missing lookup (the lookup column logical name on this form)`); continue; }@@ -660,6 +755,92 @@ function validateAppSpec(spec, opts = {}) {checkCmdAction(`command '${c.label}' on ${c.entity}`, c.library, c.function);}}+ // Business rules. Every reference is checked against the spec's own columns, because a rule that+ // names a column the app does not create is authored against nothing — and the platform accepts it+ // silently (the rule just never fires), so nothing downstream would catch it.+ for (const r of spec.businessRules || []) {+ const label = `business rule '${(r && r.name) || '(unnamed)'}'`;+ if (!r || typeof r !== 'object' || Array.isArray(r)) { errors.push('businessRules[] entries must be objects'); continue; }+ if (!r.name) errors.push(`${label}: name is required`);+ if (!r.entity || !entityNames.has(r.entity)) { errors.push(`${label}: references unknown entity '${r.entity}'`); continue; }+ if (r.scope !== undefined && !BUSINESS_RULE_SCOPES.includes(r.scope)) {+ errors.push(`${label}: scope must be ${BUSINESS_RULE_SCOPES.join('|')} (a form-scoped rule needs a form id that does not exist until the forms phase runs)`);+ }+ if (r.status !== undefined && !['Active', 'Draft'].includes(r.status)) {+ errors.push(`${label}: status must be Active|Draft`);+ }++ // Columns the rule may reference: the entity's own declared columns plus its primary name.+ const ent = (spec.entities || []).find((e) => e && e.schemaName === r.entity);+ const cols = new Set();+ if (ent) {+ if (ent.primaryAttribute && ent.primaryAttribute.schemaName) cols.add(String(ent.primaryAttribute.schemaName).toLowerCase());+ for (const c of ent.columns || []) if (c && c.schemaName) cols.add(String(c.schemaName).toLowerCase());+ // A lookup created by a relationship is a real column on the referencing table.+ for (const rel of spec.relationships || []) {+ if (rel && rel.referencing === r.entity && rel.lookup && rel.lookup.schemaName) cols.add(String(rel.lookup.schemaName).toLowerCase());+ }+ }+ const checkField = (field, what) => {+ if (!field) { errors.push(`${label}: ${what} needs a field`); return; }+ if (cols.size && !cols.has(String(field).toLowerCase())) {+ errors.push(`${label}: ${what} references '${field}', which is not a column on ${r.entity}`);+ }+ };++ if (!Array.isArray(r.conditions) || !r.conditions.length) {+ errors.push(`${label}: conditions[] is required (a rule with no condition would apply unconditionally, which the compiler emits as an empty rule that silently never fires)`);+ }+ for (const c of r.conditions || []) {+ if (!c || typeof c !== 'object') { errors.push(`${label}: each condition must be an object`); continue; }+ checkField(c.field, 'condition');+ if (!BUSINESS_RULE_OPERATORS.includes(c.operator)) {+ // Name the platform failure rather than pretending the operator is unrecognised: an author+ // who reaches for ContainsData has written something reasonable that we cannot deploy.+ if (BUSINESS_RULE_BLOCKED_OPERATORS.has(c.operator)) {+ errors.push(`${label}: operator '${c.operator}' is not usable — the SDK compiles it to XAML the platform rejects with "Error generating UiData" (HTTP 500), live-measured on every column type. Use ${BUSINESS_RULE_OPERATORS.join(' or ')}, or test the value directly. Tracking: https://github.com/microsoft/power-platform-skills/issues/481`);+ } else {+ errors.push(`${label}: condition operator must be one of ${BUSINESS_RULE_OPERATORS.join('|')} (got '${c.operator}')`);+ }+ continue;+ }+ const valueless = BUSINESS_RULE_VALUELESS_OPERATORS.has(c.operator);+ if (valueless && c.value !== undefined) {+ errors.push(`${label}: '${c.operator}' tests presence, so it must not carry a value`);+ }+ if (!valueless && (c.value === undefined || c.value === null || c.value === '')) {+ errors.push(`${label}: '${c.operator}' needs a value`);+ }+ if (c.dataType !== undefined && !BUSINESS_RULE_DATA_TYPES.includes(c.dataType)) {+ // Name the offending value: this list mirrors the compiler's literal-type map, and the most+ // likely mistake is a plausible-but-absent type (DateTime is the classic one), so echoing+ // what was written is what makes the message actionable.+ errors.push(`${label}: condition dataType '${c.dataType}' is not supported — must be one of ${BUSINESS_RULE_DATA_TYPES.join('|')}`);+ }+ }++ if (!Array.isArray(r.actions) || !r.actions.length) {+ errors.push(`${label}: actions[] is required (a rule that does nothing is not worth deploying)`);+ }+ for (const a of r.actions || []) {+ if (!a || typeof a !== 'object') { errors.push(`${label}: each action must be an object`); continue; }+ if (!BUSINESS_RULE_ACTION_TYPES.includes(a.type)) {+ errors.push(`${label}: action type must be one of ${BUSINESS_RULE_ACTION_TYPES.join('|')} (got '${a.type}')`);+ continue;+ }+ checkField(a.field, `action '${a.type}'`);+ const payload = BUSINESS_RULE_ACTIONS[a.type];+ if (a[payload] === undefined) {+ errors.push(`${label}: action '${a.type}' needs '${payload}'`);+ } else if (BUSINESS_RULE_BOOLEAN_ACTIONS.has(a.type) && typeof a[payload] !== 'boolean') {+ // A string "false" is truthy, so coercing here would invert the author's intent silently.+ errors.push(`${label}: action '${a.type}'.${payload} must be a boolean`);+ }+ if (a.type === 'SetFieldValue' && a.dataType !== undefined && !BUSINESS_RULE_DATA_TYPES.includes(a.dataType)) {+ errors.push(`${label}: action dataType must be one of ${BUSINESS_RULE_DATA_TYPES.join('|')}`);+ }+ }+ }// Dashboards: chart/list tiles reference a declared chart/view; iframe needs a url; webresource a// declared web resource.const DASH_TILE_TYPES = new Set(['chart', 'list', 'iframe', 'webresource']);@@ -832,6 +1013,58 @@ function validateAppSpec(spec, opts = {}) {if (typeof p.pageInput !== 'object' || p.pageInput === null || Array.isArray(p.pageInput)) errors.push(`page '${p.key || p.name}': pageInput must be an object`);}}+ // INPUT CONTRACT. These two rules together resolve a policy conflict that was previously left+ // implicit, and that a page author had no way to satisfy:+ //+ // - Every page MUST be sitemap-placed (the MEMBERSHIP invariant above): the sitemap is the+ // download's only membership oracle, so a page reached only by navigation is invisible to+ // download and gets re-created as a duplicate on the next build.+ // - But a DETAIL page declares `pageInput` (e.g. `{ data: { orderId: 'string' } }`) because it+ // is opened from a list with a row id.+ //+ // Being sitemap-placed means the page is ALSO reachable straight from the app's navigation, with+ // NO input at all. That is a real, user-reachable state — it is what a user gets by clicking the+ // nav entry — and previously nothing made the author account for it, so the generated page would+ // render against `undefined` context. Rather than weaken the membership invariant (which would+ // reintroduce duplicate pages on every rebuild), require the author to say what direct entry+ // does. `directEntry` is that answer, and page-plan feeds it to the generator.+ for (const p of spec.pages || []) {+ const key = p.key || p.name;+ const inputKeys = Object.keys((p.pageInput && p.pageInput.data) || {});+ if (!inputKeys.length) continue;++ if (p.directEntry === undefined) {+ errors.push(`page '${key}' declares pageInput (${inputKeys.join(', ')}) but no directEntry — every page is sitemap-placed, so a user can open it from the app navigation with no input. Declare directEntry: { "behavior": "selector" | "emptyState", "note": "…" } to say what that shows.`);+ } else if (typeof p.directEntry !== 'object' || p.directEntry === null || Array.isArray(p.directEntry)) {+ errors.push(`page '${key}': directEntry must be an object`);+ } else if (!DIRECT_ENTRY_BEHAVIORS.includes(p.directEntry.behavior)) {+ errors.push(`page '${key}': directEntry.behavior must be one of ${DIRECT_ENTRY_BEHAVIORS.join('|')}`);+ }++ // Trace each declared input back to a navigation edge that actually produces it. An input no+ // caller supplies is either a typo or a page that can ONLY ever be entered directly — both are+ // worth failing on, because the generated page would read a key nothing ever sets.+ //+ // EXCEPT when the spec was RECONSTRUCTED from a deployed app (`opts.reconstructed`, set by+ // download). This is an authoring rule: it gates what you are about to create. A reconstruction+ // describes an app that ALREADY EXISTS, and download validates before it writes — so treating+ // it as fatal there produces no spec file at all and strands the author with nothing to edit,+ // which is the #430 failure this release exists to fix. A page whose manifest predates the rule+ // (input supplied externally, or from its own .tsx) hits exactly that. Reported as a warning+ // instead: the author gets the file, the finding, and the chance to fix it.+ const produced = new Set();+ for (const other of spec.pages || []) {+ for (const nav of other.navigatesTo || []) {+ if (nav && nav.targetKey === key) for (const k of Object.keys((nav.data) || {})) produced.add(k);+ }+ }+ const orphaned = inputKeys.filter((k) => !produced.has(k));+ if (orphaned.length) {+ const msg = `page '${key}': pageInput declares ${orphaned.map((k) => `'${k}'`).join(', ')} but no page navigates to it with that data — add it to the producing page's navigatesTo[].data, or drop it from pageInput.`;+ if (opts.reconstructed) warnings.push(msg);+ else errors.push(msg);+ }+ }}// Icons are chrome, not a target. An `icon` that is a **platform reference** (a path or// `$webresource:` — see isPlatformIconRef) is a live/OOB value a downloaded app carries and is valid@@ -1311,6 +1544,14 @@ module.exports = {SDK_ROLE_MARKER,canonicalPersonaName,VALIDATION_PROFILES,+ DIRECT_ENTRY_BEHAVIORS,+ COLUMN_VISUALIZATIONS,+ BUSINESS_RULE_OPERATORS,+ BUSINESS_RULE_VALUELESS_OPERATORS,+ BUSINESS_RULE_ACTIONS,+ BUSINESS_RULE_ACTION_TYPES,+ BUSINESS_RULE_DATA_TYPES,+ BUSINESS_RULE_SCOPES,migrateAppSpec,columnTypeMap,TYPE_MAP,diff --git a/plugins/model-apps/scripts/lib/artifact-intent.js b/plugins/model-apps/scripts/lib/artifact-intent.jsindex e7a03715a..3792ff58f 100644--- a/plugins/model-apps/scripts/lib/artifact-intent.js+++ b/plugins/model-apps/scripts/lib/artifact-intent.js@@ -166,6 +166,12 @@ function formEventsRegionIntent(events) {// 'attribute' is only present on onchange events; including it on onload/onsave would// produce invalid form XML (Dataverse only sets it when a field triggers the handler).if (ev.attribute) attrs.push(['attribute', ev.attribute]);+ // FormXML attribute values are strings, so the booleans are rendered rather than passed+ // through. `enabled` and `passExecutionContext` default to true because that is what an author+ // wiring a handler almost always wants — and it is what the App Spec contract documents; these+ // three were previously HARDCODED here and the authored values silently discarded, so+ // `"enabled": false` produced a handler that ran anyway.+ const flag = (v) => (v === false ? 'false' : 'true');return {n: 'event',a: attrs,@@ -177,9 +183,11 @@ function formEventsRegionIntent(events) {a: [['functionName', ev.function],['libraryName', ev.library],- ['enabled', 'true'],- ['parameters', ''],- ['passExecutionContext', 'true']+ ['enabled', flag(ev.enabled)],+ // Dataverse expects a comma-separated argument list; an absent value is the empty+ // string, NOT a missing attribute (the platform writes `parameters=""` itself).+ ['parameters', ev.parameters === undefined || ev.parameters === null ? '' : String(ev.parameters)],+ ['passExecutionContext', flag(ev.passExecutionContext)]],c: []}]diff --git a/plugins/model-apps/scripts/lib/dataverse-auth.js b/plugins/model-apps/scripts/lib/dataverse-auth.jsindex 8363e166e..e640217ca 100644--- a/plugins/model-apps/scripts/lib/dataverse-auth.js+++ b/plugins/model-apps/scripts/lib/dataverse-auth.js@@ -5,6 +5,9 @@// All operation scripts (provision-entities.js, provision-solution.js, etc.) import from this module.const { execFileSync } = require('child_process');+// Shared with the App Spec + CLI so the provisioned-language probe and the validator cannot disagree+// about what counts as an LCID. app-spec.js does not require this module, so there is no cycle.+const { normalizeLanguageCode } = require('./app-spec.js');/*** Gets an Azure CLI access token for the given Dataverse environment URL.@@ -189,6 +192,93 @@ async function getDefaultPublisherPrefix(envUrl) {}}+/**+ * The set of LCIDs this organization actually has provisioned.+ *+ * `RetrieveProvisionedLanguages` is an unbound OData *function*, so it is not something the maker SDK+ * models — this is the sanctioned `dataverseRequest` hatch (see the "Dataverse Access From Scripts"+ * policy), the same class of read as `WhoAmI`.+ * See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/retrieveprovisionedlanguages+ *+ * Fail-soft by design: this is a *diagnostic* used to turn a silently-ignored language override into+ * a clear message, so every failure mode resolves to `null` ("unknown") rather than throwing. A build+ * must never break because the diagnostic could not run.+ *+ * @param {string} envUrl+ * @param {Function} [request=dataverseRequest] injectable transport, so the status gate below is+ * testable without a network or a live org+ * @returns {Promise<number[]|null>} provisioned LCIDs, or null when they could not be determined+ */+async function readProvisionedLanguages(envUrl, request = dataverseRequest) {+ try {+ const res = await request(envUrl, 'GET', 'RetrieveProvisionedLanguages');+ // `dataverseRequest` has TWO failure surfaces and both must land on null:+ // * an HTTP response, including 4xx/5xx, is RESOLVED as { status, data } — it does not throw.+ // Without this status gate an error envelope would parse as "zero languages provisioned",+ // indistinguishable from a real empty list, and would reject every otherwise-valid LCID.+ // * token acquisition, transport, and retry exhaustion THROW — handled by the catch below,+ // which is why that catch is load-bearing rather than defensive padding.+ if (!res || res.status < 200 || res.status >= 300) return null;+ // Live-verified shape:+ // { "@odata.context": ".../$metadata#Microsoft.Dynamics.CRM.RetrieveProvisionedLanguagesResponse",+ // "RetrieveProvisionedLanguages": [1033] }+ const list = res.data && res.data.RetrieveProvisionedLanguages;+ if (!Array.isArray(list)) return null;+ // Parse with the SAME normalizer the App Spec and the CLI flag use, rather than `Number()`.+ // `Number()` coerces far too much and every one of these previously produced a plausible LCID:+ // [null] -> 0 [true] -> 1 [[1033]] -> 1033 ['1e3'] -> 1000 [''] -> 0+ // `normalizeLanguageCode` accepts only a real integer or a digits-only string (app-spec.js), so+ // the probe and the validator cannot disagree about what an LCID is.+ //+ // ALL-OR-NOTHING on purpose. `checkProvisioned` treats any non-empty list as COMPLETE and+ // authoritative (entity-provision.js), so silently dropping the elements we could not parse would+ // hand it a SHORTER list and make it reject languages the organization may well have. A payload+ // we do not fully understand is "unknown" — null — not "here is the subset I liked".+ const lcids = [];+ for (const raw of list) {+ const lcid = normalizeLanguageCode(raw);+ if (!lcid) return null;+ lcids.push(lcid);+ }+ // An org always has at least its base language, so an empty array is a payload we did not+ // understand too — "unknown", not "zero languages provisioned" (which would reject every LCID).+ return lcids.length ? lcids : null;+ } catch {+ return null;+ }+}++/**+ * The organization's base language (LCID), read at transport level.+ *+ * Needed *before* the maker SDK exists: `MakerSdkOptions.languageCode` is a construction-time+ * option, but the SDK's own `queryRecords` is the usual way to read `organization.languagecode` —+ * a chicken-and-egg the transport hatch resolves. Same class of read as `WhoAmI`.+ *+ * Fail-soft, for the same reason as {@link readProvisionedLanguages}: a caller that cannot learn the+ * base language must fall back and say so, not fail the build.+ *+ * @param {string} envUrl+ * @param {Function} [request=dataverseRequest] injectable transport for tests+ * @returns {Promise<number|null>} the base LCID, or null when it could not be determined+ */+async function readOrgLanguageCode(envUrl, request = dataverseRequest) {+ try {+ const res = await request(envUrl, 'GET', 'organizations?$select=languagecode&$top=1');+ // Status-gated for the same reason as readProvisionedLanguages: dataverseRequest resolves+ // { status, data } for every HTTP response, so an error envelope would otherwise read as+ // "no rows" and silently become the 1033 fallback.+ if (!res || res.status < 200 || res.status >= 300) return null;+ // Shape: { "@odata.context": "...", "value": [ { "organizationid": "...", "languagecode": 1033 } ] }+ // NOTE the plural entity SET name: the singular 'organization' 404s on the Web API.+ const row = res.data && Array.isArray(res.data.value) ? res.data.value[0] : null;+ const lcid = row && Number(row.languagecode);+ return Number.isInteger(lcid) && lcid > 0 && lcid <= 65535 ? lcid : null;+ } catch {+ return null;+ }+}+/*** Parses CLI args. Accepts both space-separated (`--flag value`) and* equals-separated (`--flag=value`) forms, plus bare boolean flags (`--bool`).@@ -223,6 +313,33 @@ function parseArgs(argv) {return { positional, flags };}+/**+ * Read a flag that has both kebab-case and camelCase spellings, rejecting a conflicting pair.+ *+ * `flags[kebab] ?? flags[camel]` silently prefers one and discards the other, which is the wrong+ * answer when the two disagree — the user passed both and believes one is in effect, so guessing+ * either way produces a build they did not ask for with no indication why.+ *+ * Comparison is on the TRIMMED string. Surrounding whitespace in a shell argument is never+ * meaningful (`--language-code " 1031"` and `--languageCode 1031` are the same request), so+ * treating it as a conflict would reject a pair the user got right.+ *+ * Value-domain equivalence is deliberately NOT collapsed: `1031` and `01031` stay a conflict even+ * though both normalize to the same LCID downstream. This helper is domain-agnostic — it has no way+ * to know whether a caller's flag is a number, a name, or an id where `007` differs from `7` — and+ * the two outcomes are not symmetric. A false conflict is a loud error the user fixes in seconds; a+ * wrong guess is a silent, wrong build. So it errs toward the loud one.+ */+function readAliasedFlag(flags, kebab, camel) {+ const a = flags[kebab];+ const b = flags[camel];+ const same = (x, y) => String(x).trim() === String(y).trim();+ if (a !== undefined && b !== undefined && !same(a, b)) {+ throw new Error(`--${kebab} '${a}' and --${camel} '${b}' disagree — pass only one`);+ }+ return a !== undefined ? a : b;+}+/** Reads a JSON value either inline or from a file via @path syntax. */function readJsonArg(raw) {if (raw == null) return null;@@ -270,7 +387,10 @@ module.exports = {label,requiredLevel,getDefaultPublisherPrefix,+ readProvisionedLanguages,+ readOrgLanguageCode,parseArgs,+ readAliasedFlag,readJsonArg,emitResult,};diff --git a/plugins/model-apps/scripts/lib/entity-provision.js b/plugins/model-apps/scripts/lib/entity-provision.jsindex 689de1a08..ed8679799 100644--- a/plugins/model-apps/scripts/lib/entity-provision.js+++ b/plugins/model-apps/scripts/lib/entity-provision.js@@ -18,6 +18,9 @@ const { topoOrderEntities, entityByLogical } = require('./_graph.js');// OData string-literal escaping for spec-controlled values interpolated into $filter (a solution// uniquename / publisher prefix with a `'` would otherwise break the query or inject a clause).const { odataLit } = require('./odata.js');+// Transport-level language reads. Needed here because `MakerSdkOptions.languageCode` is a+// construction-time option, so the LCID must be known before the SDK that would normally read it.+const { readOrgLanguageCode, readProvisionedLanguages } = require('./dataverse-auth.js');// App Spec column type -> SDK ColumnType. Lookup is omitted (side effect of a OneToMany// relationship); Customer is handled specially (createCustomerColumn).@@ -30,11 +33,57 @@ const SDK_COLUMN_TYPE = {const REQUIRED = (c) => (c.required === true ? 'ApplicationRequired' : c.required === 'recommended' ? 'Recommended' : 'None');const DEFAULT_LANGUAGE_CODE = 1033;+// Halt on an EXPLICIT language choice the organization cannot serve, naming what it does have.+//+// Live-verified: Dataverse handles an unprovisioned label LCID INCONSISTENTLY, which is why doing+// nothing is not an option and why a warning is not enough. Against a 1033-only org, writing labels+// at LanguageCode 1036:+// * EntityDefinitions create -> HTTP 204, label silently stored at 1033+// * GlobalOptionSetDefinitions -> HTTP 204, label silently stored at 1033+// * DateTime / Memo column create -> HTTP 400 "The language code 1036 is not a valid language+// for this organization"+// So the build does not fail cleanly and it does not succeed either: the table is created with+// silently wrong labels, then it dies on the first DateTime or Memo column. That leaves a+// half-provisioned data model, and the error surfaces phases away from the flag that caused it —+// it reads like an environment fault.+//+// Warning instead of halting would not help: by the time a warning is read the table already exists+// and has to be torn down. Halting costs the user one flag before any LABEL is written. Note this is+// deliberately not "before any write at all" — `provisionSolution` runs first in `runSdkBuild` and+// may create the publisher and solution — but those carry no language, so nothing lands mislabelled.+//+// Only an explicit override is checked; the org's own base language is provisioned by definition, so+// probing it would cost a round trip to learn nothing.+//+// `provisionedLanguages` is injected rather than called directly so this module stays free of transport.+// Best-effort: an unavailable probe must NOT block a build, because it is a diagnostic — if it cannot+// answer, the build proceeds exactly as it did before.+async function checkProvisioned(lcid, source, provisionedLanguages) {+ if (typeof provisionedLanguages !== 'function') return lcid;+ let list;+ try {+ list = await provisionedLanguages();+ } catch {+ return lcid; // the probe is a nicety; never let it fail a build+ }+ if (!Array.isArray(list) || !list.length) return lcid;+ if (list.includes(lcid)) return lcid;+ throw new BuildHalt(+ `${source} ${lcid} is not provisioned in this organization, so the data model cannot be built in `+ + 'that language. Dataverse fails inconsistently here: table and choice labels are accepted and '+ + "silently stored under the organization's base language, while DateTime and Memo columns are "+ + `rejected outright — so the build would create the table, label it wrong, then stop partway `+ + `through the columns. Provisioned languages: ${list.join(', ')}. Pick one of those, provision `+ + `${lcid} in the organization first, or omit the override to use the base language.`,+ { phase: 'data-model', code: 'language-not-provisioned', recoverable: false }+ );+}+// Dataverse label payloads must use an LCID the org actually has provisioned. Resolve an explicit// CLI override first, then an App Spec override, then the org's base `organization.languagecode`,// and only fall back to 1033 if discovery itself fails so an unrelated read error does not block// the whole build.-async function resolveLanguageCode({ provision, spec, languageCode, warn }) {+async function resolveLanguageCode({ provision, spec, languageCode, warn, provisionedLanguages }) {// A supplied-but-invalid value is DISCARDED, not honoured — but it must not be discarded in// silence. "You gave me nothing" and "you gave me something I could not use" are different facts,// and only the second means the caller believes they pinned a language and is wrong. The CLI flags@@ -48,11 +97,11 @@ async function resolveLanguageCode({ provision, spec, languageCode, warn }) {};const explicit = normalizeLanguageCode(languageCode);- if (explicit) return explicit;+ if (explicit) return await checkProvisioned(explicit, '--language-code', provisionedLanguages);if (languageCode !== undefined && languageCode !== null) rejected('--language-code', languageCode);const specLanguage = normalizeLanguageCode(spec?.languageCode);- if (specLanguage) return specLanguage;+ if (specLanguage) return await checkProvisioned(specLanguage, 'languageCode', provisionedLanguages);if (spec && spec.languageCode !== undefined && spec.languageCode !== null) rejected('languageCode', spec.languageCode);// EVERY fallback to the default is announced, not just the read-threw case. 1033 is precisely the@@ -145,6 +194,28 @@ function isAlreadyExists(err) {return /already exist|duplicate|with the (?:specified|same) name|a key with/.test(msg);}+// The grid data-visualization preview is not provisioned on every environment. When it is absent,+// Dataverse answers the `controlconfigurations` set with a raw 404 naming the segment — the SDK+// deliberately propagates that rather than reporting 'None', so "cannot inspect here" is never+// confused with "plain text on purpose" (see getColumnVisualization in the SDK's SchemaApi).+// Treat it as a SKIP, not a build failure: the table, its columns and every other artifact are+// fine, and failing the whole data-model phase over an optional rendering flourish would strand+// an otherwise-complete app. Anything else (403, 500, a bad column name) still halts.+function isVisualizationUnsupported(err) {+ if (!err) return false;+ const status = err.statusCode || err.status || (err.cause && (err.cause.statusCode || err.cause.status));+ if (status !== 404) return false;+ const msg = String((err && err.message) || '');+ // Match the SEGMENT-missing phrasing specifically, not merely the word "controlconfigurations".+ // The SDK's message embeds the full request URL, which ALWAYS contains that word — so a plain+ // substring test would also swallow a row-level 404 (e.g. `controlconfigurations(<id>)` deleted+ // concurrently), silently reporting "preview unavailable" and leaving the renderer unset on an+ // org that supports it. The server's actual response when the table is absent is:+ // {"error":{"code":"0x80060888","message":"Resource not found for the segment+ // 'controlconfigurations'."}}+ return /not found for the segment\s+'?controlconfigurations/i.test(msg);+}+// Bounded-concurrency map — parallelize independent ops without flooding Dataverse (which// raises SQL-deadlock risk). Preserves input order in the result.async function mapLimit(items, limit, fn) {@@ -185,20 +256,64 @@ function makeRunner({ emit, total }) {}// Route every artifact push (form/view/chart/app/command/dashboard) through this. The SDK's-// pushArtifact RESOLVES (it does NOT throw) with { success:false, error:VersionConflictError } on a-// 412 — the artifact changed in Maker since our last fetch. The engine previously ignored push-// results, so a conflict silently reported success while DROPPING the edit. Halt loudly and require-// a fresh download instead of auto refetch-and-overlay (which would clobber a concurrent Maker edit-// and violates the SDK's rebuild-from-model tenet, architecture-spec T6). A 412 is the only failure-// pushArtifact signals by return value; every other failure still throws. See MakerSdk.pushArtifact.-function requireSuccessfulPush(result, what) {- if (result && result.success === false) {+// pushArtifact RESOLVES (it does NOT throw) with a failed PushResult on a 412 — the artifact changed+// in Maker since our last fetch — and on an ARTIFACT_ALREADY_EXISTS collision. The engine previously+// ignored push results, so a conflict silently reported success while DROPPING the edit. Halt loudly+// and require a fresh download instead of auto refetch-and-overlay (which would clobber a concurrent+// Maker edit and violates the SDK's rebuild-from-model tenet, architecture-spec T6). Those two are+// the failures signalled by return value; every other failure still throws.+//+// The SDK renamed `PushResult.success` to `saved`, DELIBERATELY, to force every call site to be+// re-read once: `saved` means the write committed, NOT that the runtime serves it (that is+// `shipped`, true only when the publish was verified). Both spellings are accepted here because the+// rename is invisible at runtime — a bundle that still returns `success` would otherwise sail past+// a `saved === false` check, and a bundle that returns `saved` sails past a `success === false`+// check. Either mismatch silently disarms this guard, which is the one thing it must never do, so+// the check is written to fail CLOSED against both bundle generations rather than assume one.+function requireSuccessfulPush(result, what, warn) {+ if (!result) return result;+ const committed = result.saved !== undefined ? result.saved : result.success;+ if (committed === false || (committed === undefined && result.error)) {+ // Two DIFFERENT by-value failures reach here, and they need different remedies. Reporting an+ // already-exists collision as a concurrent edit tells the operator to re-download when nothing+ // changed under them, and hides the actual cause.+ const alreadyExists = result.error && result.error.code === 'ARTIFACT_ALREADY_EXISTS';const detail = (result.error && result.error.message) || 'version conflict (412)';throw new BuildHalt(- `push ${what || (result && result.type) || 'artifact'} failed: ${detail} — the artifact changed in Maker since it was fetched; re-download the app and rebuild (never overwrite a concurrent edit)`,- { phase: 'push', code: 'version-conflict', recoverable: true, cause: result && result.error }+ alreadyExists+ ? `push ${what || result.type || 'artifact'} failed: ${detail} — a row already exists at that id and no duplicate was created; adopt it (fetchArtifact) instead of re-creating it`+ : `push ${what || result.type || 'artifact'} failed: ${detail} — the artifact changed in Maker since it was fetched; re-download the app and rebuild (never overwrite a concurrent edit)`,+ { phase: 'push', code: alreadyExists ? 'already-exists' : 'version-conflict', recoverable: true, cause: result.error });}+ // A push can COMMIT and still be partially wrong, and the SDK reports that by value rather than+ // failing: an app whose components could not all be pinned, whose system-admin role assignment+ // failed (which yields an app nobody can open), or which saved but did not publish. The SDK's own+ // comment says these exist "so a create that produced an UNOPENABLE app is not read as a clean+ // success" — which is precisely what dropping them on the floor does.+ reportPartialPush(result, what, warn);+ return result;+}++// Surface the non-fatal half of a push/publish outcome. Never throws and never halts: the primary+// write committed, so the build should continue — but silence here turns a partial success into a+// reported clean one.+//+// The remediation hint is deliberately NOT "re-run with --publish". This runs for three different+// callers and that advice is only right for one of them: an explicit `publishArtifact` has already+// attempted the publish, and an app CREATE publishes inside the SDK, so telling either to pass a+// flag they effectively already used sends the operator in a circle. What is true for all three is+// that the save survived and the publish did not, so a re-run once the cause clears is the fix.+function reportPartialPush(result, what, warn) {+ if (!result || typeof warn !== 'function') return result;+ const label = what || result.type || 'artifact';+ const st = result.publish;+ if (st && st.kind === 'failed') {+ warn(`publish ${label} FAILED: ${(st.error && st.error.message) || 'unknown error'} — 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`);+ } else if (st && st.kind === 'unverifiable') {+ warn(`publish ${label} could not be CONFIRMED (${st.reason}) — the publish call succeeded but the published projection was not read back, so treat "live" as unproven`);+ }+ for (const w of result.warnings || []) warn(`${label}: ${w}`);return result;}@@ -215,11 +330,51 @@ async function provisionSolution({ sdk, provision, runner, solution }) {}, { recoverable: true });}+// Resolve the AUTHORING language once, at transport level, before the maker SDK is constructed.+//+// #455: `MakerSdkOptions.languageCode` is a construction-time option — the App, Form and Dashboard+// adapters bake it in, so it must be known before `createMakerSdk`. But the default source for it is+// `organization.languagecode`, which the SDK itself would normally read. That circularity is why+// this reads over the transport hatch instead.+//+// Same precedence as `resolveLanguageCode`, and deliberately so: an explicit CLI flag, then the App+// Spec field, then the organization's base language, then 1033. The explicit branches are also+// checked against the provisioned set here, so the halt happens once — before the SDK exists and+// long before any label is written.+//+// `readOrg` / `provisionedLanguages` are injected for tests.+async function resolveAuthoringLanguage({ envUrl, languageCode, spec, warn, readOrg, provisionedLanguages }) {+ const readOrgLcid = readOrg || ((url) => readOrgLanguageCode(url));+ const probe = provisionedLanguages || (() => readProvisionedLanguages(envUrl));+ return resolveLanguageCode({+ // resolveLanguageCode only needs `.queryRecords('organization', …)`; adapt the transport read to+ // that shape rather than duplicating the precedence ladder, so the two paths cannot drift.+ provision: {+ queryRecords: async (set) => {+ if (set !== 'organization') return [];+ const lcid = await readOrgLcid(envUrl);+ return lcid ? [{ languagecode: lcid }] : [];+ },+ },+ spec,+ languageCode,+ warn,+ provisionedLanguages: probe,+ });+}+// Discover-then-create global choices, tables, columns, status reasons, alternate keys,// and relationships (idempotent). Returns captured maps used by sample data + later phases.-async function provisionDataModel({ sdk, provision, runner, spec, apply, languageCode, warn }) {+async function provisionDataModel({ sdk, provision, runner, spec, apply, languageCode, warn, provisionedLanguages, preResolvedLanguageCode }) {const result = { entities: {}, globalChoiceIds: {}, statusReasonValues: {}, columns: {}, relationships: [] };- const resolvedLanguageCode = await resolveLanguageCode({ provision, spec, languageCode, warn });+ // The CLI resolves the authoring LCID BEFORE constructing the SDK, because+ // `MakerSdkOptions.languageCode` is a construction-time option (#455) — the App/Form/Dashboard+ // adapters bake it in. Re-resolving here would repeat the org read and the provisioned-languages+ // probe, and could disagree with the value the SDK is already stamping into FormXML and sitemap+ // titles. So an already-resolved value wins outright. The self-resolving path stays for callers+ // that construct the SDK themselves and for the existing unit tests.+ const resolvedLanguageCode = preResolvedLanguageCode+ || await resolveLanguageCode({ provision, spec, languageCode, warn, provisionedLanguages });const globalChoiceIds = result.globalChoiceIds;const statusReasonValues = result.statusReasonValues;@@ -304,6 +459,33 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply, languag});}});+ // Grid data visualization (preview) — render a column's value as a radial dial / line chart /+ // heat map / star rating instead of text. Applied HERE, with the columns, and not with views:+ // it is per-COLUMN metadata (a `controlconfiguration` row bound to the attribute), so the+ // platform honours it in EVERY grid and view that shows the column.+ //+ // Runs for pre-existing columns as well as freshly created ones. `setColumnVisualization` is+ // idempotent — it PATCHes the single config row it finds and prunes duplicates — so re-asserting+ // the spec on a rebuild converges rather than piling up rows. Serial for the same reason the+ // column loop is: these writes touch the same table's customizations.+ //+ // Deliberately a SEPARATE call rather than `createColumn`'s inline `visualization` option, for+ // two reasons: (1) the inline option only ever fires for a column being created, so a rebuild —+ // where every column already exists — would never re-assert the spec; (2) when the binding+ // fails, createColumn raises its own `..._BIND_FAILED` error wrapping the cause, which the+ // absent-preview check below cannot cleanly recognise. Calling it separately yields the raw 404+ // and lets an unprovisioned environment skip instead of halting.+ const withVisualization = (e.columns || []).filter((c) => c && c.schemaName && c.visualization !== undefined);+ for (const c of withVisualization) {+ // Prefer the logical name the create call actually returned; fall back to the conventional+ // lower-cased schema name for a column that already existed (Dataverse lower-cases logical+ // names, so `cfo_Rating` is always `cfo_rating`).+ const created = (result.columns[e.schemaName] || []).find((x) => x.schemaName === c.schemaName);+ const columnLogical = (created && created.logicalName) || String(c.schemaName).toLowerCase();+ await runner.run('data-model', `visualization ${e.schemaName}.${c.schemaName} (${c.visualization})`,+ () => sdk.setColumnVisualization(logical, columnLogical, c.visualization),+ { recoverable: true, skipIf: isVisualizationUnsupported });+ }// custom status reasons — capture the option value so sample data can set them. IDEMPOTENT:// insertStatusValue itself is not (with no explicit Value, Dataverse auto-assigns a NEW value// every call, duplicating the reason on a data-model re-run). So we PIN a deterministic value@@ -501,4 +683,4 @@ async function provisionSampleData({ sdk, provision, runner, spec, dataModel })return { records: result.records, entitySetFor };}-module.exports = { makeRunner, requireSuccessfulPush, makeEntitySetResolver, resolveLanguageCode, provisionSolution, provisionDataModel, provisionSampleData, buildSeedGroup, BuildHalt, SDK_COLUMN_TYPE };+module.exports = { makeRunner, requireSuccessfulPush, reportPartialPush, makeEntitySetResolver, resolveLanguageCode, resolveAuthoringLanguage, provisionSolution, provisionDataModel, provisionSampleData, buildSeedGroup, BuildHalt, SDK_COLUMN_TYPE, isVisualizationUnsupported };diff --git a/plugins/model-apps/scripts/lib/hydrate-spec.js b/plugins/model-apps/scripts/lib/hydrate-spec.jsindex beabde64f..7c8b49a51 100644--- a/plugins/model-apps/scripts/lib/hydrate-spec.js+++ b/plugins/model-apps/scripts/lib/hydrate-spec.js@@ -105,6 +105,36 @@ async function hydrateSpec(read) {})),};+ // BACK-COMPAT: a page reconstructed from an app deployed BEFORE `directEntry` existed carries+ // `pageInput` and no `directEntry`. App Spec validation requires the pair, and download validates+ // BEFORE writing — so without a default, downloading such an app fails and writes NO spec file at+ // all, leaving the author nothing to edit and no way back into the round-trip. That is precisely+ // the "one unrelated nav entry blocks the whole download → edit → rebuild flow" failure #430 was+ // filed for, and it would have been reintroduced by the rule that fixed a different hole.+ //+ // Default to the CONSERVATIVE behaviour. `emptyState` does not promise a picker the already-+ // deployed `.tsx` never had, which `selector` would. It is a prospective intent for the NEXT+ // rebuild, not a claim about what the deployed page does today — that is genuinely unknown here,+ // since the page was written before the field existed and implements neither behaviour explicitly.+ // The value is written into the spec visibly, with a note saying where it came from, so the author+ // can decide rather than discover it later.+ //+ // This deliberately does NOT weaken the rule for hand-authored specs: those do not come through+ // hydration, so an author writing a new page with `pageInput` still has to decide.+ const directEntryDefaulted = [];+ const directEntryOf = (p) => {+ if (p.directEntry !== undefined) return { directEntry: p.directEntry };+ // Match the validation condition exactly: only a pageInput that declares DATA keys requires it.+ if (!Object.keys((p.pageInput && p.pageInput.data) || {}).length) return {};+ directEntryDefaulted.push(p.key || p.name);+ return {+ directEntry: {+ behavior: 'emptyState',+ note: 'Defaulted on download: this app predates directEntry. Change to "selector" if opening this page from the navigation should show a record picker.',+ },+ };+ };+const spec = {// schemaVersion 2 only when pages carry keys (v2 shape); omitted for legacy back-compat....(hasKeys ? { schemaVersion: 2 } : {}),@@ -123,7 +153,7 @@ async function hydrateSpec(read) {// SYSTEM "Inactive" view FALSE, so no `isdefault`/`querytype` filter isolates author views — it// grabbed the wrong one). Charts/forms/commands also need structured reads the SDK doesn't expose.// All four 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. See download docs / app-builder-roadmap.+ // downloaded spec, so edit them in Maker or a fresh spec. See download docs / app-builder-capabilities.charts: [],forms: [],commands: [],@@ -146,6 +176,7 @@ async function hydrateSpec(read) {...(p.dataSources && p.dataSources.length ? { dataSources: p.dataSources } : {}),...(p.navigatesTo ? { navigatesTo: p.navigatesTo } : {}),...(p.pageInput !== undefined ? { pageInput: p.pageInput } : {}),+ ...directEntryOf(p),...(p.prompt ? { prompt: p.prompt } : {}),source: { kind: 'tsx', codeFile: p.codeFile },}@@ -166,6 +197,10 @@ async function hydrateSpec(read) {Object.defineProperties(spec, {droppedSubareas: { value: droppedSubareaDetails.length, enumerable: false },droppedSubareaDetails: { value: droppedSubareaDetails, enumerable: false },+ // Page keys that received a defaulted `directEntry` (see directEntryOf above). Surfaced so the+ // download CLI can tell the author a value was chosen FOR them — a silently injected behaviour+ // would be its own bug, quieter than the hard failure it replaces.+ directEntryDefaulted: { value: directEntryDefaulted, enumerable: false },});return spec;}diff --git a/plugins/model-apps/scripts/lib/page-manifest.js b/plugins/model-apps/scripts/lib/page-manifest.jsindex f49a33c7f..e8b009ba5 100644--- a/plugins/model-apps/scripts/lib/page-manifest.js+++ b/plugins/model-apps/scripts/lib/page-manifest.js@@ -5,7 +5,10 @@// restores intent + navigation that pac's page download (name + resolved-GUID source only) drops. It// travels inside the solution and survives export/import. See docs/app-builder-design.md §7.3.// PURE: the engine reads/writes the web-resource bytes; this module only shapes/parses strings (no I/O,-// no SDK handle).+// no SDK handle). The one import is app-spec's `DIRECT_ENTRY_BEHAVIORS` — also pure, and shared rather+// than mirrored so the manifest parser and App Spec validation cannot drift into disagreeing about+// which values are legal (a drift here would let a manifest round-trip a value the next build rejects).+const { DIRECT_ENTRY_BEHAVIORS } = require('./app-spec.js');// Manifest payload schema version. `parseManifest` rejects any other version fail-closed: an unknown// version means an incompatible producer, so reconstruct from live state rather than mis-read the payload.@@ -38,6 +41,10 @@ function buildManifest(spec, keyToId) {if (p.dataSources && p.dataSources.length) entry.dataSources = p.dataSources;if (p.navigatesTo && p.navigatesTo.length) entry.navigatesTo = p.navigatesTo;if (p.pageInput !== undefined) entry.pageInput = p.pageInput;+ // Carried with pageInput, not separately: a page that declares an input is REQUIRED to declare+ // what direct entry renders (validation rejects one without the other), so dropping it here+ // would make a downloaded spec fail its own validation on the next build.+ if (p.directEntry !== undefined) entry.directEntry = p.directEntry;// Carry the source discriminant so the download round-trip can reconstruct the full spec shape// (§7.3): intent pages stay intent, tsx pages remember their codeFile. Omit when absent.if (p.source !== undefined) entry.source = p.source;@@ -147,6 +154,16 @@ function parseManifest(text) {if (!p.pageInput || typeof p.pageInput !== 'object' || Array.isArray(p.pageInput)) return null;}+ // directEntry — a plain object whose `behavior` is one of the values App Spec validation+ // accepts. Checking only the object-ness would let a corrupt `behavior` round-trip into a+ // rebuild that then fails App Spec validation, which is exactly what parsing the manifest+ // strictly is supposed to prevent — the manifest is a stored artifact and can be edited or+ // truncated, so a bad value here surfaces far from its cause.+ if (p.directEntry !== undefined) {+ if (!p.directEntry || typeof p.directEntry !== 'object' || Array.isArray(p.directEntry)) return null;+ if (!DIRECT_ENTRY_BEHAVIORS.includes(p.directEntry.behavior)) return null;+ }+// source — when present, must be a valid discriminated intent|tsx shapeif (p.source !== undefined && !isValidSource(p.source)) return null;}diff --git a/plugins/model-apps/scripts/lib/page-plan.js b/plugins/model-apps/scripts/lib/page-plan.jsindex 511e706aa..b238227f5 100644--- a/plugins/model-apps/scripts/lib/page-plan.js+++ b/plugins/model-apps/scripts/lib/page-plan.js@@ -253,8 +253,21 @@ function buildPagePlan(spec, opts = {}) {out.push(`- **Interactions:** ${nav.length? `Navigate to ${nav.map((k) => `"PAGEREF_${k}"`).join(', ')} via Xrm.Navigation.navigateTo (pageType "generative"); custom ids go in data:`: 'In-page interactions only (no cross-page navigation)'}`);- if (p.pageInput !== undefined) {+ // Gate on the DECLARED KEYS, not on `pageInput` being present. `pageInput: { data: {} }` is a+ // page that takes no caller-supplied context, so "direct entry" is not a distinct mode for it —+ // and App Spec validation only demands `directEntry` when at least one key is declared+ // (see app-spec.js, the `inputKeys.length` guard). Keying off presence alone made the plan+ // describe a direct-entry state the contract never required the author to answer for.+ if (Object.keys((p.pageInput && p.pageInput.data) || {}).length) {out.push('- **Page Input:** reads `pageInput` (caller-supplied context)');+ // The page is sitemap-placed, so it is ALSO reachable straight from the app navigation with+ // no input at all. The generator has to be told what that renders, or it writes a page that+ // reads `undefined` context on a path a user can reach by clicking the nav entry.+ const de = p.directEntry || {};+ const behavior = de.behavior === 'selector'+ ? 'render a picker/list so the user can choose the record, then show it'+ : 'render an explanatory empty state (do NOT render a broken/blank detail)';+ out.push(`- **Direct entry (no input):** the page is in the sitemap, so it can be opened from the nav with no \`pageInput\` — ${behavior}.${de.note ? ` ${de.note}` : ''}`);}out.push('');}diff --git a/plugins/model-apps/scripts/lib/phase-diff.js b/plugins/model-apps/scripts/lib/phase-diff.jsindex 390a8ddfb..f5fb7df40 100644--- a/plugins/model-apps/scripts/lib/phase-diff.js+++ b/plugins/model-apps/scripts/lib/phase-diff.js@@ -8,7 +8,7 @@// --apply: running ONLY the changed phases safely requires each phase to self-hydrate its cross-phase// dependencies (e.g. the pages phase currently HALTS unless app-shell ran in the same invocation —// sdk-build.js "pages-requires-app"), which needs a per-phase audit + live validation. That execution-// step is tracked in docs/app-builder-roadmap.md; this module is its correct, testable foundation.+// step is tracked in docs/app-builder-capabilities.md; this module is its correct, testable foundation.//// Comparison is a stable-stringify deep-equal (key-order-independent), so re-ordering keys in the spec// file does NOT report a false change. Any real value change in a phase's slice marks it changed. Whendiff --git a/plugins/model-apps/scripts/lib/sdk-build.js b/plugins/model-apps/scripts/lib/sdk-build.jsindex 1e2cd65b6..ae74b5d9d 100644--- a/plugins/model-apps/scripts/lib/sdk-build.js+++ b/plugins/model-apps/scripts/lib/sdk-build.js@@ -33,12 +33,14 @@ const {FORM_TYPE_CODE,FORM_GUID_RE,canonicalPersonaName,+ BUSINESS_RULE_VALUELESS_OPERATORS,} = require('./app-spec.js');const { PHASES } = require('./stages.js');const { topoOrderEntities, entityByLogical } = require('./_graph.js');const {makeRunner,requireSuccessfulPush,+ reportPartialPush,makeEntitySetResolver,provisionSolution,provisionDataModel,@@ -93,7 +95,10 @@ const TILE_CLASS_ID = {iframe: 'FD2A7985-3187-444E-908D-6624B21F69C0',webresource: '9FDF5F91-88B1-47F4-AD53-C11EFC01A01D',};-const COMPONENT_TYPE = { view: 26, chart: 59, form: 60, dashboard: 60, webResource: 61, sitemap: 62, app: 80, role: 20 };+// Solution component types. `workflow` is 29 — a business rule is a workflow row (category 2), so it+// is added to the solution under that type, not under a bespoke one.+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/solutioncomponent+const COMPONENT_TYPE = { view: 26, chart: 59, form: 60, dashboard: 60, webResource: 61, sitemap: 62, app: 80, role: 20, workflow: 29 };// Web-resource kinds (App Spec `type`) -> SDK createWebResource `type` token. The SDK maps// the token to the Dataverse webresourcetype code (js=3, html=1, css=2, …).@@ -101,6 +106,16 @@ const WEB_RESOURCE_KINDS = new Set(['js', 'html', 'css', 'xml', 'png', 'jpg', 'g// Form-event kinds the engine can wire (onload/onsave/onchange) via the /bag/c <events> region.const FORM_EVENTS = new Set(['onload', 'onsave', 'onchange']);+// The per-app setting name that turns on the modern ("new look") shell. Verified live against a real+// organization: `settingdefinition` uniquename `NewLookAlwaysOn`, datatype 2 (boolean), default+// "false". See the app-shell phase for why this one rather than the other new-look definitions.+const NEW_LOOK_SETTING = 'NewLookAlwaysOn';+// The Wave 2 header/navigation refresh (public preview) — a DIFFERENT `settingdefinition` from+// NEW_LOOK_SETTING above. Named here only for the warning message; the value encoding (a Number+// tri-state where ON is '2', not '1') lives in the SDK's setHeaderAndNavigationRefresh, which is+// why the plugin does not write this row by hand.+const HEADER_NAV_SETTING = 'HeaderAndNavigationRefresh';+// Map a dashboard tile (App Spec) to the SDK's AddDashboardTileOptions. chart/list tiles resolve// the underlying view (savedqueryid) — and the chart its visualization id — from what the build// already created; the target entity is derived from the referenced view. iframe/webresource tiles@@ -126,13 +141,22 @@ function dashboardTileOpts(spec, tile, result) {// addElement('dashboard', id, '/components', …). The adapter mints the cell/control ids and lays the// grid out from `position`; the caller supplies the classId (chart/list share the grid control id —// ChartGridMode disambiguates), the `<parameters>` map, and the placement. Tiles stack vertically-// (one per row in the first section). Param keys match the Dataverse control XML (a chart tile keys-// its visualization as `ChartId`, see DashboardAdapter / dashboard.workflow.test.ts).+// (one per row in the first section). Param keys match the Dataverse control XML; note that a chart+// tile keys its visualization as `VisualizationId`, NOT `ChartId` — see the comment on that line,+// and `lcid-real-bundle.test.js`, which pushes this exact payload through the real bundle.function dashboardComponent(t, index) {const parameters = {};if (t.type === 'chart') {+ // `VisualizationId`, NOT `ChartId`. The platform validates dashboard FormXML against a schema+ // that enumerates the legal children of `<parameters>`, and `ChartId` is not one of them:+ // The element 'parameters' has invalid child element 'ChartId'. List of possible elements+ // expected: 'ViewId, IsUserView, ... VisualizationId, ...'+ // A chart tile therefore failed the whole dashboards phase with a 400. Caught by a live build;+ // the mock-based test had asserted the wrong name, so the suite agreed with the bug.+ // `download-model-app.js` already reads `VisualizationId`, so this also makes a dashboard+ // round-trip through download -> rebuild instead of losing its chart binding.parameters.TargetEntityType = t.targetEntity; parameters.ViewId = t.viewId;- parameters.ChartId = t.visualizationId; parameters.ChartGridMode = 'Chart';+ parameters.VisualizationId = t.visualizationId; parameters.ChartGridMode = 'Chart';} else if (t.type === 'list') {parameters.TargetEntityType = t.targetEntity; parameters.ViewId = t.viewId;parameters.IsUserView = 'false'; parameters.ChartGridMode = 'Grid'; parameters.RecordsPerPage = '10';@@ -151,14 +175,41 @@ function dashboardComponent(t, index) {// Command-bar locations (CommandBarJson.location). MainTab = the entity's form/grid command bar.const COMMAND_LOCATIONS = new Set(['MainTab', 'HomeTab', 'ContextualTab']);-// Build one command control: a button, or a flyout/split-button carrying nested `children`. Each+// What a JS command must be handed so its function can do anything.+//+// `onclickeventjavascriptparameters` is a JSON array of `{type,value}` CrmParameter descriptors. When+// it is null the function is invoked with NO arguments — so the near-universal handler shape+// `function doThing(primaryControl) { primaryControl.getAttribute(...) }` throws on its first+// property access and the button silently does nothing. The error surfaces only in the browser+// console, which is exactly how this shipped unnoticed: the build, the server-side state and+// `--verify` all look perfect.+//+// LIVE-MEASURED from the platform's own maker-authored commands on a real org (the numeric codes are+// not documented in the SDK, which passes the string through verbatim):+// location 0 (form) -> [{"type":5}] e.g. AppCommon.KnowledgeArticle…markInternalOpenDialog+// …discard, …translateArticle — all type 5+// location 1 (grid) -> [{"type":12},{"type":24}] e.g. AppCommon.KnowledgeArticle.GridCommandActions.markInternal+// location 2 (subgrid)-> [{"type":12}] e.g. …relateCategoryFromSubGridStandard+// So 5 = PrimaryControl, 12 = SelectedControl, 24 = SelectedControlSelectedItemIds.+//+// MainTab is the form command bar (live-verified: our MainTab buttons deploy with `location` 0).+// HomeTab/ContextualTab are mapped to the grid/subgrid shapes by the same correspondence; those two+// are inferred from the classic ribbon meanings rather than live-verified, so an author who needs+// something else can still override with an explicit `parameters` string.+const COMMAND_DEFAULT_PARAMETERS = {+ MainTab: '[{"type":5,"value":null}]',+ ContextualTab: '[{"type":12,"value":null}]',+ HomeTab: '[{"type":12,"value":null},{"type":24,"value":null}]',+};++// control gets a GUID `id` with `command` set to the same id (the appactionid). A button with a// `library` + `function` gets a functional JS on-click action bound to the created web resource;// `hidden`/`disabled` set static visibility. A flyout/split container (type FlyoutAnchor|SplitButton)// carries `children` instead of an action — the SDK's CommandAdapter synthesizes the required// intervening Group between a flyout and its buttons (Dataverse forbids a button parented directly// to a flyout). Throws if a referenced web resource wasn't created.-function buildCommandControl(c, webResources) {+function buildCommandControl(c, webResources, location = 'MainTab') {const id = randomUUID();const type = c.type || 'Button';const control = { id, type, label: c.label, command: id };@@ -167,12 +218,18 @@ function buildCommandControl(c, webResources) {const wrId = webResources[c.library];if (!wrId) throw new Error(`command "${c.label}" references web resource '${c.library}' which wasn't created — declare it in webResources[] and don't skip the web-resources phase`);control.action = { type: 'javascript', webResourceId: wrId, functionName: c.function };- if (c.parameters !== undefined) control.action.parameters = c.parameters;+ // Default the parameters when the author did not say. A JS command with none is handed nothing+ // and cannot act on the record — see COMMAND_DEFAULT_PARAMETERS. An explicit value (including+ // an empty string, for a genuinely argument-less function) always wins.+ control.action.parameters = c.parameters !== undefined+ ? c.parameters+ : (COMMAND_DEFAULT_PARAMETERS[location] || COMMAND_DEFAULT_PARAMETERS.MainTab);}if (c.hidden) control.hidden = true;if (c.disabled) control.disabled = true;if ((type === 'FlyoutAnchor' || type === 'SplitButton') && Array.isArray(c.children)) {- control.children = c.children.map((ch) => buildCommandControl(ch, webResources));+ // Children live on the same command bar as their anchor, so they inherit its location.+ control.children = c.children.map((ch) => buildCommandControl(ch, webResources, location));}return control;}@@ -189,7 +246,7 @@ function commandDef(entityLogical, cmds, webResources) {for (const c of cmds) {const location = c.location || 'MainTab';if (!byLocation.has(location)) byLocation.set(location, []);- byLocation.get(location).push(buildCommandControl(c, webResources));+ byLocation.get(location).push(buildCommandControl(c, webResources, location));}const commandBars = [...byLocation.entries()].map(([location, controls]) => ({location,@@ -290,6 +347,7 @@ function planFor(spec, opts) {if ((f.events || []).length) items.push({ phase: 'forms', label: `wire ${f.events.length} event handler(s) on ${f.entity}` });if ((f.quickViews || []).length) items.push({ phase: 'forms', label: `place ${f.quickViews.length} quick-view(s) on ${f.entity}` });}+ if (has('business-rules')) for (const r of spec.businessRules || []) items.push({ phase: 'business-rules', label: `business rule "${r.name}" on ${r.entity}` });if (has('commands')) for (const [entity, cmds] of Object.entries(commandsByEntity(spec))) items.push({ phase: 'commands', label: `command bar for ${entity} (${cmds.length} button(s))` });if (has('dashboards')) for (const d of spec.dashboards || []) items.push({ phase: 'dashboards', label: `dashboard "${d.name}" (${(d.tiles || []).length} tile(s))` });if (has('app-shell')) items.push({ phase: 'app-shell', label: `app module "${spec.app.name}" + sitemap` });@@ -736,6 +794,74 @@ function appDef(spec, result, opts = {}) {components: { forms: Object.values(result.forms || {}).filter(Boolean), views: Object.values(result.views || {}).filter(Boolean), charts: Object.values(result.charts || {}).filter(Boolean) } };}+// Map one App Spec business rule to the SDK's BusinessRuleArtifact shape.+//+// The SDK's condition model is NOT the obvious one, and getting it wrong is SILENT: `updateElement`+// merges unknown keys onto the node, the compiler ignores them, and the push succeeds with XAML that+// references none of the author's columns — a rule that deploys, activates, and never fires. So the+// mapping is explicit and the App Spec shape is validated before we get here.+//+// conditions[] -> rootCondition.clauses[] (ANDed; `logic: 'AND'`)+// actions[] -> rootCondition.trueBranch[]+//+// `valueType` is always `'Value'`: the compiler rejects `Field` and `Lookup`, so exposing that axis+// would offer authors a choice they cannot use. The App Spec's `dataType` is the SDK's+// A business-rule row filter that selects only the DEFINITION, never the platform's activated copy.+//+// LIVE-MEASURED. Activating a business rule makes Dataverse create a SECOND `workflows` row:+// type=1, parentworkflowid=(none) -> the definition the author wrote+// type=2, parentworkflowid=<def> -> the platform's activated copy of it+// That pair is normal for every activated process, and the vendored SDK's own orphan probe filters+// `category eq 2 and type eq 1` for exactly this reason.+//+// Omitting `type` is not cosmetic: it made the build try to deactivate and delete the activated copy+// (which the platform refuses, 405), emit a false "the SDK created a duplicate" warning, and would+// have made `--verify` fail EVERY active business rule as "duplicated".+//+// category 2 = Business Rule; type 1 = definition, 2 = activated copy.+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/workflow+function businessRuleFilter(name, entityLogical) {+ return `category eq 2 and type eq 1 and name eq '${odataLit(name)}' and primaryentity eq '${odataLit(String(entityLogical).toLowerCase())}'`;+}++// `valueWorkflowType` — how the platform interprets the literal — renamed because `valueType` already+// means something else here.+function businessRuleDef(rule) {+ const ids = (prefix) => { let n = 0; return () => `${prefix}${++n}`; };+ const clauseId = ids('c');+ const actionId = ids('a');+ const valueless = (op) => BUSINESS_RULE_VALUELESS_OPERATORS.has(op);+ return {+ name: rule.name,+ entityLogicalName: String(rule.entity).toLowerCase(),+ scope: rule.scope || 'Entity',+ // Draft unless the author asks for Active. A rule is inert until activated, so defaulting to+ // Active is what makes `businessRules[]` do something on the first build.+ status: rule.status || 'Active',+ rootCondition: {+ id: 'r1',+ displayName: rule.name,+ logic: 'AND',+ clauses: (rule.conditions || []).map((c) => ({+ id: clauseId(),+ field: String(c.field).toLowerCase(),+ operator: c.operator,+ valueType: 'Value',+ ...(valueless(c.operator) ? {} : { value: String(c.value), valueWorkflowType: c.dataType || 'String' }),+ })),+ trueBranch: (rule.actions || []).map((a) => {+ const node = { id: actionId(), type: a.type, displayName: a.label || `${a.type} ${a.field}`, field: String(a.field).toLowerCase() };+ if (a.type === 'SetVisibility') node.visible = a.visible;+ else if (a.type === 'LockUnlock') node.lock = a.lock;+ else if (a.type === 'SetBusinessRequired') node.required = a.required;+ else if (a.type === 'SetFieldValue') { node.value = String(a.value); node.valueType = 'Value'; node.valueWorkflowType = a.dataType || 'String'; }+ return node;+ }),+ falseBranch: [],+ },+ };+}+// Map one App Spec persona to the vendored SDK's PersonaRoleSpec (cds-maker-sdk createPersonaRole).// Pure: spec shape -> SDK shape. Two normalizations:// 1. `entity` is lower-cased to a Dataverse logical name (the SDK resolves prv* ids from metadata@@ -879,7 +1005,7 @@ async function runSdkBuild(spec, opts = {}) {return { ok: true, dryRun: true, plan: plan.map((p) => p.label) };}- const result = { ok: true, created: { entities: {}, relationships: {}, records: {}, webResources: {}, views: {}, charts: {}, forms: {}, commands: {}, dashboards: {}, pages: {}, pageDeployedShas: {}, ai: { appFeatures: null, summaries: {} }, roles: {}, app: null } };+ const result = { ok: true, created: { entities: {}, relationships: {}, records: {}, webResources: {}, views: {}, charts: {}, forms: {}, businessRules: {}, commands: {}, dashboards: {}, pages: {}, pageDeployedShas: {}, ai: { appFeatures: null, summaries: {} }, roles: {}, app: null } };// #changed-only (pages-only fast apply): seed the LIVE app id (discovered by unique name upstream) so the// pages phase's `pages-requires-app` guard passes WITHOUT running the app-shell phase in this invocation.// The full-build path never sets opts.changedOnly, so result.created.app stays null and app-shell@@ -896,7 +1022,7 @@ async function runSdkBuild(spec, opts = {}) {// entity (fresh -> createTable result, existing -> findTables hit).let dataModel = { entities: {}, globalChoiceIds: {}, statusReasonValues: {}, columns: {}, relationships: [] };if (has('data-model')) {- dataModel = await provisionDataModel({ sdk, provision, runner, spec, apply, languageCode: opts.languageCode, warn: opts.warn });+ dataModel = await provisionDataModel({ sdk, provision, runner, spec, apply, languageCode: opts.languageCode, warn: opts.warn, provisionedLanguages: opts.provisionedLanguages, preResolvedLanguageCode: opts.preResolvedLanguageCode });Object.assign(result.created.entities, dataModel.entities);}@@ -954,19 +1080,29 @@ async function runSdkBuild(spec, opts = {}) {// --- Form authoring via the SDK's generic surface (addElement/updateElement/removeElement) -------// The new SDK removed the per-artifact form mutators; a form is built as canonical intent// (./artifact-intent.js) and applied through the generic surface.+ //+ // EVERY read/mutate call below is awaited because the SDK's generic surface is ASYNC as of the+ // upstream "300s cache staleness with async revalidating reads" change: getArtifact, addElement,+ // updateElement, removeElement, moveElement, findElements and queryTree all return Promises now+ // (a read may re-fetch from the server before serving a cached copy). Dropping an `await` here+ // does NOT throw — a Promise is truthy, so the `|| {}` fallbacks stay dormant and the pure+ // helpers below silently see a Promise instead of an artifact (hasSubgrid -> false -> duplicate+ // sub-grid; findFieldCellPointer -> null -> the field is never pruned). That silence is why+ // scripts/tests/sdk-async-surface.test.js scans this file for bare calls.// Create a NEW form body: create a MINIMAL form (the adapter seeds one default tab), append each// compiled tab (addElement recursively mints cell/section/tab ids — updateElement does NOT, so a// coarse whole-tab insert is the adapter-blessed path), then drop the seed tab at index 0. Every// intermediate state keeps >=1 tab, so the structural validator never rejects an empty form.- const createFormShell = (def) => {+ const createFormShell = async (def) => {const art = provision.createArtifact('form', { name: def.name, entityLogicalName: def.entityLogicalName, formType: def.formType, status: def.status });const tabs = def.tabs || [];- for (const tab of tabs) provision.addElement('form', art.id, '/tabs', tab);+ // Sequential (not Promise.all): tab ORDER is the on-form order, and addElement appends.+ for (const tab of tabs) await provision.addElement('form', art.id, '/tabs', tab);// Drop the adapter's seed tab (my tabs were appended after it) — but ONLY if I actually added at// least one tab, so a degenerate spec with an empty `tabs: []` still leaves the valid seed tab// rather than a tab-less form the designer can't open.- if (tabs.length > 0) provision.removeElement('form', art.id, '/tabs/0');+ if (tabs.length > 0) await provision.removeElement('form', art.id, '/tabs/0');return art.id;};@@ -987,12 +1123,12 @@ async function runSdkBuild(spec, opts = {}) {// A sub-grid used to be spliced as a single cell into the first field section's rows, which rendered// it half-width inside a 2-column section; giving it a dedicated section makes the related list span// the form. `sg.label` is already resolved to the child's display name by the forms phase.- const addSubgrids = (formId, subs) => {+ const addSubgrids = async (formId, subs) => {for (const sg of subs || []) {- if (hasSubgrid(provision.getArtifact('form', formId) || {}, sg.relationshipName)) continue;- const sectionsPtr = firstColumnSectionsPointer(provision.getArtifact('form', formId) || {});+ if (hasSubgrid(await provision.getArtifact('form', formId) || {}, sg.relationshipName)) continue;+ const sectionsPtr = firstColumnSectionsPointer(await provision.getArtifact('form', formId) || {});if (!sectionsPtr) continue;- provision.addElement('form', formId, sectionsPtr, subgridSectionIntent({ subgridClassId: SUBGRID_CLASS_ID, targetEntity: sg.targetEntity, relationshipName: sg.relationshipName, viewId: sg.viewId, label: sg.label }));+ await provision.addElement('form', formId, sectionsPtr, subgridSectionIntent({ subgridClassId: SUBGRID_CLASS_ID, targetEntity: sg.targetEntity, relationshipName: sg.relationshipName, viewId: sg.viewId, label: sg.label }));}};@@ -1009,15 +1145,15 @@ async function runSdkBuild(spec, opts = {}) {// region doesn't exist -> add it whole. Rebuild: MERGE (append only handlers not already present,// keyed by event+function+library) so a re-run never duplicates a handler or appends a second// <events> root. The adapter mints each handlerUniqueId at serialize (we omit it).- const wireFormEvents = (formId, events) => {+ const wireFormEvents = async (formId, events) => {const wanted = (events || []).filter((ev) => FORM_EVENTS.has(ev.event) && ev.library && ev.function);if (!wanted.length) return false;- const form = provision.getArtifact('form', formId) || {};+ const form = await provision.getArtifact('form', formId) || {};const bagC = (form.bag && form.bag.c) || [];const regionIdx = bagC.findIndex((e) => e && e.node && e.node.n === 'events');if (regionIdx < 0) {const nextI = bagC.reduce((m, e) => Math.max(m, e.i), -1) + 1;- provision.addElement('form', formId, '/bag/c', { i: nextI, node: formEventsRegionIntent(wanted) });+ await provision.addElement('form', formId, '/bag/c', { i: nextI, node: formEventsRegionIntent(wanted) });return true;}// Existing region: append only handlers not already wired.@@ -1031,7 +1167,7 @@ async function runSdkBuild(spec, opts = {}) {let added = false;for (const ev of wanted) {if (existing.has(`${ev.event}|${ev.function}|${ev.library}`)) continue;- provision.addElement('form', formId, `/bag/c/${regionIdx}/node/c`, formEventsRegionIntent([ev]).c[0]);+ await provision.addElement('form', formId, `/bag/c/${regionIdx}/node/c`, formEventsRegionIntent([ev]).c[0]);added = true;}return added;@@ -1051,15 +1187,15 @@ async function runSdkBuild(spec, opts = {}) {if (fn) wantCellByLogical[String(fn).toLowerCase()] = c;}const want = formFieldLogicals(def);- const have = new Set(formFieldLogicals(provision.getArtifact('form', formId) || {}));+ const have = new Set(formFieldLogicals(await provision.getArtifact('form', formId) || {}));for (const logical of want) {if (have.has(logical)) continue; // idempotent: already on the form- const rowsPtr = firstSectionRowsPointer(provision.getArtifact('form', formId) || {});+ const rowsPtr = firstSectionRowsPointer(await provision.getArtifact('form', formId) || {});if (!rowsPtr) break;- provision.addElement('form', formId, rowsPtr, { cells: [wantCellByLogical[logical]] });+ await provision.addElement('form', formId, rowsPtr, { cells: [wantCellByLogical[logical]] });have.add(logical);}- addSubgrids(formId, def.__subgrids);+ await addSubgrids(formId, def.__subgrids);// Prune fields the deployed form carries that the spec's EXPLICIT layout dropped, so editing a// form to REMOVE a field lands. Gated to an author-controlled layout (explicit `tabs`); an AUTO// layout stays additive (never strip a column a user added in Maker). Never remove the primary.@@ -1068,14 +1204,14 @@ async function runSdkBuild(spec, opts = {}) {if (def.__explicitLayout) {const wantSet = new Set(want);const primary = def.__primaryField ? String(def.__primaryField).toLowerCase() : null;- for (const logical of formFieldLogicals(provision.getArtifact('form', formId) || {})) {+ for (const logical of formFieldLogicals(await provision.getArtifact('form', formId) || {})) {if (wantSet.has(logical) || logical === primary) continue;- const ptr = findFieldCellPointer(provision.getArtifact('form', formId) || {}, logical);- if (ptr) provision.removeElement('form', formId, ptr);+ const ptr = findFieldCellPointer(await provision.getArtifact('form', formId) || {}, logical);+ if (ptr) await provision.removeElement('form', formId, ptr);}}- requireSuccessfulPush(await provision.pushArtifact('form', formId), `form ${def.name}`);- await provision.publishArtifact('form', formId);+ requireSuccessfulPush(await provision.pushArtifact('form', formId), `form ${def.name}`, opts.warn);+ reportPartialPush(await provision.publishArtifact('form', formId), `form ${def.name}`, opts.warn);await provision.addSolutionComponent({ componentId: formId, componentType: COMPONENT_TYPE.form, solutionUniqueName: sol.uniqueName });return formId;};@@ -1085,7 +1221,7 @@ async function runSdkBuild(spec, opts = {}) {// publish. Editing a view's column set (e.g. to surface a parent lookup) now takes effect.const reconcileView = async (viewId, def) => {await provision.fetchArtifact('view', viewId);- const current = provision.getArtifact('view', viewId) || {};+ const current = await provision.getArtifact('view', viewId) || {};const have = new Set((current.columns || []).map((c) => String(c.name).toLowerCase()));const merged = (current.columns || []).slice();for (const col of def.columns || []) {@@ -1094,9 +1230,9 @@ async function runSdkBuild(spec, opts = {}) {have.add(n);merged.push({ name: n, width: col.width || 100, order: merged.length });}- provision.updateElement('view', viewId, '/columns', merged);- requireSuccessfulPush(await provision.pushArtifact('view', viewId), `view ${def.name}`);- await provision.publishArtifact('view', viewId);+ await provision.updateElement('view', viewId, '/columns', merged);+ requireSuccessfulPush(await provision.pushArtifact('view', viewId), `view ${def.name}`, opts.warn);+ reportPartialPush(await provision.publishArtifact('view', viewId), `view ${def.name}`, opts.warn);await provision.addSolutionComponent({ componentId: viewId, componentType: COMPONENT_TYPE.view, solutionUniqueName: sol.uniqueName });return viewId;};@@ -1179,12 +1315,12 @@ async function runSdkBuild(spec, opts = {}) {// types (view/chart/command/dashboard/app) still serialize unchanged from a full createArtifact.let id;if (type === 'form') {- id = createFormShell(def);- addSubgrids(id, def.__subgrids);+ id = await createFormShell(def);+ await addSubgrids(id, def.__subgrids);} else {id = provision.createArtifact(type, def).id;}- const pushed = requireSuccessfulPush(await provision.pushArtifact(type, id), `${type} ${def.name}`);+ const pushed = requireSuccessfulPush(await provision.pushArtifact(type, id), `${type} ${def.name}`, opts.warn);await provision.addSolutionComponent({ componentId: pushed.id, componentType: COMPONENT_TYPE[type], solutionUniqueName: sol.uniqueName });return pushed.id;});@@ -1230,7 +1366,7 @@ async function runSdkBuild(spec, opts = {}) {}return runner.run('charts', `chart "${def.name}"`, async () => {const art = provision.createArtifact('chart', def);- const pushed = requireSuccessfulPush(await provision.pushArtifact('chart', art.id), `chart ${def.name}`);+ const pushed = requireSuccessfulPush(await provision.pushArtifact('chart', art.id), `chart ${def.name}`, opts.warn);await provision.addSolutionComponent({ componentId: pushed.id, componentType: COMPONENT_TYPE.chart, solutionUniqueName: sol.uniqueName });return pushed.id;});@@ -1294,9 +1430,9 @@ async function runSdkBuild(spec, opts = {}) {await provision.fetchArtifact('form', id);// Merge into the root-bag <events> region (idempotent — a rebuild only pushes if a NEW// handler was appended, so re-runs don't duplicate a handler or a second <events> root).- if (wireFormEvents(id, wantedEvents)) {- requireSuccessfulPush(await provision.pushArtifact('form', id), `form ${d.f.name || d.f.entity} events`);- await provision.publishArtifact('form', id);+ if (await wireFormEvents(id, wantedEvents)) {+ requireSuccessfulPush(await provision.pushArtifact('form', id), `form ${d.f.name || d.f.entity} events`, opts.warn);+ reportPartialPush(await provision.publishArtifact('form', id), `form ${d.f.name || d.f.entity} events`, opts.warn);}});}@@ -1328,15 +1464,15 @@ async function runSdkBuild(spec, opts = {}) {const qvFormId = formIdByEntityName[`${String(qv.targetEntity).toLowerCase()}|${qv.form}`];if (!qvFormId) throw new Error(`form "${f.name || f.entity}" quick-view references form '${qv.form}' on '${qv.targetEntity}' which wasn't built — declare it in forms[] with formType: "QuickView", entity "${qv.targetEntity}", and a matching name`);const lookup = String(qv.lookup).toLowerCase();- if (hasQuickView(provision.getArtifact('form', hostId) || {}, lookup)) continue; // idempotent- const rowsPtr = firstSectionRowsPointer(provision.getArtifact('form', hostId) || {});+ if (hasQuickView(await provision.getArtifact('form', hostId) || {}, lookup)) continue; // idempotent+ const rowsPtr = firstSectionRowsPointer(await provision.getArtifact('form', hostId) || {});if (!rowsPtr) continue;- provision.addElement('form', hostId, rowsPtr, { cells: [quickViewCellIntent({ quickViewClassId: QUICK_VIEW_CLASS_ID, lookupFieldName: lookup, targetEntity: String(qv.targetEntity).toLowerCase(), quickViewFormId: qvFormId, label: qv.label })] });+ await provision.addElement('form', hostId, rowsPtr, { cells: [quickViewCellIntent({ quickViewClassId: QUICK_VIEW_CLASS_ID, lookupFieldName: lookup, targetEntity: String(qv.targetEntity).toLowerCase(), quickViewFormId: qvFormId, label: qv.label })] });changed = true;}if (changed) {- requireSuccessfulPush(await provision.pushArtifact('form', hostId), `form ${f.name || f.entity} quick-views`);- await provision.publishArtifact('form', hostId);+ requireSuccessfulPush(await provision.pushArtifact('form', hostId), `form ${f.name || f.entity} quick-views`, opts.warn);+ reportPartialPush(await provision.publishArtifact('form', hostId), `form ${f.name || f.entity} quick-views`, opts.warn);}});}@@ -1347,6 +1483,138 @@ async function runSdkBuild(spec, opts = {}) {// Pushed via the workspace-owning `provision` client (the appaction lands in the Default// solution — it's not a standard solution-component type — but is entity-scoped so it shows// on the entity's command bar in the app regardless).+ // 6b-pre. Business rules. Additive discover-reconcile like charts/commands: a rule is identified by+ // (entity, name), and re-pushing on every rebuild would stack duplicate rules on the table. The SDK+ // routes to the supported bound member first and falls back to a classic `workflows` row carrying+ // compiled WWF XAML when that member faults — see sdk-uptake-contract.test.js for the exact routing.+ if (has('business-rules')) {+ for (const rule of spec.businessRules || []) {+ const entityLogical = String(rule.entity).toLowerCase();+ const existing = await provision.queryRecords('workflow', {+ select: ['workflowid', 'statecode', 'createdon'],+ // Definition rows only — see businessRuleFilter. Scoped to the entity as well as the name so+ // a same-named rule on a DIFFERENT table is not mistaken for this one.+ filter: businessRuleFilter(rule.name, entityLogical),+ // `top: 50` and ORDERED, not `top: 1`. Two reasons, both measured:+ // * A previous build (before the SDK's double-write fix) could have left duplicates. With+ // `top: 1` this branch reused one and skipped the cleanup entirely, so both rules kept+ // firing forever — the sweep below only ever ran after a fresh create.+ // * `top: 1` with no ordering returns an ARBITRARY row, so the one adopted as "the" rule+ // could be the faulted orphan rather than the good one. Oldest-first makes the survivor+ // deterministic and prefers the row that was committed first.+ orderBy: 'createdon asc',+ top: 50,+ });+ const existingId = existing && existing[0] && existing[0].workflowid;+ if (existingId) {+ // Legacy duplicates: everything beyond the first row is residue from a build that predates+ // the SDK fix. Remove it here as well as on the create path, so a rebuild repairs an org+ // instead of preserving the problem. Best-effort — these rows frequently refuse both+ // deactivate (400 0x80060015) and delete (405 0x80040227), and a failure to clean one must+ // not fail the build; `--verify` reports the surviving duplicates.+ const legacyDupes = (existing || []).slice(1);+ for (const extra of legacyDupes) {+ try { if (extra.statecode === 1) await provision.updateRecord('workflow', extra.workflowid, { statecode: 0, statuscode: 1 }); } catch { /* try the delete anyway */ }+ let removed = false;+ try { await provision.deleteRecord('workflow', extra.workflowid); removed = true; } catch { /* reported below */ }+ if (typeof opts.warn === 'function') {+ opts.warn(removed+ ? `business rule "${rule.name}": removed a duplicate left by an earlier build (${extra.workflowid})`+ : `business rule "${rule.name}": a duplicate left by an earlier build (${extra.workflowid}) could not be removed — it is wedged by the platform fault that created it. Delete it in Maker so only one copy of the rule runs. See issue #482.`);+ }+ }+ // Reuse — but a rule that EXISTS is not necessarily a rule that RUNS. A deployed rule left in+ // Draft (statecode 0) is inert, and "exists, so skip" would report success over an app whose+ // logic silently does nothing. Live-hit: a rule deactivated out-of-band stayed Draft across a+ // rebuild. So reconcile the one thing that is cheap and safe to converge — its state.+ const wantActive = (rule.status || 'Active') === 'Active';+ const isActive = existing[0].statecode === 1;+ if (wantActive !== isActive) {+ // Converge in BOTH directions. Activating a Draft rule was handled from the start; the+ // reverse was not, so a spec changed to `status: "Draft"` left the deployed rule ACTIVE and+ // still firing — a rebuild that silently ignores the one property it claims to reconcile.+ //+ // Best-effort, NOT a build halt. A rule can be wedged in a state where the platform refuses+ // both activation and deletion ("Invalid operation - You cannot activate or deactivate this+ // business rule") — live-observed on a row the SDK's bound member left behind after faulting+ // during UiData generation (#482). Failing the phase there would make one broken pre-existing+ // rule block the whole app from building, which is worse than an inert rule. The warning+ // says so, and `--verify` reports the rule's real state (see the business-rule block in+ // verify-spec.js).+ const target = wantActive ? { statecode: 1, statuscode: 2 } : { statecode: 0, statuscode: 1 };+ const verb = wantActive ? 'activated' : 'deactivated';+ try {+ await provision.updateRecord('workflow', existingId, target);+ runner.skip('business-rules', `business rule "${rule.name}" on ${rule.entity} (existed in the wrong state — ${verb})`);+ } catch (e) {+ if (typeof opts.warn === 'function') {+ opts.warn(`business rule "${rule.name}" on ${rule.entity} exists but could not be ${verb} (${e && e.message}). It is ${isActive ? 'still running' : 'inert'}. Delete it and rebuild to recreate it cleanly.`);+ }+ runner.skip('business-rules', `business rule "${rule.name}" on ${rule.entity} (exists but could not be ${verb})`);+ }+ } else {+ runner.skip('business-rules', `business rule "${rule.name}" on ${rule.entity} (exists — reuse; rule edits aren't applied on rebuild, recreate to change)`);+ }+ result.created.businessRules[`${entityLogical}|${rule.name}`] = existingId;+ continue;+ }+ await runner.run('business-rules', `business rule "${rule.name}" on ${rule.entity}`, async () => {+ const def = businessRuleDef(rule);+ const art = provision.createArtifact('businessRule', def);+ // The condition tree is a nested object, so it goes on through the generic element surface+ // rather than the create payload — mirroring how the SDK's own workflow test authors one.+ await provision.updateElement('businessRule', art.id, '/rootCondition', def.rootCondition);+ const pushed = requireSuccessfulPush(await provision.pushArtifact('businessRule', art.id), `business rule ${rule.name}`, opts.warn);+ result.created.businessRules[`${entityLogical}|${rule.name}`] = pushed.id;+ await provision.addSolutionComponent({ componentId: pushed.id, componentType: COMPONENT_TYPE.workflow, solutionUniqueName: sol.uniqueName });++ // DE-DUPLICATE — belt-and-braces now that the SDK fixes this at source.+ //+ // The SDK tries the supported bound member first and falls back to a classic `workflows` row+ // on a qualifying 400. That fallback USED to assume the 400 meant "nothing was written";+ // live measurement showed the platform commits the row and THEN faults generating its+ // UiData, so the fallback wrote a SECOND copy and both fired. Observed as two rows ~5s apart+ // in one run, one server-assigned and one carrying the client-generated id.+ //+ // Fixed upstream and vendored here: on the qualifying 400 the SDK now probes for the+ // committed row and DELETES it before writing its own, failing closed if the probe is+ // indeterminate. Live-verified against the org that originally reproduced the bug —+ // one authored rule now yields exactly one row.+ // https://github.com/microsoft/power-platform-skills/issues/482+ //+ // This sweep is KEPT because it covers what the SDK fix cannot: duplicates left on the org+ // by an EARLIER build (those rows are already committed and often refuse both deactivate and+ // delete), and any future path that reintroduces a second write. With the fix in place it+ // finds nothing on a clean org, so it costs one query.+ //+ // Scope is deliberately tight: only rules matching THIS rule's exact name and entity, and+ // only ones that are not the id the push returned. That cannot touch a rule this build did+ // not just author.+ const dupes = await provision.queryRecords('workflow', {+ select: ['workflowid', 'statecode'],+ filter: businessRuleFilter(rule.name, entityLogical),+ top: 50,+ });+ const extras = (dupes || []).filter((w) => String(w.workflowid).toLowerCase() !== String(pushed.id).toLowerCase());+ for (const extra of extras) {+ // Deactivate and delete are attempted INDEPENDENTLY. The orphan is often wedged — the+ // platform answers "Invalid operation - You cannot activate or deactivate this business+ // rule" for a row whose UiData generation faulted — and an earlier version wrapped both in+ // one try, so a failed deactivate meant the delete was never even attempted. Deactivation+ // is also asynchronous, so a row that refuses it now may become deletable shortly after.+ try { if (extra.statecode === 1) await provision.updateRecord('workflow', extra.workflowid, { statecode: 0, statuscode: 1 }); } catch { /* try the delete anyway */ }+ let removed = false;+ try { await provision.deleteRecord('workflow', extra.workflowid); removed = true; } catch { /* reported below */ }+ if (typeof opts.warn === 'function') {+ opts.warn(removed+ ? `business rule "${rule.name}": removed a duplicate the SDK's fallback created (${extra.workflowid})`+ : `business rule "${rule.name}": the SDK's fallback created a duplicate (${extra.workflowid}) that could not be removed automatically — it is wedged by the same platform fault. Delete it in Maker (or after its deactivation completes) so only one copy of the rule runs. See issue #482.`);+ }+ }+ });+ }+ }+if (has('commands')) {for (const [entityLogical, cmds] of Object.entries(commandsByEntity(spec))) {// Additive discover-reconcile (design §14): one command artifact per entity (identity = entity).@@ -1365,7 +1633,7 @@ async function runSdkBuild(spec, opts = {}) {await runner.run('commands', `command bar for ${entityLogical} (${cmds.length} button(s))`, async () => {const def = commandDef(entityLogical, cmds, result.created.webResources);const art = provision.createArtifact('command', def);- const pushed = requireSuccessfulPush(await provision.pushArtifact('command', art.id), `command ${entityLogical}`);+ const pushed = requireSuccessfulPush(await provision.pushArtifact('command', art.id), `command ${entityLogical}`, opts.warn);result.created.commands[entityLogical] = pushed.id;});}@@ -1392,8 +1660,13 @@ async function runSdkBuild(spec, opts = {}) {}await runner.run('dashboards', `dashboard "${dash.name}" (${(dash.tiles || []).length} tile(s))`, async () => {const art = provision.createArtifact('dashboard', { name: dash.name });- (dash.tiles || []).forEach((tile, ti) => provision.addElement('dashboard', art.id, '/components', dashboardComponent(dashboardTileOpts(spec, tile, result), ti)));- const pushed = requireSuccessfulPush(await provision.pushArtifact('dashboard', art.id), `dashboard ${dash.name}`);+ // for..of, not forEach: addElement is async, and a forEach callback would fire the adds+ // without awaiting them — the push below could then race an unfinished tile insert.+ const tiles = dash.tiles || [];+ for (let ti = 0; ti < tiles.length; ti++) {+ await provision.addElement('dashboard', art.id, '/components', dashboardComponent(dashboardTileOpts(spec, tiles[ti], result), ti));+ }+ const pushed = requireSuccessfulPush(await provision.pushArtifact('dashboard', art.id), `dashboard ${dash.name}`, opts.warn);await provision.addSolutionComponent({ componentId: pushed.id, componentType: COMPONENT_TYPE.dashboard, solutionUniqueName: sol.uniqueName });result.created.dashboards[dash.name] = pushed.id;});@@ -1435,7 +1708,7 @@ async function runSdkBuild(spec, opts = {}) {// (charts-phase addSolutionComponent) and shows on its table's chart pane. Preview limitation:// a NEW chart added to an ALREADY-DEPLOYED app on an edit rebuild is NOT re-pinned as an// explicit app component (rebuild the app fresh, or add the chart via a dashboard/sitemap, if- // it must be an explicit component). See docs/app-builder-roadmap.md.+ // it must be an explicit component). See docs/app-builder-capabilities.md.// Imp6 (removal-gate safety) + C2 (page-backed deferral): write the existing app's sitemap here// ONLY when the pages phase will NOT run (so there is no removal gate to bypass) AND the spec has// no page subareas (a page-backed sitemap is always resolved in the finalizer). When has('pages')@@ -1455,9 +1728,9 @@ async function runSdkBuild(spec, opts = {}) {const liveSm = await fetchSitemap(provision, appUniqueName(spec));if (!liveSm.ok) throw new BuildHalt(`cannot verify the existing app's live generative pages before rewriting its sitemap (${liveSm.reason}) — refusing to proceed (would risk orphaning pages)`, { phase: 'app-shell', code: 'pages-sitemap-read-failed', recoverable: true });if (liveSm.ids.length && opts.allowDestructive !== true) throw new BuildHalt(`refusing to rewrite a page-less sitemap over an existing app that still has ${liveSm.ids.length} live generative page(s) (would orphan them: ${liveSm.ids.join(', ')}). Include the pages phase to reconcile them, or re-run with --allow-destructive to detach.`, { phase: 'app-shell', code: 'pages-removed', recoverable: false });- provision.updateElement('app', existingId, '/siteMap', def.siteMap);- requireSuccessfulPush(await provision.pushArtifact('app', existingId), `app ${def.name}`);- await provision.publishArtifact('app', existingId);+ await provision.updateElement('app', existingId, '/siteMap', def.siteMap);+ requireSuccessfulPush(await provision.pushArtifact('app', existingId), `app ${def.name}`, opts.warn);+ reportPartialPush(await provision.publishArtifact('app', existingId), `app ${def.name}`, opts.warn);}await ensureSitemapInSolution(provision, sol, def.uniqueName);return existingId;@@ -1465,7 +1738,7 @@ async function runSdkBuild(spec, opts = {}) {// Create: the full def (siteMap + explicit components + iconWebResourceId) serializes unchanged// through createArtifact, and push emits appmodule -> sitemap -> AddAppComponents -> publish.const art = provision.createArtifact('app', def);- const pushed = requireSuccessfulPush(await provision.pushArtifact('app', art.id), `app ${def.name}`);+ const pushed = requireSuccessfulPush(await provision.pushArtifact('app', art.id), `app ${def.name}`, opts.warn);await provision.addSolutionComponent({ componentId: pushed.id, componentType: COMPONENT_TYPE.app, solutionUniqueName: sol.uniqueName });// The app module and its sitemap are DISTINCT solution components — adding the appmodule does// NOT pull the sitemap in (it lands only in the Default solution), so export/import from the@@ -1713,9 +1986,9 @@ async function runSdkBuild(spec, opts = {}) {await runner.run('pages', 'finalize sitemap (genpage subareas)', async () => {await provision.fetchArtifact('app', result.created.app);const full = appDef(spec, result.created);- provision.updateElement('app', result.created.app, '/siteMap', full.siteMap);- requireSuccessfulPush(await provision.pushArtifact('app', result.created.app), 'app sitemap finalize');- await provision.publishArtifact('app', result.created.app);+ await provision.updateElement('app', result.created.app, '/siteMap', full.siteMap);+ requireSuccessfulPush(await provision.pushArtifact('app', result.created.app), 'app sitemap finalize', opts.warn);+ reportPartialPush(await provision.publishArtifact('app', result.created.app), `app ${(spec.app && spec.app.name) || result.created.app}`, opts.warn);return result.created.app;});}@@ -1726,12 +1999,96 @@ async function runSdkBuild(spec, opts = {}) {}}+ // 7b-ii. Modern ("new look") shell — opt-in via `app.newLook`.+ //+ // This is a per-app SETTING, not an appmodule column: `navigationtype` (the only nav-ish column the+ // SDK writes) is Single/Multi *session* and unrelated. Of the several new-look definitions Dataverse+ // ships, `NewLookAlwaysOn` is the one worth writing — its own description says it "enables the new+ // look and hides the user switch", and that when it is on the user-facing "New look for model driven+ // apps" preference "will have no effect". The alternatives (`NewLookOptOut`,+ // `NewLookModernExperienceOct2023`) both DEFAULT to true and are per-user toggles, so writing them+ // would give a result the app author cannot actually depend on.+ //+ // Runs in the app-shell phase, right after the app exists, and is scoped to the app + solution so it+ // travels on export/import. Best-effort by design: a tenant where the definition is absent (it is a+ // platform feature that rolls out) must not fail an otherwise-good build, so a failure is reported+ // and the build continues — the app is fully functional, just on the classic shell.+ if (has('app-shell') && spec.app && spec.app.newLook === true && result.created.app) {+ // Deliberately NOT inside runner.run: that helper turns any throw into a BuildHalt, and failing+ // an otherwise-good app build because a rolling-out preview setting is unavailable in this tenant+ // is the wrong trade. But a silent ✓ would be worse — reporting success for something that did not+ // happen is the exact failure mode this build has had to fix elsewhere. So: warn, record the real+ // outcome, and let the caller see `newLook: false` rather than infer it.+ try {+ await provision.saveSettingValue(NEW_LOOK_SETTING, 'true', {+ appUniqueName: appUniqueName(spec),+ solutionUniqueName: spec.solution && spec.solution.uniqueName,+ });+ result.created.newLook = true;+ } catch (err) {+ result.created.newLook = false;+ const detail = (err && err.message) || String(err);+ if (typeof opts.warn === 'function') {+ opts.warn(`could not enable the new look (${NEW_LOOK_SETTING}): ${detail} — the app is fully built and functional, but stays on the classic shell. This setting is a platform feature that rolls out by tenant.`);+ }+ }+ }++ // 7b-iii. Wave 2 header + navigation refresh — stated via `app.headerNavigationRefresh`.+ // Deliberately not called "opt-in": the platform default is ON (see below), so this field exists+ // as much to turn the feature OFF as on. Absent means "no opinion" and touches nothing.+ //+ // DISTINCT from `newLook` above, and both can be set independently. `NewLookAlwaysOn` is the+ // new-look shell toggle; `HeaderAndNavigationRefresh` is the Wave 2 header/navigation redesign+ // (public preview). They are separate `settingdefinition` rows and enabling one does not enable+ // the other.+ //+ // Written through the SDK's dedicated `setHeaderAndNavigationRefresh` rather than a raw setting+ // write, because the encoding is a trap: this is a `datatype = 0` (Number) TRI-STATE where ON is+ // '2', not '1'. The SDK's own note records that of the nine Number settings with rows in a live+ // org, eight use '1' for on and only this one uses '2' — and that writing '1' is ACCEPTED by the+ // API and then silently fails to enable the feature. Hand-rolling this is how you ship a green+ // build with the feature off.+ //+ // Same best-effort contract as the new look: this is a rolling-out preview, so a tenant without+ // the definition gets a warning and the real outcome, never a silent success and never a failed+ // build. The SDK throws a plain Error (not an SdkError subclass) when the definition is absent, so+ // this catches broadly on purpose.+ //+ // BOTH values are honoured, and that is not symmetry for its own sake. Verified against the real+ // vendored bundle (offline, by capturing the writes a push issues): the SDK+ // defaults the app artifact's `headerAndNavigationRefresh` to TRUE, and pushing a new app writes+ // the setting to '2' (ON) unprompted. So the platform default is ON, not off — and treating+ // `false` as "do nothing" would silently leave it ON for an author who explicitly asked for it to+ // be off. `false` therefore has to be an active write of the OFF value, not a skip.+ if (has('app-shell') && spec.app && typeof spec.app.headerNavigationRefresh === 'boolean' && result.created.app) {+ const wanted = spec.app.headerNavigationRefresh;+ try {+ const outcome = await provision.setHeaderAndNavigationRefresh(result.created.app, wanted);+ // AppSettingWriteOutcome is 'created' | 'updated' | 'unchanged' — all three mean the row now+ // holds the requested value, so all three are success. Recorded verbatim so a caller can tell+ // a fresh write from a no-op re-run.+ result.created.headerNavigationRefresh = wanted;+ result.created.headerNavigationRefreshOutcome = outcome;+ } catch (err) {+ // Report what actually happened, NOT what was asked for. On failure the row keeps whatever it+ // had — which for a newly created app is the SDK's ON default, so reporting `false` here would+ // be as wrong as reporting success.+ result.created.headerNavigationRefresh = 'unknown';+ const detail = (err && err.message) || String(err);+ if (typeof opts.warn === 'function') {+ opts.warn(`could not ${wanted ? 'enable' : 'disable'} the header and navigation refresh (${HEADER_NAV_SETTING}): ${detail} — the app is fully built and functional, but the header and navigation setting is whatever the platform defaulted it to. This setting is a public-preview feature that rolls out by tenant.`);+ }+ }+ }+// 7c. AI features (opt-in via spec.ai). Enable app-level agents (gated on admin settings) +// configure per-table row summaries. All AI writes are best-effort-gated: setAppAiFeatures// skips features whose admin gate is off; it never throws.// Features the SDK did not put in `applied`, deferred for a post-publish re-proof (see inside the// ai-features phase for why the verdict cannot honestly be decided at write time).const pendingAiReconfirm = [];+if (has('ai-features') && spec.ai !== undefined && spec.ai !== null) {const solutionUniqueName = spec.solution && spec.solution.uniqueName;const appUnique = appUniqueName(spec);@@ -1871,8 +2228,8 @@ async function runSdkBuild(spec, opts = {}) {const perEntity = []; // [type, id] — first artifact found per entityfor (const f of spec.forms || []) { const id = result.created.forms[f.entity.toLowerCase()]; if (id && !seen.has(f.entity.toLowerCase())) { seen.add(f.entity.toLowerCase()); perEntity.push(['form', id]); } }for (const v of spec.views || []) { const k = v.entity.toLowerCase(); const vid = result.created.views[`${k}|${v.name}`]; if (vid && !seen.has(k)) { seen.add(k); perEntity.push(['view', vid]); } }- await runner.mapLimit(perEntity, concurrency, ([type, id]) => provision.publishArtifact(type, id));- if (result.created.app) await provision.publishArtifact('app', result.created.app);+ 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);});}@@ -1901,7 +2258,7 @@ async function runSdkBuild(spec, opts = {}) {if (Object.keys(retryFlags).length) {try {await provision.fetchArtifact('app', result.created.app);- await provision.publishArtifact('app', result.created.app);+ reportPartialPush(await provision.publishArtifact('app', result.created.app), `app ${(spec.app && spec.app.name) || result.created.app}`, opts.warn);const retry = await provision.setAppAiFeatures(appUnique, retryFlags, {solutionUniqueName: spec.solution && spec.solution.uniqueName,appModuleId: result.created.app,@@ -1959,4 +2316,4 @@ async function runSdkBuild(spec, opts = {}) {return result;}-module.exports = { runSdkBuild, planFor, resolvePhases, PHASES, BuildHalt, SDK_COLUMN_TYPE, viewDef, defaultViewColumns, subgridLabel, enrichesDefaultViews, artifactIdentityQuery, resolveExistingFormId, FORM_TYPE_CODE, chartDef, dashboardTileOpts, compileFormIntent, formFieldLogicals, appDef, appUniqueName, commandsByEntity, webResourceOpts, WEB_RESOURCE_KINDS, FORM_EVENTS, acquireAppPagesLease, personaRoleSpecFor, resolveRoleBusinessUnit, roleBuClause };+module.exports = { runSdkBuild, planFor, resolvePhases, PHASES, BuildHalt, SDK_COLUMN_TYPE, viewDef, defaultViewColumns, subgridLabel, enrichesDefaultViews, artifactIdentityQuery, resolveExistingFormId, FORM_TYPE_CODE, chartDef, dashboardTileOpts, dashboardComponent, compileFormIntent, formFieldLogicals, appDef, appUniqueName, commandsByEntity, commandDef, businessRuleDef, businessRuleFilter, webResourceOpts, WEB_RESOURCE_KINDS, FORM_EVENTS, acquireAppPagesLease, personaRoleSpecFor, resolveRoleBusinessUnit, roleBuClause };diff --git a/plugins/model-apps/scripts/lib/sdk-teardown.js b/plugins/model-apps/scripts/lib/sdk-teardown.jsindex 9b48279be..a834eefec 100644--- a/plugins/model-apps/scripts/lib/sdk-teardown.js+++ b/plugins/model-apps/scripts/lib/sdk-teardown.js@@ -45,7 +45,7 @@// the identical phase-grouped, status-marked log.const { topoOrderEntities } = require('./_graph.js');-const { appUniqueName, commandsByEntity, defaultViewColumns, resolveExistingFormId, resolveRoleBusinessUnit, roleBuClause } = require('./sdk-build.js');+const { appUniqueName, commandsByEntity, defaultViewColumns, resolveExistingFormId, resolveRoleBusinessUnit, roleBuClause, businessRuleFilter } = require('./sdk-build.js');const { manifestResourceName, parseManifestBase64 } = require('./page-manifest.js');const { relationshipSchemaName, manyToManySchemaName, lookupColumnsFor, SDK_ROLE_MARKER, canonicalPersonaName, FORM_GUID_RE } = require('./app-spec.js');const { selectSummaryTables } = require('./ai-candidates.js');@@ -307,6 +307,36 @@ const KIND_HANDLERS = {del: (sdk, item) => sdk.deleteSecurityRole(item.id),tolerateNotFound: true, // a role already deleted (e.g. by a prior teardown) is "gone"},+ businessRules: {+ // A business rule is a `workflows` row (category 2), not something the SDK models as a deletable+ // artifact kind — so resolve and delete it over queryRecords/deleteRecord like the row it is.+ //+ // Scoped by (category, name, primaryentity) so a same-named rule on another table is never+ // touched. An ACTIVE rule cannot be deleted, so it is deactivated first; that is a separate+ // round trip and the platform runs it asynchronously (a WorkflowSetState job), which is why a+ // solution uninstall immediately afterwards can transiently 429 — see the teardown notes.+ async resolve(sdk, target) {+ const rows = await sdk.queryRecords('workflow', {+ select: ['workflowid', 'statecode'],+ // DEFINITION rows only (see businessRuleFilter in sdk-build.js). Activating a rule makes the+ // platform create a second `type 2` activated copy whose parent is the definition; the+ // platform refuses to delete that copy directly (405) and removes it with its parent. An+ // unfiltered query therefore produced a guaranteed per-rule teardown failure.+ filter: businessRuleFilter(target.name, target.entity),+ top: 50,+ });+ return (rows || []).map((r) => ({ id: r.workflowid, name: target.name, statecode: r.statecode }));+ },+ async del(sdk, item) {+ // Deactivate before delete. Dataverse refuses to delete an activated process, and the error it+ // returns names neither the rule nor the reason clearly.+ if (item.statecode === 1) {+ try { await sdk.updateRecord('workflow', item.id, { statecode: 0, statuscode: 1 }); } catch { /* fall through: the delete below reports the real failure */ }+ }+ return sdk.deleteRecord('workflow', item.id);+ },+ tolerateNotFound: true,+ },commands: {// The vendored SDK models a table's command bar as ONE artifact per entity (identity = entity):// resolveArtifact('command', { entity }) returns that single per-entity artifact and@@ -324,9 +354,66 @@ const KIND_HANDLERS = {return { items: [], skipReason: "command bar on an existing/external table is not deleted — the SDK deletes the whole bar and cannot scope to this spec's buttons (per-button delete unsupported); remove it manually if intended" };}const items = await sdk.resolveArtifact('command', { entity: target.entity });- return (items || []).map((x) => ({ id: x.id, entity: x.entity || target.entity }));+ const bar = (items || []).map((x) => ({ id: x.id, entity: x.entity || target.entity, kind: 'bar' }));++ // The bar delete does NOT remove the individual `appaction` rows. LIVE-MEASURED: after a+ // teardown that deleted the table itself, five appaction rows for that entity survived, and+ // the three leaf buttons still referenced the form-JS web resource — which then could not be+ // deleted ("referenced by 3 other components", componenttype 10344 = modern command). So the+ // stranded rows are what blocked the web resource, not a platform dependency leak.+ //+ // Safe only because this branch already requires `ownsTable`: the table is one this spec+ // creates, so no foreign app can own buttons on it. Scoped to `contextvalue` (the entity the+ // command is bound to) for the same reason.+ //+ // CHILDREN FIRST: see the depth computation below — a flyout hierarchy is three levels deep,+ // so ordering has to be by real ancestor depth, not by "has a parent".+ let rows = [];+ try {+ rows = await sdk.queryRecords('appaction', {+ select: ['appactionid', '_parentappactionid_value'],+ filter: `contextvalue eq '${odataLit(target.entity)}'`,+ top: 200,+ });+ } catch {+ // Best-effort: if the rows cannot be listed, the bar delete below still runs and the web+ // resource simply reports its dependency, which is the pre-existing behaviour.+ rows = [];+ }+ // DEEPEST FIRST, by real ancestor depth. A flyout is three levels — anchor (no parent), an+ // intervening group (parent = anchor), then the buttons (parent = group) — so+ // `_parentappactionid_value` is set on BOTH the group and the leaves. Sorting merely by "has a+ // parent" puts them in the same bucket in arbitrary order, which can delete the group while its+ // buttons still hang off it; Dataverse rejects deleting a parent that still has children.+ // (Observed while resetting a command bar by hand: a leaf came back 404 because its group had+ // already gone — the platform happened to cascade, which is luck, not ordering.)+ //+ // So walk the parent pointers to a true depth and delete the deepest rows first.+ const byId = new Map((rows || []).map((r) => [r.appactionid, r]));+ const depthOf = (r) => {+ let d = 0;+ let cur = r;+ // Bounded by the row count so a cyclic/self-referential pointer cannot spin forever.+ for (let i = 0; i < byId.size + 1 && cur && cur._parentappactionid_value; i += 1) {+ cur = byId.get(cur._parentappactionid_value);+ d += 1;+ }+ return d;+ };+ const leaves = (rows || [])+ .slice()+ .sort((a, b) => depthOf(b) - depthOf(a))+ .map((r) => ({ id: r.appactionid, entity: target.entity, kind: 'row' }));+ // Rows BEFORE the bar: the individual rows are the ones holding the web-resource dependency,+ // and deleting them first makes the outcome deterministic instead of depending on whatever the+ // bar delete happens to cascade.+ return [...leaves, ...bar];},- del: (sdk, item) => sdk.deleteRemoteArtifact('command', item.entity),+ del: (sdk, item) => (item.kind === 'row'+ ? sdk.deleteRecord('appaction', item.id)+ : sdk.deleteRemoteArtifact('command', item.entity)),+ // A row the bar delete already removed reads as gone, not as a failure.+ tolerateNotFound: true,},form: {async resolve(sdk, target) {@@ -494,6 +581,13 @@ function planTeardown(spec) {for (const entity of Object.keys(commandsByEntity(spec))) {steps.push({ kind: 'commands', phase: 'commands', label: `command bar for ${entity}`, target: { entity, ownsTable: specCreatedTables.has(String(entity).toLowerCase()) } });}+ // Business rules BEFORE forms and tables: a rule is a workflow row bound to the entity, and an+ // ACTIVE one blocks changes to what it references. It is also its own artifact rather than+ // something a table delete cascades away.+ for (const r of spec.businessRules || []) {+ const entity = String(r.entity).toLowerCase();+ steps.push({ kind: 'businessRules', phase: 'business-rules', label: `business rule "${r.name}" (${entity})`, target: { entity, name: r.name } });+ }// Delete forms so a QuickView form referenced by another form's `quickViews[]` is removed AFTER its// HOST form. The host embeds a quick-view CONTROL that references the QV form, so deleting the QV// form first makes Dataverse 400 ("cannot be deleted because it is referenced by 1 otherdiff --git a/plugins/model-apps/scripts/lib/stages.js b/plugins/model-apps/scripts/lib/stages.jsindex 37ca32608..c57a5ea00 100644--- a/plugins/model-apps/scripts/lib/stages.js+++ b/plugins/model-apps/scripts/lib/stages.js@@ -1,12 +1,14 @@'use strict';-// Canonical ordered list of the engine's 14 build phases. This is the SINGLE source of truth —+// Canonical ordered list of the engine's 15 build phases. This is the SINGLE source of truth —// sdk-build.js imports it from here so the stage layer and the engine can never drift. Order is// load-bearing: phases run top-to-bottom, and downstream phases depend on earlier ones (e.g. the-// app phase consumes forms/views/charts built earlier). The `security` phase runs AFTER app-shell+// app phase consumes forms/views/charts built earlier). `business-rules` runs after `forms` because+// a rule is authored against the entity's COLUMNS (data-model) but belongs with the record UI it+// governs; it has no dependency on the command bar. The `security` phase runs AFTER app-shell// because a persona role grants read on (and is associated to) the app module created there, so the// generated app opens for that persona. See docs/app-builder-design.md §6.-const PHASES = ['solution', 'data-model', 'sample-data', 'web-resources', 'views', 'charts', 'forms', 'commands', 'dashboards', 'app-shell', 'pages', 'ai-features', 'security', 'publish'];+const PHASES = ['solution', 'data-model', 'sample-data', 'web-resources', 'views', 'charts', 'forms', 'business-rules', 'commands', 'dashboards', 'app-shell', 'pages', 'ai-features', 'security', 'publish'];// User-facing stages, each a contiguous range of engine phases. Stages are the vocabulary the// orchestrator narrates, gates consent on, and evals assert against — they do NOT rename or merge@@ -16,7 +18,7 @@ const PHASES = ['solution', 'data-model', 'sample-data', 'web-resources', 'views// persona access model is part of standing the app up for its users. See the design doc §5–§6.const STAGES = {data: ['solution', 'data-model', 'sample-data'],- ui: ['web-resources', 'views', 'charts', 'forms', 'commands', 'dashboards'],+ ui: ['web-resources', 'views', 'charts', 'forms', 'business-rules', 'commands', 'dashboards'],app: ['app-shell', 'pages', 'ai-features', 'security'],publish: ['publish'],};diff --git a/plugins/model-apps/scripts/lib/verify-spec.js b/plugins/model-apps/scripts/lib/verify-spec.jsindex ee5bfad76..f3a18857d 100644--- a/plugins/model-apps/scripts/lib/verify-spec.js+++ b/plugins/model-apps/scripts/lib/verify-spec.js@@ -6,11 +6,12 @@const { odataLit } = require('./odata.js');const { normalizePageSource, relationshipSchemaName, manyToManySchemaName, SDK_ROLE_MARKER, canonicalPersonaName } = require('./app-spec.js');-const { resolveExistingFormId, resolveRoleBusinessUnit, roleBuClause, appUniqueName } = require('./sdk-build.js');+const { resolveExistingFormId, resolveRoleBusinessUnit, roleBuClause, appUniqueName, businessRuleFilter } = require('./sdk-build.js');const { extractNavTargets } = require('./pageref-resolver.js');const { AI_APP_SETTING, resolveAiFlags, featureWantValue, sameSettingValue, resolveAppModuleId, proveAppOverride } = require('./ai-app-settings.js');const { declaredPrivileges, compareRolePrivileges } = require('./role-privileges.js');const { resolveSurfaces } = require('./surface-resolver.js');+const { isVisualizationUnsupported } = require('./entity-provision.js');// The PER-APP setting each AI feature writes now lives in ./ai-app-settings.js, together with the// flag-resolution and override-proof helpers the BUILD uses — see that module for why one source of@@ -31,6 +32,33 @@ async function verifySpec(spec, read, opts = {}) {if (tbl) {const cols = new Set(((await read.findColumns(logical)) || []).map((c) => String(c.logicalName || c).toLowerCase()));for (const c of e.columns || []) add('column', `${e.schemaName}.${c.schemaName}`, cols.has(String(c.schemaName).toLowerCase()));+ // Grid data visualization (preview). Reconciled by VALUE, not existence: the build writes a+ // specific renderer, so "a config row exists" would pass even if the deployed renderer were a+ // star rating where the spec asked for a radial dial.+ //+ // Guarded on the reader exposing the capability — most callers construct a reader with only+ // the methods they need, and an optional preview must never turn into a TypeError for them.+ // A 404 means the preview is not provisioned on this environment, which is exactly the case+ // the build SKIPS; reporting it as a failed check would flag every app on such an org for a+ // divergence the build deliberately declined to create.+ if (typeof read.columnVisualization === 'function') {+ for (const c of e.columns || []) {+ if (!c || c.visualization === undefined) continue;+ const name = `${e.schemaName}.${c.schemaName}`;+ let deployed;+ try {+ deployed = await read.columnVisualization(logical, String(c.schemaName).toLowerCase());+ } catch (err) {+ // Skip ONLY the "preview not provisioned here" case, matched on the server's+ // segment-missing phrasing rather than on the status alone. A bare `status === 404`+ // test also swallowed a row-level 404, turning a real divergence into silence.+ if (isVisualizationUnsupported(err)) continue;+ throw err;+ }+ add('column-visualization', name, deployed === c.visualization,+ deployed === c.visualization ? '' : `expected '${c.visualization}', deployed '${deployed}'`);+ }+ }}}@@ -112,6 +140,46 @@ async function verifySpec(spec, read, opts = {}) {}}+ // Business rules. A rule that EXISTS is not a rule that RUNS: a Draft (statecode 0) rule is inert,+ // and a duplicate means the same logic fires twice. Both are states the BUILD can legitimately end+ // in without failing — activation is best-effort, and the SDK's fallback can leave a duplicate it+ // cannot remove (#482) — so the build warns and relies on verify to report the outcome. Without+ // this block that promise was empty: a missing, inert, or duplicated rule still verified PASS.+ //+ // Reconciled on THREE axes, because each fails differently and silently:+ // existence — the rule never built at all+ // cardinality — more than one row for the same (entity, name) fires the logic repeatedly+ // state — deployed Draft when the spec asked for Active (or the reverse)+ for (const rule of spec.businessRules || []) {+ const entityLogical = String(rule.entity).toLowerCase();+ const name = `${entityLogical}.${rule.name}`;+ let rows;+ try {+ // `top: 50`, not 1 — the whole point is to SEE duplicates. Scoped to DEFINITION rows only+ // (see businessRuleFilter): activating a rule makes the platform create a second, `type 2`+ // activated copy, so counting both would report every healthy ACTIVE rule as duplicated.+ rows = await read.queryRecords('workflow', {+ select: ['workflowid', 'statecode'],+ filter: businessRuleFilter(rule.name, entityLogical),+ top: 50,+ });+ } catch (e) {+ // Fail CLOSED: a read that could not run must not read as "present and correct".+ add('business-rule', name, false, `could not be read: ${e && e.message}`);+ continue;+ }+ const list = rows || [];+ if (!list.length) { add('business-rule', name, false, 'not deployed'); continue; }+ if (list.length > 1) {+ add('business-rule', name, false, `${list.length} rules share this name on ${entityLogical} — duplicates fire the same logic more than once (see issue #482)`);+ continue;+ }+ const wantActive = (rule.status || 'Active') === 'Active';+ const isActive = list[0].statecode === 1;+ add('business-rule', name, wantActive === isActive,+ wantActive === isActive ? '' : (wantActive ? 'deployed but DRAFT — the rule does not run' : 'deployed ACTIVE but the spec asks for Draft — the rule is running'));+ }+// Sitemap subareas (+ icons). Scope every check to the specific element type (and, for a subarea// icon, the owning entity) so an icon/entity value reused elsewhere in the XML can't satisfy an// unrelated check (e.g. an Area icon must not make a missing SubArea icon look present).diff --git a/plugins/model-apps/scripts/provision-entities.js b/plugins/model-apps/scripts/provision-entities.jsindex 9b42871a3..6379fc40f 100644--- a/plugins/model-apps/scripts/provision-entities.js+++ b/plugins/model-apps/scripts/provision-entities.js@@ -12,7 +12,7 @@ const { validateProvisionInput } = require('./lib/provision-input.js');const { makeRunner, provisionSolution, provisionDataModel, provisionSampleData } = require('./lib/entity-provision.js');const { quickCreateEnabledFor, normalizeLanguageCode } = require('./lib/app-spec.js');const { createAzHttpClient } = require('./lib/sdk-http-client.js');-const { parseArgs, readJsonArg, emitResult } = require('./lib/dataverse-auth.js');+const { parseArgs, readAliasedFlag, readJsonArg, emitResult, readProvisionedLanguages } = require('./lib/dataverse-auth.js');// Construct the SDK against the vendored bundle + an az-token HttpClient. Two clients:// sdk — carries solutionUniqueName (metadata + record writes auto-join the@@ -167,6 +167,10 @@ async function provisionEntities(input, opts = {}, deps = {}) {spec,apply: true,languageCode: opts.languageCode,+ // Same guard as the build path: an explicit override the org has not provisioned fails here,+ // before any write, rather than half-succeeding (labels silently coerced to the base language,+ // then a hard 400 on the first DateTime/Memo column).+ provisionedLanguages: deps.provisionedLanguages,warn,});@@ -294,7 +298,7 @@ async function main() {const inputPath = path.resolve(typeof inputArg === 'string' && inputArg.startsWith('@') ? inputArg.slice(1) : inputArg);const input = readJsonArg('@' + inputPath);- const rawLang = flags['language-code'] ?? flags.languageCode;+ const rawLang = readAliasedFlag(flags, 'language-code', 'languageCode');let languageCode;if (rawLang !== undefined) {languageCode = normalizeLanguageCode(rawLang);@@ -320,6 +324,9 @@ async function main() {warn: (m) => process.stderr.write(`⚠ ${m}\n`),sdk,provision,+ // Only consulted for an explicit override, and any failure resolves to null so a build never+ // breaks on the diagnostic itself.+ provisionedLanguages: () => readProvisionedLanguages(env),};r = await provisionEntities(input, opts, deps);diff --git a/plugins/model-apps/scripts/tests/ai-preflight.test.js b/plugins/model-apps/scripts/tests/ai-preflight.test.jsindex d80556dbe..1ef02022e 100644--- a/plugins/model-apps/scripts/tests/ai-preflight.test.js+++ b/plugins/model-apps/scripts/tests/ai-preflight.test.js@@ -112,6 +112,11 @@ function loadPreflightCli({ parseResult, readiness, sdkThrows = null }) {},};}+ // Script-relative requires must resolve against the SCRIPT, not this test file — the CLI lives+ // in scripts/ and its siblings are one directory up from tests/.+ if (id.startsWith('./')) {+ return require(path.join(path.dirname(scriptPath), id));+ }return require(id);};customRequire.main = {};@@ -161,7 +166,7 @@ test('ai-preflight CLI passes the app scope, prints admin actions, emits the repassert.ok(harness.events.some((e) => e.type === 'getAiReadiness' && e.opts.appUniqueName === 'new_supportdesk'));assert.match(stderr, /AI Feature Readiness/);- assert.match(stderr, /✗ Form fill \(FormFillBarUXEnabled\)/);+ assert.match(stderr, /✗ Form fill assist toolbar \(FormFillBarUXEnabled\)/);assert.match(stderr, /Admin actions required:/);assert.ok(cleanupIndex > -1 && cleanupIndex < emitIndex, 'emitResult exits, so cleanup must happen first');assert.strictEqual(emitted.ok, true);@@ -179,6 +184,117 @@ test('ai-preflight CLI reports all-enabled status without admin actions', async});await harness.main();- assert.match(harness.stderr.join(''), /All AI features are enabled/);+ assert.match(harness.stderr.join(''), /All AI features are available \(enabled, or already in effect\)/);assert.ok(harness.events.some((e) => e.type === 'getAiReadiness' && Object.keys(e.opts).length === 0));});++// --- "in effect" reporting: the gate is NOT the whole truth -----------------------------------+// Live-measured on a real environment: the readiness gate `EnableNLGridSearch` reads "false" while+// the feature's actual setting `NLGridSearchSetting` is "2" at ENVIRONMENT scope, so NL grid search+// runs in every app on that org. Reporting it as disabled — and telling an admin to switch it on —+// is wrong, and it is what this suite previously locked in.+const { effectiveSettingValue, settingIsOn } = require('../lib/ai-app-settings.js');++test('a gate-off feature that is ON at environment scope reports as in effect, with no admin action', () => {+ const readiness = {+ formFill: { enabled: false, setting: 'FormFillBarUXEnabled', value: '0' },+ nlSearch: { enabled: false, setting: 'EnableNLGridSearch', value: 'false' },+ };+ const effective = {+ formFill: { value: '0', scope: 'default', on: false },+ nlSearch: { value: '2', scope: 'environment', on: true },+ };+ const r = runPreflight(readiness, effective);+ const nl = r.features.find((f) => f.feature === 'nlSearch');+ assert.strictEqual(nl.inEffect, true);+ assert.strictEqual(nl.effectiveScope, 'environment');+ assert.strictEqual(nl.effectiveValue, '2');+ // Only the genuinely-off feature earns an admin action.+ assert.strictEqual(r.adminActions.length, 1);+ assert.match(r.adminActions[0], /Form fill assist toolbar/);+});++test('an UNREADABLE effective value never counts as in effect', () => {+ // Fail-closed: "could not look" must not suppress a real admin action, which would leave an+ // operator with no indication that anything needs doing.+ const readiness = { nlSearch: { enabled: false, setting: 'EnableNLGridSearch', value: 'false' } };+ const r = runPreflight(readiness, { nlSearch: { error: 'the setting definition could not be read: 401' } });+ assert.ok(!r.features.find((f) => f.feature === 'nlSearch').inEffect);+ assert.strictEqual(r.adminActions.length, 1);+});++test('omitting the effective map preserves the previous gate-only behaviour', () => {+ const readiness = { nlSearch: { enabled: false, setting: 'EnableNLGridSearch', value: 'false' } };+ const r = runPreflight(readiness);+ assert.strictEqual(r.adminActions.length, 1);+ assert.ok(!r.features.find((f) => f.feature === 'nlSearch').inEffect);+});++test('settingIsOn reads Dataverse string values, not JS truthiness', () => {+ // Every one of these is a trap: "0" and "false" are truthy strings in JS.+ assert.strictEqual(settingIsOn('0'), false);+ assert.strictEqual(settingIsOn('false'), false);+ assert.strictEqual(settingIsOn('1'), true);+ assert.strictEqual(settingIsOn('2'), true); // NL grid search uses 2, not 1+ assert.strictEqual(settingIsOn('true'), true);+ assert.strictEqual(settingIsOn(''), undefined);+ assert.strictEqual(settingIsOn(undefined), undefined);+ assert.strictEqual(settingIsOn('yes'), undefined); // unparseable => indeterminate, never a guess+});++test('effectiveSettingValue prefers app scope, then environment, then the default', async () => {+ const def = [{ settingdefinitionid: 'def-1', defaultvalue: '0' }];+ const reader = (appRows, envRows) => ({+ queryRecords: async (entity) => {+ if (entity === 'settingdefinition') return def;+ if (entity === 'appsetting') return appRows;+ if (entity === 'organizationsetting') return envRows;+ throw new Error(`unexpected entity ${entity}`);+ },+ });++ assert.deepStrictEqual(+ await effectiveSettingValue(reader([{ value: '9' }], [{ value: '2' }]), 'app-1', 'S'),+ { value: '9', scope: 'app' });+ assert.deepStrictEqual(+ await effectiveSettingValue(reader([], [{ value: '2' }]), 'app-1', 'S'),+ { value: '2', scope: 'environment' });+ assert.deepStrictEqual(+ await effectiveSettingValue(reader([], []), 'app-1', 'S'),+ { value: '0', scope: 'default' });+ // No app in scope: skip the app layer entirely rather than erroring.+ assert.deepStrictEqual(+ await effectiveSettingValue(reader([], [{ value: '2' }]), null, 'S'),+ { value: '2', scope: 'environment' });+});++test('effectiveSettingValue reports a setting the environment does not declare as unsupported', async () => {+ // Distinct from "off": there is no admin action that would satisfy it, so the caller must be able+ // to say so precisely instead of alleging a missing override.+ const read = { queryRecords: async () => [] };+ const r = await effectiveSettingValue(read, 'app-1', 'm365copilotmodelappenabled');+ assert.ok(r.error);+ assert.strictEqual(r.unsupported, true);+ assert.strictEqual(r.value, undefined);+});++test('an unresolvable --app makes effective values INDETERMINATE, not environment-derived', async () => {+ // Peer-review finding. If `--app` is supplied but the app cannot be resolved, the app-scope layer+ // is UNKNOWN, not absent. Falling through to the environment value is actively harmful: an app+ // that overrides a feature to "0" while the environment holds "2" would be reported as in effect,+ // and the admin action for a genuinely disabled feature would be suppressed.+ const harness = loadPreflightCli({+ parseResult: { flags: { env: 'https://contoso.crm.dynamics.com', app: 'missing_app' } },+ readiness: {+ formFill: { enabled: false, setting: 'FormFillBarUXEnabled', value: '0' },+ nlSearch: { enabled: false, setting: 'EnableNLGridSearch', value: 'false' },+ },+ });+ try { await harness.main(); } catch (e) { if (e.exitCode === undefined) throw e; }+ const out = harness.stderr.join('');+ // The app could not be resolved (the stub SDK has no queryRecords), so nothing may be claimed to+ // be in effect, and the admin actions must survive.+ assert.match(out, /could not resolve app/i, `expected a warning about the unresolved app; got: ${out}`);+ assert.ok(!/in effect via/.test(out), 'no feature may be reported as in effect when app scope is unknown');+ assert.match(out, /Admin actions required/, 'genuine admin actions must NOT be suppressed');+});diff --git a/plugins/model-apps/scripts/tests/app-entity-components-real-bundle.test.js b/plugins/model-apps/scripts/tests/app-entity-components-real-bundle.test.jsindex 52445bbbc..a9ad5e0ee 100644--- a/plugins/model-apps/scripts/tests/app-entity-components-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/app-entity-components-real-bundle.test.js@@ -21,6 +21,19 @@ const fs = require('node:fs');const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');const { appDef } = require('../lib/sdk-build.js');+// Every app the PLUGIN creates carries an icon: `ensureAppIcon` (sdk-build.js) resolves the author's+// `spec.app.icon` or generates an SVG web resource, and `appDef` passes its id as+// `iconWebResourceId`. These tests drive the SDK directly, so they must supply one too or they are+// exercising a path production never takes.+//+// The SDK now REQUIRES it: `appmodule.webresourceid` is a required attribute, and when no explicit id+// is given it auto-resolves an IMAGE web resource (PNG/JPG/GIF/ICO/SVG) and throws+// `APP_ICON_UNRESOLVED` if the environment has none. Previously it fell back to ANY unmanaged web+// resource — which on an org whose images are all managed returned a JAVASCRIPT file, and the platform+// rejected the create with an opaque "dependent component WebResource does not exist". Failing fast+// with a clear message is the better behaviour; these tests just have to stop relying on the old+// silent fallback. A synthetic id is right here — the mock transport never dereferences it.+const APP_ICON_ID = '11111111-2222-3333-4444-555555555555';const APP_ID = '11111111-1111-1111-1111-111111111111';const APP_UNIQUE_ID = '33333333-3333-3333-3333-333333333333';@@ -97,7 +110,7 @@ function freshSdk(tables, opts = {}) {async function pushApp(sdk, tables) {const def = appDef(specFor(tables), { forms: {}, views: {}, charts: {}, dashboards: {} });- const art = sdk.createArtifact('app', { name: def.name, uniqueName: 'contoso_customermanagement', description: '', siteMap: def.siteMap, components: def.components });+ const art = sdk.createArtifact('app', { name: def.name, uniqueName: 'contoso_customermanagement', description: '', siteMap: def.siteMap, components: def.components, iconWebResourceId: APP_ICON_ID });return sdk.pushArtifact('app', art.id);}const addComponentsCall = (reqs) => reqs.find((r) => r.method === 'POST' && /AddAppComponents/i.test(r.url));@@ -193,7 +206,7 @@ test('REAL BUNDLE: an app with no sitemap tables neither pins nor verifies (no pappShell: { areas: [{ label: 'Main', groups: [{ label: 'G', subAreas: [{ url: 'https://x/y', title: 'Link' }] }] }] } },{ forms: {}, views: {}, charts: {}, dashboards: {} });- const art = sdk.createArtifact('app', { name: def.name, uniqueName: 'contoso_pageless', description: '', siteMap: def.siteMap, components: def.components });+ const art = sdk.createArtifact('app', { name: def.name, uniqueName: 'contoso_pageless', description: '', siteMap: def.siteMap, components: def.components, iconWebResourceId: APP_ICON_ID });await assert.doesNotReject(sdk.pushArtifact('app', art.id));const call = addComponentsCall(reqs);const refs = call ? (call.body.Components || []).filter((c) => c['@odata.id']) : [];diff --git a/plugins/model-apps/scripts/tests/app-spec-keys.test.js b/plugins/model-apps/scripts/tests/app-spec-keys.test.jsindex a67e3726c..144788e4d 100644--- a/plugins/model-apps/scripts/tests/app-spec-keys.test.js+++ b/plugins/model-apps/scripts/tests/app-spec-keys.test.js@@ -26,7 +26,11 @@ test('navigatesTo.targetKey must resolve to a known page key', () => {const s = base();s.pages = [{ key: 'ov', name: 'Overview', source: { kind: 'intent' }, navigatesTo: [{ targetKey: 'detail', data: { orderId: 'string' } }] },- { key: 'detail', name: 'Detail', source: { kind: 'intent' }, pageInput: { data: { orderId: 'string' } } },+ // `detail` is sitemap-placed (every page must be), so it is reachable from the nav with no+ // orderId — `directEntry` is what the author says happens then. Without it this spec is+ // rejected, which is the point: previously it validated and generated a page that read+ // undefined context on a path a user can reach by clicking the nav entry.+ { key: 'detail', name: 'Detail', source: { kind: 'intent' }, pageInput: { data: { orderId: 'string' } }, directEntry: { behavior: 'selector' } },];// Place every page in the sitemap so the every-page-placed rule (Task 3) does not fail this spec.s.appShell.areas[0].groups[0].subAreas.push({ page: 'ov', title: 'Overview' }, { page: 'detail', title: 'Detail' });@@ -110,3 +114,85 @@ test('navigatesTo/pageInput/design validation is skipped for legacy (non-v2) speassert.ok(!r.errors.some((e) => /navigatesTo|pageInput|design/.test(e)),`unexpected v2-only errors on legacy spec: ${JSON.stringify(r.errors)}`);});++// The sitemap-placement invariant and pageInput used to CONFLICT with no way for an author to+// satisfy both: every page must be a sitemap subarea (the sitemap is download's only membership+// oracle, so a nav-only page is invisible and gets duplicated on rebuild), yet a detail page needs+// caller-supplied context. Being in the sitemap means the page is ALSO reachable from the nav with+// no input at all — a state nothing previously made the author account for, so the generated page+// read undefined context on a path a user reaches by clicking. `directEntry` is that answer.+test('a page with pageInput must declare directEntry (it is sitemap-placed, so nav entry supplies nothing)', () => {+ const s = base();+ s.pages = [+ { key: 'ov', name: 'Overview', source: { kind: 'intent' }, navigatesTo: [{ targetKey: 'detail', data: { orderId: 'string' } }] },+ { key: 'detail', name: 'Detail', source: { kind: 'intent' }, pageInput: { data: { orderId: 'string' } } },+ ];+ s.appShell.areas[0].groups[0].subAreas.push({ page: 'ov', title: 'Overview' }, { page: 'detail', title: 'Detail' });+ const r = validateAppSpec(s, { profile: 'plan' });+ assert.strictEqual(r.ok, false, 'pageInput without directEntry must be rejected');+ assert.ok(r.errors.some((e) => /declares pageInput .* but no directEntry/.test(e)), JSON.stringify(r.errors));++ // Supplying it makes the same spec valid.+ s.pages[1].directEntry = { behavior: 'selector' };+ assert.strictEqual(validateAppSpec(s, { profile: 'plan' }).ok, true, JSON.stringify(validateAppSpec(s, { profile: 'plan' }).errors));+});++test('directEntry.behavior is constrained to the behaviours the generator can actually implement', () => {+ const s = base();+ s.pages = [+ { key: 'ov', name: 'Overview', source: { kind: 'intent' }, navigatesTo: [{ targetKey: 'detail', data: { orderId: 'string' } }] },+ { key: 'detail', name: 'Detail', source: { kind: 'intent' }, pageInput: { data: { orderId: 'string' } }, directEntry: { behavior: 'shrug' } },+ ];+ s.appShell.areas[0].groups[0].subAreas.push({ page: 'ov', title: 'Overview' }, { page: 'detail', title: 'Detail' });+ const r = validateAppSpec(s, { profile: 'plan' });+ assert.ok(r.errors.some((e) => /directEntry.behavior must be one of/.test(e)), JSON.stringify(r.errors));++ for (const behavior of ['selector', 'emptyState']) {+ s.pages[1].directEntry = { behavior };+ assert.strictEqual(validateAppSpec(s, { profile: 'plan' }).ok, true, behavior + ': ' + JSON.stringify(validateAppSpec(s, { profile: 'plan' }).errors));+ }+});++// The input-contract trace. An input nothing supplies is either a typo or a page that can only ever+// be entered directly; both produce a page reading a key no caller ever sets.+test('every pageInput key must be produced by an incoming navigatesTo edge', () => {+ const s = base();+ s.pages = [+ { key: 'ov', name: 'Overview', source: { kind: 'intent' }, navigatesTo: [{ targetKey: 'detail', data: { orderId: 'string' } }] },+ // `customerId` is declared but no page navigates with it.+ { key: 'detail', name: 'Detail', source: { kind: 'intent' }, pageInput: { data: { orderId: 'string', customerId: 'string' } }, directEntry: { behavior: 'selector' } },+ ];+ s.appShell.areas[0].groups[0].subAreas.push({ page: 'ov', title: 'Overview' }, { page: 'detail', title: 'Detail' });+ const r = validateAppSpec(s, { profile: 'plan' });+ assert.strictEqual(r.ok, false);+ assert.ok(r.errors.some((e) => /'customerId'.*no page navigates to it with that data/.test(e)), JSON.stringify(r.errors));++ // Producing it on the edge resolves it.+ s.pages[0].navigatesTo[0].data.customerId = 'string';+ assert.strictEqual(validateAppSpec(s, { profile: 'plan' }).ok, true, JSON.stringify(validateAppSpec(s, { profile: 'plan' }).errors));+});++test('a page with no pageInput needs no directEntry', () => {+ const s = base();+ s.pages = [{ key: 'ov', name: 'Overview', source: { kind: 'intent' } }];+ s.appShell.areas[0].groups[0].subAreas.push({ page: 'ov', title: 'Overview' });+ assert.strictEqual(validateAppSpec(s, { profile: 'plan' }).ok, true, JSON.stringify(validateAppSpec(s, { profile: 'plan' }).errors));+});++// The modern ("new look") shell is a per-app SETTING, not an appmodule column — `navigationtype` is+// Single/Multi *session* and unrelated. Boolean-only, because a string "false" is truthy in JS and+// would turn the new look ON for an author who wrote it to stay off.+test('app.newLook must be a boolean', () => {+ const s = base();+ s.app.newLook = 'false';+ const r = validateAppSpec(s, { profile: 'plan' });+ assert.ok(r.errors.some((e) => /app.newLook must be a boolean/.test(e)), JSON.stringify(r.errors));++ for (const v of [true, false]) {+ const ok = base();+ ok.app.newLook = v;+ assert.strictEqual(validateAppSpec(ok, { profile: 'plan' }).ok, true, String(v) + ': ' + JSON.stringify(validateAppSpec(ok, { profile: 'plan' }).errors));+ }+ // Absent is fine — the new look is opt-in.+ assert.strictEqual(validateAppSpec(base(), { profile: 'plan' }).ok, true);+});diff --git a/plugins/model-apps/scripts/tests/artifact-intent.test.js b/plugins/model-apps/scripts/tests/artifact-intent.test.jsindex 3f040c0c6..cf061730f 100644--- a/plugins/model-apps/scripts/tests/artifact-intent.test.js+++ b/plugins/model-apps/scripts/tests/artifact-intent.test.js@@ -653,3 +653,39 @@ test('findFieldCellPointer: skips null-fieldName controls (notes/subgrid)', () =// null fieldName must not match anythingassert.strictEqual(findFieldCellPointer(formJson, ''), null);});++// The App Spec has documented `enabled`, `passExecutionContext` and `parameters` on+// `forms[].events[]` all along, but the intent builder HARDCODED all three and never read the+// authored values. An author who wrote `"enabled": false` got a handler that ran anyway — the+// worst shape of bug, because the spec, the docs and the deployed form all disagreed silently.+test('form event handler honours enabled / passExecutionContext / parameters', () => {+ const attrsOf = (region) => {+ const handler = region.c[0].c[0].c[0];+ return Object.fromEntries(handler.a);+ };++ // Defaults: both flags true, parameters empty — what an author wiring a handler almost always wants.+ const def = attrsOf(formEventsRegionIntent([{ event: 'onload', library: 'new_lib.js', function: 'onLoad' }]));+ assert.strictEqual(def.enabled, 'true');+ assert.strictEqual(def.passExecutionContext, 'true');+ assert.strictEqual(def.parameters, '');++ // Authored values must actually reach the FormXML.+ const set = attrsOf(formEventsRegionIntent([{+ event: 'onload', library: 'new_lib.js', function: 'onLoad',+ enabled: false, passExecutionContext: false, parameters: 'a,b',+ }]));+ assert.strictEqual(set.enabled, 'false', 'enabled:false must disable the handler, not be discarded');+ assert.strictEqual(set.passExecutionContext, 'false');+ assert.strictEqual(set.parameters, 'a,b');++ // FormXML attribute values are strings, so booleans must be rendered rather than passed through.+ for (const [k, v] of Object.entries(set)) assert.strictEqual(typeof v, 'string', k + ' must serialize as a string');+});++test('form event parameters accepts an explicit empty string and ignores null', () => {+ const attrsOf = (ev) => Object.fromEntries(formEventsRegionIntent([ev]).c[0].c[0].c[0].a);+ assert.strictEqual(attrsOf({ event: 'onsave', library: 'l.js', function: 'f', parameters: '' }).parameters, '');+ // Dataverse writes parameters="" itself, so an absent value is the empty string, not a dropped attribute.+ assert.strictEqual(attrsOf({ event: 'onsave', library: 'l.js', function: 'f', parameters: null }).parameters, '');+});diff --git a/plugins/model-apps/scripts/tests/build-model-app.test.js b/plugins/model-apps/scripts/tests/build-model-app.test.jsindex 802c47ba0..61a2a5fe8 100644--- a/plugins/model-apps/scripts/tests/build-model-app.test.js+++ b/plugins/model-apps/scripts/tests/build-model-app.test.js@@ -9,6 +9,7 @@ const fs = require('node:fs');const { buildModelApp, isTransientHalt, discoverOpDiffState, parseLanguageCode } = require(path.join(__dirname, '..', 'build-model-app.js'));const { resolveLanguageCode } = require(path.join(__dirname, '..', 'lib', 'entity-provision.js'));const { validateAppSpec, normalizeLanguageCode } = require(path.join(__dirname, '..', 'lib', 'app-spec.js'));+const { readProvisionedLanguages } = require(path.join(__dirname, '..', 'lib', 'dataverse-auth.js'));const desk = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'samples', 'app-spec.support-desk.json'), 'utf8')@@ -47,15 +48,15 @@ function mockSdk() {art.id = id; store[`${t}:${id}`] = art; return jclone(art);},createWebResource: async (o) => { calls.push(['createWebResource', o.name]); return { id: `wr-${++idc}`, name: o.name }; },- pushArtifact: async (t, id) => ({ type: t, id, success: true }),+ pushArtifact: async (t, id) => ({ type: t, id, saved: true, shipped: false, publish: { kind: 'notRequested' } }),fetchArtifact: async (t, id) => { if (!store[`${t}:${id}`]) store[`${t}:${id}`] = t === 'form' ? seedForm(id) : t === 'app' ? { id, siteMap: { areas: [] } } : { id, columns: [] }; return store[`${t}:${id}`]; },- getArtifact: (t, id) => store[`${t}:${id}`] || { id, columns: [] },- addElement: (t, id, ptr, el) => { const a = store[`${t}:${id}`] || (store[`${t}:${id}`] = { id }); const arr = jpGet(a, ptr); if (Array.isArray(arr)) arr.push(jclone(el)); return jclone(a); },- updateElement: (t, id, ptr, patch) => { const a = store[`${t}:${id}`] || (store[`${t}:${id}`] = { id }); jpSet(a, ptr, jclone(patch)); return jclone(a); },- removeElement: (t, id, ptr) => { const a = store[`${t}:${id}`]; if (a) jpRemove(a, ptr); return jclone(a || { id }); },+ getArtifact: async (t, id) => { await Promise.resolve(); return store[`${t}:${id}`] || { id, columns: [] }; },+ addElement: async (t, id, ptr, el) => { await Promise.resolve(); const a = store[`${t}:${id}`] || (store[`${t}:${id}`] = { id }); const arr = jpGet(a, ptr); if (Array.isArray(arr)) arr.push(jclone(el)); return jclone(a); },+ updateElement: async (t, id, ptr, patch) => { await Promise.resolve(); const a = store[`${t}:${id}`] || (store[`${t}:${id}`] = { id }); jpSet(a, ptr, jclone(patch)); return jclone(a); },+ removeElement: async (t, id, ptr) => { await Promise.resolve(); const a = store[`${t}:${id}`]; if (a) jpRemove(a, ptr); return jclone(a || { id }); },updateRecord: async () => undefined,addSolutionComponent: async () => undefined,- publishArtifact: async () => undefined,+ publishArtifact: async (type, id) => ({ type, id, shipped: true, publish: { kind: 'verified' } }),findArtifact: async (kind, identity) => null,};return { sdk, calls };@@ -422,7 +423,7 @@ test('discoverOpDiffState resolves an explicit-layout form by (entity, name, TYPreturn [{ publisherid: 'pub-1' }];},fetchArtifact: async () => ({ id: 'main-form-1' }),- getArtifact: () => ({ id: 'main-form-1', tabs: [] }),+ getArtifact: async () => { await Promise.resolve(); return { id: 'main-form-1', tabs: [] }; },};const spec = {solution: { uniqueName: 'S', publisherPrefix: 'zava' },@@ -709,3 +710,425 @@ test('a supplied-but-invalid language override is reported, not silently discardawait resolveLanguageCode({ provision: { queryRecords: async () => [{ languagecode: 1031 }] }, spec: {}, warn: (m) => w3.push(m) });assert.deepStrictEqual(w3, [], 'omitting the override is not a problem and must not warn');});++// #456: the two flag spellings are aliases, so passing both with DIFFERENT values means the user+// believes one is in effect and is wrong about which. `a ?? b` silently prefers the kebab form and+// discards the other, producing a build nobody asked for with no indication why.+test('a conflicting --language-code / --languageCode pair is rejected, not silently resolved', () => {+ const { readAliasedFlag } = require(path.join(__dirname, '..', 'lib', 'dataverse-auth.js'));+ assert.throws(+ () => readAliasedFlag({ 'language-code': '1031', languageCode: '1036' }, 'language-code', 'languageCode'),+ /disagree/,+ 'two different values must be an error'+ );+ // Agreeing duplicates are harmless, and either alone is fine.+ assert.strictEqual(readAliasedFlag({ 'language-code': '1031', languageCode: '1031' }, 'language-code', 'languageCode'), '1031');+ assert.strictEqual(readAliasedFlag({ 'language-code': '1031' }, 'language-code', 'languageCode'), '1031');+ assert.strictEqual(readAliasedFlag({ languageCode: '1036' }, 'language-code', 'languageCode'), '1036');+ assert.strictEqual(readAliasedFlag({}, 'language-code', 'languageCode'), undefined);+ // Surrounding whitespace is never meaningful in a shell argument, so a pair that differs only by+ // padding is the SAME request and must not be rejected. The un-trimmed value is still what gets+ // returned — normalizing is the caller's job.+ assert.strictEqual(readAliasedFlag({ 'language-code': ' 1031 ', languageCode: '1031' }, 'language-code', 'languageCode'), ' 1031 ');+ // But value-domain equivalence stays a conflict: this helper is domain-agnostic and cannot know+ // that '01031' and '1031' mean the same LCID (for an id flag, '007' and '7' would not). A loud+ // error the user fixes in seconds beats a silent guess at which spelling wins.+ assert.throws(+ () => readAliasedFlag({ 'language-code': '1031', languageCode: '01031' }, 'language-code', 'languageCode'),+ /disagree/,+ 'leading zeros are not collapsed — the helper has no value domain to collapse them in'+ );+});++// #456 item 1: an EXPLICIT language override that the organization has not provisioned must fail+// fast and say so.+//+// Live-verified premise, against a 1033-only org writing labels at LanguageCode 1036:+// * EntityDefinitions create -> HTTP 204, label silently stored at 1033+// * GlobalOptionSetDefinitions -> HTTP 204, label silently stored at 1033+// * DateTime / Memo column create -> HTTP 400 "The language code 1036 is not a valid language+// for this organization"+// So without this guard the build neither fails cleanly nor succeeds: it creates the table with+// silently wrong labels and then dies on the first DateTime or Memo column, phases away from the+// flag that caused it, leaving a half-provisioned data model.+//+// Only explicit overrides are checked. The org's own base language is provisioned by definition,+// so probing it would cost a round trip to learn nothing.+test('an explicit --language-code that is not provisioned halts, naming the provisioned set', async () => {+ const provisionedLanguages = async () => [1033, 1031];+ await assert.rejects(+ () => resolveLanguageCode({ provision: {}, spec: {}, languageCode: 1036, provisionedLanguages }),+ (err) => {+ assert.match(err.message, /1036 is not provisioned/, 'names the rejected LCID');+ assert.match(err.message, /1033, 1031/, 'names what IS provisioned so the user can pick one');+ assert.match(err.message, /--language-code/, 'names the input that caused it');+ // The message must describe what Dataverse ACTUALLY does. It is inconsistent -- some writes are+ // silently coerced to the base language, DateTime/Memo columns are rejected -- and a message+ // claiming only one of those sends the user looking for the wrong symptom.+ assert.match(err.message, /silently stored under the organization's base language/,+ 'explains the silent-coercion half');+ assert.match(err.message, /DateTime and Memo columns are rejected/,+ 'explains the hard-failure half');+ assert.match(err.message, /stop partway through the columns/,+ 'warns that the failure leaves a half-provisioned data model');+ assert.strictEqual(err.name, 'BuildHalt');+ return true;+ }+ );+});++test('a spec languageCode that is not provisioned halts too, labelled as the spec field', async () => {+ const provisionedLanguages = async () => [1033];+ await assert.rejects(+ () => resolveLanguageCode({ provision: {}, spec: { languageCode: 1036 }, provisionedLanguages }),+ (err) => {+ // The label must distinguish the two explicit sources -- telling someone to change a flag they+ // never passed sends them looking in the wrong place.+ assert.match(err.message, /^languageCode 1036 is not provisioned/, 'labelled as the spec field, not the flag');+ return true;+ }+ );+});++test('an explicit language that IS provisioned passes through untouched', async () => {+ const lc = await resolveLanguageCode({+ provision: {}, spec: {}, languageCode: 1031,+ provisionedLanguages: async () => [1033, 1031],+ });+ assert.strictEqual(lc, 1031);+});++test('the org base language is never probed -- it is provisioned by definition', async () => {+ // A round trip that cannot change the answer is pure latency on the common path, where no override+ // was given at all.+ let probed = 0;+ const lc = await resolveLanguageCode({+ provision: { queryRecords: async () => [{ languagecode: 1031 }] },+ spec: {},+ provisionedLanguages: async () => { probed += 1; return [1033]; },+ });+ assert.strictEqual(lc, 1031, 'the org language is still resolved');+ assert.strictEqual(probed, 0, 'no provisioned-languages probe on the no-override path');+});++// The probe is a diagnostic: it exists to turn a silently-ignored override into a clear message. If+// it cannot answer, the build must proceed EXACTLY as it did before -- a diagnostic that can fail a+// build is worse than no diagnostic.+test('a failing or unhelpful provisioned-languages probe never blocks the build', async () => {+ const cases = [+ ['throws', async () => { throw new Error('403 forbidden'); }],+ ['null', async () => null],+ ['empty list', async () => []],+ ['non-array', async () => ({ RetrieveProvisionedLanguages: [1033] })],+ ['absent', undefined],+ ['not a function', 1033],+ ];+ for (const [name, provisionedLanguages] of cases) {+ const lc = await resolveLanguageCode({ provision: {}, spec: {}, languageCode: 1036, provisionedLanguages });+ assert.strictEqual(lc, 1036, `probe "${name}" must not block; got ${lc}`);+ }+});++// readProvisionedLanguages is the transport half, and its single most dangerous failure mode is+// reading a non-2xx envelope as "zero languages provisioned" -- indistinguishable from a real empty+// list, and it would reject every otherwise-valid LCID. dataverseRequest resolves { status, data }+// for EVERY response rather than throwing, so the status gate is the only thing preventing that.+test('readProvisionedLanguages returns null (not []) for a non-2xx response', async () => {+ // Live-verified 200 shape:+ // { status: 200, data: { '@odata.context': '...', RetrieveProvisionedLanguages: [1033] } }+ const responses = {+ ok: { status: 200, data: { '@odata.context': 'x', RetrieveProvisionedLanguages: [1033, 1031] } },+ forbidden: { status: 403, data: { error: { code: '0x80072560', message: 'no access' } } },+ notFound: { status: 404, data: { error: { message: 'Resource not found' } } },+ serverError: { status: 500, data: 'Internal Server Error' },+ empty200: { status: 200, data: {} },+ // Status is authoritative, NOT payload shape. This case is the only one the status gate alone+ // decides -- every other error body simply lacks the key, so the shape check below would have+ // caught it anyway. Asserting it keeps the gate from being refactored away as "redundant".+ forbiddenButShaped: { status: 403, data: { RetrieveProvisionedLanguages: [1033] } },+ };+ const call = (key) => readProvisionedLanguages('https://contoso.crm.dynamics.com', async () => responses[key]);++ assert.deepStrictEqual(await call('ok'), [1033, 1031]);+ for (const bad of ['forbidden', 'notFound', 'serverError']) {+ assert.strictEqual(await call(bad), null, `HTTP error "${bad}" must read as unknown, never as an empty list`);+ }+ assert.strictEqual(+ await call('forbiddenButShaped'), null,+ 'a non-2xx must be rejected on STATUS even when the body happens to carry a well-shaped array'+ );+ assert.strictEqual(await call('empty200'), null, 'a 200 with no payload is also "unknown"');+ // A transport that throws is unknown too -- never a build failure.+ assert.strictEqual(+ await readProvisionedLanguages('https://contoso.crm.dynamics.com', async () => { throw new Error('ENOTFOUND'); }),+ null+ );+});++// The OTHER way this diagnostic can break a build, and the more dangerous one because the status+// gate above does not touch it: a 2xx whose ARRAY carries values that are not LCIDs.+//+// `Number(null)` and `Number('')` are both 0 -- finite, so a `Number.isFinite` filter kept them.+// The result was a NON-EMPTY list of garbage, and `checkProvisioned` treats any non-empty list as+// authoritative (`entity-provision.js`: `if (!Array.isArray(list) || !list.length) return lcid`).+// So a malformed payload rejected every genuinely valid LCID and HALTED the build -- the exact+// inverse of the fail-soft contract this function documents.+test('readProvisionedLanguages never returns a non-empty list of non-LCIDs (it would halt builds)', async () => {+ const call = (payload) => readProvisionedLanguages(+ 'https://contoso.crm.dynamics.com',+ async () => ({ status: 200, data: { RetrieveProvisionedLanguages: payload } })+ );++ // Each of these previously produced a truthy, non-empty array and would have halted a 1033 build.+ // `Number()` coerces all of them into something that looks like an LCID: `true`->1, `[1033]`->1033,+ // `'1e3'`->1000, `null`/`''`->0. The repo already documents why bare Number() is wrong for this+ // (app-spec.js normalizeLanguageCode); the probe now uses that same normalizer.+ for (const payload of [[null], [''], [-1], [0], [1.5], [Number.NaN], [{}], [[]], ['abc'],+ [true], [false], [[1033]], ['1e3'], ['0x40D'], [' '], ['1033abc'], [null, undefined]]) {+ assert.strictEqual(await call(payload), null,+ `payload ${JSON.stringify(payload)} yields nothing trustworthy, which is "unknown" (null)`);+ }+ // An org always has at least its base language, so an empty array is a payload we did not+ // understand -- "unknown", not "zero languages provisioned" (which would reject every LCID).+ assert.strictEqual(await call([]), null);++ // ALL-OR-NOTHING. A PARTIALLY malformed payload must NOT be silently reduced to the elements we+ // could parse: `checkProvisioned` treats any non-empty list as COMPLETE, so handing it a shorter+ // list makes it reject languages the org may actually have. An earlier version of this test+ // asserted the opposite -- it codified `[1033, null, 1031, 'x'] -> [1033, 1031]` as correct, which+ // is exactly the silent-truncation bug.+ assert.strictEqual(await call([1033, null, 1031, 'x']), null,+ 'one unparseable element makes the WHOLE payload untrustworthy');+ assert.strictEqual(await call([1031, null]), null);+ assert.strictEqual(await call([1033, true]), null);++ // Clean payloads still parse, including the numeric-string form and the boundary value.+ assert.deepStrictEqual(await call([1033, 1031]), [1033, 1031]);+ assert.deepStrictEqual(await call(['1033']), [1033]);+ assert.deepStrictEqual(await call([65535]), [65535]);+ // Above the bound the plugin enforces (see normalizeLanguageCode) -- a policy limit shared with+ // the App Spec and the CLI flag, not a claim about the width of a Windows LCID.+ assert.strictEqual(await call([65536]), null);+});++// END-TO-END on the consumer: prove the fail-soft contract at the level that actually matters --+// a build must not halt because the diagnostic returned nonsense. Asserting only on+// readProvisionedLanguages would leave the coupling to checkProvisioned untested.+test('a garbage provisioned-languages payload cannot halt a build', async () => {+ const { resolveLanguageCode } = require(path.join(__dirname, '..', 'lib', 'entity-provision.js'));+ const garbage = async () => readProvisionedLanguages(+ 'https://contoso.crm.dynamics.com',+ async () => ({ status: 200, data: { RetrieveProvisionedLanguages: [null, ''] } })+ );+ const lc = await resolveLanguageCode({ provision: {}, spec: {}, languageCode: 1033, provisionedLanguages: garbage });+ assert.strictEqual(lc, 1033, 'an unreadable probe must let the explicit LCID through, not reject it');++ // Control: a REAL list that genuinely lacks the LCID must still halt. If this stopped throwing,+ // the fix above would have disabled the check rather than hardened it.+ const real = async () => [1031, 1036];+ await assert.rejects(+ () => resolveLanguageCode({ provision: {}, spec: {}, languageCode: 1033, provisionedLanguages: real }),+ /1033 is not provisioned/,+ 'a genuine provisioned list must still be authoritative'+ );+});++// AGENTS.md convention: test the reader ITSELF, not only an injected stub. A stub that ignores its+// arguments would keep passing if the verb or the function name were mistyped -- and because the+// check is fail-soft, that typo would degrade every build to "cannot verify, proceeding" in+// silence, which is indistinguishable from an org that legitimately returns nothing. That is the+// exact failure mode this guard exists to prevent, so it must not be reachable through the guard.+test('readProvisionedLanguages calls the unbound function by name with GET', async () => {+ const calls = [];+ const out = await readProvisionedLanguages('https://contoso.crm.dynamics.com/', async (...args) => {+ calls.push(args);+ return { status: 200, data: { RetrieveProvisionedLanguages: [1033] } };+ });+ assert.deepStrictEqual(out, [1033]);+ assert.strictEqual(calls.length, 1, 'exactly one round trip');+ const [envUrl, method, apiPath] = calls[0];+ assert.strictEqual(envUrl, 'https://contoso.crm.dynamics.com/', 'the caller-supplied env url is passed through untouched');+ assert.strictEqual(method, 'GET', 'RetrieveProvisionedLanguages is a FUNCTION, not an action -- POST would 405');+ assert.strictEqual(apiPath, 'RetrieveProvisionedLanguages',+ 'unbound function name, no entity-set prefix and no $-query -- a typo here fails open and silently disables the guard');+});++// The wiring, not just the function. `deps.provisionedLanguages` crosses three seams before it+// reaches the check -- build-model-app deps -> runSdkBuild opts -> provisionDataModel -> resolve --+// and a break at any one of them silently restores the old broken behaviour with every unit test+// above still green. This is the same reason the `deps.warn` wiring test exists.+test('an unprovisioned --language-code halts the real buildModelApp path (wiring, not just the unit)', async () => {+ const { sdk } = mockSdk();+ sdk.queryRecords = async (set) => {+ if (set === 'organization') return [{ languagecode: 1033 }];+ if (set === 'solution') return [];+ return [{ publisherid: 'pub-1' }];+ };+ let probed = 0;+ const r = await buildModelApp(+ desk,+ { apply: true, env: 'https://x', languageCode: 1036 },+ { sdk, warn: () => undefined, provisionedLanguages: async () => { probed += 1; return [1033]; } }+ ).then((x) => x, (e) => e);++ assert.strictEqual(probed, 1, 'deps.provisionedLanguages must actually reach the data-model phase');+ const message = (r && r.message) || (r && r.error) || JSON.stringify(r);+ assert.match(String(message), /1036 is not provisioned/,+ `the halt must surface from the real build path; got: ${JSON.stringify(r)}`);+});++// Same wiring, other entry point: provision-entities.js is the genpage data-model path and builds+// its own deps object, so it can regress independently of build-model-app.js.+test('an unprovisioned languageCode halts the real provisionEntities path too', async () => {+ const { provisionEntities } = require(path.join(__dirname, '..', 'provision-entities.js'));+ const input = {+ solution: { uniqueName: 'Default', publisherPrefix: 'cr' },+ entities: [{ schemaName: 'cr_a', displayName: 'A', pluralName: 'As', primaryAttribute: { schemaName: 'cr_name' }, columns: [] }],+ relationships: [],+ languageCode: 1036,+ };+ const provision = {+ queryRecords: async (set) => (set === 'organization' ? [{ languagecode: 1033 }] : [{ solutionid: 's', publisherid: 'p' }]),+ createPublisher: async () => ({ id: 'p' }),+ createSolution: async () => ({ id: 's' }),+ };+ let probed = 0;+ const r = await provisionEntities(input, { apply: true }, {+ sdk: mockSdk().sdk, provision, warn: () => undefined,+ provisionedLanguages: async () => { probed += 1; return [1033]; },+ }).then((x) => x, (e) => e);++ assert.strictEqual(probed, 1, 'deps.provisionedLanguages must reach the genpage data-model path');+ const message = (r && r.message) || (r && r.error) || JSON.stringify(r);+ assert.match(String(message), /1036 is not provisioned/,+ `the halt must surface from provisionEntities; got: ${JSON.stringify(r)}`);+});++// `readOrgLanguageCode` is the #455 counterpart to `readProvisionedLanguages`: it answers "what is+// this organization's base language" at TRANSPORT level, because `MakerSdkOptions.languageCode` is a+// construction-time option and the SDK that would normally read it does not exist yet.+//+// Its dangerous failure mode is the same one, and it is worth stating: `dataverseRequest` resolves+// { status, data } for EVERY HTTP response rather than throwing, so without a status gate an error+// envelope parses as "no rows" and silently becomes the 1033 fallback — the exact wrong answer in+// the non-English org this whole line of work exists for.+test('readOrgLanguageCode returns null (not a fallback) for a non-2xx response', async () => {+ const { readOrgLanguageCode } = require(path.join(__dirname, '..', 'lib', 'dataverse-auth.js'));+ // Live-verified 200 shape:+ // { status: 200, data: { '@odata.context': '...', value: [ { languagecode: 1033, organizationid: '…' } ] } }+ const responses = {+ ok: { status: 200, data: { value: [{ '@odata.etag': 'W/"1"', languagecode: 1031, organizationid: 'x' }] } },+ forbidden: { status: 403, data: { error: { message: 'no access' } } },+ unauthorized: { status: 401, data: null },+ serverError: { status: 500, data: 'Internal Server Error' },+ empty: { status: 200, data: { value: [] } },+ noValue: { status: 200, data: {} },+ // A 4xx whose body happens to be well-shaped: decided by STATUS alone, like the sibling reader.+ forbiddenButShaped: { status: 403, data: { value: [{ languagecode: 1031 }] } },+ };+ const call = (k) => readOrgLanguageCode('https://contoso.crm.dynamics.com', async () => responses[k]);++ assert.strictEqual(await call('ok'), 1031, 'the base language is read from value[0].languagecode');+ for (const bad of ['forbidden', 'unauthorized', 'serverError', 'empty', 'noValue']) {+ assert.strictEqual(await call(bad), null, `"${bad}" must read as unknown, never as a language`);+ }+ assert.strictEqual(await call('forbiddenButShaped'), null,+ 'a non-2xx is rejected on STATUS even when the body carries a usable row');+ assert.strictEqual(+ await readOrgLanguageCode('https://contoso.crm.dynamics.com', async () => { throw new Error('ENOTFOUND'); }),+ null, 'a throwing transport is unknown too — never a build failure'+ );+});++test('readOrgLanguageCode rejects values that are not real LCIDs', async () => {+ // An LCID is a 16-bit value. A malformed or out-of-range number reaching the SDK constructor would+ // stamp every FormXML label with a language Dataverse cannot serve, so garbage must read as+ // "unknown" and fall back, not be passed through.+ const { readOrgLanguageCode } = require(path.join(__dirname, '..', 'lib', 'dataverse-auth.js'));+ const at = (languagecode) => readOrgLanguageCode('https://x', async () => ({ status: 200, data: { value: [{ languagecode }] } }));+ for (const bad of [0, -1, 65536, 1e9, null, undefined, 'de-DE', '', NaN, 1033.5, {}, []]) {+ assert.strictEqual(await at(bad), null, `languagecode=${JSON.stringify(bad)} must be rejected`);+ }+ // Numeric strings are accepted — Dataverse has returned both shapes for Number-typed columns.+ assert.strictEqual(await at('1036'), 1036, 'a numeric string is a valid LCID');+ assert.strictEqual(await at(65535), 65535, 'the 16-bit boundary is valid');+});++test('readOrgLanguageCode queries the PLURAL entity set', async () => {+ // The singular `organization` 404s on the Web API — a live-verified trap that already cost this+ // project once. A stub that ignores its arguments would never catch the regression, so assert the+ // request itself.+ const { readOrgLanguageCode } = require(path.join(__dirname, '..', 'lib', 'dataverse-auth.js'));+ const calls = [];+ await readOrgLanguageCode('https://contoso.crm.dynamics.com', async (...args) => {+ calls.push(args);+ return { status: 200, data: { value: [{ languagecode: 1033 }] } };+ });+ assert.strictEqual(calls.length, 1, 'exactly one round trip');+ const [envUrl, method, apiPath] = calls[0];+ assert.strictEqual(envUrl, 'https://contoso.crm.dynamics.com');+ assert.strictEqual(method, 'GET');+ assert.match(apiPath, /^organizations\?/, 'PLURAL entity set — the singular form 404s');+ assert.match(apiPath, /\$select=languagecode/, 'projects only the column it needs');+ assert.match(apiPath, /\$top=1/, 'one row is enough; there is exactly one organization row');+});++// The BLOCKER this file exists to prevent: `buildModelApp` builds a FRESH literal for `runBuild`+// rather than spreading `opts`, so a field added to `opts` in `main()` is silently dropped unless it+// is forwarded by hand. `preResolvedLanguageCode` was, in exactly that way, and nothing caught it —+// the only other test touching it calls `provisionDataModel` directly, bypassing this seam entirely.+//+// Why the drop matters rather than merely wasting a round trip: without the pre-resolved value the+// data-model phase re-resolves, and `resolveLanguageCode` falls back to 1033 when the org read+// fails. On a transient failure (429, socket timeout, token refresh mid-flight) the SDK is already+// baked at the resolved LCID while the columns land at 1033 — a split-language app, which is the+// precise failure this threading exists to prevent.+test('buildModelApp forwards preResolvedLanguageCode to the build (the literal drops what it does not name)', async () => {+ const seen = [];+ const r = await buildModelApp(+ desk,+ // Deliberately CONTRADICTORY: if the pre-resolved value is forwarded it wins outright. If it is+ // dropped, the spec/flag value or the org read decides — and the assertion below names which.+ { apply: true, env: 'https://x', languageCode: 1031, preResolvedLanguageCode: 3082 },+ {+ sdk: (() => {+ const { sdk } = mockSdk();+ sdk.queryRecords = async (set) => {+ if (set === 'organization') return [{ languagecode: 1036 }];+ if (set === 'solution') return [];+ return [{ publisherid: 'pub-1' }];+ };+ const origColumn = sdk.createColumn;+ sdk.createColumn = async (l, o) => { seen.push(o); return origColumn ? origColumn(l, o) : { logicalName: 'x', metadataId: 'c' }; };+ return sdk;+ })(),+ warn: () => undefined,+ }+ );+ assert.ok(r.ok, JSON.stringify(r.errors || []));+ const withLang = seen.filter((o) => o && o.languageCode !== undefined);+ assert.ok(withLang.length > 0, 'the build created label-bearing columns');+ for (const o of withLang) {+ assert.strictEqual(o.languageCode, 3082,+ 'the PRE-RESOLVED language must reach the data-model phase — 1031 means the flag won, 1036 means the org read won, undefined means the literal dropped it');+ }+});++// The stale-warning regression. `--language-code` used to be consumed only by `data-model`, so the+// warning said so. Since #455 the SDK also stamps forms, dashboards and sitemap titles, and a+// warning that tells a user their flag was ignored — while the build is faithfully applying it — is+// worse than no warning, because it stops them investigating a real problem.+test('--language-code only warns "no effect" for phases that genuinely create no labels', () => {+ const src = fs.readFileSync(path.join(__dirname, '..', 'build-model-app.js'), 'utf8');+ const m = /const LANGUAGE_CONSUMING_PHASES = \[([^\]]+)\]/.exec(src);+ assert.ok(m, 'the phase list is declared as a named constant, not inlined into the condition');+ const listed = m[1].split(',').map((s) => s.trim().replace(/['"]/g, '')).filter(Boolean);+ for (const phase of ['data-model', 'forms', 'dashboards', 'app-shell']) {+ assert.ok(listed.includes(phase),+ `'${phase}' stamps an authoring language and must not be reported as unaffected by --language-code`);+ }+ // Phases that create no labels must NOT be listed, or the warning never fires when it should.+ for (const phase of ['publish', 'sample-data', 'pages']) {+ assert.ok(!listed.includes(phase), `'${phase}' creates no labels and must not suppress the warning`);+ }+});diff --git a/plugins/model-apps/scripts/tests/business-rule-real-bundle.test.js b/plugins/model-apps/scripts/tests/business-rule-real-bundle.test.jsnew file mode 100644index 000000000..87ce43002--- /dev/null+++ b/plugins/model-apps/scripts/tests/business-rule-real-bundle.test.js@@ -0,0 +1,166 @@+'use strict';+// REAL BUNDLE: the business-rule authoring contract.+//+// The plugin does not author business rules yet — this pins what the vendored SDK can actually do,+// so the feature can be built against a verified contract instead of a reading of the types, and so+// a re-vendor that breaks the path fails here rather than in a user's build.+//+// Why this is worth having before the feature exists: business rules were deferred on the belief+// that they could not be verified at all, because the `*ProcessWithWfomJson` bound actions were+// absent on the test orgs available at the time. That premise turned out to be wrong — on current+// orgs `$metadata` DOES declare all three (`CreateProcessWithWfomJson`, `UpdateProcessWithWfomJson`,+// `RetrieveProcessWithWfomJson`).+//+// But the API is declared and NOT FUNCTIONAL, which is a different and better-evidenced blocker.+// Measured across 6 orgs: `RetrieveProcessWithWfomJson` — a bound FUNCTION whose only parameter is+// the bound entity, so there is nothing a caller can get wrong — returns HTTP 400 (0x80040216,+// "An unexpected error occurred") on an UNTOUCHED, server-created rule in all six. Reading a rule+// the platform itself wrote fails identically to writing one, which rules out our payload.+//+// Eliminated along the way, each on its own: the table being unpublished (PublishXml returned 204,+// still 400), wrong field logical names (read back from `Attributes` and confirmed), and anything+// specific to a brand-new custom table (the same rule on OOB `account` fails too). An earlier+// hypothesis of mine — that the first 400 was caused by pushing an EMPTY rule (null rootCondition)+// — is DISPROVEN: a complete rule with condition, clause and action fails exactly the same way.+//+// So what remains proven here is the SDK half, which is genuinely useful: the authoring contract and+// the wire payload. The environmental blocker is tracked separately, and the cheapest gate for any+// future attempt is a single `RetrieveProcessWithWfomJson` returning 200 on an existing rule.+//+// Two traps worth recording, both of which cost real time:+// * `$metadata` is XML. `dataverseRequest` sends `Accept: application/json`, so it answers 415 —+// which reads exactly like "the actions are absent" if the status is not checked.+// * The three actions are BOUND to `workflow`. Probing them as UNBOUND posts returns 404 and+// proves nothing about whether they exist.+const test = require('node:test');+const assert = require('node:assert');+const os = require('node:os');+const path = require('node:path');+const fs = require('node:fs');++const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');+const dirs = [];++function sdkWithCapture() {+ const { createMakerSdk } = require(BUNDLE);+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'br-'));+ dirs.push(dir);+ const writes = [];+ const httpClient = {+ get: async () => ({ status: 200, headers: {}, body: {} }),+ post: async (url, body) => {+ writes.push({ verb: 'post', url: String(url), body });+ return { status: 200, headers: {}, body: { ProcessId: '44444444-4444-4444-4444-444444444444' } };+ },+ patch: async (url, body) => { writes.push({ verb: 'patch', url: String(url), body }); return { status: 204, headers: {}, body: {} }; },+ put: async () => ({ status: 204, headers: {}, body: {} }),+ delete: async () => ({ status: 204, headers: {}, body: {} }),+ };+ const sdk = createMakerSdk({ workspacePath: dir, instanceUrl: 'https://contoso.crm.dynamics.com', httpClient });+ sdk.initWorkspace();+ return { sdk, writes };+}++// "IF account.name equals 'x' THEN hide fax" — the smallest rule that is actually meaningful.+// A rule with a null rootCondition is what the server rejected live, so the fixture is deliberately+// a complete one: condition + clause + a true-branch action.+function authorRule(sdk) {+ const art = sdk.createArtifact('businessRule', {+ name: 'Contract Rule', entityLogicalName: 'account', scope: 'Entity', status: 'Draft',+ });+ return { art, condition: {+ id: 'c1', displayName: 'If name is x', logic: 'AND',+ clauses: [{ id: 'cl1', field: 'name', fieldDisplayName: 'Name', operator: 'Equals', valueType: 'Value', value: 'x' }],+ trueBranch: [{ id: 'a1', kind: 'action', type: 'SetVisibility', displayName: 'Hide Fax', field: 'fax', value: 'false' }],+ falseBranch: [],+ } };+}++test.after(() => { for (const d of dirs) fs.rmSync(d, { recursive: true, force: true }); });++test('REAL BUNDLE: a business rule is authored through the generic artifact lifecycle', async () => {+ // There is no dedicated business-rule API on MakerSdkApi — it is createArtifact -> updateElement+ // -> pushArtifact, like every other artifact. Pinning that is what tells a future implementer+ // which surface to build against.+ const { sdk } = sdkWithCapture();+ const { art, condition } = authorRule(sdk);+ assert.ok(art && art.id, 'createArtifact returns an artifact with an id');+ assert.deepStrictEqual(+ Object.keys(art).sort(),+ ['description', 'entityLogicalName', 'id', 'name', 'rootCondition', 'scope', 'status'],+ 'the typed authoring surface is the documented one'+ );+ await sdk.updateElement('businessRule', art.id, '/rootCondition', condition);+ const pushed = await sdk.pushArtifact('businessRule', art.id);+ assert.strictEqual(pushed.saved, true, 'the push commits');+ // No publish was requested, so `shipped` must be false — saved is not shipped.+ assert.strictEqual(pushed.shipped, false);+ assert.strictEqual(pushed.publish.kind, 'notRequested');+});++test('REAL BUNDLE: the push targets the BOUND CreateProcessWithWfomJson action', async () => {+ // The boundness matters twice over: it is why an unbound probe 404s and proves nothing, and a+ // re-vendor that switched to an unbound or renamed endpoint would silently 404 at build time.+ const { sdk, writes } = sdkWithCapture();+ const { art, condition } = authorRule(sdk);+ await sdk.updateElement('businessRule', art.id, '/rootCondition', condition);+ await sdk.pushArtifact('businessRule', art.id);++ const call = writes.find((w) => /CreateProcessWithWfomJson/.test(w.url));+ assert.ok(call, 'a CreateProcessWithWfomJson call was issued; got ' + JSON.stringify(writes.map((w) => w.url)));+ assert.match(call.url, /workflows\(0{8}-0{4}-0{4}-0{4}-0{12}\)\/Microsoft\.Dynamics\.CRM\.CreateProcessWithWfomJson/,+ 'a CREATE binds to the all-zero workflow id — that is the documented create pattern');+ assert.deepStrictEqual(Object.keys(call.body).sort(), ['Entity', 'WfomJson'],+ 'the action takes exactly Entity + WfomJson');+});++test('REAL BUNDLE: the SDK compiles typed input into server WfomJson (not a passthrough)', async () => {+ // The whole value of the typed surface is that a caller writes a condition tree and the SDK emits+ // the server's workflow-object-model JSON. If it ever became a passthrough, callers would have to+ // hand-write WfomJson — a silent, very expensive contract change.+ const { sdk, writes } = sdkWithCapture();+ const { art, condition } = authorRule(sdk);+ await sdk.updateElement('businessRule', art.id, '/rootCondition', condition);+ await sdk.pushArtifact('businessRule', art.id);++ const call = writes.find((w) => /CreateProcessWithWfomJson/.test(w.url));+ const wfom = call.body.WfomJson;+ assert.strictEqual(typeof wfom, 'string', 'WfomJson is serialized as a STRING, not a nested object');+ const parsed = JSON.parse(wfom);+ // Observed server shape: a WorkflowStep root carrying the entity and a step list.+ assert.match(String(parsed.__class || ''), /WorkflowStep/, 'the root is a WorkflowStep');+ assert.strictEqual(parsed.primaryEntityName, 'account', 'the bound entity is carried into the model');+ // The authored field names must survive compilation — if they did not, the rule would be built+ // against nothing and would silently do nothing at runtime.+ assert.match(wfom, /"fax"/, 'the action target field reached the compiled model');+ assert.ok(wfom.length > 500, `a real rule compiles to a substantial model; got ${wfom.length} chars`);++ // `Entity` is NOT the logical name — it is the full workflow ROW to create. Pinning the+ // discriminating columns is what makes this a contract test rather than a smoke test: a rule+ // written with the wrong `category` is not a business rule at all, and the wrong+ // `processtriggerscope` silently changes whether it runs on the entity or one specific form.+ // Observed shape:+ // { '@odata.type': '#Microsoft.Dynamics.CRM.workflow', name, description, workflowid,+ // category: 2, type: 1, mode: 1, scope: 4, primaryentity: 'account',+ // iscrmuiworkflow: true, processtriggerscope: 2, ondemand/subprocess/trigger*: false }+ const ent = call.body.Entity;+ assert.strictEqual(typeof ent, 'object', 'Entity is the workflow row, not a logical-name string');+ assert.match(String(ent['@odata.type'] || ''), /workflow/, 'typed as a workflow row');+ assert.strictEqual(ent.category, 2, 'category 2 is Business Rule — any other value is a different process type');+ assert.strictEqual(ent.primaryentity, 'account', 'bound to the authored entity');+ assert.strictEqual(ent.processtriggerscope, 2, "scope 'Entity' maps to processtriggerscope 2 (1 + a form id means one form)");+ assert.strictEqual(ent.iscrmuiworkflow, true, 'authored through the UI object model, not raw XAML');+});++test('REAL BUNDLE: an invalid condition is rejected at authoring time, not at the server', async () => {+ // Local validation is what turns "HTTP 400: An unexpected error occurred" — which is exactly what+ // the server returns for a malformed rule — into an actionable message. Verify it actually fires.+ const { sdk } = sdkWithCapture();+ const { art } = authorRule(sdk);+ await assert.rejects(+ async () => await sdk.updateElement('businessRule', art.id, '/rootCondition', {+ id: 'c1', displayName: '', logic: 'XOR', clauses: [], trueBranch: [], falseBranch: [],+ }),+ 'an unsupported logic operator must be caught locally rather than sent to the server'+ );+});diff --git a/plugins/model-apps/scripts/tests/business-rules.test.js b/plugins/model-apps/scripts/tests/business-rules.test.jsnew file mode 100644index 000000000..b3a128e49--- /dev/null+++ b/plugins/model-apps/scripts/tests/business-rules.test.js@@ -0,0 +1,414 @@+'use strict';+// `businessRules[]` — the App Spec surface over the SDK's business-rule compiler.+//+// Three layers, because a failure in any one of them is silent in a different way:+// 1. VALIDATION — the spec surface mirrors the SDK's supported slice exactly. Anything outside it+// throws a ValidationError deep inside the push, so catching it here names the field instead.+// 2. MAPPING — `businessRuleDef` produces the SDK's node shape. This is the dangerous one: the+// obvious shape (operator/lhs/rhs/thenActions) is silently MERGED and ignored, producing a rule+// that deploys, activates, and never fires. See sdk-uptake-contract.test.js.+// 3. REAL BUNDLE — the mapped def is pushed through the shipped SDK and the compiled XAML is+// inspected. Only this proves the author's columns actually reach the platform.+const test = require('node:test');+const assert = require('node:assert');+const os = require('node:os');+const path = require('node:path');+const fs = require('node:fs');++const { validateAppSpec } = require('../lib/app-spec.js');+const { businessRuleDef } = require('../lib/sdk-build.js');++const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');+const dirs = [];+test.after(() => { for (const d of dirs) fs.rmSync(d, { recursive: true, force: true }); });++// Minimal spec that is valid on its own, so a validation failure below is always about the rule.+function specWith(rules) {+ return {+ solution: { uniqueName: 'BR', displayName: 'BR', publisherPrefix: 'new' },+ app: { name: 'BR App', description: '' },+ entities: [{+ schemaName: 'new_ticket', displayName: 'Ticket', pluralName: 'Tickets',+ primaryAttribute: { schemaName: 'new_subject', displayName: 'Subject' },+ columns: [+ { schemaName: 'new_status', displayName: 'Status', type: 'Choice', options: ['New', 'Closed'] },+ { schemaName: 'new_notes', displayName: 'Notes', type: 'Memo' },+ { schemaName: 'new_owner', displayName: 'Owner', type: 'Text' },+ ],+ }],+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Records', subAreas: [{ entity: 'new_ticket', title: 'Tickets' }] }] }] },+ businessRules: rules,+ };+}+const RULE = {+ entity: 'new_ticket', name: 'Hide notes when closed',+ conditions: [{ field: 'new_status', operator: 'Equals', value: '100000001', dataType: 'Picklist' }],+ actions: [{ type: 'SetVisibility', field: 'new_notes', visible: false }],+};+const errorsFor = (rules) => (validateAppSpec(specWith(rules), { profile: 'plan' }).errors || []);++// --- 1. validation ----------------------------------------------------------------------------++test('a well-formed business rule validates', () => {+ const v = validateAppSpec(specWith([RULE]), { profile: 'plan' });+ assert.strictEqual(v.ok, true, JSON.stringify(v.errors));+});++test('a rule must name a known entity and its own columns', () => {+ assert.ok(errorsFor([{ ...RULE, entity: 'new_nope' }]).some((e) => /unknown entity/.test(e)));+ // A column that does not exist on the table is the silent case that matters: the platform accepts+ // such a rule and it simply never fires, so nothing downstream would catch it.+ assert.ok(errorsFor([{ ...RULE, conditions: [{ field: 'new_ghost', operator: 'Equals', value: '1' }] }])+ .some((e) => /'new_ghost', which is not a column on new_ticket/.test(e)));+ assert.ok(errorsFor([{ ...RULE, actions: [{ type: 'SetVisibility', field: 'new_ghost', visible: false }] }])+ .some((e) => /not a column on new_ticket/.test(e)));+});++test('operators and actions are constrained to the slice the SDK can compile', () => {+ // Outside the slice the SDK throws mid-push; the point of validating here is to name the field.+ assert.ok(errorsFor([{ ...RULE, conditions: [{ field: 'new_status', operator: 'BeginsWith', value: 'x' }] }])+ .some((e) => /condition operator must be one of/.test(e)));+ assert.ok(errorsFor([{ ...RULE, actions: [{ type: 'ShowErrorMessage', field: 'new_notes', message: 'x' }] }])+ .some((e) => /action type must be one of/.test(e)));+ for (const operator of ['Equals', 'DoesNotEqual']) {+ assert.deepStrictEqual(errorsFor([{ ...RULE, conditions: [{ field: 'new_status', operator, value: '1' }] }]), []);+ }+});++test('presence operators are rejected — they compile to XAML the platform 500s on', () => {+ // LIVE-MEASURED: `ContainsData` / `DoesNotContainData` answer "Error generating UiData" (HTTP 500)+ // on every column type and in both directions, while Equals/DoesNotEqual succeed in the same run.+ // The error must name the platform failure, not pretend the operator is unrecognised — an author+ // reaching for ContainsData has written something reasonable that we simply cannot deploy.+ for (const operator of ['ContainsData', 'DoesNotContainData']) {+ const errs = errorsFor([{ ...RULE, conditions: [{ field: 'new_notes', operator }] }]);+ assert.ok(errs.some((e) => /is not usable/.test(e) && /Error generating UiData/.test(e) && /issues\/481/.test(e)),+ `${operator} must be rejected with the platform reason: ${JSON.stringify(errs)}`);+ }+});++test('comparison operators must carry a value', () => {+ assert.ok(errorsFor([{ ...RULE, conditions: [{ field: 'new_status', operator: 'Equals' }] }])+ .some((e) => /needs a value/.test(e)));+});++test('a boolean action payload must be a real boolean', () => {+ // "false" is truthy, so coercing would invert the author's intent silently — the same trap+ // `app.newLook` validation closes.+ for (const bad of ['false', 'true', 0, 1]) {+ assert.ok(errorsFor([{ ...RULE, actions: [{ type: 'SetVisibility', field: 'new_notes', visible: bad }] }])+ .some((e) => /must be a boolean/.test(e)), `visible=${JSON.stringify(bad)} must be rejected`);+ }+ assert.deepStrictEqual(errorsFor([{ ...RULE, actions: [{ type: 'LockUnlock', field: 'new_notes', lock: true }] }]), []);+ assert.ok(errorsFor([{ ...RULE, actions: [{ type: 'LockUnlock', field: 'new_notes' }] }])+ .some((e) => /needs 'lock'/.test(e)));+});++test('a rule with no conditions or no actions is rejected', () => {+ // Both compile to a rule that deploys and does nothing — the failure mode this whole surface exists+ // to make impossible.+ assert.ok(errorsFor([{ ...RULE, conditions: [] }]).some((e) => /conditions\[\] is required/.test(e)));+ assert.ok(errorsFor([{ ...RULE, actions: [] }]).some((e) => /actions\[\] is required/.test(e)));+});++// --- 2. mapping -------------------------------------------------------------------------------++test('businessRuleDef maps onto the SDK node shape (clauses + trueBranch), not the obvious one', () => {+ const def = businessRuleDef({+ ...RULE,+ actions: [+ { type: 'SetVisibility', field: 'new_notes', visible: false },+ { type: 'LockUnlock', field: 'new_owner', lock: true },+ { type: 'SetBusinessRequired', field: 'new_owner', required: true },+ { type: 'SetFieldValue', field: 'new_owner', value: 'unassigned' },+ ],+ });+ assert.strictEqual(def.entityLogicalName, 'new_ticket');+ assert.strictEqual(def.scope, 'Entity');+ assert.strictEqual(def.status, 'Active', 'a rule is inert until activated, so Active is the default');++ const rc = def.rootCondition;+ assert.strictEqual(rc.logic, 'AND');+ // The keys that matter. `thenActions`/`lhs`/`rhs` would be merged and ignored.+ assert.deepStrictEqual(Object.keys(rc).sort(), ['clauses', 'displayName', 'falseBranch', 'id', 'logic', 'trueBranch']);+ assert.deepStrictEqual(rc.clauses, [{+ id: 'c1', field: 'new_status', operator: 'Equals', valueType: 'Value', value: '100000001', valueWorkflowType: 'Picklist',+ }]);+ assert.deepStrictEqual(rc.trueBranch.map((a) => [a.type, a.field, a.visible ?? a.lock ?? a.required ?? a.value]), [+ ['SetVisibility', 'new_notes', false],+ ['LockUnlock', 'new_owner', true],+ ['SetBusinessRequired', 'new_owner', true],+ ['SetFieldValue', 'new_owner', 'unassigned'],+ ]);+ assert.ok(rc.trueBranch.every((a) => a.id && a.displayName), 'every action carries an id and a label');+});++test('a presence operator still MAPS correctly (the mapper is fine; the platform is not)', () => {+ // Kept because the block is a platform limitation, not a mapping bug — when #481 is fixed the+ // operator can be re-enabled in validation without touching businessRuleDef. Emitting+ // `value: undefined` would still add the key, and the compiler treats present-but-empty+ // differently from absent.+ const def = businessRuleDef({ ...RULE, conditions: [{ field: 'new_notes', operator: 'ContainsData' }] });+ assert.deepStrictEqual(Object.keys(def.rootCondition.clauses[0]).sort(), ['field', 'id', 'operator', 'valueType']);+});++// --- 3. real bundle ---------------------------------------------------------------------------++test('REAL BUNDLE: the mapped rule compiles to XAML naming the authored columns', async () => {+ const { createMakerSdk } = require(BUNDLE);+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'br-spec-'));+ dirs.push(dir);+ const calls = [];+ const sdk = createMakerSdk({+ workspacePath: dir, instanceUrl: 'https://contoso.crm.dynamics.com',+ httpClient: {+ get: async () => ({ status: 200, headers: {}, body: { value: [] } }),+ post: async (url, body) => {+ calls.push({ url, body });+ // Force the classic path so the compiled XAML is observable on the wire.+ if (/WithWfomJson/i.test(url)) return { status: 400, headers: {}, body: { error: { code: '0x80040216' } } };+ return { status: 204, headers: { 'odata-entityid': 'https://x/workflows(55555555-5555-5555-5555-555555555555)' }, body: {} };+ },+ patch: async () => ({ status: 204, headers: {}, body: {} }),+ put: async () => ({ status: 204, headers: {}, body: {} }),+ delete: async () => ({ status: 204, headers: {}, body: {} }),+ },+ });+ sdk.initWorkspace();++ const def = businessRuleDef(RULE);+ const art = sdk.createArtifact('businessRule', def);+ await sdk.updateElement('businessRule', art.id, '/rootCondition', def.rootCondition);+ const pushed = await sdk.pushArtifact('businessRule', art.id);+ assert.strictEqual(pushed.saved, true);++ const classic = calls.find((c) => /\/workflows$/.test(String(c.url)));+ assert.ok(classic, 'the classic row is written; urls: ' + JSON.stringify(calls.map((c) => c.url)));+ assert.strictEqual(classic.body.primaryentity, 'new_ticket');+ assert.strictEqual(classic.body.category, 2);+ // The assertion that matters: a well-formed but EMPTY rule would satisfy everything above.+ assert.match(classic.body.xaml, /new_status/, 'the condition column reaches the compiled XAML');+ assert.match(classic.body.xaml, /new_notes/, 'the action column reaches the compiled XAML');+});++// --- peer-review findings: verified and fixed ---------------------------------------------------++test('dataType mirrors the compiler literal-type map exactly (no DateTime)', () => {+ // The bundle's literal table is the authority. `DateTime` used to be accepted here and does NOT+ // exist there, so such a spec validated and then threw from INSIDE the push — the worst place,+ // because the bound member may already have committed a workflow row (#482), leaving an orphan+ // behind a "failed" build.+ const bundle = require('node:fs').readFileSync(BUNDLE, 'utf8');+ const i = bundle.indexOf('Picklist:{propertyType:"OptionSetValue"');+ assert.ok(i > 0, 'the literal-type map must be present in the vendored bundle');+ const seg = bundle.slice(i, i + 1200);+ const sdkTypes = [...seg.matchAll(/(\w+):\{propertyType/g)].map((m) => m[1]);+ assert.ok(!sdkTypes.includes('DateTime'), 'guard assumes the compiler has no DateTime literal');+ const { BUSINESS_RULE_DATA_TYPES } = require('../lib/app-spec.js');+ assert.deepStrictEqual([...BUSINESS_RULE_DATA_TYPES].sort(), [...sdkTypes].sort());+});++test('a DateTime dataType is rejected at the spec gate, not mid-build', () => {+ const res = validateAppSpec(specWith([{+ name: 'R', entity: 'new_ticket',+ conditions: [{ field: 'new_owner', operator: 'Equals', value: 'x', dataType: 'DateTime' }],+ actions: [{ type: 'SetVisibility', field: 'new_notes', visible: false }],+ }]));+ assert.ok(res.errors.some((e) => /dataType/i.test(e) && /DateTime/.test(e)), `expected a dataType error, got ${JSON.stringify(res.errors)}`);+});++// --- verify reconciles business rules (previously: no checks at all) ----------------------------++const { verifySpec } = require('../lib/verify-spec.js');++function ruleSpec(status) {+ const s = specWith([{+ name: 'Lock when closed', entity: 'new_ticket',+ conditions: [{ field: 'new_owner', operator: 'Equals', value: 'x', dataType: 'String' }],+ actions: [{ type: 'SetVisibility', field: 'new_notes', visible: false }],+ ...(status ? { status } : {}),+ }]);+ return s;+}+const baseReader = (workflows) => ({+ findTable: async () => ({ logicalName: 'new_ticket' }),+ findColumns: async () => [{ logicalName: 'new_status' }, { logicalName: 'new_notes' }, { logicalName: 'new_owner' }],+ queryRecords: async (entity) => (entity === 'workflow' ? workflows : []),+ sitemapXml: async () => '',+});+const ruleCheck = (r) => r.checks.find((c) => c.kind === 'business-rule');++test('verify PASSES an Active rule the spec wants Active', async () => {+ const r = await verifySpec(ruleSpec(), baseReader([{ workflowid: 'w1', statecode: 1 }]));+ assert.strictEqual(ruleCheck(r).present, true);+});++test('verify FAILS a rule that never deployed', async () => {+ const c = ruleCheck(await verifySpec(ruleSpec(), baseReader([])));+ assert.strictEqual(c.present, false);+ assert.match(c.detail, /not deployed/);+});++test('verify FAILS a rule deployed as Draft — "exists" is not "runs"', async () => {+ const c = ruleCheck(await verifySpec(ruleSpec(), baseReader([{ workflowid: 'w1', statecode: 0 }])));+ assert.strictEqual(c.present, false);+ assert.match(c.detail, /DRAFT/);+});++test('verify FAILS duplicates — the #482 residue the build cannot always remove', async () => {+ const c = ruleCheck(await verifySpec(ruleSpec(), baseReader([{ workflowid: 'w1', statecode: 1 }, { workflowid: 'w2', statecode: 1 }])));+ assert.strictEqual(c.present, false);+ assert.match(c.detail, /2 rules share this name/);+});++test('verify FAILS an ACTIVE rule the spec asks to be Draft', async () => {+ const c = ruleCheck(await verifySpec(ruleSpec('Draft'), baseReader([{ workflowid: 'w1', statecode: 1 }])));+ assert.strictEqual(c.present, false);+ assert.match(c.detail, /running/);+});++test('verify fails CLOSED when the workflow read itself errors', async () => {+ // "Could not look" must never read as "present and correct".+ const read = Object.assign(baseReader([]), {+ queryRecords: async (entity) => { if (entity === 'workflow') throw new Error('HTTP 401'); return []; },+ });+ const c = ruleCheck(await verifySpec(ruleSpec(), read));+ assert.strictEqual(c.present, false);+ assert.match(c.detail, /could not be read/);+});++// --- rebuild repairs legacy duplicates (peer-review finding) ------------------------------------+//+// Before the SDK fix, a build could leave two rows for one rule. The reuse branch queried `top: 1`+// and returned immediately, so the de-duplication sweep — which lived only on the CREATE path —+// never ran on a rebuild. Both rules kept firing forever, and because `top: 1` is unordered, the row+// adopted as "the" rule could be the faulted orphan rather than the good one.+const { runSdkBuild: runBuild } = require('../lib/sdk-build.js');++function ruleOnlySpec() {+ const s = specWith([{+ name: 'Lock when closed', entity: 'new_ticket',+ conditions: [{ field: 'new_owner', operator: 'Equals', value: 'x', dataType: 'String' }],+ actions: [{ type: 'SetVisibility', field: 'new_notes', visible: false }],+ }]);+ return s;+}++// Minimal provision double: only the workflow surface the business-rules phase touches.+function provisionWithRules(rows) {+ const calls = [];+ return {+ calls,+ provision: {+ queryRecords: async (entity, opts) => {+ if (entity === 'workflow') { calls.push(['queryRecords', entity, opts]); return rows; }+ return entity === 'solution' ? [] : [{ publisherid: 'pub-1' }];+ },+ updateRecord: async (e, id, patch) => { calls.push(['updateRecord', e, id, patch]); },+ deleteRecord: async (e, id) => { calls.push(['deleteRecord', e, id]); },+ createArtifact: () => ({ id: 'br-new' }),+ updateElement: async () => undefined,+ pushArtifact: async () => ({ id: 'br-new', saved: true, publish: { kind: 'notRequested' } }),+ addSolutionComponent: async () => undefined,+ },+ };+}++test('a rebuild REMOVES duplicates an earlier build left behind', async () => {+ const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();+ const { provision, calls } = provisionWithRules([+ { workflowid: 'keep-oldest', statecode: 1, createdon: '2026-01-01T00:00:00Z' },+ { workflowid: 'dupe-1', statecode: 1, createdon: '2026-01-01T00:00:05Z' },+ ]);+ const warnings = [];+ await runBuild(ruleOnlySpec(), {+ sdk, provisionSdk: provision, apply: true,+ phases: ['business-rules'], warn: (m) => warnings.push(m),+ });++ // The extra row is deactivated then deleted; the FIRST (oldest) row is kept.+ const deletes = calls.filter((c) => c[0] === 'deleteRecord').map((c) => c[2]);+ assert.deepStrictEqual(deletes, ['dupe-1'], `expected only the duplicate to be deleted, got ${JSON.stringify(deletes)}`);+ assert.ok(warnings.some((w) => /duplicate left by an earlier build/.test(w)), `expected a warning; got ${JSON.stringify(warnings)}`);+});++test('the reuse query is ORDERED and asks for more than one row', async () => {+ // `top: 1` unordered is what made the survivor arbitrary and hid the duplicates entirely.+ const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();+ const { provision, calls } = provisionWithRules([{ workflowid: 'only', statecode: 1, createdon: '2026-01-01T00:00:00Z' }]);+ await runBuild(ruleOnlySpec(), { sdk, provisionSdk: provision, apply: true, phases: ['business-rules'] });+ const q = calls.find((c) => c[0] === 'queryRecords');+ assert.ok(q, 'the reuse query must run');+ assert.ok(q[2].top > 1, `the reuse query must be able to SEE duplicates; top was ${q[2].top}`);+ assert.match(String(q[2].orderBy), /createdon asc/, 'oldest-first makes the surviving row deterministic');+});++test('a single existing rule is left completely alone', async () => {+ // The repair must not become a delete-happy sweep: one row is the healthy case.+ const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();+ const { provision, calls } = provisionWithRules([{ workflowid: 'only', statecode: 1, createdon: '2026-01-01T00:00:00Z' }]);+ const warnings = [];+ await runBuild(ruleOnlySpec(), { sdk, provisionSdk: provision, apply: true, phases: ['business-rules'], warn: (m) => warnings.push(m) });+ assert.strictEqual(calls.filter((c) => c[0] === 'deleteRecord').length, 0);+ assert.strictEqual(warnings.length, 0);+});++// --- the activated copy is NOT a duplicate (live-measured) --------------------------------------+//+// Activating a business rule makes Dataverse create a SECOND workflows row:+// type=1, parentworkflowid=(none) -> the definition+// type=2, parentworkflowid=<def> -> the platform's activated copy+// Measured directly: a Draft create yields 1 row; a plain PATCH to statecode 1 yields 2. A PATCH+// cannot create anything, so the platform made it, and the pair is normal for any activated process.+//+// Every business-rule query must therefore filter `type eq 1`. Without it the build tried to delete+// the activated copy (405), warned about a "duplicate" that did not exist, and verify would have+// failed EVERY active rule. The vendored SDK's own orphan probe filters the same way.+const { businessRuleFilter } = require('../lib/sdk-build.js');++test('businessRuleFilter selects the definition only', () => {+ const f = businessRuleFilter("O'Brien rule", 'CFO_WorkOrder');+ assert.match(f, /category eq 2/);+ assert.match(f, /type eq 1/, 'without `type eq 1` the activated copy is counted as a duplicate');+ assert.match(f, /primaryentity eq 'cfo_workorder'/, 'entity is lower-cased for the logical name');+ assert.match(f, /name eq 'O''Brien rule'/, "a quote in the name must be OData-escaped, not left to break the filter");+});++test('every business-rule query in build, verify and teardown filters on type', () => {+ // A guard on the SOURCE, because the three call sites are in different modules and it is the+ // omission — not a wrong value — that caused the defect. Any new query that forgets the shared+ // helper fails here.+ const fs = require('node:fs');+ const path = require('node:path');+ for (const file of ['sdk-build.js', 'verify-spec.js', 'sdk-teardown.js']) {+ const src = fs.readFileSync(path.resolve(__dirname, '..', 'lib', file), 'utf8');+ const raw = src.match(/category eq 2(?! and type eq 1)/g) || [];+ // The only permitted mention of `category eq 2` without `type eq 1` is inside businessRuleFilter+ // itself, which immediately follows it with the type clause — hence the negative lookahead above+ // matching nothing.+ assert.deepStrictEqual(raw, [], `${file} has a business-rule query that does not constrain type: ${raw.join(' | ')}`);+ }+});++test('a rule with an activated copy present is NOT reported as duplicated', async () => {+ // The reader is filtered server-side in production; this pins that verify treats a single+ // definition row as healthy rather than counting anything extra it might receive.+ const spec = specWith([{+ name: 'Lock when closed', entity: 'new_ticket',+ conditions: [{ field: 'new_owner', operator: 'Equals', value: 'x', dataType: 'String' }],+ actions: [{ type: 'SetVisibility', field: 'new_notes', visible: false }],+ }]);+ const read = {+ findTable: async () => ({ logicalName: 'new_ticket' }),+ findColumns: async () => [{ logicalName: 'new_status' }, { logicalName: 'new_notes' }, { logicalName: 'new_owner' }],+ queryRecords: async (entity, opts) => {+ if (entity !== 'workflow') return [];+ assert.match(String(opts.filter), /type eq 1/, 'verify must ask the server for definitions only');+ return [{ workflowid: 'def-1', statecode: 1 }];+ },+ sitemapXml: async () => '',+ };+ const r = await verifySpec(spec, read);+ const c = r.checks.find((x) => x.kind === 'business-rule');+ assert.strictEqual(c.present, true, `an active rule with its activated copy must PASS; detail: ${c.detail}`);+});diff --git a/plugins/model-apps/scripts/tests/column-visualization.test.js b/plugins/model-apps/scripts/tests/column-visualization.test.jsnew file mode 100644index 000000000..42a5a5dc0--- /dev/null+++ b/plugins/model-apps/scripts/tests/column-visualization.test.js@@ -0,0 +1,286 @@+'use strict';+// `entities[].columns[].visualization` — the App Spec surface over the SDK's per-column grid data+// visualization (preview).+//+// Four layers, because each fails silently in a different way:+// 1. VALIDATION — the enum must mirror the SDK's `ColumnVisualizationType` exactly. A value the+// SDK does not know throws deep inside the push; catching it here names the column.+// 2. BUILD — the write must happen for columns that ALREADY EXIST, not just freshly created ones.+// Getting that wrong makes the feature work on the first build and quietly stop on every+// rebuild, which is the hardest variant to notice.+// 3. DEGRADATION — on an environment without the preview provisioned, Dataverse 404s the+// `controlconfigurations` set. That must SKIP, not fail the data-model phase.+// 4. VERIFY — reconciliation is by VALUE. An existence-only check would pass a column deployed+// with the wrong renderer.+const test = require('node:test');+const assert = require('node:assert');+const path = require('node:path');++const { validateAppSpec, COLUMN_VISUALIZATIONS } = require('../lib/app-spec.js');+const { provisionDataModel, isVisualizationUnsupported } = require('../lib/entity-provision.js');+const { verifySpec } = require('../lib/verify-spec.js');++const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');++function specWith(columns) {+ return {+ solution: { uniqueName: 'CV', displayName: 'CV', publisherPrefix: 'new' },+ app: { name: 'CV App', description: '' },+ entities: [{+ schemaName: 'new_ticket', displayName: 'Ticket', pluralName: 'Tickets',+ primaryAttribute: { schemaName: 'new_subject', displayName: 'Subject' },+ columns,+ }],+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Records', subAreas: [{ entity: 'new_ticket', title: 'Tickets' }] }] }] },+ };+}++const SCORE = { schemaName: 'new_score', displayName: 'Score', type: 'WholeNumber' };++// ---------------------------------------------------------------- 1. validation++test('every visualization the SDK accepts is accepted by the spec', () => {+ for (const v of COLUMN_VISUALIZATIONS) {+ const res = validateAppSpec(specWith([Object.assign({}, SCORE, { visualization: v })]));+ assert.strictEqual(res.errors.filter((e) => /visualization/.test(e)).length, 0, `${v} should validate`);+ }+});++test('the spec enum matches the shipped SDK exactly', () => {+ // The bundle is the authority. Widening the spec without widening the SDK produces a mid-build+ // throw; narrowing it silently drops a renderer an author asked for.+ //+ // Typings are not vendored, so pin against the renderer-id map the bundle actually ships — it is+ // the table `setColumnVisualization` looks the renderer up in:+ // {RadialDial:"c3d4e5f6-…",LineChart:"a1b2c3d4-…",HeatMap:"e7f8a9b0-…",StarRating:"b5e4c3d2-…"}+ // `None` is not in that map by design: it is the CLEAR verb (delete the config row), not a+ // renderer, so it is added back before comparing.+ const bundle = require('node:fs').readFileSync(BUNDLE, 'utf8');+ const m = /\{RadialDial:"[^"]+",(?:[A-Za-z]+:"[^"]+",?)+\}/.exec(bundle);+ assert.ok(m, 'the renderer-id map must be present in the vendored bundle');+ const sdkRenderers = [...m[0].matchAll(/([A-Za-z]+):"/g)].map((x) => x[1]);+ assert.deepStrictEqual([...COLUMN_VISUALIZATIONS].sort(), ['None', ...sdkRenderers].sort());+});++test('the live-observed "preview absent" error is recognised as a SKIP', () => {+ // Pinned from a REAL failure (see the org scan: the set is missing on 17 of 18 test orgs). The+ // shape is easy to get wrong from first principles — the SDK stamps `code: 'CONNECTION_ERROR'`+ // even though this is a clean server 404, so a predicate keyed off `code` would never fire, and+ // an unprovisioned org would HALT the data-model phase over one optional flourish.+ const err = new Error("HTTP 404 from https://example.crm.dynamics.com/api/data/v9.0/controlconfigurations?$select=name: Resource not found for the segment 'controlconfigurations'.");+ err.code = 'CONNECTION_ERROR';+ err.statusCode = 404;+ assert.strictEqual(isVisualizationUnsupported(err), true);++ // Fail-loud on everything else: a permission error is a real defect, not an absent preview.+ const denied = new Error('Principal lacks prvWriteControlConfiguration');+ denied.statusCode = 403;+ assert.strictEqual(isVisualizationUnsupported(denied), false);++ // A 404 from somewhere else entirely must not be swallowed either.+ const otherFourOhFour = new Error("Resource not found for the segment 'workflows'.");+ otherFourOhFour.statusCode = 404;+ assert.strictEqual(isVisualizationUnsupported(otherFourOhFour), false);++ // A ROW-level 404 on the controlconfigurations SET must NOT be swallowed. The SDK's message+ // always embeds the request URL, which contains the word "controlconfigurations" — so a plain+ // substring test also matched a row that was deleted concurrently, silently reporting "preview+ // unavailable" and leaving the renderer unset on an org that fully supports it. Only the+ // segment-missing phrasing means the table is absent.+ const rowGone = new Error("HTTP 404 from https://contoso.crm.dynamics.com/api/data/v9.0/controlconfigurations(00000000-0000-0000-0000-000000000001): The record does not exist.");+ rowGone.statusCode = 404;+ assert.strictEqual(isVisualizationUnsupported(rowGone), false);+});++test('an unknown visualization is rejected and names the column', () => {+ const res = validateAppSpec(specWith([Object.assign({}, SCORE, { visualization: 'Sparkline' })]));+ const err = res.errors.find((e) => /visualization/.test(e));+ assert.ok(err, 'expected a validation error');+ assert.match(err, /new_score/);+ assert.match(err, /Sparkline/);+});++test('omitting visualization is valid — it is not the same as None', () => {+ const res = validateAppSpec(specWith([SCORE]));+ assert.strictEqual(res.errors.filter((e) => /visualization/.test(e)).length, 0);+});++// ---------------------------------------------------------------- 2/3. build++// Minimal provision harness: entity-provision only needs a table/column surface plus the+// visualization setter, so the mock stays small enough that a behaviour change is obvious.+function provisionHarness(opts = {}) {+ const calls = [];+ const existing = opts.existingColumns || [];+ const sdk = {+ createTable: async (o) => ({ logicalName: o.schemaName.toLowerCase(), entitySetName: `${o.schemaName.toLowerCase()}s` }),+ createColumn: async (e, o) => { calls.push(['createColumn', o.schemaName]); return { logicalName: o.schemaName.toLowerCase() }; },+ createCustomerColumn: async (e, o) => ({ logicalName: o.schemaName.toLowerCase() }),+ createGlobalOptionSet: async (o) => ({ name: o.name }),+ createRelationship: async (o) => ({ schemaName: o.schemaName }),+ createAlternateKey: async (e, o) => ({ logicalName: o.schemaName.toLowerCase() }),+ insertStatusValue: async () => 100000001,+ updateTable: async () => undefined,+ setColumnVisualization: async (e, c, v) => {+ calls.push(['setColumnVisualization', e, c, v]);+ if (opts.setThrows) throw opts.setThrows;+ },+ };+ const provision = {+ findTables: async () => (opts.tableExists+ ? [{ logicalName: 'new_ticket', entitySetName: 'new_tickets', schemaName: 'new_ticket' }] : []),+ findColumns: async () => existing.map((c) => ({ logicalName: c })),+ fetchEntityMetadata: async (l) => ({ logicalName: l, entitySetName: `${l}s`, relationships: [] }),+ queryRecords: async () => [{ solutionid: 's' }],+ };+ return { sdk, provision, calls };+}++async function runProvision(spec, harness) {+ const steps = [];+ const runner = {+ run: async (phase, label, fn, o = {}) => {+ try {+ const v = await fn();+ steps.push({ phase, label, status: 'ok' });+ return v;+ } catch (err) {+ if (o.skipIf && o.skipIf(err)) { steps.push({ phase, label, status: 'skipped' }); return undefined; }+ throw err;+ }+ },+ skip: (phase, label) => steps.push({ phase, label, status: 'skipped' }),+ mapLimit: async (items, _n, fn) => { const out = []; for (const it of items) out.push(await fn(it)); return out; },+ };+ await provisionDataModel({ spec, sdk: harness.sdk, provision: harness.provision, runner, preResolvedLanguageCode: 1033 });+ return steps;+}++test('a visualization is written for a NEWLY CREATED column', async () => {+ const h = provisionHarness();+ await runProvision(specWith([Object.assign({}, SCORE, { visualization: 'StarRating' })]), h);+ assert.deepStrictEqual(+ h.calls.find((c) => c[0] === 'setColumnVisualization'),+ ['setColumnVisualization', 'new_ticket', 'new_score', 'StarRating']);+});++test('a visualization is re-asserted for a column that ALREADY EXISTS', async () => {+ // The rebuild path. `setColumnVisualization` converges (PATCH + prune duplicates), so skipping+ // pre-existing columns would make the renderer stick only on the very first build.+ const h = provisionHarness({ tableExists: true, existingColumns: ['new_score'] });+ await runProvision(specWith([Object.assign({}, SCORE, { visualization: 'RadialDial' })]), h);+ assert.ok(!h.calls.some((c) => c[0] === 'createColumn'), 'column already exists — must not be re-created');+ assert.deepStrictEqual(+ h.calls.find((c) => c[0] === 'setColumnVisualization'),+ ['setColumnVisualization', 'new_ticket', 'new_score', 'RadialDial']);+});++test('columns without a visualization are left alone', async () => {+ const h = provisionHarness();+ await runProvision(specWith([SCORE]), h);+ assert.ok(!h.calls.some((c) => c[0] === 'setColumnVisualization'));+});++test("declaring 'None' still writes — it is how a spec CLEARS a renderer", async () => {+ const h = provisionHarness({ tableExists: true, existingColumns: ['new_score'] });+ await runProvision(specWith([Object.assign({}, SCORE, { visualization: 'None' })]), h);+ assert.deepStrictEqual(+ h.calls.find((c) => c[0] === 'setColumnVisualization'),+ ['setColumnVisualization', 'new_ticket', 'new_score', 'None']);+});++test('a 404 from an environment without the preview SKIPS instead of failing the build', async () => {+ const err = new Error("Resource not found for the segment 'controlconfigurations'.");+ err.statusCode = 404;+ const h = provisionHarness({ setThrows: err });+ const steps = await runProvision(specWith([Object.assign({}, SCORE, { visualization: 'HeatMap' })]), h);+ const step = steps.find((s) => /visualization new_ticket\.new_score/.test(s.label));+ assert.ok(step, 'the visualization step should be reported');+ assert.strictEqual(step.status, 'skipped');+});++test('a non-404 failure still halts the build', async () => {+ // Fail-loud on anything that is not "the preview is absent here": a 403 or a bad column name is a+ // real defect, and swallowing it would ship an app silently missing what the author asked for.+ const err = new Error('Principal lacks prvWriteControlConfiguration');+ err.statusCode = 403;+ const h = provisionHarness({ setThrows: err });+ await assert.rejects(+ () => runProvision(specWith([Object.assign({}, SCORE, { visualization: 'HeatMap' })]), h),+ /prvWriteControlConfiguration/);+});++// ---------------------------------------------------------------- 4. verify++function verifyReader(extra = {}) {+ return Object.assign({+ findTable: async () => ({ logicalName: 'new_ticket' }),+ findColumns: async () => [{ logicalName: 'new_score' }],+ queryRecords: async () => [],+ sitemapXml: async () => '',+ }, extra);+}++test('verify reconciles the visualization by VALUE, not existence', async () => {+ const spec = specWith([Object.assign({}, SCORE, { visualization: 'StarRating' })]);+ const good = await verifySpec(spec, verifyReader({ columnVisualization: async () => 'StarRating' }));+ const okCheck = good.checks.find((c) => c.kind === 'column-visualization');+ assert.ok(okCheck && okCheck.present, 'matching renderer must pass');++ const bad = await verifySpec(spec, verifyReader({ columnVisualization: async () => 'RadialDial' }));+ const badCheck = bad.checks.find((c) => c.kind === 'column-visualization');+ assert.ok(badCheck && !badCheck.present, 'a different deployed renderer must FAIL');+ assert.match(badCheck.detail, /expected 'StarRating', deployed 'RadialDial'/);+});++test('verify skips the check when the environment 404s the preview', async () => {+ const err = new Error("Resource not found for the segment 'controlconfigurations'.");+ err.statusCode = 404;+ const res = await verifySpec(+ specWith([Object.assign({}, SCORE, { visualization: 'StarRating' })]),+ verifyReader({ columnVisualization: async () => { throw err; } }));+ assert.ok(!res.checks.some((c) => c.kind === 'column-visualization'),+ 'an unprovisioned environment must not report a divergence the build declined to create');+});++test('verify tolerates a reader that predates the capability', async () => {+ // Most callers build a reader with only the methods they need; an optional preview must never+ // become a TypeError for them.+ const res = await verifySpec(+ specWith([Object.assign({}, SCORE, { visualization: 'StarRating' })]),+ verifyReader());+ assert.ok(!res.checks.some((c) => c.kind === 'column-visualization'));+});++// ---------------------------------------------------------------- real bundle++test('the shipped SDK exposes the visualization surface the build calls', () => {+ // Assert on a real instance: the bundle's factory is `createMakerSdk`, and the class itself is+ // not exported, so a `prototype` check would only ever prove the export shape.+ const os = require('node:os');+ const fs = require('node:fs');+ const { createMakerSdk } = require(BUNDLE);+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cv-surface-'));+ try {+ const sdk = createMakerSdk({+ workspacePath: dir,+ instanceUrl: 'https://contoso.crm.dynamics.com',+ httpClient: {+ get: async () => ({ status: 200, headers: {}, body: { value: [] } }),+ post: async () => ({ status: 204, headers: {}, body: {} }),+ patch: async () => ({ status: 204, headers: {}, body: {} }),+ put: async () => ({ status: 204, headers: {}, body: {} }),+ delete: async () => ({ status: 204, headers: {}, body: {} }),+ },+ });+ assert.strictEqual(typeof sdk.setColumnVisualization, 'function');+ assert.strictEqual(typeof sdk.getColumnVisualization, 'function');+ // Arity is part of the contract: (entityLogicalName, columnLogicalName, visualization).+ // Passing an options object instead — the mistake that made an early probe look like an SDK+ // bug — is exactly what this pins.+ assert.strictEqual(sdk.setColumnVisualization.length, 3);+ assert.strictEqual(sdk.getColumnVisualization.length, 2);+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});diff --git a/plugins/model-apps/scripts/tests/command-real-bundle.test.js b/plugins/model-apps/scripts/tests/command-real-bundle.test.jsnew file mode 100644index 000000000..e76542763--- /dev/null+++ b/plugins/model-apps/scripts/tests/command-real-bundle.test.js@@ -0,0 +1,138 @@+'use strict';+// REAL BUNDLE: the commanding (custom ribbon button) authoring contract.+//+// The plugin already authors commands, but its unit coverage runs against a hand-written mock. This+// pins what the VENDORED bundle actually emits, so a re-vendor that changes the command wire shape+// fails here instead of silently producing buttons that never appear.+//+// The shape matters and is easy to get wrong: controls live inside `commandBars[].groups[].controls`,+// NOT directly on the bar. Putting them on the bar is accepted structurally and then emits NOTHING —+// `pushArtifact` still returns `saved: true` with zero HTTP writes. That is a silent no-op, and it+// is exactly why this file asserts on the captured writes rather than on `saved`.+//+// It also records, in executable form, the two limits that are easy to mis-remember as "the SDK+// cannot do custom buttons":+// * A titled TOP-LEVEL group is a PLATFORM limit, not an SDK one. The SDK models `title` and+// round-trips a fetched titled group, but creating a new top-level Group row is rejected by+// Dataverse ("Group button must have parentappactionid"). Note the plugin's own `commandDef`+// builds `groups: [{ id: '', title: '', controls }]` — an untitled group — for this reason.+// * CONDITIONAL (rule-evaluated) visibility is Power Fx bound to a component library, which cannot+// be authored headlessly. `hidden`/`disabled` are STATIC booleans; there is no JavaScript+// visibility for modern commands.+const test = require('node:test');+const assert = require('node:assert');+const os = require('node:os');+const path = require('node:path');+const fs = require('node:fs');++const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');+const dirs = [];++function sdkWithCapture() {+ const { createMakerSdk } = require(BUNDLE);+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cmd-'));+ dirs.push(dir);+ const writes = [];+ let minted = 0;+ const httpClient = {+ get: async () => ({ status: 200, headers: {}, body: { value: [] } }),+ post: async (url, body) => {+ writes.push({ verb: 'post', url: String(url), body });+ minted += 1;+ const id = `5${String(minted).padStart(7, '0')}-5555-5555-5555-555555555555`;+ return { status: 204, headers: { 'odata-entityid': `https://contoso.crm.dynamics.com/api/data/v9.2/appactions(${id})` }, body: {} };+ },+ patch: async (url, body) => { writes.push({ verb: 'patch', url: String(url), body }); return { status: 204, headers: {}, body: {} }; },+ put: async () => ({ status: 204, headers: {}, body: {} }),+ delete: async () => ({ status: 204, headers: {}, body: {} }),+ };+ const sdk = createMakerSdk({ workspacePath: dir, instanceUrl: 'https://contoso.crm.dynamics.com', httpClient });+ sdk.initWorkspace();+ return { sdk, writes };+}++// Mirrors the shape the plugin's own `commandDef` builds.+function commandDef(controls, location = 'MainGrid') {+ return {+ entityLogicalName: 'account',+ commandBars: [{ location, groups: [{ id: '', title: '', controls }] }],+ };+}++test.after(() => { for (const d of dirs) fs.rmSync(d, { recursive: true, force: true }); });++test('REAL BUNDLE: a custom button with a JavaScript on-click reaches the wire', async () => {+ const { sdk, writes } = sdkWithCapture();+ const art = sdk.createArtifact('command', commandDef([{+ id: 'cr_hello',+ type: 'Button',+ label: 'Say Hello',+ action: {+ type: 'javascript',+ webResourceId: '66666666-6666-6666-6666-666666666666',+ functionName: 'Contoso.sayHello',+ parameters: [],+ },+ }]));+ assert.ok(art && art.id, 'createArtifact returns a command artifact');++ const pushed = await sdk.pushArtifact('command', art.id);+ assert.strictEqual(pushed.saved, true, `push commits; warnings=${JSON.stringify(pushed.warnings || [])}`);+ // Assert on WRITES, not on `saved`: a mis-shaped definition still reports saved:true while+ // emitting nothing at all.+ assert.ok(writes.length > 0, 'the push actually issued HTTP writes — saved:true alone is not proof');++ const all = JSON.stringify(writes);+ assert.match(all, /appaction/i, 'a command row is written');+ assert.match(all, /Contoso\.sayHello/, 'the JS function name reaches the wire — without it the button is inert');+ assert.match(all, /66666666-6666-6666-6666-666666666666/, 'the handler web resource is bound to the button');+});++test('REAL BUNDLE: Button, FlyoutAnchor and SplitButton all emit writes', async () => {+ // "Custom buttons are supported" is otherwise a claim with no executable meaning, and a re-vendor+ // could narrow the accepted set without any existing test noticing.+ for (const type of ['Button', 'FlyoutAnchor', 'SplitButton']) {+ const { sdk, writes } = sdkWithCapture();+ const art = sdk.createArtifact('command', commandDef([{ id: `cr_${type.toLowerCase()}`, type, label: type }]));+ const pushed = await sdk.pushArtifact('command', art.id);+ assert.strictEqual(pushed.saved, true, `${type} pushes cleanly`);+ assert.ok(writes.length > 0, `${type} actually emitted writes rather than silently no-op'ing`);+ }+});++test('REAL BUNDLE: hidden/disabled reach the wire as real booleans, not rules or strings', async () => {+ // The limit worth recording: `hidden: true` is a fixed state, not a rule. Rule-evaluated+ // visibility on modern commands is Power Fx + a component library and cannot be authored+ // headlessly, so an author must not expect "hide when status = closed" to be expressible here.+ const { sdk, writes } = sdkWithCapture();+ const art = sdk.createArtifact('command', commandDef([+ { id: 'cr_static', type: 'Button', label: 'Static', hidden: true, disabled: true },+ ]));+ const pushed = await sdk.pushArtifact('command', art.id);+ assert.strictEqual(pushed.saved, true);+ assert.ok(writes.length > 0, 'a static hidden/disabled button still writes');++ // POSITIVE assertions on the observed wire shape:+ // { …, "buttonlabeltext": "Static", "hidden": true, "isdisabled": true }+ // A negative-only test ("no rule expression appears") would pass for three DIFFERENT failures:+ // the SDK dropping both flags, coercing them to the strings "true"/"false", or inverting them.+ // Naming the real keys and the real types is what makes this a contract test.+ const body = writes.map((w) => w.body).find((b) => b && b.hidden !== undefined);+ assert.ok(body, 'a command row carrying the visibility flags was written; got ' + JSON.stringify(writes.map((w) => w.body)).slice(0, 300));+ assert.strictEqual(body.hidden, true, '`hidden` is a real boolean on the wire, not a string and not inverted');+ assert.strictEqual(body.isdisabled, true, '`disabled` maps to `isdisabled`, also a real boolean');++ // And the negative still holds: no unevaluated rule expression is carried.+ assert.doesNotMatch(JSON.stringify(writes), /statuscode eq/i, 'no rule expression — these are static flags');+});++test('the plugin builds an UNTITLED group, because titled top-level groups are a platform limit', () => {+ // A PLATFORM limit ("Group button must have parentappactionid" -> HTTP 400), not an SDK gap. The+ // types expose `CommandGroup.title`, which reads like support until a push fails — so pin that the+ // plugin deliberately emits an empty title rather than inviting the failure.+ const src = fs.readFileSync(path.resolve(__dirname, '..', 'lib', 'sdk-build.js'), 'utf8');+ const m = /groups:\s*\[\{\s*id:\s*''\s*,\s*title:\s*''/.exec(src);+ assert.ok(m,+ "commandDef must build groups with an empty title — a titled top-level group is rejected by "+ + 'Dataverse with HTTP 400, so authoring one would fail the build');+});diff --git a/plugins/model-apps/scripts/tests/concurrency-stress.test.js b/plugins/model-apps/scripts/tests/concurrency-stress.test.jsnew file mode 100644index 000000000..b9953b009--- /dev/null+++ b/plugins/model-apps/scripts/tests/concurrency-stress.test.js@@ -0,0 +1,136 @@+'use strict';+// CONCURRENCY STRESS — the workspace manifest under interleaved artifact writes.+//+// Why this exists: the build engine fans out with `runner.mapLimit(items, concurrency, fn)`, and+// the SDK's generic surface is now async, so a single form/view build yields at MANY more points+// than it used to. Concurrent builds therefore interleave far more aggressively than any previous+// bundle ever exercised.+//+// The specific hazard: the SDK's WorkspaceManager does a read-modify-write of ONE shared file+// (manifest.json) on every artifact write —+// writeArtifact -> upsertManifestEntry -> getManifest() [read] ... writeManifest() [write]+// If any `await` were to land between that read and that write, two interleaved writers would each+// read the same manifest, and the second write would clobber the first writer's entry — an artifact+// silently missing from the manifest, on a real org, with every HTTP call returning 2xx.+//+// This is NOT a theoretical concern the async migration introduced and left unproven: it is the+// single most likely place for the extra interleaving to cause real data loss, so it is asserted+// against the REAL vendored bundle rather than reasoned about.+const test = require('node:test');+const assert = require('node:assert');+const os = require('node:os');+const path = require('node:path');+const fs = require('node:fs');++const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');++const tempDirs = [];+test.after(() => { for (const d of tempDirs) fs.rmSync(d, { recursive: true, force: true }); });++// An httpClient that RESOLVES ON A LATER TURN. A client that resolves synchronously would let each+// artifact's work run start-to-finish without ever yielding, which is exactly the interleaving this+// test needs to create. setImmediate (macrotask) is deliberately coarser than a microtask so the+// scheduler genuinely interleaves the concurrent chains.+function deferringHttpClient(counter) {+ const later = (value) => new Promise((resolve) => setImmediate(() => resolve(value)));+ return {+ get: async () => later({ status: 200, headers: {}, body: {} }),+ post: async () => {+ counter.posts++;+ return later({ status: 204, headers: { 'odata-entityid': `https://x/y(${counter.next()})` }, body: {} });+ },+ patch: async () => later({ status: 204, headers: {}, body: {} }),+ delete: async () => later({ status: 204, headers: {}, body: {} }),+ put: async () => later({ status: 204, headers: {}, body: {} }),+ };+}++function freshSdk() {+ const { createMakerSdk } = require(BUNDLE);+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'concurrency-'));+ tempDirs.push(dir);+ let n = 0;+ const counter = {+ posts: 0,+ next: () => `11111111-1111-1111-1111-${String(++n).padStart(12, '0')}`,+ };+ const sdk = createMakerSdk({+ workspacePath: dir,+ instanceUrl: 'https://example.crm.dynamics.com',+ httpClient: deferringHttpClient(counter),+ });+ sdk.initWorkspace();+ return { sdk, dir, counter };+}++const readManifest = (dir) => JSON.parse(fs.readFileSync(path.join(dir, 'manifest.json'), 'utf8'));++test('STRESS: 40 concurrent artifact mutations all survive in the shared manifest (no lost update)', async () => {+ const { sdk, dir } = freshSdk();+ const N = 40;++ // Create first (createArtifact is synchronous), so the concurrent phase is pure async mutation.+ const ids = [];+ for (let i = 0; i < N; i++) {+ ids.push(sdk.createArtifact('view', { name: `View ${i}`, entityLogicalName: 'account', columns: [] }).id);+ }++ // Now mutate ALL of them concurrently. Each updateElement writes the artifact AND rewrites the+ // one shared manifest.json, so this is the read-modify-write collision window. Awaiting each call+ // here would serialize the writers and destroy the interleaving this test exists to create.+ // sdk-async-ok: the promise is handed to Promise.all, concurrent by design.+ await Promise.all(ids.map((id, i) => sdk.updateElement('view', id, '/columns', [{ name: `col_${i}`, width: 100, order: 0 }])));++ const manifest = readManifest(dir);+ const seen = new Set(manifest.artifacts.map((a) => a.id));+ // Non-vacuity: `missing` would also be empty if nothing had been written at all, or if the+ // create loop had silently produced 0 ids.+ assert.strictEqual(ids.length, N, 'the create loop produced the ids the assertion below relies on');+ assert.ok(manifest.artifacts.length >= N,+ `the manifest holds all ${N} artifacts (saw ${manifest.artifacts.length}) — a smaller number `+ + 'means writes were lost, not that the test had nothing to check');+ const missing = ids.filter((id) => !seen.has(id));+ assert.deepStrictEqual(missing, [],+ `${missing.length}/${N} artifacts vanished from the shared manifest under concurrent writes — `+ + 'an interleaved read-modify-write lost them. On a real build that is an artifact the engine '+ + 'created but can no longer find.');++ // And the per-artifact content must be the writer's own, not another chain's.+ for (let i = 0; i < N; i++) {+ const art = await sdk.getArtifact('view', ids[i]);+ assert.strictEqual(art.columns[0].name, `col_${i}`, `view ${i} kept its OWN column, not a neighbour's`);+ }+});++test('STRESS: concurrent mutation + push of the same artifact serializes (no interleaved corruption)', async () => {+ const { sdk } = freshSdk();+ const id = sdk.createArtifact('view', { name: 'Contended', entityLogicalName: 'account', columns: [] }).id;++ // Same artifact, many writers. The SDK takes a per-artifact lock, so these must serialize; the+ // point is that the LAST write wins cleanly rather than two writes merging into a torn value.+ const contend = (i) =>+ // sdk-async-ok: concurrent by design, the promises go to Promise.all.+ sdk.updateElement('view', id, '/columns', [{ name: `c${i}`, width: 100, order: 0 }]);+ await Promise.all(Array.from({ length: 20 }, (_, i) => contend(i)));++ const art = await sdk.getArtifact('view', id);+ assert.strictEqual(art.columns.length, 1, 'exactly one column survives — writes serialized, not merged');+ assert.match(art.columns[0].name, /^c\d+$/, 'the surviving column is a whole value from one writer');+});++test('STRESS: interleaved reads of 40 artifacts each return their OWN artifact', async () => {+ // Guards against a shared-read-buffer bug in the revalidating read path: with reads now async, a+ // cache keyed or reused incorrectly would hand chain A the artifact chain B asked for. Cheap to+ // assert, and impossible to notice from a single-artifact test.+ const { sdk } = freshSdk();+ const ids = [];+ for (let i = 0; i < 40; i++) {+ ids.push(sdk.createArtifact('form', { name: `Form ${i}`, entityLogicalName: 'account', formType: 'main', status: 'draft' }).id);+ }+ // sdk-async-ok: concurrent by design, the promises go to Promise.all.+ const reads = await Promise.all(ids.map((id) => sdk.getArtifact('form', id)));+ reads.forEach((art, i) => {+ assert.strictEqual(art.id, ids[i], `read ${i} returned its own artifact`);+ assert.strictEqual(art.name, `Form ${i}`, `read ${i} returned its own NAME (no cross-chain bleed)`);+ });+});diff --git a/plugins/model-apps/scripts/tests/default-view-createdon.test.js b/plugins/model-apps/scripts/tests/default-view-createdon.test.jsindex a7cd953d3..0bb3d0f94 100644--- a/plugins/model-apps/scripts/tests/default-view-createdon.test.js+++ b/plugins/model-apps/scripts/tests/default-view-createdon.test.js@@ -19,7 +19,12 @@ test.after(() => { for (const d of tempDirs) fs.rmSync(d, { recursive: true, for// The Dataverse-shipped "Active <Entity>" default view: primary + the stock Created On column, in// both the query (fetchxml) and the grid (layoutxml). This is what enrichDefaultViews fetches live.+// The `@odata.etag` is REQUIRED: the SDK refuses to push an artifact it holds no concurrency token+// for (`ARTIFACT_UPDATE_NO_ETAG`) rather than issue an unconditional write that could silently+// overwrite a concurrent Maker edit. Real Dataverse always returns one, so a fixture without it is+// unrealistic — omitting it makes this test fail for a reason that has nothing to do with columns.const STOCK_VIEW = {+ '@odata.etag': 'W/"4180012"',savedqueryid: '00000000-0000-0000-0000-0000000000aa',name: 'Active New Tasks',description: '',@@ -73,7 +78,7 @@ test('#7 enriching a default view REPLACES the stock createdon column (dropped fconst id = STOCK_VIEW.savedqueryid;// Exactly what provision.enrichDefaultViews does: fetch the live view, replace /columns, push.await sdk.fetchArtifact('view', id);- sdk.updateElement('view', id, '/columns', defaultViewColumns(spec, spec.entities[0]));+ await sdk.updateElement('view', id, '/columns', defaultViewColumns(spec, spec.entities[0]));await sdk.pushArtifact('view', id);const patch = capture.find((c) => /\/savedqueries\(/.test(c.url) && c.body && (c.body.fetchxml || c.body.layoutxml));diff --git a/plugins/model-apps/scripts/tests/download-model-app.test.js b/plugins/model-apps/scripts/tests/download-model-app.test.jsindex 0707160be..993e13374 100644--- a/plugins/model-apps/scripts/tests/download-model-app.test.js+++ b/plugins/model-apps/scripts/tests/download-model-app.test.js@@ -4,7 +4,7 @@ const assert = require('node:assert');const fs = require('node:fs');const os = require('node:os');const path = require('node:path');-const { resolveAppId, collectSitemap, parseDownloadedPages, entityFromMetadata, iconWebResources, readDashboards, droppedSubareaCount } = require('../download-model-app.js');+const { resolveAppId, collectSitemap, parseDownloadedPages, entityFromMetadata, iconWebResources, readDashboards, droppedSubareaCount, preserveAuthoredLanguageCode } = require('../download-model-app.js');test('resolveAppId returns a guid as-is, else resolves by uniquename', async () => {const guid = '11111111-2222-3333-4444-555555555555';@@ -811,3 +811,63 @@ test('a FOREIGN-prefix nav web resource is left as a bare reference, not re-declconst { webResources } = await iconWebResources(sdk, [], [], 'crba3', true, ['isv_page.html']);assert.strictEqual(webResources.length, 0, 'a foreign-prefix nav resource must not be re-declared');});++// #456: download does NOT read languageCode from Dataverse, and that is deliberate — an LCID copied+// out of the source org would be re-applied verbatim when the spec is rebuilt elsewhere, which is how+// a spec starts failing in an org that lacks that language (#447). But dropping a value the AUTHOR+// wrote is its own bug, and a silent one: the next build resolves the org default, so new columns get+// one language while the pinned ones keep another. Mixed-language app, no error.+test('a hand-pinned languageCode survives a download (#456)', () => {+ const spec = { app: { name: 'A' }, entities: [] };+ const prior = JSON.stringify({ app: { name: 'A' }, languageCode: 1031 });+ const deps = { existsSync: () => true, readFileSync: () => prior };+ preserveAuthoredLanguageCode(spec, 'app-spec.json', deps);+ assert.strictEqual(spec.languageCode, 1031, 'the author-pinned LCID is restored');+});++test('the preserved value is CANONICAL, not the author\'s raw formatting', () => {+ // A downloaded spec is a generated artifact. `"1031"` and `" 1031 "` both validate, but writing+ // the string form back out makes the file's diff noisy and its type inconsistent with every other+ // numeric field the download emits.+ for (const raw of ['1031', ' 1031 ', '01031']) {+ const spec = { app: { name: 'A' } };+ preserveAuthoredLanguageCode(spec, 'app-spec.json', {+ existsSync: () => true,+ readFileSync: () => JSON.stringify({ languageCode: raw }),+ });+ assert.strictEqual(spec.languageCode, 1031, `${JSON.stringify(raw)} must normalize to the number 1031`);+ assert.strictEqual(typeof spec.languageCode, 'number');+ }+});++test('preserving never invents a languageCode where the author had none', () => {+ const spec = { app: { name: 'A' }, entities: [] };+ const deps = { existsSync: () => true, readFileSync: () => JSON.stringify({ app: { name: 'A' } }) };+ preserveAuthoredLanguageCode(spec, 'app-spec.json', deps);+ assert.strictEqual(spec.languageCode, undefined, 'no previous value means the field stays absent');++ // A first-ever download has no previous spec at all.+ const fresh = { app: { name: 'A' }, entities: [] };+ preserveAuthoredLanguageCode(fresh, 'app-spec.json', { existsSync: () => false, readFileSync: () => { throw new Error('nope'); } });+ assert.strictEqual(fresh.languageCode, undefined);+});++test('a downloaded languageCode is never overwritten by the previous file', () => {+ // Defensive: if a future download ever DOES emit one, the live value wins over the stale file.+ const spec = { app: { name: 'A' }, languageCode: 1036 };+ const deps = { existsSync: () => true, readFileSync: () => JSON.stringify({ languageCode: 1031 }) };+ preserveAuthoredLanguageCode(spec, 'app-spec.json', deps);+ assert.strictEqual(spec.languageCode, 1036);+});++test('a corrupt or invalid previous spec is ignored rather than failing the download', () => {+ for (const prior of ['{ not json', JSON.stringify({ languageCode: 'de-DE' }), JSON.stringify({ languageCode: true }), JSON.stringify({ languageCode: 0 }), JSON.stringify({ languageCode: 99999 })]) {+ const spec = { app: { name: 'A' } };+ preserveAuthoredLanguageCode(spec, 'app-spec.json', { existsSync: () => true, readFileSync: () => prior });+ assert.strictEqual(spec.languageCode, undefined, 'must not carry forward ' + prior.slice(0, 30));+ }+ // A read that throws must not escape either.+ const spec = { app: { name: 'A' } };+ assert.doesNotThrow(() => preserveAuthoredLanguageCode(spec, 'x', { existsSync: () => true, readFileSync: () => { throw new Error('EACCES'); } }));+ assert.strictEqual(spec.languageCode, undefined);+});diff --git a/plugins/model-apps/scripts/tests/entity-provision.test.js b/plugins/model-apps/scripts/tests/entity-provision.test.jsindex 5ebb1f688..0890a2016 100644--- a/plugins/model-apps/scripts/tests/entity-provision.test.js+++ b/plugins/model-apps/scripts/tests/entity-provision.test.js@@ -2,7 +2,7 @@const { test } = require('node:test');const assert = require('node:assert');const path = require('node:path');-const { makeRunner, requireSuccessfulPush, provisionDataModel, provisionSampleData, provisionSolution, buildSeedGroup } = require(path.join(__dirname, '..', 'lib', 'entity-provision.js'));+const { makeRunner, requireSuccessfulPush, reportPartialPush, provisionDataModel, provisionSampleData, provisionSolution, buildSeedGroup } = require(path.join(__dirname, '..', 'lib', 'entity-provision.js'));function mockSdk(existing = {}) {const calls = [];@@ -439,6 +439,37 @@ test('requireSuccessfulPush halts (BuildHalt) on a 412 version-conflict result',);});+// The SDK renamed `PushResult.success` to `saved` deliberately — its own type comment says the+// rename exists to "force every existing call site to be looked at once". This guard is such a call+// site, and it is the ONLY thing standing between a 412 and a silently dropped Maker edit.+//+// The danger is that the rename is invisible at runtime: a `success === false` check against a+// bundle that returns `saved` reads `undefined === false` -> false, so the guard just stops firing.+// Nothing fails, nothing logs, and a concurrent edit is overwritten. These pin BOTH spellings so the+// guard cannot be silently disarmed by a re-vendor in either direction.+test('requireSuccessfulPush halts on the RENAMED PushResult shape (saved:false), not just success:false', () => {+ const conflict = { type: 'form', id: 'f9', saved: false, shipped: false, error: new Error('Version conflict (412)') };+ assert.throws(+ () => requireSuccessfulPush(conflict, 'form f9'),+ (err) => err.name === 'BuildHalt' && err.code === 'version-conflict' && /Version conflict \(412\)/.test(err.message),+ 'a saved:false result MUST halt — otherwise a 412 silently drops the edit'+ );+});++test('requireSuccessfulPush accepts a saved:true result and does not confuse saved with shipped', () => {+ // `shipped:false` is normal — it means the change is committed but the runtime still serves the+ // previously published copy. That is NOT a push failure and must not halt the build; the publish+ // phase is what makes it live.+ const saved = { type: 'view', id: 'v1', saved: true, shipped: false, publish: { kind: 'notRequested' } };+ assert.strictEqual(requireSuccessfulPush(saved, 'view v1'), saved);+});++test('requireSuccessfulPush halts on a result that carries an error but neither flag', () => {+ // Fail closed: an unrecognised shape that still reports an error must not be treated as success.+ const odd = { type: 'chart', id: 'c1', error: new Error('boom') };+ assert.throws(() => requireSuccessfulPush(odd, 'chart c1'), (err) => err.name === 'BuildHalt');+});+// #447 regression net. The bug this fixes was a SINGLE label-emitting call that forgot to pass a// language, and it stayed invisible until a user in a German org filed a bug — CI runs offline mocks// and nobody's CI runs against a non-1033 org. So pinning only the two call sites that happened to be@@ -519,3 +550,136 @@ test('EVERY label-emitting SDK call carries the resolved language code (#447)','these label-emitting calls did not carry the resolved LCID: ' + JSON.stringify(missing.map((c) => c.name)));});++// The SDK moved publishArtifact from THROWING to reporting by value, exactly as it did for+// pushArtifact. Nothing in the engine read the result, so every publish failure vanished into a+// build that reported ok:true -- and because those failures no longer throw, the transient-retry+// path (429 / 503 / customization-lock, which is the everyday PublishXml failure in a real tenant)+// became unreachable for them. These pin the reporting so it cannot silently regress again.+test('a FAILED publish is reported, not swallowed', () => {+ const warnings = [];+ const result = { type: 'form', id: 'f1', shipped: false, publish: { kind: 'failed', error: new Error('PublishXml 503') } };+ reportPartialPush(result, 'form Contact Main', (m) => warnings.push(m));+ assert.strictEqual(warnings.length, 1, 'a failed publish must produce exactly one warning');+ assert.match(warnings[0], /publish form Contact Main FAILED/);+ assert.match(warnings[0], /PublishXml 503/, 'the underlying cause is named');+ assert.match(warnings[0], /SAVED but/, 'it must say the write survived — this is not a lost edit');+});++test('an UNVERIFIABLE publish is reported as unproven rather than as success', () => {+ const warnings = [];+ reportPartialPush({ type: 'app', id: 'a1', shipped: false, publish: { kind: 'unverifiable', reason: 'projection not readable' } }, 'app Contoso', (m) => warnings.push(m));+ assert.strictEqual(warnings.length, 1);+ assert.match(warnings[0], /could not be CONFIRMED/);+ assert.match(warnings[0], /projection not readable/);+});++test('a verified publish and a not-requested publish are both silent', () => {+ const warnings = [];+ reportPartialPush({ type: 'view', id: 'v1', shipped: true, publish: { kind: 'verified' } }, 'view V', (m) => warnings.push(m));+ reportPartialPush({ type: 'view', id: 'v2', shipped: false, publish: { kind: 'notRequested' } }, 'view V2', (m) => warnings.push(m));+ assert.deepStrictEqual(warnings, [], 'success and no-publish-requested must not warn');+});++// PushResult.warnings exists specifically so a partial success is not read as a clean one. The SDK's+// own comment on the app path says a failed system-admin role assignment "must not fail app creation,+// but it is reported so a create that produced an UNOPENABLE app is not read as a clean success".+test('a push that COMMITTED but carries warnings surfaces them (an unopenable app is not a clean success)', () => {+ const warnings = [];+ const result = {+ type: 'app', id: 'a2', saved: true, shipped: false, publish: { kind: 'notRequested' },+ warnings: ['one or more components were not pinned', 'system administrator role could not be assigned'],+ };+ assert.strictEqual(requireSuccessfulPush(result, 'app Contoso', (m) => warnings.push(m)), result, 'it still passes — the write committed');+ assert.strictEqual(warnings.length, 2, 'both warnings surface: ' + JSON.stringify(warnings));+ assert.ok(warnings.every((w) => /^app Contoso: /.test(w)), 'each names the artifact');+});++test('a saved push whose publish failed is reported even though the push itself passes', () => {+ // App CREATE publishes inside the SDK, so this arrives as saved:true + publish:failed with no+ // top-level error — the shape the push guard alone would wave straight through.+ const warnings = [];+ const result = { type: 'app', id: 'a3', saved: true, shipped: false, publish: { kind: 'failed', error: new Error('saved, but publishing failed') } };+ requireSuccessfulPush(result, 'app Contoso', (m) => warnings.push(m));+ assert.ok(warnings.some((w) => /publish app Contoso FAILED/.test(w)), JSON.stringify(warnings));+});++test('requireSuccessfulPush distinguishes an already-exists collision from a version conflict', () => {+ // Both are by-value failures, but the remedies are opposite: re-download for a concurrent edit,+ // adopt-the-existing-row for a replayed create. Reporting one as the other sends the operator+ // to re-download when nothing changed under them.+ const err = new Error('a record already exists at that id');+ err.code = 'ARTIFACT_ALREADY_EXISTS';+ assert.throws(+ () => requireSuccessfulPush({ type: 'view', id: 'v9', saved: false, error: err }, 'view V9'),+ (e) => e.name === 'BuildHalt' && e.code === 'already-exists' && /adopt it/.test(e.message) && !/re-download the app/.test(e.message)+ );+});++// #455 wiring: the CLI resolves the authoring LCID BEFORE constructing the SDK (because+// MakerSdkOptions.languageCode is a construction-time option) and then hands the SAME value to the+// data-model phase. Two things must hold, and neither is covered by testing resolveLanguageCode+// alone: the pre-resolved value must be USED, and it must NOT be re-resolved.+//+// Re-resolution is not merely wasteful — the data-model phase would repeat the org read and the+// provisioned-languages probe, and any disagreement would label columns in one language while the+// SDK stamps FormXML and sitemap titles in another.+test('a pre-resolved authoring language is used verbatim by the data-model phase', async () => {+ const spec = {+ solution: { uniqueName: 'S', publisherPrefix: 'cr' },+ entities: [{ schemaName: 'cr_t', displayName: 'T', pluralName: 'Ts', primaryAttribute: { schemaName: 'cr_name' }, columns: [{ schemaName: 'cr_note', displayName: 'Note', type: 'text' }] }],+ relationships: [],+ };+ const seen = [];+ let orgReads = 0;+ let probes = 0;+ const sdk = {+ createTable: async (o) => { seen.push(['createTable', o]); return { logicalName: 'cr_t', metadataId: 't' }; },+ createColumn: async (l, o) => { seen.push(['createColumn', o]); return { logicalName: (o.schemaName || '').toLowerCase(), metadataId: 'c' }; },+ };+ const provision = {+ queryRecords: async (set) => { if (set === 'organization') { orgReads += 1; return [{ languagecode: 1033 }]; } return []; },+ findTables: async () => [], findColumns: async () => [], fetchEntityMetadata: async () => ({}),+ };+ const runner = makeRunner({ emit: () => {}, total: 10 });++ await provisionDataModel({+ sdk, provision, runner, spec, apply: true,+ preResolvedLanguageCode: 3082,+ // Deliberately CONTRADICTORY inputs: if the pre-resolved value is honoured, neither of these is+ // consulted. If it is ignored, the explicit 1031 would win and the probe would fire.+ languageCode: 1031,+ provisionedLanguages: async () => { probes += 1; return [1031, 1033]; },+ });++ const withLang = seen.filter(([, o]) => o && o.languageCode !== undefined);+ assert.ok(withLang.length > 0, 'at least one label-bearing write happened');+ for (const [what, o] of withLang) {+ assert.strictEqual(o.languageCode, 3082, `${what} must use the pre-resolved LCID, not re-resolve one`);+ }+ assert.strictEqual(orgReads, 0, 'the org language must NOT be read again once it is already resolved');+ assert.strictEqual(probes, 0, 'the provisioned-languages probe must NOT fire again');+});++test('without a pre-resolved language the data-model phase still resolves one itself', async () => {+ // The self-resolving path is not dead code: provision-entities.js and every existing unit test+ // reach provisionDataModel without a pre-resolved value, so removing it would break them.+ const spec = {+ solution: { uniqueName: 'S', publisherPrefix: 'cr' },+ entities: [{ schemaName: 'cr_t', displayName: 'T', pluralName: 'Ts', primaryAttribute: { schemaName: 'cr_name' }, columns: [] }],+ relationships: [],+ };+ const seen = [];+ const sdk = {+ createTable: async (o) => { seen.push(o); return { logicalName: 'cr_t', metadataId: 't' }; },+ createColumn: async (l, o) => { seen.push(o); return { logicalName: 'x', metadataId: 'c' }; },+ };+ const provision = {+ queryRecords: async (set) => (set === 'organization' ? [{ languagecode: 1031 }] : []),+ findTables: async () => [], findColumns: async () => [], fetchEntityMetadata: async () => ({}),+ };+ await provisionDataModel({ sdk, provision, runner: makeRunner({ emit: () => {}, total: 10 }), spec, apply: true });+ const withLang = seen.filter((o) => o && o.languageCode !== undefined);+ assert.ok(withLang.length > 0 && withLang.every((o) => o.languageCode === 1031),+ 'the org base language is still resolved when nothing was pre-resolved');+});diff --git a/plugins/model-apps/scripts/tests/golden.test.js b/plugins/model-apps/scripts/tests/golden.test.jsindex c1532f487..8e816a0ee 100644--- a/plugins/model-apps/scripts/tests/golden.test.js+++ b/plugins/model-apps/scripts/tests/golden.test.js@@ -7,6 +7,19 @@ const fs = require('node:fs');const path = require('node:path');const { planFor, PHASES, appDef } = require('../lib/sdk-build.js');const { assertGolden } = require('./helpers/golden.js');+// Every app the PLUGIN creates carries an icon: `ensureAppIcon` (sdk-build.js) resolves the author's+// `spec.app.icon` or generates an SVG web resource, and `appDef` passes its id as+// `iconWebResourceId`. These tests drive the SDK directly, so they must supply one too or they are+// exercising a path production never takes.+//+// The SDK now REQUIRES it: `appmodule.webresourceid` is a required attribute, and when no explicit id+// is given it auto-resolves an IMAGE web resource (PNG/JPG/GIF/ICO/SVG) and throws+// `APP_ICON_UNRESOLVED` if the environment has none. Previously it fell back to ANY unmanaged web+// resource — which on an org whose images are all managed returned a JAVASCRIPT file, and the platform+// rejected the create with an opaque "dependent component WebResource does not exist". Failing fast+// with a clear message is the better behaviour; these tests just have to stop relying on the old+// silent fallback. A synthetic id is right here — the mock transport never dereferences it.+const APP_ICON_ID = '11111111-2222-3333-4444-555555555555';const sample = (n) => JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'samples', `app-spec.${n}.json`), 'utf8'));@@ -72,7 +85,7 @@ test('sitemap-XML golden: area + subarea icons', async () => {};const sdk = createMakerSdk({ workspacePath: ws, instanceUrl: 'https://example.crm.dynamics.com', httpClient });sdk.initWorkspace();- const art = sdk.createArtifact('app', { name: spec.app.name, uniqueName: 'new_goldenapp', description: '', siteMap: def.siteMap, components: def.components });+ const art = sdk.createArtifact('app', { name: spec.app.name, uniqueName: 'new_goldenapp', description: '', siteMap: def.siteMap, components: def.components, iconWebResourceId: APP_ICON_ID });await sdk.pushArtifact('app', art.id);fs.rmSync(ws, { recursive: true, force: true });assertGolden('sitemap.icons.xml', xml + '\n');diff --git a/plugins/model-apps/scripts/tests/golden/journal.support-desk.txt b/plugins/model-apps/scripts/tests/golden/journal.support-desk.txtindex a74d52fed..ead231f13 100644--- a/plugins/model-apps/scripts/tests/golden/journal.support-desk.txt+++ b/plugins/model-apps/scripts/tests/golden/journal.support-desk.txt@@ -54,8 +54,8 @@ forms start form "Customer"forms start form "Ticket"forms start form "Comment"forms ok form "Customer"-forms ok form "Ticket"forms ok form "Comment"+forms ok form "Ticket"app-shell start app icon (generated) new_supportdesk_iconapp-shell ok app icon (generated) new_supportdesk_iconapp-shell start app "Support Desk"diff --git a/plugins/model-apps/scripts/tests/hardening2-real-bundle.test.js b/plugins/model-apps/scripts/tests/hardening2-real-bundle.test.jsindex 237482057..b85ecc1d3 100644--- a/plugins/model-apps/scripts/tests/hardening2-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/hardening2-real-bundle.test.js@@ -49,10 +49,10 @@ function freshSdk(capture, meta) {// Mirror the engine's createFormShell sequence: minimal create, append each compiled tab (ids minted// by addElement), drop the seed tab. Returns the form id.-function buildFormShell(sdk, intent) {+async function buildFormShell(sdk, intent) {const art = sdk.createArtifact('form', { name: intent.name, entityLogicalName: intent.entityLogicalName, formType: intent.formType, status: intent.status });- for (const tab of intent.tabs) sdk.addElement('form', art.id, '/tabs', tab);- sdk.removeElement('form', art.id, '/tabs/0');+ for (const tab of intent.tabs) await sdk.addElement('form', art.id, '/tabs', tab);+ await sdk.removeElement('form', art.id, '/tabs/0');return art.id;}@@ -69,7 +69,7 @@ test('PARITY: the rewired form path reproduces the pre-swap golden facts (fieldsconst cap = [];const sdk = freshSdk(cap);const intent = ai.compileFormIntent(custSpec, custSpec.forms[0], { notesClassId: NOTES_CLASS_ID });- const id = buildFormShell(sdk, intent);+ const id = await buildFormShell(sdk, intent);await sdk.pushArtifact('form', id);const formxml = (cap.find((c) => /systemforms/.test(c.url)) || {}).body.formxml;const facts = formFacts(formxml);@@ -90,7 +90,7 @@ test('multi-tab / multi-section explicit layout serializes every tab, section anconst sdk = freshSdk(cap);const intent = ai.compileFormIntent(spec, spec.forms[0], { notesClassId: NOTES_CLASS_ID });assert.strictEqual(intent.tabs.length, 2, 'two tabs compiled');- const id = buildFormShell(sdk, intent);+ const id = await buildFormShell(sdk, intent);await sdk.pushArtifact('form', id);const formxml = String((cap.find((c) => /systemforms/.test(c.url)) || {}).body.formxml);for (const f of ['new_name', 'new_a', 'new_b', 'new_c']) assert.match(formxml, new RegExp(`datafieldname="${f}"`), `${f} present in formxml`);@@ -122,7 +122,7 @@ test('#8 authored column width: a synthesized form column with NO explicit widthconst intent = ai.compileFormIntent(spec, spec.forms[0], { notesClassId: NOTES_CLASS_ID });// Remove the plugin-set width from every tab column so ONLY the SDK default can supply it.for (const tab of intent.tabs) for (const col of (tab.columns || [])) delete col.width;- const id = buildFormShell(sdk, intent);+ const id = await buildFormShell(sdk, intent);await sdk.pushArtifact('form', id);const formxml = String((cap.find((c) => /systemforms/.test(c.url)) || {}).body.formxml);assert.ok((formxml.match(/<column\b[^>]*>/g) || []).length > 0, 'formxml has columns');@@ -139,7 +139,7 @@ test('metadata-derived control types: passing only fieldName lets the adapter clconst cap = [];const sdk = freshSdk(cap, meta);const intent = ai.compileFormIntent(spec, spec.forms[0], {});- const id = buildFormShell(sdk, intent);+ const id = await buildFormShell(sdk, intent);await sdk.pushArtifact('form', id);const formxml = String((cap.find((c) => /systemforms/.test(c.url)) || {}).body.formxml);// Lookup control classid (0d2c745a-…) differs from the single-line text control — the adapter picked@@ -156,11 +156,11 @@ test('#5 sub-grid is added as its OWN full-width section and serializes relationconst cap = [];const sdk = freshSdk(cap);const intent = ai.compileFormIntent(custSpec, custSpec.forms[0], { notesClassId: NOTES_CLASS_ID });- const id = buildFormShell(sdk, intent);+ const id = await buildFormShell(sdk, intent);// The engine now appends a whole sub-grid SECTION to a column's /sections (not a cell into an// existing field section's rows) — exercise that real path through the vendored serializer.- const secPtr = ai.firstColumnSectionsPointer(sdk.getArtifact('form', id));- sdk.addElement('form', id, secPtr, ai.subgridSectionIntent({ subgridClassId: SUBGRID_CLASS_ID, targetEntity: 'new_ticket', relationshipName: 'new_customer_new_ticket', viewId: '{00000000-0000-0000-0000-0000000000v1}', label: 'Tickets' }));+ const secPtr = ai.firstColumnSectionsPointer(await sdk.getArtifact('form', id));+ await sdk.addElement('form', id, secPtr, ai.subgridSectionIntent({ subgridClassId: SUBGRID_CLASS_ID, targetEntity: 'new_ticket', relationshipName: 'new_customer_new_ticket', viewId: '{00000000-0000-0000-0000-0000000000v1}', label: 'Tickets' }));await sdk.pushArtifact('form', id);const formxml = String((cap.find((c) => /systemforms/.test(c.url)) || {}).body.formxml);assert.match(formxml, /new_customer_new_ticket/, 'RelationshipName is serialized');@@ -173,15 +173,15 @@ test('events author + MERGE at /bag/c: appending to an existing <events> regionconst cap = [];const sdk = freshSdk(cap);const intent = ai.compileFormIntent(custSpec, custSpec.forms[0], { notesClassId: NOTES_CLASS_ID });- const id = buildFormShell(sdk, intent);+ const id = await buildFormShell(sdk, intent);// First handler -> new region.- let bagC = (sdk.getArtifact('form', id).bag.c) || [];+ let bagC = ((await sdk.getArtifact('form', id)).bag.c) || [];const nextI = bagC.reduce((m, e) => Math.max(m, e.i), -1) + 1;- sdk.addElement('form', id, '/bag/c', { i: nextI, node: ai.formEventsRegionIntent([{ event: 'onload', library: 'a.js', function: 'A.onLoad' }]) });+ await sdk.addElement('form', id, '/bag/c', { i: nextI, node: ai.formEventsRegionIntent([{ event: 'onload', library: 'a.js', function: 'A.onLoad' }]) });// Second handler -> append to the SAME region's children (the merge path the engine uses on rebuild).- bagC = sdk.getArtifact('form', id).bag.c;+ bagC = (await sdk.getArtifact('form', id)).bag.c;const regionIdx = bagC.findIndex((e) => e.node && e.node.n === 'events');- sdk.addElement('form', id, `/bag/c/${regionIdx}/node/c`, ai.formEventsRegionIntent([{ event: 'onsave', library: 'a.js', function: 'A.onSave' }]).c[0]);+ await sdk.addElement('form', id, `/bag/c/${regionIdx}/node/c`, ai.formEventsRegionIntent([{ event: 'onsave', library: 'a.js', function: 'A.onSave' }]).c[0]);await sdk.pushArtifact('form', id);const formxml = String((cap.find((c) => /systemforms/.test(c.url)) || {}).body.formxml);assert.match(formxml, /A\.onLoad/, 'first handler serialized');@@ -193,10 +193,10 @@ test('field removal: removeElement on the cell pointer drops the field from theconst cap = [];const sdk = freshSdk(cap);const intent = ai.compileFormIntent(custSpec, custSpec.forms[0], { notesClassId: NOTES_CLASS_ID });- const id = buildFormShell(sdk, intent);- const ptr = ai.findFieldCellPointer(sdk.getArtifact('form', id), 'new_tier');+ const id = await buildFormShell(sdk, intent);+ const ptr = ai.findFieldCellPointer(await sdk.getArtifact('form', id), 'new_tier');assert.ok(ptr, 'the new_tier cell is located');- sdk.removeElement('form', id, ptr);+ await sdk.removeElement('form', id, ptr);await sdk.pushArtifact('form', id);const formxml = String((cap.find((c) => /systemforms/.test(c.url)) || {}).body.formxml);assert.match(formxml, /datafieldname="new_name"/, 'primary field kept');@@ -219,8 +219,9 @@ test('412 conflict: pushArtifact resolves to { success:false, error } (the signaconst sdk = createMakerSdk({ workspacePath: dir, instanceUrl: 'https://example.crm.dynamics.com', httpClient });sdk.initWorkspace();await sdk.fetchArtifact('form', FID);- sdk.updateElement('form', FID, '/tabs/0', { expanded: false });+ await sdk.updateElement('form', FID, '/tabs/0', { expanded: false });const result = await sdk.pushArtifact('form', FID);- assert.strictEqual(result.success, false, 'a 412 is signalled by a failed PushResult, NOT a thrown error');+ // `saved` is the renamed `success`; accept either so this pins the contract, not the bundle.+ assert.strictEqual(result.saved !== undefined ? result.saved : result.success, false, 'a 412 is signalled by a failed PushResult, NOT a thrown error');assert.ok(result.error, 'the conflict carries an error the engine reports');});diff --git a/plugins/model-apps/scripts/tests/header-nav-real-bundle.test.js b/plugins/model-apps/scripts/tests/header-nav-real-bundle.test.jsnew file mode 100644index 000000000..bb39bbb3b--- /dev/null+++ b/plugins/model-apps/scripts/tests/header-nav-real-bundle.test.js@@ -0,0 +1,151 @@+'use strict';+// REAL BUNDLE: the header/navigation refresh VALUE ENCODING.+//+// `app.headerNavigationRefresh` delegates to the SDK's `setHeaderAndNavigationRefresh` precisely+// because the encoding is a trap: it is a `datatype = 0` (Number) TRI-STATE where ON is '2', not+// '1'. Of the nine Number settings with rows in a live org, eight use '1' for on and only this one+// uses '2' — and writing '1' is ACCEPTED by the API and then silently fails to enable the feature.+//+// The plugin's own tests stub `setHeaderAndNavigationRefresh` and assert delegation, which is the+// right thing to test on that side. But delegation only protects us if the BUNDLE gets the encoding+// right, and a re-vendor could flip it with every plugin test still green: the plugin would report+// `created.headerNavigationRefresh: true` while the setting quietly did nothing.+//+// So this pins the wire payload against the real bundle, the same way lcid-real-bundle.test.js pins+// the language option.+const test = require('node:test');+const assert = require('node:assert');+const os = require('node:os');+const path = require('node:path');+const fs = require('node:fs');++const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');+const APP_ID = '11111111-1111-1111-1111-111111111111';+// Every app the PLUGIN creates carries an icon (`ensureAppIcon` -> `appDef.iconWebResourceId`), and+// the SDK now REQUIRES one: it auto-resolves an IMAGE web resource and throws `APP_ICON_UNRESOLVED`+// when the org has none. It used to fall back to ANY unmanaged web resource, which on an org whose+// images are all managed returned a JAVASCRIPT file and made the platform reject the create with an+// opaque error. These tests drive the SDK directly, so they must pass an icon like production does.+const APP_ICON_ID = '11111111-2222-3333-4444-555555555555';+const dirs = [];++// The setting write is an upsert keyed by (settingdefinitionid, parentappmoduleid), so the SDK first+// looks the definition up and probes for an existing row. Answer both, then record the write.+function sdkWithCapture({ existingRow = null } = {}) {+ const { createMakerSdk } = require(BUNDLE);+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hdrnav-'));+ dirs.push(dir);+ const writes = [];+ const httpClient = {+ get: async (url) => {+ const u = String(url);+ if (/settingdefinition/i.test(u)) {+ return { status: 200, headers: {}, body: { value: [{ settingdefinitionid: '22222222-2222-2222-2222-222222222222', uniquename: 'HeaderAndNavigationRefresh', datatype: 0 }] } };+ }+ if (/appsetting/i.test(u)) {+ return { status: 200, headers: {}, body: { value: existingRow ? [existingRow] : [] } };+ }+ return { status: 200, headers: {}, body: {} };+ },+ post: async (url, body) => { writes.push({ verb: 'post', url: String(url), body }); return { status: 204, headers: { 'odata-entityid': 'https://x/appsettings(33333333-3333-3333-3333-333333333333)' }, body: {} }; },+ patch: async (url, body) => { writes.push({ verb: 'patch', url: String(url), body }); return { status: 204, headers: {}, body: {} }; },+ put: async () => ({ status: 204, headers: {}, body: {} }),+ delete: async () => ({ status: 204, headers: {}, body: {} }),+ };+ const sdk = createMakerSdk({ workspacePath: dir, instanceUrl: 'https://contoso.crm.dynamics.com', httpClient });+ sdk.initWorkspace();+ return { sdk, writes };+}++const settingValueOf = (writes) => {+ const w = writes.find((x) => x.body && typeof x.body.value === 'string');+ return w ? w.body.value : undefined;+};++test.after(() => { for (const d of dirs) fs.rmSync(d, { recursive: true, force: true }); });++test('REAL BUNDLE: enabling the header/navigation refresh writes the tri-state ON value "2"', async () => {+ const { sdk, writes } = sdkWithCapture();+ const outcome = await sdk.setHeaderAndNavigationRefresh(APP_ID, true);+ assert.ok(['created', 'updated', 'unchanged'].includes(outcome), `unexpected outcome: ${JSON.stringify(outcome)}`);+ const value = settingValueOf(writes);+ assert.strictEqual(value, '2',+ 'ON must be "2". "1" is accepted by the API and then silently fails to enable the feature, so a '+ + 'bundle that wrote "1" would produce a green build with the feature off.');+});++test('REAL BUNDLE: disabling writes "1", and ON/OFF are not the same value', async () => {+ const { sdk, writes } = sdkWithCapture();+ await sdk.setHeaderAndNavigationRefresh(APP_ID, false);+ const off = settingValueOf(writes);+ assert.strictEqual(off, '1', 'OFF is "1"');++ const on = sdkWithCapture();+ await on.sdk.setHeaderAndNavigationRefresh(APP_ID, true);+ // The guard that matters if the constants are ever swapped or collapsed: if ON and OFF serialized+ // identically, every single-value assertion above could still pass on one branch.+ assert.notStrictEqual(settingValueOf(on.writes), off, 'ON and OFF must not serialize to the same value');+});++test('REAL BUNDLE: the setting row is bound to the app module id', async () => {+ // The row is keyed by (settingdefinitionid, parentappmoduleid). Binding the wrong id would write a+ // real row that simply governs nothing — a silent no-op with a success return.+ const { sdk, writes } = sdkWithCapture();+ await sdk.setHeaderAndNavigationRefresh(APP_ID, true);+ const body = writes.find((w) => w.body && typeof w.body.value === 'string')?.body || {};+ const bind = JSON.stringify(body);+ assert.match(bind, new RegExp(APP_ID), `the app module id must appear in the write; got ${bind}`);+ assert.match(bind, /appmodule/i, 'bound through an appmodule navigation property');+});++test('REAL BUNDLE: a non-boolean is rejected rather than coerced', async () => {+ // The plugin validates `app.headerNavigationRefresh` as a boolean, but the SDK is the last line of+ // defence for any other caller: a truthy string like "false" must not be read as ON.+ //+ // Wrapped in an async thunk because the SDK validates SYNCHRONOUSLY — it throws before returning a+ // promise, which `assert.rejects` alone does not treat as a rejection.+ const { sdk } = sdkWithCapture();+ for (const bad of ['true', 'false', 1, 0, null]) {+ await assert.rejects(+ async () => sdk.setHeaderAndNavigationRefresh(APP_ID, bad),+ `${JSON.stringify(bad)} must be rejected, not coerced`+ );+ }+ // And the happy path still works, so the guard is not simply rejecting everything.+ const ok = sdkWithCapture();+ await ok.sdk.setHeaderAndNavigationRefresh(APP_ID, true);+ assert.strictEqual(settingValueOf(ok.writes), '2');+});++test('REAL BUNDLE: a NEW app gets the header/navigation refresh ON by default', async () => {+ // The behaviour that made the plugin's original "opt-in, default off" documentation wrong, and+ // that made a `headerNavigationRefresh: false` in an App Spec a silent no-op.+ //+ // Pushing a brand-new app writes the setting UNPROMPTED. So the platform default is ON, and an+ // author who wants the classic header/navigation needs an ACTIVE off-write — which is why the+ // build honours `false` instead of skipping it. If a future SDK flips this default, this test is+ // what tells us before a user's app silently changes appearance.+ const { sdk, writes } = sdkWithCapture();+ const app = sdk.createArtifact('app', { name: 'Default App', uniqueName: 'cr_defaultapp', iconWebResourceId: APP_ICON_ID });+ assert.strictEqual(app.headerAndNavigationRefresh, true,+ 'the SDK defaults the app artifact field to true');++ await sdk.pushArtifact('app', app.id);+ const setting = writes.find((w) => /appsetting/i.test(w.url) && w.body && typeof w.body.value === 'string');+ assert.ok(setting, 'pushing a new app writes an app setting unprompted; urls: ' + JSON.stringify(writes.map((w) => w.url)));+ assert.strictEqual(setting.body.value, '2',+ "the unprompted default write is the ON value '2'");+});++test('REAL BUNDLE: setting headerAndNavigationRefresh false on the app writes the OFF value', async () => {+ // The opt-out path. '1' is OFF for this tri-state; if this ever wrote '2' or nothing, an author+ // asking for the classic experience would silently get the new one.+ const { sdk, writes } = sdkWithCapture();+ const app = sdk.createArtifact('app', { name: 'Off App', uniqueName: 'cr_offapp', headerAndNavigationRefresh: false, iconWebResourceId: APP_ICON_ID });+ assert.strictEqual(app.headerAndNavigationRefresh, false, 'the explicit false survives onto the artifact');++ await sdk.pushArtifact('app', app.id);+ const setting = writes.find((w) => /appsetting/i.test(w.url) && w.body && typeof w.body.value === 'string');+ assert.ok(setting, 'an app setting is still written');+ assert.strictEqual(setting.body.value, '1', "OFF is '1' — and it must differ from the ON value");+});diff --git a/plugins/model-apps/scripts/tests/helpers/mock-sdk.js b/plugins/model-apps/scripts/tests/helpers/mock-sdk.jsindex 43ca2362b..7a4dc2b17 100644--- a/plugins/model-apps/scripts/tests/helpers/mock-sdk.js+++ b/plugins/model-apps/scripts/tests/helpers/mock-sdk.js@@ -4,6 +4,12 @@// calls; returns benign successes so the build reaches the app-shell + publish phases.// Minimal JsonPointer + form-seed helpers so the mock simulates the SDK's generic mutation surface// (addElement/updateElement/removeElement/getArtifact) the build engine now uses.+//+// The generic surface is `async` HERE because it is async in the REAL SDK. That fidelity is+// load-bearing, not cosmetic: when this mock returned plain values, an engine call that forgot its+// `await` still behaved correctly under the mock (`await` on a non-promise is a no-op), so every+// mock-driven test passed while the real bundle silently fed a Promise into a pure helper. Keeping+// the mock synchronous made ~1500 tests blind to that entire class. Do not "simplify" these back.function jpGet(o, p) { let c = o; for (const t of (p === '' ? [] : p.split('/').slice(1))) { if (c == null) return undefined; c = c[t]; } return c; }function jpSet(o, p, v) { const ts = p.split('/').slice(1); const l = ts.pop(); let c = o; for (const t of ts) c = c[t]; c[l] = v; }function jpRemove(o, p) { const ts = p.split('/').slice(1); const l = ts.pop(); let c = o; for (const t of ts) c = c[t]; if (Array.isArray(c)) c.splice(Number(l), 1); else delete c[l]; }@@ -20,6 +26,8 @@ function makeSimpleMockSdk() {createSolution: async (o) => { calls.push(['createSolution', o]); return { id: 'sol-1' }; },createTable: async (o) => { calls.push(['createTable', o]); return { logicalName: o.schemaName.toLowerCase(), entitySetName: `${o.schemaName.toLowerCase()}s` }; },createColumn: async (e, o) => { calls.push(['createColumn', e, o]); return { logicalName: o.schemaName.toLowerCase() }; },+ setColumnVisualization: async (e, c, v) => { calls.push(['setColumnVisualization', e, c, v]); },+ getColumnVisualization: async () => 'None',createCustomerColumn: async (e, o) => ({ logicalName: o.schemaName.toLowerCase() }),createGlobalOptionSet: async (o) => ({ name: o.name }),insertStatusValue: async () => 100000001,@@ -44,15 +52,15 @@ function makeSimpleMockSdk() {art.id = id; store[`${t}:${id}`] = art; return jclone(art);},createWebResource: async (o) => { calls.push(['createWebResource', o.name]); return { id: `wr-${++idc}`, name: o.name }; },- pushArtifact: async (t, id) => ({ type: t, id, success: true }),- getArtifact: (t, id) => store[`${t}:${id}`] || { id, columns: [] },+ pushArtifact: async (t, id) => ({ type: t, id, saved: true, shipped: false, publish: { kind: 'notRequested' } }),+ getArtifact: async (t, id) => { await Promise.resolve(); return store[`${t}:${id}`] || { id, columns: [] }; },fetchArtifact: async (t, id) => { if (!store[`${t}:${id}`]) store[`${t}:${id}`] = t === 'form' ? seedForm(id) : t === 'app' ? { id, siteMap: { areas: [] } } : { id, columns: [] }; return store[`${t}:${id}`]; },- addElement: (t, id, ptr, el) => { const a = store[`${t}:${id}`] || (store[`${t}:${id}`] = { id }); const arr = jpGet(a, ptr); if (Array.isArray(arr)) arr.push(jclone(el)); return jclone(a); },- updateElement: (t, id, ptr, patch) => { const a = store[`${t}:${id}`] || (store[`${t}:${id}`] = { id }); jpSet(a, ptr, jclone(patch)); return jclone(a); },- removeElement: (t, id, ptr) => { const a = store[`${t}:${id}`]; if (a) jpRemove(a, ptr); return jclone(a || { id }); },+ addElement: async (t, id, ptr, el) => { await Promise.resolve(); const a = store[`${t}:${id}`] || (store[`${t}:${id}`] = { id }); const arr = jpGet(a, ptr); if (Array.isArray(arr)) arr.push(jclone(el)); return jclone(a); },+ updateElement: async (t, id, ptr, patch) => { await Promise.resolve(); const a = store[`${t}:${id}`] || (store[`${t}:${id}`] = { id }); jpSet(a, ptr, jclone(patch)); return jclone(a); },+ removeElement: async (t, id, ptr) => { await Promise.resolve(); const a = store[`${t}:${id}`]; if (a) jpRemove(a, ptr); return jclone(a || { id }); },updateRecord: async () => undefined,addSolutionComponent: async () => undefined,- publishArtifact: async () => undefined,+ publishArtifact: async (type, id) => ({ type, id, shipped: true, publish: { kind: 'verified' } }),getAiReadiness: async (opts) => { calls.push(['getAiReadiness', opts]); return { enabled: true }; },setAppAiFeatures: async (appUnique, flags, opts) => { calls.push(['setAppAiFeatures', appUnique, flags, opts]); return { applied: Object.keys(flags).filter((k) => flags[k]), skipped: [] }; },configureRowSummary: async (promptSpec, opts) => { calls.push(['configureRowSummary', promptSpec, opts]); return { modelId: 'model-' + promptSpec.entityLogicalName, aiSkillConfigId: 'skill-' + promptSpec.entityLogicalName }; },diff --git a/plugins/model-apps/scripts/tests/hydrate-spec.test.js b/plugins/model-apps/scripts/tests/hydrate-spec.test.jsindex c43e931d8..e0e6c7c3a 100644--- a/plugins/model-apps/scripts/tests/hydrate-spec.test.js+++ b/plugins/model-apps/scripts/tests/hydrate-spec.test.js@@ -255,3 +255,124 @@ test('validateAppSpec rejects a javascript: subarea url outright (#430 guard intassert.strictEqual(v.ok, false);assert.ok((v.errors || []).some((e) => /http\(s\) URL or a \$webresource/.test(e)), JSON.stringify(v.errors));});++// UPGRADE PATH. An app deployed BEFORE `directEntry` existed has a page manifest carrying+// `pageInput` and no `directEntry`. App Spec validation now requires the pair, and+// `download-model-app.js` validates BEFORE it writes anything — so without a default here, the+// download hard-fails and writes NO spec file at all. The author is left with nothing to edit and no+// way back into the download → edit → rebuild loop.+//+// That is the same shape as #430 ("no spec file was written at all ... over a single unrelated nav+// entry"), which this release fixes — so reintroducing it through the rule that closed a DIFFERENT+// hole would be a straight regression for every app that already uses pageInput.+function legacyPageInputRead() {+ return {+ app: async () => ({+ name: 'A', description: '',+ siteMap: { areas: [{ title: 'M', groups: [{ title: 'G', subAreas: [+ { type: 'GenPage', genPageId: '11111111-1111-1111-1111-111111111111', title: 'Overview' },+ { type: 'GenPage', genPageId: '22222222-2222-2222-2222-222222222222', title: 'Detail' },+ ] }] }] },+ }),+ // Note: no `directEntry` on either page — this manifest predates the field.+ pages: async () => [+ { pageId: '11111111-1111-1111-1111-111111111111', name: 'Overview', key: 'overview', navigatesTo: [{ targetKey: 'detail', data: { orderId: 'string' } }], dataSources: [], codeFile: 'overview.tsx' },+ { pageId: '22222222-2222-2222-2222-222222222222', name: 'Detail', key: 'detail', pageInput: { data: { orderId: 'string' } }, dataSources: [], codeFile: 'detail.tsx' },+ ],+ entities: async () => [{ schemaName: 'new_order', displayName: 'Order', primaryAttribute: { schemaName: 'new_name', displayName: 'Name' }, columns: [] }],+ webResources: async () => [], solution: async () => ({ uniqueName: 'S', publisherPrefix: 'new' }),+ };+}++test('a downloaded app that predates directEntry still produces a VALID spec (upgrade path)', async () => {+ const spec = await hydrateSpec(legacyPageInputRead());+ const v = validateAppSpec(spec, { profile: 'plan', reconstructed: true });+ assert.strictEqual(v.ok, true,+ 'download validates before writing, so an invalid spec here means no file is written at all: '+ + JSON.stringify(v.errors));++ const detail = spec.pages.find((p) => p.key === 'detail');+ assert.deepStrictEqual(Object.keys(detail.pageInput.data), ['orderId'], 'the input survives');+ // `emptyState`, not `selector`: the already-deployed .tsx has no picker, so promising one would be+ // a claim about code that does not exist.+ assert.strictEqual(detail.directEntry.behavior, 'emptyState');+ assert.match(detail.directEntry.note, /predates directEntry/i,+ 'the injected value says where it came from, so the author can review rather than discover it');+});++// The case the test above DODGES, and the one that matters more: a legacy page whose input has NO+// producing `navigatesTo` edge at all -- it was supplied externally, or by the page's own .tsx.+// Injecting `directEntry` does not help there, because the ORPHANED-INPUT rule fires instead and is+// equally fatal, so download would still write no file. Reviewed and caught precisely because the+// first test supplied a matching edge and never exercised this path.+function legacyOrphanInputRead() {+ const read = legacyPageInputRead();+ return {+ ...read,+ // Same two pages, but Overview no longer navigates with `orderId`.+ pages: async () => (await read.pages()).map((p) => (p.key === 'overview' ? { ...p, navigatesTo: [{ targetKey: 'detail' }] } : p)),+ };+}++test('a legacy page whose pageInput has NO producer still downloads (authoring rule, not a deploy rule)', async () => {+ const spec = await hydrateSpec(legacyOrphanInputRead());++ // As an AUTHORED spec this is still an error -- the rule keeps its teeth for anything hand-written.+ const authored = validateAppSpec(spec, { profile: 'plan' });+ assert.strictEqual(authored.ok, false, 'authoring still rejects an input nothing produces');+ assert.ok((authored.errors || []).some((e) => /no page navigates to it with that data/.test(e)),+ JSON.stringify(authored.errors));++ // As a RECONSTRUCTION of an app that already exists, it must be writable -- with the finding+ // surfaced, not swallowed.+ const reconstructed = validateAppSpec(spec, { profile: 'plan', reconstructed: true });+ assert.strictEqual(reconstructed.ok, true,+ 'download must still emit a spec: ' + JSON.stringify(reconstructed.errors));+ assert.ok((reconstructed.warnings || []).some((w) => /no page navigates to it with that data/.test(w)),+ 'the finding is reported as a warning, not dropped: ' + JSON.stringify(reconstructed.warnings));+});++test('reconstructed mode relaxes ONLY the producer rule, not real structural errors', async () => {+ // A blanket "reconstructed means anything goes" would be worse than the bug it fixes.+ const spec = await hydrateSpec(legacyOrphanInputRead());+ spec.appShell.areas[0].groups[0].subAreas.push({ title: 'Bad', url: 'javascript:alert(1)' });+ const v = validateAppSpec(spec, { profile: 'plan', reconstructed: true });+ assert.strictEqual(v.ok, false, 'a javascript: url is still fatal under reconstruction');++ const spec2 = await hydrateSpec(legacyOrphanInputRead());+ spec2.pages.find((p) => p.key === 'detail').directEntry = { behavior: 'shrug' };+ const v2 = validateAppSpec(spec2, { profile: 'plan', reconstructed: true });+ assert.strictEqual(v2.ok, false, 'an illegal directEntry.behavior is still fatal under reconstruction');+});++test('the defaulted directEntry is reported, not silent', async () => {+ const spec = await hydrateSpec(legacyPageInputRead());+ // Non-enumerable, like the other download diagnostics: app-spec.json stays the user-facing+ // contract and must not gain transient upgrade metadata.+ assert.deepStrictEqual(spec.directEntryDefaulted, ['detail']);+ assert.strictEqual(Object.keys(spec).includes('directEntryDefaulted'), false,+ 'diagnostics must not leak into the written spec');+});++test('directEntry is defaulted ONLY where it is missing and actually required', async () => {+ // An author-supplied value is never overwritten.+ const read = legacyPageInputRead();+ const base = await read.pages();+ read.pages = async () => base.map((p) => (p.key === 'detail' ? { ...p, directEntry: { behavior: 'selector' } } : p));+ const kept = await hydrateSpec(read);+ assert.strictEqual(kept.pages.find((p) => p.key === 'detail').directEntry.behavior, 'selector');+ assert.deepStrictEqual(kept.directEntryDefaulted, [], 'nothing was defaulted, so nothing is reported');++ // A page with NO pageInput does not need directEntry and must not acquire one — the spec stays+ // minimal, and an unnecessary field would imply a decision the author never made.+ const spec = await hydrateSpec(legacyPageInputRead());+ assert.strictEqual(spec.pages.find((p) => p.key === 'overview').directEntry, undefined);++ // An EMPTY pageInput.data declares no keys, so validation does not require directEntry either.+ const emptyInput = legacyPageInputRead();+ const pages = await emptyInput.pages();+ emptyInput.pages = async () => pages.map((p) => (p.key === 'detail' ? { ...p, pageInput: { data: {} } } : p));+ const spec2 = await hydrateSpec(emptyInput);+ assert.strictEqual(spec2.pages.find((p) => p.key === 'detail').directEntry, undefined,+ 'the default tracks the validation condition exactly, not the mere presence of pageInput');+});diff --git a/plugins/model-apps/scripts/tests/lcid-real-bundle.test.js b/plugins/model-apps/scripts/tests/lcid-real-bundle.test.jsnew file mode 100644index 000000000..d9319b992--- /dev/null+++ b/plugins/model-apps/scripts/tests/lcid-real-bundle.test.js@@ -0,0 +1,207 @@+'use strict';+// #455 — REAL BUNDLE: the authoring language must reach the serializers.+//+// The plugin's data-model labels have honoured the org language since #447, but form, sitemap and+// dashboard labels went through SDK serializers that hardcoded `const LCID = 1033` with no caller+// override. That is now `MakerSdkOptions.languageCode`, and the plugin threads a resolved LCID into+// `createMakerSdk` (see `makeSdk` in build-model-app.js).+//+// COVERAGE: form labels, sitemap titles, AND dashboard labels are all covered below.+//+// The dashboard half was an open hole until now, and the reason is worth keeping: an EMPTY dashboard+// emits no `<labels>` at all, so there was nothing to assert. It needs a POPULATED one. A re-vendor+// that dropped dashboard parameterization while leaving form and sitemap intact would previously+// have passed this file; it no longer can.+//+// Live status: the FORM half is live-verified — a form pushed against a genuinely Spanish org+// (base language 3082) came back FROM THE SERVER with `languagecode="3082"` on every label. The+// sitemap and dashboard halves are real-bundle-verified only. That is a real limit, not an+// oversight: every scratch organization available here provisions 1033 ONLY (30/30 probed), and the+// #456 guard correctly refuses to build at an LCID the org has not provisioned — so a live non-1033+// dashboard cannot be produced without a language pack nobody has installed. Observing 1033 on a+// 1033-only org proves nothing here, because 1033 is exactly what the OLD hardcoded serializer+// emitted; only the non-default assertions below separate the two.+//+// This drives the REAL vendored bundle rather than a mock, because the whole failure mode is "the+// mock accepts an option the bundle ignores". A mock-based test would stay green against a bundle+// that dropped the option on the floor — precisely the state this file exists to detect after a+// re-vendor.+//+// NOTE: `createArtifact` does NOT serialize. FormXML and sitemap XML are produced at PUSH time, so+// these capture the push payload, the same way vendor-sdk-smoke.test.js does.+const test = require('node:test');+const assert = require('node:assert');+const os = require('node:os');+const path = require('node:path');+const fs = require('node:fs');+// Every app the PLUGIN creates carries an icon: `ensureAppIcon` (sdk-build.js) resolves the author's+// `spec.app.icon` or generates an SVG web resource, and `appDef` passes its id as+// `iconWebResourceId`. These tests drive the SDK directly, so they must supply one too or they are+// exercising a path production never takes.+//+// The SDK now REQUIRES it: `appmodule.webresourceid` is a required attribute, and when no explicit id+// is given it auto-resolves an IMAGE web resource (PNG/JPG/GIF/ICO/SVG) and throws+// `APP_ICON_UNRESOLVED` if the environment has none. Previously it fell back to ANY unmanaged web+// resource — which on an org whose images are all managed returned a JAVASCRIPT file, and the platform+// rejected the create with an opaque "dependent component WebResource does not exist". Failing fast+// with a clear message is the better behaviour; these tests just have to stop relying on the old+// silent fallback. A synthetic id is right here — the mock transport never dereferences it.+const APP_ICON_ID = '11111111-2222-3333-4444-555555555555';++const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');+const dirs = [];++// Offline client that records every write so the serialized payload can be inspected. Reads answer+// with an empty envelope; nothing here needs a live org.+function sdkAt(languageCode) {+ const { createMakerSdk } = require(BUNDLE);+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'lcid-'));+ dirs.push(dir);+ const capture = [];+ const rec = (verb) => async (url, body) => { capture.push({ verb, url, body }); return {}; };+ const sdk = createMakerSdk({+ workspacePath: dir,+ instanceUrl: 'https://contoso.crm.dynamics.com',+ httpClient: { get: async () => ({}), post: rec('post'), patch: rec('patch'), put: rec('put'), delete: rec('delete') },+ ...(languageCode ? { languageCode } : {}),+ });+ sdk.initWorkspace();+ return { sdk, capture };+}++const langsIn = (s) => [...new Set(String(s || '').match(/languagecode="\d+"/g) || [])];+const lcidsIn = (s) => [...new Set(String(s || '').match(/LCID="\d+"/g) || [])];++async function pushedForm(languageCode) {+ const { sdk, capture } = sdkAt(languageCode);+ const form = sdk.createArtifact('form', { entityLogicalName: 'account', name: 'LCID Form' });+ await sdk.pushArtifact('form', form.id);+ const write = capture.find((c) => c.body && typeof c.body.formxml === 'string');+ assert.ok(write, 'a write carrying FormXML was issued; got ' + JSON.stringify(capture.map((c) => c.url)));+ return write.body.formxml;+}++test.after(() => { for (const d of dirs) fs.rmSync(d, { recursive: true, force: true }); });++test('REAL BUNDLE: createMakerSdk({ languageCode }) stamps FormXML labels at that LCID (#455)', async () => {+ const xml = await pushedForm(1031);+ assert.deepStrictEqual(langsIn(xml), ['languagecode="1031"'],+ `every FormXML label must carry the configured LCID and nothing else; got ${JSON.stringify(langsIn(xml))}`);+});++test('REAL BUNDLE: omitting languageCode preserves the previous 1033 behaviour exactly', async () => {+ // This is what makes threading the option safe: a build that passes nothing must behave exactly as+ // before, so the change is opt-in rather than a silent re-labelling of every existing app.+ const xml = await pushedForm(undefined);+ assert.deepStrictEqual(langsIn(xml), ['languagecode="1033"'], 'the SDK default LCID is unchanged');+});++test('REAL BUNDLE: the sitemap title LCID follows the configured language too (#455)', async () => {+ // The sitemap is the other half of #455 — <Titles><Title LCID="…"> was hardcoded alongside FormXML.+ const { sdk, capture } = sdkAt(1036);+ const app = sdk.createArtifact('app', { name: 'LCID App', iconWebResourceId: APP_ICON_ID });+ await sdk.pushArtifact('app', app.id);+ const write = capture.find((c) => c.body && typeof c.body.sitemapxml === 'string');+ assert.ok(write, 'a write carrying sitemap XML was issued; got ' + JSON.stringify(capture.map((c) => c.url)));+ const found = lcidsIn(write.body.sitemapxml);+ assert.ok(found.length > 0, 'the sitemap carries at least one Title LCID');+ assert.deepStrictEqual(found, ['LCID="1036"'],+ `sitemap titles must use the configured LCID; got ${JSON.stringify(found)}`);+});++test('REAL BUNDLE: languageCode is a live contract — two LCIDs must not serialize identically', async () => {+ // The guard against a future re-vendor quietly dropping the option. If a bundle ignored+ // `languageCode`, both branches would produce identical bytes and a single-LCID assertion could+ // still pass by coincidence on the default path.+ const a = await pushedForm(1031);+ const b = await pushedForm(3082);+ assert.notStrictEqual(a, b, 'identical input at two different LCIDs must not serialize identically');+ assert.deepStrictEqual(langsIn(a), ['languagecode="1031"']);+ assert.deepStrictEqual(langsIn(b), ['languagecode="3082"']);+});++// --- dashboards: the third serializer #455 parameterized -------------------------------------+//+// Pushes the payload PRODUCTION builds, via the exported `dashboardComponent`, rather than a+// hand-copied literal. A duplicated shape would keep passing after production changed, which is the+// failure mode this whole file exists to prevent.+async function pushedDashboard(languageCode) {+ const { dashboardComponent } = require(path.resolve(__dirname, '..', 'lib', 'sdk-build.js'));+ const { sdk, capture } = sdkAt(languageCode);+ const art = sdk.createArtifact('dashboard', { name: 'LCID Dashboard' });+ // A tile must carry a NAME: the name becomes the cell's <label description="…">, and a dashboard+ // with no labelled tile emits no <labels> at all — which is exactly why this was uncoverable+ // before. One list tile and one chart tile, so both branches of dashboardComponent are exercised.+ const tiles = [+ { type: 'list', name: 'Recent', targetEntity: 'account', viewId: '{11111111-1111-1111-1111-111111111111}' },+ { type: 'chart', name: 'By Priority', targetEntity: 'account', viewId: '{11111111-1111-1111-1111-111111111111}', visualizationId: '{22222222-2222-2222-2222-222222222222}' },+ ];+ for (let i = 0; i < tiles.length; i++) {+ await sdk.addElement('dashboard', art.id, '/components', dashboardComponent(tiles[i], i));+ }+ await sdk.pushArtifact('dashboard', art.id);+ const write = capture.find((c) => c.body && typeof c.body.formxml === 'string');+ assert.ok(write, 'a write carrying dashboard FormXML was issued; got ' + JSON.stringify(capture.map((c) => c.url)));+ return write.body.formxml;+}++// Does EVERY <label> element carry languagecode="<lcid>"?+//+// One predicate, used for both the assertion and its guard. That matters: the earlier version+// counted `<label` occurrences against `languagecode="…"` occurrences inline, and its guard+// re-derived those counts with its own expressions — so making the primary comparison tautological+// (both sides counting `<label`) would have left the guard passing independently. A guard that does+// not run the code it guards proves nothing about it.+//+// Inspects each label TAG rather than counting attributes document-wide, so an attribute belonging+// to some other element cannot stand in for a missing one:+// <label description="Recent" languagecode="1031" />+function allLabelsHaveLanguage(xml, lcid) {+ const labels = String(xml || '').match(/<label\b[^>]*>/g) || [];+ if (!labels.length) return false;+ return labels.every((tag) => new RegExp(`languagecode="${lcid}"`).test(tag));+}++test('REAL BUNDLE: a POPULATED dashboard stamps its labels at the configured LCID (#455)', async () => {+ const xml = await pushedDashboard(1031);+ assert.deepStrictEqual(langsIn(xml), ['languagecode="1031"'],+ `every dashboard label must carry the configured LCID and nothing else; got ${JSON.stringify(langsIn(xml))}`);+ // `langsIn` DEDUPES and only sees labels that carry the attribute at all, so on its own it cannot+ // distinguish "every label is 1031" from "one label is 1031 and another has no languagecode".+ assert.ok((xml.match(/<label\b/g) || []).length > 0, 'a populated dashboard emits at least one label');+ assert.strictEqual(allLabelsHaveLanguage(xml, 1031), true,+ 'every <label> element must carry languagecode="1031"');+ // GUARD THE GUARD: prove that SAME predicate can FAIL. Delete the attribute from one label and it+ // must go false. Without this, a predicate that always returned true would look identical to a+ // passing test — which is exactly how the tautology in header-nav-real-bundle.test.js survived.+ const doctored = xml.replace(/ languagecode="1031"/, '');+ assert.strictEqual(allLabelsHaveLanguage(doctored, 1031), false,+ 'the completeness predicate must detect a label whose languagecode was removed');+});++test('REAL BUNDLE: omitting languageCode leaves dashboard labels at 1033', async () => {+ const xml = await pushedDashboard(undefined);+ assert.deepStrictEqual(langsIn(xml), ['languagecode="1033"'],+ 'the SDK dashboard default LCID is unchanged, so threading the option stays opt-in');+});++test('REAL BUNDLE: two LCIDs must not serialize a dashboard identically', async () => {+ // Same drift guard as the form case: a bundle that ignored the option would emit identical bytes.+ const a = await pushedDashboard(1031);+ const b = await pushedDashboard(3082);+ assert.notStrictEqual(a, b, 'identical dashboard input at two LCIDs must not serialize identically');+ assert.deepStrictEqual(langsIn(a), ['languagecode="1031"']);+ assert.deepStrictEqual(langsIn(b), ['languagecode="3082"']);+});++test('REAL BUNDLE: a chart tile serializes VisualizationId, never ChartId', async () => {+ // Belongs here because this is the only place the production tile payload is pushed through the+ // real bundle and the resulting XML inspected. `ChartId` is rejected by the platform's dashboard+ // FormXML schema and cost a whole phase; the mock-based test had asserted the wrong name, so the+ // suite agreed with the bug. Asserting on the SERIALIZED bytes cannot be fooled the same way.+ const xml = await pushedDashboard(1031);+ assert.match(xml, /<VisualizationId>\{22222222-2222-2222-2222-222222222222\}<\/VisualizationId>/,+ 'the chart tile binds its visualization through VisualizationId');+ assert.doesNotMatch(xml, /ChartId/,+ 'ChartId is not a legal child of <parameters> and must never be emitted');+});diff --git a/plugins/model-apps/scripts/tests/page-manifest.test.js b/plugins/model-apps/scripts/tests/page-manifest.test.jsindex 3f8ccc1e7..f203412ab 100644--- a/plugins/model-apps/scripts/tests/page-manifest.test.js+++ b/plugins/model-apps/scripts/tests/page-manifest.test.js@@ -362,3 +362,35 @@ test('parseManifest REJECTS two keys mapping to the same pageId (case-insensitiv});assert.strictEqual(parseManifest(dup), null);});++// The manifest is a STORED artifact — it lives in the solution and can be edited, truncated or+// produced by an older build. Parsing it loosely defeats the point of parsing it at all: a+// `directEntry` whose behavior is bogus would round-trip into a rebuild and fail App Spec+// validation there, far from its cause. Reject it here instead.+test('parseManifest rejects a directEntry whose behavior is not a legal value', () => {+ const good = {+ schemaVersion: 1,+ pages: [{ key: 'detail', name: 'Detail', pageId: '11111111-1111-1111-1111-111111111111',+ pageInput: { data: { orderId: 'string' } }, directEntry: { behavior: 'selector' } }],+ };+ assert.ok(parseManifest(JSON.stringify(good)), 'a legal behavior parses');++ for (const behavior of ['shrug', '', null, 123, undefined]) {+ const bad = JSON.parse(JSON.stringify(good));+ bad.pages[0].directEntry = behavior === undefined ? {} : { behavior };+ assert.strictEqual(parseManifest(JSON.stringify(bad)), null,+ `directEntry.behavior=${JSON.stringify(behavior)} must be rejected whole`);+ }++ // Both legal behaviours parse, and an absent directEntry is still fine (only pages with+ // pageInput are required to carry one, and that rule lives in App Spec validation).+ for (const behavior of ['selector', 'emptyState']) {+ const ok = JSON.parse(JSON.stringify(good));+ ok.pages[0].directEntry = { behavior };+ assert.ok(parseManifest(JSON.stringify(ok)), behavior + ' must parse');+ }+ const noDe = JSON.parse(JSON.stringify(good));+ delete noDe.pages[0].directEntry;+ delete noDe.pages[0].pageInput;+ assert.ok(parseManifest(JSON.stringify(noDe)), 'a page with neither field parses');+});diff --git a/plugins/model-apps/scripts/tests/sdk-async-surface.test.js b/plugins/model-apps/scripts/tests/sdk-async-surface.test.jsnew file mode 100644index 000000000..4b022d290--- /dev/null+++ b/plugins/model-apps/scripts/tests/sdk-async-surface.test.js@@ -0,0 +1,931 @@+'use strict';+// ASYNC-SURFACE INVARIANT — the guard for the SDK's sync -> async read/mutate change.+//+// Upstream made the generic artifact surface asynchronous ("300s cache staleness with async+// revalidating reads"): a read may now revalidate against the server before serving the cached+// copy, so `getArtifact` and every generic mutator return Promises. The bundle the plugin shipped+// before that change returned plain values.+//+// Why this needs a guard rather than trusting the suite: dropping an `await` does NOT throw.+// A Promise is truthy, so the engine's `|| {}` fallbacks stay dormant, and the PURE helpers that+// consume the result silently see a Promise instead of an artifact:+//+// hasSubgrid(Promise) -> false -> a rebuild splices a DUPLICATE sub-grid+// hasQuickView(Promise) -> false -> a rebuild splices a DUPLICATE quick-view+// formFieldLogicals(Promise) -> [] -> every spec field looks missing, so all are re-added+// findFieldCellPointer(Promise)-> null -> an explicit-layout removal silently never happens+//+// Each of those is a wrong-artifact outcome on a real org with a 2xx status and a green build.+// Only 4 of the plugin's ~1590 tests caught the original breakage, because most engine paths are+// covered through mocks that resolve synchronously. So the scan below is the real gate.+//+// ---------------------------------------------------------------------------------------------+// WHAT THIS GUARD IS, AND IS NOT.+//+// It is a TRIPWIRE for the realistic regression — someone adds `provision.getArtifact(...)` and+// forgets the `await` — not a proof. It is built to fail in the safe direction: candidates are+// matched against the RAW source and only dismissed when two INDEPENDENT signals agree, so a flaw+// in its lexer produces a false positive (loud, waivable) rather than a hidden call.+//+// It is not sound, and cannot be made sound with regular expressions. Four rounds of adversarial+// review each found new constructs, and the residual known limits are:+// * PARAMETER destructuring — `function use({ getArtifact }) { getArtifact(id); }`. No textual+// anchor distinguishes an ObjectPattern from an ObjectExpression, so trying to catch it flagged+// every mock object literal in the suite. An AST distinguishes them; a regex cannot.+// * A receiver reached through a value the scanner cannot follow (returned from a function,+// stored in an array, rebound conditionally).+// * A call written inside a string or template on a code line is REPORTED (an accepted false+// positive, asserted below so nobody "fixes" it by reopening the dismissal path).+// The exhaustive version needs a JavaScript parser. That is deliberately not done here: the plugin+// ships with no runtime dependencies and CI runs `node scripts/run-tests.js` with no install step,+// so adding a parser is a larger change than this belongs in. Tracked in+// https://github.com/microsoft/power-platform-skills/issues/475, where the corpus below doubles as+// the acceptance suite for the replacement.+// ---------------------------------------------------------------------------------------------+const test = require('node:test');+const assert = require('node:assert');+const os = require('node:os');+const path = require('node:path');+const fs = require('node:fs');++const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');+const SCRIPTS_DIR = path.resolve(__dirname, '..');++// The generic-surface methods that became async. Keep in sync with the dynamic check below — that+// test fails if the bundle disagrees with this list, in either direction.+const ASYNC_SDK_METHODS = [+ 'addElement',+ 'findElements',+ 'getArtifact',+ 'moveElement',+ 'queryTree',+ 'removeElement',+ 'updateElement',+];++// Matching is by METHOD NAME on ANY receiver, not on an allow-list of receiver identifiers.+//+// An earlier version scanned only `provision.` and `sdk.`, which an adversarial review broke in one+// line: `const client = provision; client.getArtifact(...)` is a real bug that the receiver list+// cannot see, and no list can, because a receiver can be aliased, destructured, or passed as a+// parameter. Matching the method name instead is sound here for a checked reason, not a hopeful+// one: a scan of the plugin found NO local definition of any of these names (they exist only on the+// SDK), so a same-named method on some unrelated object does not currently exist. If one is ever+// introduced, it lands as a loud failure here — which is the correct direction for this trade —+// and is resolved with the waiver below or by renaming.+//+// `\\s*\\??\\.\\s*` accepts optional chaining (`provision?.getArtifact(...)`) and a receiver split+// from its method across lines; both are ordinary JS that an earlier version of this pattern+// silently ignored.+// Comments are whitespace in JavaScript, so `provision /* note */ .getArtifact(...)` and+// `provision // note` + `.getArtifact(...)` are ordinary calls. They are NOT handled by widening+// this pattern: an alternation containing `/\*[\s\S]*?\*/` inside a `*` quantifier rescans the rest+// of the file from every position, which hung the whole test run. They are handled instead by+// running the same pattern a second time over the COMMENT-BLANKED view, where a comment has already+// become spaces — see the two-pass scan in findUnawaitedCalls.+// `(?:\\?\\.)?` before the argument list accepts optional INVOCATION, `getArtifact?.(...)`, which is+// a different construct from optional MEMBER access.+const SEP = '\\s*';+const CALL_RE = new RegExp(`(await\\s+)?(?:\\b[A-Za-z_$][\\w$]*|\\))${SEP}\\??\\.${SEP}(${ASYNC_SDK_METHODS.join('|')})${SEP}(?:\\?\\.)?\\(`, 'g');++// Computed access — `provision['getArtifact'](...)` — needs a SEPARATE pass, because the method+// name lives inside a string literal and the scanner below blanks strings (deliberately: a method+// name quoted in a log message is not a call). So this pattern is matched against a+// comments-stripped-but-strings-intact copy instead.+const COMPUTED_RE = new RegExp(`(await\\s+)?(?:\\b[A-Za-z_$][\\w$]*|\\))${SEP}(?:\\?\\.)?${SEP}\\[${SEP}['"\`](${ASYNC_SDK_METHODS.join('|')})['"\`]${SEP}\\]${SEP}(?:\\?\\.)?\\(`, 'g');++// DESTRUCTURING these methods off the SDK is banned outright rather than tracked.+//+// `const { getArtifact } = provision; getArtifact(id)` is a real evasion, and following it properly+// needs data-flow analysis: the bare call site carries no receiver, so no pattern can tell it from+// an unrelated local function. Banning the binding is the honest alternative — it is a construct+// the plugin never uses, it costs nothing to avoid, and it turns an undetectable call site into a+// detectable declaration.+//+// `[^{}();]` rather than a narrow identifier class: a binding pattern legitimately contains+// defaults (`= fallback`), renames, rest (`...rest`) and computed keys (`['getArtifact']`), all of+// which a `[\w$\s,:]`-style class silently missed. Excluding braces, parentheses and semicolons is+// what keeps it from matching an ordinary `for (…) { … }` block that merely mentions one of these+// names — a false positive the permissive version really did produce.+// Two anchors were tried; only the DECLARATION form survives. Anchoring on `}` followed by `,` or+// `)` was meant to catch parameter destructuring, but it matched every mock object literal in the+// suite (`{ name: 'getArtifact', args: [...] }` passed to a function), which is a false positive+// the ban cannot afford — a binding finding is not waivable by the ordinary marker. Parameter+// destructuring of the SDK therefore remains undetected; it is a construct nothing here would+// plausibly write, and catching it costs more than it is worth.+// `[^{};]` rather than `[^{}();]`: a default can be a CALL (`{ getArtifact = fallback() }`), which+// excluding parens made invisible. Braces and semicolons stay excluded — they are what keep this+// from matching an ordinary `for (…) { … }` block that merely mentions one of these names.+// `=[^=>]` so `=>` is not mistaken for an assignment.+const DESTRUCTURE_RE = new RegExp(`\\{[^{};]*\\b(${ASYNC_SDK_METHODS.join('|')})\\b[^{};]*\\}\\s*=[^=>]`, 'g');++// An intentionally unawaited call (e.g. handing the promise to Promise.all) must say so IN A+// COMMENT, either on the same line or on the line immediately above it — the latter because these+// calls are often too long for a readable trailing comment.+//+// The marker must be a real comment, not merely the characters appearing somewhere on the line: a+// review pointed out that `console.log('sdk-async-ok')` on the previous line would otherwise waive+// the call below it. Requiring adjacency keeps the waiver next to the code it excuses, so it cannot+// drift onto an unrelated call later.+const OPT_OUT = 'sdk-async-ok';+// A destructuring finding needs its OWN marker. The ordinary waiver must never hide a binding —+// one comment would otherwise conceal every call made through it — but a genuine false positive+// still needs an escape that is not "rename your variable".+const OPT_OUT_BINDING = 'sdk-async-binding-ok';++/**+ * True only when `marker` appears inside a real `//` COMMENT on this line.+ *+ * Determined from the RAW line by SYNTAX, not by comparing transformed views. Two earlier versions+ * inferred "comment" from "present in the raw text but absent from a stripped copy", and both were+ * wrong in the same way — anything else the stripper happened to blank also looked like a comment.+ * First it was strings (`console.log('sdk-async-ok')`), then, after that was fixed, regex literals+ * and template text (`const marker = /sdk-async-ok/;`). Inference from absence keeps finding new+ * ways to be wrong, so this asks a question with a definite answer instead.+ *+ * Accepted shape: the line is ONLY a comment — trimmed, it starts with `//`.+ *+ * A TRAILING comment is deliberately not accepted. Deciding whether a `//` late in a line is a+ * comment start or part of a string/regex requires the very lexing that may have desynced, and+ * every shortcut tried for it was wrong in a new way. Requiring the waiver to sit on its own line+ * makes the question unanswerable-by-ambiguity: nothing can span into a line that begins with `//`.+ * The cost is one extra line at three call sites; the benefit is that a waiver cannot be forged.+ */+function markerInComment(rawLine, marker) {+ const trimmed = String(rawLine || '').trimStart();+ return trimmed.startsWith('//') && trimmed.includes(marker);+}++const isWaiverLine = (rawLine) => markerInComment(rawLine, OPT_OUT);++/**+ * Blank out comments and string-literal TEXT, preserving every byte offset and newline so match+ * indices still map to the original line numbers.+ *+ * This is a small LEXER, not a regex pass, because every cheaper approach was proven wrong here:+ *+ * - "skip lines starting with //" discarded the whole line, so live code after a block comment+ * hid an un-awaited call.+ * - a naive strip corrupts a URL like https://x when it sits inside a string.+ * - ignoring REGEX LITERALS is worse than either. A regex such as one matching a quote+ * character contains a lone quote, which a regex-unaware scanner treats as an opening quote+ * and then blanks everything up to the next quote — silently erasing the CODE ON FOLLOWING+ * LINES. A guard that erases the code it is meant to inspect fails OPEN, which is the one+ * thing it must never do.+ * - blanking a template literal wholesale erases its ${...} interpolations, which are ordinary+ * executable code and can contain a real un-awaited call.+ *+ * So: comments and quoted TEXT are blanked, regex literals are consumed as opaque tokens, and+ * template interpolations stay live (with a depth stack, so nesting works). `keepStrings` leaves+ * quoted text intact for the computed-access pass, which must see the quoted method name.+ *+ * The output array is pre-sized to the input length, so a byte can never be added or dropped and+ * an offset bug is impossible by construction — an earlier version could lose a byte when a+ * backslash escape ran past the end, shifting every reported line number after it.+ */+function stripCommentsAndStrings(source, { keepStrings = false } = {}) {+ const out = new Array(source.length);+ for (let k = 0; k < source.length; k++) out[k] = source[k] === '\n' ? '\n' : ' ';+ const live = (from, to) => { for (let k = from; k < to && k < source.length; k++) out[k] = source[k]; };++ // A '/' starts a regex only where a VALUE may begin; after a value it is division.+ //+ // The last significant CHARACTER is not sufficient on its own: `return /['"]/.test(s)` is real+ // code in this plugin (scripts/lib/genpage-cli.js), and after `return` the previous character is+ // `n`, so a character-only rule reads the `/` as division and then treats the regex's quote as a+ // string opener. So keywords are checked too.+ //+ // Even with that, `/` after `)` stays genuinely ambiguous without a parser. Rather than pretend+ // otherwise, the string scanner below FAILS CLOSED: a single- or double-quoted string cannot+ // contain a raw newline in JavaScript, so if one is hit before the closing quote the scanner has+ // mis-lexed and reverts, leaving the text as code. That converts every possible regex+ // misclassification from "silently erases the following lines" into "leaves them visible" — the+ // safe direction for a guard, and the property that actually matters here.+ const REGEX_CAN_FOLLOW = '(,=:[!&|?{};+-*%~^<>';+ const REGEX_KEYWORDS = /(?:^|[^\w$])(?:return|typeof|instanceof|in|of|new|delete|void|case|do|else|yield|await|throw)$/;+ let prev = '';+ let i = 0;+ const regexMayStart = () => {+ if (prev === '' || REGEX_CAN_FOLLOW.includes(prev)) return true;+ // Look back over the code emitted so far for a keyword ending at this point.+ const back = out.slice(Math.max(0, i - 12), i).join('').replace(/\s+$/, '');+ return REGEX_KEYWORDS.test(back);+ };+ // Brace depth at which each open template interpolation closes.+ const templates = [];+ let braceDepth = 0;++ // Consume a template literal from `i`, stopping either at its closing backtick or at the start+ // of an interpolation (whose code the MAIN loop then scans normally). Returns false when the+ // literal never terminates, which means it was not a template at all.+ const runTemplate = () => {+ while (i < source.length) {+ if (source[i] === '\\') { i += 2; continue; }+ if (source[i] === '`') { i++; return true; }+ if (source.slice(i, i + 2) === '${') {+ live(i, i + 2);+ i += 2;+ braceDepth++;+ templates.push(braceDepth);+ return true;+ }+ i++;+ }+ return false;+ };++ while (i < source.length) {+ const ch = source[i];+ const two = source.slice(i, i + 2);++ if (two === '//') { while (i < source.length && source[i] !== '\n') i++; continue; }+ if (two === '/*') {+ const close = source.indexOf('*/', i + 2);+ i = close === -1 ? source.length : close + 2;+ continue;+ }++ if (ch === '"' || ch === "'") {+ const open = i;+ let j = i + 1;+ let closed = false;+ while (j < source.length) {+ if (source[j] === '\\') { j += 2; continue; }+ if (source[j] === '\n') break; // a quoted string cannot span a line -> we mis-lexed+ if (source[j] === ch) { j++; closed = true; break; }+ j++;+ }+ if (!closed) {+ // Not a string. Emit the quote as ordinary code and carry on from the next character, so a+ // misread apostrophe or regex quote can never blank the lines that follow it.+ out[i] = ch;+ prev = ch;+ i++;+ continue;+ }+ i = j;+ if (keepStrings) live(open, i);+ prev = 'x';+ continue;+ }++ if (ch === '`') {+ const open = i;+ i++;+ if (!runTemplate()) {+ // Unterminated: treat the backtick as code rather than swallowing the rest of the file.+ i = open;+ out[i] = ch;+ prev = ch;+ i++;+ continue;+ }+ if (keepStrings) live(open, Math.min(i, source.length));+ prev = 'x';+ continue;+ }++ if (ch === '}' && templates.length && braceDepth === templates[templates.length - 1]) {+ // Closing an interpolation: resume the enclosing template literal.+ out[i] = '}';+ i++;+ braceDepth--;+ templates.pop();+ runTemplate();+ prev = 'x';+ continue;+ }++ if (ch === '/' && regexMayStart()) {+ const open = i;+ i++;+ let inClass = false;+ let closed = false;+ while (i < source.length) {+ if (source[i] === '\\') { i += 2; continue; }+ if (source[i] === '[') inClass = true;+ else if (source[i] === ']') inClass = false;+ else if (source[i] === '/' && !inClass) { i++; closed = true; break; }+ else if (source[i] === '\n') break; // unterminated: not a regex after all+ i++;+ }+ if (!closed) { i = open; out[i] = ch; prev = ch; i++; continue; }+ while (i < source.length && /[a-z]/.test(source[i])) i++; // flags+ prev = 'x';+ continue;+ }++ if (ch === '{') braceDepth++;+ else if (ch === '}') braceDepth--;+ out[i] = ch;+ if (!/\s/.test(ch)) prev = ch;+ i++;+ }+ return out.join('');+}++/**+ * Find every un-awaited SDK call in `raw`, returning `{ line, text, kind }` findings.+ *+ * DIRECTION OF FAILURE — the property that makes this trustworthy.+ *+ * Candidates are matched against the RAW source, and a candidate is only DISMISSED when it can be+ * shown to be inert. Earlier versions did the opposite: they matched against a stripped copy, so+ * any flaw in the stripper made a real call invisible. Two separate stripper flaws did exactly+ * that (a regex literal's quote opening a fake string; a template literal swallowing its own+ * interpolation), and each turned the guard into a green light over a live bug.+ *+ * A candidate is DISMISSED only when both hold:+ * 1. the lexer blanked that offset, AND+ * 2. the ENTIRE raw line is inert — either it is trimmed-`//`, or the lexer blanked every+ * non-whitespace character on it.+ *+ * (2) is whole-LINE on purpose. Testing only `startsWith('/*')` or `startsWith('*')` was wrong:+ * `/* legacy *\/ provision.getArtifact(id)` starts with a block comment and then contains a LIVE+ * call, so a prefix test dismissed it — the same class of bug as the very first line-prefix filter.+ * Requiring the whole line to be blank means live code on the line always keeps it visible.+ *+ * Deliberately NOT included: "the match is inside quotes on this line". Deciding that needs the+ * very lexing that may have desynced, and the quote-counting shortcut fails on+ * `if (c) /['"]/.test(v) && provision.getArtifact('form', id)` — an odd quote count before a LIVE+ * call. The cost of leaving it out is a false positive when a call appears inside a string literal+ * on a code line — rare, loud, waivable, and asserted below as a KNOWN accepted false positive.+ */+function findUnawaitedCalls(raw) {+ const code = stripCommentsAndStrings(raw);+ const codeWithStrings = stripCommentsAndStrings(raw, { keepStrings: true });+ const rawLines = raw.split('\n');+ const found = [];+ let candidates = 0;++ const lineAt = (index) => raw.slice(0, index).split('\n').length;+ const codeLines = code.split('\n');+ const strLines = codeWithStrings.split('\n');+ // A waiver must be a whole-line `//` comment AND be blanked in BOTH lexer views.+ //+ // The second condition closes a forge: a raw line beginning with `//` is not necessarily a+ // comment — inside a template literal it is just text, e.g.+ // const note = `+ // // sdk-async-ok`;+ // provision.getArtifact('form', id);+ // A real comment is blanked in both views; template/string text survives in the+ // string-preserving view. Note the direction: this condition only ever REJECTS a waiver, and a+ // rejected waiver produces a loud finding, so being wrong here is safe.+ const waives = (lineNo, marker = OPT_OUT) => {+ const rawLine = rawLines[lineNo - 1];+ if (!markerInComment(rawLine, marker)) return false;+ const inCode = codeLines[lineNo - 1];+ const inStr = strLines[lineNo - 1];+ return inCode !== undefined && inCode.trim() === '' && inStr !== undefined && inStr.trim() === '';+ };+ // Reading the RAW lines above `lineNo`, is there an unclosed `/*`? Independent of the lexer.+ const insideOpenBlockComment = (lineNo) => {+ for (let n = lineNo - 2; n >= 0; n--) {+ const l = rawLines[n] || '';+ const open = l.lastIndexOf('/*');+ const close = l.lastIndexOf('*/');+ if (open > close) return true; // this line opens a comment that is still open+ if (close > open) return false; // a comment closed above us, so we are not inside one+ }+ return false;+ };+ const wholeLineInert = (lineText, lineNo) => {+ const trimmed = String(lineText || '').trimStart();+ if (trimmed.startsWith('//')) return true;+ const blankedLine = codeLines[lineNo - 1];+ const lexerSaysBlank = blankedLine !== undefined && blankedLine.trim() === '';+ // A block-comment CONTINUATION line. THREE signals must agree, because two were not enough:+ // a composed desync can blank a line that legitimately begins with `*` —+ // if (c) /`/.test(v);+ // const n = x+ // * provision.getArtifact('f', id); <- multiplication, not a comment+ // const s = `ok`;+ // So besides the `*` shape and the lexer, the RAW SOURCE ABOVE must show an open block comment:+ // searching upward, a `/*` must appear before any `*/`. That check reads the raw text and does+ // not depend on the lexer, so a desync cannot supply it.+ if (trimmed.startsWith('*') && lexerSaysBlank && insideOpenBlockComment(lineNo)) return true;+ // Otherwise decide from the RAW LINE ALONE, independently of the lexer.+ //+ // This matters because the lexer-derived signal is not independent of the lexer: a multi-line+ // desync blanks the WHOLE line, so "the lexer blanked every character" agreed with itself and+ // dismissed a live call —+ // if (c) /`/.test(v);+ // /* legacy *\/ provision.getArtifact('f', id); <- blanked by the desync, and dismissed+ // const s = `ok`;+ // Removing the complete comments from the raw line leaves `provision.getArtifact(...)`, which+ // is code, so the line is not inert no matter what the lexer believes.+ let s = String(lineText || '').replace(/\/\*[\s\S]*?\*\//g, ' ');+ const lineComment = s.indexOf('//');+ if (lineComment !== -1) s = s.slice(0, lineComment);+ const unterminated = s.indexOf('/*');+ if (unterminated !== -1) s = s.slice(0, unterminated);+ return s.trim() === '';+ };+ const dismissed = (index, lineText, lineNo, blankedView) => {+ const blanked = blankedView[index] !== raw[index];+ return blanked && wholeLineInert(lineText, lineNo);+ };++ const consider = (m, kind, blankedView) => {+ candidates++;+ if (m[1]) return; // awaited+ const index = m.index;+ const line = lineAt(index);+ const text = rawLines[line - 1] || '';+ if (dismissed(index, text, line, blankedView)) return;+ if (waives(line - 1) || waives(line - 2)) {+ // Deduplicated by line: the two-pass scan can match the same call twice, and a doubled count+ // would trip the "waivers must stay rare" assertion for no real reason.+ found.waivedLines = found.waivedLines || new Set();+ found.waivedLines.add(line);+ return;+ }+ const finding = { line, text: text.trim(), kind };+ if (!found.some((f) => f.line === line && f.kind === kind)) found.push(finding);+ };++ // TWO PASSES per pattern.+ //+ // The RAW pass is the one that cannot be defeated by a lexer flaw. The COMMENT-BLANKED pass+ // exists because comments are whitespace in JavaScript, so `provision /* note */ .getArtifact()`+ // is a real call that the raw pass cannot see with a `\s*` separator — and widening the separator+ // to include comments made the regex rescan the file from every position and hang the run.+ // Findings are the UNION, deduplicated by line, so the extra pass can only ADD detection.+ CALL_RE.lastIndex = 0;+ for (const m of raw.matchAll(CALL_RE)) consider(m, 'call', code);+ CALL_RE.lastIndex = 0;+ for (const m of code.matchAll(CALL_RE)) consider(m, 'call', code);+ COMPUTED_RE.lastIndex = 0;+ for (const m of raw.matchAll(COMPUTED_RE)) consider(m, 'computed', codeWithStrings);+ COMPUTED_RE.lastIndex = 0;+ for (const m of codeWithStrings.matchAll(COMPUTED_RE)) consider(m, 'computed', codeWithStrings);+ DESTRUCTURE_RE.lastIndex = 0;+ for (const m of raw.matchAll(DESTRUCTURE_RE)) {+ const line = lineAt(m.index);+ const text = rawLines[line - 1] || '';+ if (dismissed(m.index, text, line, code)) continue;+ // The ordinary waiver must NOT apply here: one comment would hide every call made through the+ // binding, and those call sites carry no receiver, so nothing else could ever see them. A+ // dedicated marker exists for a genuine false positive.+ if (waives(line - 1, OPT_OUT_BINDING)) continue;+ found.push({ line, text: text.trim(), kind: 'destructured binding' });+ }+ found.candidates = candidates;+ found.waived = found.waivedLines ? found.waivedLines.size : 0;+ return found;+}++function pluginSourceFiles() {+ const out = [];+ const walk = (dir) => {+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ const full = path.join(dir, entry.name);+ // The vendored bundle is generated SDK code, and _vendor-build is the dev-only bundler.+ if (entry.isDirectory()) {+ if (entry.name === 'vendor' || entry.name === '_vendor-build' || entry.name === 'node_modules') continue;+ walk(full);+ } else if (entry.name.endsWith('.js')) {+ out.push(full);+ }+ }+ };+ walk(SCRIPTS_DIR);+ return out;+}++test('every SDK generic-surface call in the plugin is awaited', () => {+ const findings = [];+ let scanned = 0;+ let calls = 0;+ let waived = 0;++ for (const file of pluginSourceFiles()) {+ // This file names the methods in prose and in its own pattern definitions; scanning it would+ // match its own documentation.+ if (path.basename(file) === path.basename(__filename)) continue;+ const raw = fs.readFileSync(file, 'utf8');+ scanned++;+ const hits = findUnawaitedCalls(raw);+ calls += hits.candidates;+ waived += hits.waived || 0;+ for (const h of hits) {+ const finding = `${path.relative(SCRIPTS_DIR, file)}:${h.line}: [${h.kind}] ${h.text}`;+ if (!findings.includes(finding)) findings.push(finding);+ }+ }++ // Positive assertions first: a scan that silently matched nothing would "pass" forever.+ assert.ok(scanned > 50, `the scan walked the plugin source (saw ${scanned} files)`);+ assert.ok(calls > 30, `the scan found the SDK calls it is meant to guard (saw ${calls})`);+ // The waiver must stay RARE and deliberate. If this ever grows large, the rule is being routed+ // around rather than followed.+ assert.ok(waived <= 5, `only a handful of deliberate ${OPT_OUT} waivers exist (saw ${waived})`);+ assert.deepStrictEqual(findings, [],+ 'these SDK calls are NOT awaited, but the vendored SDK returns a Promise. Unawaited, they do '+ + 'not throw — they silently feed a Promise to a pure helper and corrupt the artifact '+ + `(see this file's header). Add \`await\`, or annotate the line with ${OPT_OUT} if the promise `+ + `is deliberately handed elsewhere:\n ${findings.join('\n ')}`);+});++test('GUARD-THE-GUARD: the matcher catches evasions and does not fire on look-alikes', () => {+ // The scan above can only be trusted if its matcher is itself tested. Two of these cases were+ // proven evasions of an earlier version of this file (aliased receiver; live code after a block+ // comment), and two more were found by probing it afterwards (optional chaining; computed+ // access). Pinning them here means a future "simplification" of the regex fails loudly instead of+ // quietly reopening the hole.+ // `check` calls the REAL production scanner, not a re-implementation of it. An earlier version+ // approximated the scan and diverged from it in exactly the way that mattered (it passed a+ // different view to the waiver check), so the test passed while production was broken. Anything+ // this test proves is therefore a property of the shipped code.+ const check = (code) => findUnawaitedCalls(code).length > 0;++ const MUST_FLAG = {+ 'plain un-awaited call': "const a = provision.getArtifact('form', id);",+ 'ALIASED receiver': "const c = provision; const a = c.getArtifact('f', id);",+ 'live code AFTER a block comment': "/* legacy */ const a = provision.getArtifact('f', id);",+ 'optional chaining': "const a = provision?.getArtifact('f', id);",+ 'computed access': "const a = provision['getArtifact']('f', id);",+ 'computed access via backticks': 'const a = provision[`getArtifact`](\'f\', id);',+ 'receiver split from method across lines': "const a = provision\n .getArtifact('f', id);",+ 'promise handed to Promise.all without a waiver': "await Promise.all(ids.map((i) => sdk.getArtifact('f', i)));",+ // A regex literal containing a lone quote used to desynchronise the scanner: the quote was read+ // as a string opener, blanking every following line up to the next quote — including this call.+ // That made the guard fail OPEN, which is strictly worse than a missed edge case.+ 'a call AFTER a regex literal containing a quote': "const q = /['\"]/;\nconst a = provision.getArtifact('f', id);",+ // A `${}` interpolation is ordinary executable code; blanking the whole template hid it.+ 'a call inside a template interpolation': "const s = `${provision.getArtifact('f', id)}`;",+ 'a call after a multi-line template': "const s = `line1\n${x.y}\nline2`;\nconst a = provision.getArtifact('f', id);",+ 'parenthesized receiver': "const a = (provision).getArtifact('f', id);",+ 'DESTRUCTURED off the SDK (banned outright — a bare call site has no receiver to match)':+ "const { getArtifact } = provision;\nconst a = getArtifact('f', id);",+ 'destructured with a rename': "const { getArtifact: g } = provision;",+ 'destructured ACROSS LINES': "const {\n getArtifact: readArtifact,\n} = provision;",+ 'destructured with a waiver comment (the ban is NOT waivable)':+ "const { getArtifact } = provision; // sdk-async-ok\nconst a = getArtifact('f', id);",+ 'optional COMPUTED access': "const a = provision?.['getArtifact']('f', id);",+ // The string-blanked view made a marker in a STRING look exactly like a comment, so this+ // waived the call below it. That is a bypass anyone could have written by accident.+ 'a call whose previous line merely PRINTS the waiver marker':+ "console.log('sdk-async-ok');\nconst a = provision.getArtifact('f', id);",+ // A regex after `return` is real code in this plugin. Misreading it as division made the+ // regex's quote open a fake string, blanking the following lines — the guard erasing the code+ // it exists to inspect.+ 'a call after a regex following a KEYWORD (return)':+ "function q(s) { return /['\"]/.test(s); }\nconst a = provision.getArtifact('f', id);",+ 'a call after a regex containing a BACKTICK':+ "function q(s) { return /`/.test(s); }\nconst a = provision.getArtifact('f', id);",+ 'a call after a regex following a control parenthesis':+ "if (c) /['\"]/.test(v);\nconst a = provision.getArtifact('f', id);",+ 'a call after an apostrophe that cannot be a string (unterminated on its line)':+ "const n = 5; // it's fine\nconst a = provision.getArtifact('f', id);",+ // Sol round 3: SAME-LINE ambiguity, where the newline fallback cannot help. These are the+ // cases that motivated inverting the scan to dismiss-only-when-provably-inert.+ 'SAME LINE: a regex after a control paren whose quote could close before the call':+ "if (c) /['\"]/.test(v) && provision.getArtifact('form', id);",+ 'SAME LINE: division mistaken for a regex, spanning the call':+ "const n = x++ / provision.getArtifact('form', id) / divisor;",+ 'SAME LINE: a regex containing a backtick, with a real template later on the line':+ "if (c) /`/.test(v) && provision.getArtifact('f', id); const s = `ok`;",+ // Sol round 3: binding forms a narrow character class silently missed.+ 'destructured with a DEFAULT': "const { getArtifact = fallback } = provision;",+ 'destructured with a rename AND a default': "const { getArtifact: read = fallback } = provision;",+ 'destructured with a REST element': "const { getArtifact, ...rest } = provision;",+ 'destructured with a COMPUTED key': "const { ['getArtifact']: read } = provision;",+ // Sol round 4: constructs where NO raw candidate was produced, or both dismissal signals+ // agreed wrongly.+ 'a comment between receiver and method (comments are whitespace in JS)':+ "provision /* note */ .getArtifact('form', id);",+ 'a comment between method and its argument list':+ "provision.getArtifact /* note */ ('form', id);",+ 'optional INVOCATION': "provision.getArtifact?.('form', id);",+ 'optional invocation of a computed access': "provision['getArtifact']?.('form', id);",+ 'a LIVE call on a line that merely STARTS with a block comment':+ "if (c) /`/.test(v);\n /* legacy */ provision.getArtifact('f', id);\nconst s = `ok`;",+ 'a default that is a CALL in a destructuring pattern':+ "const { getArtifact = fallback() } = provision;",+ // Sol round 5 (non-blocking, fixed anyway): a LINE comment is whitespace too, and a composed+ // desync could satisfy the block-comment-continuation exception on a multiplication line.+ 'a LINE comment between receiver and method':+ "provision // note\n .getArtifact('form', id);",+ 'a multiplication line that only LOOKS like a comment continuation':+ "if (c) /`/.test(v);\nconst n = x\n * provision.getArtifact('f', id);\nconst s = `ok`;",+ };+ for (const [label, code] of Object.entries(MUST_FLAG)) {+ assert.strictEqual(check(code), true, `the matcher must flag: ${label}`);+ }++ const MUST_NOT_FLAG = {+ 'a correctly awaited call': "const a = await provision.getArtifact('form', id);",+ 'an awaited optional-chained call': "const a = await provision?.getArtifact('f', id);",+ 'an awaited computed call': "const a = await provision['getArtifact']('f', id);",+ 'the method name inside a string': "log('call getArtifact() next');",+ 'the method name inside a comment': '// see provision.getArtifact(id) for why',+ 'the method name inside a regex literal': 'const re = /x\\.getArtifact\\(/;',+ 'a URL whose // sits inside a string': "const u = 'https://example.com/a//b'; const a = await sdk.getArtifact('f', id);",+ 'an object literal that merely mentions the name as a VALUE': "const m = { name: getArtifactLabel };",+ 'a mock object literal passed as an argument (must not read as destructuring)':+ "calls.push({ name: 'getArtifact', args: [t, id] });",+ 'documentation prose inside a real block comment':+ "/**\n * See provision.getArtifact(id) for the rationale.\n */\nconst x = 1;",+ };+ for (const [label, code] of Object.entries(MUST_NOT_FLAG)) {+ assert.strictEqual(check(code), false, `the matcher must NOT flag: ${label}`);+ }++ // ACCEPTED FALSE POSITIVES — documented, not fixed, because fixing them reopens a fail-open path.+ //+ // A receiver-and-method that appears inside a STRING on a CODE line is reported. Suppressing it+ // would mean deciding "this offset is inside a string", which needs the lexing that may itself+ // have desynced — the exact inference that hid a live call twice. So the guard reports it, and+ // the author adds a waiver comment. A false positive costs one line; a false negative ships+ // corrupted artifacts.+ const ACCEPTED_FALSE_POSITIVES = {+ 'a call written inside a template literal on a code line': 'log(`use x.getArtifact(y)`);',+ };+ for (const [label, code] of Object.entries(ACCEPTED_FALSE_POSITIVES)) {+ assert.strictEqual(check(code), true,+ `this is a KNOWN, accepted false positive and must stay detected rather than be silently `+ + `suppressed: ${label}`);+ }++ const waiverCase = (line) => isWaiverLine(line);+ assert.strictEqual(waiverCase(' // sdk-async-ok: handed to Promise.all'), true, 'a whole-line comment waives');+ assert.strictEqual(waiverCase(" console.log('sdk-async-ok');"), false, 'a marker inside a STRING must not waive');+ // Sol round 3: inference-from-absence also mistook regex and template text for a comment.+ assert.strictEqual(waiverCase(' const marker = /sdk-async-ok/;'), false, 'a marker inside a REGEX must not waive');+ assert.strictEqual(waiverCase(' const marker = `${v}sdk-async-ok`;'), false, 'a marker inside a TEMPLATE must not waive');+ assert.strictEqual(waiverCase(' x(); // sdk-async-ok'), false,+ 'a TRAILING comment does not waive — whether a late // is a comment cannot be decided without '+ + 'the lexing that may itself be wrong, so the waiver must be a whole-line comment');+ // A whole-line `//` is not necessarily a comment — inside a template it is text. A forged waiver+ // must not silence the call below it.+ assert.strictEqual(+ check("const note = `\n // sdk-async-ok`;\nprovision.getArtifact('form', id);"), true,+ 'a waiver forged from TEMPLATE TEXT must not waive the call below it');+ assert.strictEqual(+ check("// sdk-async-ok: genuinely handed elsewhere\nprovision.getArtifact('form', id);"), false,+ 'a REAL whole-line comment waiver still works');+});++test('a STALE_ARTIFACT from the async surface HALTS the build (fails closed, with the SDK remedy)', async () => {+ // `StaleArtifactError` is a NEW error class that only exists because reads became revalidating:+ // the SDK raises it when a mutation is applied to a copy it just refreshed, because "any pointer+ // derived from the old copy may now identify a different node". The engine has never seen it.+ //+ // It is reachable in production without any bug on our side: a long build can leave more than the+ // SDK's 300s staleness window between an artifact's fetch and a later mutation, and if someone+ // edits that artifact in Maker inside that window, the next mutation raises it.+ //+ // The requirement is NOT that the engine recovers — it is that it fails CLOSED and says what to+ // do, rather than continuing and shipping a half-applied artifact. This pins that, so a future+ // refactor of the error path cannot quietly downgrade it to a warning.+ const { makeRunner, BuildHalt } = require(path.resolve(SCRIPTS_DIR, 'lib', 'entity-provision.js'));+ const { SdkError } = require(BUNDLE);++ const events = [];+ const runner = makeRunner({ emit: (e) => events.push(e), total: 1 });+ const stale = new SdkError('STALE_ARTIFACT',+ 'Cannot apply the edit at /tabs/0 to form/abc: 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 — re-read the artifact, re-derive the pointer, and retry.');++ await assert.rejects(+ () => runner.run('forms', 'form "Customer"', async () => { throw stale; }),+ (err) => {+ assert.ok(err instanceof BuildHalt, 'a stale-artifact mutation halts the build');+ assert.strictEqual(err.code, 'STALE_ARTIFACT', 'the SDK error code is preserved for the caller');+ assert.match(err.message, /re-read the artifact, re-derive the pointer, and retry/,+ 'the operator is told the remedy, not just that something failed');+ return true;+ });++ assert.ok(events.some((e) => e.status === 'error' && e.phase === 'forms'),+ 'the failure is reported on the phase, not swallowed');+});++test('the committed bundle MATCHES its recorded provenance (a bundle-only change cannot go unnoticed)', () => {+ // Provenance that is not checked against the artifact is decoration. Without this, someone could+ // rebuild or hand-edit the bundle and leave PROVENANCE.json describing the previous one — which+ // is a more convincing version of exactly the failure that motivated the file: a committed bundle+ // whose stated origin was not its real origin.+ const provPath = path.resolve(__dirname, '..', 'vendor', 'PROVENANCE.json');+ assert.ok(fs.existsSync(provPath), 'the vendored bundle ships a PROVENANCE.json');+ const prov = JSON.parse(fs.readFileSync(provPath, 'utf8'));++ const bytes = fs.readFileSync(BUNDLE);+ // Hash the LF-NORMALISED content, not the raw bytes.+ //+ // The raw bytes are not stable across platforms: git's end-of-line normalisation rewrites LF to+ // CRLF on a Windows checkout, so the same commit yields a different size and hash than on Linux.+ // This was not theoretical — the first version of this test passed on ubuntu and macOS and failed+ // on windows-latest by exactly 60 bytes. `vendor/.gitattributes` marks the bundle `-text` so git+ // stops converting it, and this normalisation keeps the assertion true even in a checkout that+ // predates that rule or ignores it.+ const normalised = Buffer.from(bytes.toString('utf8').replace(/\r\n/g, '\n'), 'utf8');+ const sha256 = require('node:crypto').createHash('sha256').update(normalised).digest('hex');+ assert.strictEqual(prov.bundleBytes, normalised.length,+ 'PROVENANCE.json records the size of the bundle actually committed');+ assert.strictEqual(prov.bundleSha256, sha256,+ 'PROVENANCE.json records the sha256 of the bundle actually committed — re-run '+ + 'scripts/_vendor-build/build.js so the record matches the artifact');++ // A committed bundle must be reproducible: it may not come from an unknown or dirty source.+ assert.strictEqual(typeof prov.commit, 'string', 'the upstream commit is recorded');+ assert.match(prov.commit, /^[0-9a-f]{40}$/, 'the upstream commit is a full SHA, not a moving ref');+ assert.strictEqual(prov.dirtySdkPackage, 0,+ 'the bundle was built from a CLEAN SDK package (null means it could not be determined, which '+ + 'is not good enough for a committed artifact)');+ assert.notStrictEqual(prov.allowUnreproducible, true,+ 'a bundle built with --allow-unreproducible must never be committed');+ assert.strictEqual(prov.libIsStale, false, 'the SDK lib/ was not stale relative to its src/');+ // NOSTUB disables the stub plugin, pulling the real shell/UI packages into the bundle. Besides+ // being ~10x larger, those packages embed an internal ownership table that must not ship in a+ // public repo — so a NOSTUB build is never a committable artifact.+ assert.strictEqual(prov.nostub, false,+ 'the committed bundle was built WITH the stubs (a NOSTUB build pulls in shell packages that '+ + 'must not ship in a public repo)');+ // The recorded subject is committed to a PUBLIC repo, so it must not carry the upstream+ // merge-tool's PR id: unresolvable from here, and it advertises a tracker nobody reading this can+ // open. `sanitizeSubject` strips it at record time; this pins the committed artifact, which is the+ // thing that actually ships.+ //+ // Asserts against the sanitizer's OWN patterns rather than a local copy, so a prefix shape added+ // there can never be one this check silently stops looking for.+ const { MERGE_PREFIXES } = require(path.resolve(__dirname, '..', '_vendor-build', 'sanitize-subject.js'));+ assert.strictEqual(typeof prov.subject, 'string', 'the upstream commit subject is recorded');+ for (const re of MERGE_PREFIXES) {+ assert.doesNotMatch(prov.subject, re,+ `the recorded subject must not keep an upstream merge-tool prefix (matched ${re})`);+ }+});++// The sanitizer that produces the above. Unit-tested against the shapes the SDK's own history+// actually emits, plus the cases where it must NOT fire — a subject that merely mentions a merge is+// prose, and over-stripping would destroy the only human-readable part of the provenance record.+//+// Every id used here is SYNTHETIC. An earlier version of this test quoted the real upstream PR id as+// its example, which reintroduced into a public file exactly the identifier the function exists to+// remove — the fix and the test cancelling each other out.+test('sanitizeSubject strips merge-tool prefixes and nothing else', () => {+ const { sanitizeSubject, NO_DESCRIPTION } = require(path.resolve(__dirname, '..', '_vendor-build', 'sanitize-subject.js'));++ assert.strictEqual(+ sanitizeSubject('Merged PR 12345678: feat(cds-maker-sdk): configurable authoring LCID'),+ 'feat(cds-maker-sdk): configurable authoring LCID');+ assert.strictEqual(+ sanitizeSubject('merged pr 42 : fix(sdk): tolerate a missing label'),+ 'fix(sdk): tolerate a missing label');+ // A GitHub merge subject with a description after the branch ref keeps only the description.+ assert.strictEqual(+ sanitizeSubject('Merge pull request #4312 from someone/some-branch: fix(sdk): tolerate a missing label'),+ 'fix(sdk): tolerate a missing label');+ // The `#` is OPTIONAL — not every tool emits it, and requiring it let a real merge subject through+ // untouched while every test stayed green.+ assert.strictEqual(+ sanitizeSubject('Merge pull request 4312 from someone/some-branch: fix(sdk): x'),+ 'fix(sdk): x');+ // The ref is matched with [^:\s]+, not \S+. A greedy \S+ swallows a colon that belongs to the+ // DESCRIPTION, silently deleting the part that says what changed.+ assert.strictEqual(+ sanitizeSubject('Merge pull request #9 from owner/ref:fix(sdk): tolerate x'),+ 'fix(sdk): tolerate x');++ // Must NOT fire: the prefix is anchored, so a mid-sentence mention survives verbatim.+ const prose = 'fix(sdk): revert the change merged PR 99 introduced';+ assert.strictEqual(sanitizeSubject(prose), prose, 'a mid-sentence mention is prose, not a prefix');+ const plain = 'feat(sdk): add setHeaderAndNavigationRefresh';+ assert.strictEqual(sanitizeSubject(plain), plain, 'an already-clean subject is unchanged');++ // A subject that is ONLY a prefix yields a neutral placeholder. Returning the ORIGINAL (the+ // previous behaviour) put the identifier straight back and produced a value that failed the+ // committed-provenance assertion above — the sanitizer breaking its own contract.+ assert.strictEqual(sanitizeSubject('Merged PR 123:'), NO_DESCRIPTION);+ assert.strictEqual(sanitizeSubject('Merge pull request #4312 from someone/some-branch'), NO_DESCRIPTION,+ 'GitHub puts the description on the body line, so a bare merge subject is entirely prefix');+ // COLONLESS prefix-only subject. This is supported deliberately: requiring the colon left it+ // unchanged, and the invariant test could not see the hole because it uses the same patterns as+ // its oracle. Recorded as an exact input->output pair so the decision is visible, not implied.+ assert.strictEqual(sanitizeSubject('Merged PR 123'), NO_DESCRIPTION,+ 'a bare "Merged PR <n>" with no colon is still entirely prefix');++ // NEGATIVE CONTROLS for the colon-or-end alternation: text after the id is a real description, so+ // the subject is prose and must survive untouched. If these ever start changing, the alternation+ // has become too greedy.+ for (const keep of ['Merged PR 99 rollback of the shell change', 'Merge pull request 7 from owner/ref is not this shape']) {+ assert.strictEqual(sanitizeSubject(keep), keep, `must not fire on: ${keep}`);+ }+ // Non-strings pass through, because `git()` records null when the call fails and null must stay+ // distinguishable from an empty subject.+ assert.strictEqual(sanitizeSubject(null), null);+});++test('sanitizeSubject strips ARBITRARILY nested prefixes, not a fixed number', () => {+ // A capped loop looked defensive and silently reintroduced the bug past the cap: at a cap of 8,+ // nine nested prefixes returned a value still carrying the ninth. Depths well past any plausible+ // cap are asserted here. This cannot PROVE no cap is ever reintroduced — a cap above 100 would+ // still pass — but it catches any cap small enough that a reviewer would plausibly write it.+ const { sanitizeSubject, NO_DESCRIPTION } = require(path.resolve(__dirname, '..', '_vendor-build', 'sanitize-subject.js'));++ for (const depth of [1, 2, 8, 9, 25, 100]) {+ const nested = Array.from({ length: depth }, (_, i) => `Merged PR ${i + 1}: `).join('') + 'real description';+ assert.strictEqual(sanitizeSubject(nested), 'real description',+ `depth ${depth} must strip every prefix`);+ }+ // Nested prefixes with NO description at the end still resolve to the placeholder.+ const bare = Array.from({ length: 12 }, (_, i) => `Merged PR ${i + 1}:`).join(' ');+ assert.strictEqual(sanitizeSubject(bare), NO_DESCRIPTION);+ // Mixed tools nest too.+ assert.strictEqual(+ sanitizeSubject('Merged PR 5: Merge pull request 9 from owner/ref: real desc'),+ 'real desc');+});++test('sanitizeSubject output can NEVER match a merge prefix (the actual contract)', () => {+ // Case-by-case assertions only prove the cases someone thought of. The property that matters is+ // that NO input produces an output still carrying a prefix — which is what the committed+ // PROVENANCE.json must satisfy.+ //+ // STATED LIMIT, because it is easy to over-read this test: its oracle is MERGE_PREFIXES, the same+ // set the implementation strips with. It therefore proves "no output matches a pattern we+ // enumerate" — NOT "no output retains a merge prefix in some syntax nobody enumerated". A new+ // merge-tool syntax is invisible to both halves at once. The exact input->output assertions above+ // are what pin the enumerated shapes; this pins that stripping is exhaustive for them.+ const { sanitizeSubject, MERGE_PREFIXES } = require(path.resolve(__dirname, '..', '_vendor-build', 'sanitize-subject.js'));++ const corpus = [+ 'Merged PR 12345678: feat(sdk): x',+ 'Merged PR 123:',+ 'Merged PR 123',+ ' merged pr 7 : ',+ 'Merge pull request #4312 from someone/some-branch',+ 'Merge pull request 4312 from someone/some-branch',+ 'Merge pull request #4312 from someone/some-branch: desc',+ 'Merge pull request #9 from owner/ref:fix(sdk): tolerate x',+ 'Merged PR 1: Merged PR 2: doubly prefixed',+ Array.from({ length: 9 }, (_, i) => `Merged PR ${i + 1}: `).join('') + 'nine deep',+ Array.from({ length: 40 }, (_, i) => `Merged PR ${i + 1}: `).join('') + 'forty deep',+ 'Merged PR 5: Merge pull request 9 from owner/ref: mixed nesting',+ 'feat(sdk): plain',+ 'fix(sdk): revert the change merged PR 99 introduced',+ 'Merged PR 99 rollback of the shell change',+ '',+ ' ',+ ];++ for (const input of corpus) {+ const out = sanitizeSubject(input);+ for (const re of MERGE_PREFIXES) {+ assert.doesNotMatch(out, re,+ `sanitizeSubject(${JSON.stringify(input)}) returned ${JSON.stringify(out)}, which still matches ${re}`);+ }+ }+});++test('the real vendored bundle agrees with ASYNC_SDK_METHODS (no drift in either direction)', async () => {+ const { createMakerSdk } = require(BUNDLE);+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'async-surface-'));+ try {+ const httpClient = {+ get: async () => ({ status: 200, headers: {}, body: {} }),+ post: async () => ({ status: 204, headers: { 'odata-entityid': 'https://x/y(11111111-1111-1111-1111-111111111111)' }, body: {} }),+ patch: async () => ({ status: 204, headers: {}, body: {} }),+ delete: async () => ({ status: 204, headers: {}, body: {} }),+ put: async () => ({ status: 204, headers: {}, body: {} }),+ };+ const sdk = createMakerSdk({ workspacePath: dir, instanceUrl: 'https://example.crm.dynamics.com', httpClient });+ sdk.initWorkspace();+ const art = sdk.createArtifact('form', { name: 'F', entityLogicalName: 'account', formType: 'main', status: 'draft' });++ for (const method of ASYNC_SDK_METHODS) {+ assert.strictEqual(typeof sdk[method], 'function', `${method} exists on the bundle`);+ // Called with deliberately incomplete arguments: the point is only whether the failure is+ // delivered synchronously (a sync method throws) or as a rejected Promise (an async one).+ let returned;+ try {+ returned = sdk[method]('form', art.id);+ } catch {+ assert.fail(`${method} threw SYNCHRONOUSLY, so the bundle still has a sync ${method}. `+ + 'Remove it from ASYNC_SDK_METHODS and drop the now-pointless awaits, or the await scan '+ + 'above is enforcing a rule the SDK no longer has.');+ }+ assert.ok(returned && typeof returned.then === 'function',+ `${method} must return a Promise on the vendored bundle`);+ // A rejected probe must never surface as an unhandled rejection and fail an unrelated test.+ await Promise.resolve(returned).catch(() => {});+ }++ // The counter-examples that make "in either direction" true rather than a slogan. These are+ // called SYNCHRONOUSLY throughout the plugin, in many places, without `await`. If the SDK ever+ // makes one of them async, every one of those call sites becomes the same silent-corruption bug+ // — and nothing else in the suite would notice, because the async list above would still be+ // satisfied. A review pointed out this test proved only one direction; this is the other.+ assert.ok(!(art && typeof art.then === 'function'),+ 'createArtifact is still synchronous — the plugin uses its return value directly');+ const ws = sdk.initWorkspace();+ assert.ok(!(ws && typeof ws.then === 'function'),+ 'initWorkspace is still synchronous — every engine calls it un-awaited before any other work; '+ + 'if it became async, the workspace could be unready when the first artifact call runs');+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});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.jsindex 7d3ac49e5..65d20bfb5 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@@ -74,13 +74,13 @@ function mockSdk(opts = {}) {updateWebResource: async (id, o) => { calls.push({ name: 'updateWebResource', args: [id, o] }); return {}; },enrichDefaultViews: async () => ({ updated: [] }),createArtifact: (t, def) => { calls.push({ name: 'createArtifact', args: [t, def] }); const id = `${t}-${++idc}`; store[`${t}:${id}`] = Object.assign({ id }, def); return JSON.parse(JSON.stringify(store[`${t}:${id}`])); },- getArtifact: (t, id) => store[`${t}:${id}`] || { id },- addElement: () => ({}),- updateElement: (t, id, ptr, patch) => { calls.push({ name: 'updateElement', args: [t, id, ptr, patch] }); return {}; },- removeElement: () => ({}),- pushArtifact: async (t, id) => ({ type: t, id, success: true }),+ getArtifact: async (t, id) => { await Promise.resolve(); return store[`${t}:${id}`] || { id }; },+ addElement: async () => { await Promise.resolve(); return {}; },+ updateElement: async (t, id, ptr, patch) => { await Promise.resolve(); calls.push({ name: 'updateElement', args: [t, id, ptr, patch] }); return {}; },+ removeElement: async () => { await Promise.resolve(); return {}; },+ pushArtifact: async (t, id) => ({ type: t, id, saved: true, shipped: false, publish: { kind: 'notRequested' } }),addSolutionComponent: async (o) => { calls.push({ name: 'addSolutionComponent', args: [o] }); },- publishArtifact: async () => {},+ publishArtifact: async (type, id) => ({ type, id, shipped: true, publish: { kind: 'verified' } }),};return { sdk, calls };}diff --git a/plugins/model-apps/scripts/tests/sdk-build-pages-migrate.test.js b/plugins/model-apps/scripts/tests/sdk-build-pages-migrate.test.jsindex e4ebefaea..68ecb6bf2 100644--- a/plugins/model-apps/scripts/tests/sdk-build-pages-migrate.test.js+++ b/plugins/model-apps/scripts/tests/sdk-build-pages-migrate.test.js@@ -81,13 +81,13 @@ function mockSdk() {store[`${t}:${id}`] = art;return JSON.parse(JSON.stringify(art));},- getArtifact: (t, id) => { calls.push({ name: 'getArtifact', args: [t, id] }); return store[`${t}:${id}`] || { id }; },- addElement: (t, id, ptr, el) => { calls.push({ name: 'addElement', args: [t, id, ptr, el] }); return {}; },- updateElement: (t, id, ptr, patch) => { calls.push({ name: 'updateElement', args: [t, id, ptr, patch] }); return {}; },- removeElement: (t, id, ptr) => { calls.push({ name: 'removeElement', args: [t, id, ptr] }); return {}; },- pushArtifact: async (t, id) => { calls.push({ name: 'pushArtifact', args: [t, id] }); return { type: t, id, success: true }; },+ getArtifact: async (t, id) => { await Promise.resolve(); calls.push({ name: 'getArtifact', args: [t, id] }); return store[`${t}:${id}`] || { id }; },+ addElement: async (t, id, ptr, el) => { await Promise.resolve(); calls.push({ name: 'addElement', args: [t, id, ptr, el] }); return {}; },+ updateElement: async (t, id, ptr, patch) => { await Promise.resolve(); calls.push({ name: 'updateElement', args: [t, id, ptr, patch] }); return {}; },+ removeElement: async (t, id, ptr) => { await Promise.resolve(); calls.push({ name: 'removeElement', args: [t, id, ptr] }); return {}; },+ pushArtifact: async (t, id) => { calls.push({ name: 'pushArtifact', args: [t, id] }); return { type: t, id, saved: true, shipped: false, publish: { kind: 'notRequested' } }; },addSolutionComponent: async (o) => { calls.push({ name: 'addSolutionComponent', args: [o] }); },- publishArtifact: async (t, id) => { calls.push({ name: 'publishArtifact', args: [t, id] }); },+ publishArtifact: async (t, id) => { calls.push({ name: 'publishArtifact', args: [t, id] }); return { type: t, id, shipped: true, publish: { kind: 'verified' } }; },};return { sdk, calls };}diff --git a/plugins/model-apps/scripts/tests/sdk-build-pages-order.test.js b/plugins/model-apps/scripts/tests/sdk-build-pages-order.test.jsindex f29296dca..085640637 100644--- a/plugins/model-apps/scripts/tests/sdk-build-pages-order.test.js+++ b/plugins/model-apps/scripts/tests/sdk-build-pages-order.test.js@@ -54,11 +54,11 @@ function harness() {updateWebResource: async (id, o) => { calls.push({ name: 'updateWebResource', args: [id, o] }); manifestB64 = Buffer.from(o.content, 'utf8').toString('base64'); return {}; },enrichDefaultViews: async () => ({ updated: [] }),createArtifact: (t, def) => { const id = `${t}-1`; store[`${t}:${id}`] = Object.assign({ id }, def); return JSON.parse(JSON.stringify(store[`${t}:${id}`])); },- getArtifact: (t, id) => store[`${t}:${id}`] || { id },- addElement: () => ({}), updateElement: (t, id, ptr, patch) => { calls.push({ name: 'updateElement', args: [t, id, ptr, patch] }); },- removeElement: () => ({}),- pushArtifact: async (t, id) => ({ type: t, id, success: true }),- addSolutionComponent: async () => {}, publishArtifact: async () => {},+ getArtifact: async (t, id) => { await Promise.resolve(); return store[`${t}:${id}`] || { id }; },+ addElement: async () => { await Promise.resolve(); return {}; }, updateElement: async (t, id, ptr, patch) => { await Promise.resolve(); calls.push({ name: 'updateElement', args: [t, id, ptr, patch] }); },+ removeElement: async () => { await Promise.resolve(); return {}; },+ pushArtifact: async (t, id) => ({ type: t, id, saved: true, shipped: false, publish: { kind: 'notRequested' } }),+ addSolutionComponent: async () => {}, publishArtifact: async (type, id) => ({ type, id, shipped: true, publish: { kind: 'verified' } }),};const genpageCli = {uploads: [],diff --git a/plugins/model-apps/scripts/tests/sdk-build.test.js b/plugins/model-apps/scripts/tests/sdk-build.test.jsindex 63cd3c4b3..748ce0820 100644--- a/plugins/model-apps/scripts/tests/sdk-build.test.js+++ b/plugins/model-apps/scripts/tests/sdk-build.test.js@@ -4,7 +4,8 @@ const assert = require('node:assert');const fs = require('node:fs');const os = require('node:os');const path = require('node:path');-const { runSdkBuild, planFor, resolvePhases, compileFormIntent, formFieldLogicals, viewDef, appDef, defaultViewColumns, enrichesDefaultViews, artifactIdentityQuery, resolveExistingFormId, FORM_TYPE_CODE, dashboardTileOpts, PHASES, appUniqueName, personaRoleSpecFor } = require('../lib/sdk-build.js');+const { commandDef, runSdkBuild, planFor, resolvePhases, compileFormIntent, formFieldLogicals, viewDef, appDef, defaultViewColumns, enrichesDefaultViews, artifactIdentityQuery, resolveExistingFormId, FORM_TYPE_CODE, dashboardTileOpts, PHASES, appUniqueName, personaRoleSpecFor } = require('../lib/sdk-build.js');+const { validateAppSpec } = require('../lib/app-spec.js');// Real GUIDs (Imp9) for the three-authority sitemap mock. SELF_* identify THIS app's appmodule + sitemap// so fetchSitemap(appUnique) resolves to opts.liveSitemapXml; otherApps get synthetic ids. Ids that flow@@ -236,36 +237,36 @@ function mockSdk(opts = {}) {store[`${t}:${id}`] = art;return clone(art);},- getArtifact: (t, id) => {+ getArtifact: async (t, id) => { await Promise.resolve();calls.push({ name: 'getArtifact', args: [t, id] });return store[`${t}:${id}`] || { id };},// Generic mutation surface (mirrors the SDK). The mock does NOT mint layout ids (tests don't// assert on them); it just maintains a coherent in-memory tree so getArtifact/firstSectionRowsPointer// and reconcile see the effects of adds/removes.- addElement: (t, id, ptr, el) => {+ addElement: async (t, id, ptr, el) => { await Promise.resolve();calls.push({ name: 'addElement', args: [t, id, ptr, el] });const art = store[`${t}:${id}`] || (store[`${t}:${id}`] = { id });const arr = jpGet(art, ptr);if (Array.isArray(arr)) arr.push(clone(el));return clone(art);},- updateElement: (t, id, ptr, patch) => {+ updateElement: async (t, id, ptr, patch) => { await Promise.resolve();calls.push({ name: 'updateElement', args: [t, id, ptr, patch] });const art = store[`${t}:${id}`] || (store[`${t}:${id}`] = { id });jpSet(art, ptr, clone(patch));return clone(art);},- removeElement: (t, id, ptr) => {+ removeElement: async (t, id, ptr) => { await Promise.resolve();calls.push({ name: 'removeElement', args: [t, id, ptr] });const art = store[`${t}:${id}`];if (art) jpRemove(art, ptr);return clone(art || { id });},updateRecord: async (e, id, data) => { calls.push({ name: 'updateRecord', args: [e, id, data] }); },- pushArtifact: async (t, id) => { calls.push({ name: 'pushArtifact', args: [t, id] }); return { type: t, id, success: true }; },+ pushArtifact: async (t, id) => { calls.push({ name: 'pushArtifact', args: [t, id] }); return { type: t, id, saved: true, shipped: false, publish: { kind: 'notRequested' } }; },addSolutionComponent: async (o) => { calls.push({ name: 'addSolutionComponent', args: [o] }); },- publishArtifact: async (t, id) => { calls.push({ name: 'publishArtifact', args: [t, id] }); },+ publishArtifact: async (t, id) => { calls.push({ name: 'publishArtifact', args: [t, id] }); return { type: t, id, shipped: true, publish: { kind: 'verified' } }; },setEntityIcon: async (logical, icons) => { calls.push({ name: 'setEntityIcon', args: [logical, icons] }); return { id: logical }; },getAiReadiness: async (opts) => { calls.push({ name: 'getAiReadiness', args: [opts] }); return { enabled: true }; },setAppAiFeatures: async (appUnique, flags, opts) => { calls.push({ name: 'setAppAiFeatures', args: [appUnique, flags, opts] }); return { applied: Object.keys(flags).filter((k) => flags[k]), skipped: [] }; },@@ -966,7 +967,13 @@ test('dashboards: chart + list tiles resolve the created view/visualization ids'const chart = tileComps.find((t) => t.type === 'chart');assert.strictEqual(chart.parameters.TargetEntityType, 'new_ticket', 'entity derived from the view');assert.ok(chart.parameters.ViewId, 'view id resolved');- assert.ok(chart.parameters.ChartId, 'chart visualization id resolved');+ // `VisualizationId`, NOT `ChartId`. This assertion previously named the wrong parameter, so the+ // suite agreed with a bug that failed the whole dashboards phase on a real environment with a+ // 400: "The element 'parameters' has invalid child element 'ChartId'". A mock cannot validate+ // FormXML against the platform schema, so the wire NAME has to be pinned explicitly here.+ assert.ok(chart.parameters.VisualizationId, 'chart visualization id resolved');+ assert.strictEqual(chart.parameters.ChartId, undefined,+ 'the rejected `ChartId` spelling is not emitted (it is not a legal <parameters> child)');const list = tileComps.find((t) => t.type === 'list');assert.strictEqual(list.name, 'Recent');assert.ok(list.parameters.ViewId);@@ -1378,6 +1385,46 @@ test('idempotency: existing view/chart/form/app are reused, not re-created (no d});// --- Gap 1/2: update-in-place (reconcile) for forms + views; stock-form reuse -----------------++// REBUILD IDEMPOTENCE — the highest-value regression net for the reconcile path, and the one the+// suite was missing. Every other reconcile test starts from an EMPTY deployed form, so "re-add+// everything" and "add only what's missing" produce identical call logs and no test can tell them+// apart. Running the build twice against the SAME mock store makes the second pass observe the+// first pass's artifacts, so a reconcile that has stopped reading the deployed form correctly+// shows up as duplicate work.+//+// Concretely, this is the test that fails when a `provision.getArtifact(...)` in reconcileForm or+// addSubgrids loses its `await`: the un-awaited Promise makes `formFieldLogicals` return `[]` and+// `hasSubgrid` return false, so the second build re-adds every field and splices a second+// sub-grid — on a real org, a visibly corrupted form behind a 2xx and a green build.+test('REBUILD idempotency: a second build over the same deployed form re-adds no field and no duplicate sub-grid', async () => {+ const spec = makeSpec();+ // artifactsExist makes both passes reconcile the SAME 'form-existing' row; the deployed form+ // starts empty, so pass 1 populates it and pass 2 must find its own work already done.+ const { sdk, calls } = mockSdk({ artifactsExist: true });+ const phases = ['solution', 'data-model', 'views', 'charts', 'forms'];++ await runSdkBuild(spec, { sdk, apply: true, phases });+ const firstPass = find(calls, 'addElement');+ assert.ok(firstPass.length > 0, 'pass 1 populated the deployed form (otherwise pass 2 proves nothing)');++ calls.length = 0; // same array the mock pushes into — measure ONLY the second pass+ await runSdkBuild(spec, { sdk, apply: true, phases });++ const readded = find(calls, 'addElement')+ .flatMap((c) => (c.args[3] && c.args[3].cells) || [])+ .filter((cell) => cell && cell.control && cell.control.fieldName)+ .map((cell) => cell.control.fieldName);+ assert.deepStrictEqual(readded, [],+ `pass 2 re-added field(s) already on the deployed form: ${JSON.stringify(readded)} — the `+ + 'reconcile is not reading the deployed form (check that every getArtifact is awaited)');++ // A sub-grid is spliced as a whole SECTION, not a field cell, so it needs its own assertion.+ const sections = find(calls, 'addElement').filter((c) => /\/sections$/.test(String(c.args[2])));+ assert.deepStrictEqual(sections.map((c) => c.args[2]), [],+ 'pass 2 spliced another sub-grid section — hasSubgrid did not see the one pass 1 added');+});+test('form update-in-place: an existing form is reconciled (addField per spec field), not recreated', async () => {const { sdk, calls } = mockSdk({ artifactsExist: true });await runSdkBuild(makeSpec(), { sdk, apply: true, phases: ['solution', 'data-model', 'views', 'charts', 'forms'] });@@ -1770,8 +1817,8 @@ test('security phase: a spec with no personas makes no security calls', async ()test('resolvePhases honors only/skip/from/to', () => {assert.deepStrictEqual(resolvePhases({ only: ['views', 'charts'] }), ['views', 'charts']);- assert.deepStrictEqual(resolvePhases({ skip: ['data-model', 'sample-data', 'publish'] }), ['solution', 'web-resources', 'views', 'charts', 'forms', 'commands', 'dashboards', 'app-shell', 'pages', 'ai-features', 'security']);- assert.deepStrictEqual(resolvePhases({ from: 'views' }), ['views', 'charts', 'forms', 'commands', 'dashboards', 'app-shell', 'pages', 'ai-features', 'security', 'publish']);+ assert.deepStrictEqual(resolvePhases({ skip: ['data-model', 'sample-data', 'publish'] }), ['solution', 'web-resources', 'views', 'charts', 'forms', 'business-rules', 'commands', 'dashboards', 'app-shell', 'pages', 'ai-features', 'security']);+ assert.deepStrictEqual(resolvePhases({ from: 'views' }), ['views', 'charts', 'forms', 'business-rules', 'commands', 'dashboards', 'app-shell', 'pages', 'ai-features', 'security', 'publish']);assert.deepStrictEqual(resolvePhases({ to: 'data-model' }), ['solution', 'data-model']);});@@ -2537,3 +2584,270 @@ test('pages: a single-app env passes the shared-page check (reads no other sitemassert.strictEqual(uploads[0].pageId, GP_O, 'reused (UPDATE); a single-app env has no other app to share with');} finally { fs.rmSync(appDir, { recursive: true, force: true }); }});++test('a by-value publish failure reaches the warn channel through the whole build', async () => {+ // The unit tests pin reportPartialPush; this pins that the ENGINE is wired to it. Before the fix a+ // build in which every publish failed reported ok:true with zero warnings and zero error events —+ // proven by probe — because all nine call sites discarded the result. A wiring break would restore+ // exactly that, and no unit test can see it.+ const { sdk, calls } = mockSdk();+ sdk.publishArtifact = async (type, id) => {+ calls.push({ name: 'publishArtifact', args: [type, id] });+ return { type, id, shipped: false, publish: { kind: 'failed', error: new Error('PublishXml 503') } };+ };+ const warnings = [];+ const spec = makeSpec();+ const result = await runSdkBuild(spec, { sdk, apply: true, publish: true, warn: (m) => warnings.push(m) });++ assert.ok(result.ok, 'a failed publish does not fail the build — the writes committed');+ assert.ok(calls.some((c) => c.name === 'publishArtifact'), 'the publish phase actually ran');+ assert.ok(+ warnings.some((w) => /publish .* FAILED/.test(w) && /PublishXml 503/.test(w)),+ 'the failure must surface with its cause; got: ' + JSON.stringify(warnings)+ );+});++test('app.newLook writes the NewLookAlwaysOn app setting, scoped to the app and solution', async () => {+ const { sdk, calls } = mockSdk();+ const saved = [];+ sdk.saveSettingValue = async (name, value, opts) => { saved.push({ name, value, opts }); };+ const spec = makeSpec();+ spec.app.newLook = true;++ const r = await runSdkBuild(spec, { sdk, apply: true });+ assert.ok(r.ok, JSON.stringify(r.errors || []));+ assert.strictEqual(saved.length, 1, 'exactly one setting write: ' + JSON.stringify(saved));+ assert.strictEqual(saved[0].name, 'NewLookAlwaysOn');+ assert.strictEqual(saved[0].value, 'true', 'the value is a STRING — Dataverse setting values are strings');+ assert.ok(saved[0].opts.appUniqueName, 'scoped to the app, not the org');+ assert.ok(saved[0].opts.solutionUniqueName, 'attributed to the solution so it travels on export/import');+ assert.strictEqual(r.created.newLook, true);+ void calls;+});++test('the new look is OPT-IN — absent or false writes nothing', async () => {+ for (const value of [undefined, false]) {+ const { sdk } = mockSdk();+ const saved = [];+ sdk.saveSettingValue = async (n, v, o) => { saved.push({ n, v, o }); };+ const spec = makeSpec();+ if (value !== undefined) spec.app.newLook = value;+ const r = await runSdkBuild(spec, { sdk, apply: true });+ assert.ok(r.ok);+ assert.deepStrictEqual(saved, [], `newLook=${value} must write no setting`);+ }+});++test('a failed new-look write does not fail the build, but is never reported as success', async () => {+ // The definition is a platform feature that rolls out by tenant; a tenant without it must still get+ // a working app on the classic shell rather than a failed build. But a silent success would be+ // worse than the failure — the caller must be able to tell the difference.+ const { sdk } = mockSdk();+ sdk.saveSettingValue = async () => { throw new Error('setting definition not found'); };+ const spec = makeSpec();+ spec.app.newLook = true;+ const warnings = [];+ const r = await runSdkBuild(spec, { sdk, apply: true, warn: (m) => warnings.push(m) });++ assert.ok(r.ok, 'the build still succeeds — the app is fully functional');+ assert.strictEqual(r.created.newLook, false, 'and the result says plainly that it was NOT applied');+ assert.ok(+ warnings.some((w) => /new look/i.test(w) && /setting definition not found/.test(w)),+ 'the cause is surfaced: ' + JSON.stringify(warnings)+ );+});++// The Wave 2 header/navigation refresh. Written through the SDK's dedicated+// `setHeaderAndNavigationRefresh` rather than a raw setting write, because the encoding is a trap:+// it is a `datatype = 0` (Number) TRI-STATE where ON is '2', not '1', and writing '1' is ACCEPTED by+// the API and then silently fails to enable the feature. Delegating means the plugin cannot get that+// wrong, and these tests pin the delegation rather than re-encoding the value here.+test('app.headerNavigationRefresh delegates to the SDK API with the created app id', async () => {+ const { sdk } = mockSdk();+ const calls = [];+ sdk.setHeaderAndNavigationRefresh = async (appId, enabled) => { calls.push({ appId, enabled }); return 'created'; };+ const spec = makeSpec();+ spec.app.headerNavigationRefresh = true;++ const r = await runSdkBuild(spec, { sdk, apply: true });+ assert.ok(r.ok, JSON.stringify(r.errors || []));+ assert.strictEqual(calls.length, 1, 'exactly one call: ' + JSON.stringify(calls));+ assert.strictEqual(calls[0].enabled, true);+ assert.strictEqual(calls[0].appId, r.created.app, 'the APP MODULE id, not the unique name — the setting row is keyed by parentappmoduleid');+ assert.strictEqual(r.created.headerNavigationRefresh, true);+ assert.strictEqual(r.created.headerNavigationRefreshOutcome, 'created', 'the outcome is recorded verbatim so a caller can tell a fresh enable from a no-op re-run');+});++test('the header/navigation refresh is a DIFFERENT setting from the new look', async () => {+ // Both are per-app settings and both can be on, but they are separate settingdefinition rows and+ // enabling one must not enable the other. Conflating them would silently under-deliver whichever+ // one the author actually asked for.+ const { sdk } = mockSdk();+ const saved = [];+ const hdr = [];+ sdk.saveSettingValue = async (name, value, opts) => { saved.push({ name, value, opts }); };+ sdk.setHeaderAndNavigationRefresh = async (appId, enabled) => { hdr.push({ appId, enabled }); return 'created'; };++ // newLook alone must not touch header/nav+ const a = makeSpec(); a.app.newLook = true;+ const ra = await runSdkBuild(a, { sdk, apply: true });+ assert.ok(ra.ok);+ assert.strictEqual(saved.length, 1, 'newLook wrote its own setting');+ assert.deepStrictEqual(hdr, [], 'newLook must NOT enable the header/navigation refresh');+ assert.strictEqual(ra.created.headerNavigationRefresh, undefined);++ // header/nav alone must not touch newLook+ saved.length = 0; hdr.length = 0;+ const b = makeSpec(); b.app.headerNavigationRefresh = true;+ const rb = await runSdkBuild(b, { sdk, apply: true });+ assert.ok(rb.ok);+ assert.strictEqual(hdr.length, 1, 'header/nav was written');+ assert.deepStrictEqual(saved, [], 'the header/navigation refresh must NOT enable the new look');+ assert.strictEqual(rb.created.newLook, undefined);++ // both together: two independent writes+ saved.length = 0; hdr.length = 0;+ const c = makeSpec(); c.app.newLook = true; c.app.headerNavigationRefresh = true;+ const rc = await runSdkBuild(c, { sdk, apply: true });+ assert.ok(rc.ok);+ assert.strictEqual(saved.length, 1, 'both set: new look written');+ assert.strictEqual(hdr.length, 1, 'both set: header/nav written');+ assert.strictEqual(rc.created.newLook, true);+ assert.strictEqual(rc.created.headerNavigationRefresh, true);+});++test('the header/navigation refresh honours BOTH values — false actively disables', async () => {+ // NOT symmetry for its own sake. Verified against the real vendored bundle (offline, by capturing+ // the writes a push issues): the SDK defaults the app artifact's+ // `headerAndNavigationRefresh` to TRUE and pushing a new app writes '2' (ON) unprompted, so the+ // platform default is ON. Treating `false` as "do nothing" would silently leave the feature ON for+ // an author who explicitly asked for it off — the exact silent-disagreement class this build keeps+ // having to fix. So `false` must be an ACTIVE write of the OFF value.+ for (const value of [true, false]) {+ const { sdk } = mockSdk();+ const calls = [];+ sdk.setHeaderAndNavigationRefresh = async (a, e) => { calls.push({ a, e }); return 'updated'; };+ const spec = makeSpec();+ spec.app.headerNavigationRefresh = value;+ const r = await runSdkBuild(spec, { sdk, apply: true });+ assert.ok(r.ok);+ assert.strictEqual(calls.length, 1, `headerNavigationRefresh=${value} must issue exactly one write`);+ assert.strictEqual(calls[0].e, value, `the requested value ${value} must be passed through, not coerced`);+ assert.strictEqual(r.created.headerNavigationRefresh, value);+ }+});++test('the header/navigation refresh is only touched when the author states a preference', async () => {+ // Absent means "no opinion" — leave the platform default alone rather than fighting it.+ const { sdk } = mockSdk();+ const calls = [];+ sdk.setHeaderAndNavigationRefresh = async (a, e) => { calls.push({ a, e }); return 'created'; };+ const spec = makeSpec();+ const r = await runSdkBuild(spec, { sdk, apply: true });+ assert.ok(r.ok);+ assert.deepStrictEqual(calls, [], 'an absent headerNavigationRefresh must make no call');+ assert.strictEqual(r.created.headerNavigationRefresh, undefined);+});++test('a failed header/navigation write does not fail the build, but is never reported as success', async () => {+ // Public preview, rolls out by tenant. The SDK throws a PLAIN Error (not an SdkError subclass)+ // when the environment lacks the setting definition, so the catch here is deliberately broad.+ const { sdk } = mockSdk();+ sdk.setHeaderAndNavigationRefresh = async () => { throw new Error("App setting 'HeaderAndNavigationRefresh' is not available in this environment"); };+ const spec = makeSpec();+ spec.app.headerNavigationRefresh = true;+ const warnings = [];++ const r = await runSdkBuild(spec, { sdk, apply: true, warn: (m) => warnings.push(m) });+ assert.ok(r.ok, 'a rolling-out preview setting must not fail an otherwise-good build');+ // 'unknown', NOT false. On failure the row keeps whatever the platform defaulted it to — which for+ // a new app is ON — so reporting `false` would be as wrong as reporting success.+ assert.strictEqual(r.created.headerNavigationRefresh, 'unknown',+ 'a failed write reports the truth (unknown), not the value that was asked for and not its opposite');+ assert.ok(+ warnings.some((w) => /header and navigation refresh/i.test(w) && /not available in this environment/.test(w)),+ 'the real cause reaches the caller; got: ' + JSON.stringify(warnings)+ );+});++test('app.headerNavigationRefresh must be a boolean', () => {+ // A string "false" is truthy in JS and would silently turn the feature ON for an author who meant+ // to disable it — the same trap the newLook validation exists to close.+ for (const bad of ['true', 'false', 1, 0, {}, []]) {+ const spec = makeSpec();+ spec.app.headerNavigationRefresh = bad;+ const v = validateAppSpec(spec);+ assert.ok(+ (v.errors || []).some((e) => /app.headerNavigationRefresh must be a boolean/.test(e)),+ `headerNavigationRefresh=${JSON.stringify(bad)} must be rejected`+ );+ }+ for (const good of [true, false, undefined]) {+ const spec = makeSpec();+ if (good !== undefined) spec.app.headerNavigationRefresh = good;+ const v = validateAppSpec(spec);+ assert.ok(!(v.errors || []).some((e) => /headerNavigationRefresh/.test(e)), `${good} must be accepted`);+ }+});++// --- command buttons must be HANDED the record (live-measured) ----------------------------------+//+// `onclickeventjavascriptparameters` null means the function is invoked with NO arguments, so the+// near-universal handler shape `function doThing(primaryControl) { primaryControl.getAttribute(…) }`+// throws on its first property access and the button silently does nothing. Reported by a user as+// "nothing happens when I press Escalate"; the build, the deployed rows and `--verify` all looked+// perfect, because the failure is client-side only.+//+// The codes come from the platform's own maker-authored commands on a live org:+// form (location 0) [{"type":5}] PrimaryControl+// grid (location 1) [{"type":12},{"type":24}] SelectedControl + SelectedControlSelectedItemIds+test('a JS command defaults to receiving the primary control', () => {+ const spec = {+ webResources: [{ name: 'x.js', type: 'js', content: '//' }],+ commands: [{ entity: 'new_t', label: 'Go', library: 'x.js', function: 'Ns.go' }],+ };+ const def = commandDef('new_t', spec.commands, { 'x.js': 'wr-1' });+ const control = def.commandBars[0].groups[0].controls[0];+ assert.strictEqual(control.action.parameters, '[{"type":5,"value":null}]',+ 'without this the handler is called with no arguments and the button does nothing');+});++test('flyout CHILDREN also receive the primary control', () => {+ // The children are the actual buttons a user clicks; missing parameters there is the same bug.+ const cmds = [{+ entity: 'new_t', label: 'Set status', type: 'FlyoutAnchor',+ children: [{ label: 'Closed', library: 'x.js', function: 'Ns.close' }],+ }];+ const def = commandDef('new_t', cmds, { 'x.js': 'wr-1' });+ const child = def.commandBars[0].groups[0].controls[0].children[0];+ assert.strictEqual(child.action.parameters, '[{"type":5,"value":null}]');+});++test('a grid command gets the grid shape, not the form one', () => {+ const cmds = [{ entity: 'new_t', label: 'Bulk', location: 'HomeTab', library: 'x.js', function: 'Ns.bulk' }];+ const def = commandDef('new_t', cmds, { 'x.js': 'wr-1' });+ assert.strictEqual(def.commandBars[0].groups[0].controls[0].action.parameters,+ '[{"type":12,"value":null},{"type":24,"value":null}]');+});++test('an explicit parameters value always wins, including empty', () => {+ // An author with a genuinely argument-less function must be able to say so.+ const cmds = [+ { entity: 'new_t', label: 'A', library: 'x.js', function: 'Ns.a', parameters: '[{"type":99,"value":1}]' },+ { entity: 'new_t', label: 'B', library: 'x.js', function: 'Ns.b', parameters: '' },+ ];+ const def = commandDef('new_t', cmds, { 'x.js': 'wr-1' });+ const [a, b] = def.commandBars[0].groups[0].controls;+ assert.strictEqual(a.action.parameters, '[{"type":99,"value":1}]');+ assert.strictEqual(b.action.parameters, '');+});++test('a flyout ANCHOR has no action at all', () => {+ // The anchor only opens the menu; giving it parameters would imply a handler it does not have.+ const cmds = [{+ entity: 'new_t', label: 'Menu', type: 'FlyoutAnchor',+ children: [{ label: 'One', library: 'x.js', function: 'Ns.one' }],+ }];+ const def = commandDef('new_t', cmds, { 'x.js': 'wr-1' });+ assert.strictEqual(def.commandBars[0].groups[0].controls[0].action, undefined);+});diff --git a/plugins/model-apps/scripts/tests/sdk-surface-contract.test.js b/plugins/model-apps/scripts/tests/sdk-surface-contract.test.jsindex 088f29109..76631b23d 100644--- a/plugins/model-apps/scripts/tests/sdk-surface-contract.test.js+++ b/plugins/model-apps/scripts/tests/sdk-surface-contract.test.js@@ -16,7 +16,7 @@//// When you bump + re-vendor the SDK, run this first: a method the skill depends on that the// new bundle no longer exposes fails HERE (listing the exact names) instead of silently at-// build time. Update the migration accordingly (see docs/app-builder-roadmap.md).+// build time. Update the migration accordingly (see docs/app-builder-capabilities.md).const test = require('node:test');const assert = require('node:assert');const os = require('node:os');@@ -65,6 +65,8 @@ const SKILL_SDK_SURFACE = ['findTables','getAiReadiness','getArtifact',+ 'getColumnVisualization',+ 'getSolution','initWorkspace','insertStatusValue','publishArtifact',@@ -73,9 +75,18 @@ const SKILL_SDK_SURFACE = ['removeElement','removeRowSummary','resolveArtifact',+ 'retrieveSetting','seedRecordGraph','setAppAiFeatures',+ 'setColumnVisualization',+ // Written by the app-shell phase for `app.newLook` — the modern shell is a per-app SETTING+ // (`NewLookAlwaysOn`), not an appmodule column.+ 'saveSettingValue','setEntityIcon',+ // Wave 2 header/navigation refresh (`app.headerNavigationRefresh`). Used instead of a raw setting+ // write because the value is a Number TRI-STATE where ON is '2', not '1' — writing '1' is accepted+ // by the API and silently fails to enable the feature. The SDK owns that encoding.+ 'setHeaderAndNavigationRefresh','updateElement','updateRecord','updateTable',@@ -112,24 +123,60 @@ test('CONTRACT: every SDK method the skill depends on is a function on the real}});-// Collect every `provision.<name>(` / `sdk.<name>(` identifier the two engines call. These-// aliases are the MakerSdk instance in sdk-build.js (`provision`) and sdk-teardown.js (`sdk`).+// Collect every `provision.<name>(` / `sdk.<name>(` identifier the plugin calls. These aliases are+// the MakerSdk instance in sdk-build.js (`provision`) and sdk-teardown.js (`sdk`).// e.g. matches `provision.createTable(o)` and `await sdk.deleteTable(...)` -> 'createTable' / 'deleteTable'.+//+// The scan covers scripts/ RECURSIVELY, not a hand-listed set of library files. An adversarial+// review found that the hand-listed version silently omitted two real calls made from the top-level+// CLI scripts — `sdk.getSolution(...)` in download-model-app.js and `sdk.retrieveSetting(...)` in+// verify-model-app.js — so the "every method the engines call is guarded" claim was false, and a+// future bundle could drop either method with this test still green and download/verify failing at+// runtime with a TypeError. A list of files to scan is exactly the kind of thing that rots; a walk+// does not.function calledSdkMethods() {- const files = [- path.join(LIB_DIR, 'sdk-build.js'),- path.join(LIB_DIR, 'sdk-teardown.js'),- path.join(LIB_DIR, 'entity-provision.js'),- // artifact-intent.js is PURE (no SDK calls) by design, but scan it too so a future SDK call- // added to the compiler is caught by this guard rather than slipping past the mock-based tests.- path.join(LIB_DIR, 'artifact-intent.js'),- ].filter((f) => fs.existsSync(f));- const re = /\b(?:provision|sdk)\.([A-Za-z][A-Za-z0-9]*)\s*\(/g;+ const files = [];+ const walk = (dir) => {+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ // vendor/ is the generated SDK itself; _vendor-build is the dev-only bundler; tests/ define+ // MOCK sdk objects whose method set is deliberately not the real surface.+ if (['vendor', '_vendor-build', 'node_modules', 'tests'].includes(entry.name)) continue;+ walk(full);+ } else if (entry.name.endsWith('.js')) {+ files.push(full);+ }+ }+ };+ walk(SCRIPTS_DIR);+ // Receivers: any identifier that plausibly holds an SDK instance, not a two-name allow-list.+ //+ // A review found `provisionSdk.initWorkspace()` in build-model-app.js was invisible to the old+ // `(provision|sdk)` pattern — the method happened to be listed anyway, via a `sdk.` call+ // elsewhere, so nothing failed; a method used ONLY through such a receiver would have been+ // silently unguarded. Matching any identifier containing "sdk" or "provision" (case-insensitive)+ // covers every handle the plugin actually uses (`provision`, `sdk`, `provisionSdk`) and errs+ // toward over-collecting: a false positive here just adds a name to SKILL_SDK_SURFACE, where the+ // bundle check immediately proves whether it is real.+ //+ // Still invisible, and deliberately not chased: a destructured or fully dynamic call. Those need+ // real data-flow analysis, and unlike the async guard — where an unguarded call CORRUPTS data —+ // the failure here is a loud TypeError at runtime, so a tripwire is proportionate.+ // `matchAll`, not a shared `/g` regex with `exec`. The exec form is CORRECT here as written — a+ // loop run to exhaustion gets `lastIndex` reset to 0 by the failing `exec`, verified: three files+ // scanned in sequence find all matches and leave `lastIndex` at 0 after each. But the correctness+ // depends entirely on nobody ever adding a `break`, `continue` or early `return` inside the loop:+ // with one `break`, the same three files yield 2 of 5 matches instead of 5, silently. A guard whose+ // soundness rests on an invisible invariant is one edit from being a no-op, and this one exists to+ // catch unguarded SDK calls. `matchAll` does not touch the source regex's `lastIndex` at all.+ const re = /\b([A-Za-z_$][\w$]*)\.([A-Za-z][A-Za-z0-9]*)\s*\(/g;const found = new Set();for (const f of files) {const src = fs.readFileSync(f, 'utf8');- let m;- while ((m = re.exec(src)) !== null) found.add(m[1]);+ for (const m of src.matchAll(re)) {+ if (/sdk|provision/i.test(m[1])) found.add(m[2]);+ }}return found;}diff --git a/plugins/model-apps/scripts/tests/sdk-teardown.test.js b/plugins/model-apps/scripts/tests/sdk-teardown.test.jsindex ab841a987..a6456a7cd 100644--- a/plugins/model-apps/scripts/tests/sdk-teardown.test.js+++ b/plugins/model-apps/scripts/tests/sdk-teardown.test.js@@ -1153,3 +1153,82 @@ test('genpage deletes nothing when the manifest is absent or unreadable', asyncconst items = await KIND_HANDLERS.genpage.resolve(sdk, { manifestName: 'new_app_pagemanifest' });assert.deepStrictEqual(items, []);});++// --- command teardown: delete order must respect the real hierarchy depth -----------------------+//+// A flyout is THREE levels: anchor (no parent) -> intervening group (parent = anchor) -> buttons+// (parent = group). `_parentappactionid_value` is set on the group AND on the leaves, so ordering by+// "has a parent" collapses them into one bucket and can delete the group while its buttons still+// hang off it — which Dataverse rejects. Seen for real while resetting a command bar by hand: a leaf+// answered 404 because its group had already gone, i.e. the platform cascaded rather than the order+// being right.+//+// Also: the individual rows must go BEFORE the bar. They are the ones holding the web-resource+// dependency that previously stranded a form-JS resource at teardown.+test('command teardown deletes deepest-first, rows before the bar', async () => {+ const ANCHOR = 'a-anchor';+ const GROUP = 'b-group';+ const LEAF1 = 'c-leaf1';+ const LEAF2 = 'd-leaf2';+ const TOP = 'e-top';+ const sdk = {+ resolveArtifact: async () => [{ id: 'bar-1', entity: 'new_ticket' }],+ queryRecords: async (entity) => {+ assert.strictEqual(entity, 'appaction');+ // Deliberately returned shallow-first, so a correct implementation must REORDER them.+ return [+ { appactionid: ANCHOR, _parentappactionid_value: null },+ { appactionid: TOP, _parentappactionid_value: null },+ { appactionid: GROUP, _parentappactionid_value: ANCHOR },+ { appactionid: LEAF1, _parentappactionid_value: GROUP },+ { appactionid: LEAF2, _parentappactionid_value: GROUP },+ ];+ },+ };+ const items = await KIND_HANDLERS.commands.resolve(sdk, { entity: 'new_ticket', ownsTable: true });+ const order = items.map((i) => i.id);++ const pos = (id) => order.indexOf(id);+ assert.ok(pos(LEAF1) < pos(GROUP), `leaf must precede its group: ${order.join(' -> ')}`);+ assert.ok(pos(LEAF2) < pos(GROUP), `leaf must precede its group: ${order.join(' -> ')}`);+ assert.ok(pos(GROUP) < pos(ANCHOR), `group must precede its anchor: ${order.join(' -> ')}`);+ assert.ok(pos(LEAF1) < pos(TOP), 'deeper rows come before unrelated top-level rows');+ assert.strictEqual(order[order.length - 1], 'bar-1', 'the bar is deleted LAST, after every row');+});++test('command teardown survives a self-referential parent pointer', async () => {+ // Depth is computed by walking parent pointers; a cycle must not spin forever. Bad data is not+ // hypothetical here — these rows are written by several different tools.+ const sdk = {+ resolveArtifact: async () => [],+ queryRecords: async () => [+ { appactionid: 'x', _parentappactionid_value: 'y' },+ { appactionid: 'y', _parentappactionid_value: 'x' },+ ],+ };+ const items = await KIND_HANDLERS.commands.resolve(sdk, { entity: 'new_ticket', ownsTable: true });+ assert.strictEqual(items.length, 2, 'both rows are still scheduled for deletion');+});++test('command teardown still refuses to touch a bar on a table the spec does not own', async () => {+ // The fail-closed rule that predates all of this: deleting the bar on an adopted table would+ // destroy another app's buttons.+ const sdk = {+ resolveArtifact: async () => { throw new Error('must not resolve'); },+ queryRecords: async () => { throw new Error('must not query'); },+ };+ const res = await KIND_HANDLERS.commands.resolve(sdk, { entity: 'account', ownsTable: false });+ assert.deepStrictEqual(res.items, []);+ assert.match(res.skipReason, /existing\/external table/);+});++test('command teardown proceeds with the bar when the row listing fails', async () => {+ // Best-effort: an unreadable appaction list must not block the bar delete, which is the+ // pre-existing behaviour.+ const sdk = {+ resolveArtifact: async () => [{ id: 'bar-1', entity: 'new_ticket' }],+ queryRecords: async () => { throw new Error('HTTP 401'); },+ };+ const items = await KIND_HANDLERS.commands.resolve(sdk, { entity: 'new_ticket', ownsTable: true });+ assert.deepStrictEqual(items.map((i) => i.id), ['bar-1']);+});diff --git a/plugins/model-apps/scripts/tests/sdk-uptake-contract.test.js b/plugins/model-apps/scripts/tests/sdk-uptake-contract.test.jsnew file mode 100644index 000000000..78b27b992--- /dev/null+++ b/plugins/model-apps/scripts/tests/sdk-uptake-contract.test.js@@ -0,0 +1,390 @@+'use strict';+// REAL BUNDLE contract tests for the capabilities this SDK uptake introduced.+//+// These drive the shipped `vendor/cds-maker-sdk.cjs`, not a mock, because the whole failure mode of a+// re-vendor is "the bundle stopped doing what we believe it does" — a mock cannot detect that. They+// exist so the next uptake fails loudly here instead of silently on a customer's org.+//+// Covered:+// 1. App icon is now REQUIRED and must be an IMAGE (the behaviour that broke 13 tests on uptake).+// 2. Business-rule authoring, which was previously impossible on our tenants: supported bound+// member first, classic WWF-XAML `workflows` row as a NARROW fallback.+const test = require('node:test');+const assert = require('node:assert');+const os = require('node:os');+const path = require('node:path');+const fs = require('node:fs');++const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');+const dirs = [];++// Offline SDK whose POST handler the test supplies, so a server fault can be simulated exactly.+// GET answers an empty collection: that is what an org with no image web resource looks like, which+// is precisely the state the icon contract below is about.+function sdkWith({ post, get, del } = {}) {+ const { createMakerSdk } = require(BUNDLE);+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'uptake-'));+ dirs.push(dir);+ const calls = [];+ const ok204 = { status: 204, headers: { 'odata-entityid': 'https://x/workflows(55555555-5555-5555-5555-555555555555)' }, body: {} };+ const sdk = createMakerSdk({+ workspacePath: dir,+ instanceUrl: 'https://contoso.crm.dynamics.com',+ httpClient: {+ get: async (url) => { calls.push({ verb: 'GET', url }); return (get && get(url)) || { status: 200, headers: {}, body: { value: [] } }; },+ post: async (url, body) => { calls.push({ verb: 'POST', url, body }); return (post && post(url, body)) || ok204; },+ patch: async (url, body) => { calls.push({ verb: 'PATCH', url, body }); return { status: 204, headers: {}, body: {} }; },+ put: async (url, body) => { calls.push({ verb: 'PUT', url, body }); return { status: 204, headers: {}, body: {} }; },+ delete: async (url) => { calls.push({ verb: 'DELETE', url }); return (del && del(url)) || { status: 204, headers: {}, body: {} }; },+ },+ });+ sdk.initWorkspace();+ return { sdk, calls };+}++test.after(() => { for (const d of dirs) fs.rmSync(d, { recursive: true, force: true }); });++// The smallest complete business rule, authored the way the build authors one: create the artifact,+// set the condition tree through the generic element surface, push. Shared by the #482 tests below.+async function authorDupGuard(sdk) {+ const art = sdk.createArtifact('businessRule', {+ name: 'Dup Guard', entityLogicalName: 'account', scope: 'Entity', status: 'Draft',+ });+ await sdk.updateElement('businessRule', art.id, '/rootCondition', {+ id: 'root', logicalOperator: 'And',+ clauses: [{ id: 'c1', field: 'name', operator: 'Equals', valueType: 'Value', value: 'x', valueWorkflowType: 'String' }],+ trueBranch: [{ id: 'a1', type: 'SetVisibility', field: 'fax', visible: false }],+ });+ return sdk.pushArtifact('businessRule', art.id);+}++// --- 1. app icon ------------------------------------------------------------------------------++test('REAL BUNDLE: creating an app with no icon and no image web resource fails with APP_ICON_UNRESOLVED', async () => {+ // `appmodule.webresourceid` is a REQUIRED attribute. The SDK used to fall back to ANY unmanaged web+ // resource, which on an org whose images are all managed returned a JAVASCRIPT file — the platform+ // then rejected the create with an opaque "dependent component WebResource does not exist". It now+ // requires an IMAGE and says so plainly when there is none.+ //+ // The PLUGIN never relies on this path (`ensureAppIcon` always resolves or generates an SVG and+ // `appDef` passes `iconWebResourceId`), so this pins a boundary we depend on NOT crossing. If a+ // future bundle silently restored the old fallback, an app could again be created pointing at a+ // JavaScript file.+ const { sdk } = sdkWith();+ const app = sdk.createArtifact('app', { name: 'No Icon App', uniqueName: 'cr_noiconapp' });+ await assert.rejects(+ () => sdk.pushArtifact('app', app.id),+ (err) => {+ assert.strictEqual(err.code, 'APP_ICON_UNRESOLVED', `expected APP_ICON_UNRESOLVED, got ${err.code}: ${err.message}`);+ assert.match(err.message, /image web resource/i, 'the message names what is missing');+ return true;+ }+ );+});++test('REAL BUNDLE: an explicit iconWebResourceId is used verbatim and skips discovery', async () => {+ // What the plugin actually does. The id must reach the appmodule write unchanged — a bundle that+ // ignored it would silently re-introduce the cross-solution managed-icon dependency the plugin+ // generates its own SVG to avoid.+ const ICON = '11111111-2222-3333-4444-555555555555';+ const { sdk, calls } = sdkWith();+ const app = sdk.createArtifact('app', { name: 'Icon App', uniqueName: 'cr_iconapp', iconWebResourceId: ICON });+ await sdk.pushArtifact('app', app.id);+ const write = calls.find((c) => c.verb === 'POST' && c.body && c.body.webresourceid);+ assert.ok(write, 'the appmodule write carries a webresourceid; urls: ' + JSON.stringify(calls.map((c) => c.url)));+ assert.strictEqual(write.body.webresourceid, ICON, 'the explicit id is used verbatim');+ // No icon-discovery query should have been issued at all.+ assert.strictEqual(+ calls.some((c) => c.verb === 'GET' && /webresourceset/i.test(c.url) && /webresourcetype/i.test(c.url)),+ false,+ 'an explicit id must short-circuit icon discovery entirely');+});++// --- 2. business rules ------------------------------------------------------------------------++const BR_ENTITY = 'lvz_ticket';++// The authoring shape, which is NOT obvious and is silently forgiving of getting it wrong: conditions+// go in `clauses` and actions in `trueBranch`. Passing `operator`/`lhs`/`rhs`/`thenActions` (a very+// natural guess) merges those keys onto the node, the compiler ignores them, and you get a rule with+// an EMPTY condition that still creates 204 — a wrong artifact behind a success. Pinned below.+function authorRule(sdk) {+ const art = sdk.createArtifact('businessRule', {+ name: 'Hide notes when closed', entityLogicalName: BR_ENTITY, scope: 'Entity', status: 'Active',+ });+ return art;+}+const CONDITION = {+ id: 'r1', displayName: 'If status is Closed', logic: 'AND',+ clauses: [{ id: 'c1', field: 'lvz_status', operator: 'Equals', valueType: 'Value', value: '1', valueWorkflowType: 'Picklist' }],+ trueBranch: [{ id: 'a1', type: 'SetVisibility', displayName: 'Hide notes', field: 'lvz_notes', visible: false }],+ falseBranch: [],+};++test('REAL BUNDLE: a business rule goes through the SUPPORTED bound member first', async () => {+ const { sdk, calls } = sdkWith();+ const art = authorRule(sdk);+ await sdk.updateElement('businessRule', art.id, '/rootCondition', CONDITION);+ const res = await sdk.pushArtifact('businessRule', art.id);+ assert.strictEqual(res.saved, true);++ const bound = calls.find((c) => c.verb === 'POST' && /CreateProcessWithWfomJson/i.test(c.url));+ assert.ok(bound, 'the supported member is tried FIRST; urls: ' + JSON.stringify(calls.map((c) => c.url)));+ assert.ok(typeof bound.body.WfomJson === 'string' && bound.body.WfomJson.length > 100,+ 'it carries a compiled workflow object model');+ // When the supported member succeeds there must be NO classic write — two writes would be two rules.+ assert.strictEqual(calls.some((c) => c.verb === 'POST' && /\/workflows$/.test(String(c.url))), false,+ 'a successful supported write must not also POST the classic row');+ // Activation is a separate PATCH (statecode 1 / statuscode 2).+ const activate = calls.find((c) => c.verb === 'PATCH' && c.body && c.body.statecode !== undefined);+ assert.ok(activate, 'status: Active triggers an activation PATCH');+ assert.strictEqual(activate.body.statecode, 1);+ assert.strictEqual(activate.body.statuscode, 2);+});++test('REAL BUNDLE: 0x80040216 falls back to the classic XAML row, and the XAML names the authored columns', async () => {+ // This is the whole point of the uptake: the bound member faults with a server-side plugin error on+ // our tenants, so business rules were unauthorable. The fallback compiles the same typed rule to WWF+ // XAML and writes a plain `workflows` row, which works.+ const { sdk, calls } = sdkWith({+ post: (url) => (/WithWfomJson/i.test(url)+ ? { status: 400, headers: {}, body: { error: { code: '0x80040216', message: 'System failure in WorkflowService' } } }+ : undefined),+ });+ const art = authorRule(sdk);+ await sdk.updateElement('businessRule', art.id, '/rootCondition', CONDITION);+ const res = await sdk.pushArtifact('businessRule', art.id);+ assert.strictEqual(res.saved, true, 'the fallback makes the push succeed');++ const classic = calls.find((c) => c.verb === 'POST' && /\/workflows$/.test(String(c.url)));+ assert.ok(classic, 'the classic row is written; urls: ' + JSON.stringify(calls.map((c) => c.url)));+ assert.strictEqual(classic.body.category, 2, 'category 2 = Business Rule');+ assert.strictEqual(classic.body.type, 1);+ assert.strictEqual(classic.body.primaryentity, BR_ENTITY);+ assert.strictEqual(classic.body.iscrmuiworkflow, true);++ // The DECISIVE assertion. A compiler that emitted well-formed but EMPTY XAML would satisfy every+ // structural check above and still produce a rule that does nothing — which is exactly what a+ // wrongly-shaped condition silently produces (see the next test).+ const xaml = classic.body.xaml;+ assert.ok(typeof xaml === 'string' && xaml.length > 500, 'the row carries compiled XAML');+ assert.match(xaml, /lvz_status/, 'the condition column reaches the XAML');+ assert.match(xaml, /lvz_notes/, 'the action column reaches the XAML');+});++test('REAL BUNDLE: a NON-qualifying failure must NOT fall back (a second write could duplicate the rule)', async () => {+ // The fallback trigger is deliberately narrow: only a 400 carrying 0x80040216, or a 404. An auth+ // failure, a throttle or a lost response tells us NOTHING about whether the first write committed,+ // so writing again risks a duplicate or a half-configured rule.+ //+ // The INVARIANT under test is "no classic write", not "throws". Measured against the bundle, the+ // failure is surfaced two different ways and both are correct:+ // 401 / 403 / 429 / 500 / 400-with-another-code -> THROW+ // 412 -> resolves with `saved: false`+ // A 412 is a version conflict, which this SDK reports BY VALUE like every other push outcome+ // (the same throw-to-return refactor this release already handles); `requireSuccessfulPush` turns+ // that into a build halt. Asserting "throws" for it would have been asserting the wrong contract.+ const THROWS = [[401, null], [403, null], [429, null], [500, null], [400, '0x80040265']];+ for (const [status, code] of THROWS) {+ const { sdk, calls } = sdkWith({+ post: (url) => (/WithWfomJson/i.test(url)+ ? { status, headers: {}, body: { error: { code: code || '0x0', message: 'unrelated' } } }+ : undefined),+ });+ const art = authorRule(sdk);+ await sdk.updateElement('businessRule', art.id, '/rootCondition', CONDITION);+ await assert.rejects(() => sdk.pushArtifact('businessRule', art.id), `HTTP ${status} must propagate`);+ assert.strictEqual(+ calls.some((c) => c.verb === 'POST' && /\/workflows$/.test(String(c.url))), false,+ `HTTP ${status} must not trigger a classic write`);+ }++ // 412: reported by value, still no second write.+ const { sdk, calls } = sdkWith({+ post: (url) => (/WithWfomJson/i.test(url) ? { status: 412, headers: {}, body: {} } : undefined),+ });+ const art = authorRule(sdk);+ await sdk.updateElement('businessRule', art.id, '/rootCondition', CONDITION);+ const res = await sdk.pushArtifact('businessRule', art.id);+ assert.strictEqual(res.saved, false, 'a version conflict is reported by value, not swallowed');+ assert.strictEqual(+ calls.some((c) => c.verb === 'POST' && /\/workflows$/.test(String(c.url))), false,+ 'a 412 must not trigger the very write the caller\'s stale token exists to prevent');+});++test('REAL BUNDLE: a 404 on the bound member DOES qualify for the classic fallback', async () => {+ // The other qualifying trigger: an org where the member is not declared at all. Kept separate from+ // the 0x80040216 case so a change that narrowed the trigger to only one of them is caught.+ const { sdk, calls } = sdkWith({+ post: (url) => (/WithWfomJson/i.test(url) ? { status: 404, headers: {}, body: {} } : undefined),+ });+ const art = authorRule(sdk);+ await sdk.updateElement('businessRule', art.id, '/rootCondition', CONDITION);+ const res = await sdk.pushArtifact('businessRule', art.id);+ assert.strictEqual(res.saved, true);+ assert.ok(calls.some((c) => c.verb === 'POST' && /\/workflows$/.test(String(c.url))),+ 'an undeclared member falls back to the classic row');+});++test('REAL BUNDLE: a wrongly-shaped condition compiles an EMPTY rule rather than erroring', async () => {+ // Recorded because it cost real time and would cost it again. `operator`/`lhs`/`rhs`/`thenActions`+ // is the natural guess at the shape; `updateElement` merges those keys onto the node, the compiler+ // ignores them, and the push SUCCEEDS with XAML that mentions none of the author's columns.+ //+ // So a caller CANNOT rely on an error to tell them the shape is wrong. Any future plugin-side+ // business-rule support must validate `clauses`/`trueBranch` itself before pushing.+ const { sdk, calls } = sdkWith({+ post: (url) => (/WithWfomJson/i.test(url)+ ? { status: 400, headers: {}, body: { error: { code: '0x80040216', message: 'fault' } } }+ : undefined),+ });+ const art = authorRule(sdk);+ await sdk.updateElement('businessRule', art.id, '/rootCondition', {+ operator: 'Equal',+ lhs: { type: 'Field', attributeLogicalName: 'lvz_status' },+ rhs: { type: 'Value', value: 'Closed' },+ thenActions: [{ type: 'SetVisibility', attributeLogicalName: 'lvz_notes', visible: false }],+ });+ const res = await sdk.pushArtifact('businessRule', art.id);+ assert.strictEqual(res.saved, true, 'the push succeeds — that is the trap');++ const classic = calls.find((c) => c.verb === 'POST' && /\/workflows$/.test(String(c.url)));+ assert.ok(classic, 'a row is still written');+ assert.doesNotMatch(classic.body.xaml, /lvz_status/, 'the guessed shape contributes NO condition');+ assert.doesNotMatch(classic.body.xaml, /lvz_notes/, 'and NO action');+});++// ---------------------------------------------------------------------------------------------+// 3. The AI setting NAMES the build writes to, pinned against the bundle's own maps.+//+// Discovered while chasing a report that form fill was enabled when our probe read it as off. The+// names turned out to be correct — but NOTHING was checking that. Every existing test hardcoded the+// same strings the source does, so an upstream rename would leave the whole suite green while the+// build wrote to a setting that no longer exists, and the feature would silently never turn on.+//+// That is the exact failure this uptake already suffered once: `PushResult.success` was renamed to+// `saved`, and the guard reading `success === false` simply stopped firing. A constant is only+// guarded if something compares it to the BUNDLE.+test('REAL BUNDLE: AI_APP_SETTING matches the SDK per-app setting map exactly', () => {+ const src = fs.readFileSync(BUNDLE, 'utf8');+ // The map is emitted as, e.g.:+ // var xV={formFill:"FormFillBarUXEnabled",nlSearch:"NLGridSearchSetting",+ // nlChart:"NLChartDataVisualizationSetting",m365:"m365copilotmodelappenabled"}+ // The GATE map carries an extra `summaries` key between nlChart and m365 (the per-app map has no+ // summaries entry — row summaries are configured through configureRowSummary, not a flag), so the+ // optional group is required to match BOTH. Anchor on the `formFill` key rather than the minified+ // variable name, which changes every build.+ const m = /\{formFill:"[^"]+",nlSearch:"[^"]+",nlChart:"[^"]+",(?:summaries:"[^"]+",)?m365:"[^"]+"\}/g;+ const maps = [...src.matchAll(m)].map((x) => x[0]);+ assert.ok(maps.length >= 2, `expected both the gate and per-app maps in the bundle, found ${maps.length}`);++ const parse = (s) => Object.fromEntries([...s.matchAll(/(\w+):"([^"]+)"/g)].map((x) => [x[1], x[2]]));+ const parsed = maps.map(parse);++ // The GATE map and the PER-APP map are deliberately different for nlSearch and nlChart — that+ // difference is the whole reason `AI_APP_SETTING` exists as its own constant. Identify the+ // per-app map as the one whose nlSearch is NOT the gate name.+ const appMap = parsed.find((p) => p.nlSearch !== 'EnableNLGridSearch');+ assert.ok(appMap, 'could not identify the per-app setting map in the bundle');++ const { AI_APP_SETTING } = require('../lib/ai-app-settings.js');+ assert.deepStrictEqual(AI_APP_SETTING, appMap);++ // And pin the distinction itself: if these ever collapse to the same name, the "gate is not the+ // setting" logic in verify and preflight becomes dead code and should be revisited deliberately.+ const gateMap = parsed.find((p) => p.nlSearch === 'EnableNLGridSearch');+ assert.ok(gateMap, 'could not identify the gate map in the bundle');+ assert.notStrictEqual(gateMap.nlSearch, appMap.nlSearch, 'gate and per-app names must stay distinct for nlSearch');+ assert.notStrictEqual(gateMap.nlChart, appMap.nlChart, 'gate and per-app names must stay distinct for nlChart');+ // formFill and m365 legitimately share one name; pinned so a future divergence is noticed.+ assert.strictEqual(gateMap.formFill, appMap.formFill);+ assert.strictEqual(gateMap.m365, appMap.m365);+});++// ---------------------------------------------------------------------------------------------+// 4. The #482 double-write fix, pinned against the bundle.+//+// The platform COMMITS the workflow row and only then faults generating its UiData, raising the+// qualifying 400. The old bundle treated that status as "nothing was written" and its fallback+// wrote a SECOND copy — measured live as 4 rows for 2 authored rules, both Active, both firing.+//+// The fix probes for the committed row on that 400 and DELETES it before writing its own. Pinning+// it here because a future re-vendor that loses this reverts to silently duplicating every rule,+// and the resulting rows are not always deletable afterwards.+test('REAL BUNDLE: a qualifying 400 makes the SDK remove the committed row before the classic write', async () => {+ const COMMITTED = '77777777-7777-7777-7777-777777777777';+ const { sdk, calls } = sdkWith({+ // The bound member faults AFTER committing.+ post: (url) => (/CreateProcessWithWfomJson/i.test(url)+ ? { status: 400, headers: {}, body: { error: { code: '0x80040216', message: 'Error generating UiData for workflow' } } }+ : { status: 204, headers: { 'odata-entityid': 'https://x/workflows(55555555-5555-5555-5555-555555555555)' }, body: {} }),+ // The probe for the orphan finds exactly one candidate.+ get: (url) => (/workflows\?/i.test(String(url))+ ? { status: 200, headers: {}, body: { value: [{ workflowid: COMMITTED }] } }+ : { status: 200, headers: {}, body: { value: [] } }),+ });++ const res = await authorDupGuard(sdk);+ assert.strictEqual(res.saved, true, 'the fallback still succeeds');++ // The committed orphan must be DELETED — not adopted. Its content is unverified (the fault+ // happened while generating UiData), so promoting it would activate a half-built definition.+ const del = calls.find((c) => c.verb === 'DELETE' && String(c.url).includes(COMMITTED));+ assert.ok(del, 'the committed row must be deleted; calls: ' + JSON.stringify(calls.map((c) => `${c.verb} ${c.url}`)));++ // And the delete must precede the classic POST, or the row it removes could be the new one.+ const delIdx = calls.indexOf(del);+ const classicIdx = calls.findIndex((c) => c.verb === 'POST' && /\/workflows$/.test(String(c.url)));+ assert.ok(classicIdx > -1, 'the classic fallback write must still happen');+ assert.ok(delIdx < classicIdx, 'the orphan is removed BEFORE the replacement is written');++ // The PROBE must be narrow. A broad probe would delete somebody else's rule, which is far worse+ // than the duplicate it exists to prevent. Measured shape:+ // workflows?$select=workflowid,createdon&$filter=category eq 2 and type eq 1 and+ // name eq 'Dup Guard' and primaryentity eq 'account' and createdon ge <watermark>+ // &$orderby=createdon desc&$top=2+ const probe = calls.find((c) => c.verb === 'GET' && /workflows\?/i.test(String(c.url)));+ assert.ok(probe, 'the orphan probe must run');+ const probeUrl = decodeURIComponent(String(probe.url));+ for (const needle of ['category eq 2', 'type eq 1', "name eq 'Dup Guard'", "primaryentity eq 'account'", 'createdon ge', '$top=2']) {+ assert.ok(probeUrl.includes(needle), `the probe must constrain on ${needle}; got ${probeUrl}`);+ }+});++test('REAL BUNDLE: orphan cleanup FAILS CLOSED — no replacement is written when it cannot be trusted', async () => {+ // "Best-effort fall-through" is how the duplicate comes back. Both of these are measured, not+ // assumed: a failed DELETE and an ambiguous probe each rethrow, and crucially neither goes on to+ // write the classic row — which would leave the orphan AND a new copy.+ const COMMITTED = '77777777-7777-7777-7777-777777777777';+ const faultingPost = (url) => (/CreateProcessWithWfomJson/i.test(url)+ ? { status: 400, headers: {}, body: { error: { code: '0x80040216', message: 'Error generating UiData for workflow' } } }+ : { status: 204, headers: { 'odata-entityid': 'https://x/workflows(55555555-5555-5555-5555-555555555555)' }, body: {} });++ // 1. The delete itself fails (the wedged-row case seen live: 405 0x80040227).+ {+ const { sdk, calls } = sdkWith({+ post: faultingPost,+ get: (url) => (/workflows\?/i.test(String(url))+ ? { status: 200, headers: {}, body: { value: [{ workflowid: COMMITTED }] } }+ : { status: 200, headers: {}, body: { value: [] } }),+ del: () => ({ status: 405, headers: {}, body: { error: { code: '0x80040227', message: 'cannot be deleted' } } }),+ });+ await assert.rejects(() => authorDupGuard(sdk), 'a failed cleanup must not resolve as success');+ assert.strictEqual(calls.some((c) => c.verb === 'POST' && /\/workflows$/.test(String(c.url))), false,+ 'no classic write may follow a failed cleanup — that is how BOTH rows end up present');+ }++ // 2. The probe is ambiguous (more than one candidate) — deleting either could destroy a real rule.+ {+ const { sdk, calls } = sdkWith({+ post: faultingPost,+ get: (url) => (/workflows\?/i.test(String(url))+ ? { status: 200, headers: {}, body: { value: [{ workflowid: COMMITTED }, { workflowid: '88888888-8888-8888-8888-888888888888' }] } }+ : { status: 200, headers: {}, body: { value: [] } }),+ });+ await assert.rejects(() => authorDupGuard(sdk), 'an ambiguous probe must not resolve as success');+ assert.strictEqual(calls.some((c) => c.verb === 'DELETE'), false, 'an ambiguous probe must delete NOTHING');+ assert.strictEqual(calls.some((c) => c.verb === 'POST' && /\/workflows$/.test(String(c.url))), false,+ 'and must not write a replacement either');+ }+});diff --git a/plugins/model-apps/scripts/tests/session-cache-contract.test.js b/plugins/model-apps/scripts/tests/session-cache-contract.test.jsnew file mode 100644index 000000000..7d731b0af--- /dev/null+++ b/plugins/model-apps/scripts/tests/session-cache-contract.test.js@@ -0,0 +1,95 @@+'use strict';+// WORKSPACE-CACHE ORDERING INVARIANT — the guard for the plugin's persistent workspace.+//+// HISTORY, because the rationale changed under us and the old one is misleading. The bundle this+// test was written against ENFORCED the workspace as an ephemeral session cache: `MakerSdk`+// recorded `sessionStartedAt` and refused a cached artifact whose `meta.fetchedAt` predated the+// instance, throwing `ARTIFACT_CACHE_PREDATES_SESSION` (issue #469).+//+// That enforcement is GONE from the SDK the plugin now vendors. Upstream replaced it with a 300s+// TIME-based staleness window: a read whose cached copy is older than the window revalidates+// against the server instead of failing, and the error no longer exists in the bundle at all.+// So #469's hard-failure hazard — a user's SECOND build throwing — is closed by the SDK, not here.+//+// The invariant below is kept anyway, because the replacement has its own sharp edge. Reads inside+// the 300s window are served from the local copy, and a mutation applied after a revalidation+// refreshed that copy can now raise `StaleArtifactError` ("any pointer derived from the old copy+// may now identify a different node"). Both hazards have the same root cause and the same fix:+// never READ or PUSH an artifact kind this run did not itself FETCH or CREATE, and re-derive a+// pointer from a fresh read rather than carrying one across a mutation.+//+// This asserts the invariant the PLUGIN owns, by source scan, rather than re-probing SDK internals+// (brittle, and it would assert the SDK's behaviour rather than the plugin's).+const test = require('node:test');+const assert = require('node:assert');+const path = require('node:path');+const fs = require('node:fs');++test('the build engine never reads an artifact kind it does not also fetch or create', () => {+ // A kind that is only ever READ from the workspace is, by construction, reading a cache entry it+ // did not put there — a copy of unknown age from an earlier run.+ const src = fs.readFileSync(path.resolve(__dirname, '..', 'lib', 'sdk-build.js'), 'utf8');+ const reads = [...src.matchAll(/provision\.getArtifact\(\s*'(\w+)'/g)].map((m) => m[1]);+ assert.ok(reads.length > 0, 'the scan found the getArtifact reads it is meant to guard');++ for (const kind of new Set(reads)) {+ const fetched = new RegExp(`provision\\.fetchArtifact\\(\\s*'${kind}'`).test(src);+ const created = new RegExp(`provision\\.createArtifact\\(\\s*'${kind}'`).test(src)+ // Forms are built through createFormShell rather than a direct createArtifact, because the+ // adapter's createDefault serializes authored tabs before minting ids and throws.+ || (kind === 'form' && /createFormShell\(/.test(src));+ assert.ok(fetched || created,+ `'${kind}' is read from the workspace but never fetched or created in the same engine — `+ + "on a user's SECOND build that serves a previous run's copy, silently while it is inside "+ + 'the SDK 300s staleness window (see issue #469)');+ }+});++test('the changed-only flow does not read SDK artifacts across runs', () => {+ // --changed-only is the one flow built around state that OUTLIVES a run, so it is the obvious+ // place for a cross-run SDK read to appear. It must keep reading only its OWN snapshot metadata+ // and delegate all artifact work to a fresh buildModelApp (and therefore a fresh SDK session).+ const src = fs.readFileSync(path.resolve(__dirname, '..', 'lib', 'changed-only-flow.js'), 'utf8');+ for (const banned of ['getArtifact', 'fetchArtifact', 'pushArtifact', 'listArtifacts', 'queryTree', 'findElements']) {+ assert.ok(!new RegExp(`\\.${banned}\\(`).test(src),+ `changed-only-flow.js must not call ${banned} directly — it spans runs, so an SDK artifact `+ + 'read there would read a previous session\'s cache (issue #469). Delegate to buildModelApp instead.');+ }+});++test('the build engine never PUSHES an artifact kind it does not also fetch or create', () => {+ // The residual half of #469, and the one the read-side guard above does not cover.+ //+ // `pushArtifact` reads the artifact from the workspace before serializing it, so a push of+ // something cached by an EARLIER run pushes that earlier copy. Note it does NOT go through the+ // same revalidating seam `getArtifact` uses — in this bundle the push path reads locally without+ // revalidating — so a push is if anything MORE exposed to a stale copy than a read is, not less.+ // Separately it trips ARTIFACT_LANGUAGE_MISMATCH once the plugin passes `languageCode`, because+ // the stored artifact language would disagree with the pushing SDK.+ //+ // Both are currently unreachable only because every push is preceded, in the same run, by a fetch+ // or a create. A future batch optimisation that pushed "known clean" artifacts without re-fetching+ // would make both reachable, and no other test would notice: the whole suite runs in one session,+ // so the failure appears on a user's SECOND build, not in CI.+ //+ // LIMIT OF THIS CHECK, stated so it is not mistaken for more than it is: it matches at the level+ // of artifact KIND across the whole file, not per call site or per code path. A new branch that+ // reads before fetching is NOT caught if any other code in the file fetches that same kind, and+ // a fully dynamic `pushArtifact(type, id)` is invisible to it. It is a cheap tripwire for the+ // obvious regression, not a proof of the invariant.+ const src = fs.readFileSync(path.resolve(__dirname, '..', 'lib', 'sdk-build.js'), 'utf8');+ const pushes = [...src.matchAll(/provision\.pushArtifact\(\s*'(\w+)'/g)].map((m) => m[1]);+ assert.ok(pushes.length > 0, 'the scan found the pushArtifact calls it is meant to guard');++ for (const kind of new Set(pushes)) {+ const fetched = new RegExp(`provision\\.fetchArtifact\\(\\s*'${kind}'`).test(src);+ const created = new RegExp(`provision\\.createArtifact\\(\\s*'${kind}'`).test(src)+ // Forms are built through createFormShell rather than a direct createArtifact, because the+ // adapter's createDefault serializes authored tabs before minting ids and throws.+ || (kind === 'form' && /createFormShell\(/.test(src));+ assert.ok(fetched || created,+ `'${kind}' is PUSHED but never fetched or created in the same engine — a second build would `+ + 'push a previous run\'s cached copy, and a non-default --language-code would additionally '+ + 'hit ARTIFACT_LANGUAGE_MISMATCH (see issue #469)');+ }+});diff --git a/plugins/model-apps/scripts/tests/stages.test.js b/plugins/model-apps/scripts/tests/stages.test.jsindex a870c3447..51bd388ae 100644--- a/plugins/model-apps/scripts/tests/stages.test.js+++ b/plugins/model-apps/scripts/tests/stages.test.js@@ -5,13 +5,13 @@ const path = require('node:path');const { PHASES, STAGES, phasesForStage, stagePhasesOrResolve } = require(path.join(__dirname, '..', 'lib', 'stages.js'));const { resolvePhases } = require(path.join(__dirname, '..', 'lib', 'sdk-build.js'));-test('PHASES is the canonical 14-phase ordered list', () => {- assert.deepStrictEqual(PHASES, ['solution', 'data-model', 'sample-data', 'web-resources', 'views', 'charts', 'forms', 'commands', 'dashboards', 'app-shell', 'pages', 'ai-features', 'security', 'publish']);+test('PHASES is the canonical 15-phase ordered list', () => {+ assert.deepStrictEqual(PHASES, ['solution', 'data-model', 'sample-data', 'web-resources', 'views', 'charts', 'forms', 'business-rules', 'commands', 'dashboards', 'app-shell', 'pages', 'ai-features', 'security', 'publish']);});test('STAGES map groups contiguous phase ranges', () => {assert.deepStrictEqual(STAGES.data, ['solution', 'data-model', 'sample-data']);- assert.deepStrictEqual(STAGES.ui, ['web-resources', 'views', 'charts', 'forms', 'commands', 'dashboards']);+ assert.deepStrictEqual(STAGES.ui, ['web-resources', 'views', 'charts', 'forms', 'business-rules', 'commands', 'dashboards']);assert.deepStrictEqual(STAGES.app, ['app-shell', 'pages', 'ai-features', 'security']);assert.deepStrictEqual(STAGES.publish, ['publish']);// Every stage phase is a real engine phase, and the four stages tile PHASES with no gaps/overlaps.@@ -29,7 +29,7 @@ test('stagePhasesOrResolve: --stage wins; conflicting selectors throw', () => {});test('stagePhasesOrResolve without --stage delegates to resolvePhases', () => {- assert.deepStrictEqual(stagePhasesOrResolve({ from: 'forms' }), ['forms', 'commands', 'dashboards', 'app-shell', 'pages', 'ai-features', 'security', 'publish']);+ assert.deepStrictEqual(stagePhasesOrResolve({ from: 'forms' }), ['forms', 'business-rules', 'commands', 'dashboards', 'app-shell', 'pages', 'ai-features', 'security', 'publish']);});test('resolvePhases rejects an unknown phase instead of silently ignoring it', () => {diff --git a/plugins/model-apps/scripts/tests/vendor-sdk-smoke.test.js b/plugins/model-apps/scripts/tests/vendor-sdk-smoke.test.jsindex 0b0602ef8..696159ea1 100644--- a/plugins/model-apps/scripts/tests/vendor-sdk-smoke.test.js+++ b/plugins/model-apps/scripts/tests/vendor-sdk-smoke.test.js@@ -13,6 +13,20 @@ const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');// The migration's pure intent helpers, used to drive the generic surface in the CONTRACT tests below.const { formEventsRegionIntent, findFieldCellPointer } = require('../lib/artifact-intent.js');+// Every app the PLUGIN creates carries an icon: `ensureAppIcon` (sdk-build.js) resolves the author's+// `spec.app.icon` or generates an SVG web resource, and `appDef` passes its id as+// `iconWebResourceId`. These tests drive the SDK directly, so they must supply one too or they are+// exercising a path production never takes.+//+// The SDK now REQUIRES it: `appmodule.webresourceid` is a required attribute, and when no explicit id+// is given it auto-resolves an IMAGE web resource (PNG/JPG/GIF/ICO/SVG) and throws+// `APP_ICON_UNRESOLVED` if the environment has none. Previously it fell back to ANY unmanaged web+// resource — which on an org whose images are all managed returned a JAVASCRIPT file, and the platform+// rejected the create with an opaque "dependent component WebResource does not exist". Failing fast+// with a clear message is the better behaviour; these tests just have to stop relying on the old+// silent fallback. A synthetic id is right here — the mock transport never dereferences it.+const APP_ICON_ID = '11111111-2222-3333-4444-555555555555';+// Track temp workspace dirs created by the smoke tests and remove them once the suite finishes,// so repeated runs don't leak directories into the test runner's temp folder.const tempDirs = [];@@ -70,7 +84,11 @@ test('pushArtifact builds a real FormXML payload headlessly', async () => {const sdk = freshSdk(capture);const form = sdk.createArtifact('form', { entityLogicalName: 'account', name: 'Push Test Form' });const result = await sdk.pushArtifact('form', form.id);- assert.strictEqual(result.success, true);+ // The SDK renamed PushResult.success -> saved to force call sites to distinguish "the write+ // committed" from "the runtime serves it" (`shipped`, true only on a VERIFIED publish). Accept+ // either spelling so this pins the CONTRACT rather than one bundle generation.+ assert.strictEqual(result.saved !== undefined ? result.saved : result.success, true);+ assert.strictEqual(result.shipped, false, 'a push with no publish requested is saved but NOT shipped');assert.ok(capture.length > 0, 'a POST should have been issued');const body = capture[0].body;assert.ok(typeof body.formxml === 'string' && body.formxml.includes('<form'), 'payload carries FormXML');@@ -125,7 +143,7 @@ test('CONTRACT: a canonical /bag/c <events> region wires a handler into the reta// retired addFormEventHandler is gone). The adapter mints the handlerUniqueId at serialize.const bagC = (fetched.bag && fetched.bag.c) || [];const nextI = bagC.reduce((m, e) => Math.max(m, e.i), -1) + 1;- sdk.addElement('form', FID, '/bag/c', { i: nextI, node: formEventsRegionIntent([{ event: 'onload', library: 'new_smoke.js', function: 'Ticket.onLoad' }]) });+ await sdk.addElement('form', FID, '/bag/c', { i: nextI, node: formEventsRegionIntent([{ event: 'onload', library: 'new_smoke.js', function: 'Ticket.onLoad' }]) });await sdk.pushArtifact('form', FID);assert.match(pushedXml, /Ticket\.onLoad/, 'the handler function is baked into the pushed formxml');assert.match(pushedXml, /handlerUniqueId/, 'the adapter minted the handlerUniqueId the caller omitted');@@ -156,9 +174,9 @@ test('CONTRACT: removeElement drops a bound field from a fetched form (reconcileconst sdk = createMakerSdk({ workspacePath: ws, instanceUrl: 'https://example.crm.dynamics.com', httpClient });sdk.initWorkspace();await sdk.fetchArtifact('form', FID);- const ptr = findFieldCellPointer(sdk.getArtifact('form', FID), 'new_tier');+ const ptr = findFieldCellPointer(await sdk.getArtifact('form', FID), 'new_tier');assert.ok(ptr, 'the cell hosting the dropped field is located in the canonical tree');- sdk.removeElement('form', FID, ptr);+ await sdk.removeElement('form', FID, ptr);await sdk.pushArtifact('form', FID);assert.ok(/datafieldname="new_name"/.test(pushedXml), 'the kept field survives the push');assert.ok(!/datafieldname="new_tier"/.test(pushedXml), 'the removed field is gone from the pushed formxml');@@ -285,7 +303,7 @@ test('CONTRACT: free-text sitemap titles/URLs are XML-escaped, not rejected (a s};const sdk = createMakerSdk({ workspacePath: ws, instanceUrl: 'https://example.crm.dynamics.com', httpClient });sdk.initWorkspace();- const art = sdk.createArtifact('app', { name: spec.app.name, uniqueName: 'new_escapp', description: spec.app.description, siteMap: def.siteMap, components: def.components });+ const art = sdk.createArtifact('app', { name: spec.app.name, uniqueName: 'new_escapp', description: spec.app.description, siteMap: def.siteMap, components: def.components, iconWebResourceId: APP_ICON_ID });await assert.doesNotReject(sdk.pushArtifact('app', art.id), 'special-char titles/URLs must serialize, not throw');assert.ok(sitemapXml, 'the sitemap was serialized and posted');assert.match(sitemapXml, /&/, 'ampersands in titles/URLs are escaped');@@ -293,15 +311,22 @@ test('CONTRACT: free-text sitemap titles/URLs are XML-escaped, not rejected (a sassert.ok(!/<Title[^>]*>[^<]*&(?!amp;|lt;|gt;|quot;|apos;|#)/.test(sitemapXml), 'no raw unescaped ampersand inside a Title');});-test('CONTRACT: vendored deleteAppCascade returns a structured { success, deleted, failures } result surfacing child-cleanup failures (teardown relies on this to report orphaned genpage rows)', async () => {- // The app (and its sitemap) delete atomically, but a cascaded GENERATIVE-PAGE delete fails (a- // locked/500 row). The old void contract swallowed this; the skill's teardown reads- // result.failures to flag the orphan, so the bundle MUST keep returning the structured result- // after a re-vendor.+test('CONTRACT: vendored deleteAppCascade returns a structured { success, deleted, failures, retained } result and RETAINS generative pages rather than cascading them', async () => {+ // The app (and its sitemap) delete atomically. A generative page referenced by the sitemap is+ // deliberately NOT deleted: a `uxagentproject` is REFERENCED by an app, not owned by one — another+ // app's sitemap, or a form's UxAgentControl `RefId`, can point at the same row — so the SDK reports+ // it in `retained[]` and leaves the decision to the caller. `scripts/lib/sdk-teardown.js` is that+ // caller: it deletes only the pages the build's own page manifest records as authored here, and+ // lets Dataverse's dependency graph reject anything still referenced.+ //+ // This test previously asserted the OPPOSITE contract — that a failed cascaded genpage delete set+ // `success=false` and landed in `failures[]`. That was written against a bundle which cascaded+ // genpage deletes. Keep it pinned to `retained[]`: silently reverting to a cascade would delete a+ // page another app still surfaces.//- // The sitemap is deliberately NOT the failing row here: it is no longer an independently- // addressable cascade target — it is deleted in the SAME atomic $batch change set as the app, so- // a sitemap failure rejects the whole call instead of landing in failures[].+ // The sitemap is deliberately not the failing row here: it is not an independently addressable+ // cascade target — it is deleted in the SAME atomic $batch change set as the app, so a sitemap+ // failure rejects the whole call instead of landing in failures[].const APP_ID = '77777777-7777-7777-7777-777777777777';const APP_UNIQUE = '88888888-8888-8888-8888-888888888888';const SITEMAP_ID = '99999999-9999-9999-9999-999999999999';@@ -348,9 +373,13 @@ test('CONTRACT: vendored deleteAppCascade returns a structured { success, deleteconst sdk = sdkWith(client);const result = await sdk.deleteAppCascade(APP_ID, APP_UNIQUE);assert.ok(result && typeof result === 'object', 'deleteAppCascade returns a structured result (not void)');- assert.strictEqual(result.success, false, 'a failed child cleanup makes success=false');assert.ok(Array.isArray(result.deleted) && result.deleted.some((d) => d.type === 'app'), 'the primary app delete is reported in deleted[]');- assert.ok(Array.isArray(result.failures) && result.failures.some((f) => f.type === 'genPage'), 'the orphaned generative-page cleanup failure is surfaced in failures[]');+ assert.strictEqual(result.success, true, 'retaining a referenced generative page is not a failure');+ assert.deepStrictEqual(result.failures, [], 'nothing was attempted against the genpage, so nothing failed');+ assert.ok(+ Array.isArray(result.retained) && result.retained.some((r) => r.type === 'genPage' && r.id === GENPAGE_ID),+ 'the referenced generative page is surfaced in retained[] so the caller can decide'+ );});test('CONTRACT: vendored seedRecordGraph returns { createdIds: { <entity>: [ids] } } (the sample-data phase reads createdIds to bind children)', async () => {@@ -567,7 +596,7 @@ test('CONTRACT: a platform-ref VectorIcon on an Entity subarea reaches the seria};const sdk = createMakerSdk({ workspacePath: mkTempWorkspace('sdk-vecicon-'), instanceUrl: 'https://example.crm.dynamics.com', httpClient });sdk.initWorkspace();- const art = sdk.createArtifact('app', { name: spec.app.name, uniqueName: 'new_vecapp', description: '', siteMap: def.siteMap, components: def.components });+ const art = sdk.createArtifact('app', { name: spec.app.name, uniqueName: 'new_vecapp', description: '', siteMap: def.siteMap, components: def.components, iconWebResourceId: APP_ICON_ID });await assert.doesNotReject(sdk.pushArtifact('app', art.id), 'the smoke spec must push without a component-verification refusal');assert.ok(sitemapXml, 'the sitemap was serialized and posted');@@ -607,7 +636,47 @@ test('CONTRACT: the vendored SDK does NOT filter a bare Fluent VectorIcon — apconst siteMap = { areas: [{ id: 'area_0', title: 'Main', groups: [{ id: 'g0', title: 'G', subAreas: [{ id: 's0', title: 'Orders', type: 'Entity', entity: 'new_torder', vectorIcon: 'Grid' },] }] }] };- const art = sdk.createArtifact('app', { name: 'Raw Token', uniqueName: 'new_rawtoken', description: '', siteMap, components: { forms: [], views: [], charts: [] } });+ const art = sdk.createArtifact('app', { name: 'Raw Token', uniqueName: 'new_rawtoken', description: '', siteMap, components: { forms: [], views: [], charts: [] }, iconWebResourceId: APP_ICON_ID });await sdk.pushArtifact('app', art.id);assert.match(sitemapXml, /<SubArea[^>]*Entity="new_torder"[^>]*VectorIcon="Grid"/, 'the bundle serializes a bare token when handed one — so the plugin must not hand it one');});++test('CONTRACT: vendored publishArtifact RESOLVES with publish.kind on failure — it does NOT throw', async () => {+ // This is the contract whose change slipped through unnoticed. The SDK moved publishArtifact from+ // throwing to reporting by value; the engine discarded the result at all nine call sites, so every+ // publish failure became invisible and `ok: true` was reported anyway. There was a method-PRESENCE+ // guard for publishArtifact but no BEHAVIOURAL one, which is exactly the gap that let it land.+ //+ // A throw would also silently re-arm the transient-retry path, and a by-value failure would silently+ // disarm it, so which one the bundle does is load-bearing and must be pinned rather than assumed.+ const client = {+ get: async (url) => {+ if (/EntityDefinitions\(LogicalName=/i.test(url)) {+ const ln = (url.match(/LogicalName='([^']+)'/) || [])[1] || 'x';+ return { status: 200, headers: {}, body: { MetadataId: '33333333-3333-3333-3333-333333333333', EntitySetName: `${ln}s`, LogicalName: ln, PrimaryIdAttribute: `${ln}id`, PrimaryNameAttribute: 'name', SchemaName: ln, IsCustomEntity: true, ObjectTypeCode: 10001 } };+ }+ if (/\/systemforms\(/.test(url)) return { status: 200, headers: {}, body: { '@odata.etag': 'W/"1"', formid: FID, formxml: '<form/>', name: 'F', objecttypecode: 'account', type: 2 } };+ return { status: 200, headers: {}, body: { value: [] } };+ },+ // Only PublishXml fails; everything else succeeds, so this isolates the publish half.+ post: async (url) => (/PublishXml/i.test(url)+ ? { status: 500, headers: {}, body: { error: { message: 'PublishXml exploded' } } }+ : { status: 204, headers: {}, body: {} }),+ patch: async () => ({ status: 204, headers: {}, body: {} }),+ put: async () => ({ status: 204, headers: {}, body: {} }),+ delete: async () => ({ status: 204, headers: {}, body: {} }),+ postRaw: async () => ({ status: 200, headers: {}, body: '' }),+ };+ const FID = '11111111-1111-1111-1111-111111111111';+ const sdk = sdkWith(client);+ await sdk.fetchArtifact('form', FID);++ let threw = null;+ let result = null;+ try { result = await sdk.publishArtifact('form', FID); } catch (e) { threw = e; }++ assert.strictEqual(threw, null, 'publishArtifact must RESOLVE on a failed publish, not throw — the engine reads the result');+ assert.ok(result && typeof result === 'object', 'it returns a structured result');+ assert.ok(result.publish && result.publish.kind === 'failed', `publish.kind must be 'failed'; got ${JSON.stringify(result.publish)}`);+ assert.strictEqual(result.shipped, false, 'a failed publish is not shipped');+});diff --git a/plugins/model-apps/scripts/vendor/.gitattributes b/plugins/model-apps/scripts/vendor/.gitattributesnew file mode 100644index 000000000..23c9bc863--- /dev/null+++ b/plugins/model-apps/scripts/vendor/.gitattributes@@ -0,0 +1,11 @@+# The vendored SDK bundle is a GENERATED artifact whose bytes are claimed — PROVENANCE.json records+# its sha256, and scripts/tests/sdk-async-surface.test.js asserts the committed file matches.+#+# Without this rule, git's end-of-line normalisation makes that claim platform-dependent: a Windows+# checkout (autocrlf) rewrites every LF to CRLF, so the same commit produces a different file size+# and a different hash than on Linux or macOS. That is exactly how it was caught — the provenance+# test passed on ubuntu and macOS and failed on windows-latest with a 60-byte difference.+#+# `-text` tells git to store and check this file out verbatim on every platform, which is the+# correct treatment for generated output nobody hand-edits.+cds-maker-sdk.cjs -textdiff --git a/plugins/model-apps/scripts/vendor/PROVENANCE.json b/plugins/model-apps/scripts/vendor/PROVENANCE.jsonnew file mode 100644index 000000000..f6fe8a5f5--- /dev/null+++ b/plugins/model-apps/scripts/vendor/PROVENANCE.json@@ -0,0 +1,14 @@+{+ "commit": "b17bd3da66121a620c8cb1b198a7aaab6b6a0eed",+ "subject": "feat(cds-maker-sdk): Business Process Flow (BPF) authoring - all phases (create/activate/edit/structure/flow/security)",+ "dirtySdkPackage": 0,+ "libBuiltAt": "2026-08-28T16:33:04.842Z",+ "newestSrcAt": "2026-08-28T16:28:40.376Z",+ "libIsStale": false,+ "nostub": false,+ "esbuildVersion": "0.28.1",+ "nodeVersion": "v22.13.1",+ "builtAt": "2026-08-28T16:34:11.012Z",+ "bundleSha256": "0168206487969d69f01f843c1cfa3b751c018271b320d64017f880a17c466b86",+ "bundleBytes": 687133+}diff --git a/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs b/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjsindex 4a80097f7..d7a94e799 100644--- a/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs+++ b/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs@@ -25,34 +25,37 @@}globalThis.document=globalThis.document||globalThis.window.document;})();-"use strict";var PD=Object.create;var ao=Object.defineProperty;var OD=Object.getOwnPropertyDescriptor;var TD=Object.getOwnPropertyNames;var RD=Object.getPrototypeOf,FD=Object.prototype.hasOwnProperty;var D=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var m=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},Bt=(e,t)=>{for(var r in t)ao(e,r,{get:t[r],enumerable:!0})},Bp=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of TD(t))!FD.call(e,i)&&i!==r&&ao(e,i,{get:()=>t[i],enumerable:!(n=OD(t,i))||n.enumerable});return e};var ne=(e,t,r)=>(r=e!=null?PD(RD(e)):{},Bp(t||!e||!e.__esModule?ao(r,"default",{value:e,enumerable:!0}):r,e)),kt=e=>Bp(ao({},"__esModule",{value:!0}),e);var be=m(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.IncompatibleWorkspaceError=Z.PathTraversalError=Z.AmbiguousArtifactError=Z.JsonPointerError=Z.NotImplementedError=Z.WorkspaceNotInitializedError=Z.ConnectionError=Z.VersionConflictError=Z.InvalidArgumentError=Z.ValidationError=Z.PathNotFoundError=Z.ArtifactNotFoundError=Z.SdkError=void 0;var Je=class extends Error{constructor(t,r){super(r),this.code=t,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}};Z.SdkError=Je;var Pl=class extends Je{constructor(t,r){super("ARTIFACT_NOT_FOUND",`Artifact ${t}/${r} not found in workspace`),this.type=t,this.id=r}};Z.ArtifactNotFoundError=Pl;var Ol=class extends Je{constructor(t,r,n){super("PATH_NOT_FOUND",`Path ${n} not found in ${t}/${r}`),this.type=t,this.id=r,this.pointer=n}};Z.PathNotFoundError=Ol;var Tl=class extends Je{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}:+"use strict";var O1=Object.create;var is=Object.defineProperty;var x1=Object.getOwnPropertyDescriptor;var R1=Object.getOwnPropertyNames;var L1=Object.getPrototypeOf,F1=Object.prototype.hasOwnProperty;var I=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var g=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},sr=(e,t)=>{for(var r in t)is(e,r,{get:t[r],enumerable:!0})},$m=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of R1(t))!F1.call(e,i)&&i!==r&&is(e,i,{get:()=>t[i],enumerable:!(n=x1(t,i))||n.enumerable});return e};var se=(e,t,r)=>(r=e!=null?O1(L1(e)):{},$m(t||!e||!e.__esModule?is(r,"default",{value:e,enumerable:!0}):r,e)),lr=e=>$m(is({},"__esModule",{value:!0}),e);var le=g(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.IncompatibleWorkspaceError=K.PathTraversalError=K.AmbiguousArtifactError=K.JsonPointerError=K.NotImplementedError=K.WorkspaceNotInitializedError=K.ConnectionError=K.VersionConflictError=K.LocalEditsWouldBeLostError=K.StaleArtifactError=K.InvalidArgumentError=K.ValidationError=K.PathNotFoundError=K.ArtifactNotFoundError=K.readPartialTokens=K.withPartialTokens=K.SdkError=void 0;var Qe=class extends Error{constructor(t,r){super(r),this.code=t,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}};K.SdkError=Qe;var qm=Symbol.for("cds-maker-sdk.partialWriteTokens");function k1(e,t){return typeof e=="object"&&e!==null&&(e[qm]=t),e}K.withPartialTokens=k1;function M1(e){let t=e;for(let r=0;t&&typeof t=="object"&&r<8;r++){let n=t[qm];if(n&&typeof n=="object")return n;t=t.cause}}K.readPartialTokens=M1;var Zu=class extends Qe{constructor(t,r){super("ARTIFACT_NOT_FOUND",`Artifact ${t}/${r} not found in workspace`),this.type=t,this.id=r}};K.ArtifactNotFoundError=Zu;var ec=class extends Qe{constructor(t,r,n){super("PATH_NOT_FOUND",`Path ${n} not found in ${t}/${r}`),this.type=t,this.id=r,this.pointer=n}};K.PathNotFoundError=ec;var tc=class extends Qe{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}:`+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"}};Z.ValidationError=Tl;var Rl=class extends Je{constructor(t){super("INVALID_ARGUMENT",t)}};Z.InvalidArgumentError=Rl;var Fl=class extends Je{constructor(t,r,n,i){super("VERSION_CONFLICT",`Version conflict for ${t}/${r}: local=${n??"(none)"}, server=${i??"(none)"}. Re-fetch and reapply changes.`),this.type=t,this.id=r,this.localEtag=n,this.serverEtag=i}};Z.VersionConflictError=Fl;var xl=class extends Je{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}};Z.ConnectionError=xl;var Ll=class extends Je{constructor(t){super("WORKSPACE_NOT_INITIALIZED",`Workspace not initialized at ${t}. Call initWorkspace() first.`),this.workspacePath=t}};Z.WorkspaceNotInitializedError=Ll;var Ml=class extends Je{constructor(t,r){super("NOT_IMPLEMENTED",`Operation '${t}' is not implemented yet${r?`: ${r}`:""}.`),this.operation=t}};Z.NotImplementedError=Ml;var Ul=class extends Je{constructor(t,r){super("INVALID_JSON_POINTER",`Invalid JSON Pointer '${t}': ${r}`),this.pointer=t}};Z.JsonPointerError=Ul;var Bl=class extends Je{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}};Z.AmbiguousArtifactError=Bl;var kl=class extends Je{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}};Z.PathTraversalError=kl;var ql=class extends Je{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}};Z.IncompatibleWorkspaceError=ql});var lo=m(so=>{"use strict";Object.defineProperty(so,"__esModule",{value:!0});so.JsonPointer=void 0;var pt=be(),oo=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 pt.JsonPointerError(t,'non-empty pointers must start with "/"');return t.substring(1).split("/").map(r=>{if(/~(?![01])/.test(r))throw new pt.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 pt.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 pt.JsonPointerError(r,`'${o}' is not a valid array index`);if(s>a.length)throw new pt.JsonPointerError(r,`array index '${o}' is out of range`);a[s]=n}else{if(e.isReservedToken(o))throw new pt.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 pt.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 pt.JsonPointerError(r,`array index '${a}' is out of range`);i.splice(o,1)}else{if(e.isReservedToken(a))throw new pt.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 pt.JsonPointerError(r,"add target must be an array");u.push(n);return}let o=e.resolve(t,r);if(!Array.isArray(o))throw new pt.JsonPointerError(r,"add target must be an array");let s=i===void 0?o.length:i;if(s<0||s>o.length)throw new pt.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 pt.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)}};so.JsonPointer=oo;oo.RESERVED_TOKENS=new Set(["__proto__","prototype","constructor"])});var qp=m(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.findElements=void 0;var kp=lo();function xD(e,t){let r=[];return $l(e,"",t,r),r}uo.findElements=xD;function $l(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)=>{$l(i,kp.JsonPointer.append(t,a),r,n)});else for(let i of Object.keys(e))$l(e[i],kp.JsonPointer.append(t,i),r,n)}});var Gp=m(Qe=>{"use strict";var LD=Qe&&Qe.__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]})),MD=Qe&&Qe.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Vp=Qe&&Qe.__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)&&LD(t,e,r);return MD(t,e),t};Object.defineProperty(Qe,"__esModule",{value:!0});Qe.WorkspaceManager=Qe.WORKSPACE_SCHEMA_VERSION=void 0;var he=Vp(require("fs")),ye=Vp(require("path")),wn=be();Qe.WORKSPACE_SCHEMA_VERSION=1;var co={form:"forms",view:"views",businessRule:"business-rules",app:"apps",command:"commands",chart:"charts",dashboard:"dashboards"},UD="manifest.json",po=".metadata",$p="entities",Vl=class{constructor(t,r){this.workspacePath=t,this.instanceUrl=r}getRoot(){return this.workspacePath}getArtifactDir(t){return ye.join(this.workspacePath,co[t])}getArtifactFilePath(t,r){return this.assertSafeId(r),this.assertWithinRoot(ye.join(this.getArtifactDir(t),`${fo(r)}.json`))}getMetaFilePath(t,r){return this.assertSafeId(r),this.assertWithinRoot(ye.join(this.workspacePath,po,co[t],`${fo(r)}.meta.json`))}getEntityMetaFilePath(t){return this.assertSafeId(t),this.assertWithinRoot(ye.join(this.workspacePath,po,$p,`${t}.json`))}assertSafeId(t){if(typeof t!="string"||t.length===0||/[\u0000-\u001f]/.test(t)||t.includes("/")||t.includes("\\")||t.includes(":")||t==="."||t===".."||t.includes("..")||ye.basename(t)!==t)throw new wn.PathTraversalError(String(t),this.workspacePath)}assertWithinRoot(t){let r=ye.resolve(this.workspacePath),n=ye.resolve(t);if(n!==r&&!n.startsWith(r+ye.sep))throw new wn.PathTraversalError(t,this.workspacePath);let i=he.existsSync(r)?he.realpathSync(r):r,a=n,o=[];for(;!he.existsSync(a);){o.unshift(ye.basename(a));let l=ye.dirname(a);if(l===a)break;a=l}let s=ye.resolve(he.realpathSync(a),...o);if(s!==i&&!s.startsWith(i+ye.sep))throw new wn.PathTraversalError(t,this.workspacePath);return n}get manifestPath(){return ye.join(this.workspacePath,UD)}init(){for(let t of Object.keys(co))he.mkdirSync(this.getArtifactDir(t),{recursive:!0}),he.mkdirSync(ye.dirname(this.getMetaFilePath(t,"x")),{recursive:!0});if(he.mkdirSync(ye.join(this.workspacePath,po,$p),{recursive:!0}),!this.exists(this.manifestPath)){let t={instanceUrl:this.instanceUrl,createdAt:new Date().toISOString(),artifacts:[]};this.writeManifest(t)}}isInitialized(){return this.exists(this.manifestPath)}ensureInitialized(){if(!this.isInitialized())throw new wn.WorkspaceNotInitializedError(this.workspacePath)}clean(){for(let r of Object.keys(co))Gl(this.getArtifactDir(r));Gl(ye.join(this.workspacePath,po));let t=this.getManifest();t.artifacts=[],t.lastSyncAt=void 0,this.init(),this.writeManifest(t)}readArtifact(t,r){return this.ensureInitialized(),this.readJson(this.getArtifactFilePath(t,r))}writeArtifact(t,r,n){this.ensureInitialized(),this.writeJson(this.getArtifactFilePath(t,r),n),this.upsertManifestEntry(t,r,n)}deleteArtifact(t,r){this.ensureInitialized(),this.removeFile(this.getArtifactFilePath(t,r)),this.removeFile(this.getMetaFilePath(t,r));let n=fo(r),i=this.getManifest();i.artifacts=i.artifacts.filter(a=>!(a.type===t&&a.id===n)),this.writeManifest(i)}listArtifacts(t,r){return this.ensureInitialized(),this.getManifest().artifacts.filter(n=>!(t&&n.type!==t||r?.entityLogicalName&&n.entityLogicalName!==r.entityLogicalName))}readEntityMetadata(t){this.ensureInitialized();let r=this.readJson(this.getEntityMetaFilePath(t));return!r||typeof r.schemaName!="string"||typeof r.primaryNameAttribute!="string"||typeof r.primaryIdAttribute!="string"||typeof r.isCustomEntity!="boolean"?null:r}writeEntityMetadata(t,r){this.ensureInitialized(),this.writeJson(this.getEntityMetaFilePath(t),r)}getManifest(){this.ensureInitialized();let t=this.readJson(this.manifestPath);if(!t)throw new wn.WorkspaceNotInitializedError(this.workspacePath);if(t.schemaVersion!==void 0&&t.schemaVersion>Qe.WORKSPACE_SCHEMA_VERSION)throw new wn.IncompatibleWorkspaceError(t.schemaVersion,Qe.WORKSPACE_SCHEMA_VERSION);return t}writeManifest(t){this.writeJson(this.manifestPath,{...t,schemaVersion:Qe.WORKSPACE_SCHEMA_VERSION})}updateManifest(t){let r=this.getManifest();this.writeManifest({...r,...t})}upsertManifestEntry(t,r,n){let i=this.getManifest(),a=fo(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}),this.writeManifest(i)}readJson(t){return this.exists(t)?JSON.parse(he.readFileSync(t,"utf8")):null}writeJson(t,r){let n=ye.dirname(t);he.mkdirSync(n,{recursive:!0});let i=ye.join(n,`.${ye.basename(t)}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);try{he.writeFileSync(i,`${JSON.stringify(r,null,2)}-`,"utf8"),he.renameSync(i,t)}catch(a){try{he.existsSync(i)&&he.unlinkSync(i)}catch{}throw a}}removeFile(t){this.exists(t)&&he.unlinkSync(t)}exists(t){return he.existsSync(t)}};Qe.WorkspaceManager=Vl;function fo(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()}function Gl(e){let t;try{t=he.lstatSync(e)}catch{return}if(t.isSymbolicLink()){try{he.unlinkSync(e)}catch{he.rmdirSync(e)}return}if(!t.isDirectory()){he.unlinkSync(e);return}for(let r of he.readdirSync(e))Gl(ye.join(e,r));he.rmdirSync(e)}});var Jp=m(Nn=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});Nn.deepEqual=Nn.deepDiff=void 0;var BD=lo();function kD(e,t){let r=[];return Wp(e,t,"",r,0),r}Nn.deepDiff=kD;var mo=Symbol("missing"),ho=512;function Wp(e,t,r,n,i){if(e===t)return;if(i>ho)throw new RangeError(`deepDiff exceeded the maximum supported depth of ${ho}`);let a=go(e),o=go(t);if(a&&o&&Array.isArray(e)===Array.isArray(t)){let s=qD(e,t);for(let l of s){let u=zp(e,l),c=zp(t,l),d=BD.JsonPointer.append(r,l);u===mo?n.push({pointer:d,type:"added",newValue:c}):c===mo?n.push({pointer:d,type:"removed",oldValue:u}):Wp(u,c,d,n,i+1)}return}jp(e,t)||n.push({pointer:r,type:"modified",oldValue:e,newValue:t})}function go(e){return e!==null&&typeof e=="object"}function qD(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 zp(e,t){if(Array.isArray(e)){let r=Number(t);return r<e.length?e[r]:mo}return t in e?e[t]:mo}function jp(e,t){return Hp(e,t,0)}Nn.deepEqual=jp;function Hp(e,t,r){if(e===t)return!0;if(r>ho)throw new RangeError(`deepEqual exceeded the maximum supported depth of ${ho}`);if(!go(e)||!go(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&&Hp(e[a],t[a],r+1))}});var Xp=m(vo=>{"use strict";Object.defineProperty(vo,"__esModule",{value:!0});vo.VersionManager=void 0;var Qp=Jp(),zl=class{constructor(t){this.workspace=t}storeMeta(t,r,n){this.workspace.writeJson(this.workspace.getMetaFilePath(t,r),n)}getMeta(t,r){return this.workspace.readJson(this.workspace.getMetaFilePath(t,r))}isDirty(t,r){let n=this.workspace.readArtifact(t,r);if(n===null)return!1;let i=this.getMeta(t,r);return i?!(0,Qp.deepEqual)(i.snapshot,n):!0}diff(t,r){let n=this.workspace.readArtifact(t,r),i=this.getMeta(t,r),a;return n===null?a=i?[{pointer:"",type:"removed",oldValue:i.snapshot}]:[]:i?a=(0,Qp.deepDiff)(i.snapshot,n):a=[{pointer:"",type:"added",newValue:n}],{artifactType:t,artifactId:r,changes:a}}checkConflict(t,r,n){let i=this.getMeta(t,r);return!i||i.etag===null?!1:i.etag!==n}};vo.VersionManager=zl});var Yp=m((Wl,Kp)=>{(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof Wl=="object"?Kp.exports=t():e.compareVersions=t()})(Wl,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),f=parseInt(u[c]||0,10);if(d>f)return 1;if(f>d)return-1}var h=l[l.length-1],b=u[u.length-1];if(h&&b){var w=h.split(".").map(n),N=b.split(".").map(n);for(c=0;c<Math.max(w.length,N.length);c++){if(w[c]===void 0||typeof N[c]=="string"&&typeof w[c]=="number")return-1;if(N[c]===void 0||typeof w[c]=="string"&&typeof N[c]=="number"||w[c]>N[c])return 1;if(N[c]>w[c])return-1}}else if(h||b)return h?-1:1;return 0}})});var nf=m(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.EnvironmentFlowHostingType=fe.EnvironmentDisableReasonCode=fe.EnvironmentMigrationConstants=fe.EnvironmentProvisioningStates=fe.EnvironmentLocations=fe.EnvironmentCreationTypeConstants=fe.EnvironmentType=fe.EnvironmentSkuConstants=fe.environmentPermissions=fe.DatabaseType=void 0;var Zp;(function(e){e.CommonDataService="CommonDataService",e.None="None"})(Zp||(fe.DatabaseType=Zp={}));fe.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"};fe.EnvironmentSkuConstants={NotSpecified:"NotSpecified",Standard:"Standard",Premium:"Premium",Developer:"Developer",Basic:"Basic",Production:"Production",Sandbox:"Sandbox",Trial:"Trial",Default:"Default",Teams:"Teams",Platform:"Platform"};var ef;(function(e){e[e.CDS2=0]="CDS2",e[e.CDS1=1]="CDS1",e[e.Empty=2]="Empty"})(ef||(fe.EnvironmentType=ef={}));fe.EnvironmentCreationTypeConstants={NotSpecified:"NotSpecified",Legacy:"Legacy",DefaultTenant:"DefaultTenant",User:"User",CommonDataModelLegacy:"CommonDataModelLegacy"};fe.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"};fe.EnvironmentProvisioningStates={NotSpecified:"NotSpecified",Succeeded:"Succeeded",Deleting:"Deleting",Deleted:"Deleted",FailedDeleting:"FailedDeleting",LinkedDatabaseProvisioning:"LinkedDatabaseProvisioning",LinkedDatabaseFailedProvisioning:"LinkedDatabaseFailedProvisioning",LinkedDatabaseFailedConfiguring:"LinkedDatabaseFailedConfiguring",LinkedDatabaseUnavailable:"LinkedDatabaseUnavailable",Creating:"Creating"};fe.EnvironmentMigrationConstants={phases:{completed:"Completed"}};var tf;(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"})(tf||(fe.EnvironmentDisableReasonCode=tf={}));var rf;(function(e){e.LogicApps="LogicApps",e.SelfHostSingleTenant="SelfHostSingleTenant",e.SelfHostMultiTenant="SelfHostMultiTenant"})(rf||(fe.EnvironmentFlowHostingType=rf={}))});var pf=m(y=>{"use strict";var $D=y&&y.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(y,"__esModule",{value:!0});y.hasCommonDataServiceDatabase=y.getEnvironmentDiscoveryUrl=y.getEnvironmentWebApiUrl=y.getEnvironmentInstanceApiUrl=y.getEnvironmentLanguageCode=y.getEnvironmentUpdateCadence=y.checkVersions=y.isCds2EnvironmentVersionAtLeast=y.getSecurityOrConnectedGroupId=y.hasSecurityGroupId=y.doesCds2VersionSupportApiVersion9_1=y.doesCds2EnvironmentSupportApiVersion9_1=y.cdsVersionSupportingOSColorEdit=y.getEnvironmentDisplayName=y.getEnvironmentName=y.isEnvironmentInFirstReleaseCluster=y.isEnvironmentInPreprodCluster=y.isEnvironmentInTestCluster=y.isLiteEnvironmentUpgrading=y.isEnvironmentExpired=y.isEnvironmentInDeletedState=y.isEnvironmentInCreatingState=y.isDatabaseInProvisioningState=y.canUserCreateDatabase=y.isDisabledEnvironment=y.isDefaultEnvironment=y.isTrialEnvironment=y.isPlatformEnvironment=y.isTeamsEnvironment=y.isSandboxEnvironment=y.isProdEnvironment=y.isDevEnvironment=y.getEnvironmentType=y.getCrmInstanceName=y.getCrmInstanceUrl=y.getCrmAppDesignerUrl=y.getDevResourcesUrl=y.isEnvironmentInSuccessfulState=y.getAllThemesUrl=y.getAllPublishersUrl=y.getAllSolutionsUrl=y.getSecurityRolesUrl=y.getSecurityUsersUrl=y.environmentHasCds2Database=y.DEFAULT_SOLUTION_UNIQUE_NAME=y.DEFAULT_SOLUTION_ID=y.crmBapSolutionId=y.doesUserHavePermission=y.getLinkedEnvironmentMetadata=y.getCrmVersion=void 0;y.doesUserHaveFlowRunOnlyPermission=y.isUserPautoMakerWithoutDataAccess=y.isUserPautoMakerWithDataAccess=y.doesUserHaveCreateFlowPermission=y.equalsIgnoreCase=y.doesUserHaveCreateDatabasePermission=y.doesUserHaveDatabaseTablePermissions=y.isUserMakerWithoutDataAccess=y.isUserMakerWithDataAccess=y.doesUserHaveCreateAppPermission=y.doesUserHaveAdminPermission=void 0;var VD=$D(Yp()),ee=nf(),Ti=Hl();function GD(e){let t=ar(e);return t&&t.version}y.getCrmVersion=GD;function ar(e){return e&&e.properties&&e.properties.linkedEnvironmentMetadata}y.getLinkedEnvironmentMetadata=ar;function ir(e,t){return e?!!e[t]:!1}y.doesUserHavePermission=ir;y.crmBapSolutionId="00000001-0000-0000-0001-00000000009b";y.DEFAULT_SOLUTION_ID="fd140aaf-4df4-11dd-bd17-0019b9312238";y.DEFAULT_SOLUTION_UNIQUE_NAME="Default";function jr(e){return!!ar(e)&&af(e)}y.environmentHasCds2Database=jr;function zD(e){if(e&&jr(e)){let t=Ir(e);return(0,Ti.getCrmAdminSecurityRolesUrl)(t)}return""}y.getSecurityUsersUrl=zD;function WD(e){if(e&&jr(e)){let t=Ir(e);return(0,Ti.getCrmAdminSecurityUsersUrl)(t)}return""}y.getSecurityRolesUrl=WD;function jD(e){if(e&&jr(e)){let t=Ir(e);(0,Ti.getCrmAllSolutionsUrl)(t)}return""}y.getAllSolutionsUrl=jD;function HD(e){if(e&&jr(e)){let t=Ir(e);return(0,Ti.getCrmAllPublishersUrl)(t)}return""}y.getAllPublishersUrl=HD;function JD(e){return e&&jr(e)?Ir(e):""}y.getAllThemesUrl=JD;function af(e){return!!e&&e.properties&&!!e.properties.provisioningState&&e.properties.provisioningState.toUpperCase()===ee.EnvironmentProvisioningStates.Succeeded.toUpperCase()}y.isEnvironmentInSuccessfulState=af;function QD(e){if(e&&jr(e)){let t=Ir(e);return(0,Ti.getCrmDevResourcesUrl)(t)}return""}y.getDevResourcesUrl=QD;function XD(e){return`${e}designer/app/{${y.crmBapSolutionId}}/CreateNewApp}}`}y.getCrmAppDesignerUrl=XD;function Ir(e){let t=ar(e);if(t){let r=t.instanceUrl;return r?r.endsWith("/")?r:r+"/":""}return""}y.getCrmInstanceUrl=Ir;function KD(e){let t=ar(e);return t?t.uniqueName:""}y.getCrmInstanceName=KD;function YD(e){return ar(e)?ee.EnvironmentType.CDS2:e&&e.properties&&e.properties.namespace?ee.EnvironmentType.CDS1:ee.EnvironmentType.Empty}y.getEnvironmentType=YD;function ZD(e){return e&&e.properties&&e.properties.environmentSku===ee.EnvironmentSkuConstants.Developer}y.isDevEnvironment=ZD;function eE(e){return e&&e.properties&&e.properties.environmentSku===ee.EnvironmentSkuConstants.Production}y.isProdEnvironment=eE;function tE(e){return e&&e.properties&&e.properties.environmentSku===ee.EnvironmentSkuConstants.Sandbox}y.isSandboxEnvironment=tE;function Ri(e){return e&&e.properties&&e.properties.environmentSku===ee.EnvironmentSkuConstants.Teams}y.isTeamsEnvironment=Ri;function rE(e){return e&&e.properties&&e.properties.environmentSku===ee.EnvironmentSkuConstants.Platform}y.isPlatformEnvironment=rE;var nE=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.environmentSku)===ee.EnvironmentSkuConstants.Trial};y.isTrialEnvironment=nE;function iE(e){return e&&e.properties&&(e.properties.isDefault||e.properties.creationType===ee.EnvironmentCreationTypeConstants.DefaultTenant)}y.isDefaultEnvironment=iE;function aE(e){return e&&e.properties&&!!e.properties.states&&!!e.properties.states.runtime&&e.properties.states.runtime.id==="Disabled"}y.isDisabledEnvironment=aE;function oE(e){return e&&e.properties&&ir(e.properties.permissions,ee.environmentPermissions.CreateDatabase)}y.canUserCreateDatabase=oE;function sE(e){return!!(e&&e.properties&&e.properties.provisioningState&&df(e.properties.provisioningState,ee.EnvironmentProvisioningStates.LinkedDatabaseProvisioning))}y.isDatabaseInProvisioningState=sE;function lE(e){return!!e&&!!e.properties&&e.properties.provisioningState===ee.EnvironmentProvisioningStates.Creating}y.isEnvironmentInCreatingState=lE;function uE(e){return e&&e.properties&&(e.properties.provisioningState===ee.EnvironmentProvisioningStates.Deleted||e.properties.provisioningState===ee.EnvironmentProvisioningStates.Deleting||e.properties.provisioningState===ee.EnvironmentProvisioningStates.FailedDeleting)}y.isEnvironmentInDeletedState=uE;function cE(e){return!!e&&!!e.properties&&!!e.properties.expirationTime&&Date.parse(e.properties.expirationTime)<Date.now()}y.isEnvironmentExpired=cE;function dE(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"}y.isLiteEnvironmentUpgrading=dE;function pE(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Test"}y.isEnvironmentInTestCluster=pE;function fE(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Preprod"}y.isEnvironmentInPreprodCluster=fE;function mE(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="FirstRelease"}y.isEnvironmentInFirstReleaseCluster=mE;function hE(e){return e&&e.name||""}y.getEnvironmentName=hE;function gE(e){return e&&e.properties&&e.properties.displayName||""}y.getEnvironmentDisplayName=gE;var of="9.1.0.8202";y.cdsVersionSupportingOSColorEdit="9.1.0000.20708";function vE(e){return uf(e,of)}y.doesCds2EnvironmentSupportApiVersion9_1=vE;function bE(e){return jl(e,of)}y.doesCds2VersionSupportApiVersion9_1=bE;function sf(e){let t=ar(e);if(t)return t.securityGroupId}function lf(e){return e&&e.properties&&e.properties.connectedGroups}function yE(e,t){let r=lf(e);return!!r&&!!r.find(n=>n.id===t)||sf(e)===t}y.hasSecurityGroupId=yE;function CE(e){let t=lf(e);return t&&t.length>0&&t[0].id?t[0].id:sf(e)}y.getSecurityOrConnectedGroupId=CE;function uf(e,t){let r=e.version;return r?jl(r,t):!1}y.isCds2EnvironmentVersionAtLeast=uf;function jl(e,t){return t?e?(0,VD.default)(e,t)>=0:!1:!0}y.checkVersions=jl;function AE(e){return e&&e.properties&&e.properties.updateCadence&&e.properties.updateCadence.id||"NotSpecified"}y.getEnvironmentUpdateCadence=AE;function wE(e){let t=ar(e);return t?Number(t.baseLanguage):0}y.getEnvironmentLanguageCode=wE;function cf(e){let t=ar(e);return t?t.instanceApiUrl:void 0}y.getEnvironmentInstanceApiUrl=cf;function NE(e){let t=cf(e);return t?t+"/api/data/v9.2":""}y.getEnvironmentWebApiUrl=NE;function SE(e){let t=Ir(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"}y.getEnvironmentDiscoveryUrl=SE;var DE=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.databaseType)===ee.DatabaseType.CommonDataService};y.hasCommonDataServiceDatabase=DE;var EE=e=>{var t;return ir((t=e.properties)===null||t===void 0?void 0:t.permissions,ee.environmentPermissions.AdminReadEnvironment)};y.doesUserHaveAdminPermission=EE;var IE=e=>{var t;return ir((t=e.properties)===null||t===void 0?void 0:t.permissions,ee.environmentPermissions.CreatePowerApp)};y.doesUserHaveCreateAppPermission=IE;var _E=e=>(0,y.doesUserHaveAdminPermission)(e)&&(0,y.hasCommonDataServiceDatabase)(e)?!0:(0,y.doesUserHaveCreateAppPermission)(e)?Ri(e)||(0,y.doesUserHaveDatabaseTablePermissions)(e):!1;y.isUserMakerWithDataAccess=_E;var PE=e=>(0,y.doesUserHaveCreateAppPermission)(e)&&!Ri(e)&&!(0,y.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,y.doesUserHaveAdminPermission)(e)||!(0,y.hasCommonDataServiceDatabase)(e));y.isUserMakerWithoutDataAccess=PE;var OE=e=>[ee.environmentPermissions.CreateDatabaseEntities,ee.environmentPermissions.ListDatabaseEntities,ee.environmentPermissions.UpdateDatabaseEntities,ee.environmentPermissions.DeleteDatabaseEntities].every(t=>{var r;return ir((r=e.properties)===null||r===void 0?void 0:r.permissions,t)});y.doesUserHaveDatabaseTablePermissions=OE;var TE=e=>{var t;return ir((t=e.properties)===null||t===void 0?void 0:t.permissions,ee.environmentPermissions.CreateDatabase)};y.doesUserHaveCreateDatabasePermission=TE;function df(e,t){return!e&&!t?!0:!e||!t?!1:e.toUpperCase()===t.toUpperCase()}y.equalsIgnoreCase=df;var RE=e=>{var t;return ir((t=e.properties)===null||t===void 0?void 0:t.permissions,ee.environmentPermissions.CreateFlow)};y.doesUserHaveCreateFlowPermission=RE;var FE=e=>(0,y.doesUserHaveAdminPermission)(e)&&(0,y.hasCommonDataServiceDatabase)(e)?!0:(0,y.doesUserHaveCreateFlowPermission)(e)?Ri(e)||(0,y.doesUserHaveDatabaseTablePermissions)(e):!1;y.isUserPautoMakerWithDataAccess=FE;var xE=e=>(0,y.doesUserHaveCreateFlowPermission)(e)&&!Ri(e)&&!(0,y.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,y.doesUserHaveAdminPermission)(e)||!(0,y.hasCommonDataServiceDatabase)(e));y.isUserPautoMakerWithoutDataAccess=xE;var LE=e=>{var t,r;return!ir((t=e.properties)===null||t===void 0?void 0:t.permissions,ee.environmentPermissions.CreateFlow)&&ir((r=e.properties)===null||r===void 0?void 0:r.permissions,ee.environmentPermissions.ReadEnvironment)};y.doesUserHaveFlowRunOnlyPermission=LE});var Hl=m(v=>{"use strict";Object.defineProperty(v,"__esModule",{value:!0});v.getRequiredComponentsQueryUrl=v.solutionComponentCountSummariesQueryUrl=v.solutionComponentSummariesQueryUrl=v.solutionComponentConfigurationsQueryUrl=v.chartsQueryUrl=v.workflowsQueryUrl=v.entityDefinitionsQueryUrl=v.solutionComponentDefinitionsQueryUrl=v.getCreateNewArticleTemplateUrl=v.getCreateNewPublisherUrl=v.getEnableSecurityRolesUrl=v.getArticleTemplateUrl=v.getFieldSecurityProfileDesignerUrl=v.getSecurityRoleDesignerUrl=v.getMailMergeTemplateDesignerUrl=v.getEmailTemplateDesignerUrl=v.getConnectionRoleDesignerUrl=v.getSiteMapDesignerUrl=v.getWebResourceFileUrl=v.getWebResourceDesignerUrl=v.getReportDesignerUrl=v.getBusinessProcessFlowDesignerUrl=v.getProcessShareUrl=v.getProcessDesignerUrl=v.getChartDesignerUrl=v.getOpenModernEntityDashboardUrl=v.getNewModernEntityDashboardUrl=v.getNewModernDashboardUrl=v.getOpenModernDashboardUrl=v.getDashboardDesignerUrl=v.getAppModuleDesignerUrl=v.privilegesQueryUrls=v.xrmApiUrl=v.getPlayAppModuleUrl=v.getCrmAdminSecurityUsersUrl=v.getCrmAdminSecurityRolesUrl=v.getCrmMyAppsUrl=v.getCrmAppDesignerUrl=v.getCrmDevResourcesUrl=v.getCrmAllPublishersUrl=v.getCrmAllSolutionsUrl=v.getSolutionPublisherUrl=v.getExportTranslationFileName=v.getExportSolutionTranslationUrl=v.getImportSolutionTranslationUrl=v.getShowSolutionDependenciesUrl=v.getShowComponentDependenciesUrl=v.cdsServiceUrl=v.ODATA_NEXT_LINK=v.ODATA_MAX_PAGE_SIZE=void 0;v.retrieveOrganizationResources=v.getUCIEntityRecordEditUrl=v.getUCIEntityRecordBaseUrl=v.getBusinessRuleDesignerUri=v.retrieveUnpublishedSuffix=v.getSavePowerSettingUri=v.getPowerSettingUri=v.getPowerSettingsUri=v.RetrievePlatform=v.getAppSettingOverrideUri=v.AppSettingOverrideName=v.getOrgSettingOverrideUri=v.OrgSettingOverrideName=v.getSettingDefinitionsUri=v.retrieveFeatureControlSettingsByNamespaceUrl=v.retrieveDeploymentPipelineConfigAppUrl=v.SPNPrincipalIdUrl=v.retrieveDeploymentEnvironmentInfoUrl=v.devSolutionInfoUrl=v.deployOperationStatusUrl=v.getAIGeneratedDeploymentNotesUrl=v.deploymentStageRunUrl=v.validatePackageAsyncUrl=v.deployPackageAsyncUrl=v.updateDeploymentStageRunUrl=v.createDeploymentStageRunUrl=v.retrieveDeploymentStagesUrl=v.retrievePipelinesUrl=v.retrieveDeploymentPipelineInfoUrl=v.getDeploymentStageRunsUrl=v.appDeploymentUrls=v.getProvisionLanguageUrl=v.getSolutionQueryUrl=v.getSolutionsByUniqueNameQueryUrl=v.solutionsQueryUrl=v.getDependentComponentsWithMetadataQueryUrl=void 0;var ff=pf();v.ODATA_MAX_PAGE_SIZE="odata.maxpagesize";v.ODATA_NEXT_LINK="@odata.nextLink";v.cdsServiceUrl="https://cds-org/";var xi;(function(e){e.AllSolutions="11",e.AllPublishers="10",e.DevResources="05"})(xi||(xi={}));function ME(e,t,r,n){return`${e}tools/dependency/dependencyviewdialog.aspx?appSolutionId=%7b${t}%7d&dType=1&objectid=%7b${r}%7d&objecttype=${n}&operationtype=showdependency`}v.getShowComponentDependenciesUrl=ME;function UE(e,t){let r=`dType=1&isproactivecheck=true&objecttype=7100&operationtype=dependenciesforuninstall&objectid=${t}`;return`${e}tools/dependency/dependencyviewdialog.aspx?${r}`}v.getShowSolutionDependenciesUrl=UE;function BE(e,t){return`${e}tools/muiProvisioning/Dialogs/LangTranslationsImport.aspx?dType=1&appSolutionId=${t}`}v.getImportSolutionTranslationUrl=BE;function kE(e,t){return`${e}_grid/cmds/dlg_exportsolution.aspx?command=exporttranslation&appSolutionId=${t}`}v.getExportSolutionTranslationUrl=kE;function qE(e,t){return e!==void 0&&t!==void 0&&`CrmTranslations_${e}_${t.replace(/[.]/g,"_")}.zip`||""}v.getExportTranslationFileName=qE;function $E(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`}v.getSolutionPublisherUrl=$E;function Jl(e,t){return`${e}tools/systemcustomization/systemCustomization.aspx?pid=${t}`}function VE(e){return Jl(e,xi.AllSolutions)}v.getCrmAllSolutionsUrl=VE;function GE(e){return Jl(e,xi.AllPublishers)}v.getCrmAllPublishersUrl=GE;function zE(e){return Jl(e,xi.DevResources)}v.getCrmDevResourcesUrl=zE;function WE(e,t=ff.crmBapSolutionId){return`${e}designer/app/${t}#/CreateNewApp`}v.getCrmAppDesignerUrl=WE;function jE(e){return`${e}apps`}v.getCrmMyAppsUrl=jE;function HE(e){return mf(e,"role")+"&forceUCI=0"}v.getCrmAdminSecurityRolesUrl=HE;function JE(e){return`${mf(e,"systemuser")}&forceclassic=1`}v.getCrmAdminSecurityUsersUrl=JE;function mf(e,t){return`${e}main.aspx?pagetype=entitylist&etn=${t}`}function QE(e,t){return`${e}main.aspx?appid=${t}`}v.getPlayAppModuleUrl=QE;v.xrmApiUrl="api/data/v9.0";v.privilegesQueryUrls={systemUserInfo:e=>`${e}${v.xrmApiUrl}/WhoAmI`,userPrivileges:(e,t)=>`${e}${v.xrmApiUrl}/systemusers(${t})/Microsoft.Dynamics.CRM.RetrieveUserPrivileges`,systemPrivileges:e=>`${e}${v.xrmApiUrl}/privileges/Microsoft.Dynamics.CRM.RetrievePrivilegeSet`};function XE(e,t,r=ff.crmBapSolutionId){return`${e}designer/app/${r}/${t}/AppDesignerCanvas/${t}`}v.getAppModuleDesignerUrl=XE;function KE(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${r}%7d&extraqs=%26formId%3d%7b${t}%7d%26dashboardType%3d1030&pagetype=${`${n?"ic":""}dashboardeditor`}`}v.getDashboardDesignerUrl=KE;function YE(e,t,r){return`/e/${e}/s/${t}/dashboard/${r}`}v.getOpenModernDashboardUrl=YE;function ZE(e,t,r){let n=r!==void 0?r.toString():void 0;return`/e/${e}/s/${t}/dashboard/new${n?`/${n}`:""}`}v.getNewModernDashboardUrl=ZE;function eI(e,t,r,n){let i=n!==void 0?n.toString():void 0;return`/e/${e}/s/${t}/n/${r}/dashboard/new${i?`/${i}`:""}`}v.getNewModernEntityDashboardUrl=eI;function tI(e,t,r,n){return`/e/${e}/s/${t}/n/${r}/dashboard/${n}`}v.getOpenModernEntityDashboardUrl=tI;function rI(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${t}%7d&extraqs=etc=${r||""}`+(n?`%26id=${n}`:"")+"&pagetype=vizdesigner"}v.getChartDesignerUrl=rI;function nI(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}v.getProcessDesignerUrl=nI;function iI(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}v.getProcessShareUrl=iI;function aI(e,t){return`${e}Tools/ProcessControl/UnifiedProcessDesigner.aspx?id=${t}`}v.getBusinessProcessFlowDesignerUrl=aI;function oI(e,t,r){return`${e}CRMReports/reportproperty.aspx?appSolutionId=%7b${r}%7d&disablePersonal=true&id=%7b${t}%7d`}v.getReportDesignerUrl=oI;function sI(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`}v.getWebResourceDesignerUrl=sI;function lI(e,t){return`${e}WebResources/${t}`}v.getWebResourceFileUrl=lI;function uI(e,t,r){return`${e}designer/sitemap/${r}/${t}/SiteMapHome/${t}`}v.getSiteMapDesignerUrl=uI;function cI(e,t,r){return`${e}connections/connectionroles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}v.getConnectionRoleDesignerUrl=cI;function dI(e,t,r){return`${e}tools/emailtemplateeditor/emailtemplateeditor.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}v.getEmailTemplateDesignerUrl=dI;function pI(e,t,r){return`${e}tools/mailmerge/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}v.getMailMergeTemplateDesignerUrl=pI;function fI(e,t,r){return`${e}biz/roles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}v.getSecurityRoleDesignerUrl=fI;function mI(e,t,r){return`${e}biz/fieldsecurityprofiles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}v.getFieldSecurityProfileDesignerUrl=mI;function hI(e,t,r){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?_CreateFromId=%7b${t}%7d&_CreateFromType=7100&appSolutionId=%7b${t}%7d&id=%7b${r}%7d`}v.getArticleTemplateUrl=hI;function gI(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}`}v.getEnableSecurityRolesUrl=gI;function vI(e){return`${e}tools/publisher/edit.aspx`}v.getCreateNewPublisherUrl=vI;function bI(e,t){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?appSolutionId=${t}`}v.getCreateNewArticleTemplateUrl=bI;v.solutionComponentDefinitionsQueryUrl="api/data/v9.0/solutioncomponentdefinitions";v.entityDefinitionsQueryUrl="api/data/v9.0/EntityDefinitions?$select=EntitySetName,DisplayName,LogicalName&$filter=";v.workflowsQueryUrl="api/data/v9.0/workflows";v.chartsQueryUrl="/api/data/v9.0/savedqueryvisualizations";v.solutionComponentConfigurationsQueryUrl="/api/data/v9.1/solutioncomponentconfigurations?$filter=isdisplayable eq true&$select=name";v.solutionComponentSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentsummaries";v.solutionComponentCountSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentcountsummaries";function yI(e,t){return`${v.xrmApiUrl}/RetrieveRequiredComponents(ObjectId=${e},ComponentType=${t})`}v.getRequiredComponentsQueryUrl=yI;function CI(e,t){return`${v.cdsServiceUrl}${v.xrmApiUrl}/RetrieveDependentComponentsWithMetadata(ObjectId=${e},ComponentType=${t})`}v.getDependentComponentsWithMetadataQueryUrl=CI;v.solutionsQueryUrl="/api/data/v9.0/solutions?$expand=publisherid&$filter=(isvisible eq true)";function AI(e){return`/api/data/v9.0/solutions?$expand=publisherid&$filter=(uniquename eq '${e}')`}v.getSolutionsByUniqueNameQueryUrl=AI;function wI(e){return`/api/data/v9.0/solutions(${e})?$expand=publisherid`}v.getSolutionQueryUrl=wI;function NI(e){return`${e}api/data/v9.1/ProvisionLanguageForUser`}v.getProvisionLanguageUrl=NI;v.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 SI(e,t,r,n=!1,i=!1,a=!1,o=!1,s=!1,l=!1,u=!1){return`/api/data/v9.1/deploymentstageruns+`)),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"}};K.ValidationError=tc;var rc=class extends Qe{constructor(t){super("INVALID_ARGUMENT",t)}};K.InvalidArgumentError=rc;var nc=class extends Qe{constructor(t,r,n){super("STALE_ARTIFACT",`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}};K.StaleArtifactError=nc;var ic=class extends Qe{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}};K.LocalEditsWouldBeLostError=ic;var ac=class extends Qe{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}};K.VersionConflictError=ac;var oc=class extends Qe{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}};K.ConnectionError=oc;var sc=class extends Qe{constructor(t){super("WORKSPACE_NOT_INITIALIZED",`Workspace not initialized at ${t}. Call initWorkspace() first.`),this.workspacePath=t}};K.WorkspaceNotInitializedError=sc;var lc=class extends Qe{constructor(t,r){super("NOT_IMPLEMENTED",`Operation '${t}' is not implemented yet${r?`: ${r}`:""}.`),this.operation=t}};K.NotImplementedError=lc;var uc=class extends Qe{constructor(t,r){super("INVALID_JSON_POINTER",`Invalid JSON Pointer '${t}': ${r}`),this.pointer=t}};K.JsonPointerError=uc;var cc=class extends Qe{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}};K.AmbiguousArtifactError=cc;var dc=class extends Qe{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}};K.PathTraversalError=dc;var pc=class extends Qe{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}};K.IncompatibleWorkspaceError=pc});var ss=g(os=>{"use strict";Object.defineProperty(os,"__esModule",{value:!0});os.JsonPointer=void 0;var _t=le(),as=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 _t.JsonPointerError(t,'non-empty pointers must start with "/"');return t.substring(1).split("/").map(r=>{if(/~(?![01])/.test(r))throw new _t.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 _t.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 _t.JsonPointerError(r,`'${o}' is not a valid array index`);if(s>a.length)throw new _t.JsonPointerError(r,`array index '${o}' is out of range`);a[s]=n}else{if(e.isReservedToken(o))throw new _t.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 _t.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 _t.JsonPointerError(r,`array index '${a}' is out of range`);i.splice(o,1)}else{if(e.isReservedToken(a))throw new _t.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 _t.JsonPointerError(r,"add target must be an array");u.push(n);return}let o=e.resolve(t,r);if(!Array.isArray(o))throw new _t.JsonPointerError(r,"add target must be an array");let s=i===void 0?o.length:i;if(s<0||s>o.length)throw new _t.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 _t.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)}};os.JsonPointer=as;as.RESERVED_TOKENS=new Set(["__proto__","prototype","constructor"])});var Gm=g(ls=>{"use strict";Object.defineProperty(ls,"__esModule",{value:!0});ls.findElements=void 0;var Vm=ss();function U1(e,t){let r=[];return fc(e,"",t,r),r}ls.findElements=U1;function fc(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)=>{fc(i,Vm.JsonPointer.append(t,a),r,n)});else for(let i of Object.keys(e))fc(e[i],Vm.JsonPointer.append(t,i),r,n)}});var jm=g(Je=>{"use strict";var B1=Je&&Je.__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]})),$1=Je&&Je.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Wm=Je&&Je.__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)&&B1(t,e,r);return $1(t,e),t};Object.defineProperty(Je,"__esModule",{value:!0});Je.canonicalArtifactId=Je.WorkspaceManager=Je.WORKSPACE_SCHEMA_VERSION=void 0;var Ne=Wm(require("fs")),Ie=Wm(require("path")),ui=le();Je.WORKSPACE_SCHEMA_VERSION=1;var us={form:"forms",view:"views",businessRule:"business-rules",app:"apps",command:"commands",chart:"charts",dashboard:"dashboards",genPage:"gen-pages",bpf:"business-process-flows"},q1="manifest.json",cs=".metadata",zm="entities",mc=class{constructor(t,r){this.workspacePath=t,this.instanceUrl=r}getRoot(){return this.workspacePath}getArtifactDir(t){return Ie.join(this.workspacePath,us[t])}getArtifactFilePath(t,r){return this.assertSafeId(r),this.assertWithinRoot(Ie.join(this.getArtifactDir(t),`${_a(r)}.json`))}getMetaFilePath(t,r){return this.assertSafeId(r),this.assertWithinRoot(Ie.join(this.workspacePath,cs,us[t],`${_a(r)}.meta.json`))}getEntityMetaFilePath(t){return this.assertSafeId(t),this.assertWithinRoot(Ie.join(this.workspacePath,cs,zm,`${t}.json`))}assertSafeId(t){if(typeof t!="string"||t.length===0||/[\u0000-\u001f]/.test(t)||t.includes("/")||t.includes("\\")||t.includes(":")||t==="."||t===".."||t.includes("..")||Ie.basename(t)!==t)throw new ui.PathTraversalError(String(t),this.workspacePath)}assertWithinRoot(t){let r=Ie.resolve(this.workspacePath),n=Ie.resolve(t);if(n!==r&&!n.startsWith(r+Ie.sep))throw new ui.PathTraversalError(t,this.workspacePath);let i=Ne.existsSync(r)?Ne.realpathSync(r):r,a=n,o=[];for(;!Ne.existsSync(a);){o.unshift(Ie.basename(a));let l=Ie.dirname(a);if(l===a)break;a=l}let s=Ie.resolve(Ne.realpathSync(a),...o);if(s!==i&&!s.startsWith(i+Ie.sep))throw new ui.PathTraversalError(t,this.workspacePath);return n}get manifestPath(){return Ie.join(this.workspacePath,q1)}init(){for(let t of Object.keys(us))Ne.mkdirSync(this.getArtifactDir(t),{recursive:!0}),Ne.mkdirSync(Ie.dirname(this.getMetaFilePath(t,"x")),{recursive:!0});if(Ne.mkdirSync(Ie.join(this.workspacePath,cs,zm),{recursive:!0}),!this.exists(this.manifestPath)){let t={instanceUrl:this.instanceUrl,createdAt:new Date().toISOString(),artifacts:[]};this.writeManifest(t)}}isInitialized(){return this.exists(this.manifestPath)}ensureInitialized(){if(!this.isInitialized())throw new ui.WorkspaceNotInitializedError(this.workspacePath)}clean(){for(let r of Object.keys(us))hc(this.getArtifactDir(r));hc(Ie.join(this.workspacePath,cs));let t=this.getManifest();t.artifacts=[],t.lastSyncAt=void 0,this.init(),this.writeManifest(t)}readArtifact(t,r){return this.ensureInitialized(),this.readJson(this.getArtifactFilePath(t,r))}writeArtifact(t,r,n){this.ensureInitialized(),this.writeJson(this.getArtifactFilePath(t,r),n),this.upsertManifestEntry(t,r,n)}deleteArtifact(t,r){this.ensureInitialized(),this.removeFile(this.getArtifactFilePath(t,r)),this.removeFile(this.getMetaFilePath(t,r));let n=_a(r),i=this.getManifest();i.artifacts=i.artifacts.filter(a=>!(a.type===t&&a.id===n)),this.writeManifest(i)}listArtifacts(t,r){return this.ensureInitialized(),this.getManifest().artifacts.filter(n=>!(t&&n.type!==t||r?.entityLogicalName&&n.entityLogicalName!==r.entityLogicalName))}readEntityMetadata(t){this.ensureInitialized();let r=this.readJson(this.getEntityMetaFilePath(t));return!r||typeof r.schemaName!="string"||typeof r.primaryNameAttribute!="string"||typeof r.primaryIdAttribute!="string"||typeof r.isCustomEntity!="boolean"?null:r}writeEntityMetadata(t,r){this.ensureInitialized(),this.writeJson(this.getEntityMetaFilePath(t),r)}getManifest(){this.ensureInitialized();let t=this.readJson(this.manifestPath);if(!t)throw new ui.WorkspaceNotInitializedError(this.workspacePath);if(t.schemaVersion!==void 0&&t.schemaVersion>Je.WORKSPACE_SCHEMA_VERSION)throw new ui.IncompatibleWorkspaceError(t.schemaVersion,Je.WORKSPACE_SCHEMA_VERSION);return t}writeManifest(t){this.writeJson(this.manifestPath,{...t,schemaVersion:Je.WORKSPACE_SCHEMA_VERSION})}updateManifest(t){let r=this.getManifest();this.writeManifest({...r,...t})}upsertManifestEntry(t,r,n){let i=this.getManifest(),a=_a(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}),this.writeManifest(i)}readJson(t){return this.exists(t)?JSON.parse(Ne.readFileSync(t,"utf8")):null}writeJson(t,r){let n=Ie.dirname(t);Ne.mkdirSync(n,{recursive:!0});let i=Ie.join(n,`.${Ie.basename(t)}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);try{Ne.writeFileSync(i,`${JSON.stringify(r,null,2)}+`,"utf8"),Ne.renameSync(i,t)}catch(a){try{Ne.existsSync(i)&&Ne.unlinkSync(i)}catch{}throw a}}removeFile(t){this.exists(t)&&Ne.unlinkSync(t)}exists(t){return Ne.existsSync(t)}};Je.WorkspaceManager=mc;function _a(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()}Je.canonicalArtifactId=_a;function hc(e){let t;try{t=Ne.lstatSync(e)}catch{return}if(t.isSymbolicLink()){try{Ne.unlinkSync(e)}catch{Ne.rmdirSync(e)}return}if(!t.isDirectory()){Ne.unlinkSync(e);return}for(let r of Ne.readdirSync(e))hc(Ie.join(e,r));Ne.rmdirSync(e)}});var gc=g(ci=>{"use strict";Object.defineProperty(ci,"__esModule",{value:!0});ci.deepEqual=ci.deepDiff=void 0;var V1=ss();function G1(e,t){let r=[];return Qm(e,t,"",r,0),r}ci.deepDiff=G1;var ds=Symbol("missing"),ps=512;function Qm(e,t,r,n,i){if(e===t)return;if(i>ps)throw new RangeError(`deepDiff exceeded the maximum supported depth of ${ps}`);let a=fs(e),o=fs(t);if(a&&o&&Array.isArray(e)===Array.isArray(t)){let s=z1(e,t);for(let l of s){let u=Hm(e,l),c=Hm(t,l),d=V1.JsonPointer.append(r,l);u===ds?n.push({pointer:d,type:"added",newValue:c}):c===ds?n.push({pointer:d,type:"removed",oldValue:u}):Qm(u,c,d,n,i+1)}return}Jm(e,t)||n.push({pointer:r,type:"modified",oldValue:e,newValue:t})}function fs(e){return e!==null&&typeof e=="object"}function z1(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 Hm(e,t){if(Array.isArray(e)){let r=Number(t);return r<e.length?e[r]:ds}return t in e?e[t]:ds}function Jm(e,t){return Xm(e,t,0)}ci.deepEqual=Jm;function Xm(e,t,r){if(e===t)return!0;if(r>ps)throw new RangeError(`deepEqual exceeded the maximum supported depth of ${ps}`);if(!fs(e)||!fs(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&&Xm(e[a],t[a],r+1))}});var Ym=g(ms=>{"use strict";Object.defineProperty(ms,"__esModule",{value:!0});ms.VersionManager=void 0;var Km=gc(),vc=class{constructor(t){this.workspace=t}storeMeta(t,r,n){this.workspace.writeJson(this.workspace.getMetaFilePath(t,r),n)}getMeta(t,r){return this.workspace.readJson(this.workspace.getMetaFilePath(t,r))}isDirty(t,r){let n=this.workspace.readArtifact(t,r);if(n===null)return!1;let i=this.getMeta(t,r);return i?!(0,Km.deepEqual)(i.snapshot,n):!0}diff(t,r){let n=this.workspace.readArtifact(t,r),i=this.getMeta(t,r),a;return n===null?a=i?[{pointer:"",type:"removed",oldValue:i.snapshot}]:[]:i?a=(0,Km.deepDiff)(i.snapshot,n):a=[{pointer:"",type:"added",newValue:n}],{artifactType:t,artifactId:r,changes:a}}checkConflict(t,r,n){let i=this.getMeta(t,r);return!i||i.etag===null?!1:i.etag!==n}};ms.VersionManager=vc});var eh=g((yc,Zm)=>{(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof yc=="object"?Zm.exports=t():e.compareVersions=t()})(yc,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],h=u[u.length-1];if(f&&h){var b=f.split(".").map(n),w=h.split(".").map(n);for(c=0;c<Math.max(b.length,w.length);c++){if(b[c]===void 0||typeof w[c]=="string"&&typeof b[c]=="number")return-1;if(w[c]===void 0||typeof b[c]=="string"&&typeof w[c]=="number"||b[c]>w[c])return 1;if(w[c]>b[c])return-1}}else if(f||h)return f?-1:1;return 0}})});var ah=g(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.EnvironmentFlowHostingType=we.EnvironmentDisableReasonCode=we.EnvironmentMigrationConstants=we.EnvironmentProvisioningStates=we.EnvironmentLocations=we.EnvironmentCreationTypeConstants=we.EnvironmentType=we.EnvironmentSkuConstants=we.environmentPermissions=we.DatabaseType=void 0;var th;(function(e){e.CommonDataService="CommonDataService",e.None="None"})(th||(we.DatabaseType=th={}));we.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"};we.EnvironmentSkuConstants={NotSpecified:"NotSpecified",Standard:"Standard",Premium:"Premium",Developer:"Developer",Basic:"Basic",Production:"Production",Sandbox:"Sandbox",Trial:"Trial",Default:"Default",Teams:"Teams",Platform:"Platform"};var rh;(function(e){e[e.CDS2=0]="CDS2",e[e.CDS1=1]="CDS1",e[e.Empty=2]="Empty"})(rh||(we.EnvironmentType=rh={}));we.EnvironmentCreationTypeConstants={NotSpecified:"NotSpecified",Legacy:"Legacy",DefaultTenant:"DefaultTenant",User:"User",CommonDataModelLegacy:"CommonDataModelLegacy"};we.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"};we.EnvironmentProvisioningStates={NotSpecified:"NotSpecified",Succeeded:"Succeeded",Deleting:"Deleting",Deleted:"Deleted",FailedDeleting:"FailedDeleting",LinkedDatabaseProvisioning:"LinkedDatabaseProvisioning",LinkedDatabaseFailedProvisioning:"LinkedDatabaseFailedProvisioning",LinkedDatabaseFailedConfiguring:"LinkedDatabaseFailedConfiguring",LinkedDatabaseUnavailable:"LinkedDatabaseUnavailable",Creating:"Creating"};we.EnvironmentMigrationConstants={phases:{completed:"Completed"}};var nh;(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"})(nh||(we.EnvironmentDisableReasonCode=nh={}));var ih;(function(e){e.LogicApps="LogicApps",e.SelfHostSingleTenant="SelfHostSingleTenant",e.SelfHostMultiTenant="SelfHostMultiTenant"})(ih||(we.EnvironmentFlowHostingType=ih={}))});var fh=g(A=>{"use strict";var W1=A&&A.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(A,"__esModule",{value:!0});A.hasCommonDataServiceDatabase=A.getEnvironmentDiscoveryUrl=A.getEnvironmentWebApiUrl=A.getEnvironmentInstanceApiUrl=A.getEnvironmentLanguageCode=A.getEnvironmentUpdateCadence=A.checkVersions=A.isCds2EnvironmentVersionAtLeast=A.getSecurityOrConnectedGroupId=A.hasSecurityGroupId=A.doesCds2VersionSupportApiVersion9_1=A.doesCds2EnvironmentSupportApiVersion9_1=A.cdsVersionSupportingOSColorEdit=A.getEnvironmentDisplayName=A.getEnvironmentName=A.isEnvironmentInFirstReleaseCluster=A.isEnvironmentInPreprodCluster=A.isEnvironmentInTestCluster=A.isLiteEnvironmentUpgrading=A.isEnvironmentExpired=A.isEnvironmentInDeletedState=A.isEnvironmentInCreatingState=A.isDatabaseInProvisioningState=A.canUserCreateDatabase=A.isDisabledEnvironment=A.isDefaultEnvironment=A.isTrialEnvironment=A.isPlatformEnvironment=A.isTeamsEnvironment=A.isSandboxEnvironment=A.isProdEnvironment=A.isDevEnvironment=A.getEnvironmentType=A.getCrmInstanceName=A.getCrmInstanceUrl=A.getCrmAppDesignerUrl=A.getDevResourcesUrl=A.isEnvironmentInSuccessfulState=A.getAllThemesUrl=A.getAllPublishersUrl=A.getAllSolutionsUrl=A.getSecurityRolesUrl=A.getSecurityUsersUrl=A.environmentHasCds2Database=A.DEFAULT_SOLUTION_UNIQUE_NAME=A.DEFAULT_SOLUTION_ID=A.crmBapSolutionId=A.doesUserHavePermission=A.getLinkedEnvironmentMetadata=A.getCrmVersion=void 0;A.doesUserHaveFlowRunOnlyPermission=A.isUserPautoMakerWithoutDataAccess=A.isUserPautoMakerWithDataAccess=A.doesUserHaveCreateFlowPermission=A.equalsIgnoreCase=A.doesUserHaveCreateDatabasePermission=A.doesUserHaveDatabaseTablePermissions=A.isUserMakerWithoutDataAccess=A.isUserMakerWithDataAccess=A.doesUserHaveCreateAppPermission=A.doesUserHaveAdminPermission=void 0;var j1=W1(eh()),ae=ah(),Pa=wc();function H1(e){let t=Rr(e);return t&&t.version}A.getCrmVersion=H1;function Rr(e){return e&&e.properties&&e.properties.linkedEnvironmentMetadata}A.getLinkedEnvironmentMetadata=Rr;function xr(e,t){return e?!!e[t]:!1}A.doesUserHavePermission=xr;A.crmBapSolutionId="00000001-0000-0000-0001-00000000009b";A.DEFAULT_SOLUTION_ID="fd140aaf-4df4-11dd-bd17-0019b9312238";A.DEFAULT_SOLUTION_UNIQUE_NAME="Default";function Ln(e){return!!Rr(e)&&oh(e)}A.environmentHasCds2Database=Ln;function Q1(e){if(e&&Ln(e)){let t=nn(e);return(0,Pa.getCrmAdminSecurityRolesUrl)(t)}return""}A.getSecurityUsersUrl=Q1;function J1(e){if(e&&Ln(e)){let t=nn(e);return(0,Pa.getCrmAdminSecurityUsersUrl)(t)}return""}A.getSecurityRolesUrl=J1;function X1(e){if(e&&Ln(e)){let t=nn(e);(0,Pa.getCrmAllSolutionsUrl)(t)}return""}A.getAllSolutionsUrl=X1;function K1(e){if(e&&Ln(e)){let t=nn(e);return(0,Pa.getCrmAllPublishersUrl)(t)}return""}A.getAllPublishersUrl=K1;function Y1(e){return e&&Ln(e)?nn(e):""}A.getAllThemesUrl=Y1;function oh(e){return!!e&&e.properties&&!!e.properties.provisioningState&&e.properties.provisioningState.toUpperCase()===ae.EnvironmentProvisioningStates.Succeeded.toUpperCase()}A.isEnvironmentInSuccessfulState=oh;function Z1(e){if(e&&Ln(e)){let t=nn(e);return(0,Pa.getCrmDevResourcesUrl)(t)}return""}A.getDevResourcesUrl=Z1;function eP(e){return`${e}designer/app/{${A.crmBapSolutionId}}/CreateNewApp}}`}A.getCrmAppDesignerUrl=eP;function nn(e){let t=Rr(e);if(t){let r=t.instanceUrl;return r?r.endsWith("/")?r:r+"/":""}return""}A.getCrmInstanceUrl=nn;function tP(e){let t=Rr(e);return t?t.uniqueName:""}A.getCrmInstanceName=tP;function rP(e){return Rr(e)?ae.EnvironmentType.CDS2:e&&e.properties&&e.properties.namespace?ae.EnvironmentType.CDS1:ae.EnvironmentType.Empty}A.getEnvironmentType=rP;function nP(e){return e&&e.properties&&e.properties.environmentSku===ae.EnvironmentSkuConstants.Developer}A.isDevEnvironment=nP;function iP(e){return e&&e.properties&&e.properties.environmentSku===ae.EnvironmentSkuConstants.Production}A.isProdEnvironment=iP;function aP(e){return e&&e.properties&&e.properties.environmentSku===ae.EnvironmentSkuConstants.Sandbox}A.isSandboxEnvironment=aP;function Ta(e){return e&&e.properties&&e.properties.environmentSku===ae.EnvironmentSkuConstants.Teams}A.isTeamsEnvironment=Ta;function oP(e){return e&&e.properties&&e.properties.environmentSku===ae.EnvironmentSkuConstants.Platform}A.isPlatformEnvironment=oP;var sP=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.environmentSku)===ae.EnvironmentSkuConstants.Trial};A.isTrialEnvironment=sP;function lP(e){return e&&e.properties&&(e.properties.isDefault||e.properties.creationType===ae.EnvironmentCreationTypeConstants.DefaultTenant)}A.isDefaultEnvironment=lP;function uP(e){return e&&e.properties&&!!e.properties.states&&!!e.properties.states.runtime&&e.properties.states.runtime.id==="Disabled"}A.isDisabledEnvironment=uP;function cP(e){return e&&e.properties&&xr(e.properties.permissions,ae.environmentPermissions.CreateDatabase)}A.canUserCreateDatabase=cP;function dP(e){return!!(e&&e.properties&&e.properties.provisioningState&&ph(e.properties.provisioningState,ae.EnvironmentProvisioningStates.LinkedDatabaseProvisioning))}A.isDatabaseInProvisioningState=dP;function pP(e){return!!e&&!!e.properties&&e.properties.provisioningState===ae.EnvironmentProvisioningStates.Creating}A.isEnvironmentInCreatingState=pP;function fP(e){return e&&e.properties&&(e.properties.provisioningState===ae.EnvironmentProvisioningStates.Deleted||e.properties.provisioningState===ae.EnvironmentProvisioningStates.Deleting||e.properties.provisioningState===ae.EnvironmentProvisioningStates.FailedDeleting)}A.isEnvironmentInDeletedState=fP;function mP(e){return!!e&&!!e.properties&&!!e.properties.expirationTime&&Date.parse(e.properties.expirationTime)<Date.now()}A.isEnvironmentExpired=mP;function hP(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"}A.isLiteEnvironmentUpgrading=hP;function gP(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Test"}A.isEnvironmentInTestCluster=gP;function vP(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Preprod"}A.isEnvironmentInPreprodCluster=vP;function yP(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="FirstRelease"}A.isEnvironmentInFirstReleaseCluster=yP;function bP(e){return e&&e.name||""}A.getEnvironmentName=bP;function wP(e){return e&&e.properties&&e.properties.displayName||""}A.getEnvironmentDisplayName=wP;var sh="9.1.0.8202";A.cdsVersionSupportingOSColorEdit="9.1.0000.20708";function AP(e){return ch(e,sh)}A.doesCds2EnvironmentSupportApiVersion9_1=AP;function CP(e){return bc(e,sh)}A.doesCds2VersionSupportApiVersion9_1=CP;function lh(e){let t=Rr(e);if(t)return t.securityGroupId}function uh(e){return e&&e.properties&&e.properties.connectedGroups}function SP(e,t){let r=uh(e);return!!r&&!!r.find(n=>n.id===t)||lh(e)===t}A.hasSecurityGroupId=SP;function NP(e){let t=uh(e);return t&&t.length>0&&t[0].id?t[0].id:lh(e)}A.getSecurityOrConnectedGroupId=NP;function ch(e,t){let r=e.version;return r?bc(r,t):!1}A.isCds2EnvironmentVersionAtLeast=ch;function bc(e,t){return t?e?(0,j1.default)(e,t)>=0:!1:!0}A.checkVersions=bc;function EP(e){return e&&e.properties&&e.properties.updateCadence&&e.properties.updateCadence.id||"NotSpecified"}A.getEnvironmentUpdateCadence=EP;function DP(e){let t=Rr(e);return t?Number(t.baseLanguage):0}A.getEnvironmentLanguageCode=DP;function dh(e){let t=Rr(e);return t?t.instanceApiUrl:void 0}A.getEnvironmentInstanceApiUrl=dh;function IP(e){let t=dh(e);return t?t+"/api/data/v9.2":""}A.getEnvironmentWebApiUrl=IP;function _P(e){let t=nn(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"}A.getEnvironmentDiscoveryUrl=_P;var PP=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.databaseType)===ae.DatabaseType.CommonDataService};A.hasCommonDataServiceDatabase=PP;var TP=e=>{var t;return xr((t=e.properties)===null||t===void 0?void 0:t.permissions,ae.environmentPermissions.AdminReadEnvironment)};A.doesUserHaveAdminPermission=TP;var OP=e=>{var t;return xr((t=e.properties)===null||t===void 0?void 0:t.permissions,ae.environmentPermissions.CreatePowerApp)};A.doesUserHaveCreateAppPermission=OP;var xP=e=>(0,A.doesUserHaveAdminPermission)(e)&&(0,A.hasCommonDataServiceDatabase)(e)?!0:(0,A.doesUserHaveCreateAppPermission)(e)?Ta(e)||(0,A.doesUserHaveDatabaseTablePermissions)(e):!1;A.isUserMakerWithDataAccess=xP;var RP=e=>(0,A.doesUserHaveCreateAppPermission)(e)&&!Ta(e)&&!(0,A.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,A.doesUserHaveAdminPermission)(e)||!(0,A.hasCommonDataServiceDatabase)(e));A.isUserMakerWithoutDataAccess=RP;var LP=e=>[ae.environmentPermissions.CreateDatabaseEntities,ae.environmentPermissions.ListDatabaseEntities,ae.environmentPermissions.UpdateDatabaseEntities,ae.environmentPermissions.DeleteDatabaseEntities].every(t=>{var r;return xr((r=e.properties)===null||r===void 0?void 0:r.permissions,t)});A.doesUserHaveDatabaseTablePermissions=LP;var FP=e=>{var t;return xr((t=e.properties)===null||t===void 0?void 0:t.permissions,ae.environmentPermissions.CreateDatabase)};A.doesUserHaveCreateDatabasePermission=FP;function ph(e,t){return!e&&!t?!0:!e||!t?!1:e.toUpperCase()===t.toUpperCase()}A.equalsIgnoreCase=ph;var kP=e=>{var t;return xr((t=e.properties)===null||t===void 0?void 0:t.permissions,ae.environmentPermissions.CreateFlow)};A.doesUserHaveCreateFlowPermission=kP;var MP=e=>(0,A.doesUserHaveAdminPermission)(e)&&(0,A.hasCommonDataServiceDatabase)(e)?!0:(0,A.doesUserHaveCreateFlowPermission)(e)?Ta(e)||(0,A.doesUserHaveDatabaseTablePermissions)(e):!1;A.isUserPautoMakerWithDataAccess=MP;var UP=e=>(0,A.doesUserHaveCreateFlowPermission)(e)&&!Ta(e)&&!(0,A.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,A.doesUserHaveAdminPermission)(e)||!(0,A.hasCommonDataServiceDatabase)(e));A.isUserPautoMakerWithoutDataAccess=UP;var BP=e=>{var t,r;return!xr((t=e.properties)===null||t===void 0?void 0:t.permissions,ae.environmentPermissions.CreateFlow)&&xr((r=e.properties)===null||r===void 0?void 0:r.permissions,ae.environmentPermissions.ReadEnvironment)};A.doesUserHaveFlowRunOnlyPermission=BP});var wc=g(y=>{"use strict";Object.defineProperty(y,"__esModule",{value:!0});y.getRequiredComponentsQueryUrl=y.solutionComponentCountSummariesQueryUrl=y.solutionComponentSummariesQueryUrl=y.solutionComponentConfigurationsQueryUrl=y.chartsQueryUrl=y.workflowsQueryUrl=y.entityDefinitionsQueryUrl=y.solutionComponentDefinitionsQueryUrl=y.getCreateNewArticleTemplateUrl=y.getCreateNewPublisherUrl=y.getEnableSecurityRolesUrl=y.getArticleTemplateUrl=y.getFieldSecurityProfileDesignerUrl=y.getSecurityRoleDesignerUrl=y.getMailMergeTemplateDesignerUrl=y.getEmailTemplateDesignerUrl=y.getConnectionRoleDesignerUrl=y.getSiteMapDesignerUrl=y.getWebResourceFileUrl=y.getWebResourceDesignerUrl=y.getReportDesignerUrl=y.getBusinessProcessFlowDesignerUrl=y.getProcessShareUrl=y.getProcessDesignerUrl=y.getChartDesignerUrl=y.getOpenModernEntityDashboardUrl=y.getNewModernEntityDashboardUrl=y.getNewModernDashboardUrl=y.getOpenModernDashboardUrl=y.getDashboardDesignerUrl=y.getAppModuleDesignerUrl=y.privilegesQueryUrls=y.xrmApiUrl=y.getPlayAppModuleUrl=y.getCrmAdminSecurityUsersUrl=y.getCrmAdminSecurityRolesUrl=y.getCrmMyAppsUrl=y.getCrmAppDesignerUrl=y.getCrmDevResourcesUrl=y.getCrmAllPublishersUrl=y.getCrmAllSolutionsUrl=y.getSolutionPublisherUrl=y.getExportTranslationFileName=y.getExportSolutionTranslationUrl=y.getImportSolutionTranslationUrl=y.getShowSolutionDependenciesUrl=y.getShowComponentDependenciesUrl=y.cdsServiceUrl=y.ODATA_NEXT_LINK=y.ODATA_MAX_PAGE_SIZE=void 0;y.retrieveOrganizationResources=y.getUCIEntityRecordEditUrl=y.getUCIEntityRecordBaseUrl=y.getBusinessRuleDesignerUri=y.retrieveUnpublishedSuffix=y.getSavePowerSettingUri=y.getPowerSettingUri=y.getPowerSettingsUri=y.RetrievePlatform=y.getAppSettingOverrideUri=y.AppSettingOverrideName=y.getOrgSettingOverrideUri=y.OrgSettingOverrideName=y.getSettingDefinitionsUri=y.retrieveFeatureControlSettingsByNamespaceUrl=y.retrieveDeploymentPipelineConfigAppUrl=y.SPNPrincipalIdUrl=y.retrieveDeploymentEnvironmentInfoUrl=y.devSolutionInfoUrl=y.deployOperationStatusUrl=y.getAIGeneratedDeploymentNotesUrl=y.deploymentStageRunUrl=y.validatePackageAsyncUrl=y.deployPackageAsyncUrl=y.updateDeploymentStageRunUrl=y.createDeploymentStageRunUrl=y.retrieveDeploymentStagesUrl=y.retrievePipelinesUrl=y.retrieveDeploymentPipelineInfoUrl=y.getDeploymentStageRunsUrl=y.appDeploymentUrls=y.getProvisionLanguageUrl=y.getSolutionQueryUrl=y.getSolutionsByUniqueNameQueryUrl=y.solutionsQueryUrl=y.getDependentComponentsWithMetadataQueryUrl=void 0;var mh=fh();y.ODATA_MAX_PAGE_SIZE="odata.maxpagesize";y.ODATA_NEXT_LINK="@odata.nextLink";y.cdsServiceUrl="https://cds-org/";var xa;(function(e){e.AllSolutions="11",e.AllPublishers="10",e.DevResources="05"})(xa||(xa={}));function $P(e,t,r,n){return`${e}tools/dependency/dependencyviewdialog.aspx?appSolutionId=%7b${t}%7d&dType=1&objectid=%7b${r}%7d&objecttype=${n}&operationtype=showdependency`}y.getShowComponentDependenciesUrl=$P;function qP(e,t){let r=`dType=1&isproactivecheck=true&objecttype=7100&operationtype=dependenciesforuninstall&objectid=${t}`;return`${e}tools/dependency/dependencyviewdialog.aspx?${r}`}y.getShowSolutionDependenciesUrl=qP;function VP(e,t){return`${e}tools/muiProvisioning/Dialogs/LangTranslationsImport.aspx?dType=1&appSolutionId=${t}`}y.getImportSolutionTranslationUrl=VP;function GP(e,t){return`${e}_grid/cmds/dlg_exportsolution.aspx?command=exporttranslation&appSolutionId=${t}`}y.getExportSolutionTranslationUrl=GP;function zP(e,t){return e!==void 0&&t!==void 0&&`CrmTranslations_${e}_${t.replace(/[.]/g,"_")}.zip`||""}y.getExportTranslationFileName=zP;function WP(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`}y.getSolutionPublisherUrl=WP;function Ac(e,t){return`${e}tools/systemcustomization/systemCustomization.aspx?pid=${t}`}function jP(e){return Ac(e,xa.AllSolutions)}y.getCrmAllSolutionsUrl=jP;function HP(e){return Ac(e,xa.AllPublishers)}y.getCrmAllPublishersUrl=HP;function QP(e){return Ac(e,xa.DevResources)}y.getCrmDevResourcesUrl=QP;function JP(e,t=mh.crmBapSolutionId){return`${e}designer/app/${t}#/CreateNewApp`}y.getCrmAppDesignerUrl=JP;function XP(e){return`${e}apps`}y.getCrmMyAppsUrl=XP;function KP(e){return hh(e,"role")+"&forceUCI=0"}y.getCrmAdminSecurityRolesUrl=KP;function YP(e){return`${hh(e,"systemuser")}&forceclassic=1`}y.getCrmAdminSecurityUsersUrl=YP;function hh(e,t){return`${e}main.aspx?pagetype=entitylist&etn=${t}`}function ZP(e,t){return`${e}main.aspx?appid=${t}`}y.getPlayAppModuleUrl=ZP;y.xrmApiUrl="api/data/v9.0";y.privilegesQueryUrls={systemUserInfo:e=>`${e}${y.xrmApiUrl}/WhoAmI`,userPrivileges:(e,t)=>`${e}${y.xrmApiUrl}/systemusers(${t})/Microsoft.Dynamics.CRM.RetrieveUserPrivileges`,systemPrivileges:e=>`${e}${y.xrmApiUrl}/privileges/Microsoft.Dynamics.CRM.RetrievePrivilegeSet`};function eT(e,t,r=mh.crmBapSolutionId){return`${e}designer/app/${r}/${t}/AppDesignerCanvas/${t}`}y.getAppModuleDesignerUrl=eT;function tT(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${r}%7d&extraqs=%26formId%3d%7b${t}%7d%26dashboardType%3d1030&pagetype=${`${n?"ic":""}dashboardeditor`}`}y.getDashboardDesignerUrl=tT;function rT(e,t,r){return`/e/${e}/s/${t}/dashboard/${r}`}y.getOpenModernDashboardUrl=rT;function nT(e,t,r){let n=r!==void 0?r.toString():void 0;return`/e/${e}/s/${t}/dashboard/new${n?`/${n}`:""}`}y.getNewModernDashboardUrl=nT;function iT(e,t,r,n){let i=n!==void 0?n.toString():void 0;return`/e/${e}/s/${t}/n/${r}/dashboard/new${i?`/${i}`:""}`}y.getNewModernEntityDashboardUrl=iT;function aT(e,t,r,n){return`/e/${e}/s/${t}/n/${r}/dashboard/${n}`}y.getOpenModernEntityDashboardUrl=aT;function oT(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${t}%7d&extraqs=etc=${r||""}`+(n?`%26id=${n}`:"")+"&pagetype=vizdesigner"}y.getChartDesignerUrl=oT;function sT(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}y.getProcessDesignerUrl=sT;function lT(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}y.getProcessShareUrl=lT;function uT(e,t){return`${e}Tools/ProcessControl/UnifiedProcessDesigner.aspx?id=${t}`}y.getBusinessProcessFlowDesignerUrl=uT;function cT(e,t,r){return`${e}CRMReports/reportproperty.aspx?appSolutionId=%7b${r}%7d&disablePersonal=true&id=%7b${t}%7d`}y.getReportDesignerUrl=cT;function dT(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`}y.getWebResourceDesignerUrl=dT;function pT(e,t){return`${e}WebResources/${t}`}y.getWebResourceFileUrl=pT;function fT(e,t,r){return`${e}designer/sitemap/${r}/${t}/SiteMapHome/${t}`}y.getSiteMapDesignerUrl=fT;function mT(e,t,r){return`${e}connections/connectionroles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}y.getConnectionRoleDesignerUrl=mT;function hT(e,t,r){return`${e}tools/emailtemplateeditor/emailtemplateeditor.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}y.getEmailTemplateDesignerUrl=hT;function gT(e,t,r){return`${e}tools/mailmerge/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}y.getMailMergeTemplateDesignerUrl=gT;function vT(e,t,r){return`${e}biz/roles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}y.getSecurityRoleDesignerUrl=vT;function yT(e,t,r){return`${e}biz/fieldsecurityprofiles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}y.getFieldSecurityProfileDesignerUrl=yT;function bT(e,t,r){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?_CreateFromId=%7b${t}%7d&_CreateFromType=7100&appSolutionId=%7b${t}%7d&id=%7b${r}%7d`}y.getArticleTemplateUrl=bT;function wT(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}`}y.getEnableSecurityRolesUrl=wT;function AT(e){return`${e}tools/publisher/edit.aspx`}y.getCreateNewPublisherUrl=AT;function CT(e,t){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?appSolutionId=${t}`}y.getCreateNewArticleTemplateUrl=CT;y.solutionComponentDefinitionsQueryUrl="api/data/v9.0/solutioncomponentdefinitions";y.entityDefinitionsQueryUrl="api/data/v9.0/EntityDefinitions?$select=EntitySetName,DisplayName,LogicalName&$filter=";y.workflowsQueryUrl="api/data/v9.0/workflows";y.chartsQueryUrl="/api/data/v9.0/savedqueryvisualizations";y.solutionComponentConfigurationsQueryUrl="/api/data/v9.1/solutioncomponentconfigurations?$filter=isdisplayable eq true&$select=name";y.solutionComponentSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentsummaries";y.solutionComponentCountSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentcountsummaries";function ST(e,t){return`${y.xrmApiUrl}/RetrieveRequiredComponents(ObjectId=${e},ComponentType=${t})`}y.getRequiredComponentsQueryUrl=ST;function NT(e,t){return`${y.cdsServiceUrl}${y.xrmApiUrl}/RetrieveDependentComponentsWithMetadata(ObjectId=${e},ComponentType=${t})`}y.getDependentComponentsWithMetadataQueryUrl=NT;y.solutionsQueryUrl="/api/data/v9.0/solutions?$expand=publisherid&$filter=(isvisible eq true)";function ET(e){return`/api/data/v9.0/solutions?$expand=publisherid&$filter=(uniquename eq '${e}')`}y.getSolutionsByUniqueNameQueryUrl=ET;function DT(e){return`/api/data/v9.0/solutions(${e})?$expand=publisherid`}y.getSolutionQueryUrl=DT;function IT(e){return`${e}api/data/v9.1/ProvisionLanguageForUser`}y.getProvisionLanguageUrl=IT;y.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 _T(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&$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`}v.getDeploymentStageRunsUrl=SI;function DI(e,t,r){return`/api/data/v9.1/RetrieveDeploymentPipelineInfo(DeploymentPipelineId=${e},SourceEnvironmentId='${t}',ArtifactName='${r}')`}v.retrieveDeploymentPipelineInfoUrl=DI;function EI(e){return`/api/data/v9.0/deploymentenvironments+ &$orderby=starttime desc`}y.getDeploymentStageRunsUrl=_T;function PT(e,t,r){return`/api/data/v9.1/RetrieveDeploymentPipelineInfo(DeploymentPipelineId=${e},SourceEnvironmentId='${t}',ArtifactName='${r}')`}y.retrieveDeploymentPipelineInfoUrl=PT;function TT(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}')`}v.retrievePipelinesUrl=EI;function II(e){return`/api/data/v9.0/deploymentstages+ &$filter=(environmentid eq '${e}')`}y.retrievePipelinesUrl=TT;function OT(e){return`/api/data/v9.0/deploymentstages?$filter=(_deploymentpipelineid_value eq ${e})&$select=name,description,deploymentstageid,_previousdeploymentstageid_value- &$expand=targetdeploymentenvironmentid($select=deploymentenvironmentid,environmentid,name)`}v.retrieveDeploymentStagesUrl=II;function _I(){return"/api/data/v9.0/deploymentstageruns?$select=deploymentstagerunid"}v.createDeploymentStageRunUrl=_I;function PI(e){return`/api/data/v9.0/deploymentstageruns(${e})`}v.updateDeploymentStageRunUrl=PI;function OI(){return"/api/data/v9.0/DeployPackageAsync"}v.deployPackageAsyncUrl=OI;function TI(){return"/api/data/v9.0/ValidatePackageAsync"}v.validatePackageAsyncUrl=TI;function RI(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)":""}`}v.deploymentStageRunUrl=RI;function FI(e){return`/api/data/v9.0/deploymentstageruns(${e})- ?$select=aigenerateddeploymentnotes,deploymentstagerunid`}v.getAIGeneratedDeploymentNotesUrl=FI;function xI(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)`}y.retrieveDeploymentStagesUrl=OT;function xT(){return"/api/data/v9.0/deploymentstageruns?$select=deploymentstagerunid"}y.createDeploymentStageRunUrl=xT;function RT(e){return`/api/data/v9.0/deploymentstageruns(${e})`}y.updateDeploymentStageRunUrl=RT;function LT(){return"/api/data/v9.0/DeployPackageAsync"}y.deployPackageAsyncUrl=LT;function FT(){return"/api/data/v9.0/ValidatePackageAsync"}y.validatePackageAsyncUrl=FT;function kT(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)":""}`}y.deploymentStageRunUrl=kT;function MT(e){return`/api/data/v9.0/deploymentstageruns(${e})+ ?$select=aigenerateddeploymentnotes,deploymentstagerunid`}y.getAIGeneratedDeploymentNotesUrl=MT;function UT(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`}v.deployOperationStatusUrl=xI;function LI(e){return`/api/data/v9.0/solutions(${e})- ?$select=solutionid,uniquename,version`}v.devSolutionInfoUrl=LI;function MI(e){return`/api/data/v9.0/deploymentenvironments+ &$select=_deploymentstageid_value,deploymentstagerunid,stagerunstatus,operation,operationstatus,suboperation,artifactname`}y.deployOperationStatusUrl=UT;function BT(e){return`/api/data/v9.0/solutions(${e})+ ?$select=solutionid,uniquename,version`}y.devSolutionInfoUrl=BT;function $T(e){return`/api/data/v9.0/deploymentenvironments?$select=deploymentenvironmentid,environmentid,environmenttype,name- &$filter=(environmentid eq '${e}')`}v.retrieveDeploymentEnvironmentInfoUrl=MI;var UI=e=>`/api/data/v9.0/systemusers+ &$filter=(environmentid eq '${e}')`}y.retrieveDeploymentEnvironmentInfoUrl=$T;var qT=e=>`/api/data/v9.0/systemusers?$select=azureactivedirectoryobjectid- &$filter=(applicationid eq '${e}')`;v.SPNPrincipalIdUrl=UI;function BI(){return"/api/data/v9.0/appmodules?$filter=(uniquename eq 'AppDeploymentConfiguration')"}v.retrieveDeploymentPipelineConfigAppUrl=BI;v.retrieveFeatureControlSettingsByNamespaceUrl="/api/data/v9.1/RetrieveFeatureControlSettingsByNamespace";function kI(e){return`/api/data/v9.0/settingdefinitions${e}`}v.getSettingDefinitionsUri=kI;v.OrgSettingOverrideName="organizationsettings";function qI(e,t=!1){let r=`/api/data/v9.0/${v.OrgSettingOverrideName}${e}`;return t?`${v.cdsServiceUrl}${r}`:r}v.getOrgSettingOverrideUri=qI;v.AppSettingOverrideName="appsettings";function $I(e,t=!1){let r=`/api/data/v9.0/${v.AppSettingOverrideName}${e}`;return t?`${v.cdsServiceUrl.replace("/$","")}${r}`:r}v.getAppSettingOverrideUri=$I;var Fi;(function(e){e[e.All=0]="All",e[e.IsPlatformOnly=1]="IsPlatformOnly",e[e.NotPlatformOnly=2]="NotPlatformOnly"})(Fi||(v.RetrievePlatform=Fi={}));function VI(e,t,r,n=Fi.All,i=!1){let a=[];e&&a.push(`AppUniqueName='${e}'`),t!=null&&a.push(`ReleaseLevel=${t}`),r&&a.push(`RetrieveHiddenSettings=${r}`),n!==Fi.All&&a.push(`RetrievePlatformSettings=${n===Fi.IsPlatformOnly?1:0}`);let o="/api/data/v9.0/RetrieveUnpublishedOverridableSettingsInfo";return a.length&&(o=`${o}(${a.join(",")})`),i?`${v.cdsServiceUrl}${o}`:o}v.getPowerSettingsUri=VI;function GI(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?`${v.cdsServiceUrl}${a}`:a}v.getPowerSettingUri=GI;function zI(e=!1){let t="/api/data/v9.0/SaveSettingValue()";return e?`${v.cdsServiceUrl}${t}`:t}v.getSavePowerSettingUri=zI;v.retrieveUnpublishedSuffix="Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()";function WI(e){return`tools/systemcustomization/businessrules/businessRulesDesigner.aspx?BRlaunchpoint=BRGrid&appSolutionId={${e}}`}v.getBusinessRuleDesignerUri=WI;function hf({environmentInstanceUrl:e,entityLogicalName:t}){return e&&t?`${e}main.aspx?cmdbar=true&forceUCI=1&navbar=off&newWindow=true&pageType=entityRecord&etn=${t}`:void 0}v.getUCIEntityRecordBaseUrl=hf;function jI({baseUrl:e,environmentInstanceUrl:t,entityLogicalName:r,recordId:n}){let i=e||hf({environmentInstanceUrl:t,entityLogicalName:r});return i&&n?`${i}&id=${n}`:void 0}v.getUCIEntityRecordEditUrl=jI;v.retrieveOrganizationResources=`${v.cdsServiceUrl}api/data/v9.0/RetrieveOrganizationResources`});var gf=m(bo=>{"use strict";Object.defineProperty(bo,"__esModule",{value:!0});bo.DataverseClient=void 0;var HI=Hl(),Sn=be(),Ql=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}/${HI.xrmApiUrl}${n}`}async send(t,r){try{return await r()}catch(n){throw n instanceof Sn.SdkError?n:new Sn.ConnectionError(t,0,n instanceof Error?n.message:String(n),n)}}get(t,r){let n=this.apiUrl(t);return this.send(n,()=>this.httpClient.get(n,r))}getAbsolute(t,r){return this.assertSameOrigin(t),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 Sn.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${t}'`)}if(r.protocol!==n.protocol||r.host!==n.host)throw new Sn.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"}postBatch(t,r,n){if(!this.httpClient.postRaw)throw new Sn.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)))}put(t,r,n){if(!this.httpClient.put)throw new Sn.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)))}};bo.DataverseClient=Ql});var ce=m(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.odataQuery=Te.normalizeGuid=Te.createSafeXmlElement=Te.assertODataName=Te.assertXmlName=Te.xmlText=Te.odataPathLiteral=Te.odataLiteral=void 0;var Xl=be();function vf(e){return String(e??"").replace(/'/g,"''")}Te.odataLiteral=vf;function JI(e){return encodeURIComponent(vf(e))}Te.odataPathLiteral=JI;function QI(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}Te.xmlText=QI;function bf(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 Xl.InvalidArgumentError(`${t} must be a valid XML element name (got '${e}')`);return e}Te.assertXmlName=bf;function XI(e,t){let r=String(e??"");if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new Xl.InvalidArgumentError(`${t} must be a valid OData identifier (letters, digits, underscore): got '${e}'`);return e}Te.assertODataName=XI;function KI(e,t,r){return e.createElement(bf(t,r))}Te.createSafeXmlElement=KI;var YI=/^[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 ZI(e,t){let r=String(e??""),n=r.length===38&&r.startsWith("{")&&r.endsWith("}")?r.slice(1,-1):r;if(!YI.test(n))throw new Xl.InvalidArgumentError(`${t} must be a valid GUID (got '${e}')`);return n.toLowerCase()}Te.normalizeGuid=ZI;function e1(e){let t=[];for(let[r,n]of e)n!=null&&n!==""&&t.push(`${r}=${encodeURIComponent(String(n))}`);return t.length>0?`?${t.join("&")}`:""}Te.odataQuery=e1});var Ve=m(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.nowIso=Ne.isAlreadyDeleted=Ne.deleteRecord=Ne.ensureSuccess=Ne.requireCreatedId=Ne.readCreatedId=Ne.readEtag=Ne.VERSION_CONFLICT_CODE=void 0;var yo=be(),Kl=ce();Ne.VERSION_CONFLICT_CODE="VERSION_CONFLICT";function t1(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}Ne.readEtag=t1;function yf(e,t){var r;let n=e.body;if(n&&typeof n[t]=="string")return(0,Kl.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,Kl.normalizeGuid)(o[1],t)}return null}Ne.readCreatedId=yf;function r1(e,t,r){let n=yf(e,t);if(!n)throw new yo.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`);return n}Ne.requireCreatedId=r1;function Cf(e,t){if(e.status===412)throw new yo.SdkError(Ne.VERSION_CONFLICT_CODE,`Version conflict (412) from ${t}`);if(e.status<200||e.status>=300)throw new yo.ConnectionError(t,e.status,n1(e.body),e.body);return e}Ne.ensureSuccess=Cf;function n1(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 i1(e,t,r){let n=(0,Kl.normalizeGuid)(r,"id"),i=`/${t}(${n})`;Cf(await e.delete(i),e.apiUrl(i))}Ne.deleteRecord=i1;function a1(e){return e instanceof yo.ConnectionError&&e.statusCode===404}Ne.isAlreadyDeleted=a1;function o1(){return new Date().toISOString()}Ne.nowIso=o1});var Af=m(Pr=>{"use strict";Object.defineProperty(Pr,"__esModule",{value:!0});Pr.findColumns=Pr.findTables=Pr.fetchEntityMetadataFromApi=void 0;var Yl=Ve(),qt=ce();function Li(e){var t,r;return(r=(t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)!==null&&r!==void 0?r:""}async function Dn(e,t){var r,n;let i=await e.get(t);return i.status<200||i.status>=300?[]:(n=(r=i.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]}function _r(e){return`/EntityDefinitions(LogicalName='${(0,qt.odataLiteral)(e)}')`}async function s1(e,t,r){let n=await Dn(e,`${_r(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata${(0,qt.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 l1(e,t,r){var n;let i=await Dn(e,`${_r(t)}/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata${(0,qt.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:Li(s.Label)}}))}}async function u1(e,t,r){let n=await Dn(e,`${_r(t)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata${(0,qt.odataQuery)([["$select","LogicalName,Targets"]])}`);for(let i of n){let a=r.get(i.LogicalName);a&&i.Targets&&(a.targets=i.Targets)}}async function c1(e,t){var r,n,i,a;let o=[],s=await Dn(e,`${_r(t)}/OneToManyRelationships${(0,qt.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 Dn(e,`${_r(t)}/ManyToOneRelationships${(0,qt.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 Dn(e,`${_r(t)}/ManyToManyRelationships${(0,qt.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 d1(e,t){var r,n,i,a,o;let s=`${_r(t)}`+(0,qt.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,EntitySetName,IsCustomEntity,PrimaryNameAttribute,PrimaryIdAttribute"],["$expand","Attributes($select=LogicalName,DisplayName,AttributeType,IsCustomAttribute)"]]),u=(0,Yl.ensureSuccess)(await e.get(s),e.apiUrl(s)).body,c=((r=u.Attributes)!==null&&r!==void 0?r:[]).map(h=>{var b;return{logicalName:h.LogicalName,displayName:Li(h.DisplayName),attributeType:(b=h.AttributeType)!==null&&b!==void 0?b:"Unknown",isCustomAttribute:!!h.IsCustomAttribute}}),d=new Map(c.map(h=>[h.logicalName,h])),[,,,f]=await Promise.all([s1(e,t,d),l1(e,t,d),u1(e,t,d),c1(e,t)]);return{logicalName:u.LogicalName,schemaName:(n=u.SchemaName)!==null&&n!==void 0?n:u.LogicalName,displayName:Li(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:"",isCustomEntity:!!u.IsCustomEntity,attributes:c,relationships:f}}Pr.fetchEntityMetadataFromApi=d1;async function p1(e,t,r){var n,i;let a=`/EntityDefinitions${(0,qt.odataQuery)([["$select","LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity"]])}`,s=(i=(n=(0,Yl.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,f;return{logicalName:c.LogicalName,schemaName:(d=c.SchemaName)!==null&&d!==void 0?d:c.LogicalName,displayName:Li(c.DisplayName),entitySetName:(f=c.EntitySetName)!==null&&f!==void 0?f:"",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}Pr.findTables=p1;async function f1(e,t,r,n){var i,a;let o=`${_r(t)}/Attributes`+(0,qt.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute"]]),l=(a=(i=(0,Yl.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 f,h;return{logicalName:d.LogicalName,schemaName:(f=d.SchemaName)!==null&&f!==void 0?f:d.LogicalName,displayName:Li(d.DisplayName),attributeType:(h=d.AttributeType)!==null&&h!==void 0?h:"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}Pr.findColumns=f1});var Co=m(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.updateTable=J.deleteAlternateKey=J.createAlternateKey=J.deleteGlobalOptionSet=J.createGlobalOptionSet=J.deleteRelationship=J.deleteColumn=J.updateColumn=J.deleteTable=J.createRelationship=J.insertStatusValue=J.createCustomerColumn=J.createColumn=J.createTable=J.resolveEntitySetName=void 0;var se=Ve(),X=ce(),Ot=be(),m1={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"},or=1033;function ge(e,t){return{"@odata.type":"Microsoft.Dynamics.CRM.Label",LocalizedLabels:[{"@odata.type":"Microsoft.Dynamics.CRM.LocalizedLabel",Label:e,LanguageCode:t}]}}function Mi(e){return{Value:e,CanBeChanged:!0,ManagedPropertyLogicalName:"canmodifyrequirementlevelsettings"}}function eu(e){let t=e.indexOf("_");return t>0?e.slice(0,t):e}function wf(e,t,r){let n=e[t];n&&typeof n=="object"?n.Value=r:e[t]={Value:r}}function Ui(e){let t=(0,se.readCreatedId)(e,"MetadataId");if(!t)throw new Ot.InvalidArgumentError("Dataverse did not return a MetadataId for the created metadata component");return t}function h1(e,t,r){var n,i,a,o,s,l,u,c,d,f,h,b,w,N,I,R,F,M,W,B,j,k;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:"None",MinValue:(o=t.minValue)!==null&&o!==void 0?o:-2147483648,MaxValue:(s=t.maxValue)!==null&&s!==void 0?s: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:(l=t.precision)!==null&&l!==void 0?l:2,MinValue:(u=t.minValue)!==null&&u!==void 0?u:-1e11,MaxValue:(c=t.maxValue)!==null&&c!==void 0?c:1e11};case"decimal":return{"@odata.type":"Microsoft.Dynamics.CRM.DecimalAttributeMetadata",AttributeType:"Decimal",AttributeTypeName:{Value:"DecimalType"},Precision:(d=t.precision)!==null&&d!==void 0?d:2,MinValue:(f=t.minValue)!==null&&f!==void 0?f:-1e11,MaxValue:(h=t.maxValue)!==null&&h!==void 0?h:1e11};case"money":return{"@odata.type":"Microsoft.Dynamics.CRM.MoneyAttributeMetadata",AttributeType:"Money",AttributeTypeName:{Value:"MoneyType"},Precision:(b=t.precision)!==null&&b!==void 0?b:2,PrecisionSource:2,MinValue:(w=t.minValue)!==null&&w!==void 0?w:0,MaxValue:(N=t.maxValue)!==null&&N!==void 0?N:1e9};case"boolean":return{"@odata.type":"Microsoft.Dynamics.CRM.BooleanAttributeMetadata",AttributeType:"Boolean",AttributeTypeName:{Value:"BooleanType"},DefaultValue:!1,OptionSet:{"@odata.type":"Microsoft.Dynamics.CRM.BooleanOptionSetMetadata",TrueOption:{Value:1,Label:ge((I=t.trueLabel)!==null&&I!==void 0?I:"Yes",r)},FalseOption:{Value:0,Label:ge((R=t.falseLabel)!==null&&R!==void 0?R:"No",r)}}};case"dateTime":return{"@odata.type":"Microsoft.Dynamics.CRM.DateTimeAttributeMetadata",AttributeType:"DateTime",AttributeTypeName:{Value:"DateTimeType"},Format:(F=t.dateFormat)!==null&&F!==void 0?F:"DateAndTime"};case"choice":return Nf(t,r,!1);case"multiChoice":return Nf(t,r,!0);case"file":return{"@odata.type":"Microsoft.Dynamics.CRM.FileAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"FileType"},MaxSizeInKB:(M=t.maxSizeKb)!==null&&M!==void 0?M:10240};case"image":return{"@odata.type":"Microsoft.Dynamics.CRM.ImageAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"ImageType"},IsPrimaryImage:(W=t.isPrimaryImage)!==null&&W!==void 0?W:!1,MaxSizeInKB:(B=t.maxSizeKb)!==null&&B!==void 0?B:10240};case"autonumber":return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},FormatName:{Value:"Text"},MaxLength:(j=t.maxLength)!==null&&j!==void 0?j:100,AutoNumberFormat:(k=t.autoNumberFormat)!==null&&k!==void 0?k:""};default:throw new Ot.InvalidArgumentError(`unsupported column type '${String(e)}'`)}}function Nf(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,X.normalizeGuid)(e.globalChoiceMetadataId,"globalChoiceMetadataId")})`,i;if(!e.options||e.options.length===0)throw new Ot.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:ge(a.label,t)}))},i}var Zl=new WeakMap;async function g1(e,t){var r,n;let i=(r=Zl.get(e))===null||r===void 0?void 0:r.get(t);if(i)return i;let a=`/EntityDefinitions(LogicalName='${(0,X.odataLiteral)(t)}')${(0,X.odataQuery)([["$select","EntitySetName"]])}`,s=(n=(0,se.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.EntitySetName;if(!s)throw new Ot.InvalidArgumentError(`could not resolve EntitySetName for '${t}'`);(0,X.assertODataName)(s,`server-derived EntitySetName for '${t}'`);let l=Zl.get(e);return l||(l=new Map,Zl.set(e,l)),l.set(t,s),s}J.resolveEntitySetName=g1;async function v1(e,t){var r,n,i,a,o,s,l,u,c,d,f,h;let b=(r=t.languageCode)!==null&&r!==void 0?r:or,w=eu(t.schemaName),N=(n=t.primaryColumnSchemaName)!==null&&n!==void 0?n:`${w}_Name`,I={"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},SchemaName:N,RequiredLevel:Mi("None"),MaxLength:(i=t.primaryColumnMaxLength)!==null&&i!==void 0?i:100,FormatName:{Value:"Text"},DisplayName:ge((a=t.primaryColumnDisplayName)!==null&&a!==void 0?a:"Name",b),IsPrimaryName:!0};t.primaryColumnAutoNumberFormat&&(I.AutoNumberFormat=t.primaryColumnAutoNumberFormat);let R={"@odata.type":"Microsoft.Dynamics.CRM.EntityMetadata",SchemaName:t.schemaName,DisplayName:ge(t.displayName,b),DisplayCollectionName:ge((o=t.pluralName)!==null&&o!==void 0?o:`${t.displayName}s`,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:[I]};t.description&&(R.Description=ge(t.description,b));let F="/EntityDefinitions",M=(0,se.ensureSuccess)(await e.post(F,R),e.apiUrl(F)),W=Ui(M),B=`/EntityDefinitions(${W})`+(0,X.odataQuery)([["$select","LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute"]]),k=(0,se.ensureSuccess)(await e.get(B),e.apiUrl(B)).body;return{logicalName:(c=k.LogicalName)!==null&&c!==void 0?c:t.schemaName.toLowerCase(),metadataId:W,entitySetName:(d=k.EntitySetName)!==null&&d!==void 0?d:"",primaryIdAttribute:(f=k.PrimaryIdAttribute)!==null&&f!==void 0?f:`${t.schemaName.toLowerCase()}id`,primaryNameAttribute:(h=k.PrimaryNameAttribute)!==null&&h!==void 0?h:N.toLowerCase()}}J.createTable=v1;async function b1(e,t,r){var n,i;let a=(n=r.languageCode)!==null&&n!==void 0?n:or,o={...h1(r.type,r,a),SchemaName:r.schemaName,RequiredLevel:Mi((i=r.required)!==null&&i!==void 0?i:"None"),DisplayName:ge(r.displayName,a)};r.description&&(o.Description=ge(r.description,a)),r.sourceType&&r.sourceType!=="Simple"&&(o.SourceType=r.sourceType==="Rollup"?2:1,r.formulaDefinition&&(o.FormulaDefinition=r.formulaDefinition));let s=`/EntityDefinitions(LogicalName='${(0,X.odataLiteral)(t)}')/Attributes`,l=(0,se.ensureSuccess)(await e.post(s,o),e.apiUrl(s));return{logicalName:r.schemaName.toLowerCase(),metadataId:Ui(l)}}J.createColumn=b1;async function y1(e,t,r){var n,i,a,o;let s=(n=r.languageCode)!==null&&n!==void 0?n:or,l=eu(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:ge(r.displayName,s),RequiredLevel:Mi((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,se.ensureSuccess)(await e.post("/CreateCustomerRelationships",d),e.apiUrl("/CreateCustomerRelationships")),{logicalName:r.schemaName.toLowerCase(),metadataId:""}}J.createCustomerColumn=y1;async function C1(e,t,r){var n,i,a,o,s;let l=(n=r.languageCode)!==null&&n!==void 0?n:or,u={EntityLogicalName:t,AttributeLogicalName:"statuscode",Label:ge(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,se.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)}J.insertStatusValue=C1;async function A1(e,t){var r,n,i,a,o;let s=(r=t.languageCode)!==null&&r!==void 0?r:or,l,u;if(t.type==="OneToMany"){if(!t.referencedEntity||!t.referencingEntity)throw new Ot.InvalidArgumentError("OneToMany relationship requires referencedEntity and referencingEntity");let f=(n=t.lookupSchemaName)!==null&&n!==void 0?n:`${eu(t.schemaName)}_${t.referencedEntity}Id`;u=f.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:f,RequiredLevel:Mi((i=t.lookupRequired)!==null&&i!==void 0?i:"None"),DisplayName:ge((a=t.lookupDisplayName)!==null&&a!==void 0?a:t.referencedEntity,s)}}}else{if(!t.entity1||!t.entity2)throw new Ot.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,se.ensureSuccess)(await e.post(c,l),e.apiUrl(c));return{schemaName:t.schemaName,metadataId:Ui(d),lookupLogicalName:u}}J.createRelationship=A1;async function w1(e,t){let r=`/EntityDefinitions(LogicalName='${(0,X.odataLiteral)(t)}')`;(0,se.ensureSuccess)(await e.delete(r),e.apiUrl(r))}J.deleteTable=w1;async function N1(e,t,r,n){var i,a;let o=(i=n.languageCode)!==null&&i!==void 0?i:or,s=`/EntityDefinitions(LogicalName='${(0,X.odataLiteral)(t)}')/Attributes`,l=`${s}(LogicalName='${(0,X.odataLiteral)(r)}')${(0,X.odataQuery)([["$select","MetadataId,AttributeType"]])}`,c=(0,se.ensureSuccess)(await e.get(l),e.apiUrl(l)).body,d=m1[(a=c.AttributeType)!==null&&a!==void 0?a:""];if(!c.MetadataId||!d)throw new Ot.InvalidArgumentError(`cannot update column '${r}' on '${t}' (type '${c.AttributeType}' not supported)`);let f=(0,X.normalizeGuid)(c.MetadataId,"MetadataId"),h=`${s}(${f})/${d}`,b=(0,se.ensureSuccess)(await e.get(h),e.apiUrl(h)).body;for(let N of Object.keys(b))N.startsWith("@odata.")&&delete b[N];b["@odata.type"]=d,n.displayName!==void 0&&(b.DisplayName=ge(n.displayName,o)),n.description!==void 0&&(b.Description=ge(n.description,o)),n.required!==void 0&&(b.RequiredLevel=Mi(n.required)),n.maxLength!==void 0&&(b.MaxLength=n.maxLength),n.autoNumberFormat!==void 0&&(b.AutoNumberFormat=n.autoNumberFormat);let w=`${s}(${f})`;(0,se.ensureSuccess)(await e.put(w,b,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(w))}J.updateColumn=N1;async function S1(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,X.odataLiteral)(t)}')/Attributes`,a=`${i}(LogicalName='${(0,X.odataLiteral)(r)}')${(0,X.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,se.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new Ot.InvalidArgumentError(`column '${r}' not found on '${t}'`);let l=`${i}(${(0,X.normalizeGuid)(s,"MetadataId")})`;(0,se.ensureSuccess)(await e.delete(l),e.apiUrl(l))}J.deleteColumn=S1;async function D1(e,t){var r,n,i;let a=`/RelationshipDefinitions${(0,X.odataQuery)([["$filter",`SchemaName eq '${(0,X.odataLiteral)(t)}'`],["$select","MetadataId"]])}`,s=(i=(n=(r=(0,se.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 Ot.InvalidArgumentError(`relationship '${t}' not found`);let l=`/RelationshipDefinitions(${(0,X.normalizeGuid)(s,"MetadataId")})`;(0,se.ensureSuccess)(await e.delete(l),e.apiUrl(l))}J.deleteRelationship=D1;async function Sf(e,t){var r;let n=`/GlobalOptionSetDefinitions(Name='${(0,X.odataPathLiteral)(t)}')${(0,X.odataQuery)([["$select","MetadataId"]])}`,i=await e.get(n);if(i.status===404)return;let o=(r=(0,se.ensureSuccess)(i,e.apiUrl(n)).body)===null||r===void 0?void 0:r.MetadataId;return o?(0,X.normalizeGuid)(o,"MetadataId"):void 0}async function E1(e,t){var r;let n=t.name.toLowerCase(),i=await Sf(e,n);if(i)return{name:n,metadataId:i};let a=(r=t.languageCode)!==null&&r!==void 0?r:or,o={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",Name:n,DisplayName:ge(t.displayName,a),IsGlobal:!0,OptionSetType:"Picklist",Options:t.options.map(l=>({Value:l.value,Label:ge(l.label,a)}))};t.description&&(o.Description=ge(t.description,a));let s="/GlobalOptionSetDefinitions";try{let l=(0,se.ensureSuccess)(await e.post(s,o),e.apiUrl(s));return{name:n,metadataId:Ui(l)}}catch(l){let u;try{u=await Sf(e,n)}catch{u=void 0}if(u)return{name:n,metadataId:u};throw l}}J.createGlobalOptionSet=E1;async function I1(e,t){let r=`/GlobalOptionSetDefinitions(Name='${(0,X.odataLiteral)(t.toLowerCase())}')`;(0,se.ensureSuccess)(await e.delete(r),e.apiUrl(r))}J.deleteGlobalOptionSet=I1;async function _1(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:or,a={"@odata.type":"Microsoft.Dynamics.CRM.EntityKeyMetadata",SchemaName:r.schemaName,DisplayName:ge(r.displayName,i),KeyAttributes:r.keyAttributes},o=`/EntityDefinitions(LogicalName='${(0,X.odataLiteral)(t)}')/Keys`,s=(0,se.ensureSuccess)(await e.post(o,a),e.apiUrl(o));return{logicalName:r.schemaName.toLowerCase(),metadataId:Ui(s)}}J.createAlternateKey=_1;async function P1(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,X.odataLiteral)(t)}')/Keys`,a=`${i}(LogicalName='${(0,X.odataLiteral)(r.toLowerCase())}')${(0,X.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,se.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new Ot.InvalidArgumentError(`alternate key '${r}' not found on '${t}'`);let l=`${i}(${(0,X.normalizeGuid)(s,"MetadataId")})`;(0,se.ensureSuccess)(await e.delete(l),e.apiUrl(l))}J.deleteAlternateKey=P1;async function O1(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:or,a=`/EntityDefinitions(LogicalName='${(0,X.odataLiteral)(t)}')`,s=(0,se.ensureSuccess)(await e.get(a),e.apiUrl(a)).body,l=s.MetadataId;if(!l)throw new Ot.InvalidArgumentError(`table '${t}' not found`);let u=(0,X.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=ge(r.displayName,i)),r.pluralName!==void 0&&(s.DisplayCollectionName=ge(r.pluralName,i)),r.description!==void 0&&(s.Description=ge(r.description,i)),r.auditEnabled!==void 0&&wf(s,"IsAuditEnabled",r.auditEnabled),r.duplicateDetectionEnabled!==void 0&&wf(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,se.ensureSuccess)(await e.put(c,s,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(c))}J.updateTable=O1});var Bi=m(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.disassociateRecords=me.associateRecords=me.createRecordsBulk=me.upsertRecord=me.queryAllRecords=me.queryRecords=me.getRecord=me.deleteRecord=me.updateRecord=me.createRecord=void 0;var vt=Ve(),Ge=ce(),Hr=be(),$t=Co();function Ao(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 T1(e,t,r){let i=`/${await(0,$t.resolveEntitySetName)(e,t)}`,a=(0,vt.ensureSuccess)(await e.post(i,Ao(r)),e.apiUrl(i)),o=(0,vt.readCreatedId)(a,`${t}id`);if(!o)throw new Hr.InvalidArgumentError(`Dataverse did not return an id for the created '${t}' row`);return{id:o,entityType:t}}me.createRecord=T1;async function R1(e,t,r,n){let i=(0,Ge.normalizeGuid)(r,"id"),o=`/${await(0,$t.resolveEntitySetName)(e,t)}(${i})`;(0,vt.ensureSuccess)(await e.patch(o,Ao(n)),e.apiUrl(o))}me.updateRecord=R1;async function F1(e,t,r){let n=(0,Ge.normalizeGuid)(r,"id"),a=`/${await(0,$t.resolveEntitySetName)(e,t)}(${n})`;(0,vt.ensureSuccess)(await e.delete(a),e.apiUrl(a))}me.deleteRecord=F1;async function x1(e,t,r,n){var i;let a=(0,Ge.normalizeGuid)(r,"id"),o=await(0,$t.resolveEntitySetName)(e,t),s=(0,Ge.odataQuery)([["$select",n&&n.length>0?n.join(","):void 0]]),l=`/${o}(${a})${s}`;return(i=(0,vt.ensureSuccess)(await e.get(l),e.apiUrl(l)).body)!==null&&i!==void 0?i:{}}me.getRecord=x1;function L1(e){return e?.fetchXml?(0,Ge.odataQuery)([["fetchXml",e.fetchXml]]):(0,Ge.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 Df(e,t,r){var n,i;if(r?.paginate){if(r.top!==void 0)throw new Hr.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 Hr.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,$t.resolveEntitySetName)(e,t)}${L1(r)}`,s=(0,vt.ensureSuccess)(await e.get(o),e.apiUrl(o));if(!r?.paginate)return(i=(n=s.body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[];let l=[],u=new Set,c=e.apiUrl(o);for(;;){let d=s.body,f=d?.value;if(!Array.isArray(f))throw new Hr.ConnectionError(c,s.status,`paginated query returned a malformed page \u2014 expected an OData 'value' array but got ${M1(f)}; refusing to return partial results.`);for(let b of f)l.push(b);let h=d?.["@odata.nextLink"];if(!h)break;if(typeof h!="string")throw new Hr.ConnectionError(c,s.status,`paginated query returned a non-string @odata.nextLink (${typeof h}); cannot follow it.`);if(u.has(h))throw new Hr.InvalidArgumentError(`queryRecords: aborting pagination \u2014 the server returned a repeated @odata.nextLink ('${h}'), which would loop indefinitely.`);u.add(h),c=h,s=(0,vt.ensureSuccess)(await e.getAbsolute(h),h)}return l}me.queryRecords=Df;function M1(e){return e===null?"null":e===void 0?"undefined (missing)":`a ${typeof e}`}async function U1(e,t,r){return Df(e,t,{...r,paginate:!0})}me.queryAllRecords=U1;function B1(e){if("id"in e)return`(${(0,Ge.normalizeGuid)(e.id,"id")})`;let t=typeof e.value=="string"?`'${(0,Ge.odataPathLiteral)(e.value)}'`:e.value;return`(${(0,Ge.assertODataName)(e.key,"alternate key name")}=${t})`}async function k1(e,t,r,n){let i=B1(r),o=`/${await(0,$t.resolveEntitySetName)(e,t)}${i}`,s=(0,vt.ensureSuccess)(await e.patch(o,Ao(n)),e.apiUrl(o)),l=s.status===201,u=(0,vt.readCreatedId)(s,`${t}id`);return{id:u??("id"in r?(0,Ge.normalizeGuid)(r.id,"id"):""),created:l}}me.upsertRecord=k1;async function q1(e,t,r){var n,i;if(r.length===0)return[];let a=await(0,$t.resolveEntitySetName)(e,t),o=r.map(c=>({"@odata.type":`Microsoft.Dynamics.CRM.${t}`,...Ao(c)})),s=`/${a}/Microsoft.Dynamics.CRM.CreateMultiple`,u=(i=(n=(0,vt.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 Hr.InvalidArgumentError(`CreateMultiple on '${t}' returned ${u.length} id(s) for ${r.length} row(s)`);return u}me.createRecordsBulk=q1;async function $1(e,t,r,n){let i=(0,Ge.normalizeGuid)(r,"id"),a=(0,Ge.normalizeGuid)(n.targetId,"targetId"),o=await(0,$t.resolveEntitySetName)(e,t),s=await(0,$t.resolveEntitySetName)(e,n.targetEntity),l=(0,Ge.assertODataName)(n.relationshipName,"relationshipName"),u=`/${o}(${i})/${l}/$ref`,c={"@odata.id":e.apiUrl(`/${s}(${a})`)};(0,vt.ensureSuccess)(await e.post(u,c),e.apiUrl(u))}me.associateRecords=$1;async function V1(e,t,r,n,i){let a=(0,Ge.normalizeGuid)(r,"id"),o=(0,Ge.normalizeGuid)(i,"targetId"),s=await(0,$t.resolveEntitySetName)(e,t),l=(0,Ge.assertODataName)(n,"relationshipName"),u=`/${s}(${a})/${l}(${o})/$ref`;(0,vt.ensureSuccess)(await e.delete(u),e.apiUrl(u))}me.disassociateRecords=V1});var _f=m(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.deleteWebResource=Vt.getWebResource=Vt.updateWebResource=Vt.createWebResource=void 0;var En=Ve(),ki=ce(),tu=be(),G1={html:1,css:2,js:3,xml:4,png:5,jpg:6,gif:7,xsl:9,ico:10,svg:11,resx:12};function z1(e){let t=globalThis;if(t.Buffer)return t.Buffer.from(e,"utf8").toString("base64");if(t.btoa){let r=globalThis.TextEncoder;if(r){let n=new r().encode(e),i="",a=32768;for(let o=0;o<n.length;o+=a)i+=String.fromCharCode(...n.subarray(o,o+a));return t.btoa(i)}return t.btoa(e)}throw new tu.InvalidArgumentError("no base64 encoder available; pass contentBase64 instead of content")}function Ef(e){if(e.contentBase64!==void 0)return e.contentBase64;if(e.content!==void 0)return z1(e.content)}async function If(e,t){let r=`<importexportxml><webresources><webresource>${(0,ki.xmlText)(t)}</webresource></webresources></importexportxml>`;(0,En.ensureSuccess)(await e.post("/PublishXml",{ParameterXml:r}),e.apiUrl("/PublishXml"))}async function W1(e,t){var r;let n=Ef(t);if(n===void 0)throw new tu.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:G1[t.type],content:n};t.description&&(i.description=t.description);let a=(0,En.ensureSuccess)(await e.post("/webresourceset",i),e.apiUrl("/webresourceset")),o=(0,En.readCreatedId)(a,"webresourceid");if(!o)throw new tu.InvalidArgumentError(`Dataverse did not return an id for web resource '${t.name}'`);return t.publish!==!1&&await If(e,o),{id:o,name:t.name}}Vt.createWebResource=W1;async function j1(e,t,r){let n=(0,ki.normalizeGuid)(t,"id"),i={},a=Ef(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,En.ensureSuccess)(await e.patch(o,i),e.apiUrl(o)),r.publish!==!1&&await If(e,n)}Vt.updateWebResource=j1;async function H1(e,t){var r;let i=`/webresourceset(${(0,ki.normalizeGuid)(t,"id")})${(0,ki.odataQuery)([["$select","name,displayname,webresourcetype,content,description"]])}`;return(r=(0,En.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)!==null&&r!==void 0?r:{}}Vt.getWebResource=H1;async function J1(e,t){let n=`/webresourceset(${(0,ki.normalizeGuid)(t,"id")})`;(0,En.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Vt.deleteWebResource=J1});var Pf=m(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.deleteSolution=K.importSolution=K.exportSolution=K.removeSolutionComponent=K.addSolutionComponent=K.setSolutionVersion=K.createSolution=K.createPublisher=K.getSolution=K.fetchSolutionComponents=K.SolutionComponentType=void 0;var mt=Ve(),ft=ce(),Jr=be();K.SolutionComponentType={SavedQuery:26,Workflow:29,SavedQueryVisualization:59,SystemForm:60,AppModule:80};var Q1=[K.SolutionComponentType.SavedQuery,K.SolutionComponentType.Workflow,K.SolutionComponentType.SavedQueryVisualization,K.SolutionComponentType.SystemForm,K.SolutionComponentType.AppModule];async function X1(e,t){var r;let n=(0,ft.normalizeGuid)(t,"solutionId"),i=Q1.map(l=>`msdyn_componenttype eq ${l}`).join(" or "),a=`/msdyn_solutioncomponentsummaries${(0,ft.odataQuery)([["$select","msdyn_objectid,msdyn_componenttype,msdyn_workflowcategory,msdyn_displayname,msdyn_name"],["$filter",`msdyn_solutionid eq ${n} and (${i})`]])}`,o=[],s=(0,mt.ensureSuccess)(await e.get(a),e.apiUrl(a));for(;;){let l=s.body;for(let c of(r=l?.value)!==null&&r!==void 0?r:[])o.push(c);let u=l?.["@odata.nextLink"];if(!u)break;s=(0,mt.ensureSuccess)(await e.getAbsolute(u),u)}return o.filter(l=>typeof l.msdyn_objectid=="string").map(l=>({objectId:l.msdyn_objectid,componentType:Number(l.msdyn_componenttype),workflowCategory:l.msdyn_workflowcategory==null?void 0:Number(l.msdyn_workflowcategory),displayName:l.msdyn_displayname,name:l.msdyn_name}))}K.fetchSolutionComponents=X1;function K1(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 Y1(e,t){var r,n,i,a,o,s,l,u,c,d;let f=String(t??"").trim();if(!f)throw new Jr.InvalidArgumentError("getSolution: a solution unique name or id is required.");let h=K1(f)?`solutionid eq ${(0,ft.normalizeGuid)(f,"solutionId")}`:`uniquename eq '${(0,ft.odataLiteral)(f)}'`,b=`/solutions${(0,ft.odataQuery)([["$select","solutionid,uniquename,friendlyname,version,ismanaged"],["$expand","publisherid($select=publisherid,uniquename,customizationprefix,customizationoptionvalueprefix)"],["$filter",h]])}`,I=((n=(r=(0,mt.ensureSuccess)(await e.get(b),e.apiUrl(b)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0];if(!I?.solutionid)throw new Jr.InvalidArgumentError(`No solution found for '${t}'.`);let R=I.publisherid;if(!R?.publisherid)throw new Jr.InvalidArgumentError(`Solution '${(i=I.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 R))throw new Jr.InvalidArgumentError(`Solution '${(a=I.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,ft.normalizeGuid)(I.solutionid,"solutionId"),uniqueName:(o=I.uniquename)!==null&&o!==void 0?o:"",friendlyName:(s=I.friendlyname)!==null&&s!==void 0?s:"",version:(l=I.version)!==null&&l!==void 0?l:"",isManaged:!!I.ismanaged,publisherId:(0,ft.normalizeGuid)(R.publisherid,"publisherId"),publisherUniqueName:(u=R.uniquename)!==null&&u!==void 0?u:"",publisherPrefix:(c=R.customizationprefix)!==null&&c!==void 0?c:"",publisherOptionValuePrefix:(d=R.customizationoptionvalueprefix)!==null&&d!==void 0?d:0}}K.getSolution=Y1;async function Z1(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,mt.ensureSuccess)(await e.post("/publishers",n),e.apiUrl("/publishers")),a=(0,mt.readCreatedId)(i,"publisherid");if(!a)throw new Jr.InvalidArgumentError(`Dataverse did not return an id for publisher '${t.uniqueName}'`);return{id:a,uniqueName:t.uniqueName}}K.createPublisher=Z1;async function e_(e,t){var r;let n=(0,ft.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,mt.ensureSuccess)(await e.post("/solutions",i),e.apiUrl("/solutions")),o=(0,mt.readCreatedId)(a,"solutionid");if(!o)throw new Jr.InvalidArgumentError(`Dataverse did not return an id for solution '${t.uniqueName}'`);return{id:o,uniqueName:t.uniqueName}}K.createSolution=e_;async function t_(e,t,r){let i=`/solutions(${(0,ft.normalizeGuid)(t,"solutionId")})`;(0,mt.ensureSuccess)(await e.patch(i,{version:r}),e.apiUrl(i))}K.setSolutionVersion=t_;async function r_(e,t){var r;let i={ComponentId:(0,ft.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,mt.ensureSuccess)(await e.post("/AddSolutionComponent",i),e.apiUrl("/AddSolutionComponent"))}K.addSolutionComponent=r_;async function n_(e,t,r,n){let a={SolutionComponent:{"@odata.type":"Microsoft.Dynamics.CRM.solutioncomponent",solutioncomponentid:(0,ft.normalizeGuid)(t,"componentId")},ComponentType:r,SolutionUniqueName:n};(0,mt.ensureSuccess)(await e.post("/RemoveSolutionComponent",a),e.apiUrl("/RemoveSolutionComponent"))}K.removeSolutionComponent=n_;async function i_(e,t){var r,n;let i={SolutionName:t.solutionName,Managed:(r=t.managed)!==null&&r!==void 0?r:!1},o=(n=(0,mt.ensureSuccess)(await e.post("/ExportSolution",i),e.apiUrl("/ExportSolution")).body)===null||n===void 0?void 0:n.ExportSolutionFile;if(!o)throw new Jr.InvalidArgumentError(`ExportSolution returned no file for '${t.solutionName}'`);return{base64:o}}K.exportSolution=i_;async function a_(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,ft.normalizeGuid)(t.importJobId,"importJobId")),(0,mt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution"))}K.importSolution=a_;async function o_(e,t){let n=`/solutions(${(0,ft.normalizeGuid)(t,"solutionId")})`;(0,mt.ensureSuccess)(await e.delete(n),e.apiUrl(n))}K.deleteSolution=o_});var Of=m(ru=>{"use strict";Object.defineProperty(ru,"__esModule",{value:!0});ru.default="ffffffff-ffff-ffff-ffff-ffffffffffff"});var Tf=m(nu=>{"use strict";Object.defineProperty(nu,"__esModule",{value:!0});nu.default="00000000-0000-0000-0000-000000000000"});var Rf=m(iu=>{"use strict";Object.defineProperty(iu,"__esModule",{value:!0});iu.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i});var qi=m(au=>{"use strict";Object.defineProperty(au,"__esModule",{value:!0});var s_=Rf();function l_(e){return typeof e=="string"&&s_.default.test(e)}au.default=l_});var $i=m(ou=>{"use strict";Object.defineProperty(ou,"__esModule",{value:!0});var u_=qi();function c_(e){if(!(0,u_.default)(e))throw TypeError("Invalid UUID");let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,t&255,(t=parseInt(e.slice(9,13),16))>>>8,t&255,(t=parseInt(e.slice(14,18),16))>>>8,t&255,(t=parseInt(e.slice(19,23),16))>>>8,t&255,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255)}ou.default=c_});var sr=m(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0});Vi.unsafeStringify=void 0;var d_=qi(),Be=[];for(let e=0;e<256;++e)Be.push((e+256).toString(16).slice(1));function Ff(e,t=0){return(Be[e[t+0]]+Be[e[t+1]]+Be[e[t+2]]+Be[e[t+3]]+"-"+Be[e[t+4]]+Be[e[t+5]]+"-"+Be[e[t+6]]+Be[e[t+7]]+"-"+Be[e[t+8]]+Be[e[t+9]]+"-"+Be[e[t+10]]+Be[e[t+11]]+Be[e[t+12]]+Be[e[t+13]]+Be[e[t+14]]+Be[e[t+15]]).toLowerCase()}Vi.unsafeStringify=Ff;function p_(e,t=0){let r=Ff(e,t);if(!(0,d_.default)(r))throw TypeError("Stringified UUID is invalid");return r}Vi.default=p_});var So=m(su=>{"use strict";Object.defineProperty(su,"__esModule",{value:!0});var f_=require("crypto"),No=new Uint8Array(256),wo=No.length;function m_(){return wo>No.length-16&&((0,f_.randomFillSync)(No),wo=0),No.slice(wo,wo+=16)}su.default=m_});var lu=m(zi=>{"use strict";Object.defineProperty(zi,"__esModule",{value:!0});zi.updateV1State=void 0;var xf=So(),h_=sr(),Gi={};function g_(e,t,r){let n,i=e?._v6??!1;if(e){let a=Object.keys(e);a.length===1&&a[0]==="_v6"&&(e=void 0)}if(e)n=Lf(e.random??e.rng?.()??(0,xf.default)(),e.msecs,e.nsecs,e.clockseq,e.node,t,r);else{let a=Date.now(),o=(0,xf.default)();Mf(Gi,a,o),n=Lf(o,Gi.msecs,Gi.nsecs,i?void 0:Gi.clockseq,i?void 0:Gi.node,t,r)}return t??(0,h_.unsafeStringify)(n)}function Mf(e,t,r){return e.msecs??=-1/0,e.nsecs??=0,t===e.msecs?(e.nsecs++,e.nsecs>=1e4&&(e.node=void 0,e.nsecs=0)):t>e.msecs?e.nsecs=0:t<e.msecs&&(e.node=void 0),e.node||(e.node=r.slice(10,16),e.node[0]|=1,e.clockseq=(r[8]<<8|r[9])&16383),e.msecs=t,e}zi.updateV1State=Mf;function Lf(e,t,r,n,i,a,o=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(!a)a=new Uint8Array(16),o=0;else if(o<0||o+16>a.length)throw new RangeError(`UUID byte range ${o}:${o+15} is out of buffer bounds`);t??=Date.now(),r??=0,n??=(e[8]<<8|e[9])&16383,i??=e.slice(10,16),t+=122192928e5;let s=((t&268435455)*1e4+r)%4294967296;a[o++]=s>>>24&255,a[o++]=s>>>16&255,a[o++]=s>>>8&255,a[o++]=s&255;let l=t/4294967296*1e4&268435455;a[o++]=l>>>8&255,a[o++]=l&255,a[o++]=l>>>24&15|16,a[o++]=l>>>16&255,a[o++]=n>>>8|128,a[o++]=n&255;for(let u=0;u<6;++u)a[o++]=i[u];return a}zi.default=g_});var cu=m(uu=>{"use strict";Object.defineProperty(uu,"__esModule",{value:!0});var v_=$i(),b_=sr();function y_(e){let t=typeof e=="string"?(0,v_.default)(e):e,r=C_(t);return typeof e=="string"?(0,b_.unsafeStringify)(r):r}uu.default=y_;function C_(e){return Uint8Array.of((e[6]&15)<<4|e[7]>>4&15,(e[7]&15)<<4|(e[4]&240)>>4,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,(e[1]&15)<<4|(e[2]&240)>>4,96|e[2]&15,e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}});var Uf=m(du=>{"use strict";Object.defineProperty(du,"__esModule",{value:!0});var A_=require("crypto");function w_(e){return Array.isArray(e)?e=Buffer.from(e):typeof e=="string"&&(e=Buffer.from(e,"utf8")),(0,A_.createHash)("md5").update(e).digest()}du.default=w_});var Wi=m(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});lr.URL=lr.DNS=lr.stringToBytes=void 0;var Bf=$i(),N_=sr();function kf(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let r=0;r<e.length;++r)t[r]=e.charCodeAt(r);return t}lr.stringToBytes=kf;lr.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8";lr.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function S_(e,t,r,n,i,a){let o=typeof r=="string"?kf(r):r,s=typeof n=="string"?(0,Bf.default)(n):n;if(typeof n=="string"&&(n=(0,Bf.default)(n)),n?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let l=new Uint8Array(16+o.length);if(l.set(s),l.set(o,s.length),l=t(l),l[6]=l[6]&15|e,l[8]=l[8]&63|128,i){if(a=a||0,a<0||a+16>i.length)throw new RangeError(`UUID byte range ${a}:${a+15} is out of buffer bounds`);for(let u=0;u<16;++u)i[a+u]=l[u];return i}return(0,N_.unsafeStringify)(l)}lr.default=S_});var $f=m(Qr=>{"use strict";Object.defineProperty(Qr,"__esModule",{value:!0});Qr.URL=Qr.DNS=void 0;var D_=Uf(),pu=Wi(),qf=Wi();Object.defineProperty(Qr,"DNS",{enumerable:!0,get:function(){return qf.DNS}});Object.defineProperty(Qr,"URL",{enumerable:!0,get:function(){return qf.URL}});function fu(e,t,r,n){return(0,pu.default)(48,D_.default,e,t,r,n)}fu.DNS=pu.DNS;fu.URL=pu.URL;Qr.default=fu});var Vf=m(mu=>{"use strict";Object.defineProperty(mu,"__esModule",{value:!0});var E_=require("crypto");mu.default={randomUUID:E_.randomUUID}});var zf=m(hu=>{"use strict";Object.defineProperty(hu,"__esModule",{value:!0});var Gf=Vf(),I_=So(),__=sr();function P_(e,t,r){if(Gf.default.randomUUID&&!t&&!e)return Gf.default.randomUUID();e=e||{};let n=e.random??e.rng?.()??(0,I_.default)();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(0,__.unsafeStringify)(n)}hu.default=P_});var Wf=m(gu=>{"use strict";Object.defineProperty(gu,"__esModule",{value:!0});var O_=require("crypto");function T_(e){return Array.isArray(e)?e=Buffer.from(e):typeof e=="string"&&(e=Buffer.from(e,"utf8")),(0,O_.createHash)("sha1").update(e).digest()}gu.default=T_});var Hf=m(Xr=>{"use strict";Object.defineProperty(Xr,"__esModule",{value:!0});Xr.URL=Xr.DNS=void 0;var R_=Wf(),vu=Wi(),jf=Wi();Object.defineProperty(Xr,"DNS",{enumerable:!0,get:function(){return jf.DNS}});Object.defineProperty(Xr,"URL",{enumerable:!0,get:function(){return jf.URL}});function bu(e,t,r,n){return(0,vu.default)(80,R_.default,e,t,r,n)}bu.DNS=vu.DNS;bu.URL=vu.URL;Xr.default=bu});var Jf=m(yu=>{"use strict";Object.defineProperty(yu,"__esModule",{value:!0});var F_=sr(),x_=lu(),L_=cu();function M_(e,t,r){e??={},r??=0;let n=(0,x_.default)({...e,_v6:!0},new Uint8Array(16));if(n=(0,L_.default)(n),t){if(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(0,F_.unsafeStringify)(n)}yu.default=M_});var Qf=m(Cu=>{"use strict";Object.defineProperty(Cu,"__esModule",{value:!0});var U_=$i(),B_=sr();function k_(e){let t=typeof e=="string"?(0,U_.default)(e):e,r=q_(t);return typeof e=="string"?(0,B_.unsafeStringify)(r):r}Cu.default=k_;function q_(e){return Uint8Array.of((e[3]&15)<<4|e[4]>>4&15,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|e[6]&15,e[7],(e[1]&15)<<4|(e[2]&240)>>4,(e[2]&15)<<4|(e[3]&240)>>4,16|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}});var Zf=m(ji=>{"use strict";Object.defineProperty(ji,"__esModule",{value:!0});ji.updateV7State=void 0;var Xf=So(),$_=sr(),Au={};function V_(e,t,r){let n;if(e)n=Kf(e.random??e.rng?.()??(0,Xf.default)(),e.msecs,e.seq,t,r);else{let i=Date.now(),a=(0,Xf.default)();Yf(Au,i,a),n=Kf(a,Au.msecs,Au.seq,t,r)}return t??(0,$_.unsafeStringify)(n)}function Yf(e,t,r){return e.msecs??=-1/0,e.seq??=0,t>e.msecs?(e.seq=r[6]<<23|r[7]<<16|r[8]<<8|r[9],e.msecs=t):(e.seq=e.seq+1|0,e.seq===0&&e.msecs++),e}ji.updateV7State=Yf;function Kf(e,t,r,n,i=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(!n)n=new Uint8Array(16),i=0;else if(i<0||i+16>n.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);return t??=Date.now(),r??=e[6]*127<<24|e[7]<<16|e[8]<<8|e[9],n[i++]=t/1099511627776&255,n[i++]=t/4294967296&255,n[i++]=t/16777216&255,n[i++]=t/65536&255,n[i++]=t/256&255,n[i++]=t&255,n[i++]=112|r>>>28&15,n[i++]=r>>>20&255,n[i++]=128|r>>>14&63,n[i++]=r>>>6&255,n[i++]=r<<2&255|e[10]&3,n[i++]=e[11],n[i++]=e[12],n[i++]=e[13],n[i++]=e[14],n[i++]=e[15],n}ji.default=V_});var em=m(wu=>{"use strict";Object.defineProperty(wu,"__esModule",{value:!0});var G_=qi();function z_(e){if(!(0,G_.default)(e))throw TypeError("Invalid UUID");return parseInt(e.slice(14,15),16)}wu.default=z_});var Nu=m(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.version=Q.validate=Q.v7=Q.v6ToV1=Q.v6=Q.v5=Q.v4=Q.v3=Q.v1ToV6=Q.v1=Q.stringify=Q.parse=Q.NIL=Q.MAX=void 0;var W_=Of();Object.defineProperty(Q,"MAX",{enumerable:!0,get:function(){return W_.default}});var j_=Tf();Object.defineProperty(Q,"NIL",{enumerable:!0,get:function(){return j_.default}});var H_=$i();Object.defineProperty(Q,"parse",{enumerable:!0,get:function(){return H_.default}});var J_=sr();Object.defineProperty(Q,"stringify",{enumerable:!0,get:function(){return J_.default}});var Q_=lu();Object.defineProperty(Q,"v1",{enumerable:!0,get:function(){return Q_.default}});var X_=cu();Object.defineProperty(Q,"v1ToV6",{enumerable:!0,get:function(){return X_.default}});var K_=$f();Object.defineProperty(Q,"v3",{enumerable:!0,get:function(){return K_.default}});var Y_=zf();Object.defineProperty(Q,"v4",{enumerable:!0,get:function(){return Y_.default}});var Z_=Hf();Object.defineProperty(Q,"v5",{enumerable:!0,get:function(){return Z_.default}});var eP=Jf();Object.defineProperty(Q,"v6",{enumerable:!0,get:function(){return eP.default}});var tP=Qf();Object.defineProperty(Q,"v6ToV1",{enumerable:!0,get:function(){return tP.default}});var rP=Zf();Object.defineProperty(Q,"v7",{enumerable:!0,get:function(){return rP.default}});var nP=qi();Object.defineProperty(Q,"validate",{enumerable:!0,get:function(){return nP.default}});var iP=em();Object.defineProperty(Q,"version",{enumerable:!0,get:function(){return iP.default}})});var Tt=m(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.assignMissingIds=In.newId=void 0;var aP=Nu();function tm(){return(0,aP.v4)()}In.newId=tm;function oP(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var sP=new Set(["parameters","bag"]);function lP(e){return Su(e),e}In.assignMissingIds=lP;function Su(e){if(Array.isArray(e)){e.forEach(t=>Su(t));return}if(oP(e)){(typeof e.id!="string"||e.id.length===0)&&(e.id=tm());for(let t of Object.keys(e))t==="id"||sP.has(t)||Su(e[t])}}});var _u=m(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.appApi=_n.deleteAppResolvingOnce=void 0;var Re=Ve(),ie=ce(),Eu=Tt(),Se=be(),lm=(0,ie.odataQuery)([["$select","appmoduleid,name,uniquename,description"]]),uP=(0,ie.odataQuery)([["$select","appmoduleid,name,uniquename,description"]]);function Do(e,t){return"/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,ie.odataQuery)([["$select",t],["$filter",`sitemapid eq ${e}`],["$top",1]])}function Eo(e){var t;let r=(t=e.body)===null||t===void 0?void 0:t.value;if(Array.isArray(r))return r[0]}function Iu(e){let t=e?.["@odata.etag"];return typeof t=="string"?t:null}function Hi(e){let t=new Set,r=[];for(let n of e??[])n&&!t.has(n)&&(t.add(n),r.push(n));return r}function cP(e){return`cdsapp_${(e||"").replace(/[^a-zA-Z0-9]/g,"")||"app"}`}async function um(e,t){var r,n;let i=u=>{throw new Se.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,ie.odataQuery)([["$select","sitemapid"],["$filter",`sitemapnameunique eq '${(0,ie.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 dP(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,ie.odataQuery)([["$select","webresourceid"],["$top",1],["$filter",s]])}`,n=await e.get(r("webresourcetype eq 5 and ismanaged eq false and contains(name,'icon')")),i=t(n);if(i)return i;let a=await e.get(r("webresourcetype eq 5 and ismanaged eq false")),o=t(a);return o||t(await e.get(r("ismanaged eq false")))}async function pP(e,t){var r,n,i;try{let a=`/roles${(0,ie.odataQuery)([["$select","roleid"],["$filter","name eq 'System Administrator'"],["$top",1]])}`,s=(i=(n=(r=(await e.get(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;let l=`/appmodules(${t})/appmoduleroles_association/$ref`;await e.post(l,{"@odata.id":e.apiUrl(`/roles(${s})`)})}catch{}}async function fP(e,t){async function r(o,s){var l,u;try{let c=await e.get(o);return c.status<200||c.status>=300?[]:((u=(l=c.body)===null||l===void 0?void 0:l.value)!==null&&u!==void 0?u:[]).map(f=>String(f[s])).filter(f=>f&&f!=="undefined")}catch{return[]}}let[n,i,a]=await Promise.all([r(`/systemforms${(0,ie.odataQuery)([["$select","formid"],["$filter",`objecttypecode eq '${(0,ie.odataLiteral)(t)}' and type eq 2 and formactivationstate eq 1`]])}`,"formid"),r(`/savedqueries${(0,ie.odataQuery)([["$select","savedqueryid"],["$filter",`returnedtypecode eq '${(0,ie.odataLiteral)(t)}' and querytype eq 0 and statecode eq 0`]])}`,"savedqueryid"),r(`/savedqueryvisualizations${(0,ie.odataQuery)([["$select","savedqueryvisualizationid"],["$filter",`primaryentitytypecode eq '${(0,ie.odataLiteral)(t)}'`]])}`,"savedqueryvisualizationid")]);return{forms:n,views:i,charts:a}}var rm=new WeakMap;async function mP(e,t){let r=rm.get(e);r||(r=new Map,rm.set(e,r));let n=r.get(t);if(n!==void 0)return n;let i=await hP(e,t);return i&&r.set(t,i),i}async function nm(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 hP(e,t){let r=`/EntityDefinitions(LogicalName='${(0,ie.odataLiteral)(t)}')${(0,ie.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 im(e,t){let r=[],n=Hi(t.entities),i=4,a=await nm(n,i,f=>mP(e,f)),o=n.filter((f,h)=>!a[h]);if(o.length>0)throw new Se.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 Hi(t.components.forms))r.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:f});for(let f of Hi(t.components.views))r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:f});for(let f of Hi(t.components.charts))r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:f});for(let f of Hi(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 nm(n,i,f=>fP(e,f));for(let f of d){for(let h of f.forms)l.has(h)||(l.add(h),r.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:h}));for(let h of f.views)u.has(h)||(u.add(h),r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:h}));for(let h of f.charts)c.has(h)||(c.add(h),r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:h}))}return{components:r,tables:s}}async function am(e,t,r){if(r.length===0)return;let n="/AddAppComponents";(0,Re.ensureSuccess)(await e.post(n,{AppId:t,Components:r}),e.apiUrl(n))}function gP(e){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,ie.odataQuery)([["$select","appmoduleid,appmoduleidunique"],["$filter",`appmoduleid eq ${e}`],["$top",1]])}async function om(e,t,r){var n;if(r.length===0)return;let i=gP(t),a=await e.get(i);if(a.status<200||a.status>=300)throw new Se.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=Eo(a),s=o?.appmoduleidunique;if(typeof s!="string"||!s)throw new Se.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,ie.odataQuery)([["$select","objectid,componenttype"],["$filter",`_appmoduleidunique_value eq ${(0,ie.normalizeGuid)(s,`App '${t}' appmoduleidunique`)} and componenttype eq 1`]])}`,u=await e.get(l);if(u.status<200||u.status>=300)throw new Se.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 Se.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(h=>h.objectid).filter(h=>typeof h=="string").map(h=>h.toLowerCase())),f=r.filter(h=>!d.has(h.metadataId.toLowerCase()));if(f.length>0)throw new Se.SdkError("APP_COMPONENTS_NOT_PERSISTED",`App '${t}': ${f.length} declared table(s) are NOT components of the app after AddAppComponents reported success \u2014 ${f.map(h=>`'${h.logicalName}' (expected objectid ${h.metadataId})`).join(", ")}. The app's navigation would reference content the app does not contain.`)}async function vP(e,t,r){let n=`/appmodules(${t})`,i=`/sitemaps(${r.sitemapId})`;try{if(!await bP(e,r.sitemapId)){r.serverRefusedSitemap&&(0,Re.ensureSuccess)(await e.delete(n),e.apiUrl(n));return}e.supportsAtomicBatch&&await dm(e,[{path:n,etag:r.appEtag},{path:i,etag:r.sitemapEtag}])}catch{}}async function bP(e,t){var r;let n=Do(t,"sitemapid"),i=await e.get(n);if(i.status<200||i.status>=300)throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned HTTP ${i.status}, so it cannot be determined whether the row exists.`);let a=(r=i.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new Se.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 a.length>0}async function cm(e,t){var r;let n=(0,ie.normalizeGuid)(t,"id"),i=b=>{throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${n}': ${b} 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})${lm}`,o;try{o=await e.get(a)}catch(b){return i(`reading the app failed (${b.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 um(e,s);if(!l)return{uniquename:s,appEtag:(0,Re.readEtag)(o)};let u=(0,ie.normalizeGuid)(l,"sitemapId"),c=Do(u,"sitemapid,sitemapnameunique,sitemapxml"),d;try{d=await e.get(c)}catch(b){return i(`reading sitemap '${u}' failed (${b.message}).`)}if(d.status<200||d.status>=300)return i(`reading sitemap '${u}' returned HTTP ${d.status}.`);let f=Eo(d);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.`);let h=f.sitemapxml;return typeof h!="string"?i(`sitemap '${u}' returned no sitemapxml.`):{sitemapId:u,uniquename:s,sitemapXml:h,appEtag:(0,Re.readEtag)(o),sitemapEtag:Iu(f)}}async function yP(e,t,r){let n=(0,ie.normalizeGuid)(t,"id"),i=await cm(e,n);await r?.(i.sitemapXml),await pm(e,n,i)}_n.deleteAppResolvingOnce=yP;async function dm(e,t){let r=`batch_${(0,Eu.newId)()}`,n=`changeset_${(0,Eu.newId)()}`,i=t.map((d,f)=>[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${f+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,Re.ensureSuccess)(o,s);let l=`app '${t[0].path}'`;if(typeof o.body!="string"||o.body.length===0)throw new Se.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=CP(o.body,i.map((d,f)=>String(f+1)));if(u===void 0)throw new Se.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 Se.ConnectionError(s,c,`atomic delete of ${l} was rolled back: the change set reported HTTP ${c}`);if(u.length!==i.length)throw new Se.ConnectionError(s,o.status,`atomic delete of ${l} cannot be confirmed: the $batch response reported ${u.length} operation result(s), expected exactly ${i.length}`)}function CP(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 f of l.slice(1)){if(f.startsWith("--"))break;let h=f.indexOf(`\r+ &$filter=(applicationid eq '${e}')`;y.SPNPrincipalIdUrl=qT;function VT(){return"/api/data/v9.0/appmodules?$filter=(uniquename eq 'AppDeploymentConfiguration')"}y.retrieveDeploymentPipelineConfigAppUrl=VT;y.retrieveFeatureControlSettingsByNamespaceUrl="/api/data/v9.1/RetrieveFeatureControlSettingsByNamespace";function GT(e){return`/api/data/v9.0/settingdefinitions${e}`}y.getSettingDefinitionsUri=GT;y.OrgSettingOverrideName="organizationsettings";function zT(e,t=!1){let r=`/api/data/v9.0/${y.OrgSettingOverrideName}${e}`;return t?`${y.cdsServiceUrl}${r}`:r}y.getOrgSettingOverrideUri=zT;y.AppSettingOverrideName="appsettings";function WT(e,t=!1){let r=`/api/data/v9.0/${y.AppSettingOverrideName}${e}`;return t?`${y.cdsServiceUrl.replace("/$","")}${r}`:r}y.getAppSettingOverrideUri=WT;var Oa;(function(e){e[e.All=0]="All",e[e.IsPlatformOnly=1]="IsPlatformOnly",e[e.NotPlatformOnly=2]="NotPlatformOnly"})(Oa||(y.RetrievePlatform=Oa={}));function jT(e,t,r,n=Oa.All,i=!1){let a=[];e&&a.push(`AppUniqueName='${e}'`),t!=null&&a.push(`ReleaseLevel=${t}`),r&&a.push(`RetrieveHiddenSettings=${r}`),n!==Oa.All&&a.push(`RetrievePlatformSettings=${n===Oa.IsPlatformOnly?1:0}`);let o="/api/data/v9.0/RetrieveUnpublishedOverridableSettingsInfo";return a.length&&(o=`${o}(${a.join(",")})`),i?`${y.cdsServiceUrl}${o}`:o}y.getPowerSettingsUri=jT;function HT(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?`${y.cdsServiceUrl}${a}`:a}y.getPowerSettingUri=HT;function QT(e=!1){let t="/api/data/v9.0/SaveSettingValue()";return e?`${y.cdsServiceUrl}${t}`:t}y.getSavePowerSettingUri=QT;y.retrieveUnpublishedSuffix="Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()";function JT(e){return`tools/systemcustomization/businessrules/businessRulesDesigner.aspx?BRlaunchpoint=BRGrid&appSolutionId={${e}}`}y.getBusinessRuleDesignerUri=JT;function gh({environmentInstanceUrl:e,entityLogicalName:t}){return e&&t?`${e}main.aspx?cmdbar=true&forceUCI=1&navbar=off&newWindow=true&pageType=entityRecord&etn=${t}`:void 0}y.getUCIEntityRecordBaseUrl=gh;function XT({baseUrl:e,environmentInstanceUrl:t,entityLogicalName:r,recordId:n}){let i=e||gh({environmentInstanceUrl:t,entityLogicalName:r});return i&&n?`${i}&id=${n}`:void 0}y.getUCIEntityRecordEditUrl=XT;y.retrieveOrganizationResources=`${y.cdsServiceUrl}api/data/v9.0/RetrieveOrganizationResources`});var vh=g(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.DataverseClient=void 0;var KT=wc(),Fn=le(),Cc=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}/${KT.xrmApiUrl}${n}`}async send(t,r){try{return await r()}catch(n){throw n instanceof Fn.SdkError?n:new Fn.ConnectionError(t,0,n instanceof Error?n.message:String(n),n)}}get(t,r){let n=this.apiUrl(t);return this.send(n,()=>this.httpClient.get(n,r))}getAbsolute(t,r){return this.assertSameOrigin(t),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 Fn.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${t}'`)}if(r.protocol!==n.protocol||r.host!==n.host)throw new Fn.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 Fn.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 Fn.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 Fn.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)))}};hs.DataverseClient=Cc});var Z=g(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.odataQuery=_e.normalizeGuid=_e.createSafeXmlElement=_e.assertNoControlChars=_e.assertODataName=_e.assertXmlName=_e.xmlText=_e.odataPathLiteral=_e.odataLiteral=void 0;var gs=le();function yh(e){return String(e??"").replace(/'/g,"''")}_e.odataLiteral=yh;function YT(e){return encodeURIComponent(yh(e))}_e.odataPathLiteral=YT;function ZT(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}_e.xmlText=ZT;function bh(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 gs.InvalidArgumentError(`${t} must be a valid XML element name (got '${e}')`);return e}_e.assertXmlName=bh;function eO(e,t){let r=String(e??"");if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new gs.InvalidArgumentError(`${t} must be a valid OData identifier (letters, digits, underscore): got '${e}'`);return e}_e.assertODataName=eO;function tO(e,t){if(/[\u0000-\u001F\u007F]/.test(String(e??"")))throw new gs.InvalidArgumentError(`${t} must not contain control characters (including CR/LF): they would inject additional lines into the request`);return e}_e.assertNoControlChars=tO;function rO(e,t,r){return e.createElement(bh(t,r))}_e.createSafeXmlElement=rO;var nO=/^[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 iO(e,t){let r=String(e??""),n=r.length===38&&r.startsWith("{")&&r.endsWith("}")?r.slice(1,-1):r;if(!nO.test(n))throw new gs.InvalidArgumentError(`${t} must be a valid GUID (got '${e}')`);return n.toLowerCase()}_e.normalizeGuid=iO;function aO(e){let t=[];for(let[r,n]of e)n!=null&&n!==""&&t.push(`${r}=${encodeURIComponent(String(n))}`);return t.length>0?`?${t.join("&")}`:""}_e.odataQuery=aO});var he=g(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.nowIso=ee.isAlreadyDeleted=ee.deleteRecord=ee.ensureSuccess=ee.resolveCreatedId=ee.requireCreatedId=ee.withClientMintedId=ee.readCreatedId=ee.readEtag=ee.requireEtag=ee.echoWrite=ee.UPDATE_NO_ETAG_CODE=ee.VERSION_CONFLICT_CODE=void 0;var di=le(),Ra=Z();ee.VERSION_CONFLICT_CODE="VERSION_CONFLICT";ee.UPDATE_NO_ETAG_CODE="ARTIFACT_UPDATE_NO_ETAG";function oO(e,t){return{query:`?$select=${encodeURIComponent(e)}`,options:{headers:{...t??{},Prefer:"return=representation"}}}}ee.echoWrite=oO;function sO(e,t,r){if(!e)throw new di.SdkError(ee.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}ee.requireEtag=sO;function lO(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}ee.readEtag=lO;function Sc(e,t){var r;let n=e.body;if(n&&typeof n[t]=="string")return(0,Ra.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,Ra.normalizeGuid)(o[1],t)}return null}ee.readCreatedId=Sc;function uO(e,t,r){return r?{...e,[t]:(0,Ra.normalizeGuid)(r,t)}:e}ee.withClientMintedId=uO;function cO(e,t,r){let n=Sc(e,t);if(!n)throw new di.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`);return n}ee.requireCreatedId=cO;function dO(e,t,r,n){let i=Sc(e,t);if(i)return i;if(n)return(0,Ra.normalizeGuid)(n,t);throw new di.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`)}ee.resolveCreatedId=dO;function wh(e,t){if(e.status===412)throw new di.SdkError(ee.VERSION_CONFLICT_CODE,`Version conflict (412) from ${t}`);if(e.status<200||e.status>=300)throw new di.ConnectionError(t,e.status,pO(e.body),e.body);return e}ee.ensureSuccess=wh;function pO(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 fO(e,t,r,n){let i=(0,Ra.normalizeGuid)(r,"id"),a=`/${t}(${i})`;wh(await e.delete(a,n?{headers:{"If-Match":n}}:void 0),e.apiUrl(a))}ee.deleteRecord=fO;function mO(e){return e instanceof di.ConnectionError&&e.statusCode===404}ee.isAlreadyDeleted=mO;function hO(){return new Date().toISOString()}ee.nowIso=hO});var Ah=g(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.findColumns=on.findTables=on.fetchEntityMetadataFromApi=void 0;var Nc=he(),ur=Z();function La(e){var t,r;return(r=(t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)!==null&&r!==void 0?r:""}async function pi(e,t){var r,n;let i=await e.get(t);return i.status<200||i.status>=300?[]:(n=(r=i.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]}function an(e){return`/EntityDefinitions(LogicalName='${(0,ur.odataLiteral)(e)}')`}async function gO(e,t,r){let n=await pi(e,`${an(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata${(0,ur.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 vO(e,t,r){var n;let i=await pi(e,`${an(t)}/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata${(0,ur.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:La(s.Label)}}))}}async function yO(e,t,r){let n=await pi(e,`${an(t)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata${(0,ur.odataQuery)([["$select","LogicalName,Targets"]])}`);for(let i of n){let a=r.get(i.LogicalName);a&&i.Targets&&(a.targets=i.Targets)}}async function bO(e,t){var r,n,i,a;let o=[],s=await pi(e,`${an(t)}/OneToManyRelationships${(0,ur.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 pi(e,`${an(t)}/ManyToOneRelationships${(0,ur.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 pi(e,`${an(t)}/ManyToManyRelationships${(0,ur.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 wO(e,t){var r,n,i,a,o;let s=`${an(t)}`+(0,ur.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,EntitySetName,IsCustomEntity,PrimaryNameAttribute,PrimaryIdAttribute"],["$expand","Attributes($select=LogicalName,DisplayName,AttributeType,IsCustomAttribute)"]]),u=(0,Nc.ensureSuccess)(await e.get(s),e.apiUrl(s)).body,c=((r=u.Attributes)!==null&&r!==void 0?r:[]).map(f=>{var h;return{logicalName:f.LogicalName,displayName:La(f.DisplayName),attributeType:(h=f.AttributeType)!==null&&h!==void 0?h:"Unknown",isCustomAttribute:!!f.IsCustomAttribute}}),d=new Map(c.map(f=>[f.logicalName,f])),[,,,p]=await Promise.all([gO(e,t,d),vO(e,t,d),yO(e,t,d),bO(e,t)]);return{logicalName:u.LogicalName,schemaName:(n=u.SchemaName)!==null&&n!==void 0?n:u.LogicalName,displayName:La(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:"",isCustomEntity:!!u.IsCustomEntity,attributes:c,relationships:p}}on.fetchEntityMetadataFromApi=wO;async function AO(e,t,r){var n,i;let a=`/EntityDefinitions${(0,ur.odataQuery)([["$select","LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity"]])}`,s=(i=(n=(0,Nc.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:La(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}on.findTables=AO;async function CO(e,t,r,n){var i,a;let o=`${an(t)}/Attributes`+(0,ur.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute"]]),l=(a=(i=(0,Nc.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:La(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}on.findColumns=CO});var fi=g(vs=>{"use strict";Object.defineProperty(vs,"__esModule",{value:!0});vs.DEFAULT_LCID=void 0;vs.DEFAULT_LCID=1033});var Ch=g(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});Ec.default="ffffffff-ffff-ffff-ffff-ffffffffffff"});var Sh=g(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});Dc.default="00000000-0000-0000-0000-000000000000"});var Nh=g(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});Ic.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i});var Fa=g(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var SO=Nh();function NO(e){return typeof e=="string"&&SO.default.test(e)}_c.default=NO});var ka=g(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});var EO=Fa();function DO(e){if(!(0,EO.default)(e))throw TypeError("Invalid UUID");let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,t&255,(t=parseInt(e.slice(9,13),16))>>>8,t&255,(t=parseInt(e.slice(14,18),16))>>>8,t&255,(t=parseInt(e.slice(19,23),16))>>>8,t&255,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255)}Pc.default=DO});var Lr=g(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});Ma.unsafeStringify=void 0;var IO=Fa(),Xe=[];for(let e=0;e<256;++e)Xe.push((e+256).toString(16).slice(1));function Eh(e,t=0){return(Xe[e[t+0]]+Xe[e[t+1]]+Xe[e[t+2]]+Xe[e[t+3]]+"-"+Xe[e[t+4]]+Xe[e[t+5]]+"-"+Xe[e[t+6]]+Xe[e[t+7]]+"-"+Xe[e[t+8]]+Xe[e[t+9]]+"-"+Xe[e[t+10]]+Xe[e[t+11]]+Xe[e[t+12]]+Xe[e[t+13]]+Xe[e[t+14]]+Xe[e[t+15]]).toLowerCase()}Ma.unsafeStringify=Eh;function _O(e,t=0){let r=Eh(e,t);if(!(0,IO.default)(r))throw TypeError("Stringified UUID is invalid");return r}Ma.default=_O});var ws=g(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});var PO=require("crypto"),bs=new Uint8Array(256),ys=bs.length;function TO(){return ys>bs.length-16&&((0,PO.randomFillSync)(bs),ys=0),bs.slice(ys,ys+=16)}Tc.default=TO});var Oc=g(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.updateV1State=void 0;var Dh=ws(),OO=Lr(),Ua={};function xO(e,t,r){let n,i=e?._v6??!1;if(e){let a=Object.keys(e);a.length===1&&a[0]==="_v6"&&(e=void 0)}if(e)n=Ih(e.random??e.rng?.()??(0,Dh.default)(),e.msecs,e.nsecs,e.clockseq,e.node,t,r);else{let a=Date.now(),o=(0,Dh.default)();_h(Ua,a,o),n=Ih(o,Ua.msecs,Ua.nsecs,i?void 0:Ua.clockseq,i?void 0:Ua.node,t,r)}return t??(0,OO.unsafeStringify)(n)}function _h(e,t,r){return e.msecs??=-1/0,e.nsecs??=0,t===e.msecs?(e.nsecs++,e.nsecs>=1e4&&(e.node=void 0,e.nsecs=0)):t>e.msecs?e.nsecs=0:t<e.msecs&&(e.node=void 0),e.node||(e.node=r.slice(10,16),e.node[0]|=1,e.clockseq=(r[8]<<8|r[9])&16383),e.msecs=t,e}Ba.updateV1State=_h;function Ih(e,t,r,n,i,a,o=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(!a)a=new Uint8Array(16),o=0;else if(o<0||o+16>a.length)throw new RangeError(`UUID byte range ${o}:${o+15} is out of buffer bounds`);t??=Date.now(),r??=0,n??=(e[8]<<8|e[9])&16383,i??=e.slice(10,16),t+=122192928e5;let s=((t&268435455)*1e4+r)%4294967296;a[o++]=s>>>24&255,a[o++]=s>>>16&255,a[o++]=s>>>8&255,a[o++]=s&255;let l=t/4294967296*1e4&268435455;a[o++]=l>>>8&255,a[o++]=l&255,a[o++]=l>>>24&15|16,a[o++]=l>>>16&255,a[o++]=n>>>8|128,a[o++]=n&255;for(let u=0;u<6;++u)a[o++]=i[u];return a}Ba.default=xO});var Rc=g(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});var RO=ka(),LO=Lr();function FO(e){let t=typeof e=="string"?(0,RO.default)(e):e,r=kO(t);return typeof e=="string"?(0,LO.unsafeStringify)(r):r}xc.default=FO;function kO(e){return Uint8Array.of((e[6]&15)<<4|e[7]>>4&15,(e[7]&15)<<4|(e[4]&240)>>4,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,(e[1]&15)<<4|(e[2]&240)>>4,96|e[2]&15,e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}});var Ph=g(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});var MO=require("crypto");function UO(e){return Array.isArray(e)?e=Buffer.from(e):typeof e=="string"&&(e=Buffer.from(e,"utf8")),(0,MO.createHash)("md5").update(e).digest()}Lc.default=UO});var $a=g(Fr=>{"use strict";Object.defineProperty(Fr,"__esModule",{value:!0});Fr.URL=Fr.DNS=Fr.stringToBytes=void 0;var Th=ka(),BO=Lr();function Oh(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let r=0;r<e.length;++r)t[r]=e.charCodeAt(r);return t}Fr.stringToBytes=Oh;Fr.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8";Fr.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function $O(e,t,r,n,i,a){let o=typeof r=="string"?Oh(r):r,s=typeof n=="string"?(0,Th.default)(n):n;if(typeof n=="string"&&(n=(0,Th.default)(n)),n?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let l=new Uint8Array(16+o.length);if(l.set(s),l.set(o,s.length),l=t(l),l[6]=l[6]&15|e,l[8]=l[8]&63|128,i){if(a=a||0,a<0||a+16>i.length)throw new RangeError(`UUID byte range ${a}:${a+15} is out of buffer bounds`);for(let u=0;u<16;++u)i[a+u]=l[u];return i}return(0,BO.unsafeStringify)(l)}Fr.default=$O});var Rh=g(kn=>{"use strict";Object.defineProperty(kn,"__esModule",{value:!0});kn.URL=kn.DNS=void 0;var qO=Ph(),Fc=$a(),xh=$a();Object.defineProperty(kn,"DNS",{enumerable:!0,get:function(){return xh.DNS}});Object.defineProperty(kn,"URL",{enumerable:!0,get:function(){return xh.URL}});function kc(e,t,r,n){return(0,Fc.default)(48,qO.default,e,t,r,n)}kc.DNS=Fc.DNS;kc.URL=Fc.URL;kn.default=kc});var Lh=g(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});var VO=require("crypto");Mc.default={randomUUID:VO.randomUUID}});var kh=g(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});var Fh=Lh(),GO=ws(),zO=Lr();function WO(e,t,r){if(Fh.default.randomUUID&&!t&&!e)return Fh.default.randomUUID();e=e||{};let n=e.random??e.rng?.()??(0,GO.default)();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(0,zO.unsafeStringify)(n)}Uc.default=WO});var Mh=g(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});var jO=require("crypto");function HO(e){return Array.isArray(e)?e=Buffer.from(e):typeof e=="string"&&(e=Buffer.from(e,"utf8")),(0,jO.createHash)("sha1").update(e).digest()}Bc.default=HO});var Bh=g(Mn=>{"use strict";Object.defineProperty(Mn,"__esModule",{value:!0});Mn.URL=Mn.DNS=void 0;var QO=Mh(),$c=$a(),Uh=$a();Object.defineProperty(Mn,"DNS",{enumerable:!0,get:function(){return Uh.DNS}});Object.defineProperty(Mn,"URL",{enumerable:!0,get:function(){return Uh.URL}});function qc(e,t,r,n){return(0,$c.default)(80,QO.default,e,t,r,n)}qc.DNS=$c.DNS;qc.URL=$c.URL;Mn.default=qc});var $h=g(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});var JO=Lr(),XO=Oc(),KO=Rc();function YO(e,t,r){e??={},r??=0;let n=(0,XO.default)({...e,_v6:!0},new Uint8Array(16));if(n=(0,KO.default)(n),t){if(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(0,JO.unsafeStringify)(n)}Vc.default=YO});var qh=g(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var ZO=ka(),ex=Lr();function tx(e){let t=typeof e=="string"?(0,ZO.default)(e):e,r=rx(t);return typeof e=="string"?(0,ex.unsafeStringify)(r):r}Gc.default=tx;function rx(e){return Uint8Array.of((e[3]&15)<<4|e[4]>>4&15,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|e[6]&15,e[7],(e[1]&15)<<4|(e[2]&240)>>4,(e[2]&15)<<4|(e[3]&240)>>4,16|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}});var Wh=g(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.updateV7State=void 0;var Vh=ws(),nx=Lr(),zc={};function ix(e,t,r){let n;if(e)n=Gh(e.random??e.rng?.()??(0,Vh.default)(),e.msecs,e.seq,t,r);else{let i=Date.now(),a=(0,Vh.default)();zh(zc,i,a),n=Gh(a,zc.msecs,zc.seq,t,r)}return t??(0,nx.unsafeStringify)(n)}function zh(e,t,r){return e.msecs??=-1/0,e.seq??=0,t>e.msecs?(e.seq=r[6]<<23|r[7]<<16|r[8]<<8|r[9],e.msecs=t):(e.seq=e.seq+1|0,e.seq===0&&e.msecs++),e}qa.updateV7State=zh;function Gh(e,t,r,n,i=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(!n)n=new Uint8Array(16),i=0;else if(i<0||i+16>n.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);return t??=Date.now(),r??=e[6]*127<<24|e[7]<<16|e[8]<<8|e[9],n[i++]=t/1099511627776&255,n[i++]=t/4294967296&255,n[i++]=t/16777216&255,n[i++]=t/65536&255,n[i++]=t/256&255,n[i++]=t&255,n[i++]=112|r>>>28&15,n[i++]=r>>>20&255,n[i++]=128|r>>>14&63,n[i++]=r>>>6&255,n[i++]=r<<2&255|e[10]&3,n[i++]=e[11],n[i++]=e[12],n[i++]=e[13],n[i++]=e[14],n[i++]=e[15],n}qa.default=ix});var jh=g(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var ax=Fa();function ox(e){if(!(0,ax.default)(e))throw TypeError("Invalid UUID");return parseInt(e.slice(14,15),16)}Wc.default=ox});var As=g(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.version=te.validate=te.v7=te.v6ToV1=te.v6=te.v5=te.v4=te.v3=te.v1ToV6=te.v1=te.stringify=te.parse=te.NIL=te.MAX=void 0;var sx=Ch();Object.defineProperty(te,"MAX",{enumerable:!0,get:function(){return sx.default}});var lx=Sh();Object.defineProperty(te,"NIL",{enumerable:!0,get:function(){return lx.default}});var ux=ka();Object.defineProperty(te,"parse",{enumerable:!0,get:function(){return ux.default}});var cx=Lr();Object.defineProperty(te,"stringify",{enumerable:!0,get:function(){return cx.default}});var dx=Oc();Object.defineProperty(te,"v1",{enumerable:!0,get:function(){return dx.default}});var px=Rc();Object.defineProperty(te,"v1ToV6",{enumerable:!0,get:function(){return px.default}});var fx=Rh();Object.defineProperty(te,"v3",{enumerable:!0,get:function(){return fx.default}});var mx=kh();Object.defineProperty(te,"v4",{enumerable:!0,get:function(){return mx.default}});var hx=Bh();Object.defineProperty(te,"v5",{enumerable:!0,get:function(){return hx.default}});var gx=$h();Object.defineProperty(te,"v6",{enumerable:!0,get:function(){return gx.default}});var vx=qh();Object.defineProperty(te,"v6ToV1",{enumerable:!0,get:function(){return vx.default}});var yx=Wh();Object.defineProperty(te,"v7",{enumerable:!0,get:function(){return yx.default}});var bx=Fa();Object.defineProperty(te,"validate",{enumerable:!0,get:function(){return bx.default}});var wx=jh();Object.defineProperty(te,"version",{enumerable:!0,get:function(){return wx.default}})});var mt=g(mi=>{"use strict";Object.defineProperty(mi,"__esModule",{value:!0});mi.assignMissingIds=mi.newId=void 0;var Ax=As();function Hh(){return(0,Ax.v4)()}mi.newId=Hh;function Cx(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Sx=new Set(["parameters","bag"]);function Nx(e){return jc(e),e}mi.assignMissingIds=Nx;function jc(e){if(Array.isArray(e)){e.forEach(t=>jc(t));return}if(Cx(e)){(typeof e.id!="string"||e.id.length===0)&&(e.id=Hh());for(let t of Object.keys(e))t==="id"||Sx.has(t)||jc(e[t])}}});var Hc=g(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.postChangeSet=sn.parseChangeSetStatuses=sn.renderChangeSet=void 0;var Cs=le(),Ex=he(),Qh=mt(),Jh=Z();function Xh(e,t){let r=`batch_${(0,Qh.newId)()}`,n=`changeset_${(0,Qh.newId)()}`,i=t.map((s,l)=>String(l+1)),a=t.map((s,l)=>{let u=s.body===void 0?void 0:JSON.stringify(s.body);return(0,Jh.assertNoControlChars)(s.path,"batch operation path"),s.etag&&(0,Jh.assertNoControlChars)(s.etag,"batch operation etag"),[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${i[l]}`,"",`${s.method} ${e.apiUrl(s.path)} HTTP/1.1`,...u===void 0?[]:["Content-Type: application/json;type=entry"],...e.solutionName?[`MSCRM.SolutionUniqueName: ${e.solutionName}`]:[],...s.etag?[`If-Match: ${s.etag}`]:[],"",...u===void 0?[]:[u]].join(`\r+`)});return{body:[`--${r}`,`Content-Type: multipart/mixed;boundary=${n}`,"",...a,`--${n}--`,`--${r}--`,""].join(`\r+`),batchId:r,contentIds:i}}sn.renderChangeSet=Xh;function Kh(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\r-`);if(h===-1)return;let b=f.slice(0,h),w=f.slice(h+4);if(!/^Content-Type:\s*application\/http\b/im.test(b))return;let N=/^HTTP\/1\.[01] (\d{3})\b/.exec(w);if(!N||((i=w.match(/^HTTP\/1\.[01] \d{3}\b/gm))!==null&&i!==void 0?i:[]).length!==1)return;let I=(a=/^Content-ID:\s*(\S+)/im.exec(b))===null||a===void 0?void 0:a[1];if(I===void 0||d.has(I)||!u.has(I))return;d.add(I),c.push(Number(N[1]))}return c.length===0?void 0:c}async function sm(e,t){try{let r=Do(t,"sitemapid"),n=await e.get(r);return n.status<200||n.status>=300?null:Iu(Eo(n))}catch{return null}}function AP(e){return e>=400&&e<500&&e!==408&&e!==429}function Du(e,t,r){if(!e)throw new Se.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 pm(e,t,r){let n=`/appmodules(${t})`;if(!r.sitemapId){await wP(e,n,Du(r.appEtag,t,"app"));return}if(!e.supportsAtomicBatch)throw new Se.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 dm(e,[{path:n,etag:Du(r.appEtag,t,"app")},{path:`/sitemaps(${r.sitemapId})`,etag:Du(r.sitemapEtag,t,"sitemap")}])}async function wP(e,t,r){(0,Re.ensureSuccess)(await e.delete(t,{headers:{"If-Match":r}}),e.apiUrl(t))}_n.appApi={async get(e,t){var r;let n=(0,ie.normalizeGuid)(t,"id"),i=`/appmodules(${n})${lm}`,o=(r=(0,Re.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)!==null&&r!==void 0?r:{},s=await um(e,o.uniquename),l=s?(0,ie.normalizeGuid)(s,"sitemapId"):void 0,u=null;if(l){let c=Do(l,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"),d=(0,Re.ensureSuccess)(await e.get(c),e.apiUrl(c)),f=Eo(d);if(f&&f.sitemapnameunique!==o.uniquename)throw new Se.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.`);o.$sitemap=f??{},u=Iu(f)}return{raw:o,etag:u}},async list(e,t){var r;let n=`/appmodules${uP}`,a=(0,Re.ensureSuccess)(await e.get(n),e.apiUrl(n)).body;return((r=a?.value)!==null&&r!==void 0?r:[]).map(s=>{var l,u;return{type:"app",id:(l=s.appmoduleid)!==null&&l!==void 0?l:"",name:(u=s.name)!==null&&u!==void 0?u:"",isDirty:!1}})},async create(e,t){let r=t,n=r.iconWebResourceId||await dP(e),i=r.appModuleUniqueName||cP(r.appModuleId),a={name:r.appModuleName,uniquename:i,clienttype:4,formfactor:1,navigationtype:0};r.appModuleDescription&&(a.description=r.appModuleDescription),n&&(a.webresourceid=n);let o="/appmodules",s=(0,Re.ensureSuccess)(await e.post(o,a),e.apiUrl(o)),l=(0,Re.requireCreatedId)(s,"appmoduleid","app module"),u=null,c=(0,Eu.newId)(),d=!1;try{let f="/sitemaps",h=await e.post(f,{sitemapid:c,sitemapnameunique:i,sitemapname:r.sitemapname,sitemapxml:r.sitemapxml});d=AP(h.status);let b=(0,Re.ensureSuccess)(h,e.apiUrl(f));u=(0,Re.readEtag)(b),u||(u=await sm(e,c));let w=await im(e,r),N=w.components;N.unshift({"@odata.type":"Microsoft.Dynamics.CRM.sitemap",sitemapid:c}),await am(e,l,N),await om(e,l,w.tables),await pP(e,l);let I="/PublishXml";(0,Re.ensureSuccess)(await e.post(I,{ParameterXml:`<importexportxml><appmodules><appmodule>${l}</appmodule></appmodules></importexportxml>`}),e.apiUrl(I))}catch(f){throw await vP(e,l,{sitemapId:c,serverRefusedSitemap:d,appEtag:(0,Re.readEtag)(s),sitemapEtag:u}),f}return{id:l,etag:u,serverIdentity:{sitemapId:c}}},async update(e,t,r,n){var i;let a=r,o=(0,ie.normalizeGuid)(t,"id");if(!a.sitemapId)throw new Se.ValidationError("app",o,"/sitemapId","missing sitemap identity \u2014 re-fetch the app before pushing edits");let s=(0,ie.normalizeGuid)(a.sitemapId,"sitemapId");if(!n)throw new Se.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${o}': 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 l={"If-Match":n},u=`/sitemaps(${s})`,c=(0,Re.ensureSuccess)(await e.patch(u,{sitemapxml:a.sitemapxml,sitemapname:a.sitemapname},l?{headers:l}:void 0),e.apiUrl(u)),d=`/appmodules(${o})`;(0,Re.ensureSuccess)(await e.patch(d,{name:a.appModuleName,description:a.appModuleDescription}),e.apiUrl(d));let f=[];try{let h=await im(e,a);await am(e,o,h.components),await om(e,o,h.tables)}catch(h){f.push(`App '${o}': one or more components were not pinned (${h.message}). Navigation may reference content not included in the app; re-push to retry.`)}return{id:o,etag:(i=(0,Re.readEtag)(c))!==null&&i!==void 0?i:await sm(e,s),...f.length>0?{warnings:f}:{}}},async delete(e,t){let r=(0,ie.normalizeGuid)(t,"id");await pm(e,r,await cm(e,r))}}});var Ji=m(Pn=>{"use strict";function NP(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 Pu(e,t){return t===void 0&&(t=Object),t&&typeof t.freeze=="function"?t.freeze(e):e}function SP(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 fm=Pu({HTML:"text/html",isHTML:function(e){return e===fm.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),mm=Pu({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(e){return e===mm.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"});Pn.assign=SP;Pn.find=NP;Pn.freeze=Pu;Pn.MIME_TYPE=fm;Pn.NAMESPACE=mm});var $u=m(pr=>{var wm=Ji(),Gt=wm.find,Qi=wm.NAMESPACE;function DP(e){return e!==""}function EP(e){return e?e.split(/[\t\n\f\r ]+/).filter(DP):[]}function IP(e,t){return e.hasOwnProperty(t)||(e[t]=!0),e}function hm(e){if(!e)return[];var t=EP(e);return Object.keys(t.reduce(IP,{}))}function _P(e){return function(t){return e&&e.indexOf(t)!==-1}}function Ki(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function it(e,t){var r=e.prototype;if(!(r instanceof t)){let i=function(){};var n=i;i.prototype=t.prototype,i=new i,Ki(r,i),e.prototype=r=i}r.constructor!=e&&(typeof e!="function"&&console.error("unknown Class:"+e),r.constructor=e)}var at={},bt=at.ELEMENT_NODE=1,Tn=at.ATTRIBUTE_NODE=2,_o=at.TEXT_NODE=3,Nm=at.CDATA_SECTION_NODE=4,Sm=at.ENTITY_REFERENCE_NODE=5,PP=at.ENTITY_NODE=6,Ou=at.PROCESSING_INSTRUCTION_NODE=7,Tu=at.COMMENT_NODE=8,Dm=at.DOCUMENT_NODE=9,Em=at.DOCUMENT_TYPE_NODE=10,ur=at.DOCUMENT_FRAGMENT_NODE=11,OP=at.NOTATION_NODE=12,ze={},xe={},U9=ze.INDEX_SIZE_ERR=(xe[1]="Index size error",1),B9=ze.DOMSTRING_SIZE_ERR=(xe[2]="DOMString size error",2),nt=ze.HIERARCHY_REQUEST_ERR=(xe[3]="Hierarchy request error",3),k9=ze.WRONG_DOCUMENT_ERR=(xe[4]="Wrong document",4),TP=ze.INVALID_CHARACTER_ERR=(xe[5]="Invalid character",5),q9=ze.NO_DATA_ALLOWED_ERR=(xe[6]="No data allowed",6),$9=ze.NO_MODIFICATION_ALLOWED_ERR=(xe[7]="No modification allowed",7),Im=ze.NOT_FOUND_ERR=(xe[8]="Not found",8),V9=ze.NOT_SUPPORTED_ERR=(xe[9]="Not supported",9),gm=ze.INUSE_ATTRIBUTE_ERR=(xe[10]="Attribute in use",10),On=ze.INVALID_STATE_ERR=(xe[11]="Invalid state",11),G9=ze.SYNTAX_ERR=(xe[12]="Syntax error",12),z9=ze.INVALID_MODIFICATION_ERR=(xe[13]="Invalid modification",13),W9=ze.NAMESPACE_ERR=(xe[14]="Invalid namespace",14),j9=ze.INVALID_ACCESS_ERR=(xe[15]="Invalid access",15);function te(e,t){if(t instanceof Error)var r=t;else r=this,Error.call(this,xe[e]),this.message=xe[e],Error.captureStackTrace&&Error.captureStackTrace(this,te);return r.code=e,t&&(this.message=this.message+": "+t),r}te.prototype=Error.prototype;Ki(ze,te);function cr(){}cr.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++)qu(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 Rn(e,t){this._node=e,this._refresh=t,Ru(this)}function Ru(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!==t){var r=e._refresh(e._node);if(km(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];Ki(r,e),e._inc=t}}Rn.prototype.item=function(e){return Ru(this),this[e]||null};it(Rn,cr);function Po(){}function _m(e,t){for(var r=e.length;r--;)if(e[r]===t)return r}function vm(e,t,r,n){if(n?t[_m(t,n)]=r:t[t.length++]=r,e){r.ownerElement=e;var i=e.ownerDocument;i&&(n&&Tm(i,e,n),RP(i,e,r))}}function bm(e,t,r){var n=_m(t,r);if(n>=0){for(var i=t.length-1;n<i;)t[n]=t[++n];if(t.length=i,e){var a=e.ownerDocument;a&&(Tm(a,e,r),r.ownerElement=null)}}else throw new te(Im,new Error(e.tagName+"@"+r))}Po.prototype={length:0,item:cr.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 te(gm);var r=this.getNamedItem(e.nodeName);return vm(this._ownerElement,this,e,r),r},setNamedItemNS:function(e){var t=e.ownerElement,r;if(t&&t!=this._ownerElement)throw new te(gm);return r=this.getNamedItemNS(e.namespaceURI,e.localName),vm(this._ownerElement,this,e,r),r},removeNamedItem:function(e){var t=this.getNamedItem(e);return bm(this._ownerElement,this,t),t},removeNamedItemNS:function(e,t){var r=this.getNamedItemNS(e,t);return bm(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 Pm(){}Pm.prototype={hasFeature:function(e,t){return!0},createDocument:function(e,t,r){var n=new Yi;if(n.implementation=this,n.childNodes=new cr,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 Fo;return n.name=e,n.nodeName=e,n.publicId=t||"",n.systemId=r||"",n}};function Y(){}Y.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 To(this,e,t)},replaceChild:function(e,t){To(this,e,t,Fm),t&&this.removeChild(t)},removeChild:function(e){return Rm(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return Bm(this.ownerDocument||this,this,e)},normalize:function(){Fe(this,null,{enter:function(e){for(var t=e.firstChild;t;){var r=t.nextSibling;r!==null&&r.nodeType===_o&&t.nodeType===_o?(e.removeChild(r),t.appendData(r.data)):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==Tn?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==Tn?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){var t=this.lookupPrefix(e);return t==null}};function Om(e){return e=="<"&&"<"||e==">"&&">"||e=="&"&&"&"||e=='"'&&"""||"&#"+e.charCodeAt()+";"}Ki(at,Y);Ki(at,Y.prototype);function Oo(e,t){return Fe(e,null,{enter:function(r){return t(r)?Fe.STOP:!0}})===Fe.STOP}function Fe(e,t,r){for(var n=[{node:e,context:t,phase:Fe.ENTER}];n.length>0;){var i=n.pop();if(i.phase===Fe.ENTER){var a=r.enter(i.node,i.context);if(a===Fe.STOP)return Fe.STOP;if(n.push({node:i.node,context:a,phase:Fe.EXIT}),a==null)continue;for(var o=i.node.lastChild;o;)n.push({node:o,context:a,phase:Fe.ENTER}),o=o.previousSibling}else r.exit&&r.exit(i.node,i.context)}}Fe.STOP=Symbol("walkDOM.STOP");Fe.ENTER=0;Fe.EXIT=1;function Yi(){this.ownerDocument=this}function RP(e,t,r){e&&e._inc++;var n=r.namespaceURI;n===Qi.XMLNS&&(t._nsMap[r.prefix?r.localName:""]=r.value)}function Tm(e,t,r,n){e&&e._inc++;var i=r.namespaceURI;i===Qi.XMLNS&&delete t._nsMap[r.prefix?r.localName:""]}function Fu(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 Rm(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,Fu(e.ownerDocument,e),t}function FP(e){return e&&(e.nodeType===Y.DOCUMENT_NODE||e.nodeType===Y.DOCUMENT_FRAGMENT_NODE||e.nodeType===Y.ELEMENT_NODE)}function xP(e){return e&&(zt(e)||xu(e)||dr(e)||e.nodeType===Y.DOCUMENT_FRAGMENT_NODE||e.nodeType===Y.COMMENT_NODE||e.nodeType===Y.PROCESSING_INSTRUCTION_NODE)}function dr(e){return e&&e.nodeType===Y.DOCUMENT_TYPE_NODE}function zt(e){return e&&e.nodeType===Y.ELEMENT_NODE}function xu(e){return e&&e.nodeType===Y.TEXT_NODE}function ym(e,t){var r=e.childNodes||[];if(Gt(r,zt)||dr(t))return!1;var n=Gt(r,dr);return!(t&&n&&r.indexOf(n)>r.indexOf(t))}function Cm(e,t){var r=e.childNodes||[];function n(a){return zt(a)&&a!==t}if(Gt(r,n))return!1;var i=Gt(r,dr);return!(t&&i&&r.indexOf(i)>r.indexOf(t))}function LP(e,t,r){if(!FP(e))throw new te(nt,"Unexpected parent node type "+e.nodeType);if(r&&r.parentNode!==e)throw new te(Im,"child not in parent");if(!xP(t)||dr(t)&&e.nodeType!==Y.DOCUMENT_NODE)throw new te(nt,"Unexpected node type "+t.nodeType+" for parent node type "+e.nodeType)}function MP(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===Y.DOCUMENT_FRAGMENT_NODE){var a=i.filter(zt);if(a.length>1||Gt(i,xu))throw new te(nt,"More than one element or text in fragment");if(a.length===1&&!ym(e,r))throw new te(nt,"Element in fragment can not be inserted before doctype")}if(zt(t)&&!ym(e,r))throw new te(nt,"Only one element can be added and only after doctype");if(dr(t)){if(Gt(n,dr))throw new te(nt,"Only one doctype is allowed");var o=Gt(n,zt);if(r&&n.indexOf(o)<n.indexOf(r))throw new te(nt,"Doctype can only be inserted before an element");if(!r&&o)throw new te(nt,"Doctype can not be appended since element is present")}}function Fm(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===Y.DOCUMENT_FRAGMENT_NODE){var a=i.filter(zt);if(a.length>1||Gt(i,xu))throw new te(nt,"More than one element or text in fragment");if(a.length===1&&!Cm(e,r))throw new te(nt,"Element in fragment can not be inserted before doctype")}if(zt(t)&&!Cm(e,r))throw new te(nt,"Only one element can be added and only after doctype");if(dr(t)){let l=function(u){return dr(u)&&u!==r};var s=l;if(Gt(n,l))throw new te(nt,"Only one doctype is allowed");var o=Gt(n,zt);if(r&&n.indexOf(o)<n.indexOf(r))throw new te(nt,"Doctype can only be inserted before an element")}}function To(e,t,r,n){LP(e,t,r),e.nodeType===Y.DOCUMENT_NODE&&(n||MP)(e,t,r);var i=t.parentNode;if(i&&i.removeChild(t),t.nodeType===ur){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;Xi(a,l)}while(a!==o&&(a=a.nextSibling));return Fu(e.ownerDocument||e,e),t.nodeType==ur&&(t.firstChild=t.lastChild=null),t}function Xi(e,t){if(e.ownerDocument!==t){if(e.ownerDocument=t,e.nodeType===bt&&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;)Xi(i,t),i=i.nextSibling}}function UP(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,Fu(e.ownerDocument,e,t);var r=e.ownerDocument||e;return Xi(t,r),t}Yi.prototype={nodeName:"#document",nodeType:Dm,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==ur){for(var r=e.firstChild;r;){var n=r.nextSibling;this.insertBefore(r,t),r=n}return e}return To(this,e,t),Xi(e,this),this.documentElement===null&&e.nodeType===bt&&(this.documentElement=e),e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),Rm(this,e)},replaceChild:function(e,t){To(this,e,t,Fm),Xi(e,this),t&&this.removeChild(t),zt(e)&&(this.documentElement=e)},importNode:function(e,t){return BP(this,e,t)},getElementById:function(e){var t=null;return Oo(this.documentElement,function(r){if(r.nodeType==bt&&r.getAttribute("id")==e)return t=r,!0}),t},getElementsByClassName:function(e){var t=hm(e);return new Rn(this,function(r){var n=[];return t.length>0&&Oo(r.documentElement,function(i){if(i!==r&&i.nodeType===bt){var a=i.getAttribute("class");if(a){var o=e===a;if(!o){var s=hm(a);o=t.every(_P(s))}o&&n.push(i)}}}),n})},createElement:function(e){var t=new Kr;t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.localName=e,t.childNodes=new cr;var r=t.attributes=new Po;return r._ownerElement=t,t},createDocumentFragment:function(){var e=new xo;return e.ownerDocument=this,e.childNodes=new cr,e},createTextNode:function(e){var t=new Lu;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new Mu;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){if(e.indexOf("]]>")!==-1)throw new te(TP,'data contains "]]>"');var t=new Uu;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var r=new ku;return r.ownerDocument=this,r.tagName=r.nodeName=r.target=e,r.nodeValue=r.data=t,r},createAttribute:function(e){var t=new Ro;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){var t=new Bu;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var r=new Kr,n=t.split(":"),i=r.attributes=new Po;return r.childNodes=new cr,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 Ro,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}};it(Yi,Y);function Kr(){this._nsMap={}}Kr.prototype={nodeType:bt,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===ur?this.insertBefore(e,null):UP(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 Rn(this,function(t){var r=[];return Oo(t,function(n){n!==t&&n.nodeType==bt&&(e==="*"||n.tagName==e)&&r.push(n)}),r})},getElementsByTagNameNS:function(e,t){return new Rn(this,function(r){var n=[];return Oo(r,function(i){i!==r&&i.nodeType===bt&&(e==="*"||i.namespaceURI===e)&&(t==="*"||i.localName==t)&&n.push(i)}),n})}};Yi.prototype.getElementsByTagName=Kr.prototype.getElementsByTagName;Yi.prototype.getElementsByTagNameNS=Kr.prototype.getElementsByTagNameNS;it(Kr,Y);function Ro(){}Ro.prototype.nodeType=Tn;it(Ro,Y);function Zi(){}Zi.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(xe[nt])},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}};it(Zi,Y);function Lu(){}Lu.prototype={nodeName:"#text",nodeType:_o,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}};it(Lu,Zi);function Mu(){}Mu.prototype={nodeName:"#comment",nodeType:Tu};it(Mu,Zi);function Uu(){}Uu.prototype={nodeName:"#cdata-section",nodeType:Nm};it(Uu,Zi);function Fo(){}Fo.prototype.nodeType=Em;it(Fo,Y);function xm(){}xm.prototype.nodeType=OP;it(xm,Y);function Lm(){}Lm.prototype.nodeType=PP;it(Lm,Y);function Bu(){}Bu.prototype.nodeType=Sm;it(Bu,Y);function xo(){}xo.prototype.nodeName="#document-fragment";xo.prototype.nodeType=ur;it(xo,Y);function ku(){}ku.prototype.nodeType=Ou;it(ku,Y);function Mm(){}Mm.prototype.serializeToString=function(e,t,r,n){return Um.call(e,t,r,n)};Y.prototype.toString=Um;function Um(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 qu(this,i,e,t,l,n),i.join("")}function Am(e,t,r){var n=e.prefix||"",i=e.namespaceURI;if(!i||n==="xml"&&i===Qi.XML||i===Qi.XMLNS)return!1;for(var a=r.length;a--;){var o=r[a];if(o.prefix===n)return o.namespace!==i}return!0}function Io(e,t,r){e.push(" ",t,'="',r.replace(/[<>&"\t\n\r]/g,Om),'"')}function qu(e,t,r,n,i,a){i||(i=[]),Fe(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 bt:var c=o.attributes,d=c.length,f=o.tagName;u=Qi.isHTML(o.namespaceURI)||u;var h=f;if(!u&&!o.prefix&&o.namespaceURI){for(var b,w=0;w<c.length;w++)if(c.item(w).name==="xmlns"){b=c.item(w).value;break}if(!b)for(var N=l.length-1;N>=0;N--){var I=l[N];if(I.prefix===""&&I.namespace===o.namespaceURI){b=I.namespace;break}}if(b!==o.namespaceURI)for(var N=l.length-1;N>=0;N--){var I=l[N];if(I.namespace===o.namespaceURI){I.prefix&&(h=I.prefix+":"+f);break}}}t.push("<",h);for(var R=l.slice(),F=0;F<d;F++){var M=c.item(F);M.prefix=="xmlns"?R.push({prefix:M.localName,namespace:M.value}):M.nodeName=="xmlns"&&R.push({prefix:"",namespace:M.value})}for(var F=0;F<d;F++){var M=c.item(F);if(Am(M,u,R)){var W=M.prefix||"",B=M.namespaceURI;Io(t,W?"xmlns:"+W:"xmlns",B),R.push({prefix:W,namespace:B})}var j=n?n(M):M;j&&(typeof j=="string"?t.push(j):Io(t,j.name,j.value))}if(f===h&&Am(o,u,R)){var k=o.prefix||"",B=o.namespaceURI;Io(t,k?"xmlns:"+k:"xmlns",B),R.push({prefix:k,namespace:B})}var $=o.firstChild;if($||u&&!/^(?:meta|link|img|br|hr|input)$/i.test(f)){if(t.push(">"),u&&/^script$/i.test(f)){for(;$;)$.data?t.push($.data):qu($,t,u,n,R.slice(),a),$=$.nextSibling;return t.push("</",f,">"),null}return{ns:R,isHTML:u,tag:h}}else return t.push("/>"),null;case Dm:case ur:return{ns:l.slice(),isHTML:u,tag:null};case Tn:return Io(t,o.name,o.value),null;case _o:return t.push(o.data.replace(/[<&>]/g,Om)),null;case Nm:if(a&&o.data.indexOf("]]>")!==-1)throw new te(On,'The CDATASection data contains "]]>"');return t.push("<![CDATA[",o.data.replace(/]]>/g,"]]]]><![CDATA[>"),"]]>"),null;case Tu:if(a&&o.data.indexOf("-->")!==-1)throw new te(On,'The comment node data contains "-->"');return t.push("<!--",o.data,"-->"),null;case Em:if(a){if(o.publicId&&!/^("[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%']*"|'[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%'"]*')$/.test(o.publicId))throw new te(On,"DocumentType publicId is not a valid PubidLiteral");if(o.systemId&&!/^("[^"]*"|'[^']*')$/.test(o.systemId))throw new te(On,"DocumentType systemId is not a valid SystemLiteral");if(o.internalSubset&&o.internalSubset.indexOf("]>")!==-1)throw new te(On,'DocumentType internalSubset contains "]>"')}var re=o.publicId,H=o.systemId;if(t.push("<!DOCTYPE ",o.name),re)t.push(" PUBLIC ",re),H&&H!="."&&t.push(" ",H),t.push(">");else if(H&&H!=".")t.push(" SYSTEM ",H,">");else{var nr=o.internalSubset;nr&&t.push(" [",nr,"]"),t.push(">")}return null;case Ou:if(a&&o.data.indexOf("?>")!==-1)throw new te(On,'The ProcessingInstruction data contains "?>"');return t.push("<?",o.target," ",o.data,"?>"),null;case Sm: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 BP(e,t,r){var n;return Fe(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===Tn||r;return s?o:null}}),n}function Bm(e,t,r){var n;return Fe(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 cr),o.ownerDocument=e;var u=r;switch(o.nodeType){case bt:var c=i.attributes,d=o.attributes=new Po,f=c.length;d._ownerElement=o;for(var h=0;h<f;h++)o.setAttributeNode(Bm(e,c.item(h),!0));break;case Tn:u=!0}return a!==null?a.appendChild(o):n=o,u?o:null}}),n}function km(e,t,r){e[t]=r}try{Object.defineProperty&&(Object.defineProperty(Rn.prototype,"length",{get:function(){return Ru(this),this.$$length}}),Object.defineProperty(Y.prototype,"textContent",{get:function(){if(this.nodeType===bt||this.nodeType===ur){var e=[];return Fe(this,null,{enter:function(t){if(t.nodeType===bt||t.nodeType===ur)return!0;if(t.nodeType===Ou||t.nodeType===Tu)return null;e.push(t.nodeValue)}}),e.join("")}return this.nodeValue},set:function(e){switch(this.nodeType){case bt:case ur: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}}}),km=function(e,t,r){e["$$"+t]=r})}catch{}pr.DocumentType=Fo;pr.DOMException=te;pr.DOMImplementation=Pm;pr.Element=Kr;pr.Node=Y;pr.NodeList=cr;pr.walkDOM=Fe;pr.XMLSerializer=Mm});var $m=m(ea=>{"use strict";var qm=Ji().freeze;ea.XML_ENTITIES=qm({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});ea.HTML_ENTITIES=qm({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"});ea.entityMap=ea.HTML_ENTITIES});var Qm=m(Gu=>{var ia=Ji().NAMESPACE,Vu=/[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]/,Vm=new RegExp("[\\-\\.0-9"+Vu.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),Gm=new RegExp("^"+Vu.source+Vm.source+"*(?::"+Vu.source+Vm.source+"*)?$"),ta=0,Or=1,Fn=2,ra=3,xn=4,Ln=5,na=6,Lo=7;function Mn(e,t){this.message=e,this.locator=t,Error.captureStackTrace&&Error.captureStackTrace(this,Mn)}Mn.prototype=new Error;Mn.prototype.name=Mn.name;function jm(){}jm.prototype={parse:function(e,t,r){var n=this.domBuilder;n.startDocument(),Hm(t,t={}),kP(e,t,r,n,this.errorHandler),n.endDocument()}};function kP(e,t,r,n,i){function a(ue){if(ue>65535){ue-=65536;var rt=55296+(ue>>10),_l=56320+(ue&1023);return String.fromCharCode(rt,_l)}else return String.fromCharCode(ue)}function o(ue){var rt=ue.slice(1,-1);return Object.hasOwnProperty.call(r,rt)?r[rt]:rt.charAt(0)==="#"?a(parseInt(rt.substr(1).replace("x","0x"))):(i.error("entity not found:"+ue),ue)}function s(ue){if(ue>w){var rt=e.substring(w,ue).replace(/&#?\w+;/g,o);f&&l(w),n.characters(rt,0,ue-w),w=ue}}function l(ue,rt){for(;ue>=c&&(rt=d.exec(e));)u=rt.index,c=u+rt[0].length,f.lineNumber++;f.columnNumber=ue-u+1}for(var u=0,c=0,d=/.*(?:\r\n?|\n)|.*$/g,f=n.locator,h=[{currentNSMap:t}],b={},w=0;;){try{var N=e.indexOf("<",w);if(N<0){if(!e.substr(w).match(/^\s*$/)){var I=n.doc,R=I.createTextNode(e.substr(w));I.appendChild(R),n.currentElement=R}return}switch(N>w&&s(N),e.charAt(N+1)){case"/":var H=e.indexOf(">",N+3),F=e.substring(N+2,H).replace(/[ \t\n\r]+$/g,""),M=h.pop();H<0?(F=e.substring(N+2).replace(/[\s<].*/,""),i.error("end tag name: "+F+" is not complete:"+M.tagName),H=N+1+F.length):F.match(/\s</)&&(F=F.replace(/[\s<].*/,""),i.error("end tag name: "+F+" maybe not complete"),H=N+1+F.length);var W=M.localNSMap,B=M.tagName==F,j=B||M.tagName&&M.tagName.toLowerCase()==F.toLowerCase();if(j){if(n.endElement(M.uri,M.localName,F),W)for(var k in W)Object.prototype.hasOwnProperty.call(W,k)&&n.endPrefixMapping(k);B||i.fatalError("end tag name: "+F+" is not match the current start tagName:"+M.tagName)}else h.push(M);H++;break;case"?":f&&l(N),H=zP(e,N,n);break;case"!":f&&l(N),H=GP(e,N,n,i);break;default:f&&l(N);var $=new Jm,re=h[h.length-1].currentNSMap,H=qP(e,N,$,re,o,i),nr=$.length;if(!$.closed&&VP(e,H,$.tagName,b)&&($.closed=!0,r.nbsp||i.warning("unclosed xml attribute")),f&&nr){for(var Il=zm(f,{}),Oi=0;Oi<nr;Oi++){var io=$[Oi];l(io.offset),io.locator=zm(f,{})}n.locator=Il,Wm($,n,re)&&h.push($),n.locator=f}else Wm($,n,re)&&h.push($);ia.isHTML($.uri)&&!$.closed?H=$P(e,H,$.tagName,o,n):H++}}catch(ue){if(ue instanceof Mn)throw ue;i.error("element parse error: "+ue),H=-1}H>w?w=H:s(Math.max(N,w)+1)}}function zm(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function qP(e,t,r,n,i,a){function o(h,b,w){r.attributeNames.hasOwnProperty(h)&&a.fatalError("Attribute "+h+" redefined"),r.addValue(h,b.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,i),w)}for(var s,l,u=++t,c=ta;;){var d=e.charAt(u);switch(d){case"=":if(c===Or)s=e.slice(t,u),c=ra;else if(c===Fn)c=ra;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(c===ra||c===Or)if(c===Or&&(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=Ln;else throw new Error("attribute value no end '"+d+"' match");else if(c==xn)l=e.slice(t,u),o(s,l,t),a.warning('attribute "'+s+'" missed start quot('+d+")!!"),t=u+1,c=Ln;else throw new Error('attribute value must after "="');break;case"/":switch(c){case ta:r.setTagName(e.slice(t,u));case Ln:case na:case Lo:c=Lo,r.closed=!0;case xn:case Or:break;case Fn:r.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return a.error("unexpected end of input"),c==ta&&r.setTagName(e.slice(t,u)),u;case">":switch(c){case ta:r.setTagName(e.slice(t,u));case Ln:case na:case Lo:break;case xn:case Or:l=e.slice(t,u),l.slice(-1)==="/"&&(r.closed=!0,l=l.slice(0,-1));case Fn:c===Fn&&(l=s),c==xn?(a.warning('attribute "'+l+'" missed quot(")!'),o(s,l,t)):((!ia.isHTML(n[""])||!l.match(/^(?:disabled|checked|selected)$/i))&&a.warning('attribute "'+l+'" missed value!! "'+l+'" instead!!'),o(l,l,t));break;case ra:throw new Error("attribute value missed!!")}return u;case"\x80":d=" ";default:if(d<=" ")switch(c){case ta:r.setTagName(e.slice(t,u)),c=na;break;case Or:s=e.slice(t,u),c=Fn;break;case xn:var l=e.slice(t,u);a.warning('attribute "'+l+'" missed quot(")!!'),o(s,l,t);case Ln:c=na;break}else switch(c){case Fn:var f=r.tagName;(!ia.isHTML(n[""])||!s.match(/^(?:disabled|checked|selected)$/i))&&a.warning('attribute "'+s+'" missed value!! "'+s+'" instead2!!'),o(s,s,t),t=u,c=Or;break;case Ln:a.warning('attribute space is required"'+s+'"!!');case na:c=Or,t=u;break;case ra:c=xn,t=u;break;case Lo:throw new Error("elements closed character '/' and '>' must be connected to")}}u++}}function Wm(e,t,r){for(var n=e.tagName,i=null,d=e.length;d--;){var a=e[d],o=a.qName,s=a.value,f=o.indexOf(":");if(f>0)var l=a.prefix=o.slice(0,f),u=o.slice(f+1),c=l==="xmlns"&&u;else u=o,l=null,c=o==="xmlns"&&"";a.localName=u,c!==!1&&(i==null&&(i={},Hm(r,r={})),r[c]=i[c]=s,a.uri=ia.XMLNS,t.startPrefixMapping(c,s))}for(var d=e.length;d--;){a=e[d];var l=a.prefix;l&&(l==="xml"&&(a.uri=ia.XML),l!=="xmlns"&&(a.uri=r[l||""]))}var f=n.indexOf(":");f>0?(l=e.prefix=n.slice(0,f),u=e.localName=n.slice(f+1)):(l=null,u=e.localName=n);var h=e.uri=r[l||""];if(t.startElement(h,u,n,e),e.closed){if(t.endElement(h,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 $P(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 VP(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 Hm(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function GP(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=WP(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 zP(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 Jm(){this.attributeNames={}}Jm.prototype={setTagName:function(e){if(!Gm.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},addValue:function(e,t,r){if(!Gm.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 WP(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}Gu.XMLReader=jm;Gu.ParseError=Mn});var rh=m(Uo=>{var jP=Ji(),HP=$u(),Xm=$m(),Zm=Qm(),JP=HP.DOMImplementation,Km=jP.NAMESPACE,QP=Zm.ParseError,XP=Zm.XMLReader;function eh(e){return e.replace(/\r[\n\u0085]/g,`+`);if(f===-1)return;let h=p.slice(0,f),b=p.slice(f+4);if(!/^Content-Type:\s*application\/http\b/im.test(h))return;let w=/^HTTP\/1\.[01] (\d{3})\b/.exec(b);if(!w||((i=b.match(/^HTTP\/1\.[01] \d{3}\b/gm))!==null&&i!==void 0?i:[]).length!==1)return;let E=(a=/^Content-ID:\s*(\S+)/im.exec(h))===null||a===void 0?void 0:a[1];if(E===void 0||d.has(E)||!u.has(E))return;d.add(E),c.push(Number(w[1]))}return c.length===0?void 0:c}sn.parseChangeSetStatuses=Kh;async function Dx(e,t,r){if(t.length===0)return;let{body:n,batchId:i,contentIds:a}=Xh(e,t),o=await e.postBatch(n,i),s=e.apiUrl("/$batch");if((0,Ex.ensureSuccess)(o,s),typeof o.body!="string"||o.body.length===0)throw new Cs.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=Kh(o.body,a);if(l===void 0)throw new Cs.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 Cs.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 Cs.ConnectionError(s,u,`atomic write of ${r} was rolled back: the change set reported HTTP ${u}`)}sn.postChangeSet=Dx});var Ss=g(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.updateTable=Q.deleteAlternateKey=Q.createAlternateKey=Q.deleteGlobalOptionSet=Q.createGlobalOptionSet=Q.deleteRelationship=Q.deleteColumn=Q.updateColumn=Q.deleteTable=Q.createRelationship=Q.insertStatusValue=Q.createCustomerColumn=Q.createColumns=Q.setColumnVisualization=Q.getColumnVisualization=Q.createColumn=Q.createTable=Q.resolveEntitySetName=void 0;var re=he(),j=Z(),cr=fi(),Ze=le(),Ix=Hc(),_x={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 Ee(e,t){return{"@odata.type":"Microsoft.Dynamics.CRM.Label",LocalizedLabels:[{"@odata.type":"Microsoft.Dynamics.CRM.LocalizedLabel",Label:e,LanguageCode:t}]}}function Va(e){return{Value:e,CanBeChanged:!0,ManagedPropertyLogicalName:"canmodifyrequirementlevelsettings"}}function Xc(e){let t=e.indexOf("_");return t>0?e.slice(0,t):e}function Yh(e,t,r){let n=e[t];n&&typeof n=="object"?n.Value=r:e[t]={Value:r}}function Ga(e){let t=(0,re.readCreatedId)(e,"MetadataId");if(!t)throw new Ze.InvalidArgumentError("Dataverse did not return a MetadataId for the created metadata component");return t}function Px(e,t,r){var n,i,a,o,s,l,u,c,d,p,f,h,b,w,E,D,L,R,B,V,M,$;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:"None",MinValue:(o=t.minValue)!==null&&o!==void 0?o:-2147483648,MaxValue:(s=t.maxValue)!==null&&s!==void 0?s: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:(l=t.precision)!==null&&l!==void 0?l:2,MinValue:(u=t.minValue)!==null&&u!==void 0?u:-1e11,MaxValue:(c=t.maxValue)!==null&&c!==void 0?c:1e11};case"decimal":return{"@odata.type":"Microsoft.Dynamics.CRM.DecimalAttributeMetadata",AttributeType:"Decimal",AttributeTypeName:{Value:"DecimalType"},Precision:(d=t.precision)!==null&&d!==void 0?d:2,MinValue:(p=t.minValue)!==null&&p!==void 0?p:-1e11,MaxValue:(f=t.maxValue)!==null&&f!==void 0?f: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:(b=t.minValue)!==null&&b!==void 0?b:0,MaxValue:(w=t.maxValue)!==null&&w!==void 0?w:1e9};case"boolean":return{"@odata.type":"Microsoft.Dynamics.CRM.BooleanAttributeMetadata",AttributeType:"Boolean",AttributeTypeName:{Value:"BooleanType"},DefaultValue:!1,OptionSet:{"@odata.type":"Microsoft.Dynamics.CRM.BooleanOptionSetMetadata",TrueOption:{Value:1,Label:Ee((E=t.trueLabel)!==null&&E!==void 0?E:"Yes",r)},FalseOption:{Value:0,Label:Ee((D=t.falseLabel)!==null&&D!==void 0?D:"No",r)}}};case"dateTime":return{"@odata.type":"Microsoft.Dynamics.CRM.DateTimeAttributeMetadata",AttributeType:"DateTime",AttributeTypeName:{Value:"DateTimeType"},Format:(L=t.dateFormat)!==null&&L!==void 0?L:"DateAndTime"};case"choice":return Zh(t,r,!1);case"multiChoice":return Zh(t,r,!0);case"file":return{"@odata.type":"Microsoft.Dynamics.CRM.FileAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"FileType"},MaxSizeInKB:(R=t.maxSizeKb)!==null&&R!==void 0?R:10240};case"image":return{"@odata.type":"Microsoft.Dynamics.CRM.ImageAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"ImageType"},IsPrimaryImage:(B=t.isPrimaryImage)!==null&&B!==void 0?B:!1,MaxSizeInKB:(V=t.maxSizeKb)!==null&&V!==void 0?V:10240};case"autonumber":return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},FormatName:{Value:"Text"},MaxLength:(M=t.maxLength)!==null&&M!==void 0?M:100,AutoNumberFormat:($=t.autoNumberFormat)!==null&&$!==void 0?$:""};default:throw new Ze.InvalidArgumentError(`unsupported column type '${String(e)}'`)}}function Zh(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 Ze.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:Ee(a.label,t)}))},i}var Qc=new WeakMap;async function Tx(e,t){var r,n;let i=(r=Qc.get(e))===null||r===void 0?void 0:r.get(t);if(i)return i;let a=`/EntityDefinitions(LogicalName='${(0,j.odataLiteral)(t)}')${(0,j.odataQuery)([["$select","EntitySetName"]])}`,s=(n=(0,re.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.EntitySetName;if(!s)throw new Ze.InvalidArgumentError(`could not resolve EntitySetName for '${t}'`);(0,j.assertODataName)(s,`server-derived EntitySetName for '${t}'`);let l=Qc.get(e);return l||(l=new Map,Qc.set(e,l)),l.set(t,s),s}Q.resolveEntitySetName=Tx;async function Ox(e,t){var r,n,i,a,o,s,l,u,c,d,p,f,h,b,w;let E=(r=t.languageCode)!==null&&r!==void 0?r:cr.DEFAULT_LCID,D=Xc(t.schemaName),L=(n=t.primaryColumnSchemaName)!==null&&n!==void 0?n:`${D}_Name`,R={"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},SchemaName:L,RequiredLevel:Va("None"),MaxLength:(i=t.primaryColumnMaxLength)!==null&&i!==void 0?i:100,FormatName:{Value:"Text"},DisplayName:Ee((a=t.primaryColumnDisplayName)!==null&&a!==void 0?a:"Name",E),IsPrimaryName:!0};t.primaryColumnAutoNumberFormat&&(R.AutoNumberFormat=t.primaryColumnAutoNumberFormat),t.columns&&rg(t.columns,"createTable");let B={"@odata.type":"Microsoft.Dynamics.CRM.EntityMetadata",SchemaName:t.schemaName,DisplayName:Ee(t.displayName,E),DisplayCollectionName:Ee((o=t.pluralName)!==null&&o!==void 0?o:`${t.displayName}s`,E),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:[R,...((c=t.columns)!==null&&c!==void 0?c:[]).map(Ue=>Kc(Ue,E))]};t.description&&(B.Description=Ee(t.description,E));let V="/EntityDefinitions",M=(0,re.ensureSuccess)(await e.post(V,B),e.apiUrl(V)),$=Ga(M),G=`/EntityDefinitions(${$})`+(0,j.odataQuery)([["$select","LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute"]]),X=Math.max(1,Math.trunc((d=t.readBackAttempts)!==null&&d!==void 0?d:6)),U=Math.max(0,(p=t.readBackDelayMs)!==null&&p!==void 0?p:1e3),Oe;for(let Ue=1;Ue<=X;Ue+=1){let He=await e.get(G);if(He.status>=200&&He.status<300){Oe=He;break}He.status!==404&&(0,re.ensureSuccess)(He,e.apiUrl(G)),Ue<X&&U>0&&await new Promise(ue=>setTimeout(ue,U))}if(!Oe)throw new Ze.SdkError("TABLE_METADATA_NOT_VISIBLE",`Table '${t.schemaName}' WAS CREATED (MetadataId ${$}) but its metadata was still not readable after ${X} attempt(s). Do NOT re-run the create \u2014 it will collide on the schema name. Re-read /EntityDefinitions(${$}) once the environment catches up, or raise 'readBackAttempts'.`);let me=Oe.body;return{logicalName:(f=me.LogicalName)!==null&&f!==void 0?f:t.schemaName.toLowerCase(),metadataId:$,entitySetName:(h=me.EntitySetName)!==null&&h!==void 0?h:"",primaryIdAttribute:(b=me.PrimaryIdAttribute)!==null&&b!==void 0?b:`${t.schemaName.toLowerCase()}id`,primaryNameAttribute:(w=me.PrimaryNameAttribute)!==null&&w!==void 0?w:L.toLowerCase()}}Q.createTable=Ox;function Kc(e,t){var r,n;let i=(r=e.languageCode)!==null&&r!==void 0?r:t,a={...Px(e.type,e,i),SchemaName:e.schemaName,RequiredLevel:Va((n=e.required)!==null&&n!==void 0?n:"None"),DisplayName:Ee(e.displayName,i)};return e.description&&(a.Description=Ee(e.description,i)),e.sourceType&&e.sourceType!=="Simple"&&(a.SourceType=e.sourceType==="Rollup"?2:1,e.formulaDefinition&&(a.FormulaDefinition=e.formulaDefinition)),a}async function xx(e,t,r){var n;let i=Kc(r,(n=r.languageCode)!==null&&n!==void 0?n:cr.DEFAULT_LCID),a=`/EntityDefinitions(LogicalName='${(0,j.odataLiteral)(t)}')/Attributes`,o=(0,re.ensureSuccess)(await e.post(a,i),e.apiUrl(a)),s={logicalName:r.schemaName.toLowerCase(),metadataId:Ga(o)};if(r.visualization&&r.visualization!=="None")try{await ag(e,t,s.logicalName,s.metadataId,r.visualization)}catch(l){let u=new Ze.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}Q.createColumn=xx;var hi="/controlconfigurations",tg="CustomRenderersConfiguration",Jc={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 rg(e,t){let r=e.find(n=>n.visualization&&n.visualization!=="None");if(r)throw new Ze.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 ng(e){return JSON.stringify({type:Jc[e]})}function Rx(e){if(!e)return"None";let t;try{t=JSON.parse(e)}catch{return"None"}let r=t?.type,n=Object.keys(Jc).find(i=>Jc[i]===r);return n??"None"}async function ig(e,t,r){var n,i;let a=`entitylogicalname eq '${(0,j.odataLiteral)(t)}' and Attribute/logicalname eq '${(0,j.odataLiteral)(r)}'`,o=`${hi}${(0,j.odataQuery)([["$select","name,uniquename,metadatajson"],["$expand","Attribute($select=name,logicalname)"],["$filter",a]])}`,l=(i=(n=(0,re.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 Lx(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,j.odataLiteral)(t)}')/Attributes(LogicalName='${(0,j.odataLiteral)(r)}')${(0,j.odataQuery)([["$select","MetadataId"]])}`,o=(n=(0,re.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||n===void 0?void 0:n.MetadataId;if(!o)throw new Ze.InvalidArgumentError(`cannot resolve column '${r}' on '${t}' to set its visualization`);return(0,j.normalizeGuid)(o,"MetadataId")}async function ag(e,t,r,n,i){let a={name:tg,uniquename:`msdyn_${t}_${r}_customrenderers`,metadatajson:ng(i),"[email protected]":`/attributes(${(0,j.normalizeGuid)(n,"MetadataId")})`,entitylogicalname:t};(0,re.ensureSuccess)(await e.post(hi,a),e.apiUrl(hi))}async function Fx(e,t,r){var n;let i=await ig(e,t,r);return Rx((n=i[0])===null||n===void 0?void 0:n.metadatajson)}Q.getColumnVisualization=Fx;async function kx(e,t,r,n){let a=(await ig(e,t,r)).map(u=>u.controlconfigurationid).filter(u=>!!u);if(n==="None"){for(let u of a){let c=`${hi}(${(0,j.normalizeGuid)(u,"controlconfigurationid")})`;(0,re.ensureSuccess)(await e.delete(c),e.apiUrl(c))}return}let[o,...s]=a,l=await Lx(e,t,r);if(o){let u=`${hi}(${(0,j.normalizeGuid)(o,"controlconfigurationid")})`,c={name:tg,metadatajson:ng(n),"[email protected]":`/attributes(${l})`,entitylogicalname:t};(0,re.ensureSuccess)(await e.patch(u,c),e.apiUrl(u))}else await ag(e,t,r,l,n);for(let u of s){let c=`${hi}(${(0,j.normalizeGuid)(u,"controlconfigurationid")})`;(0,re.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}Q.setColumnVisualization=kx;async function Mx(e,t,r){if(r.length===0)return;if(rg(r,"createColumns"),!e.supportsAtomicBatch)throw new Ze.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.odataLiteral)(t)}')/Attributes`;await(0,Ix.postChangeSet)(e,r.map(i=>{var a;return{method:"POST",path:n,body:Kc(i,(a=i.languageCode)!==null&&a!==void 0?a:cr.DEFAULT_LCID)}}),`${r.length} column(s) on '${t}'`)}Q.createColumns=Mx;async function Ux(e,t,r){var n,i,a,o;let s=(n=r.languageCode)!==null&&n!==void 0?n:cr.DEFAULT_LCID,l=Xc(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:Ee(r.displayName,s),RequiredLevel:Va((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,re.ensureSuccess)(await e.post("/CreateCustomerRelationships",d),e.apiUrl("/CreateCustomerRelationships")),{logicalName:r.schemaName.toLowerCase(),metadataId:""}}Q.createCustomerColumn=Ux;async function Bx(e,t,r){var n,i,a,o,s;let l=(n=r.languageCode)!==null&&n!==void 0?n:cr.DEFAULT_LCID,u={EntityLogicalName:t,AttributeLogicalName:"statuscode",Label:Ee(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,re.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)}Q.insertStatusValue=Bx;async function $x(e,t){var r,n,i,a,o;let s=(r=t.languageCode)!==null&&r!==void 0?r:cr.DEFAULT_LCID,l,u;if(t.type==="OneToMany"){if(!t.referencedEntity||!t.referencingEntity)throw new Ze.InvalidArgumentError("OneToMany relationship requires referencedEntity and referencingEntity");let p=(n=t.lookupSchemaName)!==null&&n!==void 0?n:`${Xc(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:Va((i=t.lookupRequired)!==null&&i!==void 0?i:"None"),DisplayName:Ee((a=t.lookupDisplayName)!==null&&a!==void 0?a:t.referencedEntity,s)}}}else{if(!t.entity1||!t.entity2)throw new Ze.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,re.ensureSuccess)(await e.post(c,l),e.apiUrl(c));return{schemaName:t.schemaName,metadataId:Ga(d),lookupLogicalName:u}}Q.createRelationship=$x;async function qx(e,t){let r=`/EntityDefinitions(LogicalName='${(0,j.odataLiteral)(t)}')`;(0,re.ensureSuccess)(await e.delete(r),e.apiUrl(r))}Q.deleteTable=qx;async function Vx(e,t,r,n){var i,a;let o=(i=n.languageCode)!==null&&i!==void 0?i:cr.DEFAULT_LCID,s=`/EntityDefinitions(LogicalName='${(0,j.odataLiteral)(t)}')/Attributes`,l=`${s}(LogicalName='${(0,j.odataLiteral)(r)}')${(0,j.odataQuery)([["$select","MetadataId,AttributeType"]])}`,c=(0,re.ensureSuccess)(await e.get(l),e.apiUrl(l)).body,d=_x[(a=c.AttributeType)!==null&&a!==void 0?a:""];if(!c.MetadataId||!d)throw new Ze.InvalidArgumentError(`cannot update column '${r}' on '${t}' (type '${c.AttributeType}' not supported)`);let p=(0,j.normalizeGuid)(c.MetadataId,"MetadataId"),f=`${s}(${p})/${d}`,h=(0,re.ensureSuccess)(await e.get(f),e.apiUrl(f)).body;for(let w of Object.keys(h))w.startsWith("@odata.")&&delete h[w];h["@odata.type"]=d,n.displayName!==void 0&&(h.DisplayName=Ee(n.displayName,o)),n.description!==void 0&&(h.Description=Ee(n.description,o)),n.required!==void 0&&(h.RequiredLevel=Va(n.required)),n.maxLength!==void 0&&(h.MaxLength=n.maxLength),n.autoNumberFormat!==void 0&&(h.AutoNumberFormat=n.autoNumberFormat);let b=`${s}(${p})`;(0,re.ensureSuccess)(await e.put(b,h,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(b))}Q.updateColumn=Vx;async function Gx(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,j.odataLiteral)(t)}')/Attributes`,a=`${i}(LogicalName='${(0,j.odataLiteral)(r)}')${(0,j.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,re.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new Ze.InvalidArgumentError(`column '${r}' not found on '${t}'`);let l=`${i}(${(0,j.normalizeGuid)(s,"MetadataId")})`;(0,re.ensureSuccess)(await e.delete(l),e.apiUrl(l))}Q.deleteColumn=Gx;async function zx(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,re.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 Ze.InvalidArgumentError(`relationship '${t}' not found`);let l=`/RelationshipDefinitions(${(0,j.normalizeGuid)(s,"MetadataId")})`;(0,re.ensureSuccess)(await e.delete(l),e.apiUrl(l))}Q.deleteRelationship=zx;async function eg(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,re.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 Wx(e,t){var r;let n=t.name.toLowerCase(),i=await eg(e,n);if(i)return{name:n,metadataId:i};let a=(r=t.languageCode)!==null&&r!==void 0?r:cr.DEFAULT_LCID,o={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",Name:n,DisplayName:Ee(t.displayName,a),IsGlobal:!0,OptionSetType:"Picklist",Options:t.options.map(l=>({Value:l.value,Label:Ee(l.label,a)}))};t.description&&(o.Description=Ee(t.description,a));let s="/GlobalOptionSetDefinitions";try{let l=(0,re.ensureSuccess)(await e.post(s,o),e.apiUrl(s));return{name:n,metadataId:Ga(l)}}catch(l){let u;try{u=await eg(e,n)}catch{u=void 0}if(u)return{name:n,metadataId:u};throw l}}Q.createGlobalOptionSet=Wx;async function jx(e,t){let r=`/GlobalOptionSetDefinitions(Name='${(0,j.odataLiteral)(t.toLowerCase())}')`;(0,re.ensureSuccess)(await e.delete(r),e.apiUrl(r))}Q.deleteGlobalOptionSet=jx;async function Hx(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:cr.DEFAULT_LCID,a={"@odata.type":"Microsoft.Dynamics.CRM.EntityKeyMetadata",SchemaName:r.schemaName,DisplayName:Ee(r.displayName,i),KeyAttributes:r.keyAttributes},o=`/EntityDefinitions(LogicalName='${(0,j.odataLiteral)(t)}')/Keys`,s=(0,re.ensureSuccess)(await e.post(o,a),e.apiUrl(o));return{logicalName:r.schemaName.toLowerCase(),metadataId:Ga(s)}}Q.createAlternateKey=Hx;async function Qx(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,j.odataLiteral)(t)}')/Keys`,a=`${i}(LogicalName='${(0,j.odataLiteral)(r.toLowerCase())}')${(0,j.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,re.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new Ze.InvalidArgumentError(`alternate key '${r}' not found on '${t}'`);let l=`${i}(${(0,j.normalizeGuid)(s,"MetadataId")})`;(0,re.ensureSuccess)(await e.delete(l),e.apiUrl(l))}Q.deleteAlternateKey=Qx;async function Jx(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:cr.DEFAULT_LCID,a=`/EntityDefinitions(LogicalName='${(0,j.odataLiteral)(t)}')`,s=(0,re.ensureSuccess)(await e.get(a),e.apiUrl(a)).body,l=s.MetadataId;if(!l)throw new Ze.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=Ee(r.displayName,i)),r.pluralName!==void 0&&(s.DisplayCollectionName=Ee(r.pluralName,i)),r.description!==void 0&&(s.Description=Ee(r.description,i)),r.auditEnabled!==void 0&&Yh(s,"IsAuditEnabled",r.auditEnabled),r.duplicateDetectionEnabled!==void 0&&Yh(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,re.ensureSuccess)(await e.put(c,s,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(c))}Q.updateTable=Jx});var Xt=g(gi=>{"use strict";Object.defineProperty(gi,"__esModule",{value:!0});gi.describeMalformedValue=gi.collectPages=void 0;var og=he(),Yc=le();async function Xx(e,t,r){let n=[],i=new Set,a=e.apiUrl(t),o=(0,og.ensureSuccess)(await e.get(t),a);for(;;){let s=o.body,l=s?.value;if(!Array.isArray(l))throw new Yc.ConnectionError(a,o.status,`${r}: paginated read returned a malformed page \u2014 expected an OData 'value' array but got ${Zc(l)}; refusing to return partial results.`);for(let c of l)n.push(c);let u=s?.["@odata.nextLink"];if(u==null)break;if(typeof u!="string"||u.length===0)throw new Yc.ConnectionError(a,o.status,`${r}: paginated read returned a malformed @odata.nextLink (${Zc(u)}); cannot follow it, and refusing to return partial results.`);if(i.has(u))throw new Yc.InvalidArgumentError(`${r}: aborting pagination \u2014 the server returned a repeated @odata.nextLink ('${u}'), which would loop indefinitely.`);i.add(u),a=u,o=(0,og.ensureSuccess)(await e.getAbsolute(u),u)}return n}gi.collectPages=Xx;function Zc(e){return e===null?"null":e===void 0?"undefined (missing)":`a ${typeof e}`}gi.describeMalformedValue=Zc});var Ds=g(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.disassociateRecords=Ae.associateRecords=Ae.createRecordsBulk=Ae.upsertRecord=Ae.queryAllRecords=Ae.queryRecords=Ae.getRecord=Ae.deleteRecord=Ae.updateRecord=Ae.createRecord=void 0;var Kx=Xt(),Kt=he(),et=Z(),Ns=le(),dr=Ss();function Es(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 Yx(e,t,r){let i=`/${await(0,dr.resolveEntitySetName)(e,t)}`,a=(0,Kt.ensureSuccess)(await e.post(i,Es(r)),e.apiUrl(i)),o=(0,Kt.readCreatedId)(a,`${t}id`);if(!o)throw new Ns.InvalidArgumentError(`Dataverse did not return an id for the created '${t}' row`);return{id:o,entityType:t}}Ae.createRecord=Yx;async function Zx(e,t,r,n){let i=(0,et.normalizeGuid)(r,"id"),o=`/${await(0,dr.resolveEntitySetName)(e,t)}(${i})`;(0,Kt.ensureSuccess)(await e.patch(o,Es(n)),e.apiUrl(o))}Ae.updateRecord=Zx;async function eR(e,t,r){let n=(0,et.normalizeGuid)(r,"id"),a=`/${await(0,dr.resolveEntitySetName)(e,t)}(${n})`;(0,Kt.ensureSuccess)(await e.delete(a),e.apiUrl(a))}Ae.deleteRecord=eR;async function tR(e,t,r,n){var i;let a=(0,et.normalizeGuid)(r,"id"),o=await(0,dr.resolveEntitySetName)(e,t),s=(0,et.odataQuery)([["$select",n&&n.length>0?n.join(","):void 0]]),l=`/${o}(${a})${s}`;return(i=(0,Kt.ensureSuccess)(await e.get(l),e.apiUrl(l)).body)!==null&&i!==void 0?i:{}}Ae.getRecord=tR;function rR(e){return e?.fetchXml?(0,et.odataQuery)([["fetchXml",e.fetchXml]]):(0,et.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 sg(e,t,r){var n,i;if(r?.paginate){if(r.top!==void 0)throw new Ns.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 Ns.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,dr.resolveEntitySetName)(e,t)}${rR(r)}`;return r?.paginate?(0,Kx.collectPages)(e,o,"queryRecords"):(i=(n=(0,Kt.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]}Ae.queryRecords=sg;async function nR(e,t,r){return sg(e,t,{...r,paginate:!0})}Ae.queryAllRecords=nR;function iR(e){if("id"in e)return`(${(0,et.normalizeGuid)(e.id,"id")})`;let t=typeof e.value=="string"?`'${(0,et.odataPathLiteral)(e.value)}'`:e.value;return`(${(0,et.assertODataName)(e.key,"alternate key name")}=${t})`}async function aR(e,t,r,n){let i=iR(r),o=`/${await(0,dr.resolveEntitySetName)(e,t)}${i}`,s=(0,Kt.ensureSuccess)(await e.patch(o,Es(n)),e.apiUrl(o)),l=s.status===201,u=(0,Kt.readCreatedId)(s,`${t}id`);return{id:u??("id"in r?(0,et.normalizeGuid)(r.id,"id"):""),created:l}}Ae.upsertRecord=aR;async function oR(e,t,r){var n,i;if(r.length===0)return[];let a=await(0,dr.resolveEntitySetName)(e,t),o=r.map(c=>({"@odata.type":`Microsoft.Dynamics.CRM.${t}`,...Es(c)})),s=`/${a}/Microsoft.Dynamics.CRM.CreateMultiple`,u=(i=(n=(0,Kt.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 Ns.InvalidArgumentError(`CreateMultiple on '${t}' returned ${u.length} id(s) for ${r.length} row(s)`);return u}Ae.createRecordsBulk=oR;async function sR(e,t,r,n){let i=(0,et.normalizeGuid)(r,"id"),a=(0,et.normalizeGuid)(n.targetId,"targetId"),o=await(0,dr.resolveEntitySetName)(e,t),s=await(0,dr.resolveEntitySetName)(e,n.targetEntity),l=(0,et.assertODataName)(n.relationshipName,"relationshipName"),u=`/${o}(${i})/${l}/$ref`,c={"@odata.id":e.apiUrl(`/${s}(${a})`)};(0,Kt.ensureSuccess)(await e.post(u,c),e.apiUrl(u))}Ae.associateRecords=sR;async function lR(e,t,r,n,i){let a=(0,et.normalizeGuid)(r,"id"),o=(0,et.normalizeGuid)(i,"targetId"),s=await(0,dr.resolveEntitySetName)(e,t),l=(0,et.assertODataName)(n,"relationshipName"),u=`/${s}(${a})/${l}(${o})/$ref`;(0,Kt.ensureSuccess)(await e.delete(u),e.apiUrl(u))}Ae.disassociateRecords=lR});var Yt=g(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.publishBoundEntity=Be.boundEntityPublishScope=Be.publishGenPageById=Be.publishDashboardById=Be.publishWebResourceById=Be.publishEntity=Be.publishAppModule=Be.publishXml=void 0;var uR=he(),za=Z(),lg="/PublishXml";async function vi(e,t){(0,uR.ensureSuccess)(await e.post(lg,{ParameterXml:t}),e.apiUrl(lg))}Be.publishXml=vi;function cR(e,t){return vi(e,`<importexportxml><appmodules><appmodule>${(0,za.xmlText)(t)}</appmodule></appmodules></importexportxml>`)}Be.publishAppModule=cR;function ug(e,t){return vi(e,`<importexportxml><entities><entity>${(0,za.xmlText)(t)}</entity></entities></importexportxml>`)}Be.publishEntity=ug;function dR(e,t){return vi(e,`<importexportxml><webresources><webresource>${(0,za.xmlText)(t)}</webresource></webresources></importexportxml>`)}Be.publishWebResourceById=dR;function pR(e,t){return vi(e,`<importexportxml><dashboards><dashboard>${(0,za.xmlText)(t)}</dashboard></dashboards></importexportxml>`)}Be.publishDashboardById=pR;function fR(e,t){return vi(e,`<importexportxml><uxagentprojects><uxagentproject>${(0,za.xmlText)(t)}</uxagentproject></uxagentprojects></importexportxml>`)}Be.publishGenPageById=fR;function mR(e){let t=e?.entityLogicalName;return t?{envelope:"entity",entityLogicalName:t,blastRadiusWarning:"ENTITY_ENVELOPE_ALSO_SHIPS_UNRELATED_UNPUBLISHED_CHANGES"}:{envelope:"entity"}}Be.boundEntityPublishScope=mR;function hR(e,t){let r=t?.entityLogicalName;return r?ug(e,r):Promise.resolve()}Be.publishBoundEntity=hR});var pg=g(pr=>{"use strict";Object.defineProperty(pr,"__esModule",{value:!0});pr.deleteWebResource=pr.getWebResource=pr.updateWebResource=pr.createWebResource=void 0;var gR=Yt(),Wa=he(),Is=Z(),ed=le(),vR={html:1,css:2,js:3,xml:4,png:5,jpg:6,gif:7,xsl:9,ico:10,svg:11,resx:12};function yR(e){let t=globalThis;if(t.Buffer)return t.Buffer.from(e,"utf8").toString("base64");if(t.btoa){let r=globalThis.TextEncoder;if(r){let n=new r().encode(e),i="",a=32768;for(let o=0;o<n.length;o+=a)i+=String.fromCharCode(...n.subarray(o,o+a));return t.btoa(i)}return t.btoa(e)}throw new ed.InvalidArgumentError("no base64 encoder available; pass contentBase64 instead of content")}function cg(e){if(e.contentBase64!==void 0)return e.contentBase64;if(e.content!==void 0)return yR(e.content)}async function dg(e,t){return(0,gR.publishWebResourceById)(e,t)}async function bR(e,t){var r;let n=cg(t);if(n===void 0)throw new ed.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:vR[t.type],content:n};t.description&&(i.description=t.description);let a=(0,Wa.ensureSuccess)(await e.post("/webresourceset",i),e.apiUrl("/webresourceset")),o=(0,Wa.readCreatedId)(a,"webresourceid");if(!o)throw new ed.InvalidArgumentError(`Dataverse did not return an id for web resource '${t.name}'`);return t.publish!==!1&&await dg(e,o),{id:o,name:t.name}}pr.createWebResource=bR;async function wR(e,t,r){let n=(0,Is.normalizeGuid)(t,"id"),i={},a=cg(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,Wa.ensureSuccess)(await e.patch(o,i),e.apiUrl(o)),r.publish!==!1&&await dg(e,n)}pr.updateWebResource=wR;async function AR(e,t){var r;let i=`/webresourceset(${(0,Is.normalizeGuid)(t,"id")})${(0,Is.odataQuery)([["$select","name,displayname,webresourcetype,content,description"]])}`;return(r=(0,Wa.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)!==null&&r!==void 0?r:{}}pr.getWebResource=AR;async function CR(e,t){let n=`/webresourceset(${(0,Is.normalizeGuid)(t,"id")})`;(0,Wa.ensureSuccess)(await e.delete(n),e.apiUrl(n))}pr.deleteWebResource=CR});var _s=g($e=>{"use strict";Object.defineProperty($e,"__esModule",{value:!0});$e.applyAppSettings=$e.setAppSetting=$e.readAppSettings=$e.resolveSettingDefinitions=$e.APP_SETTING_UNSET=$e.APP_SETTING_OFF=$e.APP_SETTING_ON=$e.HEADER_AND_NAVIGATION_REFRESH=void 0;var yi=he(),kr=Z();$e.HEADER_AND_NAVIGATION_REFRESH="HeaderAndNavigationRefresh";$e.APP_SETTING_ON="2";$e.APP_SETTING_OFF="1";$e.APP_SETTING_UNSET="0";function hg(e,t){return"/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,kr.odataQuery)([["$select",e],["$filter",t]])}async function gg(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,kr.odataLiteral)(c)}'`).join(" or "),s=`/settingdefinitions${(0,kr.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",o]])}`,u=((n=(r=(0,yi.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}$e.resolveSettingDefinitions=gg;async function SR(e,t){var r,n,i,a;let o=(0,kr.normalizeGuid)(t,"App id"),s=hg("appsettingid,value,_settingdefinitionid_value",`_parentappmoduleid_value eq ${o}`),u=((n=(r=(0,yi.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(b=>`settingdefinitionid eq ${(0,kr.normalizeGuid)(b,"Setting definition id")}`).join(" or "),f=`/settingdefinitions${(0,kr.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",p]])}`,h=(0,yi.ensureSuccess)(await e.get(f),e.apiUrl(f));for(let b of((a=(i=h.body)===null||i===void 0?void 0:i.value)!==null&&a!==void 0?a:[]).filter(Boolean))b.settingdefinitionid&&d.set(b.settingdefinitionid.toLowerCase(),b)}return u.map(p=>{var f,h,b,w,E;let D=d.get(((f=p._settingdefinitionid_value)!==null&&f!==void 0?f:"").toLowerCase());return{id:(h=p.appsettingid)!==null&&h!==void 0?h:"",name:(w=(b=D?.uniquename)!==null&&b!==void 0?b:p._settingdefinitionid_value)!==null&&w!==void 0?w:"",value:(E=p.value)!==null&&E!==void 0?E:"",...D?.displayname?{displayName:D.displayname}:{}}})}$e.readAppSettings=SR;async function fg(e,t,r){var n,i,a;let o=hg("appsettingid,value",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${r}`),l=((i=(n=(0,yi.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 vg(e,t,r,n){let i=(0,kr.normalizeGuid)(t,"App id"),o=(await gg(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,kr.normalizeGuid)(s,"Setting definition id"),u=await fg(e,i,l);if(u)return mg(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(b){f=b}let h;try{h=await fg(e,i,l)}catch{h=void 0}if(h)return mg(e,h,n);throw p&&(0,yi.ensureSuccess)(p,e.apiUrl(c)),f}$e.setAppSetting=vg;async function mg(e,t,r){if(t.value===r)return"unchanged";let n=`/appsettings(${(0,kr.normalizeGuid)(t.id,"App setting id")})`;return(0,yi.ensureSuccess)(await e.patch(n,{value:r}),e.apiUrl(n)),"updated"}async function NR(e,t,r){var n;let i=[];for(let[a,o]of Object.entries(r??{}))try{await vg(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}$e.applyAppSettings=NR});var Ts=g(Ps=>{"use strict";Object.defineProperty(Ps,"__esModule",{value:!0});Ps.HEADER_NAV_BOOLEAN_RULE=void 0;Ps.HEADER_NAV_BOOLEAN_RULE="headerAndNavigationRefresh-must-be-boolean"});var bg=g(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.deleteSolution=Y.importSolution=Y.exportSolution=Y.removeSolutionComponent=Y.addSolutionComponent=Y.setSolutionVersion=Y.createSolution=Y.createPublisher=Y.getSolution=Y.fetchSolutionComponents=Y.SolutionComponentType=void 0;var yg=Xt(),Zt=he(),ht=Z(),Un=le();Y.SolutionComponentType={SavedQuery:26,Workflow:29,SavedQueryVisualization:59,SystemForm:60,AppModule:80,UxAgentProject:10372};var ER=[Y.SolutionComponentType.SavedQuery,Y.SolutionComponentType.Workflow,Y.SolutionComponentType.SavedQueryVisualization,Y.SolutionComponentType.SystemForm,Y.SolutionComponentType.AppModule,Y.SolutionComponentType.UxAgentProject];async function DR(e,t){let r=(0,ht.normalizeGuid)(t,"solutionId"),n=ER.map(s=>`msdyn_componenttype eq ${s}`).join(" or "),i=`/msdyn_solutioncomponentsummaries${(0,ht.odataQuery)([["$select","msdyn_objectid,msdyn_componenttype,msdyn_workflowcategory,msdyn_displayname,msdyn_name"],["$filter",`msdyn_solutionid eq ${r} and (${n})`]])}`,o=(await(0,yg.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 IR(e,r,o)]}Y.fetchSolutionComponents=DR;async function IR(e,t,r){let n=new Set(r.map(s=>s.objectId.toLowerCase())),i=`/solutioncomponents${(0,ht.odataQuery)([["$select","objectid,componenttype"],["$filter",`_solutionid_value eq ${t} and componenttype eq ${Y.SolutionComponentType.UxAgentProject}`]])}`,a=await(0,yg.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:Y.SolutionComponentType.UxAgentProject}))}return o}function _R(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 PR(e,t){var r,n,i,a,o,s,l,u,c,d;let p=String(t??"").trim();if(!p)throw new Un.InvalidArgumentError("getSolution: a solution unique name or id is required.");let f=_R(p)?`solutionid eq ${(0,ht.normalizeGuid)(p,"solutionId")}`:`uniquename eq '${(0,ht.odataLiteral)(p)}'`,h=`/solutions${(0,ht.odataQuery)([["$select","solutionid,uniquename,friendlyname,version,ismanaged"],["$expand","publisherid($select=publisherid,uniquename,customizationprefix,customizationoptionvalueprefix)"],["$filter",f]])}`,E=((n=(r=(0,Zt.ensureSuccess)(await e.get(h),e.apiUrl(h)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0];if(!E?.solutionid)throw new Un.InvalidArgumentError(`No solution found for '${t}'.`);let D=E.publisherid;if(!D?.publisherid)throw new Un.InvalidArgumentError(`Solution '${(i=E.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 D))throw new Un.InvalidArgumentError(`Solution '${(a=E.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,ht.normalizeGuid)(E.solutionid,"solutionId"),uniqueName:(o=E.uniquename)!==null&&o!==void 0?o:"",friendlyName:(s=E.friendlyname)!==null&&s!==void 0?s:"",version:(l=E.version)!==null&&l!==void 0?l:"",isManaged:!!E.ismanaged,publisherId:(0,ht.normalizeGuid)(D.publisherid,"publisherId"),publisherUniqueName:(u=D.uniquename)!==null&&u!==void 0?u:"",publisherPrefix:(c=D.customizationprefix)!==null&&c!==void 0?c:"",publisherOptionValuePrefix:(d=D.customizationoptionvalueprefix)!==null&&d!==void 0?d:0}}Y.getSolution=PR;async function TR(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,Zt.ensureSuccess)(await e.post("/publishers",n),e.apiUrl("/publishers")),a=(0,Zt.readCreatedId)(i,"publisherid");if(!a)throw new Un.InvalidArgumentError(`Dataverse did not return an id for publisher '${t.uniqueName}'`);return{id:a,uniqueName:t.uniqueName}}Y.createPublisher=TR;async function OR(e,t){var r;let n=(0,ht.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,Zt.ensureSuccess)(await e.post("/solutions",i),e.apiUrl("/solutions")),o=(0,Zt.readCreatedId)(a,"solutionid");if(!o)throw new Un.InvalidArgumentError(`Dataverse did not return an id for solution '${t.uniqueName}'`);return{id:o,uniqueName:t.uniqueName}}Y.createSolution=OR;async function xR(e,t,r){let i=`/solutions(${(0,ht.normalizeGuid)(t,"solutionId")})`;(0,Zt.ensureSuccess)(await e.patch(i,{version:r}),e.apiUrl(i))}Y.setSolutionVersion=xR;async function RR(e,t){var r;let i={ComponentId:(0,ht.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,Zt.ensureSuccess)(await e.post("/AddSolutionComponent",i),e.apiUrl("/AddSolutionComponent"))}Y.addSolutionComponent=RR;async function LR(e,t,r,n){let a={SolutionComponent:{"@odata.type":"Microsoft.Dynamics.CRM.solutioncomponent",solutioncomponentid:(0,ht.normalizeGuid)(t,"componentId")},ComponentType:r,SolutionUniqueName:n};(0,Zt.ensureSuccess)(await e.post("/RemoveSolutionComponent",a),e.apiUrl("/RemoveSolutionComponent"))}Y.removeSolutionComponent=LR;async function FR(e,t){var r,n;let i={SolutionName:t.solutionName,Managed:(r=t.managed)!==null&&r!==void 0?r:!1},o=(n=(0,Zt.ensureSuccess)(await e.post("/ExportSolution",i),e.apiUrl("/ExportSolution")).body)===null||n===void 0?void 0:n.ExportSolutionFile;if(!o)throw new Un.InvalidArgumentError(`ExportSolution returned no file for '${t.solutionName}'`);return{base64:o}}Y.exportSolution=FR;async function kR(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,ht.normalizeGuid)(t.importJobId,"importJobId")),(0,Zt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution"))}Y.importSolution=kR;async function MR(e,t){let n=`/solutions(${(0,ht.normalizeGuid)(t,"solutionId")})`;(0,Zt.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Y.deleteSolution=MR});var Rs=g(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.appApi=ln.deleteAppResolvingOnce=ln.unpublishedAppModulesQuery=void 0;var od=Xt(),UR=ld(),wg=Yt(),BR=_s(),ve=he(),ne=Z(),ad=mt(),$R=Hc(),ce=le(),qR=(0,ne.odataQuery)([["$select","appmoduleid,name,uniquename,description"]]),td="appmoduleid,name,uniquename,description";function Ig(e,t,r){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,ne.odataQuery)([["$select",e],["$filter",t],["$top",r]])}ln.unpublishedAppModulesQuery=Ig;function rd(e,t){return Ig(e,t?`appmoduleid eq ${t}`:void 0,t?1:void 0)}function xs(e,t){return"/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,ne.odataQuery)([["$select",t],["$filter",`sitemapid eq ${e}`],["$top",1]])}function bi(e){var t;let r=(t=e.body)===null||t===void 0?void 0:t.value;if(Array.isArray(r))return r[0]}function Os(e){let t=e?.["@odata.etag"];return typeof t=="string"?t:null}function ja(e){let t=new Set,r=[];for(let n of e??[])n&&!t.has(n)&&(t.add(n),r.push(n));return r}function VR(e){return`cdsapp_${(e||"").replace(/[^a-zA-Z0-9]/g,"")||"app"}`}async function _g(e,t){var r,n;let i=u=>{throw new ce.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,ne.odataQuery)([["$select","sitemapid"],["$filter",`sitemapnameunique eq '${(0,ne.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 GR(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,ne.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 sd(e){return e instanceof Error?e.message:String(e)}async function zR(e,t){var r,n,i;try{let a=`/roles${(0,ne.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 (${sd(a)}); it will not be visible or playable until a role is granted access to it.`}}async function WR(e,t){let r=[];async function n(s,l,u){try{return(await(0,od.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}' (${sd(c)}); they were NOT added to the app.`),[]}}let[i,a,o]=await Promise.all([n(`/systemforms${(0,ne.odataQuery)([["$select","formid"],["$filter",`objecttypecode eq '${(0,ne.odataLiteral)(t)}' and type eq 2 and formactivationstate eq 1`]])}`,"formid","forms"),n(`/savedqueries${(0,ne.odataQuery)([["$select","savedqueryid"],["$filter",`returnedtypecode eq '${(0,ne.odataLiteral)(t)}' and querytype eq 0 and statecode eq 0`]])}`,"savedqueryid","views"),n(`/savedqueryvisualizations${(0,ne.odataQuery)([["$select","savedqueryvisualizationid"],["$filter",`primaryentitytypecode eq '${(0,ne.odataLiteral)(t)}'`]])}`,"savedqueryvisualizationid","charts")]);return{forms:i,views:a,charts:o,warnings:r}}var Ag=new WeakMap;async function jR(e,t){let r=Ag.get(e);r||(r=new Map,Ag.set(e,r));let n=r.get(t);if(n!==void 0)return n;let i=await HR(e,t);return i&&r.set(t,i),i}async function Cg(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 HR(e,t){let r=`/EntityDefinitions(LogicalName='${(0,ne.odataLiteral)(t)}')${(0,ne.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 Sg(e,t){let r=[],n=ja(t.entities),i=4,a=await Cg(n,i,f=>jR(e,f)),o=n.filter((f,h)=>!a[h]);if(o.length>0)throw new ce.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 ja(t.components.forms))r.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:f});for(let f of ja(t.components.views))r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:f});for(let f of ja(t.components.charts))r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:f});for(let f of ja(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 Cg(n,i,f=>WR(e,f)),p=d.flatMap(f=>f.warnings);for(let f of d){for(let h of f.forms)l.has(h)||(l.add(h),r.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:h}));for(let h of f.views)u.has(h)||(u.add(h),r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:h}));for(let h of f.charts)c.has(h)||(c.add(h),r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:h}))}return{components:r,tables:s,warnings:p}}async function Ng(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 QR(e){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,ne.odataQuery)([["$select","appmoduleid,appmoduleidunique"],["$filter",`appmoduleid eq ${e}`],["$top",1]])}async function Eg(e,t,r){var n;if(r.length===0)return;let i=QR(t),a=await e.get(i);if(a.status<200||a.status>=300)throw new ce.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=bi(a),s=o?.appmoduleidunique;if(typeof s!="string"||!s)throw new ce.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,ne.odataQuery)([["$select","objectid,componenttype"],["$filter",`_appmoduleidunique_value eq ${(0,ne.normalizeGuid)(s,`App '${t}' appmoduleidunique`)} and componenttype eq 1`]])}`,u=await e.get(l);if(u.status<200||u.status>=300)throw new ce.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 ce.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 ce.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 JR(e,t,r){let n=`/appmodules(${t})`,i=`/sitemaps(${r.sitemapId})`;try{if(!await XR(e,r.sitemapId)){r.serverRefusedSitemap&&(0,ve.ensureSuccess)(await e.delete(n),e.apiUrl(n));return}e.supportsAtomicBatch&&await Tg(e,[{path:n,etag:r.appEtag},{path:i,etag:r.sitemapEtag}])}catch{}}async function XR(e,t){var r;let n=xs(t,"sitemapid"),i=await e.get(n);if(i.status<200||i.status>=300)throw new ce.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned HTTP ${i.status}, so it cannot be determined whether the row exists.`);let a=(r=i.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new ce.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 a.length>0}async function Pg(e,t){var r;let n=(0,ne.normalizeGuid)(t,"id"),i=h=>{throw new ce.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})${qR}`,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 _g(e,s);if(!l)return{uniquename:s,appEtag:(0,ve.readEtag)(o)};let u=(0,ne.normalizeGuid)(l,"sitemapId"),c=xs(u,"sitemapid,sitemapnameunique,sitemapxml"),d;try{d=await e.get(c)}catch(h){return i(`reading sitemap '${u}' failed (${h.message}).`)}if(d.status<200||d.status>=300)return i(`reading sitemap '${u}' returned HTTP ${d.status}.`);let p=bi(d);if(!p)return i(`sitemap '${u}' was not returned by the unpublished-aware read.`);if(p.sitemapnameunique!==s)return i(`sitemap '${u}' now carries sitemapnameunique '${String(p.sitemapnameunique)}', not '${s}', so it is no longer this app's sitemap.`);let f=p.sitemapxml;return typeof f!="string"?i(`sitemap '${u}' returned no sitemapxml.`):{sitemapId:u,uniquename:s,sitemapXml:f,appEtag:(0,ve.readEtag)(o),sitemapEtag:Os(p)}}async function KR(e,t,r){let n=(0,ne.normalizeGuid)(t,"id"),i=await Pg(e,n);await r?.(i.sitemapXml),await Og(e,n,i)}ln.deleteAppResolvingOnce=KR;async function Tg(e,t){let r=`batch_${(0,ad.newId)()}`,n=`changeset_${(0,ad.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 ce.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,$R.parseChangeSetStatuses)(o.body,i.map((d,p)=>String(p+1)));if(u===void 0)throw new ce.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 ce.ConnectionError(s,c,`atomic delete of ${l} was rolled back: the change set reported HTTP ${c}`);if(u.length!==i.length)throw new ce.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 nd(e,t){try{let r=xs(t,"sitemapid"),n=await e.get(r);return n.status<200||n.status>=300?null:Os(bi(n))}catch{return null}}function YR(e){return e>=400&&e<500&&e!==408&&e!==429}function id(e,t,r){if(!e)throw new ce.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 Og(e,t,r){let n=`/appmodules(${t})`;if(!r.sitemapId){await ZR(e,n,id(r.appEtag,t,"app"));return}if(!e.supportsAtomicBatch)throw new ce.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 Tg(e,[{path:n,etag:id(r.appEtag,t,"app")},{path:`/sitemaps(${r.sitemapId})`,etag:id(r.sitemapEtag,t,"sitemap")}])}async function ZR(e,t,r){(0,ve.ensureSuccess)(await e.delete(t,{headers:{"If-Match":r}}),e.apiUrl(t))}async function Dg(e,t){if(!/GenPageId/i.test(t))return;let r;try{r=[...new Set((0,UR.collectGenPageIds)(t))]}catch(o){throw new ce.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 (${sd(o)}).`)}if(r.length===0)return;let n=new Set,i=50;for(let o=0;o<r.length;o+=i){let s=r.slice(o,o+i),l="/uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,ne.odataQuery)([["$select","uxagentprojectid"],["$filter",s.map(c=>`uxagentprojectid eq ${c}`).join(" or ")]]),u=await(0,od.collectPages)(e,l,"sitemap generative-page preflight");for(let c of u){let d=c.uxagentprojectid;typeof d=="string"&&d.trim()!==""&&n.add((0,ne.normalizeGuid)(d,"uxagentprojectid"))}}let a=r.filter(o=>!n.has(o));if(a.length>0)throw new ce.SdkError("SITEMAP_TARGET_NOT_FOUND",`Refusing to push the app: its sitemap navigates to generative page(s) ${a.map(o=>`'${o}'`).join(", ")} that do not exist in this environment. Push the page before the app that links to it.`)}function eL(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")}ln.appApi={async get(e,t){var r;let n=(0,ne.normalizeGuid)(t,"id"),i=rd(td,n),a=(0,ve.ensureSuccess)(await e.get(i),e.apiUrl(i)),o=(r=bi(a))!==null&&r!==void 0?r:{};if(!o.appmoduleid)throw new ce.SdkError("APP_NOT_FOUND",`App '${n}' was not found (checked the unpublished-aware projection, which includes drafts).`);let s=await _g(e,o.uniquename),l=s?(0,ne.normalizeGuid)(s,"sitemapId"):void 0,u=null;if(l){let d=xs(l,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"),p=(0,ve.ensureSuccess)(await e.get(d),e.apiUrl(d)),f=bi(p);if(f&&f.sitemapnameunique!==o.uniquename)throw new ce.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.`);o.$sitemap=f??{},u=Os(f)}let c=Os(o);return{raw:o,etag:u,...o.appmoduleid?{siblingEtags:{[(0,ne.normalizeGuid)(o.appmoduleid,"appmoduleid")]:c}}:{}}},async list(e,t){let r=rd(td);return(await(0,od.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 Dg(e,n.sitemapxml);let i=n.iconWebResourceId?void 0:await GR(e),a=n.iconWebResourceId||i?.id;if(!a)throw new ce.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||VR(n.appModuleId),l={name:n.appModuleName,uniquename:s,clienttype:4,formfactor:1,navigationtype:0};n.appModuleDescription&&(l.description=n.appModuleDescription),a&&(l.webresourceid=a);let u="/appmodules",c=(0,ve.ensureSuccess)(await e.post(u,(0,ve.withClientMintedId)(l,"appmoduleid",r)),e.apiUrl(u)),d=(0,ve.resolveCreatedId)(c,"appmoduleid","app module",r),p=null,f=[];o&&f.push(o);let h={kind:"notRequested"},b=(0,ad.newId)(),w=!1;try{let D="/sitemaps",L=await e.post(D,{sitemapid:b,sitemapnameunique:s,sitemapname:n.sitemapname,sitemapxml:n.sitemapxml});w=YR(L.status);let R=(0,ve.ensureSuccess)(L,e.apiUrl(D));p=(0,ve.readEtag)(R),p||(p=await nd(e,b));let B=await Sg(e,n);f.push(...B.warnings);let V=B.components;V.unshift({"@odata.type":"Microsoft.Dynamics.CRM.sitemap",sitemapid:b}),await Ng(e,d,V),await Eg(e,d,B.tables);let M=await zR(e,d);M&&f.push(M),n.appSettings&&Object.keys(n.appSettings).length>0&&f.push(...await(0,BR.applyAppSettings)(e,d,n.appSettings)),n.published!==!1&&(await(0,wg.publishAppModule)(e,d),h={kind:"submitted"})}catch(D){throw await JR(e,d,{sitemapId:b,serverRefusedSitemap:w,appEtag:(0,ve.readEtag)(c),sitemapEtag:p}),D}let E=null;if(h.kind==="submitted")try{let D=await e.get(`/appmodules(${d})?$select=appmoduleid`);D.status>=200&&D.status<300&&(E=(0,ve.readEtag)(D))}catch{}return{id:d,etag:p,serverIdentity:{sitemapId:b},siblingEtags:{[d]:E},publish:h,...f.length>0?{warnings:f}:{}}},async update(e,t,r,n,i,a){var o,s,l,u,c,d,p;let f=r,h=(0,ne.normalizeGuid)(t,"id");if(await Dg(e,f.sitemapxml),!f.sitemapId)throw new ce.ValidationError("app",h,"/sitemapId","missing sitemap identity \u2014 re-fetch the app before pushing edits");let b=(0,ne.normalizeGuid)(f.sitemapId,"sitemapId");if(!n)throw new ce.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${h}': 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 Sg(e,f),E=`/appmodules(${h})`,D=(o=a?.[h])!==null&&o!==void 0?o:null,L=!0,R=!1;try{let me=rd(td,h),Ue=await e.get(me);if(Ue.status>=200&&Ue.status<300){let He=(s=bi(Ue))!==null&&s!==void 0?s:{};R=!0,L=String((l=He.name)!==null&&l!==void 0?l:"")!==String((u=f.appModuleName)!==null&&u!==void 0?u:"")||String((c=He.description)!==null&&c!==void 0?c:"")!==String((d=f.appModuleDescription)!==null&&d!==void 0?d:"")}}catch{}let B=D;if(L){let me=R?D:null,Ue=me?(0,ve.echoWrite)("appmoduleid",{"If-Match":me}):{query:"",options:void 0},He=await e.patch(`${E}${Ue.query}`,{name:f.appModuleName,description:f.appModuleDescription},Ue.options);if(eL(He))throw new ce.SdkError("APP_DRAFT_HEADER_NOT_WRITABLE",`Refusing to update app '${h}': 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)(He,e.apiUrl(E)),B=(0,ve.readEtag)(He)}let V={"If-Match":n},M=`/sitemaps(${b})`,$;try{$=(0,ve.ensureSuccess)(await e.patch(M,{sitemapxml:f.sitemapxml,sitemapname:f.sitemapname},V?{headers:V}:void 0),e.apiUrl(M))}catch(me){throw(0,ce.withPartialTokens)(me,{siblingEtags:{[h]:B}})}let G=[...w.warnings];try{await Ng(e,h,w.components),await Eg(e,h,w.tables)}catch(me){G.push(`App '${h}': one or more components were not pinned (${me.message}). Navigation may reference content not included in the app; re-push to retry.`)}let X={kind:"notRequested"},U=B,Oe=(0,ve.readEtag)($);if(f.published===!0){try{await(0,wg.publishAppModule)(e,h),X={kind:"submitted"}}catch(me){X={kind:"failed",error:me},G.push(`App '${h}': saved, but publishing failed (${me.message}). The app remains unpublished; re-push to retry.`)}if(X.kind==="submitted"){U=null;try{let me=await e.get(`/appmodules(${h})?$select=appmoduleid`);me.status>=200&&me.status<300&&(U=(0,ve.readEtag)(me)),Oe=(p=await nd(e,b))!==null&&p!==void 0?p:Oe}catch{}}}return{id:h,etag:Oe??await nd(e,b),siblingEtags:{[h]:U},publish:X,...G.length>0?{warnings:G}:{}}},async delete(e,t){let r=(0,ne.normalizeGuid)(t,"id");await Og(e,r,await Pg(e,r))}}});var Ha=g(wi=>{"use strict";function tL(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 ud(e,t){return t===void 0&&(t=Object),t&&typeof t.freeze=="function"?t.freeze(e):e}function rL(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 xg=ud({HTML:"text/html",isHTML:function(e){return e===xg.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),Rg=ud({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(e){return e===Rg.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"});wi.assign=rL;wi.find=tL;wi.freeze=ud;wi.MIME_TYPE=xg;wi.NAMESPACE=Rg});var Ad=g($r=>{var qg=Ha(),fr=qg.find,Qa=qg.NAMESPACE;function nL(e){return e!==""}function iL(e){return e?e.split(/[\t\n\f\r ]+/).filter(nL):[]}function aL(e,t){return e.hasOwnProperty(t)||(e[t]=!0),e}function Lg(e){if(!e)return[];var t=iL(e);return Object.keys(t.reduce(aL,{}))}function oL(e){return function(t){return e&&e.indexOf(t)!==-1}}function Xa(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function vt(e,t){var r=e.prototype;if(!(r instanceof t)){let i=function(){};var n=i;i.prototype=t.prototype,i=new i,Xa(r,i),e.prototype=r=i}r.constructor!=e&&(typeof e!="function"&&console.error("unknown Class:"+e),r.constructor=e)}var yt={},xt=yt.ELEMENT_NODE=1,Ci=yt.ATTRIBUTE_NODE=2,Fs=yt.TEXT_NODE=3,Vg=yt.CDATA_SECTION_NODE=4,Gg=yt.ENTITY_REFERENCE_NODE=5,sL=yt.ENTITY_NODE=6,cd=yt.PROCESSING_INSTRUCTION_NODE=7,dd=yt.COMMENT_NODE=8,zg=yt.DOCUMENT_NODE=9,Wg=yt.DOCUMENT_TYPE_NODE=10,Mr=yt.DOCUMENT_FRAGMENT_NODE=11,lL=yt.NOTATION_NODE=12,tt={},Ve={},Zz=tt.INDEX_SIZE_ERR=(Ve[1]="Index size error",1),eW=tt.DOMSTRING_SIZE_ERR=(Ve[2]="DOMString size error",2),gt=tt.HIERARCHY_REQUEST_ERR=(Ve[3]="Hierarchy request error",3),tW=tt.WRONG_DOCUMENT_ERR=(Ve[4]="Wrong document",4),uL=tt.INVALID_CHARACTER_ERR=(Ve[5]="Invalid character",5),rW=tt.NO_DATA_ALLOWED_ERR=(Ve[6]="No data allowed",6),nW=tt.NO_MODIFICATION_ALLOWED_ERR=(Ve[7]="No modification allowed",7),jg=tt.NOT_FOUND_ERR=(Ve[8]="Not found",8),iW=tt.NOT_SUPPORTED_ERR=(Ve[9]="Not supported",9),Fg=tt.INUSE_ATTRIBUTE_ERR=(Ve[10]="Attribute in use",10),Ai=tt.INVALID_STATE_ERR=(Ve[11]="Invalid state",11),aW=tt.SYNTAX_ERR=(Ve[12]="Syntax error",12),oW=tt.INVALID_MODIFICATION_ERR=(Ve[13]="Invalid modification",13),sW=tt.NAMESPACE_ERR=(Ve[14]="Invalid namespace",14),lW=tt.INVALID_ACCESS_ERR=(Ve[15]="Invalid access",15);function oe(e,t){if(t instanceof Error)var r=t;else r=this,Error.call(this,Ve[e]),this.message=Ve[e],Error.captureStackTrace&&Error.captureStackTrace(this,oe);return r.code=e,t&&(this.message=this.message+": "+t),r}oe.prototype=Error.prototype;Xa(tt,oe);function Ur(){}Ur.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++)wd(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 Si(e,t){this._node=e,this._refresh=t,pd(this)}function pd(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!==t){var r=e._refresh(e._node);if(i0(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];Xa(r,e),e._inc=t}}Si.prototype.item=function(e){return pd(this),this[e]||null};vt(Si,Ur);function ks(){}function Hg(e,t){for(var r=e.length;r--;)if(e[r]===t)return r}function kg(e,t,r,n){if(n?t[Hg(t,n)]=r:t[t.length++]=r,e){r.ownerElement=e;var i=e.ownerDocument;i&&(n&&Xg(i,e,n),cL(i,e,r))}}function Mg(e,t,r){var n=Hg(t,r);if(n>=0){for(var i=t.length-1;n<i;)t[n]=t[++n];if(t.length=i,e){var a=e.ownerDocument;a&&(Xg(a,e,r),r.ownerElement=null)}}else throw new oe(jg,new Error(e.tagName+"@"+r))}ks.prototype={length:0,item:Ur.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 oe(Fg);var r=this.getNamedItem(e.nodeName);return kg(this._ownerElement,this,e,r),r},setNamedItemNS:function(e){var t=e.ownerElement,r;if(t&&t!=this._ownerElement)throw new oe(Fg);return r=this.getNamedItemNS(e.namespaceURI,e.localName),kg(this._ownerElement,this,e,r),r},removeNamedItem:function(e){var t=this.getNamedItem(e);return Mg(this._ownerElement,this,t),t},removeNamedItemNS:function(e,t){var r=this.getNamedItemNS(e,t);return Mg(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 Qg(){}Qg.prototype={hasFeature:function(e,t){return!0},createDocument:function(e,t,r){var n=new Ka;if(n.implementation=this,n.childNodes=new Ur,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 $s;return n.name=e,n.nodeName=e,n.publicId=t||"",n.systemId=r||"",n}};function ie(){}ie.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 Us(this,e,t)},replaceChild:function(e,t){Us(this,e,t,Yg),t&&this.removeChild(t)},removeChild:function(e){return Kg(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return n0(this.ownerDocument||this,this,e)},normalize:function(){qe(this,null,{enter:function(e){for(var t=e.firstChild;t;){var r=t.nextSibling;r!==null&&r.nodeType===Fs&&t.nodeType===Fs?(e.removeChild(r),t.appendData(r.data)):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==Ci?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==Ci?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){var t=this.lookupPrefix(e);return t==null}};function Jg(e){return e=="<"&&"<"||e==">"&&">"||e=="&"&&"&"||e=='"'&&"""||"&#"+e.charCodeAt()+";"}Xa(yt,ie);Xa(yt,ie.prototype);function Ms(e,t){return qe(e,null,{enter:function(r){return t(r)?qe.STOP:!0}})===qe.STOP}function qe(e,t,r){for(var n=[{node:e,context:t,phase:qe.ENTER}];n.length>0;){var i=n.pop();if(i.phase===qe.ENTER){var a=r.enter(i.node,i.context);if(a===qe.STOP)return qe.STOP;if(n.push({node:i.node,context:a,phase:qe.EXIT}),a==null)continue;for(var o=i.node.lastChild;o;)n.push({node:o,context:a,phase:qe.ENTER}),o=o.previousSibling}else r.exit&&r.exit(i.node,i.context)}}qe.STOP=Symbol("walkDOM.STOP");qe.ENTER=0;qe.EXIT=1;function Ka(){this.ownerDocument=this}function cL(e,t,r){e&&e._inc++;var n=r.namespaceURI;n===Qa.XMLNS&&(t._nsMap[r.prefix?r.localName:""]=r.value)}function Xg(e,t,r,n){e&&e._inc++;var i=r.namespaceURI;i===Qa.XMLNS&&delete t._nsMap[r.prefix?r.localName:""]}function fd(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 Kg(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,fd(e.ownerDocument,e),t}function dL(e){return e&&(e.nodeType===ie.DOCUMENT_NODE||e.nodeType===ie.DOCUMENT_FRAGMENT_NODE||e.nodeType===ie.ELEMENT_NODE)}function pL(e){return e&&(mr(e)||md(e)||Br(e)||e.nodeType===ie.DOCUMENT_FRAGMENT_NODE||e.nodeType===ie.COMMENT_NODE||e.nodeType===ie.PROCESSING_INSTRUCTION_NODE)}function Br(e){return e&&e.nodeType===ie.DOCUMENT_TYPE_NODE}function mr(e){return e&&e.nodeType===ie.ELEMENT_NODE}function md(e){return e&&e.nodeType===ie.TEXT_NODE}function Ug(e,t){var r=e.childNodes||[];if(fr(r,mr)||Br(t))return!1;var n=fr(r,Br);return!(t&&n&&r.indexOf(n)>r.indexOf(t))}function Bg(e,t){var r=e.childNodes||[];function n(a){return mr(a)&&a!==t}if(fr(r,n))return!1;var i=fr(r,Br);return!(t&&i&&r.indexOf(i)>r.indexOf(t))}function fL(e,t,r){if(!dL(e))throw new oe(gt,"Unexpected parent node type "+e.nodeType);if(r&&r.parentNode!==e)throw new oe(jg,"child not in parent");if(!pL(t)||Br(t)&&e.nodeType!==ie.DOCUMENT_NODE)throw new oe(gt,"Unexpected node type "+t.nodeType+" for parent node type "+e.nodeType)}function mL(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===ie.DOCUMENT_FRAGMENT_NODE){var a=i.filter(mr);if(a.length>1||fr(i,md))throw new oe(gt,"More than one element or text in fragment");if(a.length===1&&!Ug(e,r))throw new oe(gt,"Element in fragment can not be inserted before doctype")}if(mr(t)&&!Ug(e,r))throw new oe(gt,"Only one element can be added and only after doctype");if(Br(t)){if(fr(n,Br))throw new oe(gt,"Only one doctype is allowed");var o=fr(n,mr);if(r&&n.indexOf(o)<n.indexOf(r))throw new oe(gt,"Doctype can only be inserted before an element");if(!r&&o)throw new oe(gt,"Doctype can not be appended since element is present")}}function Yg(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===ie.DOCUMENT_FRAGMENT_NODE){var a=i.filter(mr);if(a.length>1||fr(i,md))throw new oe(gt,"More than one element or text in fragment");if(a.length===1&&!Bg(e,r))throw new oe(gt,"Element in fragment can not be inserted before doctype")}if(mr(t)&&!Bg(e,r))throw new oe(gt,"Only one element can be added and only after doctype");if(Br(t)){let l=function(u){return Br(u)&&u!==r};var s=l;if(fr(n,l))throw new oe(gt,"Only one doctype is allowed");var o=fr(n,mr);if(r&&n.indexOf(o)<n.indexOf(r))throw new oe(gt,"Doctype can only be inserted before an element")}}function Us(e,t,r,n){fL(e,t,r),e.nodeType===ie.DOCUMENT_NODE&&(n||mL)(e,t,r);var i=t.parentNode;if(i&&i.removeChild(t),t.nodeType===Mr){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;Ja(a,l)}while(a!==o&&(a=a.nextSibling));return fd(e.ownerDocument||e,e),t.nodeType==Mr&&(t.firstChild=t.lastChild=null),t}function Ja(e,t){if(e.ownerDocument!==t){if(e.ownerDocument=t,e.nodeType===xt&&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;)Ja(i,t),i=i.nextSibling}}function hL(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,fd(e.ownerDocument,e,t);var r=e.ownerDocument||e;return Ja(t,r),t}Ka.prototype={nodeName:"#document",nodeType:zg,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==Mr){for(var r=e.firstChild;r;){var n=r.nextSibling;this.insertBefore(r,t),r=n}return e}return Us(this,e,t),Ja(e,this),this.documentElement===null&&e.nodeType===xt&&(this.documentElement=e),e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),Kg(this,e)},replaceChild:function(e,t){Us(this,e,t,Yg),Ja(e,this),t&&this.removeChild(t),mr(e)&&(this.documentElement=e)},importNode:function(e,t){return gL(this,e,t)},getElementById:function(e){var t=null;return Ms(this.documentElement,function(r){if(r.nodeType==xt&&r.getAttribute("id")==e)return t=r,!0}),t},getElementsByClassName:function(e){var t=Lg(e);return new Si(this,function(r){var n=[];return t.length>0&&Ms(r.documentElement,function(i){if(i!==r&&i.nodeType===xt){var a=i.getAttribute("class");if(a){var o=e===a;if(!o){var s=Lg(a);o=t.every(oL(s))}o&&n.push(i)}}}),n})},createElement:function(e){var t=new Bn;t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.localName=e,t.childNodes=new Ur;var r=t.attributes=new ks;return r._ownerElement=t,t},createDocumentFragment:function(){var e=new qs;return e.ownerDocument=this,e.childNodes=new Ur,e},createTextNode:function(e){var t=new hd;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new gd;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){if(e.indexOf("]]>")!==-1)throw new oe(uL,'data contains "]]>"');var t=new vd;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var r=new bd;return r.ownerDocument=this,r.tagName=r.nodeName=r.target=e,r.nodeValue=r.data=t,r},createAttribute:function(e){var t=new Bs;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){var t=new yd;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var r=new Bn,n=t.split(":"),i=r.attributes=new ks;return r.childNodes=new Ur,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 Bs,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}};vt(Ka,ie);function Bn(){this._nsMap={}}Bn.prototype={nodeType:xt,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===Mr?this.insertBefore(e,null):hL(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 Si(this,function(t){var r=[];return Ms(t,function(n){n!==t&&n.nodeType==xt&&(e==="*"||n.tagName==e)&&r.push(n)}),r})},getElementsByTagNameNS:function(e,t){return new Si(this,function(r){var n=[];return Ms(r,function(i){i!==r&&i.nodeType===xt&&(e==="*"||i.namespaceURI===e)&&(t==="*"||i.localName==t)&&n.push(i)}),n})}};Ka.prototype.getElementsByTagName=Bn.prototype.getElementsByTagName;Ka.prototype.getElementsByTagNameNS=Bn.prototype.getElementsByTagNameNS;vt(Bn,ie);function Bs(){}Bs.prototype.nodeType=Ci;vt(Bs,ie);function Ya(){}Ya.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(Ve[gt])},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}};vt(Ya,ie);function hd(){}hd.prototype={nodeName:"#text",nodeType:Fs,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}};vt(hd,Ya);function gd(){}gd.prototype={nodeName:"#comment",nodeType:dd};vt(gd,Ya);function vd(){}vd.prototype={nodeName:"#cdata-section",nodeType:Vg};vt(vd,Ya);function $s(){}$s.prototype.nodeType=Wg;vt($s,ie);function Zg(){}Zg.prototype.nodeType=lL;vt(Zg,ie);function e0(){}e0.prototype.nodeType=sL;vt(e0,ie);function yd(){}yd.prototype.nodeType=Gg;vt(yd,ie);function qs(){}qs.prototype.nodeName="#document-fragment";qs.prototype.nodeType=Mr;vt(qs,ie);function bd(){}bd.prototype.nodeType=cd;vt(bd,ie);function t0(){}t0.prototype.serializeToString=function(e,t,r,n){return r0.call(e,t,r,n)};ie.prototype.toString=r0;function r0(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 wd(this,i,e,t,l,n),i.join("")}function $g(e,t,r){var n=e.prefix||"",i=e.namespaceURI;if(!i||n==="xml"&&i===Qa.XML||i===Qa.XMLNS)return!1;for(var a=r.length;a--;){var o=r[a];if(o.prefix===n)return o.namespace!==i}return!0}function Ls(e,t,r){e.push(" ",t,'="',r.replace(/[<>&"\t\n\r]/g,Jg),'"')}function wd(e,t,r,n,i,a){i||(i=[]),qe(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 xt:var c=o.attributes,d=c.length,p=o.tagName;u=Qa.isHTML(o.namespaceURI)||u;var f=p;if(!u&&!o.prefix&&o.namespaceURI){for(var h,b=0;b<c.length;b++)if(c.item(b).name==="xmlns"){h=c.item(b).value;break}if(!h)for(var w=l.length-1;w>=0;w--){var E=l[w];if(E.prefix===""&&E.namespace===o.namespaceURI){h=E.namespace;break}}if(h!==o.namespaceURI)for(var w=l.length-1;w>=0;w--){var E=l[w];if(E.namespace===o.namespaceURI){E.prefix&&(f=E.prefix+":"+p);break}}}t.push("<",f);for(var D=l.slice(),L=0;L<d;L++){var R=c.item(L);R.prefix=="xmlns"?D.push({prefix:R.localName,namespace:R.value}):R.nodeName=="xmlns"&&D.push({prefix:"",namespace:R.value})}for(var L=0;L<d;L++){var R=c.item(L);if($g(R,u,D)){var B=R.prefix||"",V=R.namespaceURI;Ls(t,B?"xmlns:"+B:"xmlns",V),D.push({prefix:B,namespace:V})}var M=n?n(R):R;M&&(typeof M=="string"?t.push(M):Ls(t,M.name,M.value))}if(p===f&&$g(o,u,D)){var $=o.prefix||"",V=o.namespaceURI;Ls(t,$?"xmlns:"+$:"xmlns",V),D.push({prefix:$,namespace:V})}var G=o.firstChild;if(G||u&&!/^(?:meta|link|img|br|hr|input)$/i.test(p)){if(t.push(">"),u&&/^script$/i.test(p)){for(;G;)G.data?t.push(G.data):wd(G,t,u,n,D.slice(),a),G=G.nextSibling;return t.push("</",p,">"),null}return{ns:D,isHTML:u,tag:f}}else return t.push("/>"),null;case zg:case Mr:return{ns:l.slice(),isHTML:u,tag:null};case Ci:return Ls(t,o.name,o.value),null;case Fs:return t.push(o.data.replace(/[<&>]/g,Jg)),null;case Vg:if(a&&o.data.indexOf("]]>")!==-1)throw new oe(Ai,'The CDATASection data contains "]]>"');return t.push("<![CDATA[",o.data.replace(/]]>/g,"]]]]><![CDATA[>"),"]]>"),null;case dd:if(a&&o.data.indexOf("-->")!==-1)throw new oe(Ai,'The comment node data contains "-->"');return t.push("<!--",o.data,"-->"),null;case Wg:if(a){if(o.publicId&&!/^("[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%']*"|'[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%'"]*')$/.test(o.publicId))throw new oe(Ai,"DocumentType publicId is not a valid PubidLiteral");if(o.systemId&&!/^("[^"]*"|'[^']*')$/.test(o.systemId))throw new oe(Ai,"DocumentType systemId is not a valid SystemLiteral");if(o.internalSubset&&o.internalSubset.indexOf("]>")!==-1)throw new oe(Ai,'DocumentType internalSubset contains "]>"')}var X=o.publicId,U=o.systemId;if(t.push("<!DOCTYPE ",o.name),X)t.push(" PUBLIC ",X),U&&U!="."&&t.push(" ",U),t.push(">");else if(U&&U!=".")t.push(" SYSTEM ",U,">");else{var Oe=o.internalSubset;Oe&&t.push(" [",Oe,"]"),t.push(">")}return null;case cd:if(a&&o.data.indexOf("?>")!==-1)throw new oe(Ai,'The ProcessingInstruction data contains "?>"');return t.push("<?",o.target," ",o.data,"?>"),null;case Gg: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 gL(e,t,r){var n;return qe(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===Ci||r;return s?o:null}}),n}function n0(e,t,r){var n;return qe(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 Ur),o.ownerDocument=e;var u=r;switch(o.nodeType){case xt:var c=i.attributes,d=o.attributes=new ks,p=c.length;d._ownerElement=o;for(var f=0;f<p;f++)o.setAttributeNode(n0(e,c.item(f),!0));break;case Ci:u=!0}return a!==null?a.appendChild(o):n=o,u?o:null}}),n}function i0(e,t,r){e[t]=r}try{Object.defineProperty&&(Object.defineProperty(Si.prototype,"length",{get:function(){return pd(this),this.$$length}}),Object.defineProperty(ie.prototype,"textContent",{get:function(){if(this.nodeType===xt||this.nodeType===Mr){var e=[];return qe(this,null,{enter:function(t){if(t.nodeType===xt||t.nodeType===Mr)return!0;if(t.nodeType===cd||t.nodeType===dd)return null;e.push(t.nodeValue)}}),e.join("")}return this.nodeValue},set:function(e){switch(this.nodeType){case xt:case Mr: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}}}),i0=function(e,t,r){e["$$"+t]=r})}catch{}$r.DocumentType=$s;$r.DOMException=oe;$r.DOMImplementation=Qg;$r.Element=Bn;$r.Node=ie;$r.NodeList=Ur;$r.walkDOM=qe;$r.XMLSerializer=t0});var o0=g(Za=>{"use strict";var a0=Ha().freeze;Za.XML_ENTITIES=a0({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});Za.HTML_ENTITIES=a0({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"});Za.entityMap=Za.HTML_ENTITIES});var m0=g(Sd=>{var no=Ha().NAMESPACE,Cd=/[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]/,s0=new RegExp("[\\-\\.0-9"+Cd.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),l0=new RegExp("^"+Cd.source+s0.source+"*(?::"+Cd.source+s0.source+"*)?$"),eo=0,un=1,Ni=2,to=3,Ei=4,Di=5,ro=6,Vs=7;function Ii(e,t){this.message=e,this.locator=t,Error.captureStackTrace&&Error.captureStackTrace(this,Ii)}Ii.prototype=new Error;Ii.prototype.name=Ii.name;function d0(){}d0.prototype={parse:function(e,t,r){var n=this.domBuilder;n.startDocument(),p0(t,t={}),vL(e,t,r,n,this.errorHandler),n.endDocument()}};function vL(e,t,r,n,i){function a(ue){if(ue>65535){ue-=65536;var ft=55296+(ue>>10),Yu=56320+(ue&1023);return String.fromCharCode(ft,Yu)}else return String.fromCharCode(ue)}function o(ue){var ft=ue.slice(1,-1);return Object.hasOwnProperty.call(r,ft)?r[ft]:ft.charAt(0)==="#"?a(parseInt(ft.substr(1).replace("x","0x"))):(i.error("entity not found:"+ue),ue)}function s(ue){if(ue>b){var ft=e.substring(b,ue).replace(/&#?\w+;/g,o);p&&l(b),n.characters(ft,0,ue-b),b=ue}}function l(ue,ft){for(;ue>=c&&(ft=d.exec(e));)u=ft.index,c=u+ft[0].length,p.lineNumber++;p.columnNumber=ue-u+1}for(var u=0,c=0,d=/.*(?:\r\n?|\n)|.*$/g,p=n.locator,f=[{currentNSMap:t}],h={},b=0;;){try{var w=e.indexOf("<",b);if(w<0){if(!e.substr(b).match(/^\s*$/)){var E=n.doc,D=E.createTextNode(e.substr(b));E.appendChild(D),n.currentElement=D}return}switch(w>b&&s(w),e.charAt(w+1)){case"/":var U=e.indexOf(">",w+3),L=e.substring(w+2,U).replace(/[ \t\n\r]+$/g,""),R=f.pop();U<0?(L=e.substring(w+2).replace(/[\s<].*/,""),i.error("end tag name: "+L+" is not complete:"+R.tagName),U=w+1+L.length):L.match(/\s</)&&(L=L.replace(/[\s<].*/,""),i.error("end tag name: "+L+" maybe not complete"),U=w+1+L.length);var B=R.localNSMap,V=R.tagName==L,M=V||R.tagName&&R.tagName.toLowerCase()==L.toLowerCase();if(M){if(n.endElement(R.uri,R.localName,L),B)for(var $ in B)Object.prototype.hasOwnProperty.call(B,$)&&n.endPrefixMapping($);V||i.fatalError("end tag name: "+L+" is not match the current start tagName:"+R.tagName)}else f.push(R);U++;break;case"?":p&&l(w),U=CL(e,w,n);break;case"!":p&&l(w),U=AL(e,w,n,i);break;default:p&&l(w);var G=new f0,X=f[f.length-1].currentNSMap,U=yL(e,w,G,X,o,i),Oe=G.length;if(!G.closed&&wL(e,U,G.tagName,h)&&(G.closed=!0,r.nbsp||i.warning("unclosed xml attribute")),p&&Oe){for(var me=u0(p,{}),Ue=0;Ue<Oe;Ue++){var He=G[Ue];l(He.offset),He.locator=u0(p,{})}n.locator=me,c0(G,n,X)&&f.push(G),n.locator=p}else c0(G,n,X)&&f.push(G);no.isHTML(G.uri)&&!G.closed?U=bL(e,U,G.tagName,o,n):U++}}catch(ue){if(ue instanceof Ii)throw ue;i.error("element parse error: "+ue),U=-1}U>b?b=U:s(Math.max(w,b)+1)}}function u0(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function yL(e,t,r,n,i,a){function o(f,h,b){r.attributeNames.hasOwnProperty(f)&&a.fatalError("Attribute "+f+" redefined"),r.addValue(f,h.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,i),b)}for(var s,l,u=++t,c=eo;;){var d=e.charAt(u);switch(d){case"=":if(c===un)s=e.slice(t,u),c=to;else if(c===Ni)c=to;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(c===to||c===un)if(c===un&&(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=Di;else throw new Error("attribute value no end '"+d+"' match");else if(c==Ei)l=e.slice(t,u),o(s,l,t),a.warning('attribute "'+s+'" missed start quot('+d+")!!"),t=u+1,c=Di;else throw new Error('attribute value must after "="');break;case"/":switch(c){case eo:r.setTagName(e.slice(t,u));case Di:case ro:case Vs:c=Vs,r.closed=!0;case Ei:case un:break;case Ni:r.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return a.error("unexpected end of input"),c==eo&&r.setTagName(e.slice(t,u)),u;case">":switch(c){case eo:r.setTagName(e.slice(t,u));case Di:case ro:case Vs:break;case Ei:case un:l=e.slice(t,u),l.slice(-1)==="/"&&(r.closed=!0,l=l.slice(0,-1));case Ni:c===Ni&&(l=s),c==Ei?(a.warning('attribute "'+l+'" missed quot(")!'),o(s,l,t)):((!no.isHTML(n[""])||!l.match(/^(?:disabled|checked|selected)$/i))&&a.warning('attribute "'+l+'" missed value!! "'+l+'" instead!!'),o(l,l,t));break;case to:throw new Error("attribute value missed!!")}return u;case"\x80":d=" ";default:if(d<=" ")switch(c){case eo:r.setTagName(e.slice(t,u)),c=ro;break;case un:s=e.slice(t,u),c=Ni;break;case Ei:var l=e.slice(t,u);a.warning('attribute "'+l+'" missed quot(")!!'),o(s,l,t);case Di:c=ro;break}else switch(c){case Ni:var p=r.tagName;(!no.isHTML(n[""])||!s.match(/^(?:disabled|checked|selected)$/i))&&a.warning('attribute "'+s+'" missed value!! "'+s+'" instead2!!'),o(s,s,t),t=u,c=un;break;case Di:a.warning('attribute space is required"'+s+'"!!');case ro:c=un,t=u;break;case to:c=Ei,t=u;break;case Vs:throw new Error("elements closed character '/' and '>' must be connected to")}}u++}}function c0(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={},p0(r,r={})),r[c]=i[c]=s,a.uri=no.XMLNS,t.startPrefixMapping(c,s))}for(var d=e.length;d--;){a=e[d];var l=a.prefix;l&&(l==="xml"&&(a.uri=no.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 bL(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 wL(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 p0(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function AL(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=SL(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 CL(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 f0(){this.attributeNames={}}f0.prototype={setTagName:function(e){if(!l0.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},addValue:function(e,t,r){if(!l0.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 SL(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}Sd.XMLReader=d0;Sd.ParseError=Ii});var A0=g(zs=>{var NL=Ha(),EL=Ad(),h0=o0(),y0=m0(),DL=EL.DOMImplementation,g0=NL.NAMESPACE,IL=y0.ParseError,_L=y0.XMLReader;function b0(e){return e.replace(/\r[\n\u0085]/g,``).replace(/[\r\u0085\u2028]/g,`-`)}function th(e){this.options=e||{locator:{}}}th.prototype.parseFromString=function(e,t){var r=this.options,n=new XP,i=r.domBuilder||new aa,a=r.errorHandler,o=r.locator,s=r.xmlns||{},l=/\/x?html?$/.test(t),u=l?Xm.HTML_ENTITIES:Xm.XML_ENTITIES;o&&i.setDocumentLocator(o),n.errorHandler=KP(a,i,o),n.domBuilder=r.domBuilder||i,l&&(s[""]=Km.HTML),s.xml=s.xml||Km.XML;var c=r.normalizeLineEndings||eh;return e&&typeof e=="string"?n.parse(c(e),s,u):n.errorHandler.error("invalid doc source"),i.doc};function KP(e,t,r){if(!e){if(t instanceof aa)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+zu(r))}||function(){}}return a("warning"),a("error"),a("fatalError"),n}function aa(){this.cdata=!1}function Un(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}aa.prototype={startDocument:function(){this.doc=new JP().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;Mo(this,a),this.currentElement=a,this.locator&&Un(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&&Un(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&&Un(this.locator,r),Mo(this,r)},ignorableWhitespace:function(e,t,r){},characters:function(e,t,r){if(e=Ym.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&&Un(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=Ym.apply(this,arguments);var n=this.doc.createComment(e);this.locator&&Un(this.locator,n),Mo(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&&Un(this.locator,i),Mo(this,i),this.doc.doctype=i}},warning:function(e){console.warn("[xmldom warning] "+e,zu(this.locator))},error:function(e){console.error("[xmldom error] "+e,zu(this.locator))},fatalError:function(e){throw new QP(e,this.locator)}};function zu(e){if(e)return`-@`+(e.systemId||"")+"#[line:"+e.lineNumber+",col:"+e.columnNumber+"]"}function Ym(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){aa.prototype[e]=function(){return null}});function Mo(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}Uo.__DOMHandler=aa;Uo.normalizeLineEndings=eh;Uo.DOMParser=th});var Wu=m(Bo=>{var nh=$u();Bo.DOMImplementation=nh.DOMImplementation;Bo.XMLSerializer=nh.XMLSerializer;Bo.DOMParser=rh().DOMParser});var ih=m(qo=>{"use strict";Object.defineProperty(qo,"__esModule",{value:!0});qo.deleteAppCascade=void 0;var YP=_u(),ju=Bi(),ZP=be(),ko=ce(),eO=Wu();function Hu(e){return e instanceof Error?e:new Error(String(e))}function tO(e){let t=[],r=s=>l=>t.push(`${s}: ${l}`),i=new eO.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml").documentElement;if(!i||t.length>0)throw new ZP.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,ko.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}async function rO(e,t,r){let n=(0,ko.normalizeGuid)(t,"appModuleId");(0,ko.normalizeGuid)(r,"appModuleIdUnique");let i=[],a=[],o=[];await(0,YP.deleteAppResolvingOnce)(e,n,s=>{s!==void 0&&o.push(...tO(s))}),i.push({type:"app",id:n});for(let s of new Set(o)){let l;try{l=await(0,ju.queryAllRecords)(e,"uxagentprojectfile",{select:["uxagentprojectfileid"],filter:`_uxagentprojectid_value eq ${s}`})}catch(u){a.push({operation:"resolve",type:"genPageFile",id:s,error:Hu(u)});continue}for(let u of l??[]){let c="";try{c=(0,ko.normalizeGuid)(String(u.uxagentprojectfileid),"uxagentprojectfileid"),await(0,ju.deleteRecord)(e,"uxagentprojectfile",c),i.push({type:"genPageFile",id:c})}catch(d){a.push({operation:"delete",type:"genPageFile",id:c,error:Hu(d)})}}try{await(0,ju.deleteRecord)(e,"uxagentproject",s),i.push({type:"genPage",id:s})}catch(u){a.push({operation:"delete",type:"genPage",id:s,error:Hu(u)})}}return{success:a.length===0,deleted:i,failures:a}}qo.deleteAppCascade=rO});var ah={};Bt(ah,{Guid:()=>_});var _,De=D(()=>{"use strict";_=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 P,We=D(()=>{"use strict";Ce();P=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,"&").replace(/</g,"<").replace(/>/g,">"),r&&(n=n.replace(/"/g,""").replace(/'/g,"'"))),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(!S.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 S.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 oh={};Bt(oh,{ScriptUtilities:()=>S});var S,Ce=D(()=>{"use strict";De();We();S=class e{static IsNullOrUndefined(t){return t==null||t===void 0}static IsMacMachine(){return navigator.platform.indexOf("Mac")!==-1}static IsNullOrEmptyGuid(t){return P.IsNullOrEmpty(t.ToString())?!0:_.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:P.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 $o,Vo,Yr,Go,Ju,zo,Qu=D(()=>{"use strict";(function(e){e[e.FormElementNodeChange=0]="FormElementNodeChange",e[e.FormElementAttributeChange=1]="FormElementAttributeChange"})($o||($o={}));Vo=class{type;targetNode;constructor(t,r){this.type=t,this.targetNode=r}},Yr=class extends Vo{key;oldValue;newValue;constructor(t,r,n,i){super($o.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)}},Go=class extends Vo{property;oldValue;newValue;constructor(t,r,n,i){super($o.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)}},Ju=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()})}},zo=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 Ju(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 sh={};Bt(sh,{ChartGridMode:()=>yt,ColumnLayoutWidths:()=>sO,ComponentCategory:()=>jo,ComponentType:()=>Xu,ControlLayoutTypes:()=>nc,DisplayConditionsInfo:()=>aO,ElementNames:()=>g,ElementProperties:()=>p,ElementType:()=>Yu,EntityAttributeProperty:()=>Zu,EventType:()=>oa,FormActivationState:()=>rc,FormCanvasServiceScope:()=>yO,FormDesignerSideBarTab:()=>Ku,FormPresentation:()=>ec,FormState:()=>Wo,FormType:()=>Ee,HeaderDensityType:()=>Tr,LookUpTable:()=>Wt,MORE_TAB_PREFIX:()=>uO,NavBarChildElementType:()=>tc,PREVIEW_ID_HEADER_FLYOUT:()=>fO,PREVIEW_ID_HEADER_OVERFLOW_BUTTON:()=>hO,PREVIEW_ID_NAVIGATION_AREA:()=>dO,PREVIEW_ID_QUICKCREATE_ROOT:()=>vO,PREVIEW_ID_TAB:()=>gO,PREVIEW_ID_TAB_LIST:()=>mO,PREVIEW_ID_TAB_PANEL:()=>pO,PropertyModelKeys:()=>oc,PropertyModelSectionKeys:()=>lO,RELATED_TAB_ID:()=>sc,RELATED_TAB_PREFIX:()=>cO,SectionDefaultProperties:()=>oO,SectionLayoutTypes:()=>pe,TabContentType:()=>ic,TabDefaultProperties:()=>Rr,TabLayoutTypes:()=>de,TelemetryPropertyNames:()=>bO,UnboundControlPropertyKeys:()=>ac,compositeAddressFields:()=>iO,compositeFieldNames:()=>ht,compositeFields:()=>nO});var Ee,Xu,Ku,g,p,Yu,ht,nO,iO,Zu,Wt,Wo,Tr,ec,aO,tc,rc,de,oO,Rr,pe,nc,ic,sO,ac,oc,lO,oa,yt,sc,uO,cO,dO,pO,fO,mO,hO,gO,vO,bO,jo,yO,G=D(()=>{"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"})(Ee||(Ee={}));(function(e){e[e.Form=0]="Form",e[e.Dialog=1]="Dialog"})(Xu||(Xu={}));(function(e){e[e.Components=0]="Components",e[e.Properties=1]="Properties",e[e.Relationship=2]="Relationship",e[e.BusinessRules=3]="BusinessRules"})(Ku||(Ku={}));(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"})(g||(g={}));p={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"})(Yu||(Yu={}));ht={fullname:"fullname",yomifullname:"yomifullname",address1_composite:"address1_composite",address2_composite:"address2_composite",address3_composite:"address3_composite",billto:"billto_composite",shipto:"shipto_composite"},nO=[ht.fullname,ht.yomifullname,ht.address1_composite,ht.address2_composite,ht.address3_composite,ht.billto,ht.shipto],iO=[ht.address1_composite,ht.address2_composite,ht.address3_composite,ht.billto,ht.shipto];(function(e){e[e.IsValidForForm=0]="IsValidForForm",e[e.IsValidForCreate=1]="IsValidForCreate"})(Zu||(Zu={}));(function(e){e[e.DependencyFieldTable=0]="DependencyFieldTable",e[e.LockedFieldTable=1]="LockedFieldTable"})(Wt||(Wt={}));(function(e){e[e.Published=0]="Published",e[e.Draft=1]="Draft",e[e.New=2]="New",e[e.SaveAs=3]="SaveAs"})(Wo||(Wo={}));(function(e){e.Low="Low",e.HighReadOnlyValues="HighReadOnlyValues",e.HighWithControls="HighWithControls"})(Tr||(Tr={}));(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(ec||(ec={}));aO={TopOrderFormId:"topOrderFormId",NextDisplayOrder:"nextDisplayOrder"};(function(e){e[e.NavBarRelationShipItem=0]="NavBarRelationShipItem",e[e.NavBarItem=1]="NavBarItem"})(tc||(tc={}));(function(e){e[e.InActive=0]="InActive",e[e.Active=1]="Active"})(rc||(rc={}));(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"})(de||(de={}));oO={ShowLabel:"false",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_"},Rr={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"})(pe||(pe={}));(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"})(nc||(nc={}));(function(e){e.cardSections="cardSections",e.singleComponent="singleComponent",e.default="default",e.expandAvailableSpace="expandAvailableSpace"})(ic||(ic={}));sO={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"})(ac||(ac={}));(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"})(oc||(oc={}));lO={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"})(oa||(oa={}));(function(e){e.All="All",e.Chart="Chart",e.Grid="Grid"})(yt||(yt={}));sc="tab_related3b554255-7717-4d17-bb7f-9936fb1e75ca",uO="more_tab_",cO="related_tab_",dO="preview_id_navigation_area",pO="tab-section",fO="headerFieldsFlyout",mO="tablist",hO="header_overflowButton",gO="tab",vO="quickCreateRoot",bO={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"})(jo||(jo={}));yO="CellCanvasServiceScope"});var lh={};Bt(lh,{Attribute:()=>Ho,FormElementNode:()=>q});var Ho,q,Le=D(()=>{"use strict";Ce();We();Qu();G();De();Ho=class{key;value;constructor(t,r){this.key=t,this.value=r}},q=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-${_.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(g.form);r&&r.raiseMetadataChange(t)}trackPropertyAddition(t,r){this.trackPropertyCollectionChange(()=>{this.properties.push(new Ho(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 Yr(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 Yr(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 Yr(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 Go(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 Yr(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){S.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(S.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:P.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=S.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 g.formCell:let t=this.getAncestor(g.formSection);return t||(t=this.getAncestor(g.formHeader),t)||(t=this.getAncestor(g.formFooter),t)?t:null;case g.formSection:return this.getAncestor(g.formTab);case g.formTab:return this.getAncestor(g.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(g.form);return t?t.changeTracker():null}}});var uh={};Bt(uh,{ControlClassId:()=>A,ControlNamePrefixes:()=>Jo,getControlDisplayNames:()=>CO});function CO(e){return{[A.AccessPrivilegeControl]:e("controls.controlNames.accessPrivilege"),[A.AccessTeamTablePickerControl]:e("controls.controlNames.accessTeamTablePicker"),[A.ACIControl]:e("controls.controlNames.aci"),[A.ActivitiesContainerControl]:e("controls.controlNames.activitiesContainer"),[A.ActivitiesWallControl]:e("controls.controlNames.activitiesWall"),[A.AppliedFiltersControl]:e("controls.controlNames.appliedFilters"),[A.ArticleContentControl]:e("controls.controlNames.articleContent"),[A.BooleanControl]:e("controls.controlNames.twoOption"),[A.ButtonControl]:e("controls.controlNames.button"),[A.CheckboxControl]:e("controls.controlNames.checkbox"),[A.CompositionLinkControl]:e("controls.controlNames.compositionLink"),[A.ConnectionControl]:e("controls.controlNames.connection"),[A.ConnectionRoleObjectTypeListControl]:e("controls.controlNames.connectionRoleObjectTypeList"),[A.CoverageChoiceControl]:e("controls.controlNames.coverageChoice"),[A.DashboardControl]:e("controls.controlNames.dashboard"),[A.DynamicPropertyListControl]:e("controls.controlNames.dynamicPropertyList"),[A.EditFilterControl]:e("controls.controlNames.editFilter"),[A.ErrorStatusControl]:e("controls.controlNames.errorStatus"),[A.GlobalFilterControl]:e("controls.controlNames.globalFilter"),[A.HiddenInputControl]:e("controls.controlNames.hiddenInput"),[A.KBViewerControl]:e("controls.controlNames.kbViewer"),[A.LabelControl]:e("controls.controlNames.label"),[A.MailMergeLanguagePickerControl]:e("controls.controlNames.mailMergeLanguagePicker"),[A.MapLinkControl]:e("controls.controlNames.mapLink"),[A.OrgInsightsControl]:e("controls.controlNames.orgInsights"),[A.ChoiceLookupControl]:e("controls.controlNames.choiceLookup"),[A.PowerBIControl]:e("controls.controlNames.powerBI"),[A.ProcessControl]:e("controls.controlNames.process"),[A.RelatedInformationControl]:e("controls.controlNames.relatedInformation"),[A.RelationshipRoleChoiceControl]:e("controls.controlNames.relationshipRoleChoice"),[A.ReportControl]:e("controls.controlNames.report"),[A.StreamsControl]:e("controls.controlNames.streams"),[A.WebResourceSilverlightControl]:e("controls.controlNames.webResourceSilverlight"),[A.CurrencyControl]:e("controls.controlNames.currency"),[A.DateTimeControl]:e("controls.controlNames.dateAndTime"),[A.DecimalControl]:e("controls.controlNames.decimal"),[A.DurationControl]:e("controls.controlNames.duration"),[A.EmailAddressControl]:e("controls.controlNames.email"),[A.FileControl]:e("controls.controlNames.file"),[A.FloatingNumberControl]:e("controls.controlNames.floatingNumber"),[A.IframeControl]:e("controls.controlNames.iframe"),[A.ImageControl]:e("controls.controlNames.image"),[A.LookupControl]:e("controls.controlNames.lookup"),[A.MapsControl]:e("controls.controlNames.maps"),[A.PhoneNumberControl]:e("controls.controlNames.phoneNumber"),[A.ChoiceControl]:e("controls.controlNames.choice"),[A.QuickViewControl]:e("controls.controlNames.quickView"),[A.QuickFormControl]:e("controls.controlNames.quickForm"),[A.CustomControl]:e("controls.controlNames.customControl"),[A.SearchWidgetControl]:e("controls.controlNames.searchWidget"),[A.SocialInsightsControl]:e("controls.controlNames.socialInsights"),[A.SubgridControl]:e("controls.controlNames.subgrid"),[A.TextAreaControl]:e("controls.controlNames.textArea"),[A.TextboxControl]:e("controls.controlNames.textBox"),[A.TickerControl]:e("controls.controlNames.ticker"),[A.UrlControl]:e("controls.controlNames.url"),[A.WebResourceHTMLControl]:e("controls.controlNames.webResourceHTML"),[A.WebResourceImageControl]:e("controls.controlNames.webResourceImage"),[A.IntegerControl]:e("controls.controlNames.integer"),[A.TimerControl]:e("controls.controlNames.timer"),[A.TimelineControl]:e("controls.controlNames.timeline"),[A.EmailBodyControl]:e("controls.controlNames.emailBody"),[A.PartyListControl]:e("controls.controlNames.partyList"),[A.TimezoneControl]:e("controls.controlNames.timezone"),[A.LanguageControl]:e("controls.controlNames.language"),[A.ChoiceStatusControl]:e("controls.controlNames.choiceStatus"),[A.ChoicesControl]:e("controls.controlNames.choices"),[A.RegardingControl]:e("controls.controlNames.regarding"),[A.EmailEngagementActionsControl]:e("controls.controlNames.emailEngagementActions"),[A.EmailRecipientActivityControl]:e("controls.controlNames.emailRecipientActivity"),[A.ReferencePanelSearchWidgetControl]:e("controls.controlNames.referencePanelSearchWidget"),[A.ReferencePanelQuickViewControl]:e("controls.controlNames.referencePanelQuickView"),[A.ReferencePanelSubgridControl]:e("controls.controlNames.referencePanelSubgrid"),[A.KBEditorControl]:e("controls.controlNames.KBEditor"),[A.LinkControl]:e("controls.controlNames.link")}}var A,Jo,Zr=D(()=>{"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"})(A||(A={}));Jo={[A.WebResourceHTMLControl]:"WebResource",[A.WebResourceImageControl]:"WebResource",[A.IframeControl]:"IFRAME",[A.SearchWidgetControl]:"Search widget",[A.SubgridControl]:"Subgrid",[A.TimelineControl]:"Timeline",[A.QuickViewControl]:"QuickviewControl"}});var en=m((u8,dh)=>{var sa=new Proxy(function(){return sa},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:sa},apply:function(){return sa},construct:function(){return{}}}),ch=function(){return sa};Object.setPrototypeOf(ch,sa);dh.exports=ch});var Xe,fr,ph,fh,Bn=D(()=>{"use strict";Xe="cds-designer-models",fr="FormCustomControl",ph="FormCell",fh="Form"});var kn,Ke,la=D(()=>{"use strict";kn=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}},Ke=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 tn,lc=D(()=>{"use strict";la();G();tn=class e{static lockedFieldCount=new Ke;static dependencyFieldCount=new Ke;static getNecessaryLookUpTable(t){switch(t){case Wt.DependencyFieldTable:return e.dependencyFieldCount;case Wt.LockedFieldTable:return e.lockedFieldCount}}static initCanvasLockedFieldLookUp(t){switch(t){case Wt.DependencyFieldTable:e.dependencyFieldCount=new Ke;case Wt.LockedFieldTable:e.lockedFieldCount=new Ke}}}});var Qo,mh=D(()=>{"use strict";De();Ce();G();Le();Qo=class extends q{constructor(t){super(g.controlDescription,t)}get forControl(){let t=this.getProperty(p.ForControl);return S.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new _(t))}set forControl(t){this.setProperty(p.ForControl,`{${t.ToString()}}`)}get customControls(){return this.getChildren(g.customControl)}set customControls(t){this.deleteAllChildren();for(let r of t)this.addChild(r)}get DefaultControlClassId(){for(let t of this.customControls)if(!S.IsNullOrUndefined(t.id))return t.id;return null}get DefaultCustomControl(){for(let t of this.customControls)if(!S.IsNullOrUndefined(t.id))return t;return null}get DefaultCustomControls(){let t=[];for(let r of this.customControls)S.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 gh,vh,Ye,E,hh,Fr,rn,qn,uc,cc,$n=D(()=>{"use strict";gh={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"},vh={GroupDefinition:"GroupDefinition"},Ye={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"})(E||(E={}));(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"})(hh||(hh={}));(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"})(Fr||(Fr={}));(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"})(rn||(rn={}));(function(e){e[e.Bound=0]="Bound",e[e.Input=1]="Input",e[e.Output=2]="Output"})(qn||(qn={}));uc=[E.LookupCustomer,E.LookupOwner,E.LookupPartyList,E.LookupRegarding,E.LookupSimple],cc=[E.WholeNone,E.WholeDuration,E.WholeLanguage,E.WholeTimeZone,E.FP,E.Decimal]});function mr(){return jt||(jt=window._makerConfig,jt&&window?.location?.search?.indexOf("useProductionConfig")>-1&&(jt={...jt,region:"prod",graphQLEndpoint:"https://graph.make.powerapps.com/"}),jt?.region==="prod"&&(jt={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/"}}},...jt}),jt||{aadClientId:"a8f7a65c-f5ba-4859-b2d6-df772c264e9d",location:"cus",region:"test",publicPath:"/",graphQLEndpoint:"https://graph.make.test.powerapps.com/"})}var jt,Xo=D(()=>{"use strict";});function bh(e,t,r){if(!e)return Ko.has(e)||(window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoIsEmpty"}),Ko.add("")),!1;if(e){if(e=e.toLowerCase(),Ko.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}}),Ko.add(e),!1}return!0}function AO(e){return bh(e,dc,"Location dictionary")?dc[e.toLowerCase()]:"us"}function wO(){let e=mr().location.toLowerCase();return bh(e,dc,"Current location dictionary")?e:"us"}var Ko,dc,S8,yh=D(()=>{"use strict";Xo();Ko=new Set,dc={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"};S8=AO(wO())});var x,E8,Ch=D(()=>{"use strict";x={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"},E8={[x.USWest]:{geoName:"us",regionShortName:"wus"},[x.USCentral]:{geoName:"us",regionShortName:"cus"},[x.USEast]:{geoName:"us",regionShortName:"eus"},[x.USEast2]:{geoName:"us",regionShortName:"eus2"},[x.USWestCentral]:{geoName:"us",regionShortName:"wcus"},[x.USWest2]:{geoName:"us",regionShortName:"wus2"},[x.USSouthCentral]:{geoName:"br",regionShortName:"scus"},[x.BrazilSouth]:{geoName:"br",regionShortName:"sbr"},[x.UKSouth]:{geoName:"uk",regionShortName:"suk"},[x.UKWest]:{geoName:"uk",regionShortName:"wuk"},[x.JapanEast]:{geoName:"jp",regionShortName:"ejp"},[x.JapanWest]:{geoName:"jp",regionShortName:"wjp"},[x.IndiaCentral]:{geoName:"in",regionShortName:"cin"},[x.IndiaSouth]:{geoName:"in",regionShortName:"sin"},[x.ItalyNorth]:{geoName:"it",regionShortName:"nit"},[x.GermanyWestCentral]:{geoName:"de",regionShortName:"wcde"},[x.GermanyNorth]:{geoName:"de",regionShortName:"nde"},[x.EuropeNorth]:{geoName:"eu",regionShortName:"neu"},[x.EuropeWest]:{geoName:"eu",regionShortName:"weu"},[x.AustraliaEast]:{geoName:"au",regionShortName:"eau"},[x.AustraliaSouthEast]:{geoName:"au",regionShortName:"seau"},[x.AsiaSouthEast]:{geoName:"as",regionShortName:"seas"},[x.AsiaEast]:{geoName:"as",regionShortName:"eas"},[x.CanadaCentral]:{geoName:"ca",regionShortName:"cca"},[x.CanadaEast]:{geoName:"ca",regionShortName:"eca"},[x.SouthAfricaNorth]:{geoName:"za",regionShortName:"nza"},[x.SouthAfricaWest]:{geoName:"za",regionShortName:"wza"},[x.FranceCentral]:{geoName:"fr",regionShortName:"cfr"},[x.FranceSouth]:{geoName:"fr",regionShortName:"sfr"},[x.UAENorth]:{geoName:"ae",regionShortName:"nae"},[x.UAECentral]:{geoName:"ae",regionShortName:"cae"},[x.SwedenCentral]:{geoName:"se",regionShortName:"cse"},[x.SwitzerlandNorth]:{geoName:"ch",regionShortName:"nch"},[x.SwitzerlandWest]:{geoName:"ch",regionShortName:"wch"},[x.NorwayEast]:{geoName:"no",regionShortName:"eno"},[x.NorwayWest]:{geoName:"no",regionShortName:"wno"},[x.KoreaCentral]:{geoName:"kr",regionShortName:"ckr"},[x.KoreaSouth]:{geoName:"kr",regionShortName:"skr"},[x.SingaporeSouthEast]:{geoName:"sg",regionShortName:"seas"},[x.PolandCentral]:{geoName:"pl",regionShortName:"cpl"},[x.QatarCentral]:{geoName:"qa",regionShortName:"cqa"},[x.NewZealandNorth]:{geoName:"nz",regionShortName:"nnz"},[x.GovernmentUSTexas]:{geoName:"us",regionShortName:"ugtx"},[x.GovernmentUSVirginia]:{geoName:"us",regionShortName:"ugva"},[x.GovernmentUSDodCentral]:{regionShortName:"udc"},[x.GovernmentUSDodEast]:{regionShortName:"ude"},[x.ChinaEast]:{regionShortName:"cne"},[x.ChinaEast2]:{regionShortName:"cne2"},[x.ChinaEast3]:{regionShortName:"cne3"},[x.ChinaNorth]:{regionShortName:"cnn"},[x.ChinaNorth2]:{regionShortName:"cnn2"},[x.ChinaNorth3]:{regionShortName:"cnn3"},[x.UssecEast]:{geoName:"us",regionShortName:"erx"},[x.UssecWest]:{geoName:"us",regionShortName:"wrx"},[x.UsnatEast]:{geoName:"us",regionShortName:"eex"},[x.UsnatWest]:{geoName:"us",regionShortName:"wex"}}});var Ah=D(()=>{"use strict";Xo();});var ua=D(()=>{"use strict";Xo();yh();Ch();Ah();});function ca(e,t){return wh?wh.isOverridden(e,t):{overridden:!1}}var wh,da=D(()=>{"use strict";});var pc=D(()=>{"use strict";ua();da();});function NO(e,t){let{region:r}=mr();return()=>{let n=e.settings[t];if(n.allowOverrides){let s=ca(e.packageName,t);if(s.overridden)return typeof s.value=="string"?SO(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 SO(e){return isNaN(Number(e))?e==="true"?!0:e==="false"?!1:e:Number(e)}function DO(e){let t=e.packageName;if(Yo.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=>mc(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=>!es(i))){let i=`error parsing settings config for package ${t}, setting ${r} has invalid region`;throw console.error(i),new Error(i)}})}function pa(e){DO(e);let t={};return Object.keys(e.settings).forEach(r=>{t[r]={enumerable:!0,get:NO(e,r)}}),Yo.set(e.packageName,e),Object.defineProperties({},t)}function fc(e,t){return Yo.has(e)?!!Yo.get(e).settings[t]:!1}var Yo,Zo=D(()=>{"use strict";ua();da();hc();fa();Yo=new Map});function Nh(e,t){let{region:r}=mr();return()=>{let n=ca(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 EO(e){let t=e.packageName;if(ts.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=>fc(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=>!es(i))){let i=`error parsing feature gates config for package ${t}, feature ${r} has invalid region`;throw console.error(i),new Error(i)}})}function gc(e){EO(e);let t={};Object.keys(e.features).forEach(i=>{t[i]={enumerable:!0,configurable:!0,get:Nh(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:Nh(e,a.toString())}}),Object.defineProperties(r,i),n.clear()}},ts.set(e.packageName,e),Object.defineProperties(r,t)}function mc(e,t){return ts.has(e)?!!ts.get(e).features[t]:!1}var ts,hc=D(()=>{"use strict";ua();fa();da();Zo();ts=new Map});var Dh=m((K8,Sh)=>{"use strict";Sh.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 _h=m(vc=>{"use strict";var IO=Object.prototype.hasOwnProperty,_O;function Eh(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch{return null}}function Ih(e){try{return encodeURIComponent(e)}catch{return null}}function PO(e){for(var t=/([^=?#&]+)=?([^&]*)/g,r={},n;n=t.exec(e);){var i=Eh(n[1]),a=Eh(n[2]);i===null||a===null||i in r||(r[i]=a)}return r}function OO(e,t){t=t||"";var r=[],n,i;typeof t!="string"&&(t="?");for(i in e)if(IO.call(e,i)){if(n=e[i],!n&&(n===null||n===_O||isNaN(n))&&(n=""),i=Ih(i),n=Ih(n),i===null||n===null)continue;r.push(i+"="+n)}return r.length?t+r.join("&"):""}vc.stringify=OO;vc.parse=PO});var Cc=m((Z8,xh)=>{"use strict";var Oh=Dh(),rs=_h(),Th=/[\n\r\t]/g,TO=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,RO=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,FO=/^[a-zA-Z]:/,xO=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;function yc(e){return(e||"").toString().replace(xO,"")}var bc=[["#","hash"],["?","query"],function(t,r){return Ht(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]],Ph={hash:1,query:1};function Rh(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 Jt(unescape(e.pathname),{});else if(i==="string"){n=new Jt(e,{});for(a in Ph)delete n[a]}else if(i==="object"){for(a in e)a in Ph||(n[a]=e[a]);n.slashes===void 0&&(n.slashes=TO.test(e.href))}return n}function Ht(e){return e==="file:"||e==="ftp:"||e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function Fh(e,t){e=yc(e),e=e.replace(Th,""),t=t||{};var r=RO.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)):Ht(n)?s=r[4]:n?i&&(s=s.slice(2)):o>=2&&Ht(t.protocol)&&(s=r[4]),{protocol:n,slashes:i||Ht(n),slashesCount:o,rest:s}}function LO(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 Jt(e,t,r){if(e=yc(e),e=e.replace(Th,""),!(this instanceof Jt))return new Jt(e,t,r);var n,i,a,o,s,l,u=bc.slice(),c=typeof t,d=this,f=0;for(c!=="object"&&c!=="string"&&(r=t,t=null),r&&typeof r!="function"&&(r=rs.parse),t=Rh(t),i=Fh(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||FO.test(e))||!i.slashes&&(i.protocol||i.slashesCount<2||!Ht(d.protocol)))&&(u[3]=[/(.*)/,"pathname"]);f<u.length;f++){if(o=u[f],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=LO(d.pathname,t.pathname)),d.pathname.charAt(0)!=="/"&&Ht(d.protocol)&&(d.pathname="/"+d.pathname),Oh(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:"&&Ht(d.protocol)&&d.host?d.protocol+"//"+d.host:"null",d.href=d.toString()}function MO(e,t,r){var n=this;switch(e){case"query":typeof t=="string"&&t.length&&(t=(r||rs.parse)(t)),n[e]=t;break;case"port":n[e]=t,Oh(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<bc.length;o++){var s=bc[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:"&&Ht(n.protocol)&&n.host?n.protocol+"//"+n.host:"null",n.href=n.toString(),n}function UO(e){(!e||typeof e!="function")&&(e=rs.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||Ht(r.protocol)?"//":"");return r.username?(a+=r.username,r.password&&(a+=":"+r.password),a+="@"):r.password?(a+=":"+r.password,a+="@"):r.protocol!=="file:"&&Ht(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}Jt.prototype={set:MO,toString:UO};Jt.extractProtocol=Fh;Jt.location=Rh;Jt.trimLeft=yc;Jt.qs=rs;xh.exports=Jt});var BO,Lh=D(()=>{"use strict";BO=ne(Cc());});function Ac(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 ns=D(()=>{"use strict";});var wc,Nc,Sc=D(()=>{"use strict";ns();wc=class{features=new Map;register(t,r){let n=Ac(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()}},Nc=new wc});var Dc=D(()=>{"use strict";});function es(e){return kO.has(e)}var kO,fa=D(()=>{"use strict";pc();hc();Zo();da();pc();Lh();Sc();ns();Dc();kO=new Set(["tie","test","prod","preview","preprod","gov","high","dod","mooncake","ex","rx"])});var qO,Mh=D(()=>{"use strict";fa();qO=pa({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 is,O,L,nn,Vn,as,Uh,Bh,Ec,ma=D(()=>{"use strict";la();is=class{name;constructor(t){this.name=t}toString(){return this.name}getName(){return this.name}getDisplayNameResourceKey(){return Ec.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"})(O||(O={}));(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"})(L||(L={}));nn=class extends is{constructor(t){super(t)}static get None(){return"None"}static get SystemRequired(){return"SystemRequired"}static get ApplicationRequired(){return"ApplicationRequired"}static get Recommended(){return"Recommended"}},Vn=class e extends is{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?as.Persistent:parseInt(as[this.name])}};(function(e){e[e.Persistent=0]="Persistent",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup"})(as||(as={}));(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"})(Uh||(Uh={}));(function(e){e[e.Attribute=0]="Attribute",e[e.Organization=1]="Organization",e[e.Currency=2]="Currency"})(Bh||(Bh={}));Ec=class e{static resourceKeyMap=e.initResourceKeyMap();static initResourceKeyMap(){let t=new kn;return t.add(O.TwoOptions,"SystemCustomization.type.bit.label"),t.add(O.Customer,"SystemCustomization.type.customer.label"),t.add(O.CustomerType,"SystemCustomization.type.customer.label"),t.add(O.DateTime,"SystemCustomization.type.datetime.label"),t.add(O.DecimalNumber,"SystemCustomization.type.decimal.label"),t.add(O.FloatingPointNumber,"SystemCustomization.type.float.label"),t.add(O.WholeNumber,"SystemCustomization.type.int.label"),t.add(O.LookupType,"SystemCustomization.type.lookup.label"),t.add(O.Lookup,"SystemCustomization.type.lookup.label"),t.add(O.MultipleLineofText,"SystemCustomization.type.ntext.label"),t.add(O.Currency,"SystemCustomization.type.money.label"),t.add(O.Owner,"SystemCustomization.type.owner.label"),t.add(O.OwnerType,"SystemCustomization.type.owner.label"),t.add(O.PartyList,"SystemCustomization.type.partylist.label"),t.add(O.PartyListType,"SystemCustomization.type.partylist.label"),t.add(O.OptionSet,"SystemCustomization.type.picklist.label"),t.add(O.State,"SystemCustomization.type.state.label"),t.add(O.Status,"SystemCustomization.type.status.label"),t.add(O.SingleLineofText,"SystemCustomization.type.nvarchar.label"),t.add(O.UniqueIdentifier,"SystemCustomization.type.uniqueidentifier.label"),t.add(O.UniqueIdentifierType,"SystemCustomization.type.uniqueidentifiertype.label"),t.add(O.CalendarRulesType,"SystemCustomization.type.calendarrules.label"),t.add(O.VirtualType,"SystemCustomization.type.virtual.label"),t.add(O.BigInt,"SystemCustomization.type.bigint.label"),t.add(O.ManagedPropertyType,"SystemCustomization.type.managedproperty.label"),t.add(O.EntityNameType,"SystemCustomization.type.entityname.label"),t.add(O.Image,"SystemCustomization.type.image.label"),t.add(O.MultiSelectOptionSet,"SystemCustomization.type.multiselectpicklist.label"),t.add(O.PrimaryNameAttributeType,"SystemCustomization.type.primaryname.label"),t.add(O.LookupType,"SystemCustomization.type.lookuptype.label"),t.add(O.Subject,"SystemCustomization.type.subject.label"),t.add(L.Email,"SystemCustomization.String.Format.email"),t.add(L.Text,"SystemCustomization.String.Format.text"),t.add(L.TextArea,"SystemCustomization.String.Format.textarea"),t.add(L.Url,"SystemCustomization.String.Format.url"),t.add(L.TickerSymbol,"SystemCustomization.String.Format.tickersymbol"),t.add(L.PhoneticGuide,"SystemCustomization.String.Format.phoneticguide"),t.add(L.VersionNumber,"SystemCustomization.String.Format.versionnumber"),t.add(L.Phone,"SystemCustomization.String.Format.phone"),t.add(L.None,"SystemCustomization.Integer.Format."),t.add(L.Duration,"SystemCustomization.Integer.Format.duration"),t.add(L.TimeZone,"SystemCustomization.Integer.Format.timezone"),t.add(L.Language,"SystemCustomization.Integer.Format.language"),t.add(L.Locale,"SystemCustomization.Integer.Format.language"),t.add(L.DateOnly,"SystemCustomization.DateTime.Format.date"),t.add(L.DateAndTime,"SystemCustomization.DateTime.Format.datetime"),t.add(L.Regarding,"SystemCustomization.Lookup.Format.regarding"),t.add(Vn.Persistent,"SystemCustomization.String.Source.persistent"),t.add(Vn.Calculated,"SystemCustomization.String.Source.calculated"),t.add(Vn.Rollup,"SystemCustomization.String.Source.rollup"),t.add(Vn.None,"SystemCustomization.String.Source.none"),t}static getDisplayNameResourceKey(t){return e.resourceKeyMap.getValue(t)}}});var Vh,_c,Gn,an,Ic,os,zn,hr,le,kh,qh,$h,Rt=D(()=>{"use strict";Vh={ThreeEqColumn_FirstColumn:34,ThreeEqColumn_SecondColumn:33,ThreeEqColumn_ThirdColumn:33,FiveEqColumn:20},_c={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"})(Gn||(Gn={}));(function(e){e.Left="Left",e.Right="Right",e.Center="Center"})(an||(an={}));(function(e){e[e.Mobile=0]="Mobile",e[e.Tablet=1]="Tablet",e[e.Web=2]="Web"})(Ic||(Ic={}));os=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"})(zn||(zn={}));hr=class{static StartTag="<"},le={ShowLabel:"true",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_",labelAlignment:an.Left,labelPosition:zn.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"})(kh||(kh={}));(function(e){e.TabWithLockedFieldRemoval="TabWithLockedFieldRemoval",e.SectionWithLockedFieldRemoval="SectionWithLockedFieldRemoval",e.LockedSectionRemoval="LockedSectionRemoval",e.LockedFieldRemoval="LockedFieldRemoval",e.RequiredFieldRemoval="RequiredFieldRemoval",e.LastRemainingTab="LastRemainingTab",e.UnknownRemoval="UnknownRemoval"})(qh||(qh={}));(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"})($h||($h={}))});var ha=m(C=>{"use strict";Object.defineProperty(C,"__esModule",{value:!0});C.DateTimeBehavior=C.PrecisionSource=C.StringFormatName=C.SourceType=C.ImeMode=C.SolutionEntityTypeCodeExtToComponentTypeCode=C.SolutionComponentTypeCodeToEntityTypeCodeExt=C.SolutionComponentVirtualAttributeSubtype=C.EntityTypeCode=C.SolutionComponentTypeCodeExt=C.RootComponentBehavior=C.SolutionComponentTypeCode=C.EntityKeyIndexStatus=C.ViewStateCode=C.ViewStatusCode=C.RelationshipSecurityTypes=C.CascadeType=C.RelationshipTypeExt=C.RelationshipType=C.AppSubType=C.BusinessProcessType=C.WorkflowCategory=C.WorkflowScope=C.WorkflowTypeCode=C.StatusCodeEnabledDisabled=C.StateCodeEnabledDisabled=C.StatusCode=C.StateCode=C.OptionSetType=C.AttributeTypeCodeNum=C.AttributeFormatName=C.AttributeFormatCode=C.AttributeTypeName=C.AttributeTypeCode=C.PluginSourceType=C.AuthType=C.PluginIsolationMode=C.ComponentState=C.ChartType=C.ChartsType=C.ViewType=C.AttributeType=C.ActivationState=C.FormPresentation=C.FormType=C.TableTypeCode=C.TableTypes=C.ActivityTypeMask=C.PrincipalType=C.OwnershipTypes=void 0;C.QueryType=C.KnownCustomSolutionComponentEntitySetName=C.TeamTypeEnum=C.EnvironmentVariableDefinitionTypeEnum=C.ConnectorTypeEnum=C.RoleInheritance=C.DefaultRoleTemplates=C.DeleteDependencyErrorCode=C.ServiceEndpointConnectionMode=C.ServiceEndpointContract=C.ServiceNamespaceFormat=C.ConnectionRoleCategory=C.ReportTypeCode=C.SdkMessageProcessingMode=C.SupportedDeployment=C.SdkMessageProcessingStage=C.WebResourceTypeCode=C.IntegerFormat=C.DateTimeFormat=void 0;var Gh;(function(e){e.None="None",e.UserOwned="UserOwned",e.TeamOwned="TeamOwned",e.BusinessOwned="BusinessOwned",e.OrganizationOwned="OrganizationOwned",e.BusinessParented="BusinessParented",e.Filtered="Filtered"})(Gh||(C.OwnershipTypes=Gh={}));var zh;(function(e){e.User="Microsoft.Dynamics.CRM.systemuser",e.Team="Microsoft.Dynamics.CRM.team"})(zh||(C.PrincipalType=zh={}));var Wh;(function(e){e[e.DoNotDisplayInActivityMenus=0]="DoNotDisplayInActivityMenus",e[e.DisplayInActivityMenus=1]="DisplayInActivityMenus"})(Wh||(C.ActivityTypeMask=Wh={}));var jh;(function(e){e.Activity="Activity",e.Virtual="Virtual",e.Standard="Standard",e.Elastic="Elastic"})(jh||(C.TableTypes=jh={}));var Hh;(function(e){e.Standard="Standard",e.Virtual="Virtual",e.Elastic="Elastic"})(Hh||(C.TableTypeCode=Hh={}));var Jh;(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"})(Jh||(C.FormType=Jh={}));var Qh;(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(Qh||(C.FormPresentation=Qh={}));var Xh;(function(e){e[e.Inactive=0]="Inactive",e[e.Active=1]="Active"})(Xh||(C.ActivationState=Xh={}));var Kh;(function(e){e[e.String=0]="String",e[e.Number=1]="Number",e[e.Picklist=2]="Picklist"})(Kh||(C.AttributeType=Kh={}));var Yh;(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"})(Yh||(C.ViewType=Yh={}));var Zh;(function(e){e[e.ASPChart=0]="ASPChart",e[e.PowerBI=1]="PowerBI"})(Zh||(C.ChartsType=Zh={}));var eg;(function(e){e[e.DataAndInteractionCentric=0]="DataAndInteractionCentric",e[e.InteractionCentric=1]="InteractionCentric"})(eg||(C.ChartType=eg={}));var tg;(function(e){e[e.Published=0]="Published",e[e.Unpublished=1]="Unpublished",e[e.Deleted=2]="Deleted",e[e.DeletedUnpublished=3]="DeletedUnpublished"})(tg||(C.ComponentState=tg={}));var rg;(function(e){e[e.None=1]="None",e[e.Sandbox=2]="Sandbox",e[e.External=3]="External"})(rg||(C.PluginIsolationMode=rg={}));var ng;(function(e){e[e.BasicAuth=0]="BasicAuth"})(ng||(C.AuthType=ng={}));var ig;(function(e){e[e.Database=0]="Database",e[e.Disk=1]="Disk",e[e.Normal=2]="Normal",e[e.AzureWebApp=3]="AzureWebApp"})(ig||(C.PluginSourceType=ig={}));var ag;(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"})(ag||(C.AttributeTypeCode=ag={}));var og;(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"})(og||(C.AttributeTypeName=og={}));var sg;(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"})(sg||(C.AttributeFormatCode=sg={}));var lg;(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"})(lg||(C.AttributeFormatName=lg={}));var ug;(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"})(ug||(C.AttributeTypeCodeNum=ug={}));var cg;(function(e){e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean"})(cg||(C.OptionSetType=cg={}));var dg;(function(e){e[e.Draft=0]="Draft",e[e.Activated=1]="Activated"})(dg||(C.StateCode=dg={}));var pg;(function(e){e[e.Draft=1]="Draft",e[e.Activated=2]="Activated"})(pg||(C.StatusCode=pg={}));var fg;(function(e){e[e.Enabled=0]="Enabled",e[e.Disabled=1]="Disabled"})(fg||(C.StateCodeEnabledDisabled=fg={}));var mg;(function(e){e[e.Enabled=1]="Enabled",e[e.Disabled=2]="Disabled"})(mg||(C.StatusCodeEnabledDisabled=mg={}));var hg;(function(e){e[e.Definition=1]="Definition",e[e.Activation=2]="Activation",e[e.Template=3]="Template"})(hg||(C.WorkflowTypeCode=hg={}));var gg;(function(e){e[e.User=1]="User",e[e.BusinessUnit=2]="BusinessUnit",e[e.ParentChildBusinessUnit=3]="ParentChildBusinessUnit",e[e.Organization=4]="Organization"})(gg||(C.WorkflowScope=gg={}));var vg;(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"})(vg||(C.WorkflowCategory=vg={}));var bg;(function(e){e[e.None=-1]="None",e[e.BusinessFlow=0]="BusinessFlow",e[e.TaskFlow=1]="TaskFlow"})(bg||(C.BusinessProcessType=bg={}));var yg;(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"})(yg||(C.AppSubType=yg={}));var Cg;(function(e){e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(Cg||(C.RelationshipType=Cg={}));var Ag;(function(e){e.ManyToOneRelationship="ManyToOneRelationship",e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(Ag||(C.RelationshipTypeExt=Ag={}));var wg;(function(e){e.NoCascade="NoCascade",e.Cascade="Cascade",e.Active="Active",e.UserOwned="UserOwned",e.RemoveLink="RemoveLink",e.Restrict="Restrict"})(wg||(C.CascadeType=wg={}));var Ng;(function(e){e.None="None",e.Append="Append",e.ParentChild="ParentChild",e.Pointer="Pointer",e.Inheritance="Inheritance"})(Ng||(C.RelationshipSecurityTypes=Ng={}));var Sg;(function(e){e[e.Active=1]="Active",e[e.Inactive=2]="Inactive"})(Sg||(C.ViewStatusCode=Sg={}));var Dg;(function(e){e[e.Active=0]="Active",e[e.Inactive=1]="Inactive"})(Dg||(C.ViewStateCode=Dg={}));var Eg;(function(e){e.Active="Active",e.Failed="Failed",e.InProgress="InProgress",e.Pending="Pending"})(Eg||(C.EntityKeyIndexStatus=Eg={}));var Ig;(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"})(Ig||(C.SolutionComponentTypeCode=Ig={}));var _g;(function(e){e[e.IncludeSubcomponents=0]="IncludeSubcomponents",e[e.DoNotIncludeSubcomponents=1]="DoNotIncludeSubcomponents",e[e.IncludeAsShellOnly=2]="IncludeAsShellOnly"})(_g||(C.RootComponentBehavior=_g={}));var ss;(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"})(ss||(C.SolutionComponentTypeCodeExt=ss={}));var ls;(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"})(ls||(C.EntityTypeCode=ls={}));var Pg;(function(e){e.MultiSelectPicklist="MultiSelectPicklist",e.File="File",e.Image="Image"})(Pg||(C.SolutionComponentVirtualAttributeSubtype=Pg={}));function $O(e){let t=ss[e];return ls[t]}C.SolutionComponentTypeCodeToEntityTypeCodeExt=$O;function VO(e){let t=ls[e];return ss[t]}C.SolutionEntityTypeCodeExtToComponentTypeCode=VO;var Og;(function(e){e.Active="Active",e.Auto="Auto",e.Disabled="Disabled",e.Inactive="Inactive"})(Og||(C.ImeMode=Og={}));var Tg;(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"})(Tg||(C.SourceType=Tg={}));var Rg;(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"})(Rg||(C.StringFormatName=Rg={}));var Fg;(function(e){e[e.PrecisionProperty=0]="PrecisionProperty",e[e.Organization=1]="Organization",e[e.TransactionCurrency=2]="TransactionCurrency"})(Fg||(C.PrecisionSource=Fg={}));var xg;(function(e){e.UserLocal="UserLocal",e.DateOnly="DateOnly",e.TimeZoneIndependent="TimeZoneIndependent"})(xg||(C.DateTimeBehavior=xg={}));var Lg;(function(e){e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(Lg||(C.DateTimeFormat=Lg={}));var Mg;(function(e){e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(Mg||(C.IntegerFormat=Mg={}));var Ug;(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"})(Ug||(C.WebResourceTypeCode=Ug={}));var Bg;(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"})(Bg||(C.SdkMessageProcessingStage=Bg={}));var kg;(function(e){e[e.ServerOnly=0]="ServerOnly",e[e.OutlookClientOnly=1]="OutlookClientOnly",e[e.Both=2]="Both"})(kg||(C.SupportedDeployment=kg={}));var qg;(function(e){e[e.Synchronous=0]="Synchronous",e[e.Asynchronous=1]="Asynchronous"})(qg||(C.SdkMessageProcessingMode=qg={}));var $g;(function(e){e[e.ReportingServicesReport=1]="ReportingServicesReport",e[e.OtherReport=2]="OtherReport",e[e.LinkedReport=3]="LinkedReport"})($g||(C.ReportTypeCode=$g={}));var Vg;(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"})(Vg||(C.ConnectionRoleCategory=Vg={}));var Gg;(function(e){e[e.Name=1]="Name",e[e.Address=2]="Address"})(Gg||(C.ServiceNamespaceFormat=Gg={}));var zg;(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"})(zg||(C.ServiceEndpointContract=zg={}));var Wg;(function(e){e[e.Normal=1]="Normal",e[e.Federated=2]="Federated"})(Wg||(C.ServiceEndpointConnectionMode=Wg={}));var jg;(function(e){e.CannotDeleteInUseComponent="0x8004f01f",e.CannotDeleteInUseAttribute="0x80048418",e.CannotDeleteInUseOptionSet="0x80048417",e.CannotDeleteInUseEntity="0x80048420",e.CannotUninstallWithDependencies="0x8004F01D"})(jg||(C.DeleteDependencyErrorCode=jg={}));var Hg;(function(e){e.SystemAdministrator="627090FF-40A3-4053-8790-584EDC5BE201",e.SystemCustomizer="119F245C-3CC8-4B62-B31C-D1A046CED15D"})(Hg||(C.DefaultRoleTemplates=Hg={}));var Jg;(function(e){e[e.DefaultTeamPrivilege=0]="DefaultTeamPrivilege",e[e.DirectUserAndTeamPrivilege=1]="DirectUserAndTeamPrivilege"})(Jg||(C.RoleInheritance=Jg={}));var Qg;(function(e){e[e.NotSpecified=0]="NotSpecified",e[e.CustomConnector=1]="CustomConnector"})(Qg||(C.ConnectorTypeEnum=Qg={}));var Xg;(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"})(Xg||(C.EnvironmentVariableDefinitionTypeEnum=Xg={}));var Kg;(function(e){e[e.Owner=0]="Owner",e[e.Access=1]="Access",e[e.AADSecurityGroup=2]="AADSecurityGroup",e[e.AADOfficeGroup=3]="AADOfficeGroup"})(Kg||(C.TeamTypeEnum=Kg={}));var Yg;(function(e){e.Bots="bots"})(Yg||(C.KnownCustomSolutionComponentEntitySetName=Yg={}));var Zg;(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"})(Zg||(C.QueryType=Zg={}))});var Pc,e0=D(()=>{"use strict";(function(e){e.DefaultValue="defaultValue",e.Loaded="loaded"})(Pc||(Pc={}))});var n0,GO,t0,Y6,Z6,ga,r0,e7,t7,i0=D(()=>{"use strict";n0=ne(en());Ce();Bn();Mh();ma();Rt();$n();G();GO=ne(ha());e0();(function(e){e.Model="Model",e.Canvas="Canvas",e.CustomPages="CustomPages"})(t0||(t0={}));Y6={Read:rn.Read,Edit:rn.Edit,Both:rn.Both,Container:rn.Container},Z6={input:qn.Input,bound:qn.Bound,output:qn.Output};(function(e){e[e.dataset=0]="dataset",e[e.property=1]="property",e[e.groups=2]="groups",e[e.group=3]="group"})(ga||(ga={}));(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"})(r0||(r0={}));e7=new Set([E.Currency,E.Decimal,E.FP,E.Multiple,E.SingleLineEmail,E.SingleLinePhone,E.SingleLineText,E.SingleLineTextArea,E.SingleLineURL,E.SingleLineTickerSymbol,E.WholeNone,E.WholeDuration,E.WholeLanguage,E.WholeTimeZone,E.Enum,E.LookupSimple,E.LookupCustomer,E.LookupOwner,E.LookupPartyList,E.LookupRegarding,E.TwoOptions,E.Boolean,E.PowerBIReport,E.DateAndTimeDateAndTime,E.DateAndTimeDateOnly,E.OptionSet,E.MultiSelectOptionSet,E.CardForm]),t7={numbers:[E.WholeNone,E.FP,E.Decimal,E.Currency],text:[E.SingleLineText,E.SingleLineTextArea,E.Multiple],lookup:[E.LookupSimple,E.LookupCustomer,E.LookupOwner,E.LookupPartyList,E.LookupRegarding],dates:[E.DateAndTimeDateOnly,E.DateAndTimeDateAndTime],allFields:[E.TwoOptions,E.DateAndTimeDateOnly,E.DateAndTimeDateAndTime,E.FP,E.Decimal,E.WholeNone,E.WholeDuration,E.WholeTimeZone,E.WholeLanguage,E.LookupSimple,E.LookupCustomer,E.LookupOwner,E.LookupPartyList,E.LookupRegarding,E.Multiple,E.OptionSet,E.SingleLineText,E.SingleLineTextArea,E.SingleLineEmail,E.SingleLineURL,E.SingleLineTickerSymbol,E.SingleLinePhone]}});var Ft,us,a0=D(()=>{"use strict";Ft=ne(en());De();Ce();We();Bn();$n();i0();ma();G();Le();Rt();us=class extends q{constructor(t){super(g.customControl,t)}customControlId;get id(){let t=this.getProperty(p.id);return S.IsNullOrUndefined(t)?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new _(t.substr(1,t.length-2)):new _(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(Ye.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===Ye.name)?.value}getParameterChildrenValues(t,r,n){if(this.isDataSet(t)){let i=r.find(u=>u.key===Ye.name)?.value,a={Name:i,Type:E.Grid,Columns:[]},l=this.getParameters().get(Ye.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===p.static&&a.value==="true"){r=!0;break}}return r}get name(){return this.getProperty(p.Name)}get formFactor(){return this.getProperty(p.formFactor)}set formFactor(t){this.setProperty(p.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(hr.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),f=await this.parameterJSON(o,u,d,t);r.push({Name:c,Value:f})}else if(this.isGroups(s))r.push({Name:o,Value:{Type:vh.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===ga.dataset?a.get(Ye.dataset)?.some(h=>this.getDatasetName(h)===d)||r.push({Name:d,Value:{Name:d,Columns:[],Type:E.Grid}}):c.propertyType===ga.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,Ft.trackInfoTrace)(Xe,{eventName:`${fr}/parametersToJSON`,eventData:{message:`Configuration metadata for custom control parameter ${o} is not available for custom control : ${this.name}.`}}),r=[];break}}}else(0,Ft.trackErrorTrace)(Xe,{eventName:`${fr}/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,Ft.trackErrorTrace)(Xe,{eventName:`${fr}/parametersToJSON`,eventData:{message:"Custom Control Manifest not found"}},new Error(`No custom control manifest found for ${this.name}`))}catch(n){(0,Ft.trackErrorTrace)(Xe,{eventName:`${fr}/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===Ye.name)?.value;if(a)return this.getParameterChildrenValues(t,r);{let s=new Error(`No dataset manifest info for ${o}`);(0,Ft.trackErrorTrace)(Xe,{eventName:`${fr}/parameterJSON`,eventData:{message:"Missing custom control manifest dataset info"}},s)}}else{let a=n,o=r&&r.find(l=>l.key===p.Type),s=a&&!a.ofTypeGroup.every(l=>!uc.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===Fr.FormComponent){let d=this.getFormComponentValueByParameterName(p.bindAttribute),f=await i.formModelService.loadLookupModel(d),h=f.lookupColumn,b=this.getLookupDataTypeFromAttributeMetadata(h);return{Name:t,Type:b,Usage:l,Static:u,Primary:c,EntityName:f.primaryTableName,Value:d,ViewId:this.getFormComponentValueByParameterName(gh.DefaultViewId),TargetEntityType:h.targets[0],FilterRelationshipName:this.getFormComponentValueByParameterName(p.FilterRelationshipName),AvailableViewIds:this.getFormComponentValueByParameterName(p.AvailableViewIds),DependentAttributeName:this.getFormComponentValueByParameterName(p.DependentAttributeName),DependentAttributeType:this.getFormComponentValueByParameterName(p.DependentAttributeType),AllowFilterOff:P.IsStrictTrue(this.getFormComponentValueByParameterName(p.AllowFilterOff)),DisableQuickFind:P.IsStrictTrue(this.getFormComponentValueByParameterName(p.DisableQuickFind)),EnableViewPicker:!P.IsStrictTrue(this.getFormComponentValueByParameterName(p.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,Ft.trackErrorTrace)(Xe,{eventName:`${fr}/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 h=o.value;return{Type:h,Static:u,Usage:l,Value:this.isNumberTypeProperty(a,h)&&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 f=new Error(`No property type info for ${t}`);(0,Ft.trackErrorTrace)(Xe,{eventName:`${fr}/parameterJSON`,eventData:{message:"Missing property type info"}},f)}else{let l=new Error(`No property manifest info for ${t}`);(0,Ft.trackWarningTrace)(Xe,{eventName:`${fr}/parameterJSON`,eventData:{message:"Missing custom control manifest property info"}},l)}}return null}getLookupDataTypeFromAttributeMetadata(t){let{attributeType:r,format:n}=t;switch(r){case O.Customer:return E.LookupCustomer;case O.Owner:return E.LookupOwner;case O.PartyList:return E.LookupPartyList;default:return n===L.Regarding?E.LookupRegarding:E.LookupSimple}}isLookupType(t){return uc.includes(t)}isNumberTypeProperty(t,r){return cc.includes(r)||t.ofTypeGroup.some(n=>cc.includes(n))}isDataSet(t){return Ye.dataset===t}isGroups(t){return!!t[0].getAllProperties().find(n=>n.key==="isGroup"&&n.value==="true")}}});var U,Oc=D(()=>{"use strict";U=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 T,Wn,Ie,cs=D(()=>{"use strict";De();la();Ce();We();ma();Zr();Oc();Rt();T=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"}},Wn=class{static get RelationshipAssistant(){return"3ff9a528-dd50-4aca-8f10-2e5ed73513ad"}static get PredictiveLeadScoring(){return"6f503f2a-d033-4106-b62c-f8f2e5f01a57"}},Ie=class e{static FieldControlIds=e.initializeFieldControls();static UnboundControlIds=e.initializeUnboundControls();static ControlsAllowedForReferencePanel=e.initializeReferencePanelControls();static ControlsAllowedForFooter=e.initializeFooterControls();static CustomControlIdMap=new Ke;static initializeFieldControls(){let t=new Ke,r=e.getControlName(O.SingleLineofText,L.Phone);t.add(r,new _(T.PhoneNumberControl));let n=e.getControlName(O.SingleLineofText,L.TextArea);t.add(n,new _(T.TextAreaControl));let i=e.getControlName(O.SingleLineofText,L.Text);t.add(i,new _(T.TextBoxControl));let a=e.getControlName(O.SingleLineofText,L.Email);t.add(a,new _(T.EmailAddressControl));let o=e.getControlName(O.SingleLineofText,L.Url);t.add(o,new _(T.UrlControl));let s=e.getControlName(O.SingleLineofText,L.TickerSymbol);t.add(s,new _(T.TickerControl));let l=e.getControlName(O.SingleLineofText,L.PhoneticGuide);t.add(l,new _(T.TextBoxControl));let u=e.getControlName(O.WholeNumber,L.Duration);t.add(u,new _(T.DurationControl));let c=e.getControlName(O.WholeNumber,L.Language);t.add(c,new _(T.LanguagePickerControl));let d=e.getControlName(O.WholeNumber,L.TimeZone);t.add(d,new _(T.TimeZonePicklistControl));let f=e.getControlName(O.WholeNumber,L.None);t.add(f,new _(T.IntegerControl));let h=e.getControlName(O.DateTime,L.DateOnly);t.add(h,new _(T.DateTimeControl));let b=e.getControlName(O.DateTime,L.DateAndTime);t.add(b,new _(T.DateTimeControl));let w=e.getControlName(O.LookupType,L.None);t.add(w,new _(T.LookupControl));let N=e.getControlName(O.CustomerType,L.None);t.add(N,new _(T.LookupControl));let I=e.getControlName(O.FloatingPointNumber,L.None);t.add(I,new _(T.FloatControl));let R=e.getControlName(O.DecimalNumber,L.None);t.add(R,new _(T.DecimalControl));let F=e.getControlName(O.Currency,L.None);t.add(F,new _(T.MoneyControl));let M=e.getControlName(O.MultipleLineofText,L.None);t.add(M,new _(T.TextAreaControl));let W=e.getControlName(O.MultipleLineofText,L.Text);t.add(W,new _(T.TextAreaControl));let B=e.getControlName(O.MultipleLineofText,L.TextArea);t.add(B,new _(T.TextAreaControl));let j=e.getControlName(O.MultipleLineofText,L.Email);t.add(j,new _(T.EmailBodyControl));let k=e.getControlName(O.OptionSet,L.None);t.add(k,new _(T.PicklistControl));let $=e.getControlName(O.TwoOptions,L.None);t.add($,new _(T.RadioControl));let re=e.getControlName(O.Image,L.None);t.add(re,new _(T.WebResourceImageControl));let H=e.getControlName(O.Image,L.None);t.add(H,new _(T.WebResourceHtmlControl));let nr=e.getControlName(O.TwoOptions,"Radio");t.add(nr,new _(T.RadioControl));let Il=e.getControlName(O.TwoOptions,"CheckBox");t.add(Il,new _(T.CheckBoxControl));let Oi=e.getControlName(O.TwoOptions,"List");t.add(Oi,new _(T.PicklistControl));let io=e.getControlName(O.State,L.None);t.add(io,new _(T.PicklistControl));let ue=e.getControlName(O.Status,L.None);t.add(ue,new _(T.PicklistStatusControl));let rt=e.getControlName(O.OwnerType,L.None);t.add(rt,new _(T.LookupControl));let _l=e.getControlName(O.PartyListType,L.None);t.add(_l,new _(T.PartyListControl));let ID=e.getControlName(O.LookupType,L.Regarding);t.add(ID,new _(T.RegardingControl));let _D=e.getControlName(O.MultiSelectOptionSet,L.None);return t.add(_D,new _(T.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(!S.IsNullOrEmptyGuid(t)){let r=e.getTypeAndFormatByControlOrUniqueId(t.guidString.toLowerCase());return r=S.IsNullOrUndefined(r)?e.getUnboundControlNameFromIdentifier(t):r.substring(0,r.indexOf("_")),r}return null}static isCustomControl(t){return S.IsNullOrUndefined(t.control)||S.IsNullOrUndefined(t.control.ClassId)||t.control.ClassId.guidString===T.CustomControl}static initializeUnboundControls(){let t=new Ke;return t.add(T.ACIControl,U.ACIControl),t.add(T.IframeControl,U.IframeControl),t.add(T.SearchWidgetControl,U.SearchWidgetControl),t.add(T.MapsControl,U.MapsControl),t.add(T.QuickFormCollectionControl,U.QuickFormCollectionControl),t.add(T.GridControl,U.SubGridControl),t.add(T.WebResourceImageControl,U.WebResourceImageControl),t.add(T.WebResourceHtmlControl,U.WebResourceHtmlControl),t.add(T.ReferencePanelSearchWidget,U.SearchWidgetControl),t.add(T.ReferencePanelQuickFormCollectionControl,U.QuickFormCollectionControl),t.add(T.ReferencePanelSubgridControl,U.SubGridControl),t.add(T.TimerControl,U.TimerControl),t.add(T.TimeLineControl,U.NotesControl),t.add(T.TimeLineControlUC,U.NotesControl),t.add(T.SocialInsightControl,U.SocialInsightControl),t.add(Wn.RelationshipAssistant,U.CustomControl),t}static initializeReferencePanelControls(){let t=new Ke;return t.add(T.IframeControl,U.IframeControl),t.add(T.ReferencePanelSearchWidget,U.SearchWidgetControl),t.add(T.ReferencePanelQuickFormCollectionControl,U.QuickFormCollectionControl),t.add(T.ReferencePanelSubgridControl,U.SubGridControl),t.add(T.WebResourceHtmlControl,U.WebResourceHtmlControl),t.add(T.WebResourceImageControl,U.WebResourceHtmlControl),t}static initializeFooterControls(){let t=new kn;return t.add(Gn.IFRAME,!0),t.add(Gn.SPACER,!0),t.add(Gn.WEB_RESOURCE_HTML,!0),t}static isUnboundFormControl(t){if(S.IsNullOrUndefined(t)||S.IsNullOrUndefined(t.control)||S.IsNullOrUndefined(t.control.ClassId))return!1;let r=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.containsKey(r.guidString)}static isReferencePanelSection(t){return!S.IsNullOrUndefined(t)&&!S.IsNullOrUndefined(t.Name)&&t.Name.indexOf(le.referencePanelNamePrefix)===0}static isUnboundFormControlByIdentifier(t){return S.IsNullOrUndefined(t)||S.IsNullOrUndefined(t.guidString)?!1:e.UnboundControlIds.containsKey(t.guidString)}static getUnboundFormControlName(t){let r=P.EmptyString;if(S.IsNullOrUndefined(t)||S.IsNullOrUndefined(t.control)||S.IsNullOrUndefined(t.control.ClassId))return r;let n=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.getValue(n.guidString).toString()}static getUnboundControlNameFromIdentifier(t){return S.IsNullOrUndefined(t)||S.IsNullOrUndefined(t.guidString)?P.EmptyString:e.UnboundControlIds.getValue(t.guidString).toString()}static isSpacerControl(t){return t===T.SpacerControl}static GetRowSpan(t){let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===T.CustomControl&&!S.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}switch(e.UnboundControlIds.getValue(r.guidString)){case U.IframeControl:case U.ACIControl:case U.SocialInsightControl:return 6;case U.SubGridControl:case U.CustomControl:return 4;case U.WebResourceImageControl:return 15;case U.WebResourceHtmlControl:return 15;case U.MapsControl:return 8;case U.SearchWidgetControl:return 10;case U.NotesControl:case U.TimeLineControl:return 15;case U.TimerControl:return 2;default:}}static isLookUpControl(t){return!S.IsNullOrUndefined(t)&&t.ClassId.guidString===T.LookupControl}static isRelationshipAssistantOrLeadScoringControl(t){return!S.IsNullOrUndefined(t)&&e.isRelationshipAssistantOrLeadScoring(t.UniqueId)}static isRelationshipAssistantOrLeadScoring(t){return!S.IsNullOrUndefined(t)&&(t.guidString===Wn.RelationshipAssistant||t.guidString===Wn.PredictiveLeadScoring)}static isRelationshipAssistantControl(t){return!S.IsNullOrUndefined(t)&&e.isRelationshipAssistant(t.UniqueId)}static isRelationshipAssistant(t){return!S.IsNullOrUndefined(t)&&t.guidString===Wn.RelationshipAssistant}static getUniqueIdentifierForControl(t){if(S.IsNullOrUndefined(t))return null;let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===T.CustomControl&&!S.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}return r}}});var ds,o0=D(()=>{"use strict";ds=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 on,jn,s0,l0,xr,u0,c0,Tc=D(()=>{"use strict";(function(e){e[e.Center=0]="Center",e[e.Left=1]="Left",e[e.Right=2]="Right"})(on||(on={}));(function(e){e[e.Left=0]="Left",e[e.Top=1]="Top"})(jn||(jn={}));(function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle"})(s0||(s0={}));(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"})(l0||(l0={}));(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"})(xr||(xr={}));(function(e){e[e.None=0]="None",e[e.SystemRequired=1]="SystemRequired",e[e.ApplicationRequired=2]="ApplicationRequired",e[e.Recommended=3]="Recommended"})(u0||(u0={}));(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"})(c0||(c0={}))});var Hn,d0=D(()=>{"use strict";fa();Hn=gc({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 p0(e){return{...e,extractConfig:t=>zO(t,Object.keys(e.fallback))}}function zO(e,t){let r={};for(let n of t)typeof e[n]<"u"&&(r[n]=e[n]);return r}var Rc=D(()=>{"use strict";});var Fc=m((P7,m0)=>{var va=new Proxy(function(){return va},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:va},apply:function(){return va},construct:function(){return{}}}),f0=function(){return va};Object.setPrototypeOf(f0,va);m0.exports=f0});var v0=m((O7,g0)=>{var ba=new Proxy(function(){return ba},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:ba},apply:function(){return ba},construct:function(){return{}}}),h0=function(){return ba};Object.setPrototypeOf(h0,ba);g0.exports=h0});var xc=m((T7,y0)=>{var ya=new Proxy(function(){return ya},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:ya},apply:function(){return ya},construct:function(){return{}}}),b0=function(){return ya};Object.setPrototypeOf(b0,ya);y0.exports=b0});var A0=m((R7,C0)=>{function WO(){this.__data__=[],this.size=0}C0.exports=WO});var Jn=m((F7,w0)=>{function jO(e,t){return e===t||e!==e&&t!==t}w0.exports=jO});var Ca=m((x7,N0)=>{var HO=Jn();function JO(e,t){for(var r=e.length;r--;)if(HO(e[r][0],t))return r;return-1}N0.exports=JO});var D0=m((L7,S0)=>{var QO=Ca(),XO=Array.prototype,KO=XO.splice;function YO(e){var t=this.__data__,r=QO(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():KO.call(t,r,1),--this.size,!0}S0.exports=YO});var I0=m((M7,E0)=>{var ZO=Ca();function eT(e){var t=this.__data__,r=ZO(t,e);return r<0?void 0:t[r][1]}E0.exports=eT});var P0=m((U7,_0)=>{var tT=Ca();function rT(e){return tT(this.__data__,e)>-1}_0.exports=rT});var T0=m((B7,O0)=>{var nT=Ca();function iT(e,t){var r=this.__data__,n=nT(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}O0.exports=iT});var Aa=m((k7,R0)=>{var aT=A0(),oT=D0(),sT=I0(),lT=P0(),uT=T0();function Qn(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])}}Qn.prototype.clear=aT;Qn.prototype.delete=oT;Qn.prototype.get=sT;Qn.prototype.has=lT;Qn.prototype.set=uT;R0.exports=Qn});var x0=m((q7,F0)=>{var cT=Aa();function dT(){this.__data__=new cT,this.size=0}F0.exports=dT});var M0=m(($7,L0)=>{function pT(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}L0.exports=pT});var B0=m((V7,U0)=>{function fT(e){return this.__data__.get(e)}U0.exports=fT});var q0=m((G7,k0)=>{function mT(e){return this.__data__.has(e)}k0.exports=mT});var Lc=m((z7,$0)=>{var hT=typeof global=="object"&&global&&global.Object===Object&&global;$0.exports=hT});var xt=m((W7,V0)=>{var gT=Lc(),vT=typeof self=="object"&&self&&self.Object===Object&&self,bT=gT||vT||Function("return this")();V0.exports=bT});var wa=m((j7,G0)=>{var yT=xt(),CT=yT.Symbol;G0.exports=CT});var H0=m((H7,j0)=>{var z0=wa(),W0=Object.prototype,AT=W0.hasOwnProperty,wT=W0.toString,Na=z0?z0.toStringTag:void 0;function NT(e){var t=AT.call(e,Na),r=e[Na];try{e[Na]=void 0;var n=!0}catch{}var i=wT.call(e);return n&&(t?e[Na]=r:delete e[Na]),i}j0.exports=NT});var Q0=m((J7,J0)=>{var ST=Object.prototype,DT=ST.toString;function ET(e){return DT.call(e)}J0.exports=ET});var sn=m((Q7,Y0)=>{var X0=wa(),IT=H0(),_T=Q0(),PT="[object Null]",OT="[object Undefined]",K0=X0?X0.toStringTag:void 0;function TT(e){return e==null?e===void 0?OT:PT:K0&&K0 in Object(e)?IT(e):_T(e)}Y0.exports=TT});var gr=m((X7,Z0)=>{function RT(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}Z0.exports=RT});var ps=m((K7,ev)=>{var FT=sn(),xT=gr(),LT="[object AsyncFunction]",MT="[object Function]",UT="[object GeneratorFunction]",BT="[object Proxy]";function kT(e){if(!xT(e))return!1;var t=FT(e);return t==MT||t==UT||t==LT||t==BT}ev.exports=kT});var rv=m((Y7,tv)=>{var qT=xt(),$T=qT["__core-js_shared__"];tv.exports=$T});var av=m((Z7,iv)=>{var Mc=rv(),nv=(function(){var e=/[^.]+$/.exec(Mc&&Mc.keys&&Mc.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function VT(e){return!!nv&&nv in e}iv.exports=VT});var Uc=m((eV,ov)=>{var GT=Function.prototype,zT=GT.toString;function WT(e){if(e!=null){try{return zT.call(e)}catch{}try{return e+""}catch{}}return""}ov.exports=WT});var lv=m((tV,sv)=>{var jT=ps(),HT=av(),JT=gr(),QT=Uc(),XT=/[\\^$.*+?()[\]{}|]/g,KT=/^\[object .+?Constructor\]$/,YT=Function.prototype,ZT=Object.prototype,eR=YT.toString,tR=ZT.hasOwnProperty,rR=RegExp("^"+eR.call(tR).replace(XT,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function nR(e){if(!JT(e)||HT(e))return!1;var t=jT(e)?rR:KT;return t.test(QT(e))}sv.exports=nR});var cv=m((rV,uv)=>{function iR(e,t){return e?.[t]}uv.exports=iR});var Lr=m((nV,dv)=>{var aR=lv(),oR=cv();function sR(e,t){var r=oR(e,t);return aR(r)?r:void 0}dv.exports=sR});var fs=m((iV,pv)=>{var lR=Lr(),uR=xt(),cR=lR(uR,"Map");pv.exports=cR});var Sa=m((aV,fv)=>{var dR=Lr(),pR=dR(Object,"create");fv.exports=pR});var gv=m((oV,hv)=>{var mv=Sa();function fR(){this.__data__=mv?mv(null):{},this.size=0}hv.exports=fR});var bv=m((sV,vv)=>{function mR(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}vv.exports=mR});var Cv=m((lV,yv)=>{var hR=Sa(),gR="__lodash_hash_undefined__",vR=Object.prototype,bR=vR.hasOwnProperty;function yR(e){var t=this.__data__;if(hR){var r=t[e];return r===gR?void 0:r}return bR.call(t,e)?t[e]:void 0}yv.exports=yR});var wv=m((uV,Av)=>{var CR=Sa(),AR=Object.prototype,wR=AR.hasOwnProperty;function NR(e){var t=this.__data__;return CR?t[e]!==void 0:wR.call(t,e)}Av.exports=NR});var Sv=m((cV,Nv)=>{var SR=Sa(),DR="__lodash_hash_undefined__";function ER(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=SR&&t===void 0?DR:t,this}Nv.exports=ER});var Ev=m((dV,Dv)=>{var IR=gv(),_R=bv(),PR=Cv(),OR=wv(),TR=Sv();function Xn(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])}}Xn.prototype.clear=IR;Xn.prototype.delete=_R;Xn.prototype.get=PR;Xn.prototype.has=OR;Xn.prototype.set=TR;Dv.exports=Xn});var Pv=m((pV,_v)=>{var Iv=Ev(),RR=Aa(),FR=fs();function xR(){this.size=0,this.__data__={hash:new Iv,map:new(FR||RR),string:new Iv}}_v.exports=xR});var Tv=m((fV,Ov)=>{function LR(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}Ov.exports=LR});var Da=m((mV,Rv)=>{var MR=Tv();function UR(e,t){var r=e.__data__;return MR(t)?r[typeof t=="string"?"string":"hash"]:r.map}Rv.exports=UR});var xv=m((hV,Fv)=>{var BR=Da();function kR(e){var t=BR(this,e).delete(e);return this.size-=t?1:0,t}Fv.exports=kR});var Mv=m((gV,Lv)=>{var qR=Da();function $R(e){return qR(this,e).get(e)}Lv.exports=$R});var Bv=m((vV,Uv)=>{var VR=Da();function GR(e){return VR(this,e).has(e)}Uv.exports=GR});var qv=m((bV,kv)=>{var zR=Da();function WR(e,t){var r=zR(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}kv.exports=WR});var ms=m((yV,$v)=>{var jR=Pv(),HR=xv(),JR=Mv(),QR=Bv(),XR=qv();function Kn(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])}}Kn.prototype.clear=jR;Kn.prototype.delete=HR;Kn.prototype.get=JR;Kn.prototype.has=QR;Kn.prototype.set=XR;$v.exports=Kn});var Gv=m((CV,Vv)=>{var KR=Aa(),YR=fs(),ZR=ms(),eF=200;function tF(e,t){var r=this.__data__;if(r instanceof KR){var n=r.__data__;if(!YR||n.length<eF-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new ZR(n)}return r.set(e,t),this.size=r.size,this}Vv.exports=tF});var Bc=m((AV,zv)=>{var rF=Aa(),nF=x0(),iF=M0(),aF=B0(),oF=q0(),sF=Gv();function Yn(e){var t=this.__data__=new rF(e);this.size=t.size}Yn.prototype.clear=nF;Yn.prototype.delete=iF;Yn.prototype.get=aF;Yn.prototype.has=oF;Yn.prototype.set=sF;zv.exports=Yn});var jv=m((wV,Wv)=>{var lF="__lodash_hash_undefined__";function uF(e){return this.__data__.set(e,lF),this}Wv.exports=uF});var Jv=m((NV,Hv)=>{function cF(e){return this.__data__.has(e)}Hv.exports=cF});var Xv=m((SV,Qv)=>{var dF=ms(),pF=jv(),fF=Jv();function hs(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new dF;++t<r;)this.add(e[t])}hs.prototype.add=hs.prototype.push=pF;hs.prototype.has=fF;Qv.exports=hs});var Yv=m((DV,Kv)=>{function mF(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}Kv.exports=mF});var eb=m((EV,Zv)=>{function hF(e,t){return e.has(t)}Zv.exports=hF});var kc=m((IV,tb)=>{var gF=Xv(),vF=Yv(),bF=eb(),yF=1,CF=2;function AF(e,t,r,n,i,a){var o=r&yF,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,f=!0,h=r&CF?new gF:void 0;for(a.set(e,t),a.set(t,e);++d<s;){var b=e[d],w=t[d];if(n)var N=o?n(w,b,d,t,e,a):n(b,w,d,e,t,a);if(N!==void 0){if(N)continue;f=!1;break}if(h){if(!vF(t,function(I,R){if(!bF(h,R)&&(b===I||i(b,I,r,n,a)))return h.push(R)})){f=!1;break}}else if(!(b===w||i(b,w,r,n,a))){f=!1;break}}return a.delete(e),a.delete(t),f}tb.exports=AF});var qc=m((_V,rb)=>{var wF=xt(),NF=wF.Uint8Array;rb.exports=NF});var ib=m((PV,nb)=>{function SF(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}nb.exports=SF});var ob=m((OV,ab)=>{function DF(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}ab.exports=DF});var db=m((TV,cb)=>{var sb=wa(),lb=qc(),EF=Jn(),IF=kc(),_F=ib(),PF=ob(),OF=1,TF=2,RF="[object Boolean]",FF="[object Date]",xF="[object Error]",LF="[object Map]",MF="[object Number]",UF="[object RegExp]",BF="[object Set]",kF="[object String]",qF="[object Symbol]",$F="[object ArrayBuffer]",VF="[object DataView]",ub=sb?sb.prototype:void 0,$c=ub?ub.valueOf:void 0;function GF(e,t,r,n,i,a,o){switch(r){case VF:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case $F:return!(e.byteLength!=t.byteLength||!a(new lb(e),new lb(t)));case RF:case FF:case MF:return EF(+e,+t);case xF:return e.name==t.name&&e.message==t.message;case UF:case kF:return e==t+"";case LF:var s=_F;case BF:var l=n&OF;if(s||(s=PF),e.size!=t.size&&!l)return!1;var u=o.get(e);if(u)return u==t;n|=TF,o.set(e,t);var c=IF(s(e),s(t),n,i,a,o);return o.delete(e),c;case qF:if($c)return $c.call(e)==$c.call(t)}return!1}cb.exports=GF});var fb=m((RV,pb)=>{function zF(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}pb.exports=zF});var Mr=m((FV,mb)=>{var WF=Array.isArray;mb.exports=WF});var gb=m((xV,hb)=>{var jF=fb(),HF=Mr();function JF(e,t,r){var n=t(e);return HF(e)?n:jF(n,r(e))}hb.exports=JF});var bb=m((LV,vb)=>{function QF(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}vb.exports=QF});var Cb=m((MV,yb)=>{function XF(){return[]}yb.exports=XF});var Nb=m((UV,wb)=>{var KF=bb(),YF=Cb(),ZF=Object.prototype,ex=ZF.propertyIsEnumerable,Ab=Object.getOwnPropertySymbols,tx=Ab?function(e){return e==null?[]:(e=Object(e),KF(Ab(e),function(t){return ex.call(e,t)}))}:YF;wb.exports=tx});var Db=m((BV,Sb)=>{function rx(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}Sb.exports=rx});var Ur=m((kV,Eb)=>{function nx(e){return e!=null&&typeof e=="object"}Eb.exports=nx});var _b=m((qV,Ib)=>{var ix=sn(),ax=Ur(),ox="[object Arguments]";function sx(e){return ax(e)&&ix(e)==ox}Ib.exports=sx});var Vc=m(($V,Tb)=>{var Pb=_b(),lx=Ur(),Ob=Object.prototype,ux=Ob.hasOwnProperty,cx=Ob.propertyIsEnumerable,dx=Pb((function(){return arguments})())?Pb:function(e){return lx(e)&&ux.call(e,"callee")&&!cx.call(e,"callee")};Tb.exports=dx});var Fb=m((VV,Rb)=>{function px(){return!1}Rb.exports=px});var gs=m((Ea,Zn)=>{var fx=xt(),mx=Fb(),Mb=typeof Ea=="object"&&Ea&&!Ea.nodeType&&Ea,xb=Mb&&typeof Zn=="object"&&Zn&&!Zn.nodeType&&Zn,hx=xb&&xb.exports===Mb,Lb=hx?fx.Buffer:void 0,gx=Lb?Lb.isBuffer:void 0,vx=gx||mx;Zn.exports=vx});var vs=m((GV,Ub)=>{var bx=9007199254740991,yx=/^(?:0|[1-9]\d*)$/;function Cx(e,t){var r=typeof e;return t=t??bx,!!t&&(r=="number"||r!="symbol"&&yx.test(e))&&e>-1&&e%1==0&&e<t}Ub.exports=Cx});var Gc=m((zV,Bb)=>{var Ax=9007199254740991;function wx(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=Ax}Bb.exports=wx});var qb=m((WV,kb)=>{var Nx=sn(),Sx=Gc(),Dx=Ur(),Ex="[object Arguments]",Ix="[object Array]",_x="[object Boolean]",Px="[object Date]",Ox="[object Error]",Tx="[object Function]",Rx="[object Map]",Fx="[object Number]",xx="[object Object]",Lx="[object RegExp]",Mx="[object Set]",Ux="[object String]",Bx="[object WeakMap]",kx="[object ArrayBuffer]",qx="[object DataView]",$x="[object Float32Array]",Vx="[object Float64Array]",Gx="[object Int8Array]",zx="[object Int16Array]",Wx="[object Int32Array]",jx="[object Uint8Array]",Hx="[object Uint8ClampedArray]",Jx="[object Uint16Array]",Qx="[object Uint32Array]",ae={};ae[$x]=ae[Vx]=ae[Gx]=ae[zx]=ae[Wx]=ae[jx]=ae[Hx]=ae[Jx]=ae[Qx]=!0;ae[Ex]=ae[Ix]=ae[kx]=ae[_x]=ae[qx]=ae[Px]=ae[Ox]=ae[Tx]=ae[Rx]=ae[Fx]=ae[xx]=ae[Lx]=ae[Mx]=ae[Ux]=ae[Bx]=!1;function Xx(e){return Dx(e)&&Sx(e.length)&&!!ae[Nx(e)]}kb.exports=Xx});var Vb=m((jV,$b)=>{function Kx(e){return function(t){return e(t)}}$b.exports=Kx});var zb=m((Ia,ei)=>{var Yx=Lc(),Gb=typeof Ia=="object"&&Ia&&!Ia.nodeType&&Ia,_a=Gb&&typeof ei=="object"&&ei&&!ei.nodeType&&ei,Zx=_a&&_a.exports===Gb,zc=Zx&&Yx.process,eL=(function(){try{var e=_a&&_a.require&&_a.require("util").types;return e||zc&&zc.binding&&zc.binding("util")}catch{}})();ei.exports=eL});var bs=m((HV,Hb)=>{var tL=qb(),rL=Vb(),Wb=zb(),jb=Wb&&Wb.isTypedArray,nL=jb?rL(jb):tL;Hb.exports=nL});var Wc=m((JV,Jb)=>{var iL=Db(),aL=Vc(),oL=Mr(),sL=gs(),lL=vs(),uL=bs(),cL=Object.prototype,dL=cL.hasOwnProperty;function pL(e,t){var r=oL(e),n=!r&&aL(e),i=!r&&!n&&sL(e),a=!r&&!n&&!i&&uL(e),o=r||n||i||a,s=o?iL(e.length,String):[],l=s.length;for(var u in e)(t||dL.call(e,u))&&!(o&&(u=="length"||i&&(u=="offset"||u=="parent")||a&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||lL(u,l)))&&s.push(u);return s}Jb.exports=pL});var ys=m((QV,Qb)=>{var fL=Object.prototype;function mL(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||fL;return e===r}Qb.exports=mL});var jc=m((XV,Xb)=>{function hL(e,t){return function(r){return e(t(r))}}Xb.exports=hL});var Yb=m((KV,Kb)=>{var gL=jc(),vL=gL(Object.keys,Object);Kb.exports=vL});var ey=m((YV,Zb)=>{var bL=ys(),yL=Yb(),CL=Object.prototype,AL=CL.hasOwnProperty;function wL(e){if(!bL(e))return yL(e);var t=[];for(var r in Object(e))AL.call(e,r)&&r!="constructor"&&t.push(r);return t}Zb.exports=wL});var Pa=m((ZV,ty)=>{var NL=ps(),SL=Gc();function DL(e){return e!=null&&SL(e.length)&&!NL(e)}ty.exports=DL});var ny=m((eG,ry)=>{var EL=Wc(),IL=ey(),_L=Pa();function PL(e){return _L(e)?EL(e):IL(e)}ry.exports=PL});var ay=m((tG,iy)=>{var OL=gb(),TL=Nb(),RL=ny();function FL(e){return OL(e,RL,TL)}iy.exports=FL});var ly=m((rG,sy)=>{var oy=ay(),xL=1,LL=Object.prototype,ML=LL.hasOwnProperty;function UL(e,t,r,n,i,a){var o=r&xL,s=oy(e),l=s.length,u=oy(t),c=u.length;if(l!=c&&!o)return!1;for(var d=l;d--;){var f=s[d];if(!(o?f in t:ML.call(t,f)))return!1}var h=a.get(e),b=a.get(t);if(h&&b)return h==t&&b==e;var w=!0;a.set(e,t),a.set(t,e);for(var N=o;++d<l;){f=s[d];var I=e[f],R=t[f];if(n)var F=o?n(R,I,f,t,e,a):n(I,R,f,e,t,a);if(!(F===void 0?I===R||i(I,R,r,n,a):F)){w=!1;break}N||(N=f=="constructor")}if(w&&!N){var M=e.constructor,W=t.constructor;M!=W&&"constructor"in e&&"constructor"in t&&!(typeof M=="function"&&M instanceof M&&typeof W=="function"&&W instanceof W)&&(w=!1)}return a.delete(e),a.delete(t),w}sy.exports=UL});var cy=m((nG,uy)=>{var BL=Lr(),kL=xt(),qL=BL(kL,"DataView");uy.exports=qL});var py=m((iG,dy)=>{var $L=Lr(),VL=xt(),GL=$L(VL,"Promise");dy.exports=GL});var my=m((aG,fy)=>{var zL=Lr(),WL=xt(),jL=zL(WL,"Set");fy.exports=jL});var gy=m((oG,hy)=>{var HL=Lr(),JL=xt(),QL=HL(JL,"WeakMap");hy.exports=QL});var Sy=m((sG,Ny)=>{var Hc=cy(),Jc=fs(),Qc=py(),Xc=my(),Kc=gy(),wy=sn(),ti=Uc(),vy="[object Map]",XL="[object Object]",by="[object Promise]",yy="[object Set]",Cy="[object WeakMap]",Ay="[object DataView]",KL=ti(Hc),YL=ti(Jc),ZL=ti(Qc),eM=ti(Xc),tM=ti(Kc),ln=wy;(Hc&&ln(new Hc(new ArrayBuffer(1)))!=Ay||Jc&&ln(new Jc)!=vy||Qc&&ln(Qc.resolve())!=by||Xc&&ln(new Xc)!=yy||Kc&&ln(new Kc)!=Cy)&&(ln=function(e){var t=wy(e),r=t==XL?e.constructor:void 0,n=r?ti(r):"";if(n)switch(n){case KL:return Ay;case YL:return vy;case ZL:return by;case eM:return yy;case tM:return Cy}return t});Ny.exports=ln});var Ry=m((lG,Ty)=>{var Yc=Bc(),rM=kc(),nM=db(),iM=ly(),Dy=Sy(),Ey=Mr(),Iy=gs(),aM=bs(),oM=1,_y="[object Arguments]",Py="[object Array]",Cs="[object Object]",sM=Object.prototype,Oy=sM.hasOwnProperty;function lM(e,t,r,n,i,a){var o=Ey(e),s=Ey(t),l=o?Py:Dy(e),u=s?Py:Dy(t);l=l==_y?Cs:l,u=u==_y?Cs:u;var c=l==Cs,d=u==Cs,f=l==u;if(f&&Iy(e)){if(!Iy(t))return!1;o=!0,c=!1}if(f&&!c)return a||(a=new Yc),o||aM(e)?rM(e,t,r,n,i,a):nM(e,t,l,r,n,i,a);if(!(r&oM)){var h=c&&Oy.call(e,"__wrapped__"),b=d&&Oy.call(t,"__wrapped__");if(h||b){var w=h?e.value():e,N=b?t.value():t;return a||(a=new Yc),i(w,N,r,n,a)}}return f?(a||(a=new Yc),iM(e,t,r,n,i,a)):!1}Ty.exports=lM});var My=m((uG,Ly)=>{var uM=Ry(),Fy=Ur();function xy(e,t,r,n,i){return e===t?!0:e==null||t==null||!Fy(e)&&!Fy(t)?e!==e&&t!==t:uM(e,t,r,n,xy,i)}Ly.exports=xy});var By=m((cG,Uy)=>{var cM=My();function dM(e,t){return cM(e,t)}Uy.exports=dM});var Zc=m((dG,ky)=>{var pM=Lr(),fM=(function(){try{var e=pM(Object,"defineProperty");return e({},"",{}),e}catch{}})();ky.exports=fM});var As=m((pG,$y)=>{var qy=Zc();function mM(e,t,r){t=="__proto__"&&qy?qy(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}$y.exports=mM});var ed=m((fG,Vy)=>{var hM=As(),gM=Jn();function vM(e,t,r){(r!==void 0&&!gM(e[t],r)||r===void 0&&!(t in e))&&hM(e,t,r)}Vy.exports=vM});var zy=m((mG,Gy)=>{function bM(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}}Gy.exports=bM});var jy=m((hG,Wy)=>{var yM=zy(),CM=yM();Wy.exports=CM});var Ky=m((Oa,ri)=>{var AM=xt(),Xy=typeof Oa=="object"&&Oa&&!Oa.nodeType&&Oa,Hy=Xy&&typeof ri=="object"&&ri&&!ri.nodeType&&ri,wM=Hy&&Hy.exports===Xy,Jy=wM?AM.Buffer:void 0,Qy=Jy?Jy.allocUnsafe:void 0;function NM(e,t){if(t)return e.slice();var r=e.length,n=Qy?Qy(r):new e.constructor(r);return e.copy(n),n}ri.exports=NM});var eC=m((gG,Zy)=>{var Yy=qc();function SM(e){var t=new e.constructor(e.byteLength);return new Yy(t).set(new Yy(e)),t}Zy.exports=SM});var rC=m((vG,tC)=>{var DM=eC();function EM(e,t){var r=t?DM(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}tC.exports=EM});var iC=m((bG,nC)=>{function IM(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}nC.exports=IM});var sC=m((yG,oC)=>{var _M=gr(),aC=Object.create,PM=(function(){function e(){}return function(t){if(!_M(t))return{};if(aC)return aC(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})();oC.exports=PM});var td=m((CG,lC)=>{var OM=jc(),TM=OM(Object.getPrototypeOf,Object);lC.exports=TM});var cC=m((AG,uC)=>{var RM=sC(),FM=td(),xM=ys();function LM(e){return typeof e.constructor=="function"&&!xM(e)?RM(FM(e)):{}}uC.exports=LM});var pC=m((wG,dC)=>{var MM=Pa(),UM=Ur();function BM(e){return UM(e)&&MM(e)}dC.exports=BM});var hC=m((NG,mC)=>{var kM=sn(),qM=td(),$M=Ur(),VM="[object Object]",GM=Function.prototype,zM=Object.prototype,fC=GM.toString,WM=zM.hasOwnProperty,jM=fC.call(Object);function HM(e){if(!$M(e)||kM(e)!=VM)return!1;var t=qM(e);if(t===null)return!0;var r=WM.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&fC.call(r)==jM}mC.exports=HM});var rd=m((SG,gC)=>{function JM(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}gC.exports=JM});var nd=m((DG,vC)=>{var QM=As(),XM=Jn(),KM=Object.prototype,YM=KM.hasOwnProperty;function ZM(e,t,r){var n=e[t];(!(YM.call(e,t)&&XM(n,r))||r===void 0&&!(t in e))&&QM(e,t,r)}vC.exports=ZM});var yC=m((EG,bC)=>{var eU=nd(),tU=As();function rU(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?tU(r,s,l):eU(r,s,l)}return r}bC.exports=rU});var AC=m((IG,CC)=>{function nU(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}CC.exports=nU});var NC=m((_G,wC)=>{var iU=gr(),aU=ys(),oU=AC(),sU=Object.prototype,lU=sU.hasOwnProperty;function uU(e){if(!iU(e))return oU(e);var t=aU(e),r=[];for(var n in e)n=="constructor"&&(t||!lU.call(e,n))||r.push(n);return r}wC.exports=uU});var id=m((PG,SC)=>{var cU=Wc(),dU=NC(),pU=Pa();function fU(e){return pU(e)?cU(e,!0):dU(e)}SC.exports=fU});var EC=m((OG,DC)=>{var mU=yC(),hU=id();function gU(e){return mU(e,hU(e))}DC.exports=gU});var RC=m((TG,TC)=>{var IC=ed(),vU=Ky(),bU=rC(),yU=iC(),CU=cC(),_C=Vc(),PC=Mr(),AU=pC(),wU=gs(),NU=ps(),SU=gr(),DU=hC(),EU=bs(),OC=rd(),IU=EC();function _U(e,t,r,n,i,a,o){var s=OC(e,r),l=OC(t,r),u=o.get(l);if(u){IC(e,r,u);return}var c=a?a(s,l,r+"",e,t,o):void 0,d=c===void 0;if(d){var f=PC(l),h=!f&&wU(l),b=!f&&!h&&EU(l);c=l,f||h||b?PC(s)?c=s:AU(s)?c=yU(s):h?(d=!1,c=vU(l,!0)):b?(d=!1,c=bU(l,!0)):c=[]:DU(l)||_C(l)?(c=s,_C(s)?c=IU(s):(!SU(s)||NU(s))&&(c=CU(l))):d=!1}d&&(o.set(l,c),i(c,l,n,a,o),o.delete(l)),IC(e,r,c)}TC.exports=_U});var ad=m((RG,xC)=>{var PU=Bc(),OU=ed(),TU=jy(),RU=RC(),FU=gr(),xU=id(),LU=rd();function FC(e,t,r,n,i){e!==t&&TU(t,function(a,o){if(i||(i=new PU),FU(a))RU(e,t,o,r,FC,n,i);else{var s=n?n(LU(e,o),a,o+"",e,t,i):void 0;s===void 0&&(s=a),OU(e,o,s)}},xU)}xC.exports=FC});var od=m((FG,LC)=>{function MU(e){return e}LC.exports=MU});var UC=m((xG,MC)=>{function UU(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)}MC.exports=UU});var qC=m((LG,kC)=>{var BU=UC(),BC=Math.max;function kU(e,t,r){return t=BC(t===void 0?e.length-1:t,0),function(){for(var n=arguments,i=-1,a=BC(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),BU(e,this,s)}}kC.exports=kU});var VC=m((MG,$C)=>{function qU(e){return function(){return e}}$C.exports=qU});var WC=m((UG,zC)=>{var $U=VC(),GC=Zc(),VU=od(),GU=GC?function(e,t){return GC(e,"toString",{configurable:!0,enumerable:!1,value:$U(t),writable:!0})}:VU;zC.exports=GU});var HC=m((BG,jC)=>{var zU=800,WU=16,jU=Date.now;function HU(e){var t=0,r=0;return function(){var n=jU(),i=WU-(n-r);if(r=n,i>0){if(++t>=zU)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}jC.exports=HU});var QC=m((kG,JC)=>{var JU=WC(),QU=HC(),XU=QU(JU);JC.exports=XU});var KC=m((qG,XC)=>{var KU=od(),YU=qC(),ZU=QC();function eB(e,t){return ZU(YU(e,t,KU),e+"")}XC.exports=eB});var ZC=m(($G,YC)=>{var tB=Jn(),rB=Pa(),nB=vs(),iB=gr();function aB(e,t,r){if(!iB(r))return!1;var n=typeof t;return(n=="number"?rB(r)&&nB(t,r.length):n=="string"&&t in r)?tB(r[t],e):!1}YC.exports=aB});var sd=m((VG,eA)=>{var oB=KC(),sB=ZC();function lB(e){return oB(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&&sB(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})}eA.exports=lB});var rA=m((GG,tA)=>{var uB=ad(),cB=sd(),dB=cB(function(e,t,r,n){uB(e,t,r,n)});tA.exports=dB});var Ct,Ta=D(()=>{"use strict";(function(e){e[e.NotLoaded=0]="NotLoaded",e[e.Initialized=1]="Initialized",e[e.ConfigsLoaded=2]="ConfigsLoaded",e[e.Error=3]="Error"})(Ct||(Ct={}))});function iA(e,t,r="PROD"){let n=i=>`ShellSettings_ECS_ClientCache_${e}_${nA.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 nA,pB,aA=D(()=>{"use strict";nA=ne(xc()),pB=ne(Fc());});var ld,oA=D(()=>{"use strict";Zo();ld=pa({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 lA,uA,cA,dA,ud,fB,ws,sA,cd=D(()=>{"use strict";lA=ne(Fc()),uA=ne(v0()),cA=ne(xc()),dA=ne(By()),ud=ne(rA());Ta();aA();oA();fB=60*1e3,ws=class{clientName;logger;ecsEndpoint;resolveLoadingPromise;loadingPromise=new Promise(t=>this.resolveLoadingPromise=t);_status=Ct.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"?ld.prodEcsEndpoint:ld.integrationEcsEndpoint}client=new uA.default;init=async({clientVersion:t,getFilters:r,cacheStorage:n=lA.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:[cA.EcsConfigType.Default],hosts:[this.ecsEndpoint],initialAppActiveState:!0,getEcsParameters:o,databaseInterface:iA(this.clientName,n,this.endpointType),...a}),this.client.requestUpdate(),this._status===Ct.NotLoaded&&(this._status=Ct.Initialized)}catch(s){this._status=Ct.Error,this.resolveLoadingPromise(),this.logEvent("FeaturesClient/initializationFailed",{ecsClientName:this.clientName,error:s},"Error")}i&&window.setInterval(()=>this.client.requestUpdate(),i*fB)};getConfig=t=>{let r=this.getMergedClientConfigByTeamName(t.teamName),n=r?t.extractConfig(r):{};return(0,ud.default)({},t.fallback,n,t.override,sA)};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,dA.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,ud.default)({},this.client.getConfig()?.config,this.clientConfigOverride,sA);getMergedClientConfigByTeamName=t=>this.getMergedClientConfig()?.[t];handleConfigUpdated=()=>{let t=this.client.getConfig();if(t===void 0)return;this.resolveLoadingPromise(),this._status=Ct.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})}},sA=(e,t)=>{if(Array.isArray(t))return t}});var fA=m((YG,pA)=>{"use strict";var mB=()=>{let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e};pA.exports=mB});var dd=m((ZG,hA)=>{var Ra=new Proxy(function(){return Ra},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Ra},apply:function(){return Ra},construct:function(){return{}}}),mA=function(){return Ra};Object.setPrototypeOf(mA,Ra);hA.exports=mA});var bA=m((ez,vA)=>{var Fa=new Proxy(function(){return Fa},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Fa},apply:function(){return Fa},construct:function(){return{}}}),gA=function(){return Fa};Object.setPrototypeOf(gA,Fa);vA.exports=gA});var DA=m((tz,SA)=>{"use strict";var pd=bA(),hB={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},gB={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},vB={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},wA={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},fd={};fd[pd.ForwardRef]=vB;fd[pd.Memo]=wA;function yA(e){return pd.isMemo(e)?wA:fd[e.$$typeof]||hB}var bB=Object.defineProperty,yB=Object.getOwnPropertyNames,CA=Object.getOwnPropertySymbols,CB=Object.getOwnPropertyDescriptor,AB=Object.getPrototypeOf,AA=Object.prototype;function NA(e,t,r){if(typeof t!="string"){if(AA){var n=AB(t);n&&n!==AA&&NA(e,n,r)}var i=yB(t);CA&&(i=i.concat(CA(t)));for(var a=yA(e),o=yA(t),s=0;s<i.length;++s){var l=i[s];if(!gB[l]&&!(r&&r[l])&&!(o&&o[l])&&!(a&&a[l])){var u=CB(t,l);try{bB(e,l,u)}catch{}}}}return e}SA.exports=NA});function IA(e,t,r){let[n,i]=(0,ni.useState)(e.getConfig(t));return(0,ni.useEffect)(()=>{if(!r?.subscribe&&e.status===Ct.ConfigsLoaded)return;let a=e.subscribe(t,o=>{i(o),r?.subscribe||a.unsubscribe()});return a?.unsubscribe},[]),n}function _A(e){return function(t,r){return IA(e,t,r)}}function PA(e,t,r,n){let i=a=>{let o=IA(e,t,n),s={...a,...o};return ni.default.createElement(r,{...s})};return(0,EA.default)(i,r),i.displayName=`WithFeature(${r.name})`,i}function OA(e,t,r,n){return t.reduce((i,a)=>PA(e,a,i,n),r)}function TA(e){return function(t,r,n){return PA(e,t,r,n)}}var EA,ni,md=D(()=>{"use strict";EA=ne(DA()),ni=ne(dd());Ta();});var FA=m((iz,RA)=>{var wB=ad(),NB=sd(),SB=NB(function(e,t,r){wB(e,t,r)});RA.exports=SB});var Ns=m((az,xA)=>{var DB=sn(),EB=Ur(),IB="[object Symbol]";function _B(e){return typeof e=="symbol"||EB(e)&&DB(e)==IB}xA.exports=_B});var MA=m((oz,LA)=>{var PB=Mr(),OB=Ns(),TB=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,RB=/^\w*$/;function FB(e,t){if(PB(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||OB(e)?!0:RB.test(e)||!TB.test(e)||t!=null&&e in Object(t)}LA.exports=FB});var kA=m((sz,BA)=>{var UA=ms(),xB="Expected a function";function hd(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(xB);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(hd.Cache||UA),r}hd.Cache=UA;BA.exports=hd});var $A=m((lz,qA)=>{var LB=kA(),MB=500;function UB(e){var t=LB(e,function(n){return r.size===MB&&r.clear(),n}),r=t.cache;return t}qA.exports=UB});var GA=m((uz,VA)=>{var BB=$A(),kB=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,qB=/\\(\\)?/g,$B=BB(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(kB,function(r,n,i,a){t.push(i?a.replace(qB,"$1"):n||r)}),t});VA.exports=$B});var WA=m((cz,zA)=>{function VB(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}zA.exports=VB});var KA=m((dz,XA)=>{var jA=wa(),GB=WA(),zB=Mr(),WB=Ns(),jB=1/0,HA=jA?jA.prototype:void 0,JA=HA?HA.toString:void 0;function QA(e){if(typeof e=="string")return e;if(zB(e))return GB(e,QA)+"";if(WB(e))return JA?JA.call(e):"";var t=e+"";return t=="0"&&1/e==-jB?"-0":t}XA.exports=QA});var ZA=m((pz,YA)=>{var HB=KA();function JB(e){return e==null?"":HB(e)}YA.exports=JB});var tw=m((fz,ew)=>{var QB=Mr(),XB=MA(),KB=GA(),YB=ZA();function ZB(e,t){return QB(e)?e:XB(e,t)?[e]:KB(YB(e))}ew.exports=ZB});var nw=m((mz,rw)=>{var ek=Ns(),tk=1/0;function rk(e){if(typeof e=="string"||ek(e))return e;var t=e+"";return t=="0"&&1/e==-tk?"-0":t}rw.exports=rk});var ow=m((hz,aw)=>{var nk=nd(),ik=tw(),ak=vs(),iw=gr(),ok=nw();function sk(e,t,r,n){if(!iw(e))return e;t=ik(t,e);for(var i=-1,a=t.length,o=a-1,s=e;s!=null&&++i<a;){var l=ok(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=iw(c)?c:ak(t[i+1])?[]:{})}nk(s,l,u),s=s[l]}return e}aw.exports=sk});var lw=m((gz,sw)=>{var lk=ow();function uk(e,t,r){return e==null?e:lk(e,t,r)}sw.exports=uk});function pw(e){let{query:t}=(0,dw.default)(window.location.href,!0);return dk(e,t),e}function dk(e,t){let r=ck+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+fw,u={};if(a===r)u=s;else if(a.startsWith(l)){let c=a.substring(l.length);(0,cw.default)(u,c,s)}(0,uw.default)(i,u)}catch{}}),Object.keys(i).length>0&&e.overrideClientConfig(i)}var uw,cw,dw,fw,ck,mw=D(()=>{"use strict";uw=ne(FA()),cw=ne(lw()),dw=ne(Cc());fw=".",ck="ecs"+fw});function Ds(e,t,r){let n=pw(new ws(e,t,r));function i(a){(0,Ss.useEffect)(()=>{n.init(a)},[])}return{featuresClient:n,createFeature:fk(n),useFeaturesClientInitParams:i,withFeatures:(a,o,s)=>OA(n,a,o,s)}}function fk(e){let t=_A(e),r=TA(e);return function(i){let a=p0(i);return a.getConfig=()=>e.getConfig(a),a.isLoaded=()=>e.status===Ct.ConfigsLoaded,Nc.register(a,e.clientName),{useFeature:o=>t(a,o),withFeature:(o,s)=>r(a,o,s),feature:a}}}var pk,Ss,gd=D(()=>{"use strict";pk=ne(fA()),Ss=ne(dd());Rc();cd();Ta();md();mw();Sc();});var hw=D(()=>{"use strict";Rc();cd();gd();Ta();md();ns();Dc();});function Es(e){return{logEvent:(t,r,n)=>{switch(n){case"Error":(0,ii.trackErrorTrace)(e,{eventName:t,eventData:r});break;case"Warning":(0,ii.trackWarningTrace)(e,{eventName:t,eventData:r});break;default:(0,ii.trackInfoTrace)(e,{eventName:t,eventData:r});break}}}}var ii,vd=D(()=>{"use strict";ii=ne(en());});var Mz,Uz,Bz,gw=D(()=>{"use strict";hw();vd();({featuresClient:Mz,createFeature:Uz,useFeaturesClientInitParams:Bz}=Ds("PowerApps-Shell-Test",Es("shell-features")))});var yw=m((qz,bw)=>{var xa=new Proxy(function(){return xa},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:xa},apply:function(){return xa},construct:function(){return{}}}),vw=function(){return xa};Object.setPrototypeOf(vw,xa);bw.exports=vw});var mk,hk,Cw=D(()=>{"use strict";ua();mk=ne(yw()),hk=ne(en());});var Aw=D(()=>{"use strict";gw();vd();Cw();});var Qz,ai,Xz,ww=D(()=>{"use strict";Aw();gd();({featuresClient:Qz,createFeature:ai,useFeaturesClientInitParams:Xz}=Ds("PowerApps-MakerPortal",Es("powerapps-features")))});var Nw,Sw,eW,tW,rW,nW,bd=D(()=>{"use strict";d0();ww();({feature:Nw}=ai({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:Hn.enableAutoInsertionOfCellInRow}})),{feature:Sw}=ai({teamName:"MakerPortal",owners:["aansu"],description:"Enable the one grid events for form designer",createdOn:"08/21/2024",fallback:{enableOneGridEventsForFormDesigner:Hn.enableOneGridEvents}}),{feature:eW}=ai({teamName:"MakerPortal",owners:["adekulkarni"],description:"Disables PBI components and cleans them up from the form",createdOn:"01/03/2023",fallback:{enableFallbackFormTemplate:Hn.disablePBIComponents}}),{feature:tW}=ai({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:Hn.enableAgentResponse}}),{feature:rW,useFeature:nW}=ai({teamName:"MakerPortal",owners:["aansu"],description:"Enables delayed localization of custom control",createdOn:"06/08/2025",fallback:{enableDelayedLocalizationForCustomControls:Hn.enableDelayedLocalizationForCustomControls}})});var Iw=m((aW,Ew)=>{var La=new Proxy(function(){return La},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:La},apply:function(){return La},construct:function(){return{}}}),Dw=function(){return La};Object.setPrototypeOf(Dw,La);Ew.exports=Dw});var je,Br=D(()=>{"use strict";De();Ce();We();cs();G();Le();je=class extends q{static HighestUsedIndexByClass=new Map;get colspan(){let t=this.getProperty(p.colspan);return S.IsNullOrUndefined(t)?null:parseInt(t,10)}set colspan(t){S.IsNullOrUndefined(t)||this.setProperty(p.colspan,String(t))}constructor(t,r){super(t,r)}get id(){let t=this.getProperty(p.id);return t==null?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new _(t.substr(1,t.length-2)):new _(t)}set id(t){this.setProperty(p.id,`{${t.ToString()}}`)}set labelId(t){this.setProperty(p.labelId,`{${t.ToString()}}`)}get labelId(){let t=this.getProperty(p.labelId);return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new _(t.substr(1,t.length-2)):new _(t)}get Name(){return this.getProperty(p.Name)}set Name(t){this.setProperty(p.Name,t)}setDisplayName(t,r){for(let i of this.getAllLabels())if(+i.getProperty(p.languagecode)===r){i.setProperty(p.description,t);return}let n=new q(g.formLabel,null);n.setProperty(p.description,t),n.setProperty(p.languagecode,String(r)),this.addGrandChild("labels",n)}getDisplayName(t){for(let r of this.getAllLabels())if(+r.getProperty(p.languagecode)===t)return r.getProperty(p.description)}getAllLabels(){let t=this.getChildren("labels");return t.length!==1?[]:t[0].getChildren("label")}get isLocked(){return+this.getProperty(p.locklevel)==1}set isLocked(t){!this.IsUnboundControl&&this.setProperty(p.locklevel,t?"1":"0")}get availableforphone(){return this.getProcessedValue(p.availableforphone)}set availableforphone(t){S.IsNullOrUndefined(t)||!this.IsAllowedUBCForAvailableOnPhone()||this.setProperty(p.availableforphone,String(t))}get visible(){return this.getProcessedValue(p.visible)}set visible(t){S.IsNullOrUndefined(t)||!this.IsAllowedUBCForVisibleByDefault()||this.setProperty(p.visible,String(t))}isLockLevelSettable(){return!this.IsUnboundControl}get showlabel(){return this.getProcessedValue(p.showlabel)}set showlabel(t){S.IsNullOrUndefined(t)||this.setProperty(p.showlabel,String(t))}isAvailableForPhoneSettable(){return this.IsAllowedUBCForAvailableOnPhone()}isVisibleSettable(){return this.IsAllowedUBCForVisibleByDefault()}getProcessedValue(t){let r=this.getProperty(t);return S.IsNullOrUndefined(r)||this.getProperty(t)==="true"}get readonly(){let t=this.getFirstChild(g.formControl);return t?t.disabled:!1}set readonly(t){let r=this.getFirstChild(g.formControl);r&&(r.disabled=t)}get allowfilteroff(){let t=this.getFirstChild(g.formControl);if(t)return t.getParam(p.AllowFilterOff)==="true"}set allowfilteroff(t){let r=this.getFirstChild(g.formControl);r&&!this.IsUnboundControl&&r.setParameter(p.AllowFilterOff,t)}get autoresolve(){let t=this.getFirstChild(g.formControl);if(t)return t.getParam(p.AutoResolve)==="true"}set autoresolve(t){let r=this.getFirstChild(g.formControl);r&&!this.IsUnboundControl&&r.setParameter(p.AutoResolve,t)}get defaultviewid(){let t=this.getFirstChild(g.formControl);return t?t.getParam(p.DefaultViewId):P.EmptyString}set defaultviewid(t){let r=this.getFirstChild(g.formControl);r&&!this.IsUnboundControl&&r.setParameter(p.DefaultViewId,t)}get dependentattributename(){let t=this.getFirstChild(g.formControl);return t?t.getParam(p.DependentAttributeName):P.EmptyString}set dependentattributename(t){let r=this.getFirstChild(g.formControl);r&&!this.IsUnboundControl&&r.setParameter(p.DependentAttributeName,t)}get dependentattributetype(){let t=this.getFirstChild(g.formControl);return t?t.getParam(p.DependentAttributeType):P.EmptyString}set dependentattributetype(t){let r=this.getFirstChild(g.formControl);r&&!this.IsUnboundControl&&r.setParameter(p.DependentAttributeType,t)}get disablequickfind(){let t=this.getFirstChild(g.formControl);if(t)return t.getParam(p.DisableQuickFind)==="true"}set disablequickfind(t){let r=this.getFirstChild(g.formControl);r&&!this.IsUnboundControl&&r.setParameter(p.DisableQuickFind,t)}get disableviewpicker(){let t=this.getFirstChild(g.formControl);if(t)return t.getParam(p.DisableViewPicker)==="true"}set disableviewpicker(t){let r=this.getFirstChild(g.formControl);r&&!this.IsUnboundControl&&r.setParameter(p.DisableViewPicker,t)}get filterrelationshipname(){let t=this.getFirstChild(g.formControl);return t?t.getParam(p.FilterRelationshipName):P.EmptyString}set filterrelationshipname(t){let r=this.getFirstChild(g.formControl);r&&!this.IsUnboundControl&&r.setParameter(p.FilterRelationshipName,t)}get availableviewids(){let t=this.getFirstChild(g.formControl);return t?t.getParam(p.AvailableViewIds):P.EmptyString}set availableviewids(t){let r=this.getFirstChild(g.formControl);r&&!this.IsUnboundControl&&r.setParameter(p.AvailableViewIds,t)}get IsUnboundControl(){let t=this.getFirstChild(g.formControl);if(t&&t.ClassId){let r=Ie.getUniqueIdentifierForControl(t);return!S.IsNullOrUndefined(r)&&Ie.isUnboundFormControlByIdentifier(r)}else return!1}IsAllowedUBCForAvailableOnPhone(){let t=this.getFirstChild(g.formControl);if(t){let n=Ie.getUniqueIdentifierForControl(t).guidString,i=n===T.GridControl||n===T.TimeLineControl||n===T.TimeLineControlUC;return this.IsUnboundControl?i:!0}return this.NodeName===g.formSection||this.NodeName===g.formTab}IsAllowedUBCForVisibleByDefault(){let t=this.getFirstChild(g.formControl);if(t){let n=Ie.getUniqueIdentifierForControl(t).guidString,i=n===T.MapsControl||n===T.WebResourceHtmlControl||n===T.WebResourceImageControl||n===T.IframeControl||n===T.SocialInsightControl;return this.IsUnboundControl?i:!0}else return!0}get events(){let t=this.getChildren(g.formEvents);return t.length===1?t[0].getAllChildren():[]}addEvent(t){this.addGrandChild(g.formEvents,t)}getUsedNodeNameSet(t){return null}getHighestIndexById(t,r){return null}}});var oi,yd=D(()=>{"use strict";We();G();Le();oi=class extends q{constructor(t,r){super(g.dependency,t),P.IsNullOrEmpty(r)||this.setDefaultProperties(r)}set id(t){this.setProperty(p.id,t)}get id(){return this.getProperty(p.id)}setDefaultProperties(t){this.id=t}}});var _w,si,Cd=D(()=>{"use strict";Ce();yd();G();Le();Br();(function(e){e[e.Form=0]="Form",e[e.Cell=1]="Cell",e[e.Tab=2]="Tab",e[e.Control=3]="Control"})(_w||(_w={}));si=class extends je{constructor(t,r){super(g.formEvent,t),r&&(this.eventName=r,this.application="false",this.active="false")}set eventName(t){this.setProperty(p.Name,t)}get eventName(){return this.getProperty(p.Name)}set application(t){this.setProperty(p.application,t)}get application(){return this.getProperty(p.application)}set attribute(t){this.setProperty(p.EventAttribute,t)}get attribute(){return this.getProperty(p.EventAttribute)}set relationship(t){this.setProperty(p.Relationship,t)}get relationship(){return this.getProperty(p.Relationship)}set control(t){this.setProperty(p.Control,t)}get control(){return this.getProperty(p.Control)}set active(t){this.setProperty(p.EventActive,t)}get active(){return this.getProperty(p.EventActive)}getAllHandlers(){let t=this.getChildren(g.EventHandlers);return t&&t.length?t[0].getChildren(g.handler):[]}getAllDependencies(){let t=this.getChildren(g.formDependencies);return t.length===0?[]:t[0].getAllChildren()}setDependencies(t){let r=this.getFirstChild(g.formDependencies);if(S.IsNullOrUndefined(r)){if(t.length===0)return;this.addChild(new q(g.formDependencies,this)),r=this.getFirstChild(g.formDependencies)}if(t.length===0)r.getParentNode().deleteChild(r);else{r.deleteAllChildren();for(let n of t)r.addChild(new oi(r,n.toString()))}}}});var Lt,Ma=D(()=>{"use strict";De();la();Ce();Zr();G();Le();Rt();Lt=class extends q{previewVersion;constructor(t){super(g.formControl,t)}updatePreview(){this.previewVersion=Date.now()}get ClassId(){let t=this.getProperty(p.classid);return t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new _(t)}set ClassId(t){this.setProperty(p.classid,`{${t.ToString()}}`)}get dataFieldName(){return this.getProperty(p.datafieldname)}set dataFieldName(t){this.setProperty(p.datafieldname,t)}set id(t){this.setProperty(p.id,t)}get id(){return this.getProperty(p.id)}get UniqueId(){let t=this.getProperty(p.uniqueid);return S.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new _(t))}set UniqueId(t){this.setProperty(p.uniqueid,`{${t.ToString()}}`)}get isRequired(){return this.getProperty(p.isRequired)==="true"}set isRequired(t){S.IsNullOrUndefined(t)||this.setProperty(p.isRequired,String(t))}get disableMru(){return this.getParam(p.DisableMru)==="true"}set disableMru(t){S.IsNullOrUndefined(t)||this.setParameter(p.DisableMru,t)}get useMFDForCreate(){return this.getParam(p.UseMFDForCreate)==="true"}set useMFDForCreate(t){S.IsNullOrUndefined(t)||this.setParameter(p.UseMFDForCreate,t)}get useMFDForEdit(){return this.getParam(p.UseMFDForEdit)==="true"}set useMFDForEdit(t){S.IsNullOrUndefined(t)||this.setParameter(p.UseMFDForEdit,t)}get disabled(){return this.getProperty(p.disabled)==="true"}set disabled(t){S.IsNullOrUndefined(t)||this.setProperty(p.disabled,String(t))}get indicationOfSubgrid(){return this.getProperty(p.indicationOfSubgrid)==="true"}set indicationOfSubgrid(t){this.setProperty(p.indicationOfSubgrid,String(t))}getAllParameters(){let t=new Ke,r=this.getFirstChild(p.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=(hr.StartTag+r).toString(),a=this.parametersNode;if(a){let o=a.findFirst(s=>s&&s.getNodeName()===t);if(o)if(n){this.deleteFirstGrandChildOfName(g.controlParameters,o);return}else{let s=o.getAllChildren();s&&s.length>0&&s[0]?s[0].setNodeName(i):o.addChild(new q(i,o))}else n||(o=new q(t,a),o.addChild(new q(i,o)),a.addChild(o))}else if(!n){a=new q("parameters",this);let o=new q(t,a);o.addChild(new q(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)===hr.StartTag?a.substring(1):a}}}return null}get parametersNode(){let t=this.getChildren(p.parameters);return t.length===0?null:t[0]}async serializeParameters(t,r){let n=new Ke;switch(this.ClassId.guidString.toUpperCase()){case A.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(p.isUnbound)==="true"}getAttributeTypeFromClassId(t){if(t)switch(t.toUpperCase()){case A.BooleanControl:case A.CheckboxControl:return 0;case A.DateTimeControl:return 2;case A.DecimalControl:return 3;case A.FloatingNumberControl:return 4;case A.IntegerControl:case A.DurationControl:case A.LanguageControl:case A.TimezoneControl:return 5;case A.LookupControl:return 6;case A.CurrencyControl:return 8;case A.PartyListControl:return 10;case A.ChoiceControl:case A.RelationshipRoleChoiceControl:return 11;case A.ChoiceStatusControl:return 13;case A.TextAreaControl:case A.TextboxControl:case A.LabelControl:case A.EmailAddressControl:case A.UrlControl:case A.TickerControl:case A.ButtonControl:case A.PhoneNumberControl:return 14;case A.ChoicesControl:return 24;default:return}return 14}async toJSON(t){let r=this.getParent(),n=t&&t.formModelService&&t.formModelService.getFormType()===Ee.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 li,Ad=D(()=>{"use strict";We();$n();Ma();G();Le();li=class extends Lt{constructor(t){super(t)}get targetEntityType(){return this.getParam(p.targetEntityType)||P.EmptyString}set targetEntityType(t){this.setParameter(p.targetEntityType,t)}get viewId(){return P.StripBraces(this.getParam(p.viewId))||P.EmptyString}set viewId(t){this.setParameter(p.viewId,P.AddBraces(t))}get viewIds(){return this.getParam(p.viewIds)||P.EmptyString}set viewIds(t){this.setParameter(p.viewIds,t)}get relationshipName(){return this.getParam(p.RelationshipName)||P.EmptyString}set relationshipName(t){this.setParameter(p.RelationshipName,t)}get isUserView(){return P.IsStrictTrue(this.getParam(p.isUserView))}set isUserView(t){this.setParameter(p.isUserView,t.toString())}get enableViewPicker(){return P.IsStrictTrue(this.getParam(p.enableViewPicker))}set enableViewPicker(t){this.setParameter(p.enableViewPicker,t)}get autoExpand(){return this.getParent().autoexpand&&this.getParam(p.autoExpand)===p.Auto}set autoExpand(t){let r=this.getParent();this.setParameter(p.autoExpand,t?p.Auto:p.Fixed),r.autoexpand=t}get recordsPerPage(){return this.getParam(p.recordsPerPage)?Number(this.getParam(p.recordsPerPage)):Number(p.RecordsPerPageRAControlDefault)}set recordsPerPage(t){this.setParameter(p.recordsPerPage,String(t))}get enableQuickFind(){return P.IsStrictTrue(this.getParam(p.enableQuickFind))}set enableQuickFind(t){this.setParameter(p.enableQuickFind,t)}get teamTemplateId(){return P.StripBraces(this.getParam(p.teamTemplateId))||P.EmptyString}set teamTemplateId(t){this.setParameter(p.teamTemplateId,P.AddBraces(t))}get chartId(){return this.getParam(p.visualizationId)||P.EmptyString}set chartId(t){this.setParameter(p.visualizationId,t)}get enableChartPicker(){return P.IsStrictTrue(this.getParam(p.enableChartPicker))}set enableChartPicker(t){this.setParameter(p.enableChartPicker,t)}get chartGridMode(){switch(this.getParam(p.chartGridMode)){case yt.Chart:return yt.Chart;case yt.Grid:return yt.Grid;default:return yt.All}}set chartGridMode(t){this.setParameter(p.chartGridMode,t)}updateChartGridMode(t){t?this.chartGridMode=yt.Chart:this.chartGridMode=this.enableChartPicker?yt.All:yt.Grid}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case p.targetEntityType:n.getAllChildren()[0].setNodeName("<"+r.targetEntityType);break;case p.viewId:n.getAllChildren()[0].setNodeName("<"+P.AddBraces(r.viewId));break;case p.isUserView:n.getAllChildren()[0].setNodeName("<"+r.isUserView);break;case p.enableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.enableViewPicker);break;case p.RelationshipName:let i=n.getAllChildren(),a="<"+r.relationshipName;i.length?n.getAllChildren()[0].setNodeName(a):n.addChild(new q(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(Ye.dataset)?n[i].getParameters().get(Ye.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 ui,wd=D(()=>{"use strict";We();$n();Ma();G();ui=class extends Lt{constructor(t){super(t)}get defaultViewId(){return P.StripBraces(this.getParam(p.DefaultViewId))||P.EmptyString}set defaultViewId(t){this.setParameter(p.DefaultViewId,P.AddBraces(t))}get autoResolve(){return P.IsStrictTrue(this.getParam(p.AutoResolve))}set autoResolve(t){this.setParameter(p.AutoResolve,t)}get disableQuickFind(){return P.IsStrictTrue(this.getParam(p.DisableQuickFind))}set disableQuickFind(t){this.setParameter(p.DisableQuickFind,t)}get disableViewPicker(){return P.IsStrictTrue(this.getParam(p.DisableViewPicker))}set disableViewPicker(t){this.setParameter(p.DisableViewPicker,t)}get allowFilterOff(){return P.IsStrictTrue(this.getParam(p.AllowFilterOff))}set allowFilterOff(t){this.setParameter(p.AllowFilterOff,t)}get disableMru(){return P.IsStrictTrue(this.getParam(p.DisableMru))}set disableMru(t){this.setParameter(p.DisableMru,t)}get dependentAttributeName(){return this.getParam(p.DependentAttributeName)||P.EmptyString}set dependentAttributeName(t){this.setParameter(p.DependentAttributeName,t)}get dependentAttributeType(){return this.getParam(p.DependentAttributeType)||P.EmptyString}set dependentAttributeType(t){this.setParameter(p.DependentAttributeType,t)}get filterRelationshipName(){return this.getParam(p.FilterRelationshipName)||P.EmptyString}set filterRelationshipName(t){this.setParameter(p.FilterRelationshipName,t)}get availableViewIds(){return this.getParam(p.AvailableViewIds)||P.EmptyString}set availableViewIds(t){this.setParameter(p.AvailableViewIds,t)}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case p.datafieldname:case p.bindAttribute:n.getAllChildren()[0].setNodeName("<"+r.dataFieldName);break;case p.DefaultViewId:n.getAllChildren()[0].setNodeName("<"+P.AddBraces(r.defaultViewId));break;case p.AllowFilterOff:n.getAllChildren()[0].setNodeName("<"+r.allowFilterOff);break;case p.DisableQuickFind:n.getAllChildren()[0].setNodeName("<"+r.disableQuickFind);break;case p.DisableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.disableViewPicker);break;case p.FilterRelationshipName:n.getAllChildren()[0].setNodeName("<"+r.filterRelationshipName);break;case p.DependentAttributeName:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeName);break;case p.DependentAttributeType:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeType);break;case p.AvailableViewIds:n.getAllChildren()[0].setNodeName("<"+r.availableViewIds);break;case p.DisableMru:n.getAllChildren()[0].setNodeName("<"+r.disableMru);break;case p.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(Ye.value)?n[i].getParameters().get(Ye.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 Pw,Nd,ot,Ua=D(()=>{"use strict";Pw=ne(Iw());Br();G();Ce();De();Cd();Ma();cs();Oc();lc();Rt();Zr();Bn();Ad();wd();Sd();ma();Nd="_",ot=class e extends je{fieldPlaceholder;fieldRequiredLevel;isNewField;cellColType;dependentFields=[];constructor(t){super(g.formCell,t),this.isNewField=!1}get cellType(){return this.cellColType}set cellType(t){this.cellColType=t}setDefaultProperties(t){this.showlabel=t,this.isLocked=!1,S.IsNullOrUndefined(this.getProperty(p.id))&&(this.id=new _(_.NewGuid()))}addControl(t,r,n,i,a,o,s){n instanceof Lt?this.addChild(n):n instanceof _&&this.addChild(this.getControlWithControlSpecificProperties(t,r,n,i,a,o,s))}removeControl(){return this.deleteChild(this.control)>=0}get isIndependent(){if(!S.IsNullOrUndefined(this.control))return S.IsNullOrUndefined(this.control.dataFieldName)?S.IsNullOrUndefined(this.control.id)?!0:!tn.dependencyFieldCount.containsKey(this.control.id):!tn.dependencyFieldCount.containsKey(this.control.dataFieldName)}createOnLoadEvent(){this.addEvent(new si(this,oa.onLoad))}get dependencies(){let t=this.getChildren(g.formEvents);for(let r of t){let n=r.getChildren(g.formEvent);for(let i of n)this.buildDependencyList(i,this.dependentFields)}return this.dependentFields}getNextAvailableControlName(t,r,n,i){let a;if(i&&Jo[i])a=Jo[i].replace(/ /g,Nd)+Nd;else{a="Control_";let u=new Error("Control class id does not exist or is undefined");(0,Pw.trackErrorTrace)(Xe,{eventName:`${ph}/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,p.isUnbound,"true"),e.prototype.setProperty.call(t,p.isRequired,"false")}getControlWithControlSpecificProperties(t,r,n,i,a,o,s){let l;a===At.Grid?(l=new li(this),l.indicationOfSubgrid=!0):a===At.Lookup?l=new ui(this):l=new Lt(this);let u=n.guidString,c=o||this.getNextAvailableControlName(t,i,this.getUsedNodeNameSet(t),u);if(e.prototype.setProperty.call(l,p.id,c),l.ClassId=n,!S.IsNullOrUndefined(s)&&(l.UniqueId=s),!o&&r)this.getUnboundControlProperties(l);else{let d=Ie.getUniqueIdentifierForControl(l);S.IsNullOrUndefined(d)||(Ie.getControlDataTypeByControlOrUniqueId(d)===U.QuickFormCollectionControl||!Ie.isUnboundFormControlByIdentifier(d)?a!==At.Grid&&o&&u!==A.IframeControl&&u!==A.SubgridControl&&u!==A.ReferencePanelSubgridControl&&(l.dataFieldName=o,e.prototype.setProperty.call(l,p.disabled,"false")):(this.rowspan=Ie.GetRowSpan(l),(Ie.getControlDataTypeByControlOrUniqueId(d)===U.NotesControl||Ie.getControlDataTypeByControlOrUniqueId(d)===U.TimeLineControl)&&(e.prototype.setProperty.call(l,p.disabled,"false"),l.id=U.NotesControl)),(Ie.getUnboundControlNameFromIdentifier(n)===U.SubGridControl||Ie.getUnboundControlNameFromIdentifier(n)===U.NotesControl||Ie.getUnboundControlNameFromIdentifier(n)===U.TimeLineControl)&&(this.availableforphone=!0))}return l}buildDependencyList(t,r){if(S.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(p.id);o.getNodeName()===g.dependency&&s?r.push(s):this.buildDependencyList(o,r)}}}get control(){return this.getFirstChild(g.formControl)}set rowspan(t){this.setProperty(p.rowspan,String(t))}get rowspan(){let t=this.getProperty(p.rowspan);return S.IsNullOrUndefined(t)?1:parseInt(t,10)}set autoexpand(t){this.setProperty(p.auto,String(t))}get autoexpand(){return this.getProperty(p.auto)==="true"}set colspan(t){let r=Number(_c.ONE_COLUMN),n=Number(_c.FOUR_COLUMN);S.IsNullOrUndefined(t)||t>n||t<r||this.setProperty(p.colspan,String(t))}get colspan(){let t=this.getProperty(p.colspan);return S.IsNullOrUndefined(t)?1:parseInt(t,10)}getParentRow(){return this.getAncestor(g.formRow)}getParentSection(){return this.getAncestor(g.formSection)}getParentTab(){return this.getAncestor(g.formTab)}getParentForm(){return this.getAncestor(g.form)}isInHeader(){let t=this.getAncestor(g.formHeader);return!S.IsNullOrUndefined(t)}isInFooter(){let t=this.getAncestor(g.formFooter);return!S.IsNullOrUndefined(t)}isEmpty(){return S.IsNullOrUndefined(this.control)&&!this.IsUserSpacer}getHeaderFooter(){return this.isInHeader()?this.getAncestor(g.formHeader):this.isInFooter()?this.getAncestor(g.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(p.userspacer);return S.IsNullOrUndefined(t)?!1:t==="true"}SetUserSpacer(){this.setProperty(p.userspacer,"true")}ClearUserSpacer(){this.setProperty(p.userspacer,"false")}get columns(){let t=this.getProperty(p.columnName);return S.IsNullOrUndefined(t)?null:parseInt(t,10)}getColumnLayoutValue(t){let r;switch(t){case pe.TWO_COLUMN:r="11";break;case pe.THREE_COLUMN:r="111";break;case pe.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(!S.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();S.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===nn.ApplicationRequired||o===nn.SystemRequired)&&!a||this.isCellLockedByExternal(t)&&!a)return!0}}return!1}getRequiredLevel(t){return!this.control?.dataFieldName||!this.control?.id||this.IsNewField||!this.control?.ClassId?nn.None:t.getEntityAttributeByName(this.control.dataFieldName)?.requiredLevel?.toString()??nn.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()===g.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()===g.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)===Nd&&(r++,n=parseInt(t.substr(r,t.length-r),10)),n}}});var ci,Dd=D(()=>{"use strict";We();G();Le();ci=class extends q{isInternal;constructor(t,r,n,i){super(g.library,t),this.isInternal=!!i,P.IsNullOrEmpty(n)||(this.name=r,this.libraryUniqueId=n)}get libraryUniqueId(){let t=this.getProperty(p.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(p.libraryUniqueId,t)}get name(){return this.getProperty(p.libraryName)}set name(t){this.setProperty(p.libraryName,t)}get displayName(){return this.getProperty(p.displayName)}set displayName(t){this.setProperty(p.displayName,t)}get description(){return this.getProperty(p.description)}set description(t){this.setProperty(p.description,t)}}});var un,Ed=D(()=>{"use strict";Ce();Ua();G();Le();un=class extends q{isRowAddedOnDragOver;constructor(t){super(g.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 S.IsNullOrUndefined(t)?!1:this.deleteChild(t)>=0}insertCellAtIndex(t,r){return S.IsNullOrUndefined(t)?!1:(this.insertChildAtIndex(t,r),!0)}isEmpty(){return!this.cells||this.cells.every(t=>t.isEmpty())}getParentSection(){return this.getAncestor(g.formSection)}insertPaddingCellAtIndex(t){let r=new ot(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(g.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 gk(e){switch(e){case an.Left:return on.Left;case an.Right:return on.Right;case an.Center:return on.Center;default:return on.Left}}function vk(e){switch(e){case zn.Left:return jn.Left;case zn.Top:return jn.Top;default:return jn.Left}}function Ow(e){switch(e){case 1:return 1;case 2:return 11;case 3:return 111;case 4:return 1111;default:return 1}}var bk,Qt,Ba=D(()=>{"use strict";Tc();De();Ce();We();bd();Ua();G();Rt();Br();Ed();bk=115,Qt=class e extends je{colSpan=1;constructor(t,r){super(t,r)}getSectionType(){let t;switch(this.columns){case 1:t=pe.ONE_COLUMN;break;case 11:t=pe.TWO_COLUMN;break;case 111:t=pe.THREE_COLUMN;break;case 1111:t=pe.FOUR_COLUMN;break;default:t=this.colSpan-1}return t}setUniqueName(){let t=this.getParentTab(),r=le.namePrefix;if(t){let n=t.Name,i=t.TotalSectionsCount+1;r=n+le.namePrefix+i.toString()}else r+=Math.floor(Math.random()*1e3);this.setProperty(p.Name,r)}initializeDefaultProperties(t,r,n){if(n===pe.REFERENCE_PANEL){this.addProperty(p.rowheight,"25");let i=`${le.referencePanelNamePrefix}${_.NewGuid()}${le.namePrefix}`;this.addProperty(p.Name,i)}else this.setUniqueName();if(this.addProperty(p.id,new _(_.NewGuid()).guidString),this.addProperty(p.IsUserDefined,le.IsUserDefined),this.addProperty(p.locklevel,le.LockLevel),this.addProperty(p.showlabel,le.ShowLabel),this.addProperty(p.showbar,le.ShowBar),this.addProperty(p.layout,le.Layout),this.addProperty(p.Fieldlabelalignment,le.labelAlignment),this.addProperty(p.Fieldlabelposition,le.labelPosition),S.IsNullOrUndefined(n))this.addProperty(p.columnName,le.columns);else{let i=this.getColumnLayoutValue(n);this.addProperty(p.columnName,i)}this.addProperty(p.LabelWidth,le.LabelWidth),this.setDisplayName(r,t)}getColumnLayoutValue(t){let r;switch(t){case pe.TWO_COLUMN:r="11";break;case pe.THREE_COLUMN:r="111";break;case pe.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 S.IsNullOrUndefined(this.columns)?t=this.ColSpan:this.columns.toString().split(P.EmptyString).forEach(r=>{t+=parseInt(r,10)}),t}get ColSpan(){return this.colSpan}initializeRow(t){if(t>0&&t<5){let r=new un(null);if(this.addGrandChild(g.formRows,r),Nw.getConfig().enableAutoInsertionOfCellInRow)for(let n=0;n<t;n++){let i=new ot(r);i.setDefaultProperties(!1),r.addCell(i)}}}initialize(t,r,n){this.initializeDefaultProperties(t,r,n),n===pe.REFERENCE_PANEL&&(n=pe.ONE_COLUMN),this.initializeRow(n+1)}setColSpan(t){this.colSpan=t}appendRow(t){this.addGrandChild(g.formRows,t)}insertRowAtIndex(t,r){this.addGrandChildAtIndex(g.formRows,t,r)}insertRowsAtIndex(t,r){if(t&&t.length>0)for(let n=0;n<t.length;n++)this.addGrandChildAtIndex(g.formRows,t[n],r+n)}indexOfRow(t){return this.rows.indexOf(t)}deleteRow(t){return this.deleteFirstGrandChildOfName(g.formRows,t)}deleteRows(t,r){this.deleteGrandChildren(g.formRows,t,r)}get rows(){return this.getRows()}getRows(){let t=this.getChildren(g.formRows);return t.length===0?[]:t[0].getChildren(g.formRow)}get columns(){let t=this.getProperty(p.columnName),r=S.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 Ow(n)}return r}set columns(t){S.IsNullOrUndefined(t)||this.setProperty(p.columnName,String(t))}get rowHeight(){let t=this.getProperty(p.rowheight);return S.IsNullOrUndefined(t)?null:parseInt(t,10)}set rowHeight(t){this.setProperty(p.rowheight,String(t))}set autoexpand(t){this.setProperty(p.autoExpand.toLowerCase(),String(t))}get autoexpand(){return this.getProperty(p.autoExpand.toLowerCase())==="true"}get isUserDefined(){return+this.getProperty(p.IsUserDefined)!=0}set isUserDefined(t){t?this.setProperty(p.IsUserDefined,"1"):this.setProperty(p.IsUserDefined,"0")}getParentColumn(){return this.getAncestor(g.formColumn)}getParentTab(){return this.getAncestor(g.formTab)}get hasMultiColumnRow(){return this.getColumnCountValue()>1}get showlabel(){return this.getProperty(p.showlabel)==="true"}set showlabel(t){S.IsNullOrUndefined(t)||this.setProperty(p.showlabel,String(t))}get fieldLabelAlignment(){let t=le.labelAlignment,r=this.getProperty(p.Fieldlabelalignment);return S.IsNullOrUndefined(r)?t:r}set fieldLabelAlignment(t){S.IsNullOrUndefined(t)||this.setProperty(p.Fieldlabelalignment,t)}get fieldLabelPosition(){let t=this.getProperty(p.Fieldlabelposition);return S.IsNullOrUndefined(t)?le.labelPosition:t}set fieldLabelPosition(t){S.IsNullOrUndefined(t)||this.setProperty(p.Fieldlabelposition,String(t))}get showbar(){return this.getProperty(p.showbar)==="true"}set showbar(t){S.IsNullOrUndefined(t)||this.setProperty(p.showbar,String(t))}get labelwidth(){let t=+this.getProperty(p.LabelWidth);return t===0?bk:t}set labelwidth(t){S.IsNullOrUndefined(t)||t>283&&t<57||this.setProperty(p.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:gk(this.fieldLabelAlignment),Position:vk(this.fieldLabelPosition)},Columns:Ow(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()===g.formSection){let i=n;i.Name&&!P.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}isReferencePanelSection(){return!S.IsNullOrUndefined(this)&&!S.IsNullOrUndefined(this.Name)&&this.Name.indexOf(le.referencePanelNamePrefix)===0}getAllMultiRowCells(){return this.findAll(t=>{if(t.getNodeName()===g.formCell){let r=t;return!r.isEmpty()&&r.rowspan>1}return!1})}isHeaderOrFooterSection(){return this.NodeName===g.formFooter||this.NodeName===g.formHeader}}});var kr,Is=D(()=>{"use strict";G();Le();Ba();kr=class e extends q{constructor(t){super(g.formColumn,t)}initializeDefaultProperties(t){this.addProperty(p.width,t.toString()+"%")}insertSectionAtIndex(t,r){this.addGrandChildAtIndex(g.formSections,t,r)}static createAndInitNewSection(t,r,n){let i=new Qt(g.formSection,null);return i.initialize(t,r,n),i}addSectionAtIndex(t,r){this.addGrandChildAtIndex(g.formSections,t,r)}initialize(t,r,n,i=pe.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(g.formTab)}get sections(){let t=this.getChildren("sections");return t.length!==1?[]:t[0].getChildren(g.formSection)}get width(){return this.getProperty(p.width)}set width(t){this.setProperty(p.width,t)}deleteSection(t){return this.deleteFirstGrandChildOfName(g.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(p.Name),Id:this.getProperty(p.id),Label:null,ShowLabel:!1,Visible:!0,LabelId:null,PreviewId:this.getProperty(p.id),Sections:await this.getSectionsJSON(t),Width:this.width}}}});var _s,Tw=D(()=>{"use strict";De();G();Rt();Ba();_s=class extends Qt{initializeNavArea(t,r,n){this.initializeNavAreaProps(t,r,n)}get AreaName(){return this.Name}initializeNavAreaProps(t,r,n){this.addProperty(p.Name,n),this.addProperty(p.id,new _(_.NewGuid()).guidString),this.addProperty(p.columnName,le.columns),this.setDisplayName(r,t)}}});var Ps,Rw=D(()=>{"use strict";Is();G();Tw();Ps=class extends kr{addAndIntializeNavBarSection(t,r,n,i){let a=new _s(g.formSection,null);return a.initializeNavArea(t,r,i),this.addGrandChildAtIndex(g.formSections,a,n),a}}});var vr,Os=D(()=>{"use strict";De();Ce();We();Is();G();Le();Br();vr=class extends je{tabContainsAutoExpandControl;autoExpandCell;constructor(t,r){super(g.formTab,t),this.tabContainsAutoExpandControl=!1}getParentForm(){return this.getAncestor(g.form)}getTabLayoutType(){let t;switch(this.columns.length){case 1:t=de.ONE_COLUMN;break;case 2:if(parseInt(this.columns[0].width,10)===50&&parseInt(this.columns[1].width,10)===50){t=de.TWO_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===67&&parseInt(this.columns[1].width,10)===33){t=de.TWO_COLUMN_WIDER_LEFT;break}if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===66){t=de.TWO_COLUMN_WIDER_RIGHT;break}t=de.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=de.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=de.THREE_COLUMN_WIDER_MID;break}t=de.THREE_COLUMN_CUSTOM_LAYOUT;break;default:}return t}initializeProperties(t,r,n){this.addProperty(p.Name,Rr.namePrefix+t.toString()),this.addProperty(p.id,new _(_.NewGuid()).guidString),this.addProperty(p.IsUserDefined,Rr.IsUserDefined),this.addProperty(p.locklevel,Rr.LockLevel),this.addProperty(p.showlabel,Rr.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=pe.ONE_COLUMN,a=!0,o){let s=this.getChildren(g.formColumns)[0],l=[];switch(t){case de.ONE_COLUMN:l.push(100);break;case de.TWO_COLUMN_EQUAL:l.push(50),l.push(50);break;case de.TWO_COLUMN_WIDER_LEFT:l.push(67),l.push(33);break;case de.TWO_COLUMN_WIDER_RIGHT:l.push(34),l.push(66);break;case de.THREE_COLUMN_EQUAL:l.push(34),l.push(33),l.push(33);break;case de.THREE_COLUMN_WIDER_MID:l.push(28),l.push(44),l.push(28);break;default:}for(let u of l){let c=new kr(s);c.initialize(u,r,n,i),this.addGrandChild(g.formColumns,c)}}initialize(t,r,n,i,a,o=pe.ONE_COLUMN,s=!0,l){this.addChild(new q(g.formColumns,this)),this.initializeProperties(r,n,i),this.initializeColumns(t,n,a,o,s,l)}get columns(){let t=this.getChildren(g.formColumns);return t.length!==1?[]:t[0].getChildren(g.formColumn)}get expanded(){return this.getProcessedValue(p.expanded)}set expanded(t){S.IsNullOrUndefined(t)||this.setProperty(p.expanded,String(t))}get groupName(){return this.getProperty(p.groupName)}get contentType(){return this.getProperty(p.contentType)}set contentType(t){this.setProperty(p.contentType,t)}insertNewColumnAtIndex(t,r,n,i,a){t.initialize(n,i,a),this.addGrandChildAtIndex(g.formColumns,t,r)}insertColumnAtIndex(t,r){this.addGrandChildAtIndex(g.formColumns,t,r)}deleteColumn(t){return this.deleteFirstGrandChildOfName(g.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()===g.formTab){let i=n;i.Name&&!P.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}}});var cn,Id=D(()=>{"use strict";De();G();Le();Rt();Rw();Os();cn=class extends vr{constructor(t,r,n){super(t,de.THREE_COLUMN_EQUAL),this.setDisplayName(r,n),this.id=new _(_.NewGuid())}initializeDefaultProps(){this.addChild(new q(g.formColumns,this)),this.initializeFiveColumns()}get columns(){let t=this.getChildren("columns");return t.length!==1?[]:t[0].getChildren(g.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<os.FIVE_COLUMN;t++){let r=new Ps(this.getChildren(g.formColumns)[0]);r.initializeDefaultProperties(Vh.FiveEqColumn),this.addGrandChild(g.formColumns,r)}}}});function Ck(e){switch(e){case Ee.Main:return xr.Main;case Ee.QuickCreate:return xr.QuickCreate;case Ee.QuickViewForm:return xr.Quick;case Ee.Dialog:return xr.Dialog;default:return xr.None}}function Ak(e,t){if(t===Ee.Main){if(e)switch(e.toLowerCase()){case"low":return Tr.Low;case"highreadonlyvalues":return Tr.HighReadOnlyValues;default:return Tr.HighWithControls}return Tr.Low}}var Rs,yk,Ts,Fw=D(()=>{"use strict";o0();Rs=ne(en());Tc();Ce();We();Bn();bd();G();$n();Qu();Zr();Ua();G();Br();Dd();Id();Os();yk="1920";Ts=class e extends je{_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(g.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 zo,this._metadataChangeEvent=new ds}get FormLibraries(){let t=this.getFirstChild(g.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 ot).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 ot){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()===g.internalLibraries),r=[],n="src";return t.length>0&&(r=t.map(i=>{let a=i.GetPropertyByParameter(n).replace("$webresource:",""),o=new ci(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,Rs.trackErrorTrace)(fh,{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 P.IsNullOrEmpty(this.getProperty(p.ShowImage))?!0:this.getProperty(p.ShowImage)!=="false"}set ShowImagecheck(t){t?this.setProperty(p.ShowImage,String(t)):this.setProperty(p.ShowImage,"false")}get ShowNavigation(){return P.IsNullOrEmpty(this.getProperty(p.ShowNavigationbar))?!0:this.getProperty(p.ShowNavigationbar)!=="false"}set ShowNavigation(t){t?this.setProperty(p.ShowNavigationbar,String(t)):this.setProperty(p.ShowNavigationbar,"false")}get MaxWidth(){return P.IsNullOrEmpty(this.getProperty(p.MaxWidth))?yk:this.getProperty(p.MaxWidth)}set MaxWidth(t){this.setProperty(p.MaxWidth,t)}get headerDensityType(){return this.getProperty(p.HeaderDensityType)}set headerDensityType(t){t&&this.formType===Ee.Main?this.setProperty(p.HeaderDensityType,t):this.formType!==Ee.Main&&this.headerDensityType&&this.removeProperty(p.HeaderDensityType)}IsMainOrQuickCreateForm(){return this.formType===Ee.Main||this.formType===Ee.QuickCreate}get FormPresentation(){return this._formPresentation}get LanguageCode(){return this._langCode}set LanguageCode(t){this._langCode=t}get header(){let t=this.getChildren(g.formHeader);return t.length!==1?null:t[0]}set header(t){S.IsNullOrUndefined(t)||(this.deleteChild(this.header),this.addChild(t))}getAllDependencies(){return this.getChildren(g.quickFormDependencies).length===0?[]:this.ConvertModelToArray(this.getChildren(g.quickFormDependencies)[0].getAllChildren())}ConvertModelToArray(t){let r=[];return S.IsNullOrUndefined(t)||t.forEach(n=>{r.push(n.id)}),r}get footer(){let t=this.getChildren(g.formFooter);return t.length!==1?null:t[0]}set footer(t){S.IsNullOrUndefined(t)||(this.deleteChild(this.footer),this.addChild(t))}createAndInitNewTab(t,r,n){let i=new vr(null,t),a=this.getNextTabCounter(this.tabs.length+1);return i.initialize(t,a,this.LanguageCode,r,n),i}addTabAtIndex(t,r){this.addGrandChildAtIndex(g.formTabs,t,r)}createAndInitNewTabWithMarginalControl(t,r,n,i,a){let o=new vr(null,de.ONE_COLUMN),s=this.getNextTabCounter(this.tabs.length+1);o.initialize(de.ONE_COLUMN,s,this.LanguageCode,r,n,a,!1),this.addGrandChildAtIndex(g.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===Rr.namePrefix+t.toString())return this.getNextTabCounter(t+1);return t}get allTabs(){let t=this.getChildren(g.formTabs);return t.length!==1?[]:t[0].getChildren(g.formTab)}get CanvasNavigationTab(){if(this.tabs.length>0){let t=this.tabs[this.tabs.length-1];if(t instanceof cn)return t}return null}get NavigationNode(){let t=this.getChildren(g.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(g.formTabs,t)}insertTabAtIndex(t,r){this.addGrandChildAtIndex(g.formTabs,t,r)}insertRelatedTab(t){let r=this.getAllGrandChildren(g.formTabs);if(!S.IsNullOrUndefined(r)){let n=r.length;this.insertTabAtIndex(t,n)}}get isfooterPresent(){return this.getChildren(g.formFooter).length>0}get displayCondition(){let t=this.getChildren(g.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(g.formTabs).indexOf(t)}get ControlDescriptions(){return this.getAllGrandChildren(g.controlDescriptions)}addControlDescriptionNode(t){this.addGrandChild(g.controlDescriptions,t)}deleteControlDescByForControlId(t){let r=this.getControlDescriptionByForControl(t);S.IsNullOrUndefined(r)||this.deleteFirstGrandChildOfName(g.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 ot))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 ot&&i.control&&t.control&&a&&i.control.dataFieldName===t.control.dataFieldName})}isCellEditableGridControl(t){return!t?.control?.indicationOfSubgrid||t.control.ClassId.guidString.toUpperCase()!==A.CustomControl?!1:this.cellHasCustomControlWithName(t,Fr.EditableGridControl)||Sw.getConfig()?.enableOneGridEventsForFormDesigner&&this.cellHasCustomControlWithName(t,Fr.PowerAppsOneGrid)}isCellCanvasAppControl(t){return t?.control?.ClassId.guidString.toUpperCase()===A.CustomControl&&this.cellHasCustomControlWithName(t,Fr.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()===g.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 cn)){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,Rs.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===Ee.Main?{HeaderDensity:Ak(this.headerDensityType,this.formType)}:{},InlineEditGridRow:[],InlineQuickForms:[],QuickFormEntities:[],EventHandlers:[],LinkControlSections:[],FormType:Ck(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 Fs,_d,xw=D(()=>{"use strict";De();Ce();G();Le();Br();Fs=class extends je{constructor(t){super(g.formDisplayConditions,t)}get Order(){let t=this.getProperty(p.Order);return S.IsNullOrUndefined(t)?null:parseInt(t,10)}set Order(t){this.setProperty(p.Order,t.toString())}get FallbackForm(){return this.getProperty(p.FallbackForm)==="true"}set FallbackForm(t){this.setProperty(p.FallbackForm,t.toString())}addRoles(t){this.deleteAllChildren();for(let r=0;r<t.length;r++)this.addChild(t[r])}isRoleEveryone(){return!!(this.getChildren(g.formEveryOne)&&this.getChildren(g.formEveryOne)[0])}setRoleEveryone(){this.deleteAllChildren(),this.addChild(new _d(this))}},_d=class extends q{constructor(t){super(g.formEveryOne,t)}}});var xs,Lw=D(()=>{"use strict";G();Le();xs=class extends q{constructor(t,r){super(g.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(p.HandlerUniqueId)}set HandlerUniqueID(t){this.setProperty(p.HandlerUniqueId,t)}get FunctionName(){return this.getProperty(p.functionName)}set FunctionName(t){this.setProperty(p.functionName,t)}get LibraryName(){return this.getProperty(p.libraryNameEventHandler)}set LibraryName(t){this.setProperty(p.libraryNameEventHandler,t)}get Enabled(){return this.getProperty(p.enabledForField)}set Enabled(t){this.setProperty(p.enabledForField,t)}get PassExecutionContext(){return this.getProperty(p.passExecutionContext)}set PassExecutionContext(t){this.setProperty(p.passExecutionContext,t)}get Parameters(){return this.getProperty(p.parameters)}set Parameters(t){this.setProperty(p.parameters,t)}}});var di,Pd=D(()=>{"use strict";G();Ba();di=class extends Qt{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(g.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 ka,Mw=D(()=>{"use strict";G();Pd();ka=class extends di{_customFooter;constructor(t,r){super(g.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 qa,Uw=D(()=>{"use strict";G();Pd();qa=class extends di{_customHeader;constructor(t,r){super(g.formHeader,t),this._customHeader=r}get customHeader(){return this._customHeader}set customHeader(t){this._customHeader=t}get showCommandBar(){return this.getProcessedValue(p.showCommandBar)}set showCommandBar(t){t!=null&&this.setProperty(p.showCommandBar,String(t))}get showBody(){return this.getProcessedValue(p.showBody)}set showBody(t){t!=null&&this.setProperty(p.showBody,String(t))}get showTabNavigator(){return this.getProcessedValue(p.showTabNavigator)}set showTabNavigator(t){t!=null&&this.setProperty(p.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 st,dn=D(()=>{"use strict";De();We();G();Br();st=class e extends je{constructor(t,r){super(t,r)}getTitle(t){for(let r of this.getAllTitles())if(+r.getProperty(p.LCID)===t)return r.getProperty(p.text);return null}getAllTitles(){let t=this.getChildren(g.Titles);return t.length===0?[]:t[0].getChildren(g.Title)}setTitle(t,r){for(let i of this.getAllTitles())if(+i.getProperty(p.LCID)===r){i.setProperty(p.text,t);return}let n=new e(g.Title,null);n.setProperty(p.text,t),n.setProperty(p.LCID,String(r)),this.addGrandChild(g.Titles,n)}get Sequence(){return+this.getProperty(p.Sequence)}set Sequence(t){this.setProperty(p.Sequence,t.toString())}get Area(){return this.getProperty(p.Area)}set Area(t){this.setProperty(p.Area,t)}set Id(t){this.setProperty(p.Id,t)}get Id(){return this.getProperty(p.Id)}get id(){return new _(this.Id??"",!0)}set id(t){this.Id=t.guidString}get Show(){return!0}get Icon(){return this.getProperty(p.icon)}set Icon(t){t=t||P.EmptyString,this.setProperty(p.icon,t)}updateCommonProperties(t,r){this.Area=t.Area,this.Sequence=t.Sequence,this.setTitle(t.getDisplayName(r),r)}}});var $a,Bw=D(()=>{"use strict";(function(e){e[e.NavLinkNotAvailable=-1]="NavLinkNotAvailable",e[e.NavLinkIdConflict=-2]="NavLinkIdConflict",e[e.NavBarNotAvailable=-3]="NavBarNotAvailable"})($a||($a={}))});var Ls,kw=D(()=>{"use strict";Ce();G();dn();Bw();Ls=class extends st{constructor(t){super(g.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 S.IsNullOrUndefined(r)?$a.NavLinkNotAvailable:r.length===1?this.deleteChild(r[0]):$a.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 oe,wk,qw,JH,pi,Od=D(()=>{"use strict";De();G();dn();(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"})(oe||(oe={}));wk=new Map([[oe.Info,"Info"],[oe.Sales,"Sales"],[oe.Service,"Service"],[oe.Marketing,"Marketing"],[oe.ProcessCenter,"ProcessCenter"]]),qw=new Map([["Info",oe.Info],["Sales",oe.Sales],["Service",oe.Service],["Marketing",oe.Marketing],["ProcessCenter",oe.ProcessCenter]]),JH=new Map([[oe.Info,9e3],[oe.Sales,9200],[oe.Service,9400],[oe.Marketing,9600],[oe.ProcessCenter,9800],[oe.InternetMarketing,1e4],[oe.Async,10200]]),pi=class extends st{constructor(t,r){super(g.formNavBarArea,r)}setDefaultPropertiesByType(t,r,n){this.AreaId=wk.get(t);let i=n?.(`navBarArea.title.${this.AreaId}`)??this.AreaId;this.setTitle(i,r)}get ParentNavigation(){return this.getAncestor(g.formNavigation)}get AreaId(){return this.getProperty(p.Id)}set AreaId(t){this.setProperty(p.Id,t)}get id(){return new _(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 fi,Td=D(()=>{"use strict";G();dn();fi=class extends st{constructor(t,r){super(g.formNavBarAreas,r)}get AllNavBarAreaItems(){return this.getChildren(g.formNavBarArea)}get ParentNavigation(){return this.getAncestor(g.formNavigation)}addNavBarArea(t){this.addChild(t)}}});var Ms,$w=D(()=>{"use strict";Ce();G();dn();Ms=class extends st{RelationshipNameUCIRuntime;constructor(t){super(g.formNavBarByRelationshipItem,t)}get RelationshipName(){return this.getProperty(p.RelationshipName)}set RelationshipName(t){this.setProperty(p.RelationshipName,t)}set Show(t){this.setProperty(p.Show,String(t))}get Show(){let t=this.getProperty(p.Show);return S.IsNullOrUndefined(t)||t==="true"}get TitleResourceId(){return this.getProperty(p.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 Us,Vw=D(()=>{"use strict";G();dn();Us=class extends st{constructor(t){super(g.formNavBarItem,t)}get Url(){return this.getProperty(p.url)}set Url(t){this.setProperty(p.url,t)}}});var Bs,Gw=D(()=>{"use strict";De();G();Od();Td();dn();Bs=class extends st{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(g.formNavBarAreas)}setDefaultNavBarAreas(t,r){let n=[oe.Info,oe.Sales,oe.Service,oe.Marketing,oe.ProcessCenter];if(this.navBarAreas){let i=this.navBarAreas?.AllNavBarAreaItems;if(i&&i.length>0){let a=new Set(i.map(o=>qw.get(o.AreaId)));n=n.filter(o=>!a.has(o))}}else{let i=new fi(g.formNavBarAreas,this);i.isTransient=!0,this.addChild(i)}return n.length>0?(n.forEach(i=>{let a=new pi(g.formNavBarArea,this.navBarAreas);a.setDefaultPropertiesByType(i,t,r),this.navBarAreas.addNavBarArea(a)}),!0):!1}get navBar(){return this.getFirstChild(g.formNavBar)}get id(){return new _(sc,!0)}replaceNavAreaToGivenIndex(t,r){this.navBarAreas?.AllNavBarAreaItems.indexOf(r)!==-1&&(this.deleteFirstGrandChildOfName(g.formNavBarAreas,r),this.addGrandChildAtIndex(g.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 zw={};Bt(zw,{ControlType:()=>At,DeserializationService:()=>xd,DeserializationServiceScope:()=>Fd,DeserializedFormElementNode:()=>lt});var Rd,lt,Fd,At,xd,Sd=D(()=>{"use strict";Rd=ne(en());De();Ce();We();Bn();lc();Zr();mh();a0();cs();Fw();Ua();Is();Ma();yd();G();G();xw();Le();Rt();Cd();Lw();Mw();Ad();wd();Uw();Dd();Ed();Ba();Os();kw();Od();Td();$w();Vw();Gw();lt=class extends q{constructor(t,r){super(t,r)}insertProperty(t,r){this.addProperty(t,r)}insertChild(t){this.addChild(t)}},Fd="DeserializationService";(function(e){e.Grid="Grid",e.Lookup="Lookup",e.Base="Base"})(At||(At={}));xd=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 h="";throw d.length===0?h="FormXml has no form node.":h="FormXml has multiple form nodes.",(0,Rd.trackErrorTrace)(Xe,{eventName:Fd,eventData:{error:h}}),new Error(h)}let f=this.createFormModel(d.item(0),r,n,i,a,o,s,l,u,c);return S.IsNullOrUndefined(f.displayCondition)&&s!==Ee.Dialog&&this.appendDefaultDisplayCondition(f),f}upsertFieldCount(t,r){let n=tn.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(!S.IsNullOrUndefined(t)){let n=S.ParseXml(r);n!==null&&this.populateElementChildren(t,n.childNodes)}}createFormModel(t,r,n,i,a,o,s,l,u,c){let d=new Ts(r,n,i,a,o,s,l,u,c);return this.populateElementProperties(d,t.attributes),this.populateElementChildren(d,t.childNodes),s===Ee.Main&&(this.insertHeaderFooterElementProperties(g.formHeader,d,d.header),this.insertHeaderFooterElementProperties(g.formFooter,d,d.footer)),d}insertHeaderFooterElementProperties(t,r,n){if(S.IsNullOrUndefined(n)){let i=t===g.formHeader?new qa(r,!0):new ka(r,!0);lt.prototype.insertProperty.call(i,p.id,"{"+_.NewGuid()+"}"),lt.prototype.insertProperty.call(i,p.Fieldlabelposition,"Top"),lt.prototype.insertProperty.call(i,p.columnName,le.MarginalControlColumns),lt.prototype.insertProperty.call(i,p.LabelWidth,le.LabelWidth),lt.prototype.insertProperty.call(i,p.Fieldlabelalignment,"Left");let a=null,o=new un(a);for(let s=0;s<i.maxColumns;s++){let l=new ot(o);lt.prototype.insertProperty.call(l,p.id,"{"+_.NewGuid()+"}"),l.setDisplayName(P.EmptyString,this.lcid),lt.prototype.insertProperty.call(l,p.showlabel,"false"),o.addCell(l)}i.appendRow(o),t===g.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 lt(`<${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,Rd.trackErrorTrace)(Xe,{eventName:Fd,eventData:{error:n}}),new Error(n)}for(let n=0;n<r.length;n++){let i=r.item(n);i&&(lt.prototype.insertProperty.call(t,i.name,i.value),t.getNodeName()===g.formCell&&i.name===p.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&<.prototype.insertChild.call(t,a)}}createModelNode(t,r){switch(t.nodeName){case g.form:throw new Error("Form node shouldn't be created using this method");case g.formTab:return new vr(r);case g.formColumn:return new kr(r);case g.formHeader:return new qa(r,!1);case g.formFooter:return new ka(r,!1);case g.formSection:return new Qt(g.formSection,r);case g.formRow:return new un(r);case g.formCell:return new ot(r);case g.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===p.indicationOfSubgrid&&l.value==="true"||l.name===p.classid&&(l.value?.toLocaleUpperCase()===`{${A.SubgridControl}}`||l.value?.toLocaleUpperCase()===`{${A.ReferencePanelSubgridControl}}`))a=At.Grid;else if(l.name===p.classid&&l.value?.toLocaleUpperCase()===`{${A.LookupControl}}`)a=At.Lookup;else if(l.name===p.classid&&l.value?.toLocaleUpperCase()===`{${A.CustomControl}}`)for(let u=0;u<i?.length;u++)i[u].nodeName===p.DefaultViewId&&(a=At.Lookup)}return a===At.Grid?new li(r):a===At.Lookup?new ui(r):new Lt(r);case g.formEvent:return new si(r,P.EmptyString);case g.dependency:return this.populateDependencyTable(t),new oi(r,P.EmptyString);case g.Handler:let o=[];return new xs(o,r);case g.formNavigation:return new Bs(t.nodeName,r);case g.formNavBarArea:return new pi(t.nodeName,r);case g.formNavBarAreas:return new fi(t.nodeName,r);case g.formNavBar:return new Ls(r);case g.formNavBarByRelationshipItem:return new Ms(r);case g.formNavBarItem:return new Us(r);case g.formDisplayConditions:return new Fs(r);case g.library:return new ci(r,P.EmptyString,P.EmptyString);case g.controlDescription:return new Qo(r);case g.customControl:return this.populateCustomControlConfigurationId(t),new us(r);default:return new lt(t.nodeName,r)}}populateDependencyTable(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);i.name===p.id&&this.upsertFieldCount(i.value,Wt.DependencyFieldTable)}}populateCustomControlConfigurationId(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);if(i.name===p.id){let a=new _(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===p.ForControl){let l=s.value.substr(1,i.value.length-2);Ie.CustomControlIdMap.upsert(l,a);break}}break}}}}});var Ww={};Bt(Ww,{SerializationService:()=>Ld,SerializationServiceScope:()=>Nk,SerializedFormElementNode:()=>mi});var Nk,mi,Ld,jw=D(()=>{"use strict";We();Le();Rt();Id();Nk="SerializationService",mi=class extends q{fetchNodeName(){return this.getNodeName()}enumerateProperties(){return this.getAllProperties()}enumerateChildren(){return this.getAllChildren()}},Ld=class{langCode;constructor(t){this.langCode=t}serializeFormXmlNode(t){let r=mi.prototype.fetchNodeName.call(t);if(r.charAt(0)===hr.StartTag)return P.EscapeXml(r.substr(1),!1);if(t.isTransient&&!t.isDirty())return P.EmptyString;let n=mi.prototype.enumerateProperties.call(t),i=mi.prototype.enumerateChildren.call(t);if(!(t instanceof cn)){let a=`<${r}`;if(n.length!==0&&(a+=` ${this.getPropertiesString(n)}`),i.length===0)a+=" />";else{let o=P.EmptyString;for(let s of i)o+=this.serializeFormXmlNode(s);a+=`>${o}</${r}>`}return a}return P.EmptyString}getPropertiesString(t){let r=P.EmptyString;return t.forEach((n,i)=>{i!==0&&(r+=" "),r+=`${n.key}="${P.EscapeXml(n.value,!0)}"`}),r}}});var pn=m(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.rebuildRaw=ut.assembleChildren=ut.spliceChildren=ut.mergeAttrs=ut.rawFromNode=ut.emptyBag=void 0;var qr=be(),Hw=1e6,qs=512;function Sk(){return{a:[],c:[]}}ut.emptyBag=Sk;function Jw(e,t=0){if(t>qs)throw new qr.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${qs}`);return{n:e.getNodeName(),a:e.getAllProperties().map(r=>[r.key,r.value]),c:e.getAllChildren().map(r=>Jw(r,t+1))}}ut.rawFromNode=Jw;function Dk(e,t){let r=new Map;for(let[a,o]of t)r.set(a,o);let n=new Set,i=[];for(let[a,o]of e)r.has(a)?i.push([a,r.get(a)]):i.push([a,o]),n.add(a);for(let[a,o]of t)n.has(a)||(i.push([a,o]),n.add(a));return i}ut.mergeAttrs=Dk;function ks(e,t){let r=new Set;for(let s of e){let l=s.i;if(!Number.isInteger(l)||l<0||l>Hw)throw new qr.InvalidArgumentError(`Bag child index must be an integer in [0, ${Hw}] (got ${String(l)})`);if(r.has(l))throw new qr.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}ut.spliceChildren=ks;function Ek(e,t){if(e.w){let r={n:e.w.n,a:e.w.a.map(n=>[n[0],n[1]]),c:ks(e.w.c,t)};return ks(e.c,[r])}return ks(e.c,t)}ut.assembleChildren=Ek;function Qw(e,t,r,n=0){if(n>qs)throw new qr.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${qs}`);Ik(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,Qw(a,t,i,n+1));return i}ut.rebuildRaw=Qw;function Ik(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new qr.InvalidArgumentError(`Malformed hybrid node at depth ${t}: expected a JSON object`);let r=e;if(typeof r.n!="string")throw new qr.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 qr.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 qr.InvalidArgumentError(`Malformed hybrid node '${r.n}': each attribute must be a [string, string] pair`)}});var $r=m(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.childObjects=ct.optionalGuidId=ct.optionalEnum=ct.eachObject=ct.issue=ct.isJsonObject=void 0;function Xw(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}ct.isJsonObject=Xw;function Va(e,t,r,n){return n?{pointer:e,rule:t,message:r,fatal:n}:{pointer:e,rule:t,message:r}}ct.issue=Va;function Kw(e,t,r,n){if(!Array.isArray(e))return[];let i=[];return e.forEach((a,o)=>{Xw(a)?i.push({node:a,index:o}):n.push(Va(`${t}/${o}`,`${r}-must-be-object`,`a ${r} must be a JSON object, got ${a===null?"null":typeof a}`))}),i}ct.eachObject=Kw;function _k(e,t,r,n,i,a){let o=e[t];o!==void 0&&(typeof o!="string"||!r.includes(o))&&a.push(Va(`${n}/${t}`,i,`${t} must be one of ${r.map(s=>`'${s}'`).join(", ")}, got ${JSON.stringify(o)}`))}ct.optionalEnum=_k;var Pk=/^(?:\{[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 Ok(e,t,r,n,i){let a=e[t];typeof a=="string"&&a!==""&&!Pk.test(a)&&i.push(Va(`${r}/${t}`,n,`${t} must be a GUID or empty, got '${a}'`))}ct.optionalGuidId=Ok;function Tk(e,t,r,n,i){let a=e[t],o=`${r}/${t}`;return a===void 0?[]:Array.isArray(a)?Kw(a,o,n,i):(i.push(Va(o,`${n}-list-must-be-array`,`${t} must be an array when present, got ${typeof a}`)),[])}ct.childObjects=Tk});var Yw=m($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});$s.formApi=void 0;var br=Ve(),Ga=ce(),Rk="formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber",Fk="formid,name,type,objecttypecode",xk=2;$s.formApi={async get(e,t){let n=`/systemforms(${(0,Ga.normalizeGuid)(t,"id")})${(0,Ga.odataQuery)([["$select",Rk]])}`,i=(0,br.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,br.readEtag)(i)}},async list(e,t){var r;let n=[`type eq ${xk}`];t?.entityLogicalName&&n.push(`objecttypecode eq '${(0,Ga.odataLiteral)(t.entityLogicalName)}'`);let i=`/systemforms${(0,Ga.odataQuery)([["$select",Fk],["$filter",n.join(" and ")]])}`,o=(0,br.ensureSuccess)(await e.get(i),e.apiUrl(i)).body;return((r=o?.value)!==null&&r!==void 0?r:[]).map(l=>{var u,c;return{type:"form",id:(u=l.formid)!==null&&u!==void 0?u:"",name:(c=l.name)!==null&&c!==void 0?c:"",entityLogicalName:l.objecttypecode,isDirty:!1}})},async create(e,t){let r="/systemforms",n=(0,br.ensureSuccess)(await e.post(r,t),e.apiUrl(r));return{id:(0,br.requireCreatedId)(n,"formid","form"),etag:(0,br.readEtag)(n)}},async update(e,t,r,n){let i=(0,Ga.normalizeGuid)(t,"id"),a=`/systemforms(${i})`,o=n?{"If-Match":n}:void 0,s=(0,br.ensureSuccess)(await e.patch(a,r,o?{headers:o}:void 0),e.apiUrl(a));return{id:i,etag:(0,br.readEtag)(s)}},delete(e,t){return(0,br.deleteRecord)(e,"systemforms",t)}}});var fn=m(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});Vs.installDomShim=void 0;var Zw=Wu(),eN=!1,Lk={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 Mk(){if(eN)return;let e=globalThis;typeof e.DOMParser>"u"&&(e.DOMParser=Zw.DOMParser),typeof e.XMLSerializer>"u"&&(e.XMLSerializer=Zw.XMLSerializer),typeof e.Node>"u"&&(e.Node=Lk),eN=!0}Vs.installDomShim=Mk});var mN=m(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.classIdForAttributeType=dt.QUICK_VIEW_CLASS_ID=dt.NOTES_CLASS_ID=dt.SUBGRID_CLASS_ID=dt.formRegistration=dt.FormAdapter=void 0;var wt=(De(),kt(ah)),Uk=(Ce(),kt(oh)),Bk=(Le(),kt(lh)),He=(G(),kt(sh)),_e=(Zr(),kt(uh)),kk=(Sd(),kt(zw)),qk=(jw(),kt(Ww)),Pe=pn(),mn=$r(),$k=Yw(),Vk=Tt(),kd=ce(),aN=fn(),Xt=1033,Gk={[He.FormType.Main]:"Main",[He.FormType.QuickCreate]:"QuickCreate",[He.FormType.QuickViewForm]:"QuickView",[He.FormType.Card]:"Card"},Md={Main:He.FormType.Main,QuickCreate:He.FormType.QuickCreate,QuickView:He.FormType.QuickViewForm,Card:He.FormType.Card},zk=new Map(Object.entries(_e.ControlClassId).map(([e,t])=>[String(t).toUpperCase(),e]));function oN(e){var t;return e&&(t=zk.get(e.toUpperCase()))!==null&&t!==void 0?t:"Unknown"}function za(e){return e.getAllProperties().map(t=>[t.key,t.value])}function hn(e){let t=new Map;for(let r of e.getAllProperties())t.has(r.key)||t.set(r.key,r.value);return t}function sN(e,t){return e.getAllChildren().find(r=>r.getNodeName()===t)}function qd(e){var t,r;let n=sN(e,"labels");if(!n)return"";let i=n.getAllChildren().filter(o=>o.getNodeName()==="label"),a=(t=i.find(o=>hn(o).get("languagecode")===String(Xt)))!==null&&t!==void 0?t:i[0];return a&&(r=hn(a).get("description"))!==null&&r!==void 0?r:""}function Wk(e){let t=sN(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 lN(e){return/^1+$/.test(e)&&e.length>=1&&e.length<=4?e.length:1}function Ud(e){let t=Math.min(Math.max(Math.trunc(e),1),4);return"1".repeat(t)}function gn(e){return e.replace(/[{}]/g,"")}function Bd(e){return`{${gn(e)}}`}function tN(e,t){if(e===void 0||e==="")return t;let r=Number(e);return Number.isNaN(r)?t:r}function zs(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,Pe.rawFromNode)(u)})}),i<0)return{modeled:[],bag:{a:za(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,Pe.rawFromNode)(u)})}),{modeled:s,bag:{a:za(e),c:a,w:{n:o.getNodeName(),a:za(o),c:l}}}}function uN(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,Pe.rawFromNode)(a)})}),{modeled:n,bag:{a:za(e),c:i}}}function jk(e){let{modeled:t,bag:r}=zs(e,"tabs","tab");return{tabs:t.map(Hk),bag:r}}function Hk(e){var t,r;let n=hn(e),{modeled:i,bag:a}=zs(e,"columns","column");return{id:(t=n.get("id"))!==null&&t!==void 0?t:"",name:(r=n.get("name"))!==null&&r!==void 0?r:"",label:qd(e),expanded:n.get("expanded")==="true",visible:n.has("visible")?n.get("visible")==="true":!0,columns:i.map(Jk),bag:a}}function Jk(e){let t=hn(e),{modeled:r,bag:n}=zs(e,"sections","section");return{width:t.get("width"),sections:r.map(Qk),bag:n}}function Qk(e){var t,r,n;let i=hn(e),{modeled:a,bag:o}=zs(e,"rows","row");return{id:(t=i.get("id"))!==null&&t!==void 0?t:"",name:(r=i.get("name"))!==null&&r!==void 0?r:"",label:qd(e),visible:i.has("visible")?i.get("visible")==="true":!0,showLabel:i.get("showlabel")==="true",columns:lN((n=i.get("columns"))!==null&&n!==void 0?n:"1"),rows:a.map(Xk),bag:o}}function Xk(e){let{modeled:t,bag:r}=uN(e,"cell",!1);return{cells:t.map(Kk),bag:r}}function Kk(e){var t;let r=hn(e),{modeled:n,bag:i}=uN(e,"control",!0),a=qd(e),o=r.get("showlabel")==="true",s=n[0]?Yk(n[0],a,o):null;return{id:(t=r.get("id"))!==null&&t!==void 0?t:"",visible:r.has("visible")?r.get("visible")==="true":!0,colspan:tN(r.get("colspan"),1),rowspan:tN(r.get("rowspan"),1),control:s,bag:i}}function Yk(e,t,r){var n,i;let a=hn(e),o=gn((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:oN(o),isRequired:a.get("isrequired")==="true",isReadOnly:a.get("disabled")==="true",label:t,showLabel:r,parameters:Wk(e),bag:{a:za(e),c:e.getAllChildren().map((l,u)=>({i:u,node:(0,Pe.rawFromNode)(l)}))}}}function hi(e){return e.a.length===0&&e.c.length===0&&!e.w}function cN(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function vn(e,t){var r;let n=new Set(e.a.map(o=>o[0])),i=hi(e),a=[];for(let o of t)if(n.has(o.key)){let s=(r=cN(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,Pe.mergeAttrs)(e.a,a)}var Vr=(e,t)=>({key:e,matches:r=>r===t,render:()=>t,absentDefault:""}),Gr=(e,t,r=!1)=>({key:e,matches:n=>n==="true"===t,render:()=>String(t),absentDefault:String(r)}),rN=(e,t,r=1)=>({key:e,matches:n=>Number(n)===t,render:()=>String(t),absentDefault:String(r)});function $d(e){return{n:"labels",a:[],c:[{n:"label",a:[["description",e],["languagecode",String(Xt)]],c:[]}]}}function dN(e){return{n:"parameters",a:[],c:Object.keys(e).map(t=>({n:(0,kd.assertXmlName)(t,"Form control parameter name"),a:[],c:[{n:`<${e[t]}`,a:[],c:[]}]}))}}function Zk(e){var t,r;let n=e.c.find(a=>a.n==="label"&&a.a.some(o=>o[0]==="languagecode"&&o[1]===String(Xt))),i=n??e.c.find(a=>a.n==="label");return(r=(t=i?.a.find(a=>a[0]==="description"))===null||t===void 0?void 0:t[1])!==null&&r!==void 0?r:""}function eq(e,t){let r=!1,n=e.c.map(i=>i.n!=="label"||!i.a.some(o=>o[0]==="languagecode"&&o[1]===String(Xt))?i:(r=!0,{...i,a:i.a.map(o=>o[0]==="description"?["description",t]:o)}));return r||n.push({n:"label",a:[["description",t],["languagecode",String(Xt)]],c:[]}),{...e,c:n}}function Vd(e,t){let r=e.c.findIndex(i=>i.node.n==="labels");if(r<0||Zk(e.c[r].node)===t)return e;let n=eq(e.c[r].node,t);return{...e,c:e.c.map((i,a)=>a===r?{...i,node:n}:i)}}function tq(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 rq(e,t){let r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every(i=>e[i]===t[i])}function nq(e,t){return e.a.some(r=>r[0]===t)?{...e,a:e.a.filter(r=>r[0]!==t)}:e}function iq(e,t){let r=e.c.findIndex(i=>i.node.n==="parameters");if(r<0||rq(tq(e.c[r].node),t))return e;let n=dN(t);return{...e,c:e.c.map((i,a)=>a===r?{...i,node:n}:i)}}function Ws(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,Pe.spliceChildren)(e.w.c,r)};return(0,Pe.spliceChildren)(e.c,[o])}let i=n(),a={n:t,a:[],c:r};return e.c.length===0?[...i,a]:(0,Pe.spliceChildren)(e.c,[...i,a])}function aq(e){let t=e.tabs.map(oq);return{n:"form",a:vn(e.bag,[]),c:e.tabs.length===0&&hi(e.bag)?[]:Ws(e.bag,"tabs",t,()=>[])}}function oq(e){let t=[Vr("id",e.id),Vr("name",e.name),Gr("expanded",e.expanded),Gr("visible",e.visible,!0)],r=e.columns.map(sq),n=Vd(e.bag,e.label);return{n:"tab",a:vn(n,t),c:Ws(n,"columns",r,()=>e.label?[$d(e.label)]:[])}}function sq(e){let t=e.width!==void 0?[Vr("width",e.width)]:[],r=e.sections.map(lq);return{n:"column",a:vn(e.bag,t),c:Ws(e.bag,"sections",r,()=>[])}}function lq(e){let t=[Vr("id",e.id),Vr("name",e.name),Gr("showlabel",e.showLabel),Gr("visible",e.visible,!0),{key:"columns",matches:i=>lN(i)===e.columns,render:()=>Ud(e.columns),absentDefault:Ud(1)}],r=e.rows.map(uq),n=Vd(e.bag,e.label);return{n:"section",a:vn(n,t),c:Ws(n,"rows",r,()=>e.label?[$d(e.label)]:[])}}function uq(e){let t=e.cells.map(cq);return{n:"row",a:vn(e.bag,[]),c:hi(e.bag)?t:(0,Pe.assembleChildren)(e.bag,t)}}function cq(e){let t=e.control?e.control.showLabel:cN(e.bag,"showlabel")==="true",r=[Vr("id",e.id),Gr("showlabel",t),Gr("visible",e.visible,!0),rN("colspan",e.colspan),rN("rowspan",e.rowspan)],n=e.control?[dq(e.control)]:[],i;if(hi(e.bag))i=[...e.control&&e.control.label?[$d(e.control.label)]:[],...n];else{let a=e.control?Vd(e.bag,e.control.label):e.bag;i=(0,Pe.assembleChildren)(a,n)}return{n:"cell",a:vn(e.bag,r),c:i}}function dq(e){let t=[Vr("id",e.id),{key:"classid",matches:i=>gn(i)===e.classId,render:()=>Bd(e.classId),absentDefault:""}];e.fieldName!==null&&t.push(Vr("datafieldname",e.fieldName)),t.push(Gr("disabled",e.isReadOnly)),t.push(Gr("isrequired",e.isRequired));let r=e.fieldName===null?nq(e.bag,"datafieldname"):e.bag,n;return hi(r)?n=Object.keys(e.parameters).length>0?[dN(e.parameters)]:[]:n=(0,Pe.assembleChildren)(iq(r,e.parameters),[]),{n:"control",a:vn(r,t),c:n}}var pq={make:(e,t)=>new Bk.FormElementNode(e,t),setProp:(e,t,r)=>e.setProperty(t,r),addChild:(e,t)=>e.addChild(t)};function nN(e,t){(0,aN.installDomShim)();let r=mq(e,t),n=(0,Pe.rebuildRaw)(aq(r),pq,null);return new qk.SerializationService(Xt).serializeFormXmlNode(n)}function fq(e){return JSON.parse(JSON.stringify(e))}function mq(e,t){var r;let n=fq(e);n.bag||(n.bag=(0,Pe.emptyBag)()),wq(n.bag),t&&hq(n,t);for(let i of(r=n.tabs)!==null&&r!==void 0?r:[])gq(i);return n}function hq(e,t){var r;let n=(r=e.entityLogicalName)!==null&&r!==void 0?r:"";pN(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=fN(s.attributeType)))})}function pN(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 gq(e){e.id||(e.id=wt.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)vq(t);e.bag||(e.bag=(0,Pe.emptyBag)())}function vq(e){e.sections||(e.sections=[]);for(let t of e.sections)bq(t);e.bag||(e.bag=(0,Pe.emptyBag)()),e.width===void 0&&hi(e.bag)&&(e.width="100%")}function bq(e){e.id||(e.id=wt.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)yq(t);e.bag||(e.bag=(0,Pe.emptyBag)())}function yq(e){e.cells||(e.cells=[]);for(let t of e.cells)Cq(t);e.bag||(e.bag=(0,Pe.emptyBag)())}function Cq(e){e.id||(e.id=wt.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&&Aq(e.control),e.bag||(e.bag=(0,Pe.emptyBag)())}function Aq(e){var t;e.id||(e.id=wt.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":oN(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,kd.assertXmlName)(r,"Form control parameter name");e.bag||(e.bag=(0,Pe.emptyBag)())}function wq(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"&&!iN(a,"handlerUniqueId")&&a.a.push(["handlerUniqueId",Bd(wt.Guid.NewGuid())])}}else if(r.n==="formLibraries")for(let n of r.c)n.n==="Library"&&!iN(n,"libraryUniqueId")&&n.a.push(["libraryUniqueId",Bd(wt.Guid.NewGuid())])}}var Gs=class{toArtifact(t){var r,n,i;let{tabs:a,bag:o}=jk(t);return{id:t.formId?t.formId.guidString:"",name:(r=t.formName)!==null&&r!==void 0?r:"",entityLogicalName:(n=t.entityName)!==null&&n!==void 0?n:"",formType:(i=Gk[t.formType])!==null&&i!==void 0?i:"Main",status:this.readActivationStatus(t),tabs:a,bag:o}}fromArtifact(t){return this.deserialize({formxml:nN(t),formid:t.id||wt.Guid.NewGuid(),objecttypecode:t.entityLogicalName,type:Md[t.formType],name:t.name,uniquename:t.name,description:"",formpresentation:He.FormPresentation.AirForm,formactivationstate:t.status==="Active"?He.FormActivationState.Active:He.FormActivationState.InActive})}fromApiResponse(t){var r,n,i,a,o,s;let l=t,u=this.deserialize({formxml:(r=l.formxml)!==null&&r!==void 0?r:"",formid:(n=l.formid)!==null&&n!==void 0?n:wt.Guid.NewGuid(),objecttypecode:(i=l.objecttypecode)!==null&&i!==void 0?i:"",type:l.type,name:(a=l.name)!==null&&a!==void 0?a:"",uniquename:(o=l.uniquename)!==null&&o!==void 0?o:"",description:(s=l.description)!==null&&s!==void 0?s:"",formpresentation:l.formpresentation,formactivationstate:l.formactivationstate});return this.toArtifact(u)}toApiPayload(t,r,n){return{formxml:nN(t,n),name:t.name,type:Md[t.formType],objecttypecode:t.entityLogicalName}}metadataNeeds(t){let r=t.entityLogicalName;if(!r)return[];let n=new Set,i=[];return pN(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;let f=t.tabs&&t.tabs.length>0?void 0:Tq,h=f!==void 0?f:t.tabs.map(N=>Nq(N)).join(""),b=this.deserialize({formxml:`<form><tabs>${h}</tabs></form>`,formid:t.id||wt.Guid.NewGuid(),objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",type:Md[(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:"",formpresentation:He.FormPresentation.AirForm,formactivationstate:((o=t.status)!==null&&o!==void 0?o:"Active")==="Active"?He.FormActivationState.Active:He.FormActivationState.InActive}),w=this.toArtifact(b);return{id:(s=t.id)!==null&&s!==void 0?s:w.id,name:(l=t.name)!==null&&l!==void 0?l:"New Form",entityLogicalName:(u=t.entityLogicalName)!==null&&u!==void 0?u:"",formType:(c=t.formType)!==null&&c!==void 0?c:"Main",status:(d=t.status)!==null&&d!==void 0?d:"Active",tabs:w.tabs,bag:w.bag}}assignMissingIds(t){return(0,Vk.assignMissingIds)(t)}validate(t){return Fq(t)}deserialize(t){(0,aN.installDomShim)();let r=Uk.ScriptUtilities.ParseXml(t.formxml),n=new kk.DeserializationService(Xt).deSerializeFormXml(r,new wt.Guid(t.formid),t.objecttypecode,He.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===He.FormActivationState.InActive?"Inactive":"Active"}};dt.FormAdapter=Gs;function Mt(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Gd(e){return e?`<labels><label description="${Mt(e)}" languagecode="${Xt}" /></labels>`:""}function Nq(e){let t=(e.columns.length>0?e.columns:[Oq()]).map(r=>Sq(r)).join("");return`<tab id="{${Mt(gn(e.id))}}" name="${Mt(e.name)}" expanded="${e.expanded}" visible="${e.visible}">${Gd(e.label)}<columns>${t}</columns></tab>`}function Sq(e){var t;let r=e.sections.map(n=>Dq(n)).join("");return`<column width="${Mt((t=e.width)!==null&&t!==void 0?t:"100%")}"><sections>${r}</sections></column>`}function Dq(e){let t=e.rows.map(r=>Eq(r)).join("");return`<section id="{${Mt(gn(e.id))}}" name="${Mt(e.name)}" showlabel="${e.showLabel}" visible="${e.visible}" columns="${Ud(e.columns)}">${Gd(e.label)}<rows>${t}</rows></section>`}function Eq(e){return`<row>${e.cells.map(t=>Iq(t)).join("")}</row>`}function Iq(e){let t=e.control,r=t?Gd(t.label):"",n=t?_q(t):"";return`<cell id="{${Mt(gn(e.id))}}" showlabel="${t?t.showLabel:!1}" visible="${e.visible}" colspan="${e.colspan}" rowspan="${e.rowspan}">${r}${n}</cell>`}function _q(e){let t=e.fieldName?` datafieldname="${Mt(e.fieldName)}"`:"",r=Pq(e.parameters);return`<control id="${Mt(e.id)}" classid="{${Mt(gn(e.classId))}}"${t} disabled="${e.isReadOnly}" isrequired="${e.isRequired}">${r}</control>`}function Pq(e){let t=Object.keys(e);return t.length===0?"":(t.forEach(n=>(0,kd.assertXmlName)(n,"Form control parameter name")),`<parameters>${t.map(n=>`<${n}>${Mt(e[n])}</${n}>`).join("")}</parameters>`)}function Oq(){return{width:"100%",sections:[],bag:{a:[],c:[]}}}var Tq=`<tab id="{${wt.Guid.NewGuid()}}" name="tab_general" expanded="true" visible="true"><labels><label description="General" languagecode="${Xt}" /></labels><columns><column width="100%"><sections><section id="{${wt.Guid.NewGuid()}}" name="section_general" showlabel="false" visible="true" columns="1"><labels><label description="General" languagecode="${Xt}" /></labels><rows></rows></section></sections></column></columns></tab>`;function Rq(){return{adapter:new Gs,api:$k.formApi}}dt.formRegistration=Rq;function Fq(e){let t=[];return(0,mn.childObjects)(e,"tabs","","tab",t).forEach(({node:n,index:i})=>{(0,mn.childObjects)(n,"columns",`/tabs/${i}`,"column",t).forEach(({node:o,index:s})=>{let l=`/tabs/${i}/columns/${s}`;(0,mn.childObjects)(o,"sections",l,"section",t).forEach(({node:c,index:d})=>{let f=`${l}/sections/${d}`;(0,mn.childObjects)(c,"rows",f,"row",t).forEach(({node:b,index:w})=>{let N=`${f}/rows/${w}`;(0,mn.childObjects)(b,"cells",N,"cell",t).forEach(({node:R,index:F})=>{let M=R.control;M!=null&&!(0,mn.isJsonObject)(M)&&t.push((0,mn.issue)(`${N}/cells/${F}/control`,"control-must-be-object-or-null",`a cell control must be a JSON object or null, got ${typeof M}`))})})})})}),t}dt.SUBGRID_CLASS_ID=_e.ControlClassId.SubgridControl;dt.NOTES_CLASS_ID=_e.ControlClassId.TimelineControl;dt.QUICK_VIEW_CLASS_ID=_e.ControlClassId.QuickViewControl;var xq={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)},Lq="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE";function fN(e){return e==="Picklist"||e==="State"||e==="Status"?Lq:e&&xq[e]||String(_e.ControlClassId.TextboxControl)}dt.classIdForAttributeType=fN;function iN(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}});var ja=m(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.projectElementBag=ve.serializeNode=ve.domEngine=ve.nodeLikeFromDom=ve.parseXmlRoot=ve.EMPTY_FORM_SENTINEL=ve.TEXT_SENTINEL=void 0;var Mq=pn(),Wa=be();ve.TEXT_SENTINEL="#text";ve.EMPTY_FORM_SENTINEL="#empty";var Hs=new WeakSet;function Uq(e,t){let r=e&&e.trim()!==""?e:t,i=new DOMParser().parseFromString(r,"text/xml").documentElement;if(!i)throw new Wa.InvalidArgumentError("XML source has no root element (empty or malformed input)");return kq(i),qq(i),Gq(i,r),i}ve.parseXmlRoot=Uq;var Bq=new Set([1,3]);function kq(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(!Bq.has(a.nodeType))throw new Wa.InvalidArgumentError(`Unsupported XML node type ${a.nodeType} (CDATA / comment / processing-instruction) is outside the hybrid projection's lossless grammar and cannot be round-tripped`);t.push(a)}}}function qq(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 Wa.InvalidArgumentError(`Unsupported document-level XML node (type ${o.nodeType}: declaration / comment / processing-instruction outside the root element) cannot be round-tripped`)}}function $q(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 Vq(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 gN(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 Gq(e,t){let r=$q(t),n=Vq(e),i=Math.min(r.length,n.length);for(let a=0;a<i;a+=1){if(r[a])continue;let o=n[a];gN(o)||Hs.add(o)}}function zd(e){let t=e.nodeType===3;return{getNodeName:()=>t?ve.TEXT_SENTINEL:e.tagName,getAllProperties:()=>{var r;if(t)return[{key:ve.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 Hs.has(e)&&!gN(e)&&i.push({key:ve.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(zd(a))}return r}}}ve.nodeLikeFromDom=zd;function zq(e){return{make:t=>t===ve.TEXT_SENTINEL?e.createTextNode(""):e.createElement(t),setProp:(t,r,n)=>{t.nodeType===3?t.nodeValue=n:r===ve.EMPTY_FORM_SENTINEL?Hs.add(t):t.setAttribute(r,n)},addChild:(t,r)=>{t.appendChild(r)}}}ve.domEngine=zq;function vN(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 js(r);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))throw js(r);t+=1;continue}if(r>=56320&&r<=57343)throw js(r)}}function js(e){let t=e.toString(16).toUpperCase().padStart(4,"0");return new Wa.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 Wq(e){return vN(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/\r/g,"
").replace(/\n/g,"
").replace(/\t/g,"	")}function jq(e){return vN(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function Hq(e){return bN(e,0)}ve.serializeNode=Hq;var hN=512;function bN(e,t){var r;if(t>hN)throw new Wa.InvalidArgumentError(`XML nesting exceeds the maximum supported depth of ${hN}`);if(e.nodeType===3)return jq((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+'="'+Wq(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 Hs.has(n)?i+"></"+n.tagName+">":i+" />";i+=">";for(let l of o)i+=bN(l,t+1);return i+"</"+n.tagName+">"}function Jq(e){let t=zd(e);return{a:t.getAllProperties().map(r=>[r.key,r.value]),c:t.getAllChildren().map((r,n)=>({i:n,node:(0,Mq.rawFromNode)(r)}))}}ve.projectElementBag=Jq});var Wd=m(gi=>{"use strict";Object.defineProperty(gi,"__esModule",{value:!0});gi.viewApi=gi.findDefaultViews=void 0;var Kt=Ve(),yr=ce(),Qq="savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault",Xq="savedqueryid,name,returnedtypecode,querytype,isdefault";async function Kq(e,t,r={}){var n,i,a;let o=new Set(((n=r.excludeViewIds)!==null&&n!==void 0?n:[]).filter(Boolean)),s=`returnedtypecode eq '${(0,yr.odataLiteral)(t)}' and querytype eq 0`,l=`/savedqueries${(0,yr.odataQuery)([["$select","savedqueryid,name,isdefault"],["$filter",s],["$top",50]])}`;return((a=(i=(0,Kt.ensureSuccess)(await e.get(l),e.apiUrl(l)).body)===null||i===void 0?void 0:i.value)!==null&&a!==void 0?a:[]).filter(d=>{var f;return d.savedqueryid&&!o.has(d.savedqueryid)&&(d.isdefault||/^(Active|Inactive)\b/i.test((f=d.name)!==null&&f!==void 0?f:""))}).map(d=>{var f;return{id:String(d.savedqueryid),name:String((f=d.name)!==null&&f!==void 0?f:"")}})}gi.findDefaultViews=Kq;async function Yq(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,yr.odataLiteral)(t)}')${(0,yr.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 yN(e,t,r){if(!r||!/<grid\b/.test(t)||/<grid[^>]*\bobject=/.test(t))return t;let n=await Yq(e,r);return n===void 0?t:t.replace(/<grid\b/,`<grid object="${n}"`)}gi.viewApi={async get(e,t){let n=`/savedqueries(${(0,yr.normalizeGuid)(t,"id")})${(0,yr.odataQuery)([["$select",Qq]])}`,i=(0,Kt.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,Kt.readEtag)(i)}},async list(e,t){var r;let n=`/savedqueries${(0,yr.odataQuery)([["$select",Xq],["$filter",t?.entityLogicalName?`returnedtypecode eq '${(0,yr.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`,a=(0,Kt.ensureSuccess)(await e.get(n),e.apiUrl(n)).body;return((r=a?.value)!==null&&r!==void 0?r:[]).map(s=>{var l,u;return{type:"view",id:(l=s.savedqueryid)!==null&&l!==void 0?l:"",name:(u=s.name)!==null&&u!==void 0?u:"",entityLogicalName:s.returnedtypecode,isDirty:!1}})},async create(e,t){let r=t,n="/savedqueries",i=await yN(e,r.layoutxml,r.returnedtypecode),a=(0,Kt.ensureSuccess)(await e.post(n,{name:r.name,description:r.description,fetchxml:r.fetchxml,layoutxml:i,returnedtypecode:r.returnedtypecode,querytype:r.querytype,isdefault:r.isdefault}),e.apiUrl(n));return{id:(0,Kt.requireCreatedId)(a,"savedqueryid","view"),etag:(0,Kt.readEtag)(a)}},async update(e,t,r,n){let i=r,a=(0,yr.normalizeGuid)(t,"id"),o=`/savedqueries(${a})`,s=n?{"If-Match":n}:void 0,l=await yN(e,i.layoutxml,i.returnedtypecode),u=(0,Kt.ensureSuccess)(await e.patch(o,{name:i.name,description:i.description,fetchxml:i.fetchxml,layoutxml:l},s?{headers:s}:void 0),e.apiUrl(o));return{id:a,etag:(0,Kt.readEtag)(u)}},delete(e,t){return(0,Kt.deleteRecord)(e,"savedqueries",t)}}});var TN=m(bi=>{"use strict";Object.defineProperty(bi,"__esModule",{value:!0});bi.viewRegistration=bi.ViewAdapter=void 0;var vi=$r(),jd=pn(),bn=ja(),Zq=Wd(),Hd=fn(),e3=Tt(),NN=100,Js=class{toArtifact(t){var r,n,i,a,o,s,l,u;(0,Hd.installDomShim)();let c=(r=t.fetchxml)!==null&&r!==void 0?r:"",d=(n=t.layoutxml)!==null&&n!==void 0?n:"",f=(0,bn.parseXmlRoot)(c,"<fetch/>"),h=(0,bn.parseXmlRoot)(d,"<grid/>");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:t3(f),queryType:(l=t.querytype)!==null&&l!==void 0?l:0,isDefault:(u=t.isdefault)!==null&&u!==void 0?u:!1,columns:DN(h,f),filters:_N(f),sort:IN(f),fetchBag:c?(0,bn.projectElementBag)(f):void 0,layoutBag:d?(0,bn.projectElementBag)(h):void 0}}fromArtifact(t){(0,Hd.installDomShim)();let{fetchxml:r,layoutxml:n}=CN(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,Hd.installDomShim)();let{fetchxml:s,layoutxml:l}=CN(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,e3.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:[]}}assignMissingIds(t){return t}validate(t){let r=[],n=t;(0,vi.childObjects)(n,"columns","","column",r),(0,vi.childObjects)(n,"sort","","sort",r);let i=n.filters;return i!=null&&((0,vi.isJsonObject)(i)?SN(i,"/filters",r):r.push((0,vi.issue)("/filters","filters-must-be-object",`filters must be a JSON object, got ${typeof i}`))),r}};bi.ViewAdapter=Js;function SN(e,t,r){(0,vi.childObjects)(e,"conditions",t,"condition",r),(0,vi.childObjects)(e,"groups",t,"filterGroup",r).forEach(({node:i,index:a})=>SN(i,`${t}/groups/${a}`,r))}function t3(e){var t;let r=e.getElementsByTagName("entity")[0];return(t=r?.getAttribute("name"))!==null&&t!==void 0?t:""}function DN(e,t){var r;let n=EN(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)?NN:c,order:o},f=n.get(u);f&&(d.relatedEntity=f),o+=1,a.push(d)}return a}function EN(e){var t;let r=new Map,n=e.getElementsByTagName("link-entity");for(let i=0;i<n.length;i+=1){let a=n[i],o=a.getAttribute("name");if(!o)continue;let s=a.getElementsByTagName("attribute");for(let l=0;l<s.length;l+=1){let u=s[l],c=(t=u.getAttribute("alias"))!==null&&t!==void 0?t:u.getAttribute("name");c&&r.set(c,o)}}return r}function IN(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"})}}return n}function _N(e){let t=e.getElementsByTagName("entity")[0],r={type:"and",conditions:[],groups:[]};if(!t)return r;let n=Nt(t,"filter").filter(i=>!PN(i)).map(ON);return n.length===0?r:n.length===1?n[0]:{type:"and",conditions:[],groups:n}}function PN(e){if(Nt(e,"filter").length>0)return!1;let t=Nt(e,"condition");return t.length===0?!1:t.some(r=>r.getAttribute("isquickfindfields")==="1"||Nt(r,"value").length>0)}function ON(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),i.push(c)}else l.tagName==="filter"&&a.push(ON(l))}return{type:n,conditions:i,groups:a}}function Nt(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 CN(e){let t=r3(e.columns);if(!AN(e.fetchBag)||!AN(e.layoutBag))return{fetchxml:p3({...e,columns:t}),layoutxml:f3({...e,columns:t},`${e.entityLogicalName}id`)};let r=new DOMParser().parseFromString("<root/>","text/xml"),n=wN(e.fetchBag,"fetch",r),i=wN(e.layoutBag,"grid",r),a=DN(i,n),o=!Jd(t,a),s=!Jd(e.sort,IN(n)),l=!Jd(e.filters,_N(n));return o&&(n3(r,n,t,a),s3(r,i,t)),s&&c3(r,n,e.sort),l&&d3(r,n,e.filters),{fetchxml:(0,bn.serializeNode)(n),layoutxml:(0,bn.serializeNode)(i)}}function r3(e){return(e??[]).map((t,r)=>{var n,i;return{name:String(t.name).toLowerCase(),width:(n=t.width)!==null&&n!==void 0?n:NN,order:(i=t.order)!==null&&i!==void 0?i:r,...t.relatedEntity?{relatedEntity:t.relatedEntity}:{}}})}function AN(e){return!!e&&(e.c.length>0||e.a.length>0)}function wN(e,t,r){let n={n:t,a:(0,jd.mergeAttrs)(e.a,[]),c:(0,jd.spliceChildren)(e.c,[])};return(0,jd.rebuildRaw)(n,(0,bn.domEngine)(r),null)}function n3(e,t,r,n){var i;let a=t.getElementsByTagName("entity")[0];if(!a)return;let o=new Set(r.map(u=>{var c;return`${(c=u.relatedEntity)!==null&&c!==void 0?c:""}:${u.name}`}));for(let u of n)o.has(`${(i=u.relatedEntity)!==null&&i!==void 0?i:""}:${u.name}`)||i3(a,u);let s=EN(t),l=new Set(Nt(a,"attribute").map(u=>u.getAttribute("name")).filter(u=>!!u));for(let u of[...r].sort((c,d)=>c.order-d.order))if(u.relatedEntity){if(s.get(u.name)===u.relatedEntity)continue;let c=a3(e,a,u.relatedEntity),d=e.createElement("attribute");d.setAttribute("name",u.name),c.appendChild(d),s.set(u.name,u.relatedEntity)}else{if(l.has(u.name))continue;let c=e.createElement("attribute");c.setAttribute("name",u.name),o3(a,c),l.add(u.name)}}function i3(e,t){var r;if(t.relatedEntity){for(let n of Nt(e,"link-entity"))if(n.getAttribute("name")===t.relatedEntity){for(let i of Nt(n,"attribute"))if(((r=i.getAttribute("alias"))!==null&&r!==void 0?r:i.getAttribute("name"))===t.name){n.removeChild(i);return}}return}for(let n of Nt(e,"attribute"))if(n.getAttribute("name")===t.name){e.removeChild(n);return}}function a3(e,t,r){for(let i of Nt(t,"link-entity"))if(i.getAttribute("name")===r)return i;let n=e.createElement("link-entity");return n.setAttribute("name",r),t.appendChild(n),n}function o3(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 s3(e,t,r){let n=t.getElementsByTagName("row")[0];if(!n)return;let i=[...r].sort((s,l)=>s.order-l.order),a=l3(n);if(u3(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 l3(e){return Nt(e,"cell").filter(t=>!!t.getAttribute("name")&&t.getAttribute("ishidden")!=="1")}function u3(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 c3(e,t,r){let n=t.getElementsByTagName("entity")[0];if(n){for(let i of Nt(n,"order"))n.removeChild(i);for(let i of r){let a=e.createElement("order");a.setAttribute("attribute",i.attribute),a.setAttribute("descending",String(i.descending)),n.appendChild(a)}}}function d3(e,t,r){let n=t.getElementsByTagName("entity")[0];if(n){for(let i of Nt(n,"filter"))PN(i)||n.removeChild(i);(r.conditions.length>0||r.groups.length>0)&&n.appendChild(Qd(e,r))}}function Jd(e,t){return JSON.stringify(e)===JSON.stringify(t)}function p3(e){let t=new DOMParser().parseFromString("<fetch/>","text/xml"),r=t.documentElement;r.setAttribute("version","1.0"),r.setAttribute("mapping","logical");let n=t.createElement("entity");n.setAttribute("name",e.entityLogicalName),r.appendChild(n);let i=new Map;for(let a of[...e.columns].sort((o,s)=>o.order-s.order)){let o=t.createElement("attribute");if(o.setAttribute("name",a.name),a.relatedEntity){let s=i.get(a.relatedEntity);s||(s=t.createElement("link-entity"),s.setAttribute("name",a.relatedEntity),n.appendChild(s),i.set(a.relatedEntity,s)),s.appendChild(o)}else n.appendChild(o)}for(let a of e.sort){let o=t.createElement("order");o.setAttribute("attribute",a.attribute),o.setAttribute("descending",String(a.descending)),n.appendChild(o)}return(e.filters.conditions.length>0||e.filters.groups.length>0)&&n.appendChild(Qd(t,e.filters)),new XMLSerializer().serializeToString(t)}function Qd(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.value!==void 0&&i.setAttribute("value",n.value),r.appendChild(i)}for(let n of t.groups)r.appendChild(Qd(e,n));return r}function f3(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 m3(){return{adapter:new Js,api:Zq.viewApi}}bi.viewRegistration=m3});function RN(e,t=0){return(ke[e[t+0]]+ke[e[t+1]]+ke[e[t+2]]+ke[e[t+3]]+"-"+ke[e[t+4]]+ke[e[t+5]]+"-"+ke[e[t+6]]+ke[e[t+7]]+"-"+ke[e[t+8]]+ke[e[t+9]]+"-"+ke[e[t+10]]+ke[e[t+11]]+ke[e[t+12]]+ke[e[t+13]]+ke[e[t+14]]+ke[e[t+15]]).toLowerCase()}var ke,FN=D(()=>{ke=[];for(let e=0;e<256;++e)ke.push((e+256).toString(16).slice(1))});function Xd(){return Qs>Xs.length-16&&((0,xN.randomFillSync)(Xs),Qs=0),Xs.slice(Qs,Qs+=16)}var xN,Xs,Qs,LN=D(()=>{xN=require("crypto"),Xs=new Uint8Array(256),Qs=Xs.length});var MN,Kd,UN=D(()=>{MN=require("crypto"),Kd={randomUUID:MN.randomUUID}});function h3(e,t,r){if(Kd.randomUUID&&!t&&!e)return Kd.randomUUID();e=e||{};let n=e.random??e.rng?.()??Xd();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 RN(n)}var gt,BN=D(()=>{UN();LN();FN();gt=h3});var Yd=D(()=>{BN()});var kN=m(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.WorkflowConditionOperator=St.WorkflowAttributeType=St.SystemStep=St.FieldRequiredLevelTypes=St.AttributeDateTimeBehavior=void 0;St.AttributeDateTimeBehavior={None:0,Dynamic:1,DateOnly:2,StaticTimeZoneInvariant:3,UserLocal:4};St.FieldRequiredLevelTypes={None:"0",Required:"1",Recommended:"2"};St.SystemStep={IdentifyContact:"IdentifyContact",IdentifyAccount:"IdentifyAccount",IdentifyCustomer:"IdentifyCustomer",IdentifyCase:"IdentifyCase",Solution:"Solution",Resolve:"Resolve"};St.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"};St.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"}});var ZN={};Bt(ZN,{deserializeWorkflowJson:()=>I3,serializeToWorkflowJson:()=>_3});function qN(e){return e.__class==="BinaryExpression:#Microsoft.Crm.Workflow.Expressions"}function g3(e){return e.__class==="ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel"}function Ha(){return{list:[]}}function jN(e){return{__class:"PrimaryEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:"primaryEntity",entityName:e}}function tp(e,t,r){return{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,entity:jN(t),attributeName:e}}function np(e,t){return{__class:"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",type:t,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function v3(){return np("true",z.WorkflowAttributeType.Boolean)}function $N(e,t){let r=z.WorkflowAttributeType.String,n=ep[e.operator]??z.WorkflowConditionOperator.Equal,i=tp(e.field,t,r),a;return e.operator==="ContainsData"||e.operator==="DoesNotContainData"?a=[]:e.valueType==="Field"&&e.valueField?a=[tp(e.valueField,t,r)]:a=[np(e.value??"",r)],{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:i,right:a}}function b3(e,t,r){if(e.length===0)return null;if(e.length===1)return $N(e[0],r);let n=t==="AND"?z.WorkflowConditionOperator.LogicalAnd:z.WorkflowConditionOperator.LogicalOr,[i,...a]=e.map(o=>$N(o,r));return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.String,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:i,right:a}}function rp(e){return e?e.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"?{valueType:"Field",valueField:e.attributeName}:e.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"?{valueType:"Value",value:e.primitiveValue!=null?String(e.primitiveValue):""}:{valueType:"Value",value:""}:{valueType:"Value",value:""}}function Zd(e){let t=WN[e.conditionOperatoroperator]??"Equals",r=e.left.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"?e.left.attributeName:"",i=t==="ContainsData"||t==="DoesNotContainData"?{valueType:"Value"}:rp(e.right[0]);return{id:gt(),field:r,fieldDisplayName:r,operator:t,...i}}function HN(e){if(!e||e.__class!=="BinaryExpression:#Microsoft.Crm.Workflow.Expressions")return{clauses:[],logic:"AND"};let t=e.conditionOperatoroperator;if(t===z.WorkflowConditionOperator.LogicalAnd||t===z.WorkflowConditionOperator.LogicalOr){let r=t===z.WorkflowConditionOperator.LogicalAnd?"AND":"OR";return{clauses:[...qN(e.left)?[Zd(e.left)]:[],...e.right.filter(qN).map(Zd)],logic:r}}return{clauses:[Zd(e)],logic:"AND"}}function VN(e,t,r,n){return e==="Field"&&r?tp(r,n,z.WorkflowAttributeType.String):np(t??"",z.WorkflowAttributeType.String)}function GN(e,t){return{propertyName:e,propertyValueExpr:t}}function yi(e){return`Step_${e.value++}`}function Dt(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 y3(e,t,r){return e&&!r.used.has(e)?(r.used.add(e),e):Dt(t,r)}function C3(e,t,r){return{__class:"ActionStep:#Microsoft.Crm.Workflow.ObjectModel",id:Dt("ActionStep",r),name:yi(t),description:"Action step",stepLabels:{list:[{labelId:gt(),languageCode:1033,description:e}]},steps:{list:[]},actionId:null,actionType:"4",processId:gt(),uniqueName:`id_${gt().replace(/-/g,"")}ActionStep`}}function A3(e,t,r,n){let i=jN(t),a=e.stepName??yi(r),o=e.stepLabels??Ha(),s={name:a,stepLabels:o,description:e.displayName},l=e.type;switch(l){case"SetFieldValue":return{...s,id:Dt("SetAttributeValueStep",n),__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:i,specification:GN(e.field,VN(e.valueType,e.value,e.valueField,t))};case"SetDefaultValue":return{...s,id:Dt("SetDefaultValueStep",n),__class:"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:i,specification:GN(e.field,VN(e.valueType,e.value,e.valueField,t))};case"LockUnlock":return{...s,id:Dt("SetDisplayModeStep",n),__class:"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:e.field,controlType:"attribute",isReadOnly:e.lock,entity:i};case"SetBusinessRequired":return{...s,id:Dt("SetFieldRequiredLevelStep",n),__class:"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:e.field,controlType:"attribute",requiredLevel:e.required?z.FieldRequiredLevelTypes.Required:z.FieldRequiredLevelTypes.None,entity:i};case"SetVisibility":return{...s,id:Dt("SetVisibilityStep",n),__class:"SetVisibilityStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:e.field,controlType:"attribute",isVisible:e.visible,entity:i};case"ShowErrorMessage":return{...s,id:Dt("SetMessageStep",n),__class:"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel",name:e.errorMessage||e.displayName,controlId:e.field,entity:i,level:e.messageLevel??"error",actionSteps:e.messageActionSteps??{list:[]}};case"Recommendation":{let u=e.messageText||e.recommendationTitle||e.displayName,c=e.stepLabels&&e.stepLabels.list.length>0?e.stepLabels:{list:[{labelId:gt(),languageCode:1033,description:u}]},d=e.recommendationActionSteps,f=d&&d.list.length>0?d:{list:[C3(u,r,n)]};return{...s,id:Dt("SetMessageStep",n),__class:"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel",stepLabels:c,description:e.recommendationTitle||e.displayName,controlId:e.field,entity:i,level:"RECOMMENDATION",actionSteps:f}}default:throw new Error(`Unsupported action type: ${l}`)}}function w3(e){switch(e.__class){case"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let t=rp(e.specification.propertyValueExpr);return{kind:"action",id:e.id,type:"SetFieldValue",displayName:e.description||e.name||"Set Field Value",stepName:e.name,stepLabels:e.stepLabels,field:e.specification.propertyName,...t}}case"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let t=rp(e.specification.propertyValueExpr);return{kind:"action",id:e.id,type:"SetDefaultValue",displayName:e.description||e.name||"Set Default Value",stepName:e.name,stepLabels:e.stepLabels,field:e.specification.propertyName,...t}}case"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:e.id,type:"LockUnlock",displayName:e.description||e.name||"Lock/Unlock",stepName:e.name,stepLabels:e.stepLabels,field:e.controlId,lock:e.isReadOnly};case"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:e.id,type:"SetBusinessRequired",displayName:e.description||e.name||"Set Business Required",stepName:e.name,stepLabels:e.stepLabels,field:e.controlId,required:e.requiredLevel!==z.FieldRequiredLevelTypes.None};case"SetVisibilityStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:e.id,type:"SetVisibility",displayName:e.description||e.name||"Set Visibility",stepName:e.name,stepLabels:e.stepLabels,field:e.controlId,visible:e.isVisible};case"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel":{let t=e.stepLabels?.list,r=t&&t.length>0?t[0].description??"":"";return(e.level??"").toUpperCase()==="RECOMMENDATION"?{kind:"action",id:e.id,type:"Recommendation",displayName:e.description||"Recommendation",stepName:e.name,stepLabels:e.stepLabels,field:e.controlId,recommendationTitle:e.description||"",messageText:r,recommendationActionSteps:e.actionSteps}:{kind:"action",id:e.id,type:"ShowErrorMessage",displayName:e.description||"Show Error Message",stepName:e.name,stepLabels:e.stepLabels,field:e.controlId,errorMessage:r||e.name||"",messageLevel:e.level??void 0,messageActionSteps:e.actionSteps}}case"ActionStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:e.id,type:"Recommendation",displayName:e.name||"Recommendation",stepName:e.name,stepLabels:e.stepLabels,field:e.actionControl?.controlId??"",recommendationTitle:e.name||"",messageText:e.description||""};default:return null}}function JN(e,t,r,n){let i=e.stepName??yi(r),a=Dt("ConditionStep",n),o=[],s=e,l=!0;for(;s;){let u=b3(s.clauses,s.logic,t),c=l?s.branchName??yi(r):yi(r),f={__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:l?y3(s.branchId,"ConditionBranchStep",n):Dt("ConditionBranchStep",n),name:c,description:s.displayName,stepLabels:Ha(),conditionExpression:u??void 0,steps:{list:s.trueBranch.map(b=>QN(b,t,r,n))}};o.push(f);let h=s.falseBranch;if(h.length===1&&h[0].kind==="condition"){s=h[0],l=!1;continue}h.length>0&&o.push(N3(h,t,r,n)),s=void 0}return{__class:"ConditionStep:#Microsoft.Crm.Workflow.ObjectModel",id:a,name:i,description:"",stepLabels:Ha(),containsElsebranch:o.length>1,steps:{list:o}}}function N3(e,t,r,n){return{__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:Dt("ConditionBranchStep",n),name:yi(r),description:null,stepLabels:Ha(),conditionExpression:v3(),steps:{list:e.map(i=>QN(i,t,r,n))}}}function QN(e,t,r,n){return e.kind==="condition"?JN(e,t,r,n):A3(e,t,r,n)}function XN(e){let t=(e.steps?.list??[]).filter(g3);return KN(t,e,!0)}function KN(e,t,r){let[n,...i]=e,{clauses:a,logic:o}=HN(n?.conditionExpression),s=YN(n?.steps?.list??[]),l=S3(i,t),u=n?.description||n?.name||t.description||t.name||"Condition";return{kind:"condition",id:(r?t.id:n?.id)??gt(),displayName:u,clauses:a,logic:o,trueBranch:s,falseBranch:l,isCollapsed:!1,stepName:r?t.name:void 0,branchId:r?n?.id:void 0,branchName:r?n?.name:void 0}}function S3(e,t){if(e.length===0)return[];let[r]=e,{clauses:n}=HN(r.conditionExpression);return n.length===0?YN(r.steps?.list??[]):[KN(e,t,!1)]}function YN(e){return e.map(t=>t.__class==="ConditionStep:#Microsoft.Crm.Workflow.ObjectModel"?XN(t):w3(t)).filter(t=>t!==null)}function D3(e){return e===zN.StateCode.Activated?"Active":"Draft"}function E3(e,t){let r=e.processtriggerscope,n=e.processtriggerformid;return r===1&&n?n:r===2?"Entity":t??"Entity"}function I3(e){let t=e,r=null,n;if(e.wfomJson)try{let i=JSON.parse(e.wfomJson);n={id:i.id==="WorkflowStep0"||!i.id?e.workflowid??gt():i.id,name:i.name,description:i.description,nextStepIndex:i.nextStepIndex,category:i.category==="0"||i.category===0?"2":i.category,businessProcessType:i.businessProcessType,mode:i.mode,title:i.title||e.name||"",primaryEntityName:i.primaryEntityName==="1"||!i.primaryEntityName?e.primaryentity??"":i.primaryEntityName,workflowEntityId:i.workflowEntityId==="00000000-0000-0000-0000-000000000000"||!i.workflowEntityId?e.workflowid??"":i.workflowEntityId,formId:i.formId,variables:i.variables,inputs:i.inputs};let o=(i.steps?.list??[]).find(s=>s.__class==="ConditionStep:#Microsoft.Crm.Workflow.ObjectModel");o&&(r=XN(o))}catch{}return{ruleId:e.workflowid??null,name:e.name??"",description:e.description??"",entityLogicalName:e.primaryentity??"",scope:E3(t,n?.formId),status:D3(e.statecode),rootCondition:r,wfomRoot:n}}function _3(e){let t=e.entityLogicalName,r=e.wfomRoot,n={value:r?Number(r.nextStepIndex):1},i={counts:{},used:new Set},a=e.scope!=="Entity"&&e.scope!=="AllForms"?e.scope:null,o=e.rootCondition?[JN(e.rootCondition,t,n,i)]:[],s={__class:"WorkflowStep:#Microsoft.Crm.Workflow.ObjectModel",id:r?.id??e.ruleId??gt(),name:r?.name??"Step_0",description:r!==void 0?r.description:e.description||null,stepLabels:Ha(),argumentsArray:[],primaryEntityName:r?.primaryEntityName??t,nextStepIndex:String(n.value),isCrmUIWorkflow:!0,category:r?.category??"2",businessProcessType:r?.businessProcessType??"0",mode:r?.mode??"0",title:r?.title??e.name,formId:a,workflowEntityId:r?.workflowEntityId??e.ruleId??"",variables:r?.variables??[],inputs:r?.inputs??[],steps:{list:o}};return JSON.stringify(s)}var zN,z,ep,WN,e2=D(()=>{"use strict";Yd();zN=ne(ha()),z=ne(kN());ep={Equals:z.WorkflowConditionOperator.Equal,DoesNotEqual:z.WorkflowConditionOperator.NotEqual,IsGreaterThan:z.WorkflowConditionOperator.GreaterThan,IsLessThan:z.WorkflowConditionOperator.LessThan,IsGreaterThanEqualTo:z.WorkflowConditionOperator.GreaterThanOrEqual,IsLessThanEqualTo:z.WorkflowConditionOperator.LessThanOrEqual,Contains:z.WorkflowConditionOperator.Contains,DoesNotContain:z.WorkflowConditionOperator.DoesNotContain,BeginsWith:z.WorkflowConditionOperator.BeginsWith,DoesNotBeginWith:z.WorkflowConditionOperator.DoesNotBeginWith,EndsWith:z.WorkflowConditionOperator.EndsWith,DoesNotEndWith:z.WorkflowConditionOperator.DoesNotEndWith,On:z.WorkflowConditionOperator.On,NotOn:z.WorkflowConditionOperator.NotOn,ContainsData:z.WorkflowConditionOperator.NotNull,DoesNotContainData:z.WorkflowConditionOperator.IsNull},WN={};for(let e of Object.keys(ep))WN[ep[e]]=e});function ip(e){return!P3.has(e)}function t2(e){return O3.has(e)?"string":e==="Money"?"money":e==="Integer"||e==="BigInt"?"integer":e==="Decimal"||e==="Double"?"decimal":T3.has(e)?"date":R3.has(e)?"boolean":"other"}function r2(e,t){let r=t2(e),n=t2(t);return r==="other"||n==="other"?e===t:r===n}var P3,O3,T3,R3,n2=D(()=>{"use strict";P3=new Set(["ContainsData","DoesNotContainData"]);O3=new Set(["String","Memo","EntityName"]),T3=new Set(["DateTime"]),R3=new Set(["Boolean"])});var p2={};Bt(p2,{addElseIfInTree:()=>M3,appendToBranch:()=>x3,buildBreadcrumb:()=>G3,collectUsedFields:()=>$3,createEmptyAction:()=>q3,createEmptyCondition:()=>u2,findNode:()=>o2,findParent:()=>Ci,getBranchPosition:()=>k3,hasAnyTriggerGeneratingAction:()=>sp,isTriggerGeneratingAction:()=>a2,moveBranchItemInTree:()=>B3,removeElseIfInTree:()=>U3,removeNodeFromTree:()=>s2,updateActionInTree:()=>ap,updateConditionInTree:()=>yn,validateTree:()=>V3});function a2(e){return F3.has(e.type)}function sp(e){if(!e)return!1;for(let t of[...e.trueBranch,...e.falseBranch])if(t.kind==="action"){if(a2(t))return!0}else if(sp(t))return!0;return!1}function o2(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=o2(r,t);if(n)return n}}return null}function Ci(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=Ci(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=Ci(n,t);if(i)return i}}return null}function s2(e,t){return{...e,trueBranch:i2(e.trueBranch,t),falseBranch:i2(e.falseBranch,t)}}function i2(e,t){return e.filter(r=>r.id!==t).map(r=>r.kind==="condition"?s2(r,t):r)}function yn(e,t,r){return e.id===t?r(e):{...e,trueBranch:e.trueBranch.map(n=>n.kind==="condition"?yn(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="condition"?yn(n,t,r):n)}}function ap(e,t,r){return{...e,trueBranch:e.trueBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?ap(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?ap(n,t,r):n)}}function x3(e,t,r,n){return yn(e,t,i=>({...i,trueBranch:r==="true"?[...i.trueBranch,n]:i.trueBranch,falseBranch:r==="false"?[...i.falseBranch,n]:i.falseBranch}))}function L3(e){return e.length===1&&e[0].kind==="condition"}function M3(e,t){return yn(e,t,r=>l2(r))}function l2(e){if(L3(e.falseBranch))return{...e,falseBranch:[l2(e.falseBranch[0])]};let t=u2();return t.falseBranch=e.falseBranch,{...e,falseBranch:[t]}}function U3(e,t){let r=Ci(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 yn(e,r.node.id,a=>({...a,falseBranch:i}))}function B3(e,t,r){let n=Ci(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 yn(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 k3(e,t){let r=Ci(e,t);if(!r)return null;let n=r.branch==="true"?r.node.trueBranch:r.node.falseBranch;return{isFirst:r.index===0,isLast:r.index===n.length-1}}function u2(){return{kind:"condition",id:gt(),displayName:"New Condition",clauses:[],logic:"AND",trueBranch:[],falseBranch:[],isCollapsed:!1}}function q3(e){let t={kind:"action",id:gt(),type:e,displayName:`New ${e}`};switch(e){case"Recommendation":return{...t,type:"Recommendation",field:"",recommendationTitle:"",messageText:""};case"LockUnlock":return{...t,type:"LockUnlock",field:"",lock:!0};case"ShowErrorMessage":return{...t,type:"ShowErrorMessage",field:"",errorMessage:""};case"SetFieldValue":return{...t,type:"SetFieldValue",field:"",valueType:"Value",value:""};case"SetDefaultValue":return{...t,type:"SetDefaultValue",field:"",valueType:"Value",value:""};case"SetBusinessRequired":return{...t,type:"SetBusinessRequired",field:"",required:!0};case"SetVisibility":return{...t,type:"SetVisibility",field:"",visible:!0};default:return{...t,type:"SetFieldValue",field:"",valueType:"Value",value:""}}}function $3(e){if(!e)return[];let t=[];return c2(e,t),[...new Set(t)]}function c2(e,t){e.clauses.forEach(r=>{r.field&&t.push(r.field)}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"?c2(r,t):"field"in r&&r.field&&t.push(r.field)})}function V3(e,t=[]){if(!e)return[{nodeId:"root",kind:"NO_CONDITION",message:"A business rule must include at least one condition."}];let r=[],n=new Map(t.map(i=>[i.logicalName,i]));return d2(e,r,n),sp(e)||r.push({nodeId:"root",kind:"NO_ACTION",message:"A business rule must include at least one action step."}),r}function d2(e,t,r){e.clauses.length===0&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Add at least one clause to this condition."}),e.clauses.forEach(n=>{if(!n.field)t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a field for this clause."});else if(ip(n.operator)&&n.valueType==="Value"&&!n.value)t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause."});else if(ip(n.operator)&&n.valueType==="Value"&&n.value){let i=r.get(n.field);i?.maxLength&&n.value.length>i.maxLength&&t.push({nodeId:e.id,kind:"CLAUSE_VALUE_TOO_LONG",message:`Value exceeds the field's maximum length of ${i.maxLength} characters.`})}}),[...e.trueBranch,...e.falseBranch].forEach(n=>{if(n.kind==="condition")d2(n,t,r);else if(!("field"in n)||!n.field)t.push({nodeId:n.id,kind:"EMPTY_ACTION_FIELD",message:`${n.type}: a target field is required.`});else if((n.type==="SetFieldValue"||n.type==="SetDefaultValue")&&n.valueType==="Value"&&n.value){let i=r.get(n.field);i?.maxLength&&n.value.length>i.maxLength&&t.push({nodeId:n.id,kind:"ACTION_VALUE_TOO_LONG",message:`${n.type}: value exceeds the field's maximum length of ${i.maxLength} characters.`})}else if((n.type==="SetFieldValue"||n.type==="SetDefaultValue")&&n.valueType==="Field"){if(!n.valueField)t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:`${n.type}: please select a field to copy from.`});else if(r.size>0){let i=r.get(n.field),a=r.get(n.valueField);i&&a&&!r2(i.attributeType,a.attributeType)&&t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:`${n.type}: the source field's type is not compatible with the target field.`})}}})}function G3(e,t){let r=[];return op(e,t,r),r}function op(e,t,r){if(e.id===t)return r.push({conditionId:e.id,label:e.displayName}),!0;for(let n of e.trueBranch)if(n.kind==="condition"){if(r.push({conditionId:e.id,label:e.displayName}),op(n,t,r))return!0;r.pop()}for(let n of e.falseBranch)if(n.kind==="condition"){if(r.push({conditionId:e.id,label:e.displayName}),op(n,t,r))return!0;r.pop()}return!1}var F3,f2=D(()=>{"use strict";Yd();n2();F3=new Set(["LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"])});var g2=m(Zs=>{"use strict";Object.defineProperty(Zs,"__esModule",{value:!0});Zs.businessRuleApi=void 0;var Ks=ha(),Yt=Ve(),Ai=ce(),m2="00000000-0000-0000-0000-000000000000",Ys={"Content-Type":"application/json",Accept:"application/json"},z3="workflowid,name,description,primaryentity,statecode,category,type",W3="category eq 2 and type eq 1";async function h2(e,t,r){if(r==="Draft")return;let n=(0,Ai.normalizeGuid)(t,"workflowid"),i=r==="Active",a={statecode:i?Ks.StateCode.Activated:Ks.StateCode.Draft,statuscode:i?Ks.StatusCode.Activated:Ks.StatusCode.Draft},o=`/workflows(${n})`;(0,Yt.ensureSuccess)(await e.patch(o,a,{headers:Ys}),e.apiUrl(o))}Zs.businessRuleApi={async get(e,t){let n=`/workflows(${(0,Ai.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveProcessWithWfomJson`,i=(0,Yt.ensureSuccess)(await e.post(n,{},{headers:Ys}),e.apiUrl(n));return{raw:i.body,etag:(0,Yt.readEtag)(i)}},async list(e,t){var r;let n=[W3];t?.entityLogicalName&&n.push(`primaryentity eq '${(0,Ai.odataLiteral)(t.entityLogicalName)}'`);let i=`/workflows${(0,Ai.odataQuery)([["$select",z3],["$filter",n.join(" and ")]])}`,o=(0,Yt.ensureSuccess)(await e.get(i),e.apiUrl(i)).body;return((r=o?.value)!==null&&r!==void 0?r:[]).map(l=>{var u,c;return{type:"businessRule",id:(u=l.workflowid)!==null&&u!==void 0?u:"",name:(c=l.name)!==null&&c!==void 0?c:"",entityLogicalName:l.primaryentity,isDirty:!1}})},async create(e,t){let r=t,n=`/workflows(${m2})/Microsoft.Dynamics.CRM.CreateProcessWithWfomJson`,i=(0,Yt.ensureSuccess)(await e.post(n,r,{headers:Ys}),e.apiUrl(n)),a=(0,Ai.normalizeGuid)(r.Entity.workflowid,"workflowid");try{await h2(e,a,r.status)}catch(o){try{await(0,Yt.deleteRecord)(e,"workflows",a)}catch{}throw o}return{id:a,etag:(0,Yt.readEtag)(i)}},async update(e,t,r,n){let i=r,a=(0,Ai.normalizeGuid)(t,"id"),o=`/workflows(${m2})/Microsoft.Dynamics.CRM.UpdateProcessWithWfomJson`,s={...Ys};n&&(s["If-Match"]=n);let l=(0,Yt.ensureSuccess)(await e.post(o,i,{headers:s}),e.apiUrl(o));return await h2(e,a,i.status),{id:a,etag:(0,Yt.readEtag)(l)}},delete(e,t){return(0,Yt.deleteRecord)(e,"workflows",t)}}});var C2=m(zr=>{"use strict";Object.defineProperty(zr,"__esModule",{value:!0});zr.BUSINESS_RULE_NULL_GUID=zr.businessRuleRegistration=zr.BusinessRuleAdapter=void 0;var v2=Nu(),lp=ha(),b2=(e2(),kt(ZN)),j3=(f2(),kt(p2)),Ja=$r(),H3=g2(),J3=Tt(),Q3="00000000-0000-0000-0000-000000000000";zr.BUSINESS_RULE_NULL_GUID=Q3;var X3=new Set(["Recommendation","LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]),K3=["ruleId","name","description","entityLogicalName","scope","status","rootCondition"],Y3=["kind","id","displayName","logic","clauses","trueBranch","falseBranch"],el=class{toArtifact(t){let r=this.residualBag(t,K3),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){var r;let n=t.rootCondition?this.conditionFromJson(t.rootCondition):null;return{...(r=t.bag)!==null&&r!==void 0?r:{},ruleId:t.id,name:t.name,description:t.description,entityLogicalName:t.entityLogicalName,scope:t.scope,status:t.status,rootCondition:n}}fromApiResponse(t){var r;let n=t??{},i={...(r=n.Entity)!==null&&r!==void 0?r:{},wfomJson:n.WfomJson},a=(0,b2.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,b2.serializeToWorkflowJson)(n),a=(r=n.ruleId)!==null&&r!==void 0?r:(0,v2.v4)();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:(0,j3.createEmptyCondition)()},u=this.toArtifact(l);return u.id||(u.id=(0,v2.v4)()),u}assignMissingIds(t){return(0,J3.assignMissingIds)(t)}validate(t){let r=[],n=t.rootCondition;return n==null?r:(0,Ja.isJsonObject)(n)?(y2(n,"/rootCondition",r),r):(r.push((0,Ja.issue)("/rootCondition","condition-must-be-object",`rootCondition must be a JSON object or null, got ${typeof n}`)),r)}residualBag(t,r){let n=new Set(r),i={};for(let a of Object.keys(t)){if(n.has(a))continue;let o=t[a];o!==void 0&&(i[a]=o)}return Object.keys(i).length>0?i:void 0}buildWorkflowEntity(t,r){let n=t.scope!=="Entity"&&t.scope!=="AllForms";return{"@odata.type":"#Microsoft.Dynamics.CRM.workflow",name:t.name,description:t.description,workflowid:r,ondemand:!1,subprocess:!1,triggeroncreate:!1,triggerondelete:!1,category:lp.WorkflowCategory.BusinessRule,type:lp.WorkflowTypeCode.Definition,mode:1,scope:lp.WorkflowScope.Organization,primaryentity:t.entityLogicalName,iscrmuiworkflow:!0,processtriggerscope:n?1:2,...n?{processtriggerformid:t.scope}:{}}}conditionToJson(t){let r=this.residualBag(t,Y3),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){return{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}:{}}}branchItemToJson(t){return t.kind==="condition"?this.conditionToJson(t):this.actionToJson(t)}actionToJson(t){return{...t}}conditionFromJson(t){var r;return{kind:"condition",isCollapsed:!1,...(r=t.bag)!==null&&r!==void 0?r:{},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{id:t.id,field:t.field,fieldDisplayName:(r=t.fieldDisplayName)!==null&&r!==void 0?r:t.field,operator:t.operator,valueType:t.valueType,...t.value!==void 0?{value:t.value}:{},...t.valueField!==void 0?{valueField:t.valueField}:{}}}branchItemFromJson(t){return this.isConditionJson(t)?this.conditionFromJson(t):this.actionFromJson(t)}actionFromJson(t){if(!X3.has(t.type))throw new Error(`Unsupported business-rule action type: ${t.type}`);return{...t,kind:"action",type:t.type}}isConditionJson(t){return Object.prototype.hasOwnProperty.call(t,"clauses")&&Object.prototype.hasOwnProperty.call(t,"logic")&&!Object.prototype.hasOwnProperty.call(t,"type")}};zr.BusinessRuleAdapter=el;function y2(e,t,r){(0,Ja.optionalEnum)(e,"logic",["AND","OR"],t,"condition-logic-invalid",r),(0,Ja.childObjects)(e,"clauses",t,"clause",r);for(let n of["trueBranch","falseBranch"])(0,Ja.childObjects)(e,n,t,"branchItem",r).forEach(({node:a,index:o})=>{("clauses"in a||"trueBranch"in a||"falseBranch"in a)&&y2(a,`${t}/${n}/${o}`,r)})}function Z3(){return{adapter:new el,api:H3.businessRuleApi}}zr.businessRuleRegistration=Z3});var I2=m(Ni=>{"use strict";Object.defineProperty(Ni,"__esModule",{value:!0});Ni.appRegistration=Ni.AppAdapter=void 0;var wi=$r(),Me=pn(),Xa=ja(),e$=_u(),up=fn(),t$=Tt(),fp="1033",nl="7.0.0.0",A2=`<SiteMap IntroducedVersion="${nl}"></SiteMap>`,r$="/_imgs/imagestrips/transparent_spacer.gif",n$="/_imgs/TableIconsFluentV9/document_one_page_sparkle.svg",i$=["Entity","Url","DefaultDashboard","Page","GenPageId"],Qa="sitemapId",w2="sitemapName",a$="sitemapNameUnique",il=class{toArtifact(t){let{bag:r,modeledEls:n}=tl(t,"Area");return{id:"",name:"",uniqueName:"",description:"",siteMap:{areas:n.map(i=>this.areaToJson(i)),bag:r},bag:(0,Me.emptyBag)()}}fromArtifact(t){(0,up.installDomShim)();let r=this.assignMissingIds(JSON.parse(JSON.stringify(t))),n=new DOMParser().parseFromString("<root/>","text/xml"),i=this.rootToRaw(r);return(0,Me.rebuildRaw)(i,(0,Xa.domEngine)(n),null)}fromApiResponse(t){var r,n,i,a,o,s,l,u,c,d;(0,up.installDomShim)();let f=t??{},h=(r=f.$sitemap)!==null&&r!==void 0?r:f,b=(0,Xa.parseXmlRoot)((n=h.sitemapxml)!==null&&n!==void 0?n:A2,A2),w=this.toArtifact(b);return w.id=(i=f.appmoduleid)!==null&&i!==void 0?i:"",w.name=(a=f.name)!==null&&a!==void 0?a:"",w.uniqueName=(o=f.uniquename)!==null&&o!==void 0?o:"",w.description=(s=f.description)!==null&&s!==void 0?s:"",w.bag={a:[[Qa,(u=(l=h.sitemapid)!==null&&l!==void 0?l:f._sitemapid_value)!==null&&u!==void 0?u:""],[w2,(c=h.sitemapname)!==null&&c!==void 0?c:""],[a$,(d=h.sitemapnameunique)!==null&&d!==void 0?d:""]],c:[]},w}toApiPayload(t){var r,n,i,a,o,s,l,u,c,d,f,h,b,w;(0,up.installDomShim)();let N=(0,Xa.serializeNode)(this.fromArtifact(t)),I=[],R=[];for(let M of(n=(r=t.siteMap)===null||r===void 0?void 0:r.areas)!==null&&n!==void 0?n:[])for(let W of(i=M.groups)!==null&&i!==void 0?i:[])for(let B of(a=W.subAreas)!==null&&a!==void 0?a:[])B.type==="Entity"&&B.entity?I.push(B.entity):B.type==="DashBoard"&&B.dashboardId&&R.push(B.dashboardId);let F=(o=t.bag)!==null&&o!==void 0?o:(0,Me.emptyBag)();return{sitemapId:(s=S2(F,Qa))!==null&&s!==void 0?s:"",sitemapxml:N,sitemapname:S2(F,w2)||t.name,appModuleId:t.id,appModuleName:t.name,appModuleDescription:t.description,appModuleUniqueName:t.uniqueName,...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},entities:I,components:{forms:(u=(l=t.components)===null||l===void 0?void 0:l.forms)!==null&&u!==void 0?u:[],views:(d=(c=t.components)===null||c===void 0?void 0:c.views)!==null&&d!==void 0?d:[],charts:(h=(f=t.components)===null||f===void 0?void 0:f.charts)!==null&&h!==void 0?h:[],dashboards:[...(w=(b=t.components)===null||b===void 0?void 0:b.dashboards)!==null&&w!==void 0?w:[],...R]}}}createDefault(t){var r,n,i,a;let o=t.siteMap&&t.siteMap.areas.length>0?t.siteMap.areas:[{id:"",title:"Area",groups:[{id:"",title:"Group",subAreas:[]}]}];return{id:(r=t.id)!==null&&r!==void 0?r:(0,t$.newId)(),name:(n=t.name)!==null&&n!==void 0?n:"New App",uniqueName:(i=t.uniqueName)!==null&&i!==void 0?i:"",description:(a=t.description)!==null&&a!==void 0?a:"",siteMap:{areas:o},...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},...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(pp):Array.isArray(r.areas)?r.areas.forEach(pp):Array.isArray(r.groups)?pp(r):Array.isArray(r.subAreas)?E2(r):"type"in r&&al(r,"subarea"),t}validate(t){let r=[],n=t.siteMap;return n==null?r:(0,wi.isJsonObject)(n)?((0,wi.childObjects)(n,"areas","/siteMap","area",r).forEach(({node:a,index:o})=>{let s=`/siteMap/areas/${o}`;(0,wi.childObjects)(a,"groups",s,"group",r).forEach(({node:u,index:c})=>{let d=`${s}/groups/${c}`;(0,wi.childObjects)(u,"subAreas",d,"subArea",r).forEach(({node:h,index:b})=>{(0,wi.optionalEnum)(h,"type",["Entity","URL","DashBoard","CustomPage","GenPage"],`${d}/subAreas/${b}`,"subarea-type-invalid",r)})})}),r):(r.push((0,wi.issue)("/siteMap","sitemap-must-be-object",`siteMap must be a JSON object, got ${typeof n}`)),r)}applyServerIdentity(t,r){let n=r[Qa];if(!n)return;t.bag||(t.bag=(0,Me.emptyBag)());let i=t.bag.a.find(a=>a[0]===Qa);i?i[1]=n:t.bag.a.push([Qa,n])}areaToJson(t){var r;let{bag:n,modeledEls:i}=tl(t,"Group"),a={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:cp(t),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}=tl(t,"SubArea");return{id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:cp(t),subAreas:i.map(a=>this.subAreaToJson(a)),bag:n}}subAreaToJson(t){var r;let{bag:n}=tl(t,null),i=o$(t),a={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",type:i,title:cp(t),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!==r$&&(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,Me.emptyBag)(),l=rl(o)?[["IntroducedVersion",nl]]:[],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,Me.mergeAttrs)(o.a,l),c:(0,Me.spliceChildren)(o.c,u)}}areaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,Me.emptyBag)(),i=rl(n),a=[];t.id&&a.push(["Id",t.id]),i&&a.push(["ShowGroups","true"],["ResourceId","SitemapDesigner.NewTitle"],["DescriptionResourceId","SitemapDesigner.NewTitle"],["IntroducedVersion",nl]),t.icon!==void 0&&a.push(["Icon",t.icon]),t.vectorIcon!==void 0&&a.push(["VectorIcon",t.vectorIcon]);let o=t.groups.map(l=>this.groupToRaw(l)),s=dp((0,Me.spliceChildren)(n.c,o),t.title,i);return{n:"Area",a:(0,Me.mergeAttrs)(n.a,a),c:s}}groupToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,Me.emptyBag)(),i=rl(n),a=[];t.id&&a.push(["Id",t.id]),i&&a.push(["ResourceId","SitemapDesigner.NewGroup"],["DescriptionResourceId","SitemapDesigner.NewGroup"],["ToolTipResourseId","SitemapDesigner.Unknown"],["IntroducedVersion",nl],["IsProfile","false"]);let o=t.subAreas.map(l=>this.subAreaToRaw(l)),s=dp((0,Me.spliceChildren)(n.c,o),t.title,i);return{n:"Group",a:(0,Me.mergeAttrs)(n.a,a),c:s}}subAreaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,Me.emptyBag)(),i=rl(n),a=l$(n.a,t.type),o=[];t.id&&o.push(["Id",t.id]),c$(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]),t.vectorIcon!==void 0?o.push(["VectorIcon",t.vectorIcon]):t.type==="GenPage"&&!s$(a,"VectorIcon")&&o.push(["VectorIcon",n$]);let s=dp((0,Me.spliceChildren)(n.c,[]),t.title,i);return{n:"SubArea",a:(0,Me.mergeAttrs)(a,o),c:s}}};Ni.AppAdapter=il;function tl(e,t){let r=(0,Xa.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,Me.rawFromNode)((0,Xa.nodeLikeFromDom)(l))}),o+=1)}return{bag:{a:r,c:n},modeledEls:i}}function N2(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 cp(e){var t;let r=N2(e,"Titles")[0];if(!r)return"";let i=N2(r,"Title").find(a=>a.getAttribute("LCID")===fp);return i&&(t=i.getAttribute("Title"))!==null&&t!==void 0?t:""}function o$(e){return e.getAttribute("GenPageId")?"GenPage":e.getAttribute("Entity")?"Entity":e.getAttribute("Page")?"CustomPage":e.getAttribute("DefaultDashboard")?"DashBoard":"URL"}function rl(e){return e.a.length===0&&e.c.length===0}function s$(e,t){return e.some(([r])=>r===t)}function S2(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function l$(e,t){let r=u$(t);return e.filter(([n])=>!i$.includes(n)||r.has(n)).map(n=>[n[0],n[1]])}function u$(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 c$(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 dp(e,t,r){if(!t)return e;let n=e.findIndex(i=>i.n==="Titles");if(n>=0){let i=e.slice();return i[n]=d$(e[n],t),i}return r?[p$(t),...e]:e}function d$(e,t){let r=!1,n=e.c.map(i=>!r&&i.n==="Title"&&f$(i,"LCID")===fp?(r=!0,{n:i.n,a:(0,Me.mergeAttrs)(i.a,[["Title",t]]),c:i.c}):i);return r||n.unshift(D2(t)),{n:e.n,a:e.a.map(i=>[i[0],i[1]]),c:n}}function p$(e){return{n:"Titles",a:[],c:[D2(e)]}}function D2(e){return{n:"Title",a:[["LCID",fp],["Title",e]],c:[]}}function f$(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function m$(e){let t="0123456789abcdef",r="";for(let n=0;n<e;n+=1)r+=t[Math.floor(Math.random()*t.length)];return r}function al(e,t){e&&(typeof e.id!="string"||e.id.length===0)&&(e.id=`${t}_${m$(8)}`)}function pp(e){var t;al(e,"area");for(let r of(t=e.groups)!==null&&t!==void 0?t:[])E2(r)}function E2(e){var t;al(e,"group");for(let r of(t=e.subAreas)!==null&&t!==void 0?t:[])al(r,"subarea")}function h$(){return{adapter:new il,api:e$.appApi}}Ni.appRegistration=h$});var _2={};Bt(_2,{ActionType:()=>hp,AppActionOrigin:()=>Np,AppActionVisibilityType:()=>wp,ButtonType:()=>vp,CannotUpdateAppActionColumns:()=>g$,Context:()=>yp,IconType:()=>gp,Location:()=>bp,OnClickEventType:()=>Ap,Scope:()=>Cp,VisibilityType:()=>mp});var mp,hp,gp,vp,bp,yp,Cp,Ap,wp,Np,g$,P2=D(()=>{"use strict";(function(e){e[e.NotSupported=0]="NotSupported",e[e.Show=1]="Show",e[e.ClassicRules=2]="ClassicRules",e[e.Expression=3]="Expression"})(mp||(mp={}));(function(e){e[e.NotSupported=0]="NotSupported",e[e.None=1]="None",e[e.JavaScript=2]="JavaScript",e[e.Expression=3]="Expression"})(hp||(hp={}));(function(e){e[e.NoIcon=0]="NoIcon",e[e.UseIcon=1]="UseIcon",e[e.UseWebResource=2]="UseWebResource"})(gp||(gp={}));(function(e){e[e.Standard=0]="Standard",e[e.Dropdown=1]="Dropdown",e[e.Split=2]="Split",e[e.Group=3]="Group"})(vp||(vp={}));(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"})(bp||(bp={}));(function(e){e[e.All=0]="All",e[e.Entity=1]="Entity"})(yp||(yp={}));(function(e){e[e.App=0]="App",e[e.Entity=1]="Entity",e[e.Global=2]="Global"})(Cp||(Cp={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.JavaScript=2]="JavaScript"})(Ap||(Ap={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.ClassicRules=2]="ClassicRules"})(wp||(wp={}));(function(e){e[e.Default=0]="Default",e[e.Migrated=1]="Migrated",e[e.MigratedClone=2]="MigratedClone"})(Np||(Np={}));g$=["appactionid","appmoduleid","context","contextvalue","location","name","type","uniquename","isdisabled","origin"]});var T2=m(ol=>{"use strict";Object.defineProperty(ol,"__esModule",{value:!0});ol.commandApi=void 0;var Cr=Ve(),Zt=ce(),v$="OnClickEventJavaScriptWebResourceId($select=name,webresourceid),IconWebResourceId($select=name,webresourceid)";async function Sp(e,t){let r=`/EntityDefinitions(LogicalName='${(0,Zt.odataLiteral)(t)}')${(0,Zt.odataQuery)([["$select","MetadataId"]])}`,i=(0,Cr.ensureSuccess)(await e.get(r),e.apiUrl(r)).body,a=i?.MetadataId;return a?(0,Zt.normalizeGuid)(a,"entityMetadataId"):""}ol.commandApi={async get(e,t){var r;let n=t,i=await Sp(e,n),a=i?`_contextentity_value eq ${i}`:`contextvalue eq '${(0,Zt.odataLiteral)(n)}'`,o=`/appactions${(0,Zt.odataQuery)([["$expand",v$],["$filter",a]])}`,s=(0,Cr.ensureSuccess)(await e.get(o),e.apiUrl(o)),l=s.body;return{raw:{entityLogicalName:n,entityMetadataId:i,appActions:(r=l?.value)!==null&&r!==void 0?r:[]},etag:(0,Cr.readEtag)(s)}},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 Sp(e,r.entityLogicalName);return O2(e,{...r,entityMetadataId:n},!1)},async update(e,t,r,n){return O2(e,r,!0)},async delete(e,t){var r,n;let i=await Sp(e,t),a=i?`_contextentity_value eq ${i}`:`contextvalue eq '${(0,Zt.odataLiteral)(t)}'`,o=`/appactions${(0,Zt.odataQuery)([["$select","appactionid"],["$filter",a]])}`,l=(n=(r=(0,Cr.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[];for(let u of l)u.appactionid&&await(0,Cr.deleteRecord)(e,"appactions",u.appactionid)}};async function O2(e,t,r){var n;let i=t.entityMetadataId?(0,Zt.normalizeGuid)(t.entityMetadataId,"entityMetadataId"):"",a=b$(t.rows);for(let o of a)if(r&&o.exists){let l=`/appactions(${(0,Zt.normalizeGuid)(o.appactionid,"id")})`,u=o.etag?{"If-Match":o.etag}:void 0;(0,Cr.ensureSuccess)(await e.patch(l,o.body,u?{headers:u}:void 0),e.apiUrl(l))}else{let s="/appactions",l={...o.body};i&&l["[email protected]"]===void 0&&(l["[email protected]"]=`/entities(${i})`);let u=(0,Cr.ensureSuccess)(await e.post(s,l),e.apiUrl(s));(0,Cr.readCreatedId)(u,"appactionid")}for(let o of[...(n=t.deletedRowIds)!==null&&n!==void 0?n:[]].reverse())await(0,Cr.deleteRecord)(e,"appactions",(0,Zt.normalizeGuid)(o,"id"));return{id:t.entityLogicalName,etag:null}}function b$(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 z2=m(Si=>{"use strict";Object.defineProperty(Si,"__esModule",{value:!0});Si.commandRegistration=Si.CommandAdapter=void 0;var Oe=(P2(),kt(_2)),Et=$r(),y$=T2(),F2=Tt(),Ka=ce(),Ep="$ClientSvg:",Ip=".svg",C$=2,x2="entityMetadataId",A$=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"]),sl=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 h of l){let b=typeof h._parentappactionid_value=="string"&&h._parentappactionid_value?h._parentappactionid_value:"",w=(i=c.get(b))!==null&&i!==void 0?i:[];w.push(h),c.set(b,w)}let d=new Map;for(let h of(a=c.get(""))!==null&&a!==void 0?a:[]){let b=E$(h.location),w=(o=d.get(b))!==null&&o!==void 0?o:[];w.push(h),d.set(b,w)}let f=[];for(let[h,b]of d)f.push({location:h,groups:N$(b,c,k2(h),u)});return{id:u,entityLogicalName:u,commandBars:D$(f),bag:{a:[[x2,(s=t.entityMetadataId)!==null&&s!==void 0?s:""]]}}}fromArtifact(t){return{entityLogicalName:t.entityLogicalName,entityMetadataId:Pp(t),appActions:Dp(t).map(r=>r.row)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t,r){let n=new Set(r?Dp(r).map(l=>l.appactionid):[]),i=Dp(t),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?U$(l.row):G2(l.row)}}),s=[...n].filter(l=>!a.has(l));return{entityLogicalName:t.entityLogicalName,entityMetadataId:Pp(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,F2.assignMissingIds)(t)}validate(t){let r=[];return(0,Et.childObjects)(t,"commandBars","","commandBar",r).forEach(({node:i,index:a})=>{let o=`/commandBars/${a}`;(0,Et.optionalEnum)(i,"location",["MainTab","ContextualTab","HomeTab"],o,"bar-location-invalid",r),(0,Et.childObjects)(i,"groups",o,"group",r).forEach(({node:l,index:u})=>{let c=`${o}/groups/${u}`;(0,Et.optionalGuidId)(l,"id",c,"group-id-invalid",r),L2((0,Et.childObjects)(l,"controls",c,"control",r),`${c}/controls`,r)})}),r}};Si.CommandAdapter=sl;function L2(e,t,r){e.forEach(({node:n,index:i})=>{let a=`${t}/${i}`;(0,Et.optionalGuidId)(n,"id",a,"control-id-invalid",r),(0,Et.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,Et.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,Et.isJsonObject)(n.action)?(0,Et.optionalEnum)(n.action,"type",["javascript"],`${a}/action`,"action-type-invalid",r):r.push((0,Et.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,Et.childObjects)(n,"children",a,"control",r);s.length>0&&L2(s,`${a}/children`,r)})}function M2(e){return{a:Object.entries(e)}}function w$(e){return Object.fromEntries(e.a)}function _p(e,t){if(e){for(let[r,n]of e.a)if(r===t)return n}}function Pp(e){let t=_p(e.bag,x2);return typeof t=="string"?t:""}function N$(e,t,r,n){var i,a;let o=[],s=[];for(let l of ul(e))l.type===Oe.ButtonType.Group?o.push({id:B2(l.name,n),title:typeof l.grouptitle=="string"?l.grouptitle:"",controls:ul((a=t.get((i=l.appactionid)!==null&&i!==void 0?i:""))!==null&&a!==void 0?a:[]).map(u=>ll(u,t,r,n)),bag:M2(l)}):s.push(ll(l,t,r,n));return s.length>0&&o.unshift({id:(0,F2.newId)(),title:"",controls:s}),o}function ll(e,t,r,n){var i,a,o,s;let l=B2(e.name,n),u={id:l,type:I$(e.type),label:typeof e.buttonlabeltext=="string"?e.buttonlabeltext:"",command:typeof e.appactionid=="string"?e.appactionid:l,bag:M2(e)},c=U2(e);c&&(u.icon=c);let d=S$(e);d&&(u.action=d),typeof e.hidden=="boolean"&&(u.hidden=e.hidden),typeof e.isdisabled=="boolean"&&(u.disabled=e.isdisabled),typeof e.location=="number"&&e.location!==r&&(u.location=e.location);let f=t.get((i=e.appactionid)!==null&&i!==void 0?i:"");if(f&&f.length>0){let h=[];for(let b of ul(f))if(b.type===Oe.ButtonType.Group){u.flyoutGroupId=(a=b.appactionid)!==null&&a!==void 0?a:void 0;for(let w of ul((s=t.get((o=b.appactionid)!==null&&o!==void 0?o:""))!==null&&s!==void 0?s:[]))h.push(ll(w,t,r,n))}else h.push(ll(b,t,r,n));u.children=h}return u}function U2(e){var t;if(!((t=e.IconWebResourceId)===null||t===void 0)&&t.name)return e.IconWebResourceId.name;if(e.fonticon)return e.fonticon.startsWith(Ep)?e.fonticon.slice(Ep.length)+Ip:e.fonticon}function S$(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 R2(e){return typeof e.sequence=="number"?e.sequence:typeof e.buttonsequencepriority=="number"?e.buttonsequencepriority:0}function ul(e){return[...e].sort((t,r)=>R2(t)-R2(r))}function D$(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 B2(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 E$(e){switch(e){case Oe.Location.Form:case Oe.Location.QuickForm:return"MainTab";case Oe.Location.HomePageGrid:case Oe.Location.Dashboard:return"HomeTab";default:return"ContextualTab"}}function k2(e){switch(e){case"MainTab":return Oe.Location.Form;case"HomeTab":return Oe.Location.HomePageGrid;default:return Oe.Location.SubGridStandard}}function I$(e){switch(e){case Oe.ButtonType.Dropdown:return"FlyoutAnchor";case Oe.ButtonType.Split:return"SplitButton";default:return"Button"}}function _$(e){switch(e){case"FlyoutAnchor":return Oe.ButtonType.Dropdown;case"SplitButton":return Oe.ButtonType.Split;default:return Oe.ButtonType.Standard}}function P$(e){var t;return e.bag&&e.bag.a.length>0?!0:((t=e.title)!==null&&t!==void 0?t:"").length>0}function Dp(e){var t,r,n;let i=[],a=Pp(e);for(let o of(t=e.commandBars)!==null&&t!==void 0?t:[]){let s=k2(o.location);for(let l of(r=o.groups)!==null&&r!==void 0?r:[]){let u;if(P$(l)){let c=T$(l,s,void 0,e,a);i.push(c),u=c.appactionid}for(let c of(n=l.controls)!==null&&n!==void 0?n:[])q2(c,s,u,e,a,i)}}return i}function q2(e,t,r,n,i,a){var o;let s=O$(e,t,r,n,i);a.push(s);let l=(o=e.children)!==null&&o!==void 0?o:[];if(l.length===0)return;let u=e.flyoutGroupId||M$(s.appactionid);a.push(R$(u,t,s.appactionid,n,i));for(let c of l)q2(c,t,u,n,i,a)}function O$(e,t,r,n,i){let a=$2(e,t,r,n,i),o=a.row,s=U2(o);return e.location!==void 0&&(o.location=e.location),o.type=_$(e.type),o.buttonlabeltext=e.label,F$(o,e.icon,s),x$(o,e.action),e.hidden!==void 0&&(o.hidden=e.hidden),e.disabled!==void 0&&(o.isdisabled=e.disabled),{...a,row:o}}function T$(e,t,r,n,i){let a=$2(e,t,r,n,i);return a.row.type=Oe.ButtonType.Group,a.row.grouptitle=e.title,a}function R$(e,t,r,n,i){let a=V2(e,t,n,i);return a["[email protected]"]=`/appactions(${(0,Ka.normalizeGuid)(r,"Command flyout group id")})`,a.type=Oe.ButtonType.Group,a.grouptitle===void 0&&(a.grouptitle=""),a.isgrouptitlehidden=!0,{appactionid:e,exists:!1,etag:null,row:a}}function $2(e,t,r,n,i){let a,o,s,l;if(e.bag&&e.bag.a.length>0){a=w$(e.bag),o=!0;let u=_p(e.bag,"@odata.etag");s=typeof u=="string"?u:null;let c=_p(e.bag,"appactionid");l=typeof c=="string"&&c?c:e.id}else l=e.id,a=V2(l,t,n,i),o=!1,s=null;return r&&(a["[email protected]"]=`/appactions(${(0,Ka.normalizeGuid)(r,"Command parent appaction id")})`),{appactionid:l,exists:o,etag:s,row:a}}function V2(e,t,r,n){let i={appactionid:e,name:`${e}!${e.replace(/-/g,"").slice(0,32)}`,uniquename:"",location:t,context:Oe.Context.Entity,contextvalue:r.entityLogicalName,scope:Oe.Scope.Entity};return n&&(i["[email protected]"]=`/entities(${(0,Ka.normalizeGuid)(n,"Command context entity metadata id")})`),i}function F$(e,t,r){if(t===r){let n=e._iconwebresourceid_value;typeof n=="string"&&n&&!e.fonticon&&(e["[email protected]"]=`/webresourceset(${(0,Ka.normalizeGuid)(n,"Command icon web resource id")})`);return}if(t===void 0){e.fonticon="",e.IconWebResourceId=null;return}e.fonticon=t.toLowerCase().endsWith(Ip)?Ep+t.slice(0,t.length-Ip.length):t,e.IconWebResourceId=null}function x$(e,t){if(!(!t||t.type!=="javascript")){if(e.onclickeventtype=C$,t.webResourceId){let r=(0,Ka.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 L$(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 M$(e){let t="";for(let r=0;r<4;r+=1)t+=L$(`${r}:flyout-group:${e}`).toString(16).padStart(8,"0");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20,32)}`}function G2(e){let t={...e};for(let r of A$)delete t[r];return t}function U$(e){let t=G2(e);for(let r of Oe.CannotUpdateAppActionColumns)delete t[r];return t}function B$(){return{adapter:new sl,api:y$.commandApi}}Si.commandRegistration=B$});var W2=m(cl=>{"use strict";Object.defineProperty(cl,"__esModule",{value:!0});cl.chartApi=void 0;var Ar=Ve(),Ya=ce(),k$="savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault",q$="savedqueryvisualizationid,name,primaryentitytypecode,charttype,isdefault";cl.chartApi={async get(e,t){let n=`/savedqueryvisualizations(${(0,Ya.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Ya.odataQuery)([["$select",k$]]),i=(0,Ar.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,Ar.readEtag)(i)}},async list(e,t){var r;let n=`/savedqueryvisualizations${(0,Ya.odataQuery)([["$select",q$],["$filter",t?.entityLogicalName?`primaryentitytypecode eq '${(0,Ya.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`,a=(0,Ar.ensureSuccess)(await e.get(n),e.apiUrl(n)).body;return((r=a?.value)!==null&&r!==void 0?r:[]).map(s=>{var l,u;return{type:"chart",id:(l=s.savedqueryvisualizationid)!==null&&l!==void 0?l:"",name:(u=s.name)!==null&&u!==void 0?u:"",entityLogicalName:s.primaryentitytypecode,isDirty:!1}})},async create(e,t){let r=t,n="/savedqueryvisualizations",i=(0,Ar.ensureSuccess)(await e.post(n,{name:r.name,description:r.description,datadescription:r.datadescription,presentationdescription:r.presentationdescription,primaryentitytypecode:r.primaryentitytypecode,charttype:r.charttype,isdefault:r.isdefault}),e.apiUrl(n));return{id:(0,Ar.requireCreatedId)(i,"savedqueryvisualizationid","chart"),etag:(0,Ar.readEtag)(i)}},async update(e,t,r,n){let i=r,a=(0,Ya.normalizeGuid)(t,"id"),o=`/savedqueryvisualizations(${a})`,s=n?{"If-Match":n}:void 0,l=(0,Ar.ensureSuccess)(await e.patch(o,{name:i.name,description:i.description,datadescription:i.datadescription,presentationdescription:i.presentationdescription},s?{headers:s}:void 0),e.apiUrl(o));return{id:a,etag:(0,Ar.readEtag)(l)}},delete(e,t){return(0,Ar.deleteRecord)(e,"savedqueryvisualizations",t)}}});var oS=m(Di=>{"use strict";Object.defineProperty(Di,"__esModule",{value:!0});Di.chartRegistration=Di.ChartAdapter=void 0;var Op=pn(),j2=$r(),wr=ja(),$$=W2(),Tp=fn(),V$=Tt(),G$=["Column","StackedColumn","StackedColumn100","Bar","StackedBar","StackedBar100","Area","StackedArea","StackedArea100","Line","Pie","Doughnut","Funnel","Tag"],z$=new Map(G$.map(e=>[e.toLowerCase(),e]));function X2(e){var t;return e&&(t=z$.get(e.toLowerCase()))!==null&&t!==void 0?t:"Column"}function W$(){return'<Chart Palette="BrightPastel"><Series><Series ChartType="Column" ChartArea="Default" /></Series><ChartAreas><ChartArea Name="Default" /></ChartAreas><Legends><Legend Name="Default" /></Legends></Chart>'}function j$(e){var t,r;let n=e.entityLogicalName,i=e.series.map((u,c)=>({alias:`agg_${c}`,series:u})),a=e.categories.map((u,c)=>({alias:`grp_${c}`,category:u})),o=i.map(u=>`<attribute alias="${u.alias}" name="${Za(u.series.attribute)}" aggregate="${Za(u.series.aggregate)}" />`).join("")+a.map(u=>`<attribute alias="${u.alias}" name="${Za(u.category.attribute)}" groupby="true"${u.category.dateGrouping?` dategrouping="${Za(u.category.dateGrouping)}"`:""} />`).join(""),s=i.map(u=>`<measure alias="${u.alias}" />`).join(""),l=(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="${Za(n)}">${o}</entity></fetch></fetchcollection><categorycollection><category alias="${l}"><measurecollection>${s}</measurecollection></category></categorycollection></datadefinition>`}var dl=class{toArtifact(t){var r,n,i,a,o,s,l;(0,Tp.installDomShim)();let u=(r=t.datadescription)!==null&&r!==void 0?r:"",c=(n=t.presentationdescription)!==null&&n!==void 0?n:"",d=(0,wr.parseXmlRoot)(u,"<datadefinition/>"),f=(0,wr.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:K2(f),isDefault:(l=t.isdefault)!==null&&l!==void 0?l:!1,series:eS(d),categories:tS(d),presentation:Y2(f),dataBag:u?(0,wr.projectElementBag)(d):void 0,presentationBag:c?(0,wr.projectElementBag)(f):void 0,rowBag:H$(t.charttype,t.type)}}fromArtifact(t){(0,Tp.installDomShim)();let{datadescription:r,presentationdescription:n}=J$(t);return{savedqueryvisualizationid:t.id,name:t.name,description:t.description,primaryentitytypecode:t.entityLogicalName,datadescription:r,presentationdescription:n,charttype:H2(t.rowBag,"charttype"),type:H2(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,Tp.installDomShim)();let u=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,V$.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,j2.childObjects)(n,"series","","series",r),(0,j2.childObjects)(n,"categories","","category",r),r}};Di.ChartAdapter=dl;function H$(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 H2(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 K2(e){let t=e.getElementsByTagName("Series");for(let r=0;r<t.length;r+=1)if(t[r].getAttribute("ChartType"))return X2(t[r].getAttribute("ChartType"));return"Column"}function Y2(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 pl(e){return e.getElementsByTagName("fetch")[0]}function Z2(e){var t;let r=new Map;if(!e)return r;let n=e.getElementsByTagName("link-entity");for(let i=0;i<n.length;i+=1){let a=n[i],o=a.getAttribute("name");if(!o)continue;let s=a.getElementsByTagName("attribute");for(let l=0;l<s.length;l+=1){let u=s[l],c=(t=u.getAttribute("alias"))!==null&&t!==void 0?t:u.getAttribute("name");c&&r.set(c,o)}}return r}function eS(e){let t=pl(e);if(!t)return[];let r=Z2(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=X2(c));let d=o.getAttribute("alias");d&&(u.alias=d);let f=d??l,h=r.get(f);h&&(u.relatedEntity=h),i.push(u)}return i}function tS(e){var t;let r=pl(e);if(!r)return[];let n=Z2(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 f=d??l,h=n.get(f);h&&(u.relatedEntity=h),a.push(u)}return a}function J$(e){if(!J2(e.dataBag)||!J2(e.presentationBag))return{datadescription:j$(e),presentationdescription:m4(e)};let t=new DOMParser().parseFromString("<root/>","text/xml"),r=Q2(e.dataBag,"datadefinition",t),n=Q2(e.presentationBag,"Chart",t);return Rp(e.series,eS(r))||(X$(t,r,e.series),Q$(t,n,e.series.length,e.chartType)),Rp(e.categories,tS(r))||K$(t,r,e.categories),e.chartType!==K2(n)&&iS(n,e.chartType),Rp(e.presentation,Y2(n))||aS(n,e.presentation),{datadescription:(0,wr.serializeNode)(r),presentationdescription:(0,wr.serializeNode)(n)}}function J2(e){return!!e&&(e.c.length>0||e.a.length>0)}function Q$(e,t,r,n){let i,a=t.childNodes;for(let l=0;l<a.length;l+=1)if(a[l].nodeType===1&&a[l].tagName==="Series"){i=a[l];break}i||(i=e.createElement("Series"),t.insertBefore(i,t.firstChild));let o=[],s=i.childNodes;for(let l=0;l<s.length;l+=1)s[l].nodeType===1&&s[l].tagName==="Series"&&o.push(s[l]);for(let l=o.length;l<r;l+=1){let u=e.createElement("Series");u.setAttribute("ChartType",n),i.appendChild(u)}for(let l=r;l<o.length;l+=1)i.removeChild(o[l])}function Q2(e,t,r){let n={n:t,a:(0,Op.mergeAttrs)(e.a,[]),c:(0,Op.spliceChildren)(e.c,[])};return(0,Op.rebuildRaw)(n,(0,wr.domEngine)(r),null)}function X$(e,t,r){let n=pl(t),i=n?.getElementsByTagName("entity")[0];!n||!i||rS(e,t,i,i4(n),r,o4,{aliasPrefix:"aggregate_column",addRef:e4,removeRef:n4})}function K$(e,t,r){let n=pl(t),i=n?.getElementsByTagName("entity")[0];!n||!i||rS(e,t,i,a4(n),r,s4,{aliasPrefix:"groupby_column",addRef:t4,removeRef:r4})}function rS(e,t,r,n,i,a,o){let s=new Map;for(let f of n){let h=f.getAttribute("alias");h&&s.set(h,f)}let l=new Set,u=[];for(let f of i){let h=f.alias?s.get(f.alias):void 0;h&&!l.has(h)?(a(h,f),l.add(h)):u.push(f)}let c=n.filter(f=>!l.has(f)),d=0;for(let f of u)if(d<c.length){let h=c[d];a(h,f),l.add(h),d+=1}else{let h=e.createElement("attribute"),b=f.alias||Z$(t,o.aliasPrefix);h.setAttribute("alias",b),a(h,f),l4(e,r,h,f.relatedEntity),o.addRef(e,t,b)}for(let f of n)if(!l.has(f)){let h=f.getAttribute("alias");h&&o.removeRef(t,h),c4(f)}}function Y$(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 Z$(e,t){let r=Y$(e);if(!r.has(t))return t;for(let n=2;;n+=1){let i=`${t}_${n}`;if(!r.has(i))return i}}function nS(e,t){let r=t.getElementsByTagName("categorycollection")[0];if(r)return r;let n=e.createElement("categorycollection");return t.appendChild(n),n}function e4(e,t,r){let n=nS(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 t4(e,t,r){let n=nS(e,t),i=e.createElement("category");i.setAttribute("alias",r),n.appendChild(i)}function r4(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 n4(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"&&!p4(o)&&((r=o.parentNode)===null||r===void 0||r.removeChild(o))}}function i4(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 a4(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 o4(e,t){e.setAttribute("name",t.attribute),e.setAttribute("aggregate",t.aggregate),t.seriesType&&e.setAttribute("charttype",t.seriesType)}function s4(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 l4(e,t,r,n){n?u4(e,t,n).appendChild(r):t.appendChild(r)}function u4(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 c4(e){let t=e.parentNode;if(t&&(t.removeChild(e),t.tagName==="link-entity"&&!d4(t))){let r=t.parentNode;r&&r.removeChild(t)}}function d4(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 p4(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1)if(t[r].nodeType===1)return!0;return!1}function iS(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(!f4(r[i])){r[i].setAttribute("ChartType",t);return}}}function f4(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 aS(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 m4(e){let t=(0,wr.parseXmlRoot)(W$(),"<Chart/>");return iS(t,e.chartType),aS(t,e.presentation),(0,wr.serializeNode)(t)}function Rp(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Za(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function h4(){return{adapter:new dl,api:$$.chartApi}}Di.chartRegistration=h4});var sS=m(fl=>{"use strict";Object.defineProperty(fl,"__esModule",{value:!0});fl.dashboardApi=void 0;var Nr=Ve(),eo=ce(),g4="formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber",v4="formid,name,type,objecttypecode",b4=0,y4=10;fl.dashboardApi={async get(e,t){let n=`/systemforms(${(0,eo.normalizeGuid)(t,"id")})${(0,eo.odataQuery)([["$select",g4]])}`,i=(0,Nr.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,Nr.readEtag)(i)}},async list(e,t){var r;let n=[`(type eq ${b4} or type eq ${y4})`];t?.entityLogicalName&&n.push(`objecttypecode eq '${(0,eo.odataLiteral)(t.entityLogicalName)}'`);let i=`/systemforms${(0,eo.odataQuery)([["$select",v4],["$filter",n.join(" and ")]])}`,o=(0,Nr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body;return((r=o?.value)!==null&&r!==void 0?r:[]).map(l=>{var u,c;return{type:"dashboard",id:(u=l.formid)!==null&&u!==void 0?u:"",name:(c=l.name)!==null&&c!==void 0?c:"",entityLogicalName:l.objecttypecode,isDirty:!1}})},async create(e,t){let r=t,n="/systemforms",i={name:r.name,description:r.description,formxml:r.formxml,istabletenabled:r.istabletenabled,type:r.type};r.objecttypecode&&(i.objecttypecode=r.objecttypecode);let a=(0,Nr.ensureSuccess)(await e.post(n,i),e.apiUrl(n));return{id:(0,Nr.requireCreatedId)(a,"formid","dashboard"),etag:(0,Nr.readEtag)(a)}},async update(e,t,r,n){let i=r,a=(0,eo.normalizeGuid)(t,"id"),o=`/systemforms(${a})`,s=n?{"If-Match":n}:void 0,l=(0,Nr.ensureSuccess)(await e.patch(o,{name:i.name,description:i.description,formxml:i.formxml,istabletenabled:i.istabletenabled},s?{headers:s}:void 0),e.apiUrl(o));return{id:a,etag:(0,Nr.readEtag)(l)}},delete(e,t){return(0,Nr.deleteRecord)(e,"systemforms",t)}}});var bS=m(er=>{"use strict";Object.defineProperty(er,"__esModule",{value:!0});er.dashboardRegistration=er.TILE_CLASS_ID=er.DashboardAdapter=void 0;var ro=pn(),It=ja(),to=$r(),C4=sS(),Fp=fn(),Cn=Tt(),fS=ce(),hl=1033,lS="0",xp="10",A4=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"]]),w4="{3FF9A528-DD50-4ACA-8F10-2E5ED73513AD}",gl=class{toArtifact(t){var r,n,i,a;(0,Fp.installDomShim)();let o=(r=t.formxml)!==null&&r!==void 0?r:"",s=(0,It.parseXmlRoot)(o,"<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:N4(t.type),entityLogicalName:t.objecttypecode?t.objecttypecode:null,enabledForMobile:!!t.istabletenabled,layoutType:S4(s),components:uS(s),bag:(0,It.projectElementBag)(s)}}fromArtifact(t){var r;return(0,Fp.installDomShim)(),{formid:t.id,name:t.name,description:t.description,type:t.dashboardType==="Interactive"?xp:lS,objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",istabletenabled:t.enabledForMobile,formxml:cS(t)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){return{name:t.name,description:t.description,formxml:cS(t),istabletenabled:t.enabledForMobile,type:t.dashboardType==="Interactive"?xp:lS,objecttypecode:t.entityLogicalName}}createDefault(t){var r,n,i,a,o,s,l,u;(0,Fp.installDomShim)();let c=(0,It.parseXmlRoot)(U4(),"<form/>");return{id:(r=t.id)!==null&&r!==void 0?r:(0,Cn.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:uS(c),bag:(0,It.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,Cn.newId)())}return t}validate(t){let r=[],n=(0,to.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,to.isJsonObject)(u)&&r.push((0,to.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,to.isJsonObject)(a.position)){let l=no(a.position);i.has(l)?r.push((0,to.issue)(`${s}/position`,"component-position-collision",`two components occupy the same dashboard position (${l}); move one to a free cell`)):i.add(l)}}),r}};er.DashboardAdapter=gl;function N4(e){return String(e??"")===xp?"Interactive":"Standard"}function S4(e){var t;let r=(t=e?.getAttribute("formLayout"))!==null&&t!==void 0?t:e?.getAttribute("layoutType"),n=parseInt(r??"",10);return Number.isNaN(n)?0:n}function V(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 uS(e){let t=[];return V(e,"tabs").flatMap(n=>V(n,"tab")).forEach((n,i)=>{V(n,"columns").flatMap(o=>V(o,"column")).forEach((o,s)=>{V(o,"sections").flatMap(u=>V(u,"section")).forEach((u,c)=>{D4(u,{tabIndex:i,columnIndex:s,sectionIndex:c},t)})})}),t}function D4(e,t,r){V(e,"rows").flatMap(i=>V(i,"row")).forEach((i,a)=>{V(i,"cell").forEach((o,s)=>{let l=E4(o,{...t,rowIndex:a,cellIndex:s});l&&r.push(l)})})}function E4(e,t){var r,n,i;let a=gS((r=e.getAttribute("id"))!==null&&r!==void 0?r:"");if(a.toLowerCase().startsWith("spacer"))return null;let o=V(e,"control")[0];if(!o)return null;let s=(n=o.getAttribute("classid"))!==null&&n!==void 0?n:"",l=P4(o),u=O4(s,l,o),c=I4(o);return{id:(i=o.getAttribute("id"))!==null&&i!==void 0?i:a,type:u,name:hS(e),classId:s,position:t,colspan:Lp(e,"colspan",1),rowspan:Lp(e,"rowspan",1),parameters:l,bag:(0,It.projectElementBag)(e),...c?{icProperties:c}:{}}}function mS(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 I4(e){let t=mS(e);return t?(0,It.serializeNode)(t):void 0}function _4(e,t,r){let n=mS(t);if(!r){n&&t.removeChild(n);return}let i=new DOMParser().parseFromString(r,"text/xml").documentElement,a=(0,ro.rebuildRaw)((0,ro.rawFromNode)((0,It.nodeLikeFromDom)(i)),(0,It.domEngine)(e),null);n&&(0,It.serializeNode)(n)===(0,It.serializeNode)(a)||(n?t.replaceChild(a,n):t.appendChild(a))}function hS(e){var t,r;let n=V(e,"labels")[0];if(!n)return"";let i=V(n,"label"),a=(t=i.find(o=>o.getAttribute("languagecode")===String(hl)))!==null&&t!==void 0?t:i[0];return(r=a?.getAttribute("description"))!==null&&r!==void 0?r:""}function P4(e){var t;let r={},n=V(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 O4(e,t,r){var n;let i=A4.get(e.toUpperCase());return i?i==="chart"?t.ChartGridMode==="Chart"?"chart":"list":i==="assistant"&&((n=r.getAttribute("uniqueid"))!==null&&n!==void 0?n:"").toUpperCase()===w4?"assistant":i:"unknown"}function Lp(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 gS(e){return e.replace(/^\{/,"").replace(/\}$/,"")}function T4(e,t){let r={n:"form",a:(0,ro.mergeAttrs)(e.bag.a,[]),c:(0,ro.spliceChildren)(e.bag.c,[])};return(0,ro.rebuildRaw)(r,(0,It.domEngine)(t),null)}function cS(e){let t=new DOMParser().parseFromString("<root/>","text/xml"),r=T4(e,t);return x4(t,r,e.components),R4(t,r,e.components),(0,It.serializeNode)(r)}function R4(e,t,r){let n=vS(t);for(let i of r)n.has(no(i.position))||F4(e,t,i)}function F4(e,t,r){var n,i,a,o;let s=(i=(n=r.position)===null||n===void 0?void 0:n.sectionIndex)!==null&&i!==void 0?i:0,l=B4(t,e,s);for(let $ of V(l,"row"))V($,"cell").some(re=>V(re,"control").length>0)||l.removeChild($);let u=r.classId||er.TILE_CLASS_ID[r.type]||er.TILE_CLASS_ID.iframe,c=r.rowspan&&r.rowspan>0?r.rowspan:4,d=r.bag&&dS(r.bag,"id")?String(dS(r.bag,"id")):ml((0,Cn.newId)()),f=r.id?ml(r.id):ml((0,Cn.newId)()),h=l.parentNode,b=Math.max(1,parseInt(h&&h.getAttribute&&h.getAttribute("columns")||"1",10)||1),w=Math.min(Math.max(1,r.colspan&&r.colspan>0?r.colspan:1),b),N=V(l,"row"),I=N[N.length-1],R=I?V(I,"cell").reduce(($,re)=>$+Lp(re,"colspan",1),0):0;(!I||R+w>b)&&(I=e.createElement("row"),l.appendChild(I));let F=e.createElement("cell");F.setAttribute("id",d),F.setAttribute("colspan",String(w)),F.setAttribute("rowspan",String(c)),F.setAttribute("showlabel","true");let M=e.createElement("labels"),W=e.createElement("label");W.setAttribute("description",(a=r.name)!==null&&a!==void 0?a:""),W.setAttribute("languagecode",String(hl)),M.appendChild(W),F.appendChild(M);let B=e.createElement("control");B.setAttribute("id",f),B.setAttribute("classid",ml(u));let j=e.createElement("parameters"),k=(o=r.parameters)!==null&&o!==void 0?o:{};for(let $ of Object.keys(k)){let re=(0,fS.createSafeXmlElement)(e,$,"dashboard tile parameter");re.textContent=k[$],j.appendChild(re)}B.appendChild(j),F.appendChild(B),I.appendChild(F)}function dS(e,t){if(!e)return;let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function x4(e,t,r){var n;let i=vS(t),a=new Set(r.map(o=>no(o.position)));for(let o of r){let s=i.get(no(o.position));if(!s)continue;let l=V(s,"control")[0];l&&(L4(e,s,o.name),M4(e,l,o.parameters),pS(s,"colspan",o.colspan),pS(s,"rowspan",o.rowspan),o.icProperties!==void 0&&_4(e,l,o.icProperties))}for(let[o,s]of i)a.has(o)||(n=s.parentNode)===null||n===void 0||n.removeChild(s)}function vS(e){let t=new Map;return V(e,"tabs").flatMap(n=>V(n,"tab")).forEach((n,i)=>{V(n,"columns").flatMap(o=>V(o,"column")).forEach((o,s)=>{V(o,"sections").flatMap(u=>V(u,"section")).forEach((u,c)=>{V(u,"rows").flatMap(f=>V(f,"row")).forEach((f,h)=>{V(f,"cell").forEach((b,w)=>{var N;gS((N=b.getAttribute("id"))!==null&&N!==void 0?N:"").toLowerCase().startsWith("spacer")||V(b,"control")[0]&&t.set(no({tabIndex:i,columnIndex:s,sectionIndex:c,rowIndex:h,cellIndex:w}),b)})})})})}),t}function no(e){let t=e??{};return`${t.tabIndex}.${t.columnIndex}.${t.sectionIndex}.${t.rowIndex}.${t.cellIndex}`}function L4(e,t,r){if(r===hS(t))return;let n=V(t,"labels")[0];n||(n=e.createElement("labels"),t.appendChild(n));let i=V(n,"label").find(a=>a.getAttribute("languagecode")===String(hl));i||(i=V(n,"label")[0]),i||(i=e.createElement("label"),i.setAttribute("languagecode",String(hl)),n.appendChild(i)),i.setAttribute("description",r)}function M4(e,t,r){var n;if(!r)return;let i=Object.keys(r);if(i.length===0)return;let a=V(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,fS.createSafeXmlElement)(e,l,"dashboard component parameter");d.textContent=u,a.appendChild(d)}}}function pS(e,t,r){var n;((n=e.getAttribute(t))!==null&&n!==void 0?n:"")!==String(r)&&e.setAttribute(t,String(r))}function U4(e=2){let t=`{${(0,Cn.newId)()}}`,r=`{${(0,Cn.newId)()}}`,n=`{${(0,Cn.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>`}er.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 ml(e){return`{${e.replace(/[{}]/g,"")}}`}function B4(e,t,r){var n;let i=V(e,"tabs").flatMap(u=>V(u,"tab"))[0];if(!i)throw new Error("addDashboardTile: dashboard formxml has no <tab>");let a=V(i,"columns").flatMap(u=>V(u,"column"))[0];if(!a)throw new Error("addDashboardTile: dashboard formxml has no <column>");let o=V(a,"sections").flatMap(u=>V(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=V(s,"rows")[0];return l||(l=t.createElement("rows"),s.appendChild(l)),l}function k4(){return{adapter:new gl,api:C4.dashboardApi}}er.dashboardRegistration=k4});var yS=m(vl=>{"use strict";Object.defineProperty(vl,"__esModule",{value:!0});vl.buildRegistrations=void 0;var q4=mN(),$4=TN(),V4=C2(),G4=I2(),z4=z2(),W4=oS(),j4=bS();function H4(){let e=new Map;return e.set("form",(0,q4.formRegistration)()),e.set("view",(0,$4.viewRegistration)()),e.set("businessRule",(0,V4.businessRuleRegistration)()),e.set("app",(0,G4.appRegistration)()),e.set("command",(0,z4.commandRegistration)()),e.set("chart",(0,W4.chartRegistration)()),e.set("dashboard",(0,j4.dashboardRegistration)()),e}vl.buildRegistrations=H4});var CS=m(bl=>{"use strict";Object.defineProperty(bl,"__esModule",{value:!0});bl.cloneJson=void 0;function J4(e){return JSON.parse(JSON.stringify(e))}bl.cloneJson=J4});var _S=m(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.removeRowSummary=Ae.configureRowSummary=Ae.buildGptDynamicPrompt=Ae.setAppAiFeatures=Ae.getAiReadiness=Ae.saveSettingValue=Ae.retrieveSetting=Ae.AI_GATE=void 0;var Ut=Ve(),Ue=ce(),AS=Tt(),Sr=be();Ae.AI_GATE={formFill:"FormFillBarUXEnabled",nlSearch:"EnableNLGridSearch",nlChart:"NLChartVisualizationSetting",summaries:"EnableFormInsights",m365:"m365copilotmodelappenabled"};var Q4={formFill:"FormFillBarUXEnabled",nlSearch:"NLGridSearchSetting",nlChart:"NLChartDataVisualizationSetting",m365:"m365copilotmodelappenabled"},yl=1e6;function X4(e,t){let r=()=>{throw new Sr.InvalidArgumentError(`setAppAiFeatures: '${t}' must be a boolean or an integer between 0 and ${yl} (e.g. 0, 1, 2); got '${String(e)}'.`)};if(typeof e=="boolean")return e?"1":"0";if(typeof e=="number")return!Number.isSafeInteger(e)||e<0||e>yl?r():String(e);if(typeof e=="string"){let n=e.trim(),i=n.toLowerCase();if(i==="true")return"1";if(i==="false")return"0";if(/^[0-9]+$/.test(n)){let a=n.replace(/^0+(?=[0-9])/,"");return a.length>String(yl).length||Number(a)>yl?r():a}}return r()}function K4(e){return e!=="0"}async function Y4(e,t){var r,n,i;let a=`/appmodules${(0,Ue.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,Ue.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 Z4(e,t){var r,n;let i=`/appmodules${(0,Ue.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,Ue.odataLiteral)(t)}'`]])}`,a;try{a=await e.get(i)}catch(l){throw new Sr.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 Sr.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 Sr.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 Sr.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a row with no appmoduleid.`);return s}var wS=new WeakMap;async function e5(e,t){var r,n,i;let a=wS.get(e);if(a||(a=new Map,wS.set(e,a)),a.has(t))return a.get(t);let o=`/settingdefinitions${(0,Ue.odataQuery)([["$select","settingdefinitionid"],["$filter",`uniquename eq '${(0,Ue.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 t5(e,t,r){var n,i;let a=await e5(e,r);if(!t||!a)return;let o=`/appsettings${(0,Ue.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 r5=4,n5=500,NS=20,SS=3e4;function i5(e){if(e===void 0)return r5;if(!Number.isFinite(e))throw new Sr.InvalidArgumentError(`setAppAiFeatures: verifyAttempts must be a finite integer between 1 and ${NS}; got ${e}.`);return Math.min(NS,Math.max(1,Math.floor(e)))}function a5(e){if(e===void 0)return n5;if(!Number.isFinite(e))throw new Sr.InvalidArgumentError(`setAppAiFeatures: verifyDelayMs must be a finite number between 0 and ${SS}; got ${e}.`);return Math.min(SS,Math.max(0,Math.floor(e)))}function o5(e){return e>0?new Promise(t=>setTimeout(t,e)):Promise.resolve()}async function s5(e,t,r,n,i,a,o){let s,l,u,c=!1;for(let d=0;d<a;d+=1){d>0&&await o5(o*d);let f;try{let h=await t();h?(f=await t5(e,h,n),f===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(h){f=void 0,u=h.message}c=f!==void 0,l=f?.exists;try{s=(await Cl(e,n,{appUniqueName:r})).value}catch{}if(f?.exists&&f.value===i)return{result:"proven",effectiveValue:f.value,appOverrideExists:!0}}return c?{result:"absent",effectiveValue:s,appOverrideExists:l}:{result:"unverifiable",effectiveValue:s,appOverrideExists:void 0,reason:u}}function DS(e,t){return t===2?String(e).toLowerCase()==="true":e!=null&&e!=="0"&&e!==""}async function Cl(e,t,r={}){var n,i;let a=[`SettingName='${(0,Ue.odataPathLiteral)(t)}'`];r.appUniqueName&&a.push(`AppUniqueName='${(0,Ue.odataPathLiteral)(r.appUniqueName)}'`);let o=`/RetrieveSetting(${a.join(",")})`,l=(i=(n=(0,Ut.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}}Ae.retrieveSetting=Cl;async function ES(e,t,r,n={}){let i={SettingName:t,Value:r};n.appUniqueName&&(i.AppUniqueName=n.appUniqueName),n.solutionUniqueName&&(i.SolutionUniqueName=n.solutionUniqueName),(0,Ut.ensureSuccess)(await e.post("/SaveSettingValue",i),e.apiUrl("/SaveSettingValue"))}Ae.saveSettingValue=ES;async function l5(e,t={}){let r={};for(let[n,i]of Object.entries(Ae.AI_GATE)){let{value:a,dataType:o}=await Cl(e,i,t);r[n]={enabled:DS(a,o),setting:i,value:a}}return r}Ae.getAiReadiness=l5;async function u5(e,t,r,n={}){var i,a,o;if(!t||!t.trim())throw new Sr.InvalidArgumentError("setAppAiFeatures: a non-empty appUniqueName is required (an empty value would write the setting at organization scope, affecting every app).");let s=i5(n.verifyAttempts),l=a5(n.verifyDelayMs),u=[];for(let[N,I]of Object.entries(r)){if(I===void 0)continue;let R=Q4[N];R&&u.push({feature:N,setting:R,requestedValue:X4(I,N)})}let c=[],d=n.appModuleId?(0,Ue.normalizeGuid)(n.appModuleId,"appModuleId"):void 0;if(d){let N=await Z4(e,t);if(N&&(0,Ue.normalizeGuid)(N,"appModuleId")!==d)throw new Sr.InvalidArgumentError(`setAppAiFeatures: appModuleId '${d}' does not belong to app '${t}' (which resolves to '${N}'). Settings are written by unique name, so verifying against a different app would report success for a write that never landed.`)}let f,h=async()=>d||(f||(f=await Y4(e,t)),f),b=new Map,w=async N=>{let I=Ae.AI_GATE[N];if(I){if(!b.has(I)){let{value:R,dataType:F}=await Cl(e,I);b.set(I,{enabled:DS(R,F),setting:I,value:R})}return b.get(I)}};for(let{feature:N,setting:I,requestedValue:R}of u)try{if(K4(R)){let W=await w(N);if(!W?.enabled){c.push({feature:N,setting:I,requestedValue:R,status:"skipped",reason:`the org readiness gate '${(i=W?.setting)!==null&&i!==void 0?i:N}' is off, so the feature cannot be enabled for this app`});continue}}await ES(e,I,R,{appUniqueName:t,solutionUniqueName:n.solutionUniqueName});let F=await s5(e,h,t,I,R,s,l),M={feature:N,setting:I,requestedValue:R,effectiveValue:F.effectiveValue,appOverrideExists:F.appOverrideExists};F.result==="proven"?c.push({...M,status:"applied"}):F.result==="absent"?c.push({...M,status:"notPersisted",reason:`the write reported success but no app-scope override holding '${R}' was observed for '${I}' after ${s} attempt(s) \u2014 it reads '${(a=F.effectiveValue)!==null&&a!==void 0?a:""}' for this app (Dataverse can accept an app-scope write without storing it)`}):c.push({...M,status:"unverified",reason:`the write was issued but could not be confirmed: ${(o=F.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(F){c.push({feature:N,setting:I,requestedValue:R,status:"failed",reason:F.message})}return{applied:c.filter(N=>N.status==="applied").map(N=>N.feature),skipped:c.filter(N=>N.status==="skipped").map(N=>N.feature),notPersisted:c.filter(N=>N.status==="notPersisted").map(N=>N.feature),unverified:c.filter(N=>N.status==="unverified").map(N=>N.feature),failed:c.filter(N=>N.status==="failed").map(N=>N.feature),outcomes:c}}Ae.setAppAiFeatures=u5;var c5="GptPowerPrompt",d5='{ "consumptionSource": "Api", "partnerSource": "AIBuilder", "consumptionSourceVersion": "GptApiClient"}';function IS(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:""}}Ae.buildGptDynamicPrompt=IS;async function p5(e,t){var r,n;let i=`/EntityDefinitions(LogicalName='${(0,Ue.odataPathLiteral)(t)}')${(0,Ue.odataQuery)([["$select","MetadataId"]])}`;return(n=(r=(0,Ut.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.MetadataId)!==null&&n!==void 0?n:""}async function f5(e,t,r={}){var n,i,a,o,s;let l=`ais_RowSummary_${t.entityLogicalName}`,u=`/aiskillconfigs${(0,Ue.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,Ue.odataLiteral)(l)}'`],["$top",1]])}`,c=((i=(n=(0,Ut.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,Ue.odataQuery)([["$select","msdyn_aitemplateid"],["$filter",`msdyn_uniquename eq '${c5}'`],["$top",1]])}`,f=((s=(o=(a=(0,Ut.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,h=(0,AS.newId)(),b=(0,AS.newId)(),w=JSON.stringify(IS(t)),N={ModelId:h,RunConfigurationId:b,ModelName:`${t.entityLogicalName} row summary`,TemplateId:f,CustomConfiguration:w,Source:d5,RunConfiguration:""};(0,Ut.ensureSuccess)(await e.post("/AIModelPublish",N),e.apiUrl("/AIModelPublish"));try{let I=await p5(e,t.entityLogicalName),R={uniquename:l,description:`${t.entityLogicalName} row summary`,"[email protected]":`/entities(${I})`,"[email protected]":`/msdyn_aimodels(${h})`,aiskill:"RowSummary"},F=(0,Ut.ensureSuccess)(await e.post("/aiskillconfigs",R),e.apiUrl("/aiskillconfigs")),M=(0,Ut.requireCreatedId)(F,"aiskillconfigid","row-summary skill");return{modelId:h,aiSkillConfigId:M}}catch(I){try{await e.delete(`/msdyn_aimodels(${h})`)}catch{}throw I}}Ae.configureRowSummary=f5;async function m5(e,t){var r,n;let i=`ais_RowSummary_${t.entityLogicalName}`,a=`/aiskillconfigs${(0,Ue.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,Ue.odataLiteral)(i)}'`],["$top",1]])}`,o=((n=(r=(0,Ut.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=`/aiskillconfigs(${o.aiskillconfigid})`;if((0,Ut.ensureSuccess)(await e.delete(s),e.apiUrl(s)),o._aimodel_value){let l=`/msdyn_aimodels(${o._aimodel_value})`;(0,Ut.ensureSuccess)(await e.delete(l),e.apiUrl(l))}}Ae.removeRowSummary=m5});var PS=m(Ei=>{"use strict";Object.defineProperty(Ei,"__esModule",{value:!0});Ei.findArtifact=Ei.resolveArtifact=void 0;var Ze=ce(),tr=Bi(),h5=be();async function g5(e,t,r){var n,i,a,o,s,l,u,c,d,f,h;switch(t){case"app":{let b=await(0,tr.queryRecords)(e,"appmodule",{select:["appmoduleid","name","appmoduleidunique"],filter:`uniquename eq '${(0,Ze.odataLiteral)((n=r.uniqueName)!==null&&n!==void 0?n:"")}'`,top:1}),w=b&&b[0];return w?[{id:String(w.appmoduleid),name:String(w.name),appModuleIdUnique:String(w.appmoduleidunique)}]:[]}case"dashboard":return(await(0,tr.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,Ze.odataLiteral)((i=r.name)!==null&&i!==void 0?i:"")}' and type eq 0`,top:10})||[]).map(w=>({id:String(w.formid),name:String(w.name)}));case"command":{let b=await(0,tr.queryRecords)(e,"appaction",{select:["appactionid","buttonlabeltext"],filter:`contextvalue eq '${(0,Ze.odataLiteral)((a=r.entity)!==null&&a!==void 0?a:"")}'`,top:1});return b&&b.length?[{id:String(r.entity),entity:String(r.entity)}]:[]}case"form":return(await(0,tr.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,Ze.odataLiteral)((o=r.name)!==null&&o!==void 0?o:"")}' and objecttypecode eq '${(0,Ze.odataLiteral)((s=r.entity)!==null&&s!==void 0?s:"")}'`,top:10})||[]).map(w=>({id:String(w.formid),name:String(w.name)}));case"chart":return(await(0,tr.queryRecords)(e,"savedqueryvisualization",{select:["savedqueryvisualizationid","name"],filter:`name eq '${(0,Ze.odataLiteral)((l=r.name)!==null&&l!==void 0?l:"")}' and primaryentitytypecode eq '${(0,Ze.odataLiteral)((u=r.entity)!==null&&u!==void 0?u:"")}'`,top:10})||[]).map(w=>({id:String(w.savedqueryvisualizationid),name:String(w.name)}));case"view":return(await(0,tr.queryRecords)(e,"savedquery",{select:["savedqueryid","name"],filter:`name eq '${(0,Ze.odataLiteral)((c=r.name)!==null&&c!==void 0?c:"")}' and returnedtypecode eq '${(0,Ze.odataLiteral)((d=r.entity)!==null&&d!==void 0?d:"")}'`,top:10})||[]).map(w=>({id:String(w.savedqueryid),name:String(w.name)}));case"webResource":return(await(0,tr.queryRecords)(e,"webresource",{select:["webresourceid","name"],filter:`name eq '${(0,Ze.odataLiteral)((f=r.name)!==null&&f!==void 0?f:"")}'`,top:1})||[]).map(w=>({id:String(w.webresourceid),name:String(w.name)}));case"solution":return(await(0,tr.queryRecords)(e,"solution",{select:["solutionid","uniquename"],filter:`uniquename eq '${(0,Ze.odataLiteral)((h=r.uniqueName)!==null&&h!==void 0?h:"")}'`,top:1})||[]).map(w=>({id:String(w.solutionid),name:String(w.uniquename)}));default:return[]}}Ei.resolveArtifact=g5;async function v5(e,t,r){var n,i,a,o,s;let l=(0,Ze.odataLiteral)((n=r.name)!==null&&n!==void 0?n:""),u=(0,Ze.odataLiteral)((i=r.entity)!==null&&i!==void 0?i:"");if(t==="command"){let b=await(0,tr.queryRecords)(e,"appaction",{select:["appactionid"],filter:`contextvalue eq '${(0,Ze.odataLiteral)((a=r.entity)!==null&&a!==void 0?a:"")}'`,top:1});return b&&b.length?String(r.entity):null}let c=b5(t,l,u,r),d=t!=="app",f=await(0,tr.queryRecords)(e,c.set,{select:[c.idField],filter:c.filter,top:d?2:1});if(d&&f&&f.length>1)throw new h5.AmbiguousArtifactError(t,(s=(o=r.name)!==null&&o!==void 0?o:r.uniqueName)!==null&&s!==void 0?s:"",f.length);let h=f&&f[0]&&f[0][c.idField];return h!=null?String(h):null}Ei.findArtifact=v5;function b5(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,Ze.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 TS=m(wl=>{"use strict";Object.defineProperty(wl,"__esModule",{value:!0});wl.seedRecordGraph=void 0;var OS=Bi(),y5=Co(),Al=ce(),C5=be();async function A5(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:(f=>(0,y5.resolveEntitySetName)(e,f)),c={},d=f=>{var h;return(h=c[f])!==null&&h!==void 0?h:l[f]};for(let f of t){let h=f.entityLogical.toLowerCase(),b=(a=f.matchOn)===null||a===void 0?void 0:a.toLowerCase(),w=[];for(let B of f.records){let j={...B.body};for(let k of(o=B.binds)!==null&&o!==void 0?o:[]){let $=k.parentEntity.toLowerCase(),re=(s=d($))===null||s===void 0?void 0:s[k.parentIndex];if(!re)throw new C5.InvalidArgumentError(`Cannot resolve bind '${k.navProperty}' on a '${h}' record: parent '${k.parentEntity}'[${k.parentIndex}] has no created id. Seed the parent group before the child, or supply it via options.createdIds.`);let H=(0,Al.assertODataName)(await u($),`entity set for parent '${k.parentEntity}'`),nr=(0,Al.normalizeGuid)(re,`parent id for bind '${k.navProperty}'`);j[`${k.navProperty}@odata.bind`]=`/${H}(${nr})`}w.push(j)}let N=b?w.map(B=>{let j=B[b];return j!=null&&j!==""?String(j):null}):w.map(()=>null),I=new Map;if(b){let B=(0,Al.assertODataName)(b,"RecordGraph matchOn key"),j=[...new Set(N.filter(k=>k!==null))];if(j.length){let k=j.map(re=>`${B} eq '${(0,Al.odataLiteral)(re)}'`).join(" or "),$=await(0,OS.queryRecords)(e,h,{select:[B,`${h}id`],filter:k,top:5e3});for(let re of $??[]){let H=re[B];H!=null&&I.set(String(H).toLowerCase(),String(re[`${h}id`]))}}}let R=[],F=new Map,M=w.map((B,j)=>{let k=N[j];if(k&&I.has(k.toLowerCase()))return null;if(k){let $=k.toLowerCase(),re=F.get($);if(re!==void 0)return re;let H=R.push(B)-1;return F.set($,H),H}return R.push(B)-1}),W=R.length?await(0,OS.createRecordsBulk)(e,h,R):[];c[h]=w.map((B,j)=>{let k=N[j];return k&&I.has(k.toLowerCase())?I.get(k.toLowerCase()):W[M[j]]})}return{createdIds:c}}wl.seedRecordGraph=A5});var qS=m(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.deleteSecurityRole=Pt.createPersonaRole=Pt.createSecurityRole=Pt.SDK_ROLE_MARKER=void 0;var rr=Ve(),qe=ce(),_t=be(),RS={read:"Read",create:"Create",write:"Write",delete:"Delete",append:"Append",appendTo:"AppendTo",assign:"Assign",share:"Share"},BS={user:"Basic",businessUnit:"Local",parentChild:"Deep",organization:"Global"},FS={user:1,businessUnit:2,parentChild:3,organization:4},w5={user:"CanBeBasic",businessUnit:"CanBeLocal",parentChild:"CanBeDeep",organization:"CanBeGlobal"};Pt.SDK_ROLE_MARKER="Authored by @maker-studio/cds-maker-sdk (persona/security role).";function N5(e){return Object.prototype.hasOwnProperty.call(RS,e)?RS[e]:void 0}function S5(e){return Object.prototype.hasOwnProperty.call(BS,e)}var xS=new WeakMap,LS=new WeakMap;async function D5(e,t){var r,n;(0,qe.assertODataName)(t,"entity logical name");let i=xS.get(e);i||(i=new Map,xS.set(e,i));let a=i.get(t);if(a)return a;let o=`/EntityDefinitions(LogicalName='${(0,qe.odataPathLiteral)(t)}')${(0,qe.odataQuery)([["$select","LogicalName,Privileges"]])}`,l=(n=(r=(0,rr.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 _t.InvalidArgumentError(`Entity '${t}' exposes no privileges (unknown or non-securable entity).`);return i.set(t,l),l}async function E5(e){var t,r,n;let i=LS.get(e);if(i)return i;let a=`/businessunits${(0,qe.odataQuery)([["$select","businessunitid"],["$filter","_parentbusinessunitid_value eq null"],["$top",1]])}`,l=(n=((r=(t=(0,rr.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 _t.InvalidArgumentError("Could not resolve the root business unit.");let u=(0,qe.normalizeGuid)(l,"businessUnitId");return LS.set(e,u),u}async function I5(e,t){var r;let n=new Map;for(let i of t){if(!i.access||i.access.length===0)throw new _t.InvalidArgumentError(`Entity '${i.entity}' privilege request has no access levels.`);let a=(r=i.scope)!==null&&r!==void 0?r:"user";if(!S5(a))throw new _t.InvalidArgumentError(`Unknown privilege scope '${a}' for entity '${i.entity}'.`);let o=await D5(e,i.entity);for(let s of i.access){let l=N5(s);if(!l)throw new _t.InvalidArgumentError(`Unknown access level '${s}' for entity '${i.entity}'.`);let u=o.find(b=>b.PrivilegeType===l);if(!u)throw new _t.InvalidArgumentError(`Entity '${i.entity}' does not support '${s}' access.`);let c=w5[a];if(u[c]===!1)throw new _t.InvalidArgumentError(`Privilege '${u.Name}' on '${i.entity}' does not support the '${a}' scope.`);let d=(0,qe.normalizeGuid)(u.PrivilegeId,"PrivilegeId"),f=n.get(d);if(!f){n.set(d,{privilegeName:u.Name,privilegeType:l,scope:a,entities:new Set([i.entity])});continue}if(f.scope===a){f.entities.add(i.entity);continue}if(!(f.entities.size===1&&f.entities.has(i.entity))){let b=[...f.entities].sort().join(", ");throw new _t.InvalidArgumentError(`Entities '${b}' 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.`)}f.scope=FS[a]>FS[f.scope]?a:f.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 _5(e,t,r,n){if(r.length===0&&!n)return;let i={Privileges:r.map(o=>({Depth:BS[o.scope],PrivilegeId:o.privilegeId}))},a=`/roles(${t})/Microsoft.Dynamics.CRM.ReplacePrivilegesRole`;(0,rr.ensureSuccess)(await e.post(a,i),e.apiUrl(a))}async function MS(e,t,r,n,i){var a,o;let s=`/${t}(${r})/${n}${(0,qe.odataQuery)([["$select","roleid"],["$filter",`roleid eq ${i}`]])}`;return((o=(a=(0,rr.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 P5(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,qe.normalizeGuid)(l,"teamId");if(!await MS(e,"teams",u,"teamroles_association",t)){let c=`/teams(${u})/teamroles_association/$ref`;(0,rr.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,qe.normalizeGuid)(l,"userId");if(!await MS(e,"systemusers",u,"systemuserroles_association",t)){let c=`/systemusers(${u})/systemuserroles_association/$ref`;(0,rr.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}o.push(u)}return{teams:a,users:o}}async function US(e,t,r){var n,i;let a=`/roles${(0,qe.odataQuery)([["$select","roleid,description,ismanaged"],["$filter",`name eq '${(0,qe.odataLiteral)(t)}' and _businessunitid_value eq ${r}`]])}`,l=((i=(n=(0,rr.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 f;return d.ismanaged!==!0&&((f=d.description)!==null&&f!==void 0?f:"")===Pt.SDK_ROLE_MARKER};if(l.some(d=>!u(d)))throw new _t.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 _t.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,qe.normalizeGuid)(c,"roleId"):void 0}function O5(e){var t,r;return{teams:((t=e?.teams)!==null&&t!==void 0?t:[]).map(n=>(0,qe.normalizeGuid)(n,"teamId")),users:((r=e?.users)!==null&&r!==void 0?r:[]).map(n=>(0,qe.normalizeGuid)(n,"userId"))}}function T5(e){return e.map(t=>({entity:t.entity,privilegeName:t.privilegeName,privilegeType:t.privilegeType,scope:t.scope}))}async function kS(e,t){var r,n;let i=(r=t.name)===null||r===void 0?void 0:r.trim();if(!i)throw new _t.InvalidArgumentError("createSecurityRole: a non-empty role name is required.");let a=t.businessUnitId?(0,qe.normalizeGuid)(t.businessUnitId,"businessUnitId"):await E5(e),o=await I5(e,(n=t.privileges)!==null&&n!==void 0?n:[]),s=O5(t.assignTo),l=await US(e,i,a),u=l!==void 0;if(!l){let d="/roles",f={name:i,description:Pt.SDK_ROLE_MARKER,"[email protected]":`/businessunits(${a})`};try{let h=(0,rr.ensureSuccess)(await e.post(d,f),e.apiUrl(d));l=(0,qe.normalizeGuid)((0,rr.requireCreatedId)(h,"roleid","role"),"roleId")}catch(h){let b;try{b=await US(e,i,a)}catch{b=void 0}if(!b)throw h;l=b}}await _5(e,l,o,u);let c=await P5(e,l,s);return{roleId:l,name:i,reused:u,appliedPrivileges:T5(o),assignedTeams:c.teams,assignedUsers:c.users}}Pt.createSecurityRole=kS;async function R5(e,t){var r,n;let i=(r=t.persona)===null||r===void 0?void 0:r.trim();if(!i)throw new _t.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 kS(e,{name:i,businessUnitId:t.businessUnitId,privileges:a,assignTo:t.assignTo})}Pt.createPersonaRole=R5;async function F5(e,t){let n=`/roles(${(0,qe.normalizeGuid)(t,"roleId")})`;(0,rr.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Pt.deleteSecurityRole=F5});var GS=m(Pi=>{"use strict";Object.defineProperty(Pi,"__esModule",{value:!0});Pi.createMakerSdk=Pi.MakerSdk=void 0;var $e=be(),Dr=lo(),x5=qp(),L5=Gp(),M5=Xp(),U5=gf(),Mp=Af(),et=Co(),Er=Bi(),Nl=_f(),tt=Pf(),B5=ih(),k5=yS(),q5=fn(),$5=Tt(),An=CS(),Wr=Ve(),Ii=ce(),_i=_S(),$S=PS(),V5=TS(),G5=Wd(),Up=qS(),Sl=class{constructor(t){(0,q5.installDomShim)(),this.workspace=new L5.WorkspaceManager(t.workspacePath,t.instanceUrl),this.versions=new M5.VersionManager(this.workspace),this.dataverse=new U5.DataverseClient(t.instanceUrl,t.httpClient,t.solutionUniqueName),this.registrations=(0,k5.buildRegistrations)()}initWorkspace(){this.workspace.init()}getManifest(){return this.workspace.getManifest()}cleanWorkspace(){this.workspace.clean()}async fetchArtifact(t,r){let n=this.requireRegistration(t,"fetchArtifact"),{raw:i,etag:a}=await n.api.get(this.dataverse,r),o=n.adapter.fromApiResponse(i);return this.workspace.writeArtifact(t,r,o),this.versions.storeMeta(t,r,{etag:a,fetchedAt:(0,Wr.nowIso)(),snapshot:(0,An.cloneJson)(o)}),(0,An.cloneJson)(o)}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=[],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:VS(s)})}return this.workspace.updateManifest({lastSyncAt:(0,Wr.nowIso)()}),{summaries:i,skipped:a}}async fetchEntityMetadata(t){let r=await(0,Mp.fetchEntityMetadataFromApi)(this.dataverse,t);return this.workspace.writeEntityMetadata(t,r),r}findTables(t,r){return(0,Mp.findTables)(this.dataverse,t,r)}findColumns(t,r,n){return(0,Mp.findColumns)(this.dataverse,t,r,n)}createTable(t){return(0,et.createTable)(this.dataverse,t)}createColumn(t,r){return(0,et.createColumn)(this.dataverse,t,r)}updateColumn(t,r,n){return(0,et.updateColumn)(this.dataverse,t,r,n)}deleteColumn(t,r){return(0,et.deleteColumn)(this.dataverse,t,r)}createCustomerColumn(t,r){return(0,et.createCustomerColumn)(this.dataverse,t,r)}insertStatusValue(t,r){return(0,et.insertStatusValue)(this.dataverse,t,r)}updateTable(t,r){return(0,et.updateTable)(this.dataverse,t,r)}async setEntityIcon(t,r){if(await(0,et.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,Ii.xmlText)(t)}</entity></entities></importexportxml>`;(0,Wr.ensureSuccess)(await this.dataverse.post("/PublishXml",{ParameterXml:n}),this.dataverse.apiUrl("/PublishXml"))}}createAlternateKey(t,r){return(0,et.createAlternateKey)(this.dataverse,t,r)}deleteAlternateKey(t,r){return(0,et.deleteAlternateKey)(this.dataverse,t,r)}createRelationship(t){return(0,et.createRelationship)(this.dataverse,t)}deleteRelationship(t){return(0,et.deleteRelationship)(this.dataverse,t)}createGlobalOptionSet(t){return(0,et.createGlobalOptionSet)(this.dataverse,t)}deleteGlobalOptionSet(t){return(0,et.deleteGlobalOptionSet)(this.dataverse,t)}deleteTable(t){return(0,et.deleteTable)(this.dataverse,t)}createSecurityRole(t){return(0,Up.createSecurityRole)(this.dataverse,t)}createPersonaRole(t){return(0,Up.createPersonaRole)(this.dataverse,t)}deleteSecurityRole(t){return(0,Up.deleteSecurityRole)(this.dataverse,t)}createRecord(t,r){return(0,Er.createRecord)(this.dataverse,t,r)}createRecordsBulk(t,r){return(0,Er.createRecordsBulk)(this.dataverse,t,r)}updateRecord(t,r,n){return(0,Er.updateRecord)(this.dataverse,t,r,n)}upsertRecord(t,r,n){return(0,Er.upsertRecord)(this.dataverse,t,r,n)}deleteRecord(t,r){return(0,Er.deleteRecord)(this.dataverse,t,r)}getRecord(t,r,n){return(0,Er.getRecord)(this.dataverse,t,r,n)}queryRecords(t,r){return(0,Er.queryRecords)(this.dataverse,t,r)}seedRecordGraph(t,r){return(0,V5.seedRecordGraph)(this.dataverse,t,r)}resolveArtifact(t,r){return(0,$S.resolveArtifact)(this.dataverse,t,r)}findArtifact(t,r){return(0,$S.findArtifact)(this.dataverse,t,r)}async deleteAppCascade(t,r){let n=await(0,B5.deleteAppCascade)(this.dataverse,t,r),i=(0,Ii.normalizeGuid)(t,"appModuleId");return this.workspace.readArtifact("app",i)&&this.workspace.deleteArtifact("app",i),n}associateRecords(t,r,n){return(0,Er.associateRecords)(this.dataverse,t,r,n)}disassociateRecords(t,r,n,i){return(0,Er.disassociateRecords)(this.dataverse,t,r,n,i)}createWebResource(t){return(0,Nl.createWebResource)(this.dataverse,t)}updateWebResource(t,r){return(0,Nl.updateWebResource)(this.dataverse,t,r)}getWebResource(t){return(0,Nl.getWebResource)(this.dataverse,t)}deleteWebResource(t){return(0,Nl.deleteWebResource)(this.dataverse,t)}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)}getArtifact(t,r){return(0,An.cloneJson)(this.readRaw(t,r))}readRaw(t,r){let n=this.workspace.readArtifact(t,r);if(!n)throw new $e.ArtifactNotFoundError(t,r);return n}queryTree(t,r,n){let i=this.getArtifact(t,r),a=Dr.JsonPointer.resolve(i,n);if(a===void 0)throw new $e.PathNotFoundError(t,r,n);return a}findElements(t,r,n){let i=this.getArtifact(t,r);return(0,x5.findElements)(i,n)}listArtifacts(t,r){return this.workspace.listArtifacts(t,r).map(n=>({...n,isDirty:this.versions.isDirty(n.type,n.id)}))}getEntityMetadata(t){let r=this.workspace.readEntityMetadata(t);if(!r)throw new $e.ArtifactNotFoundError("entityMetadata",t);return r}getFieldMetadata(t,r){let i=this.getEntityMetadata(t).attributes.find(a=>a.logicalName===r);if(!i)throw new $e.PathNotFoundError("entityMetadata",t,r);return i}updateElement(t,r,n,i){let a=this.readRaw(t,r),o=Dr.JsonPointer.resolve(a,n);if(o===void 0)throw new $e.PathNotFoundError(t,r,n);let s=Dl(o)&&Dl(i)?{...o,...i}:i;return Dr.JsonPointer.set(a,n,(0,An.cloneJson)(s)),this.assertStructurallyValid(t,r,a,n),this.workspace.writeArtifact(t,r,a),this.getArtifact(t,r)}addElement(t,r,n,i,a){let o=this.readRaw(t,r),s=Dr.JsonPointer.resolve(o,n);if(s===void 0)throw new $e.PathNotFoundError(t,r,n);if(!Array.isArray(s))throw new $e.ValidationError(t,r,n,"parent must be an array");let l=this.assignMissingIds(t,(0,An.cloneJson)(i)),u=j5(s,a?.position);return s.splice(u,0,l),this.assertStructurallyValid(t,r,o,n),this.workspace.writeArtifact(t,r,o),this.getArtifact(t,r)}moveElement(t,r,n,i,a){var o;let s=this.readRaw(t,r),l=Dr.JsonPointer.resolve(s,n);if(l===void 0)throw new $e.PathNotFoundError(t,r,n);let u=Dr.JsonPointer.resolve(s,i);if(u===void 0)throw new $e.PathNotFoundError(t,r,i);if(!Array.isArray(u))throw new $e.ValidationError(t,r,i,"move target must be an array");if(i===n||i.startsWith(`${n}/`))throw new $e.ValidationError(t,r,i,"cannot move an element into its own subtree");Dr.JsonPointer.remove(s,n);let c=(o=a?.index)!==null&&o!==void 0?o:u.length;return u.splice(Math.max(0,Math.min(c,u.length)),0,l),this.assertStructurallyValid(t,r,s,i),this.workspace.writeArtifact(t,r,s),this.getArtifact(t,r)}removeElement(t,r,n){let i=this.readRaw(t,r);if(Dr.JsonPointer.resolve(i,n)===void 0)throw new $e.PathNotFoundError(t,r,n);return Dr.JsonPointer.remove(i,n),this.assertStructurallyValid(t,r,i,W5(n)),this.workspace.writeArtifact(t,r,i),this.getArtifact(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 $e.ValidationError(t,r,u)}retrieveSetting(t,r){return(0,_i.retrieveSetting)(this.dataverse,t,r)}saveSettingValue(t,r,n){return(0,_i.saveSettingValue)(this.dataverse,t,r,n)}getAiReadiness(t){return(0,_i.getAiReadiness)(this.dataverse,t)}setAppAiFeatures(t,r,n){return(0,_i.setAppAiFeatures)(this.dataverse,t,r,n)}configureRowSummary(t,r){return(0,_i.configureRowSummary)(this.dataverse,t,r)}removeRowSummary(t){return(0,_i.removeRowSummary)(this.dataverse,t)}async enrichDefaultViews(t,r,n={}){let i=await(0,G5.findDefaultViews)(this.dataverse,t,n);for(let a of i)await this.fetchArtifact("view",a.id),this.updateElement("view",a.id,"/columns",r),await this.pushArtifact("view",a.id);return i.length&&await this.publishArtifact("view",i[0].id),{updated:i.map(a=>a.id)}}createArtifact(t,r){let n=this.requireRegistration(t,"createArtifact"),i=n.adapter.assignMissingIds(n.adapter.createDefault(r)),a=i.id;if(!a)throw new $e.ValidationError(t,"(new)","/id","created artifact must have an id");return this.workspace.writeArtifact(t,a,i),(0,An.cloneJson)(i)}deleteArtifact(t,r){this.workspace.deleteArtifact(t,r)}async deleteRemoteArtifact(t,r){await this.requireRegistration(t,"deleteRemoteArtifact").api.delete(this.dataverse,r),this.workspace.readArtifact(t,r)&&this.workspace.deleteArtifact(t,r)}async publishArtifact(t,r){let n=this.readRaw(t,r),i;if(t==="app")i=`<importexportxml><appmodules><appmodule>${(0,Ii.xmlText)(r)}</appmodule></appmodules></importexportxml>`;else{let a=n.entityLogicalName;a&&(i=`<importexportxml><entities><entity>${(0,Ii.xmlText)(a)}</entity></entities></importexportxml>`)}i&&(0,Wr.ensureSuccess)(await this.dataverse.post("/PublishXml",{ParameterXml:i}),this.dataverse.apiUrl("/PublishXml"))}async pushArtifact(t,r){var n;let i=this.requireRegistration(t,"pushArtifact"),a=this.readRaw(t,r),o=this.versions.getMeta(t,r),s=await this.buildMetadataContext(i.adapter,a),l=i.adapter.toApiPayload(a,o?.snapshot,s);try{let u=o?await i.api.update(this.dataverse,r,l,o.etag):await i.api.create(this.dataverse,l),c=r;return o||(u.serverIdentity&&i.adapter.applyServerIdentity&&i.adapter.applyServerIdentity(a,u.serverIdentity),u.id&&u.id!==r&&(a.id=u.id,this.workspace.deleteArtifact(t,r),c=u.id),this.workspace.writeArtifact(t,c,a)),this.versions.storeMeta(t,c,{etag:u.etag,fetchedAt:(0,Wr.nowIso)(),snapshot:(0,An.cloneJson)(a)}),{type:t,id:c,success:!0,...u.warnings&&u.warnings.length>0?{warnings:u.warnings}:{}}}catch(u){if(u instanceof $e.SdkError&&u.code===Wr.VERSION_CONFLICT_CODE)return{type:t,id:r,success:!1,error:new $e.VersionConflictError(t,r,(n=o?.etag)!==null&&n!==void 0?n:null,null)};throw u}}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:[];if(a.length===0)return;let o=new Set(a.map(s=>s.entityLogicalName).filter(s=>!!s));for(let s of o)if(!this.workspace.readEntityMetadata(s))try{await this.fetchEntityMetadata(s)}catch{}return{resolveField:(s,l)=>{let u=this.workspace.readEntityMetadata(s),c=u?.attributes.find(d=>d.logicalName===l);return c?{displayName:c.displayName,attributeType:c.attributeType}:void 0}}}async pushAll(){let t=this.getDirtyArtifacts(),r=[];for(let n of t)try{r.push(await this.pushArtifact(n.type,n.id))}catch(i){r.push({type:n.type,id:n.id,success:!1,error:VS(i)})}return r}getDirtyArtifacts(){return this.workspace.listArtifacts().filter(t=>this.versions.isDirty(t.type,t.id)).map(t=>({...t,isDirty:!0}))}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,$5.assignMissingIds)(r)}async resolveComponentType(t){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":void 0;case tt.SolutionComponentType.SystemForm:return await this.isDashboardForm(t.objectId)?"dashboard":"form";default:return}}async isDashboardForm(t){let n=`/systemforms(${(0,Ii.normalizeGuid)(t,"formId")})${(0,Ii.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}requireRegistration(t,r){let n=this.registrations.get(t);if(!n)throw new $e.NotImplementedError(r,`no adapter registered for artifact type '${t}'`);return n}};Pi.MakerSdk=Sl;function z5(e){return new Sl(e)}Pi.createMakerSdk=z5;function VS(e){return e instanceof Error?e:new Error(String(e))}function Dl(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function W5(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function j5(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=>Dl(i)&&i.id===t.before);return n<0?e.length:n}let r=e.findIndex(n=>Dl(n)&&n.id===t.after);return r<0?e.length:r+1}});var zS=m(El=>{"use strict";Object.defineProperty(El,"__esModule",{value:!0});El.ARTIFACT_TYPES=void 0;El.ARTIFACT_TYPES=["form","view","businessRule","app","command","chart","dashboard"]});var jS=m(WS=>{"use strict";Object.defineProperty(WS,"__esModule",{value:!0})});var JS=m(HS=>{"use strict";Object.defineProperty(HS,"__esModule",{value:!0})});var XS=m(QS=>{"use strict";Object.defineProperty(QS,"__esModule",{value:!0})});var YS=m(KS=>{"use strict";Object.defineProperty(KS,"__esModule",{value:!0})});var eD=m(ZS=>{"use strict";Object.defineProperty(ZS,"__esModule",{value:!0})});var rD=m(tD=>{"use strict";Object.defineProperty(tD,"__esModule",{value:!0})});var iD=m(nD=>{"use strict";Object.defineProperty(nD,"__esModule",{value:!0})});var oD=m(aD=>{"use strict";Object.defineProperty(aD,"__esModule",{value:!0})});var lD=m(sD=>{"use strict";Object.defineProperty(sD,"__esModule",{value:!0})});var cD=m(uD=>{"use strict";Object.defineProperty(uD,"__esModule",{value:!0})});var pD=m(dD=>{"use strict";Object.defineProperty(dD,"__esModule",{value:!0})});var mD=m(fD=>{"use strict";Object.defineProperty(fD,"__esModule",{value:!0})});var gD=m(hD=>{"use strict";Object.defineProperty(hD,"__esModule",{value:!0})});var bD=m(vD=>{"use strict";Object.defineProperty(vD,"__esModule",{value:!0})});var CD=m(yD=>{"use strict";Object.defineProperty(yD,"__esModule",{value:!0})});var wD=m(AD=>{"use strict";Object.defineProperty(AD,"__esModule",{value:!0})});var SD=m(ND=>{"use strict";Object.defineProperty(ND,"__esModule",{value:!0})});var ED=m(DD=>{"use strict";Object.defineProperty(DD,"__esModule",{value:!0})});var H5=exports&&exports.__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]})),we=exports&&exports.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&H5(t,e,r)};Object.defineProperty(exports,"__esModule",{value:!0});exports.createMakerSdk=void 0;var J5=GS();Object.defineProperty(exports,"createMakerSdk",{enumerable:!0,get:function(){return J5.createMakerSdk}});we(zS(),exports);we(jS(),exports);we(JS(),exports);we(XS(),exports);we(YS(),exports);we(eD(),exports);we(rD(),exports);we(iD(),exports);we(oD(),exports);we(lD(),exports);we(cD(),exports);we(pD(),exports);we(mD(),exports);we(gD(),exports);we(bD(),exports);we(CD(),exports);we(wD(),exports);we(SD(),exports);we(ED(),exports);we(be(),exports);+`)}function w0(e){this.options=e||{locator:{}}}w0.prototype.parseFromString=function(e,t){var r=this.options,n=new _L,i=r.domBuilder||new io,a=r.errorHandler,o=r.locator,s=r.xmlns||{},l=/\/x?html?$/.test(t),u=l?h0.HTML_ENTITIES:h0.XML_ENTITIES;o&&i.setDocumentLocator(o),n.errorHandler=PL(a,i,o),n.domBuilder=r.domBuilder||i,l&&(s[""]=g0.HTML),s.xml=s.xml||g0.XML;var c=r.normalizeLineEndings||b0;return e&&typeof e=="string"?n.parse(c(e),s,u):n.errorHandler.error("invalid doc source"),i.doc};function PL(e,t,r){if(!e){if(t instanceof io)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+Nd(r))}||function(){}}return a("warning"),a("error"),a("fatalError"),n}function io(){this.cdata=!1}function _i(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}io.prototype={startDocument:function(){this.doc=new DL().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;Gs(this,a),this.currentElement=a,this.locator&&_i(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&&_i(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&&_i(this.locator,r),Gs(this,r)},ignorableWhitespace:function(e,t,r){},characters:function(e,t,r){if(e=v0.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&&_i(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=v0.apply(this,arguments);var n=this.doc.createComment(e);this.locator&&_i(this.locator,n),Gs(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&&_i(this.locator,i),Gs(this,i),this.doc.doctype=i}},warning:function(e){console.warn("[xmldom warning] "+e,Nd(this.locator))},error:function(e){console.error("[xmldom error] "+e,Nd(this.locator))},fatalError:function(e){throw new IL(e,this.locator)}};function Nd(e){if(e)return`+@`+(e.systemId||"")+"#[line:"+e.lineNumber+",col:"+e.columnNumber+"]"}function v0(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){io.prototype[e]=function(){return null}});function Gs(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}zs.__DOMHandler=io;zs.normalizeLineEndings=b0;zs.DOMParser=w0});var js=g(Ws=>{var C0=Ad();Ws.DOMImplementation=C0.DOMImplementation;Ws.XMLSerializer=C0.XMLSerializer;Ws.DOMParser=A0().DOMParser});var ld=g(Pi=>{"use strict";Object.defineProperty(Pi,"__esModule",{value:!0});Pi.deleteAppCascade=Pi.collectGenPageIds=void 0;var TL=Rs(),OL=le(),Ed=Z(),xL=js();function S0(e){let t=[],r=s=>l=>t.push(`${s}: ${l}`),i=new xL.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml").documentElement;if(!i||t.length>0)throw new OL.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,Ed.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}Pi.collectGenPageIds=S0;async function RL(e,t,r){let n=(0,Ed.normalizeGuid)(t,"appModuleId");(0,Ed.normalizeGuid)(r,"appModuleIdUnique");let i=[],a=[],o=[];await(0,TL.deleteAppResolvingOnce)(e,n,l=>{l!==void 0&&o.push(...S0(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}}Pi.deleteAppCascade=RL});var N0={};sr(N0,{Guid:()=>P});var P,xe=I(()=>{"use strict";P=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 T,rt=I(()=>{"use strict";Pe();T=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,"&").replace(/</g,"<").replace(/>/g,">"),r&&(n=n.replace(/"/g,""").replace(/'/g,"'"))),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(!N.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 N.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 E0={};sr(E0,{ScriptUtilities:()=>N});var N,Pe=I(()=>{"use strict";xe();rt();N=class e{static IsNullOrUndefined(t){return t==null||t===void 0}static IsMacMachine(){return navigator.platform.indexOf("Mac")!==-1}static IsNullOrEmptyGuid(t){return T.IsNullOrEmpty(t.ToString())?!0:P.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:T.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 Hs,Qs,$n,Js,Dd,Xs,Id=I(()=>{"use strict";(function(e){e[e.FormElementNodeChange=0]="FormElementNodeChange",e[e.FormElementAttributeChange=1]="FormElementAttributeChange"})(Hs||(Hs={}));Qs=class{type;targetNode;constructor(t,r){this.type=t,this.targetNode=r}},$n=class extends Qs{key;oldValue;newValue;constructor(t,r,n,i){super(Hs.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)}},Js=class extends Qs{property;oldValue;newValue;constructor(t,r,n,i){super(Hs.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)}},Dd=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()})}},Xs=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 Dd(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 D0={};sr(D0,{ChartGridMode:()=>Rt,ColumnLayoutWidths:()=>UL,ComponentCategory:()=>Ys,ComponentType:()=>_d,ControlLayoutTypes:()=>Fd,DisplayConditionsInfo:()=>kL,ElementNames:()=>v,ElementProperties:()=>m,ElementType:()=>Td,EntityAttributeProperty:()=>Od,EventType:()=>ao,FormActivationState:()=>Ld,FormCanvasServiceScope:()=>XL,FormDesignerSideBarTab:()=>Pd,FormPresentation:()=>xd,FormState:()=>Ks,FormType:()=>Re,HeaderDensityType:()=>cn,LookUpTable:()=>hr,MORE_TAB_PREFIX:()=>$L,NavBarChildElementType:()=>Rd,PREVIEW_ID_HEADER_FLYOUT:()=>zL,PREVIEW_ID_HEADER_OVERFLOW_BUTTON:()=>jL,PREVIEW_ID_NAVIGATION_AREA:()=>VL,PREVIEW_ID_QUICKCREATE_ROOT:()=>QL,PREVIEW_ID_TAB:()=>HL,PREVIEW_ID_TAB_LIST:()=>WL,PREVIEW_ID_TAB_PANEL:()=>GL,PropertyModelKeys:()=>Ud,PropertyModelSectionKeys:()=>BL,RELATED_TAB_ID:()=>Bd,RELATED_TAB_PREFIX:()=>qL,SectionDefaultProperties:()=>ML,SectionLayoutTypes:()=>be,TabContentType:()=>kd,TabDefaultProperties:()=>dn,TabLayoutTypes:()=>ye,TelemetryPropertyNames:()=>JL,UnboundControlPropertyKeys:()=>Md,compositeAddressFields:()=>FL,compositeFieldNames:()=>Pt,compositeFields:()=>LL});var Re,_d,Pd,v,m,Td,Pt,LL,FL,Od,hr,Ks,cn,xd,kL,Rd,Ld,ye,ML,dn,be,Fd,kd,UL,Md,Ud,BL,ao,Rt,Bd,$L,qL,VL,GL,zL,WL,jL,HL,QL,JL,Ys,XL,J=I(()=>{"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"})(Re||(Re={}));(function(e){e[e.Form=0]="Form",e[e.Dialog=1]="Dialog"})(_d||(_d={}));(function(e){e[e.Components=0]="Components",e[e.Properties=1]="Properties",e[e.Relationship=2]="Relationship",e[e.BusinessRules=3]="BusinessRules"})(Pd||(Pd={}));(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"})(v||(v={}));m={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"})(Td||(Td={}));Pt={fullname:"fullname",yomifullname:"yomifullname",address1_composite:"address1_composite",address2_composite:"address2_composite",address3_composite:"address3_composite",billto:"billto_composite",shipto:"shipto_composite"},LL=[Pt.fullname,Pt.yomifullname,Pt.address1_composite,Pt.address2_composite,Pt.address3_composite,Pt.billto,Pt.shipto],FL=[Pt.address1_composite,Pt.address2_composite,Pt.address3_composite,Pt.billto,Pt.shipto];(function(e){e[e.IsValidForForm=0]="IsValidForForm",e[e.IsValidForCreate=1]="IsValidForCreate"})(Od||(Od={}));(function(e){e[e.DependencyFieldTable=0]="DependencyFieldTable",e[e.LockedFieldTable=1]="LockedFieldTable"})(hr||(hr={}));(function(e){e[e.Published=0]="Published",e[e.Draft=1]="Draft",e[e.New=2]="New",e[e.SaveAs=3]="SaveAs"})(Ks||(Ks={}));(function(e){e.Low="Low",e.HighReadOnlyValues="HighReadOnlyValues",e.HighWithControls="HighWithControls"})(cn||(cn={}));(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(xd||(xd={}));kL={TopOrderFormId:"topOrderFormId",NextDisplayOrder:"nextDisplayOrder"};(function(e){e[e.NavBarRelationShipItem=0]="NavBarRelationShipItem",e[e.NavBarItem=1]="NavBarItem"})(Rd||(Rd={}));(function(e){e[e.InActive=0]="InActive",e[e.Active=1]="Active"})(Ld||(Ld={}));(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"})(ye||(ye={}));ML={ShowLabel:"false",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_"},dn={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"})(be||(be={}));(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"})(Fd||(Fd={}));(function(e){e.cardSections="cardSections",e.singleComponent="singleComponent",e.default="default",e.expandAvailableSpace="expandAvailableSpace"})(kd||(kd={}));UL={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"})(Md||(Md={}));(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"})(Ud||(Ud={}));BL={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"})(ao||(ao={}));(function(e){e.All="All",e.Chart="Chart",e.Grid="Grid"})(Rt||(Rt={}));Bd="tab_related3b554255-7717-4d17-bb7f-9936fb1e75ca",$L="more_tab_",qL="related_tab_",VL="preview_id_navigation_area",GL="tab-section",zL="headerFieldsFlyout",WL="tablist",jL="header_overflowButton",HL="tab",QL="quickCreateRoot",JL={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"})(Ys||(Ys={}));XL="CellCanvasServiceScope"});var I0={};sr(I0,{Attribute:()=>Zs,FormElementNode:()=>W});var Zs,W,Ge=I(()=>{"use strict";Pe();rt();Id();J();xe();Zs=class{key;value;constructor(t,r){this.key=t,this.value=r}},W=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-${P.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(v.form);r&&r.raiseMetadataChange(t)}trackPropertyAddition(t,r){this.trackPropertyCollectionChange(()=>{this.properties.push(new Zs(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 $n(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 $n(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 $n(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 Js(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 $n(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){N.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(N.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:T.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=N.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 v.formCell:let t=this.getAncestor(v.formSection);return t||(t=this.getAncestor(v.formHeader),t)||(t=this.getAncestor(v.formFooter),t)?t:null;case v.formSection:return this.getAncestor(v.formTab);case v.formTab:return this.getAncestor(v.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(v.form);return t?t.changeTracker():null}}});var _0={};sr(_0,{ControlClassId:()=>S,ControlNamePrefixes:()=>el,getControlDisplayNames:()=>KL});function KL(e){return{[S.AccessPrivilegeControl]:e("controls.controlNames.accessPrivilege"),[S.AccessTeamTablePickerControl]:e("controls.controlNames.accessTeamTablePicker"),[S.ACIControl]:e("controls.controlNames.aci"),[S.ActivitiesContainerControl]:e("controls.controlNames.activitiesContainer"),[S.ActivitiesWallControl]:e("controls.controlNames.activitiesWall"),[S.AppliedFiltersControl]:e("controls.controlNames.appliedFilters"),[S.ArticleContentControl]:e("controls.controlNames.articleContent"),[S.BooleanControl]:e("controls.controlNames.twoOption"),[S.ButtonControl]:e("controls.controlNames.button"),[S.CheckboxControl]:e("controls.controlNames.checkbox"),[S.CompositionLinkControl]:e("controls.controlNames.compositionLink"),[S.ConnectionControl]:e("controls.controlNames.connection"),[S.ConnectionRoleObjectTypeListControl]:e("controls.controlNames.connectionRoleObjectTypeList"),[S.CoverageChoiceControl]:e("controls.controlNames.coverageChoice"),[S.DashboardControl]:e("controls.controlNames.dashboard"),[S.DynamicPropertyListControl]:e("controls.controlNames.dynamicPropertyList"),[S.EditFilterControl]:e("controls.controlNames.editFilter"),[S.ErrorStatusControl]:e("controls.controlNames.errorStatus"),[S.GlobalFilterControl]:e("controls.controlNames.globalFilter"),[S.HiddenInputControl]:e("controls.controlNames.hiddenInput"),[S.KBViewerControl]:e("controls.controlNames.kbViewer"),[S.LabelControl]:e("controls.controlNames.label"),[S.MailMergeLanguagePickerControl]:e("controls.controlNames.mailMergeLanguagePicker"),[S.MapLinkControl]:e("controls.controlNames.mapLink"),[S.OrgInsightsControl]:e("controls.controlNames.orgInsights"),[S.ChoiceLookupControl]:e("controls.controlNames.choiceLookup"),[S.PowerBIControl]:e("controls.controlNames.powerBI"),[S.ProcessControl]:e("controls.controlNames.process"),[S.RelatedInformationControl]:e("controls.controlNames.relatedInformation"),[S.RelationshipRoleChoiceControl]:e("controls.controlNames.relationshipRoleChoice"),[S.ReportControl]:e("controls.controlNames.report"),[S.StreamsControl]:e("controls.controlNames.streams"),[S.WebResourceSilverlightControl]:e("controls.controlNames.webResourceSilverlight"),[S.CurrencyControl]:e("controls.controlNames.currency"),[S.DateTimeControl]:e("controls.controlNames.dateAndTime"),[S.DecimalControl]:e("controls.controlNames.decimal"),[S.DurationControl]:e("controls.controlNames.duration"),[S.EmailAddressControl]:e("controls.controlNames.email"),[S.FileControl]:e("controls.controlNames.file"),[S.FloatingNumberControl]:e("controls.controlNames.floatingNumber"),[S.IframeControl]:e("controls.controlNames.iframe"),[S.ImageControl]:e("controls.controlNames.image"),[S.LookupControl]:e("controls.controlNames.lookup"),[S.MapsControl]:e("controls.controlNames.maps"),[S.PhoneNumberControl]:e("controls.controlNames.phoneNumber"),[S.ChoiceControl]:e("controls.controlNames.choice"),[S.QuickViewControl]:e("controls.controlNames.quickView"),[S.QuickFormControl]:e("controls.controlNames.quickForm"),[S.CustomControl]:e("controls.controlNames.customControl"),[S.SearchWidgetControl]:e("controls.controlNames.searchWidget"),[S.SocialInsightsControl]:e("controls.controlNames.socialInsights"),[S.SubgridControl]:e("controls.controlNames.subgrid"),[S.TextAreaControl]:e("controls.controlNames.textArea"),[S.TextboxControl]:e("controls.controlNames.textBox"),[S.TickerControl]:e("controls.controlNames.ticker"),[S.UrlControl]:e("controls.controlNames.url"),[S.WebResourceHTMLControl]:e("controls.controlNames.webResourceHTML"),[S.WebResourceImageControl]:e("controls.controlNames.webResourceImage"),[S.IntegerControl]:e("controls.controlNames.integer"),[S.TimerControl]:e("controls.controlNames.timer"),[S.TimelineControl]:e("controls.controlNames.timeline"),[S.EmailBodyControl]:e("controls.controlNames.emailBody"),[S.PartyListControl]:e("controls.controlNames.partyList"),[S.TimezoneControl]:e("controls.controlNames.timezone"),[S.LanguageControl]:e("controls.controlNames.language"),[S.ChoiceStatusControl]:e("controls.controlNames.choiceStatus"),[S.ChoicesControl]:e("controls.controlNames.choices"),[S.RegardingControl]:e("controls.controlNames.regarding"),[S.EmailEngagementActionsControl]:e("controls.controlNames.emailEngagementActions"),[S.EmailRecipientActivityControl]:e("controls.controlNames.emailRecipientActivity"),[S.ReferencePanelSearchWidgetControl]:e("controls.controlNames.referencePanelSearchWidget"),[S.ReferencePanelQuickViewControl]:e("controls.controlNames.referencePanelQuickView"),[S.ReferencePanelSubgridControl]:e("controls.controlNames.referencePanelSubgrid"),[S.KBEditorControl]:e("controls.controlNames.KBEditor"),[S.LinkControl]:e("controls.controlNames.link")}}var S,el,qn=I(()=>{"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"})(S||(S={}));el={[S.WebResourceHTMLControl]:"WebResource",[S.WebResourceImageControl]:"WebResource",[S.IframeControl]:"IFRAME",[S.SearchWidgetControl]:"Search widget",[S.SubgridControl]:"Subgrid",[S.TimelineControl]:"Timeline",[S.QuickViewControl]:"QuickviewControl"}});var Vn=g((EW,T0)=>{var oo=new Proxy(function(){return oo},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:oo},apply:function(){return oo},construct:function(){return{}}}),P0=function(){return oo};Object.setPrototypeOf(P0,oo);T0.exports=P0});var ot,qr,O0,x0,Ti=I(()=>{"use strict";ot="cds-designer-models",qr="FormCustomControl",O0="FormCell",x0="Form"});var Oi,st,so=I(()=>{"use strict";Oi=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}},st=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 Gn,$d=I(()=>{"use strict";so();J();Gn=class e{static lockedFieldCount=new st;static dependencyFieldCount=new st;static getNecessaryLookUpTable(t){switch(t){case hr.DependencyFieldTable:return e.dependencyFieldCount;case hr.LockedFieldTable:return e.lockedFieldCount}}static initCanvasLockedFieldLookUp(t){switch(t){case hr.DependencyFieldTable:e.dependencyFieldCount=new st;case hr.LockedFieldTable:e.lockedFieldCount=new st}}}});var tl,R0=I(()=>{"use strict";xe();Pe();J();Ge();tl=class extends W{constructor(t){super(v.controlDescription,t)}get forControl(){let t=this.getProperty(m.ForControl);return N.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new P(t))}set forControl(t){this.setProperty(m.ForControl,`{${t.ToString()}}`)}get customControls(){return this.getChildren(v.customControl)}set customControls(t){this.deleteAllChildren();for(let r of t)this.addChild(r)}get DefaultControlClassId(){for(let t of this.customControls)if(!N.IsNullOrUndefined(t.id))return t.id;return null}get DefaultCustomControl(){for(let t of this.customControls)if(!N.IsNullOrUndefined(t.id))return t;return null}get DefaultCustomControls(){let t=[];for(let r of this.customControls)N.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 F0,k0,lt,_,L0,pn,zn,xi,qd,Vd,Ri=I(()=>{"use strict";F0={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"},k0={GroupDefinition:"GroupDefinition"},lt={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"})(_||(_={}));(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"})(L0||(L0={}));(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"})(pn||(pn={}));(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"})(zn||(zn={}));(function(e){e[e.Bound=0]="Bound",e[e.Input=1]="Input",e[e.Output=2]="Output"})(xi||(xi={}));qd=[_.LookupCustomer,_.LookupOwner,_.LookupPartyList,_.LookupRegarding,_.LookupSimple],Vd=[_.WholeNone,_.WholeDuration,_.WholeLanguage,_.WholeTimeZone,_.FP,_.Decimal]});function Vr(){return gr||(gr=window._makerConfig,gr&&window?.location?.search?.indexOf("useProductionConfig")>-1&&(gr={...gr,region:"prod",graphQLEndpoint:"https://graph.make.powerapps.com/"}),gr?.region==="prod"&&(gr={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/"}}},...gr}),gr||{aadClientId:"a8f7a65c-f5ba-4859-b2d6-df772c264e9d",location:"cus",region:"test",publicPath:"/",graphQLEndpoint:"https://graph.make.test.powerapps.com/"})}var gr,rl=I(()=>{"use strict";});function M0(e,t,r){if(!e)return nl.has(e)||(window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoIsEmpty"}),nl.add("")),!1;if(e){if(e=e.toLowerCase(),nl.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}}),nl.add(e),!1}return!0}function YL(e){return M0(e,Gd,"Location dictionary")?Gd[e.toLowerCase()]:"us"}function ZL(){let e=Vr().location.toLowerCase();return M0(e,Gd,"Current location dictionary")?e:"us"}var nl,Gd,$W,U0=I(()=>{"use strict";rl();nl=new Set,Gd={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"};$W=YL(ZL())});var F,VW,B0=I(()=>{"use strict";F={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"},VW={[F.USWest]:{geoName:"us",regionShortName:"wus"},[F.USCentral]:{geoName:"us",regionShortName:"cus"},[F.USEast]:{geoName:"us",regionShortName:"eus"},[F.USEast2]:{geoName:"us",regionShortName:"eus2"},[F.USWestCentral]:{geoName:"us",regionShortName:"wcus"},[F.USWest2]:{geoName:"us",regionShortName:"wus2"},[F.USSouthCentral]:{geoName:"br",regionShortName:"scus"},[F.BrazilSouth]:{geoName:"br",regionShortName:"sbr"},[F.UKSouth]:{geoName:"uk",regionShortName:"suk"},[F.UKWest]:{geoName:"uk",regionShortName:"wuk"},[F.JapanEast]:{geoName:"jp",regionShortName:"ejp"},[F.JapanWest]:{geoName:"jp",regionShortName:"wjp"},[F.IndiaCentral]:{geoName:"in",regionShortName:"cin"},[F.IndiaSouth]:{geoName:"in",regionShortName:"sin"},[F.ItalyNorth]:{geoName:"it",regionShortName:"nit"},[F.GermanyWestCentral]:{geoName:"de",regionShortName:"wcde"},[F.GermanyNorth]:{geoName:"de",regionShortName:"nde"},[F.EuropeNorth]:{geoName:"eu",regionShortName:"neu"},[F.EuropeWest]:{geoName:"eu",regionShortName:"weu"},[F.AustraliaEast]:{geoName:"au",regionShortName:"eau"},[F.AustraliaSouthEast]:{geoName:"au",regionShortName:"seau"},[F.AsiaSouthEast]:{geoName:"as",regionShortName:"seas"},[F.AsiaEast]:{geoName:"as",regionShortName:"eas"},[F.CanadaCentral]:{geoName:"ca",regionShortName:"cca"},[F.CanadaEast]:{geoName:"ca",regionShortName:"eca"},[F.SouthAfricaNorth]:{geoName:"za",regionShortName:"nza"},[F.SouthAfricaWest]:{geoName:"za",regionShortName:"wza"},[F.FranceCentral]:{geoName:"fr",regionShortName:"cfr"},[F.FranceSouth]:{geoName:"fr",regionShortName:"sfr"},[F.UAENorth]:{geoName:"ae",regionShortName:"nae"},[F.UAECentral]:{geoName:"ae",regionShortName:"cae"},[F.SwedenCentral]:{geoName:"se",regionShortName:"cse"},[F.SwitzerlandNorth]:{geoName:"ch",regionShortName:"nch"},[F.SwitzerlandWest]:{geoName:"ch",regionShortName:"wch"},[F.NorwayEast]:{geoName:"no",regionShortName:"eno"},[F.NorwayWest]:{geoName:"no",regionShortName:"wno"},[F.KoreaCentral]:{geoName:"kr",regionShortName:"ckr"},[F.KoreaSouth]:{geoName:"kr",regionShortName:"skr"},[F.SingaporeSouthEast]:{geoName:"sg",regionShortName:"seas"},[F.PolandCentral]:{geoName:"pl",regionShortName:"cpl"},[F.QatarCentral]:{geoName:"qa",regionShortName:"cqa"},[F.NewZealandNorth]:{geoName:"nz",regionShortName:"nnz"},[F.GovernmentUSTexas]:{geoName:"us",regionShortName:"ugtx"},[F.GovernmentUSVirginia]:{geoName:"us",regionShortName:"ugva"},[F.GovernmentUSDodCentral]:{regionShortName:"udc"},[F.GovernmentUSDodEast]:{regionShortName:"ude"},[F.ChinaEast]:{regionShortName:"cne"},[F.ChinaEast2]:{regionShortName:"cne2"},[F.ChinaEast3]:{regionShortName:"cne3"},[F.ChinaNorth]:{regionShortName:"cnn"},[F.ChinaNorth2]:{regionShortName:"cnn2"},[F.ChinaNorth3]:{regionShortName:"cnn3"},[F.UssecEast]:{geoName:"us",regionShortName:"erx"},[F.UssecWest]:{geoName:"us",regionShortName:"wrx"},[F.UsnatEast]:{geoName:"us",regionShortName:"eex"},[F.UsnatWest]:{geoName:"us",regionShortName:"wex"}}});var $0=I(()=>{"use strict";rl();});var lo=I(()=>{"use strict";rl();U0();B0();$0();});function uo(e,t){return q0?q0.isOverridden(e,t):{overridden:!1}}var q0,co=I(()=>{"use strict";});var zd=I(()=>{"use strict";lo();co();});function eF(e,t){let{region:r}=Vr();return()=>{let n=e.settings[t];if(n.allowOverrides){let s=uo(e.packageName,t);if(s.overridden)return typeof s.value=="string"?tF(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 tF(e){return isNaN(Number(e))?e==="true"?!0:e==="false"?!1:e:Number(e)}function rF(e){let t=e.packageName;if(il.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=>jd(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=>!ol(i))){let i=`error parsing settings config for package ${t}, setting ${r} has invalid region`;throw console.error(i),new Error(i)}})}function po(e){rF(e);let t={};return Object.keys(e.settings).forEach(r=>{t[r]={enumerable:!0,get:eF(e,r)}}),il.set(e.packageName,e),Object.defineProperties({},t)}function Wd(e,t){return il.has(e)?!!il.get(e).settings[t]:!1}var il,al=I(()=>{"use strict";lo();co();Hd();fo();il=new Map});function V0(e,t){let{region:r}=Vr();return()=>{let n=uo(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 nF(e){let t=e.packageName;if(sl.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=>Wd(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=>!ol(i))){let i=`error parsing feature gates config for package ${t}, feature ${r} has invalid region`;throw console.error(i),new Error(i)}})}function Qd(e){nF(e);let t={};Object.keys(e.features).forEach(i=>{t[i]={enumerable:!0,configurable:!0,get:V0(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:V0(e,a.toString())}}),Object.defineProperties(r,i),n.clear()}},sl.set(e.packageName,e),Object.defineProperties(r,t)}function jd(e,t){return sl.has(e)?!!sl.get(e).features[t]:!1}var sl,Hd=I(()=>{"use strict";lo();fo();co();al();sl=new Map});var z0=g((fj,G0)=>{"use strict";G0.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 H0=g(Jd=>{"use strict";var iF=Object.prototype.hasOwnProperty,aF;function W0(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch{return null}}function j0(e){try{return encodeURIComponent(e)}catch{return null}}function oF(e){for(var t=/([^=?#&]+)=?([^&]*)/g,r={},n;n=t.exec(e);){var i=W0(n[1]),a=W0(n[2]);i===null||a===null||i in r||(r[i]=a)}return r}function sF(e,t){t=t||"";var r=[],n,i;typeof t!="string"&&(t="?");for(i in e)if(iF.call(e,i)){if(n=e[i],!n&&(n===null||n===aF||isNaN(n))&&(n=""),i=j0(i),n=j0(n),i===null||n===null)continue;r.push(i+"="+n)}return r.length?t+r.join("&"):""}Jd.stringify=sF;Jd.parse=oF});var Yd=g((hj,Z0)=>{"use strict";var J0=z0(),ll=H0(),X0=/[\n\r\t]/g,lF=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,uF=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,cF=/^[a-zA-Z]:/,dF=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;function Kd(e){return(e||"").toString().replace(dF,"")}var Xd=[["#","hash"],["?","query"],function(t,r){return vr(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]],Q0={hash:1,query:1};function K0(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 yr(unescape(e.pathname),{});else if(i==="string"){n=new yr(e,{});for(a in Q0)delete n[a]}else if(i==="object"){for(a in e)a in Q0||(n[a]=e[a]);n.slashes===void 0&&(n.slashes=lF.test(e.href))}return n}function vr(e){return e==="file:"||e==="ftp:"||e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function Y0(e,t){e=Kd(e),e=e.replace(X0,""),t=t||{};var r=uF.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)):vr(n)?s=r[4]:n?i&&(s=s.slice(2)):o>=2&&vr(t.protocol)&&(s=r[4]),{protocol:n,slashes:i||vr(n),slashesCount:o,rest:s}}function pF(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 yr(e,t,r){if(e=Kd(e),e=e.replace(X0,""),!(this instanceof yr))return new yr(e,t,r);var n,i,a,o,s,l,u=Xd.slice(),c=typeof t,d=this,p=0;for(c!=="object"&&c!=="string"&&(r=t,t=null),r&&typeof r!="function"&&(r=ll.parse),t=K0(t),i=Y0(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||cF.test(e))||!i.slashes&&(i.protocol||i.slashesCount<2||!vr(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=pF(d.pathname,t.pathname)),d.pathname.charAt(0)!=="/"&&vr(d.protocol)&&(d.pathname="/"+d.pathname),J0(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:"&&vr(d.protocol)&&d.host?d.protocol+"//"+d.host:"null",d.href=d.toString()}function fF(e,t,r){var n=this;switch(e){case"query":typeof t=="string"&&t.length&&(t=(r||ll.parse)(t)),n[e]=t;break;case"port":n[e]=t,J0(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<Xd.length;o++){var s=Xd[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:"&&vr(n.protocol)&&n.host?n.protocol+"//"+n.host:"null",n.href=n.toString(),n}function mF(e){(!e||typeof e!="function")&&(e=ll.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||vr(r.protocol)?"//":"");return r.username?(a+=r.username,r.password&&(a+=":"+r.password),a+="@"):r.password?(a+=":"+r.password,a+="@"):r.protocol!=="file:"&&vr(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}yr.prototype={set:fF,toString:mF};yr.extractProtocol=Y0;yr.location=K0;yr.trimLeft=Kd;yr.qs=ll;Z0.exports=yr});var hF,ev=I(()=>{"use strict";hF=se(Yd());});function Zd(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 ul=I(()=>{"use strict";});var ep,tp,rp=I(()=>{"use strict";ul();ep=class{features=new Map;register(t,r){let n=Zd(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()}},tp=new ep});var np=I(()=>{"use strict";});function ol(e){return gF.has(e)}var gF,fo=I(()=>{"use strict";zd();Hd();al();co();zd();ev();rp();ul();np();gF=new Set(["tie","test","prod","preview","preprod","gov","high","dod","mooncake","ex","rx"])});var vF,tv=I(()=>{"use strict";fo();vF=po({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 cl,O,k,Wn,Li,dl,rv,nv,ip,mo=I(()=>{"use strict";so();cl=class{name;constructor(t){this.name=t}toString(){return this.name}getName(){return this.name}getDisplayNameResourceKey(){return ip.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"})(O||(O={}));(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"})(k||(k={}));Wn=class extends cl{constructor(t){super(t)}static get None(){return"None"}static get SystemRequired(){return"SystemRequired"}static get ApplicationRequired(){return"ApplicationRequired"}static get Recommended(){return"Recommended"}},Li=class e extends cl{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?dl.Persistent:parseInt(dl[this.name])}};(function(e){e[e.Persistent=0]="Persistent",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup"})(dl||(dl={}));(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"})(rv||(rv={}));(function(e){e[e.Attribute=0]="Attribute",e[e.Organization=1]="Organization",e[e.Currency=2]="Currency"})(nv||(nv={}));ip=class e{static resourceKeyMap=e.initResourceKeyMap();static initResourceKeyMap(){let t=new Oi;return t.add(O.TwoOptions,"SystemCustomization.type.bit.label"),t.add(O.Customer,"SystemCustomization.type.customer.label"),t.add(O.CustomerType,"SystemCustomization.type.customer.label"),t.add(O.DateTime,"SystemCustomization.type.datetime.label"),t.add(O.DecimalNumber,"SystemCustomization.type.decimal.label"),t.add(O.FloatingPointNumber,"SystemCustomization.type.float.label"),t.add(O.WholeNumber,"SystemCustomization.type.int.label"),t.add(O.LookupType,"SystemCustomization.type.lookup.label"),t.add(O.Lookup,"SystemCustomization.type.lookup.label"),t.add(O.MultipleLineofText,"SystemCustomization.type.ntext.label"),t.add(O.Currency,"SystemCustomization.type.money.label"),t.add(O.Owner,"SystemCustomization.type.owner.label"),t.add(O.OwnerType,"SystemCustomization.type.owner.label"),t.add(O.PartyList,"SystemCustomization.type.partylist.label"),t.add(O.PartyListType,"SystemCustomization.type.partylist.label"),t.add(O.OptionSet,"SystemCustomization.type.picklist.label"),t.add(O.State,"SystemCustomization.type.state.label"),t.add(O.Status,"SystemCustomization.type.status.label"),t.add(O.SingleLineofText,"SystemCustomization.type.nvarchar.label"),t.add(O.UniqueIdentifier,"SystemCustomization.type.uniqueidentifier.label"),t.add(O.UniqueIdentifierType,"SystemCustomization.type.uniqueidentifiertype.label"),t.add(O.CalendarRulesType,"SystemCustomization.type.calendarrules.label"),t.add(O.VirtualType,"SystemCustomization.type.virtual.label"),t.add(O.BigInt,"SystemCustomization.type.bigint.label"),t.add(O.ManagedPropertyType,"SystemCustomization.type.managedproperty.label"),t.add(O.EntityNameType,"SystemCustomization.type.entityname.label"),t.add(O.Image,"SystemCustomization.type.image.label"),t.add(O.MultiSelectOptionSet,"SystemCustomization.type.multiselectpicklist.label"),t.add(O.PrimaryNameAttributeType,"SystemCustomization.type.primaryname.label"),t.add(O.LookupType,"SystemCustomization.type.lookuptype.label"),t.add(O.Subject,"SystemCustomization.type.subject.label"),t.add(k.Email,"SystemCustomization.String.Format.email"),t.add(k.Text,"SystemCustomization.String.Format.text"),t.add(k.TextArea,"SystemCustomization.String.Format.textarea"),t.add(k.Url,"SystemCustomization.String.Format.url"),t.add(k.TickerSymbol,"SystemCustomization.String.Format.tickersymbol"),t.add(k.PhoneticGuide,"SystemCustomization.String.Format.phoneticguide"),t.add(k.VersionNumber,"SystemCustomization.String.Format.versionnumber"),t.add(k.Phone,"SystemCustomization.String.Format.phone"),t.add(k.None,"SystemCustomization.Integer.Format."),t.add(k.Duration,"SystemCustomization.Integer.Format.duration"),t.add(k.TimeZone,"SystemCustomization.Integer.Format.timezone"),t.add(k.Language,"SystemCustomization.Integer.Format.language"),t.add(k.Locale,"SystemCustomization.Integer.Format.language"),t.add(k.DateOnly,"SystemCustomization.DateTime.Format.date"),t.add(k.DateAndTime,"SystemCustomization.DateTime.Format.datetime"),t.add(k.Regarding,"SystemCustomization.Lookup.Format.regarding"),t.add(Li.Persistent,"SystemCustomization.String.Source.persistent"),t.add(Li.Calculated,"SystemCustomization.String.Source.calculated"),t.add(Li.Rollup,"SystemCustomization.String.Source.rollup"),t.add(Li.None,"SystemCustomization.String.Source.none"),t}static getDisplayNameResourceKey(t){return e.resourceKeyMap.getValue(t)}}});var sv,op,Fi,jn,ap,pl,ki,Gr,ge,iv,av,ov,er=I(()=>{"use strict";sv={ThreeEqColumn_FirstColumn:34,ThreeEqColumn_SecondColumn:33,ThreeEqColumn_ThirdColumn:33,FiveEqColumn:20},op={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"})(Fi||(Fi={}));(function(e){e.Left="Left",e.Right="Right",e.Center="Center"})(jn||(jn={}));(function(e){e[e.Mobile=0]="Mobile",e[e.Tablet=1]="Tablet",e[e.Web=2]="Web"})(ap||(ap={}));pl=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"})(ki||(ki={}));Gr=class{static StartTag="<"},ge={ShowLabel:"true",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_",labelAlignment:jn.Left,labelPosition:ki.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"})(iv||(iv={}));(function(e){e.TabWithLockedFieldRemoval="TabWithLockedFieldRemoval",e.SectionWithLockedFieldRemoval="SectionWithLockedFieldRemoval",e.LockedSectionRemoval="LockedSectionRemoval",e.LockedFieldRemoval="LockedFieldRemoval",e.RequiredFieldRemoval="RequiredFieldRemoval",e.LastRemainingTab="LastRemainingTab",e.UnknownRemoval="UnknownRemoval"})(av||(av={}));(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"})(ov||(ov={}))});var fn=g(C=>{"use strict";Object.defineProperty(C,"__esModule",{value:!0});C.DateTimeBehavior=C.PrecisionSource=C.StringFormatName=C.SourceType=C.ImeMode=C.SolutionEntityTypeCodeExtToComponentTypeCode=C.SolutionComponentTypeCodeToEntityTypeCodeExt=C.SolutionComponentVirtualAttributeSubtype=C.EntityTypeCode=C.SolutionComponentTypeCodeExt=C.RootComponentBehavior=C.SolutionComponentTypeCode=C.EntityKeyIndexStatus=C.ViewStateCode=C.ViewStatusCode=C.RelationshipSecurityTypes=C.CascadeType=C.RelationshipTypeExt=C.RelationshipType=C.AppSubType=C.BusinessProcessType=C.WorkflowCategory=C.WorkflowScope=C.WorkflowTypeCode=C.StatusCodeEnabledDisabled=C.StateCodeEnabledDisabled=C.StatusCode=C.StateCode=C.OptionSetType=C.AttributeTypeCodeNum=C.AttributeFormatName=C.AttributeFormatCode=C.AttributeTypeName=C.AttributeTypeCode=C.PluginSourceType=C.AuthType=C.PluginIsolationMode=C.ComponentState=C.ChartType=C.ChartsType=C.ViewType=C.AttributeType=C.ActivationState=C.FormPresentation=C.FormType=C.TableTypeCode=C.TableTypes=C.ActivityTypeMask=C.PrincipalType=C.OwnershipTypes=void 0;C.QueryType=C.KnownCustomSolutionComponentEntitySetName=C.TeamTypeEnum=C.EnvironmentVariableDefinitionTypeEnum=C.ConnectorTypeEnum=C.RoleInheritance=C.DefaultRoleTemplates=C.DeleteDependencyErrorCode=C.ServiceEndpointConnectionMode=C.ServiceEndpointContract=C.ServiceNamespaceFormat=C.ConnectionRoleCategory=C.ReportTypeCode=C.SdkMessageProcessingMode=C.SupportedDeployment=C.SdkMessageProcessingStage=C.WebResourceTypeCode=C.IntegerFormat=C.DateTimeFormat=void 0;var lv;(function(e){e.None="None",e.UserOwned="UserOwned",e.TeamOwned="TeamOwned",e.BusinessOwned="BusinessOwned",e.OrganizationOwned="OrganizationOwned",e.BusinessParented="BusinessParented",e.Filtered="Filtered"})(lv||(C.OwnershipTypes=lv={}));var uv;(function(e){e.User="Microsoft.Dynamics.CRM.systemuser",e.Team="Microsoft.Dynamics.CRM.team"})(uv||(C.PrincipalType=uv={}));var cv;(function(e){e[e.DoNotDisplayInActivityMenus=0]="DoNotDisplayInActivityMenus",e[e.DisplayInActivityMenus=1]="DisplayInActivityMenus"})(cv||(C.ActivityTypeMask=cv={}));var dv;(function(e){e.Activity="Activity",e.Virtual="Virtual",e.Standard="Standard",e.Elastic="Elastic"})(dv||(C.TableTypes=dv={}));var pv;(function(e){e.Standard="Standard",e.Virtual="Virtual",e.Elastic="Elastic"})(pv||(C.TableTypeCode=pv={}));var fv;(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"})(fv||(C.FormType=fv={}));var mv;(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(mv||(C.FormPresentation=mv={}));var hv;(function(e){e[e.Inactive=0]="Inactive",e[e.Active=1]="Active"})(hv||(C.ActivationState=hv={}));var gv;(function(e){e[e.String=0]="String",e[e.Number=1]="Number",e[e.Picklist=2]="Picklist"})(gv||(C.AttributeType=gv={}));var vv;(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"})(vv||(C.ViewType=vv={}));var yv;(function(e){e[e.ASPChart=0]="ASPChart",e[e.PowerBI=1]="PowerBI"})(yv||(C.ChartsType=yv={}));var bv;(function(e){e[e.DataAndInteractionCentric=0]="DataAndInteractionCentric",e[e.InteractionCentric=1]="InteractionCentric"})(bv||(C.ChartType=bv={}));var wv;(function(e){e[e.Published=0]="Published",e[e.Unpublished=1]="Unpublished",e[e.Deleted=2]="Deleted",e[e.DeletedUnpublished=3]="DeletedUnpublished"})(wv||(C.ComponentState=wv={}));var Av;(function(e){e[e.None=1]="None",e[e.Sandbox=2]="Sandbox",e[e.External=3]="External"})(Av||(C.PluginIsolationMode=Av={}));var Cv;(function(e){e[e.BasicAuth=0]="BasicAuth"})(Cv||(C.AuthType=Cv={}));var Sv;(function(e){e[e.Database=0]="Database",e[e.Disk=1]="Disk",e[e.Normal=2]="Normal",e[e.AzureWebApp=3]="AzureWebApp"})(Sv||(C.PluginSourceType=Sv={}));var Nv;(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"})(Nv||(C.AttributeTypeCode=Nv={}));var Ev;(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"})(Ev||(C.AttributeTypeName=Ev={}));var Dv;(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"})(Dv||(C.AttributeFormatCode=Dv={}));var Iv;(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"})(Iv||(C.AttributeFormatName=Iv={}));var _v;(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"})(_v||(C.AttributeTypeCodeNum=_v={}));var Pv;(function(e){e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean"})(Pv||(C.OptionSetType=Pv={}));var Tv;(function(e){e[e.Draft=0]="Draft",e[e.Activated=1]="Activated"})(Tv||(C.StateCode=Tv={}));var Ov;(function(e){e[e.Draft=1]="Draft",e[e.Activated=2]="Activated"})(Ov||(C.StatusCode=Ov={}));var xv;(function(e){e[e.Enabled=0]="Enabled",e[e.Disabled=1]="Disabled"})(xv||(C.StateCodeEnabledDisabled=xv={}));var Rv;(function(e){e[e.Enabled=1]="Enabled",e[e.Disabled=2]="Disabled"})(Rv||(C.StatusCodeEnabledDisabled=Rv={}));var Lv;(function(e){e[e.Definition=1]="Definition",e[e.Activation=2]="Activation",e[e.Template=3]="Template"})(Lv||(C.WorkflowTypeCode=Lv={}));var Fv;(function(e){e[e.User=1]="User",e[e.BusinessUnit=2]="BusinessUnit",e[e.ParentChildBusinessUnit=3]="ParentChildBusinessUnit",e[e.Organization=4]="Organization"})(Fv||(C.WorkflowScope=Fv={}));var kv;(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"})(kv||(C.WorkflowCategory=kv={}));var Mv;(function(e){e[e.None=-1]="None",e[e.BusinessFlow=0]="BusinessFlow",e[e.TaskFlow=1]="TaskFlow"})(Mv||(C.BusinessProcessType=Mv={}));var Uv;(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"})(Uv||(C.AppSubType=Uv={}));var Bv;(function(e){e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(Bv||(C.RelationshipType=Bv={}));var $v;(function(e){e.ManyToOneRelationship="ManyToOneRelationship",e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})($v||(C.RelationshipTypeExt=$v={}));var qv;(function(e){e.NoCascade="NoCascade",e.Cascade="Cascade",e.Active="Active",e.UserOwned="UserOwned",e.RemoveLink="RemoveLink",e.Restrict="Restrict"})(qv||(C.CascadeType=qv={}));var Vv;(function(e){e.None="None",e.Append="Append",e.ParentChild="ParentChild",e.Pointer="Pointer",e.Inheritance="Inheritance"})(Vv||(C.RelationshipSecurityTypes=Vv={}));var Gv;(function(e){e[e.Active=1]="Active",e[e.Inactive=2]="Inactive"})(Gv||(C.ViewStatusCode=Gv={}));var zv;(function(e){e[e.Active=0]="Active",e[e.Inactive=1]="Inactive"})(zv||(C.ViewStateCode=zv={}));var Wv;(function(e){e.Active="Active",e.Failed="Failed",e.InProgress="InProgress",e.Pending="Pending"})(Wv||(C.EntityKeyIndexStatus=Wv={}));var jv;(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"})(jv||(C.SolutionComponentTypeCode=jv={}));var Hv;(function(e){e[e.IncludeSubcomponents=0]="IncludeSubcomponents",e[e.DoNotIncludeSubcomponents=1]="DoNotIncludeSubcomponents",e[e.IncludeAsShellOnly=2]="IncludeAsShellOnly"})(Hv||(C.RootComponentBehavior=Hv={}));var fl;(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"})(fl||(C.SolutionComponentTypeCodeExt=fl={}));var ml;(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"})(ml||(C.EntityTypeCode=ml={}));var Qv;(function(e){e.MultiSelectPicklist="MultiSelectPicklist",e.File="File",e.Image="Image"})(Qv||(C.SolutionComponentVirtualAttributeSubtype=Qv={}));function yF(e){let t=fl[e];return ml[t]}C.SolutionComponentTypeCodeToEntityTypeCodeExt=yF;function bF(e){let t=ml[e];return fl[t]}C.SolutionEntityTypeCodeExtToComponentTypeCode=bF;var Jv;(function(e){e.Active="Active",e.Auto="Auto",e.Disabled="Disabled",e.Inactive="Inactive"})(Jv||(C.ImeMode=Jv={}));var Xv;(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"})(Xv||(C.SourceType=Xv={}));var Kv;(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"})(Kv||(C.StringFormatName=Kv={}));var Yv;(function(e){e[e.PrecisionProperty=0]="PrecisionProperty",e[e.Organization=1]="Organization",e[e.TransactionCurrency=2]="TransactionCurrency"})(Yv||(C.PrecisionSource=Yv={}));var Zv;(function(e){e.UserLocal="UserLocal",e.DateOnly="DateOnly",e.TimeZoneIndependent="TimeZoneIndependent"})(Zv||(C.DateTimeBehavior=Zv={}));var ey;(function(e){e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(ey||(C.DateTimeFormat=ey={}));var ty;(function(e){e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(ty||(C.IntegerFormat=ty={}));var ry;(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"})(ry||(C.WebResourceTypeCode=ry={}));var ny;(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"})(ny||(C.SdkMessageProcessingStage=ny={}));var iy;(function(e){e[e.ServerOnly=0]="ServerOnly",e[e.OutlookClientOnly=1]="OutlookClientOnly",e[e.Both=2]="Both"})(iy||(C.SupportedDeployment=iy={}));var ay;(function(e){e[e.Synchronous=0]="Synchronous",e[e.Asynchronous=1]="Asynchronous"})(ay||(C.SdkMessageProcessingMode=ay={}));var oy;(function(e){e[e.ReportingServicesReport=1]="ReportingServicesReport",e[e.OtherReport=2]="OtherReport",e[e.LinkedReport=3]="LinkedReport"})(oy||(C.ReportTypeCode=oy={}));var sy;(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"})(sy||(C.ConnectionRoleCategory=sy={}));var ly;(function(e){e[e.Name=1]="Name",e[e.Address=2]="Address"})(ly||(C.ServiceNamespaceFormat=ly={}));var uy;(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"})(uy||(C.ServiceEndpointContract=uy={}));var cy;(function(e){e[e.Normal=1]="Normal",e[e.Federated=2]="Federated"})(cy||(C.ServiceEndpointConnectionMode=cy={}));var dy;(function(e){e.CannotDeleteInUseComponent="0x8004f01f",e.CannotDeleteInUseAttribute="0x80048418",e.CannotDeleteInUseOptionSet="0x80048417",e.CannotDeleteInUseEntity="0x80048420",e.CannotUninstallWithDependencies="0x8004F01D"})(dy||(C.DeleteDependencyErrorCode=dy={}));var py;(function(e){e.SystemAdministrator="627090FF-40A3-4053-8790-584EDC5BE201",e.SystemCustomizer="119F245C-3CC8-4B62-B31C-D1A046CED15D"})(py||(C.DefaultRoleTemplates=py={}));var fy;(function(e){e[e.DefaultTeamPrivilege=0]="DefaultTeamPrivilege",e[e.DirectUserAndTeamPrivilege=1]="DirectUserAndTeamPrivilege"})(fy||(C.RoleInheritance=fy={}));var my;(function(e){e[e.NotSpecified=0]="NotSpecified",e[e.CustomConnector=1]="CustomConnector"})(my||(C.ConnectorTypeEnum=my={}));var hy;(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"})(hy||(C.EnvironmentVariableDefinitionTypeEnum=hy={}));var gy;(function(e){e[e.Owner=0]="Owner",e[e.Access=1]="Access",e[e.AADSecurityGroup=2]="AADSecurityGroup",e[e.AADOfficeGroup=3]="AADOfficeGroup"})(gy||(C.TeamTypeEnum=gy={}));var vy;(function(e){e.Bots="bots"})(vy||(C.KnownCustomSolutionComponentEntitySetName=vy={}));var yy;(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"})(yy||(C.QueryType=yy={}))});var sp,by=I(()=>{"use strict";(function(e){e.DefaultValue="defaultValue",e.Loaded="loaded"})(sp||(sp={}))});var Cy,wF,wy,mH,hH,ho,Ay,gH,vH,Sy=I(()=>{"use strict";Cy=se(Vn());Pe();Ti();tv();mo();er();Ri();J();wF=se(fn());by();(function(e){e.Model="Model",e.Canvas="Canvas",e.CustomPages="CustomPages"})(wy||(wy={}));mH={Read:zn.Read,Edit:zn.Edit,Both:zn.Both,Container:zn.Container},hH={input:xi.Input,bound:xi.Bound,output:xi.Output};(function(e){e[e.dataset=0]="dataset",e[e.property=1]="property",e[e.groups=2]="groups",e[e.group=3]="group"})(ho||(ho={}));(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"})(Ay||(Ay={}));gH=new Set([_.Currency,_.Decimal,_.FP,_.Multiple,_.SingleLineEmail,_.SingleLinePhone,_.SingleLineText,_.SingleLineTextArea,_.SingleLineURL,_.SingleLineTickerSymbol,_.WholeNone,_.WholeDuration,_.WholeLanguage,_.WholeTimeZone,_.Enum,_.LookupSimple,_.LookupCustomer,_.LookupOwner,_.LookupPartyList,_.LookupRegarding,_.TwoOptions,_.Boolean,_.PowerBIReport,_.DateAndTimeDateAndTime,_.DateAndTimeDateOnly,_.OptionSet,_.MultiSelectOptionSet,_.CardForm]),vH={numbers:[_.WholeNone,_.FP,_.Decimal,_.Currency],text:[_.SingleLineText,_.SingleLineTextArea,_.Multiple],lookup:[_.LookupSimple,_.LookupCustomer,_.LookupOwner,_.LookupPartyList,_.LookupRegarding],dates:[_.DateAndTimeDateOnly,_.DateAndTimeDateAndTime],allFields:[_.TwoOptions,_.DateAndTimeDateOnly,_.DateAndTimeDateAndTime,_.FP,_.Decimal,_.WholeNone,_.WholeDuration,_.WholeTimeZone,_.WholeLanguage,_.LookupSimple,_.LookupCustomer,_.LookupOwner,_.LookupPartyList,_.LookupRegarding,_.Multiple,_.OptionSet,_.SingleLineText,_.SingleLineTextArea,_.SingleLineEmail,_.SingleLineURL,_.SingleLineTickerSymbol,_.SingleLinePhone]}});var tr,hl,Ny=I(()=>{"use strict";tr=se(Vn());xe();Pe();rt();Ti();Ri();Sy();mo();J();Ge();er();hl=class extends W{constructor(t){super(v.customControl,t)}customControlId;get id(){let t=this.getProperty(m.id);return N.IsNullOrUndefined(t)?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new P(t.substr(1,t.length-2)):new P(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(lt.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===lt.name)?.value}getParameterChildrenValues(t,r,n){if(this.isDataSet(t)){let i=r.find(u=>u.key===lt.name)?.value,a={Name:i,Type:_.Grid,Columns:[]},l=this.getParameters().get(lt.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===m.static&&a.value==="true"){r=!0;break}}return r}get name(){return this.getProperty(m.Name)}get formFactor(){return this.getProperty(m.formFactor)}set formFactor(t){this.setProperty(m.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(Gr.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:k0.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===ho.dataset?a.get(lt.dataset)?.some(f=>this.getDatasetName(f)===d)||r.push({Name:d,Value:{Name:d,Columns:[],Type:_.Grid}}):c.propertyType===ho.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,tr.trackInfoTrace)(ot,{eventName:`${qr}/parametersToJSON`,eventData:{message:`Configuration metadata for custom control parameter ${o} is not available for custom control : ${this.name}.`}}),r=[];break}}}else(0,tr.trackErrorTrace)(ot,{eventName:`${qr}/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,tr.trackErrorTrace)(ot,{eventName:`${qr}/parametersToJSON`,eventData:{message:"Custom Control Manifest not found"}},new Error(`No custom control manifest found for ${this.name}`))}catch(n){(0,tr.trackErrorTrace)(ot,{eventName:`${qr}/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===lt.name)?.value;if(a)return this.getParameterChildrenValues(t,r);{let s=new Error(`No dataset manifest info for ${o}`);(0,tr.trackErrorTrace)(ot,{eventName:`${qr}/parameterJSON`,eventData:{message:"Missing custom control manifest dataset info"}},s)}}else{let a=n,o=r&&r.find(l=>l.key===m.Type),s=a&&!a.ofTypeGroup.every(l=>!qd.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===pn.FormComponent){let d=this.getFormComponentValueByParameterName(m.bindAttribute),p=await i.formModelService.loadLookupModel(d),f=p.lookupColumn,h=this.getLookupDataTypeFromAttributeMetadata(f);return{Name:t,Type:h,Usage:l,Static:u,Primary:c,EntityName:p.primaryTableName,Value:d,ViewId:this.getFormComponentValueByParameterName(F0.DefaultViewId),TargetEntityType:f.targets[0],FilterRelationshipName:this.getFormComponentValueByParameterName(m.FilterRelationshipName),AvailableViewIds:this.getFormComponentValueByParameterName(m.AvailableViewIds),DependentAttributeName:this.getFormComponentValueByParameterName(m.DependentAttributeName),DependentAttributeType:this.getFormComponentValueByParameterName(m.DependentAttributeType),AllowFilterOff:T.IsStrictTrue(this.getFormComponentValueByParameterName(m.AllowFilterOff)),DisableQuickFind:T.IsStrictTrue(this.getFormComponentValueByParameterName(m.DisableQuickFind)),EnableViewPicker:!T.IsStrictTrue(this.getFormComponentValueByParameterName(m.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,tr.trackErrorTrace)(ot,{eventName:`${qr}/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,tr.trackErrorTrace)(ot,{eventName:`${qr}/parameterJSON`,eventData:{message:"Missing property type info"}},p)}else{let l=new Error(`No property manifest info for ${t}`);(0,tr.trackWarningTrace)(ot,{eventName:`${qr}/parameterJSON`,eventData:{message:"Missing custom control manifest property info"}},l)}}return null}getLookupDataTypeFromAttributeMetadata(t){let{attributeType:r,format:n}=t;switch(r){case O.Customer:return _.LookupCustomer;case O.Owner:return _.LookupOwner;case O.PartyList:return _.LookupPartyList;default:return n===k.Regarding?_.LookupRegarding:_.LookupSimple}}isLookupType(t){return qd.includes(t)}isNumberTypeProperty(t,r){return Vd.includes(r)||t.ofTypeGroup.some(n=>Vd.includes(n))}isDataSet(t){return lt.dataset===t}isGroups(t){return!!t[0].getAllProperties().find(n=>n.key==="isGroup"&&n.value==="true")}}});var q,lp=I(()=>{"use strict";q=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 x,Mi,Le,gl=I(()=>{"use strict";xe();so();Pe();rt();mo();qn();lp();er();x=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"}},Mi=class{static get RelationshipAssistant(){return"3ff9a528-dd50-4aca-8f10-2e5ed73513ad"}static get PredictiveLeadScoring(){return"6f503f2a-d033-4106-b62c-f8f2e5f01a57"}},Le=class e{static FieldControlIds=e.initializeFieldControls();static UnboundControlIds=e.initializeUnboundControls();static ControlsAllowedForReferencePanel=e.initializeReferencePanelControls();static ControlsAllowedForFooter=e.initializeFooterControls();static CustomControlIdMap=new st;static initializeFieldControls(){let t=new st,r=e.getControlName(O.SingleLineofText,k.Phone);t.add(r,new P(x.PhoneNumberControl));let n=e.getControlName(O.SingleLineofText,k.TextArea);t.add(n,new P(x.TextAreaControl));let i=e.getControlName(O.SingleLineofText,k.Text);t.add(i,new P(x.TextBoxControl));let a=e.getControlName(O.SingleLineofText,k.Email);t.add(a,new P(x.EmailAddressControl));let o=e.getControlName(O.SingleLineofText,k.Url);t.add(o,new P(x.UrlControl));let s=e.getControlName(O.SingleLineofText,k.TickerSymbol);t.add(s,new P(x.TickerControl));let l=e.getControlName(O.SingleLineofText,k.PhoneticGuide);t.add(l,new P(x.TextBoxControl));let u=e.getControlName(O.WholeNumber,k.Duration);t.add(u,new P(x.DurationControl));let c=e.getControlName(O.WholeNumber,k.Language);t.add(c,new P(x.LanguagePickerControl));let d=e.getControlName(O.WholeNumber,k.TimeZone);t.add(d,new P(x.TimeZonePicklistControl));let p=e.getControlName(O.WholeNumber,k.None);t.add(p,new P(x.IntegerControl));let f=e.getControlName(O.DateTime,k.DateOnly);t.add(f,new P(x.DateTimeControl));let h=e.getControlName(O.DateTime,k.DateAndTime);t.add(h,new P(x.DateTimeControl));let b=e.getControlName(O.LookupType,k.None);t.add(b,new P(x.LookupControl));let w=e.getControlName(O.CustomerType,k.None);t.add(w,new P(x.LookupControl));let E=e.getControlName(O.FloatingPointNumber,k.None);t.add(E,new P(x.FloatControl));let D=e.getControlName(O.DecimalNumber,k.None);t.add(D,new P(x.DecimalControl));let L=e.getControlName(O.Currency,k.None);t.add(L,new P(x.MoneyControl));let R=e.getControlName(O.MultipleLineofText,k.None);t.add(R,new P(x.TextAreaControl));let B=e.getControlName(O.MultipleLineofText,k.Text);t.add(B,new P(x.TextAreaControl));let V=e.getControlName(O.MultipleLineofText,k.TextArea);t.add(V,new P(x.TextAreaControl));let M=e.getControlName(O.MultipleLineofText,k.Email);t.add(M,new P(x.EmailBodyControl));let $=e.getControlName(O.OptionSet,k.None);t.add($,new P(x.PicklistControl));let G=e.getControlName(O.TwoOptions,k.None);t.add(G,new P(x.RadioControl));let X=e.getControlName(O.Image,k.None);t.add(X,new P(x.WebResourceImageControl));let U=e.getControlName(O.Image,k.None);t.add(U,new P(x.WebResourceHtmlControl));let Oe=e.getControlName(O.TwoOptions,"Radio");t.add(Oe,new P(x.RadioControl));let me=e.getControlName(O.TwoOptions,"CheckBox");t.add(me,new P(x.CheckBoxControl));let Ue=e.getControlName(O.TwoOptions,"List");t.add(Ue,new P(x.PicklistControl));let He=e.getControlName(O.State,k.None);t.add(He,new P(x.PicklistControl));let ue=e.getControlName(O.Status,k.None);t.add(ue,new P(x.PicklistStatusControl));let ft=e.getControlName(O.OwnerType,k.None);t.add(ft,new P(x.LookupControl));let Yu=e.getControlName(O.PartyListType,k.None);t.add(Yu,new P(x.PartyListControl));let P1=e.getControlName(O.LookupType,k.Regarding);t.add(P1,new P(x.RegardingControl));let T1=e.getControlName(O.MultiSelectOptionSet,k.None);return t.add(T1,new P(x.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(!N.IsNullOrEmptyGuid(t)){let r=e.getTypeAndFormatByControlOrUniqueId(t.guidString.toLowerCase());return r=N.IsNullOrUndefined(r)?e.getUnboundControlNameFromIdentifier(t):r.substring(0,r.indexOf("_")),r}return null}static isCustomControl(t){return N.IsNullOrUndefined(t.control)||N.IsNullOrUndefined(t.control.ClassId)||t.control.ClassId.guidString===x.CustomControl}static initializeUnboundControls(){let t=new st;return t.add(x.ACIControl,q.ACIControl),t.add(x.IframeControl,q.IframeControl),t.add(x.SearchWidgetControl,q.SearchWidgetControl),t.add(x.MapsControl,q.MapsControl),t.add(x.QuickFormCollectionControl,q.QuickFormCollectionControl),t.add(x.GridControl,q.SubGridControl),t.add(x.WebResourceImageControl,q.WebResourceImageControl),t.add(x.WebResourceHtmlControl,q.WebResourceHtmlControl),t.add(x.ReferencePanelSearchWidget,q.SearchWidgetControl),t.add(x.ReferencePanelQuickFormCollectionControl,q.QuickFormCollectionControl),t.add(x.ReferencePanelSubgridControl,q.SubGridControl),t.add(x.TimerControl,q.TimerControl),t.add(x.TimeLineControl,q.NotesControl),t.add(x.TimeLineControlUC,q.NotesControl),t.add(x.SocialInsightControl,q.SocialInsightControl),t.add(Mi.RelationshipAssistant,q.CustomControl),t}static initializeReferencePanelControls(){let t=new st;return t.add(x.IframeControl,q.IframeControl),t.add(x.ReferencePanelSearchWidget,q.SearchWidgetControl),t.add(x.ReferencePanelQuickFormCollectionControl,q.QuickFormCollectionControl),t.add(x.ReferencePanelSubgridControl,q.SubGridControl),t.add(x.WebResourceHtmlControl,q.WebResourceHtmlControl),t.add(x.WebResourceImageControl,q.WebResourceHtmlControl),t}static initializeFooterControls(){let t=new Oi;return t.add(Fi.IFRAME,!0),t.add(Fi.SPACER,!0),t.add(Fi.WEB_RESOURCE_HTML,!0),t}static isUnboundFormControl(t){if(N.IsNullOrUndefined(t)||N.IsNullOrUndefined(t.control)||N.IsNullOrUndefined(t.control.ClassId))return!1;let r=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.containsKey(r.guidString)}static isReferencePanelSection(t){return!N.IsNullOrUndefined(t)&&!N.IsNullOrUndefined(t.Name)&&t.Name.indexOf(ge.referencePanelNamePrefix)===0}static isUnboundFormControlByIdentifier(t){return N.IsNullOrUndefined(t)||N.IsNullOrUndefined(t.guidString)?!1:e.UnboundControlIds.containsKey(t.guidString)}static getUnboundFormControlName(t){let r=T.EmptyString;if(N.IsNullOrUndefined(t)||N.IsNullOrUndefined(t.control)||N.IsNullOrUndefined(t.control.ClassId))return r;let n=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.getValue(n.guidString).toString()}static getUnboundControlNameFromIdentifier(t){return N.IsNullOrUndefined(t)||N.IsNullOrUndefined(t.guidString)?T.EmptyString:e.UnboundControlIds.getValue(t.guidString).toString()}static isSpacerControl(t){return t===x.SpacerControl}static GetRowSpan(t){let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===x.CustomControl&&!N.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}switch(e.UnboundControlIds.getValue(r.guidString)){case q.IframeControl:case q.ACIControl:case q.SocialInsightControl:return 6;case q.SubGridControl:case q.CustomControl:return 4;case q.WebResourceImageControl:return 15;case q.WebResourceHtmlControl:return 15;case q.MapsControl:return 8;case q.SearchWidgetControl:return 10;case q.NotesControl:case q.TimeLineControl:return 15;case q.TimerControl:return 2;default:}}static isLookUpControl(t){return!N.IsNullOrUndefined(t)&&t.ClassId.guidString===x.LookupControl}static isRelationshipAssistantOrLeadScoringControl(t){return!N.IsNullOrUndefined(t)&&e.isRelationshipAssistantOrLeadScoring(t.UniqueId)}static isRelationshipAssistantOrLeadScoring(t){return!N.IsNullOrUndefined(t)&&(t.guidString===Mi.RelationshipAssistant||t.guidString===Mi.PredictiveLeadScoring)}static isRelationshipAssistantControl(t){return!N.IsNullOrUndefined(t)&&e.isRelationshipAssistant(t.UniqueId)}static isRelationshipAssistant(t){return!N.IsNullOrUndefined(t)&&t.guidString===Mi.RelationshipAssistant}static getUniqueIdentifierForControl(t){if(N.IsNullOrUndefined(t))return null;let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===x.CustomControl&&!N.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}return r}}});var vl,Ey=I(()=>{"use strict";vl=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 Hn,Ui,Dy,Iy,mn,_y,Py,up=I(()=>{"use strict";(function(e){e[e.Center=0]="Center",e[e.Left=1]="Left",e[e.Right=2]="Right"})(Hn||(Hn={}));(function(e){e[e.Left=0]="Left",e[e.Top=1]="Top"})(Ui||(Ui={}));(function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle"})(Dy||(Dy={}));(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"})(Iy||(Iy={}));(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"})(mn||(mn={}));(function(e){e[e.None=0]="None",e[e.SystemRequired=1]="SystemRequired",e[e.ApplicationRequired=2]="ApplicationRequired",e[e.Recommended=3]="Recommended"})(_y||(_y={}));(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"})(Py||(Py={}))});var Bi,Ty=I(()=>{"use strict";fo();Bi=Qd({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 Oy(e){return{...e,extractConfig:t=>AF(t,Object.keys(e.fallback))}}function AF(e,t){let r={};for(let n of t)typeof e[n]<"u"&&(r[n]=e[n]);return r}var cp=I(()=>{"use strict";});var dp=g((WH,Ry)=>{var go=new Proxy(function(){return go},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:go},apply:function(){return go},construct:function(){return{}}}),xy=function(){return go};Object.setPrototypeOf(xy,go);Ry.exports=xy});var ky=g((jH,Fy)=>{var vo=new Proxy(function(){return vo},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:vo},apply:function(){return vo},construct:function(){return{}}}),Ly=function(){return vo};Object.setPrototypeOf(Ly,vo);Fy.exports=Ly});var pp=g((HH,Uy)=>{var yo=new Proxy(function(){return yo},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:yo},apply:function(){return yo},construct:function(){return{}}}),My=function(){return yo};Object.setPrototypeOf(My,yo);Uy.exports=My});var $y=g((QH,By)=>{function CF(){this.__data__=[],this.size=0}By.exports=CF});var $i=g((JH,qy)=>{function SF(e,t){return e===t||e!==e&&t!==t}qy.exports=SF});var bo=g((XH,Vy)=>{var NF=$i();function EF(e,t){for(var r=e.length;r--;)if(NF(e[r][0],t))return r;return-1}Vy.exports=EF});var zy=g((KH,Gy)=>{var DF=bo(),IF=Array.prototype,_F=IF.splice;function PF(e){var t=this.__data__,r=DF(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():_F.call(t,r,1),--this.size,!0}Gy.exports=PF});var jy=g((YH,Wy)=>{var TF=bo();function OF(e){var t=this.__data__,r=TF(t,e);return r<0?void 0:t[r][1]}Wy.exports=OF});var Qy=g((ZH,Hy)=>{var xF=bo();function RF(e){return xF(this.__data__,e)>-1}Hy.exports=RF});var Xy=g((eQ,Jy)=>{var LF=bo();function FF(e,t){var r=this.__data__,n=LF(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}Jy.exports=FF});var wo=g((tQ,Ky)=>{var kF=$y(),MF=zy(),UF=jy(),BF=Qy(),$F=Xy();function qi(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])}}qi.prototype.clear=kF;qi.prototype.delete=MF;qi.prototype.get=UF;qi.prototype.has=BF;qi.prototype.set=$F;Ky.exports=qi});var Zy=g((rQ,Yy)=>{var qF=wo();function VF(){this.__data__=new qF,this.size=0}Yy.exports=VF});var tb=g((nQ,eb)=>{function GF(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}eb.exports=GF});var nb=g((iQ,rb)=>{function zF(e){return this.__data__.get(e)}rb.exports=zF});var ab=g((aQ,ib)=>{function WF(e){return this.__data__.has(e)}ib.exports=WF});var fp=g((oQ,ob)=>{var jF=typeof global=="object"&&global&&global.Object===Object&&global;ob.exports=jF});var rr=g((sQ,sb)=>{var HF=fp(),QF=typeof self=="object"&&self&&self.Object===Object&&self,JF=HF||QF||Function("return this")();sb.exports=JF});var Ao=g((lQ,lb)=>{var XF=rr(),KF=XF.Symbol;lb.exports=KF});var pb=g((uQ,db)=>{var ub=Ao(),cb=Object.prototype,YF=cb.hasOwnProperty,ZF=cb.toString,Co=ub?ub.toStringTag:void 0;function ek(e){var t=YF.call(e,Co),r=e[Co];try{e[Co]=void 0;var n=!0}catch{}var i=ZF.call(e);return n&&(t?e[Co]=r:delete e[Co]),i}db.exports=ek});var mb=g((cQ,fb)=>{var tk=Object.prototype,rk=tk.toString;function nk(e){return rk.call(e)}fb.exports=nk});var Qn=g((dQ,vb)=>{var hb=Ao(),ik=pb(),ak=mb(),ok="[object Null]",sk="[object Undefined]",gb=hb?hb.toStringTag:void 0;function lk(e){return e==null?e===void 0?sk:ok:gb&&gb in Object(e)?ik(e):ak(e)}vb.exports=lk});var zr=g((pQ,yb)=>{function uk(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}yb.exports=uk});var yl=g((fQ,bb)=>{var ck=Qn(),dk=zr(),pk="[object AsyncFunction]",fk="[object Function]",mk="[object GeneratorFunction]",hk="[object Proxy]";function gk(e){if(!dk(e))return!1;var t=ck(e);return t==fk||t==mk||t==pk||t==hk}bb.exports=gk});var Ab=g((mQ,wb)=>{var vk=rr(),yk=vk["__core-js_shared__"];wb.exports=yk});var Nb=g((hQ,Sb)=>{var mp=Ab(),Cb=(function(){var e=/[^.]+$/.exec(mp&&mp.keys&&mp.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function bk(e){return!!Cb&&Cb in e}Sb.exports=bk});var hp=g((gQ,Eb)=>{var wk=Function.prototype,Ak=wk.toString;function Ck(e){if(e!=null){try{return Ak.call(e)}catch{}try{return e+""}catch{}}return""}Eb.exports=Ck});var Ib=g((vQ,Db)=>{var Sk=yl(),Nk=Nb(),Ek=zr(),Dk=hp(),Ik=/[\\^$.*+?()[\]{}|]/g,_k=/^\[object .+?Constructor\]$/,Pk=Function.prototype,Tk=Object.prototype,Ok=Pk.toString,xk=Tk.hasOwnProperty,Rk=RegExp("^"+Ok.call(xk).replace(Ik,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Lk(e){if(!Ek(e)||Nk(e))return!1;var t=Sk(e)?Rk:_k;return t.test(Dk(e))}Db.exports=Lk});var Pb=g((yQ,_b)=>{function Fk(e,t){return e?.[t]}_b.exports=Fk});var hn=g((bQ,Tb)=>{var kk=Ib(),Mk=Pb();function Uk(e,t){var r=Mk(e,t);return kk(r)?r:void 0}Tb.exports=Uk});var bl=g((wQ,Ob)=>{var Bk=hn(),$k=rr(),qk=Bk($k,"Map");Ob.exports=qk});var So=g((AQ,xb)=>{var Vk=hn(),Gk=Vk(Object,"create");xb.exports=Gk});var Fb=g((CQ,Lb)=>{var Rb=So();function zk(){this.__data__=Rb?Rb(null):{},this.size=0}Lb.exports=zk});var Mb=g((SQ,kb)=>{function Wk(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}kb.exports=Wk});var Bb=g((NQ,Ub)=>{var jk=So(),Hk="__lodash_hash_undefined__",Qk=Object.prototype,Jk=Qk.hasOwnProperty;function Xk(e){var t=this.__data__;if(jk){var r=t[e];return r===Hk?void 0:r}return Jk.call(t,e)?t[e]:void 0}Ub.exports=Xk});var qb=g((EQ,$b)=>{var Kk=So(),Yk=Object.prototype,Zk=Yk.hasOwnProperty;function eM(e){var t=this.__data__;return Kk?t[e]!==void 0:Zk.call(t,e)}$b.exports=eM});var Gb=g((DQ,Vb)=>{var tM=So(),rM="__lodash_hash_undefined__";function nM(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=tM&&t===void 0?rM:t,this}Vb.exports=nM});var Wb=g((IQ,zb)=>{var iM=Fb(),aM=Mb(),oM=Bb(),sM=qb(),lM=Gb();function Vi(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])}}Vi.prototype.clear=iM;Vi.prototype.delete=aM;Vi.prototype.get=oM;Vi.prototype.has=sM;Vi.prototype.set=lM;zb.exports=Vi});var Qb=g((_Q,Hb)=>{var jb=Wb(),uM=wo(),cM=bl();function dM(){this.size=0,this.__data__={hash:new jb,map:new(cM||uM),string:new jb}}Hb.exports=dM});var Xb=g((PQ,Jb)=>{function pM(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}Jb.exports=pM});var No=g((TQ,Kb)=>{var fM=Xb();function mM(e,t){var r=e.__data__;return fM(t)?r[typeof t=="string"?"string":"hash"]:r.map}Kb.exports=mM});var Zb=g((OQ,Yb)=>{var hM=No();function gM(e){var t=hM(this,e).delete(e);return this.size-=t?1:0,t}Yb.exports=gM});var tw=g((xQ,ew)=>{var vM=No();function yM(e){return vM(this,e).get(e)}ew.exports=yM});var nw=g((RQ,rw)=>{var bM=No();function wM(e){return bM(this,e).has(e)}rw.exports=wM});var aw=g((LQ,iw)=>{var AM=No();function CM(e,t){var r=AM(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}iw.exports=CM});var wl=g((FQ,ow)=>{var SM=Qb(),NM=Zb(),EM=tw(),DM=nw(),IM=aw();function Gi(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])}}Gi.prototype.clear=SM;Gi.prototype.delete=NM;Gi.prototype.get=EM;Gi.prototype.has=DM;Gi.prototype.set=IM;ow.exports=Gi});var lw=g((kQ,sw)=>{var _M=wo(),PM=bl(),TM=wl(),OM=200;function xM(e,t){var r=this.__data__;if(r instanceof _M){var n=r.__data__;if(!PM||n.length<OM-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new TM(n)}return r.set(e,t),this.size=r.size,this}sw.exports=xM});var gp=g((MQ,uw)=>{var RM=wo(),LM=Zy(),FM=tb(),kM=nb(),MM=ab(),UM=lw();function zi(e){var t=this.__data__=new RM(e);this.size=t.size}zi.prototype.clear=LM;zi.prototype.delete=FM;zi.prototype.get=kM;zi.prototype.has=MM;zi.prototype.set=UM;uw.exports=zi});var dw=g((UQ,cw)=>{var BM="__lodash_hash_undefined__";function $M(e){return this.__data__.set(e,BM),this}cw.exports=$M});var fw=g((BQ,pw)=>{function qM(e){return this.__data__.has(e)}pw.exports=qM});var hw=g(($Q,mw)=>{var VM=wl(),GM=dw(),zM=fw();function Al(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new VM;++t<r;)this.add(e[t])}Al.prototype.add=Al.prototype.push=GM;Al.prototype.has=zM;mw.exports=Al});var vw=g((qQ,gw)=>{function WM(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}gw.exports=WM});var bw=g((VQ,yw)=>{function jM(e,t){return e.has(t)}yw.exports=jM});var vp=g((GQ,ww)=>{var HM=hw(),QM=vw(),JM=bw(),XM=1,KM=2;function YM(e,t,r,n,i,a){var o=r&XM,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&KM?new HM:void 0;for(a.set(e,t),a.set(t,e);++d<s;){var h=e[d],b=t[d];if(n)var w=o?n(b,h,d,t,e,a):n(h,b,d,e,t,a);if(w!==void 0){if(w)continue;p=!1;break}if(f){if(!QM(t,function(E,D){if(!JM(f,D)&&(h===E||i(h,E,r,n,a)))return f.push(D)})){p=!1;break}}else if(!(h===b||i(h,b,r,n,a))){p=!1;break}}return a.delete(e),a.delete(t),p}ww.exports=YM});var yp=g((zQ,Aw)=>{var ZM=rr(),eU=ZM.Uint8Array;Aw.exports=eU});var Sw=g((WQ,Cw)=>{function tU(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}Cw.exports=tU});var Ew=g((jQ,Nw)=>{function rU(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}Nw.exports=rU});var Tw=g((HQ,Pw)=>{var Dw=Ao(),Iw=yp(),nU=$i(),iU=vp(),aU=Sw(),oU=Ew(),sU=1,lU=2,uU="[object Boolean]",cU="[object Date]",dU="[object Error]",pU="[object Map]",fU="[object Number]",mU="[object RegExp]",hU="[object Set]",gU="[object String]",vU="[object Symbol]",yU="[object ArrayBuffer]",bU="[object DataView]",_w=Dw?Dw.prototype:void 0,bp=_w?_w.valueOf:void 0;function wU(e,t,r,n,i,a,o){switch(r){case bU:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case yU:return!(e.byteLength!=t.byteLength||!a(new Iw(e),new Iw(t)));case uU:case cU:case fU:return nU(+e,+t);case dU:return e.name==t.name&&e.message==t.message;case mU:case gU:return e==t+"";case pU:var s=aU;case hU:var l=n&sU;if(s||(s=oU),e.size!=t.size&&!l)return!1;var u=o.get(e);if(u)return u==t;n|=lU,o.set(e,t);var c=iU(s(e),s(t),n,i,a,o);return o.delete(e),c;case vU:if(bp)return bp.call(e)==bp.call(t)}return!1}Pw.exports=wU});var xw=g((QQ,Ow)=>{function AU(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}Ow.exports=AU});var gn=g((JQ,Rw)=>{var CU=Array.isArray;Rw.exports=CU});var Fw=g((XQ,Lw)=>{var SU=xw(),NU=gn();function EU(e,t,r){var n=t(e);return NU(e)?n:SU(n,r(e))}Lw.exports=EU});var Mw=g((KQ,kw)=>{function DU(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}kw.exports=DU});var Bw=g((YQ,Uw)=>{function IU(){return[]}Uw.exports=IU});var Vw=g((ZQ,qw)=>{var _U=Mw(),PU=Bw(),TU=Object.prototype,OU=TU.propertyIsEnumerable,$w=Object.getOwnPropertySymbols,xU=$w?function(e){return e==null?[]:(e=Object(e),_U($w(e),function(t){return OU.call(e,t)}))}:PU;qw.exports=xU});var zw=g((eJ,Gw)=>{function RU(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}Gw.exports=RU});var vn=g((tJ,Ww)=>{function LU(e){return e!=null&&typeof e=="object"}Ww.exports=LU});var Hw=g((rJ,jw)=>{var FU=Qn(),kU=vn(),MU="[object Arguments]";function UU(e){return kU(e)&&FU(e)==MU}jw.exports=UU});var wp=g((nJ,Xw)=>{var Qw=Hw(),BU=vn(),Jw=Object.prototype,$U=Jw.hasOwnProperty,qU=Jw.propertyIsEnumerable,VU=Qw((function(){return arguments})())?Qw:function(e){return BU(e)&&$U.call(e,"callee")&&!qU.call(e,"callee")};Xw.exports=VU});var Yw=g((iJ,Kw)=>{function GU(){return!1}Kw.exports=GU});var Cl=g((Eo,Wi)=>{var zU=rr(),WU=Yw(),tA=typeof Eo=="object"&&Eo&&!Eo.nodeType&&Eo,Zw=tA&&typeof Wi=="object"&&Wi&&!Wi.nodeType&&Wi,jU=Zw&&Zw.exports===tA,eA=jU?zU.Buffer:void 0,HU=eA?eA.isBuffer:void 0,QU=HU||WU;Wi.exports=QU});var Sl=g((aJ,rA)=>{var JU=9007199254740991,XU=/^(?:0|[1-9]\d*)$/;function KU(e,t){var r=typeof e;return t=t??JU,!!t&&(r=="number"||r!="symbol"&&XU.test(e))&&e>-1&&e%1==0&&e<t}rA.exports=KU});var Ap=g((oJ,nA)=>{var YU=9007199254740991;function ZU(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=YU}nA.exports=ZU});var aA=g((sJ,iA)=>{var eB=Qn(),tB=Ap(),rB=vn(),nB="[object Arguments]",iB="[object Array]",aB="[object Boolean]",oB="[object Date]",sB="[object Error]",lB="[object Function]",uB="[object Map]",cB="[object Number]",dB="[object Object]",pB="[object RegExp]",fB="[object Set]",mB="[object String]",hB="[object WeakMap]",gB="[object ArrayBuffer]",vB="[object DataView]",yB="[object Float32Array]",bB="[object Float64Array]",wB="[object Int8Array]",AB="[object Int16Array]",CB="[object Int32Array]",SB="[object Uint8Array]",NB="[object Uint8ClampedArray]",EB="[object Uint16Array]",DB="[object Uint32Array]",de={};de[yB]=de[bB]=de[wB]=de[AB]=de[CB]=de[SB]=de[NB]=de[EB]=de[DB]=!0;de[nB]=de[iB]=de[gB]=de[aB]=de[vB]=de[oB]=de[sB]=de[lB]=de[uB]=de[cB]=de[dB]=de[pB]=de[fB]=de[mB]=de[hB]=!1;function IB(e){return rB(e)&&tB(e.length)&&!!de[eB(e)]}iA.exports=IB});var sA=g((lJ,oA)=>{function _B(e){return function(t){return e(t)}}oA.exports=_B});var uA=g((Do,ji)=>{var PB=fp(),lA=typeof Do=="object"&&Do&&!Do.nodeType&&Do,Io=lA&&typeof ji=="object"&&ji&&!ji.nodeType&&ji,TB=Io&&Io.exports===lA,Cp=TB&&PB.process,OB=(function(){try{var e=Io&&Io.require&&Io.require("util").types;return e||Cp&&Cp.binding&&Cp.binding("util")}catch{}})();ji.exports=OB});var Nl=g((uJ,pA)=>{var xB=aA(),RB=sA(),cA=uA(),dA=cA&&cA.isTypedArray,LB=dA?RB(dA):xB;pA.exports=LB});var Sp=g((cJ,fA)=>{var FB=zw(),kB=wp(),MB=gn(),UB=Cl(),BB=Sl(),$B=Nl(),qB=Object.prototype,VB=qB.hasOwnProperty;function GB(e,t){var r=MB(e),n=!r&&kB(e),i=!r&&!n&&UB(e),a=!r&&!n&&!i&&$B(e),o=r||n||i||a,s=o?FB(e.length,String):[],l=s.length;for(var u in e)(t||VB.call(e,u))&&!(o&&(u=="length"||i&&(u=="offset"||u=="parent")||a&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||BB(u,l)))&&s.push(u);return s}fA.exports=GB});var El=g((dJ,mA)=>{var zB=Object.prototype;function WB(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||zB;return e===r}mA.exports=WB});var Np=g((pJ,hA)=>{function jB(e,t){return function(r){return e(t(r))}}hA.exports=jB});var vA=g((fJ,gA)=>{var HB=Np(),QB=HB(Object.keys,Object);gA.exports=QB});var bA=g((mJ,yA)=>{var JB=El(),XB=vA(),KB=Object.prototype,YB=KB.hasOwnProperty;function ZB(e){if(!JB(e))return XB(e);var t=[];for(var r in Object(e))YB.call(e,r)&&r!="constructor"&&t.push(r);return t}yA.exports=ZB});var _o=g((hJ,wA)=>{var e$=yl(),t$=Ap();function r$(e){return e!=null&&t$(e.length)&&!e$(e)}wA.exports=r$});var CA=g((gJ,AA)=>{var n$=Sp(),i$=bA(),a$=_o();function o$(e){return a$(e)?n$(e):i$(e)}AA.exports=o$});var NA=g((vJ,SA)=>{var s$=Fw(),l$=Vw(),u$=CA();function c$(e){return s$(e,u$,l$)}SA.exports=c$});var IA=g((yJ,DA)=>{var EA=NA(),d$=1,p$=Object.prototype,f$=p$.hasOwnProperty;function m$(e,t,r,n,i,a){var o=r&d$,s=EA(e),l=s.length,u=EA(t),c=u.length;if(l!=c&&!o)return!1;for(var d=l;d--;){var p=s[d];if(!(o?p in t:f$.call(t,p)))return!1}var f=a.get(e),h=a.get(t);if(f&&h)return f==t&&h==e;var b=!0;a.set(e,t),a.set(t,e);for(var w=o;++d<l;){p=s[d];var E=e[p],D=t[p];if(n)var L=o?n(D,E,p,t,e,a):n(E,D,p,e,t,a);if(!(L===void 0?E===D||i(E,D,r,n,a):L)){b=!1;break}w||(w=p=="constructor")}if(b&&!w){var R=e.constructor,B=t.constructor;R!=B&&"constructor"in e&&"constructor"in t&&!(typeof R=="function"&&R instanceof R&&typeof B=="function"&&B instanceof B)&&(b=!1)}return a.delete(e),a.delete(t),b}DA.exports=m$});var PA=g((bJ,_A)=>{var h$=hn(),g$=rr(),v$=h$(g$,"DataView");_A.exports=v$});var OA=g((wJ,TA)=>{var y$=hn(),b$=rr(),w$=y$(b$,"Promise");TA.exports=w$});var RA=g((AJ,xA)=>{var A$=hn(),C$=rr(),S$=A$(C$,"Set");xA.exports=S$});var FA=g((CJ,LA)=>{var N$=hn(),E$=rr(),D$=N$(E$,"WeakMap");LA.exports=D$});var GA=g((SJ,VA)=>{var Ep=PA(),Dp=bl(),Ip=OA(),_p=RA(),Pp=FA(),qA=Qn(),Hi=hp(),kA="[object Map]",I$="[object Object]",MA="[object Promise]",UA="[object Set]",BA="[object WeakMap]",$A="[object DataView]",_$=Hi(Ep),P$=Hi(Dp),T$=Hi(Ip),O$=Hi(_p),x$=Hi(Pp),Jn=qA;(Ep&&Jn(new Ep(new ArrayBuffer(1)))!=$A||Dp&&Jn(new Dp)!=kA||Ip&&Jn(Ip.resolve())!=MA||_p&&Jn(new _p)!=UA||Pp&&Jn(new Pp)!=BA)&&(Jn=function(e){var t=qA(e),r=t==I$?e.constructor:void 0,n=r?Hi(r):"";if(n)switch(n){case _$:return $A;case P$:return kA;case T$:return MA;case O$:return UA;case x$:return BA}return t});VA.exports=Jn});var KA=g((NJ,XA)=>{var Tp=gp(),R$=vp(),L$=Tw(),F$=IA(),zA=GA(),WA=gn(),jA=Cl(),k$=Nl(),M$=1,HA="[object Arguments]",QA="[object Array]",Dl="[object Object]",U$=Object.prototype,JA=U$.hasOwnProperty;function B$(e,t,r,n,i,a){var o=WA(e),s=WA(t),l=o?QA:zA(e),u=s?QA:zA(t);l=l==HA?Dl:l,u=u==HA?Dl:u;var c=l==Dl,d=u==Dl,p=l==u;if(p&&jA(e)){if(!jA(t))return!1;o=!0,c=!1}if(p&&!c)return a||(a=new Tp),o||k$(e)?R$(e,t,r,n,i,a):L$(e,t,l,r,n,i,a);if(!(r&M$)){var f=c&&JA.call(e,"__wrapped__"),h=d&&JA.call(t,"__wrapped__");if(f||h){var b=f?e.value():e,w=h?t.value():t;return a||(a=new Tp),i(b,w,r,n,a)}}return p?(a||(a=new Tp),F$(e,t,r,n,i,a)):!1}XA.exports=B$});var tC=g((EJ,eC)=>{var $$=KA(),YA=vn();function ZA(e,t,r,n,i){return e===t?!0:e==null||t==null||!YA(e)&&!YA(t)?e!==e&&t!==t:$$(e,t,r,n,ZA,i)}eC.exports=ZA});var nC=g((DJ,rC)=>{var q$=tC();function V$(e,t){return q$(e,t)}rC.exports=V$});var Op=g((IJ,iC)=>{var G$=hn(),z$=(function(){try{var e=G$(Object,"defineProperty");return e({},"",{}),e}catch{}})();iC.exports=z$});var Il=g((_J,oC)=>{var aC=Op();function W$(e,t,r){t=="__proto__"&&aC?aC(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}oC.exports=W$});var xp=g((PJ,sC)=>{var j$=Il(),H$=$i();function Q$(e,t,r){(r!==void 0&&!H$(e[t],r)||r===void 0&&!(t in e))&&j$(e,t,r)}sC.exports=Q$});var uC=g((TJ,lC)=>{function J$(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}}lC.exports=J$});var dC=g((OJ,cC)=>{var X$=uC(),K$=X$();cC.exports=K$});var gC=g((Po,Qi)=>{var Y$=rr(),hC=typeof Po=="object"&&Po&&!Po.nodeType&&Po,pC=hC&&typeof Qi=="object"&&Qi&&!Qi.nodeType&&Qi,Z$=pC&&pC.exports===hC,fC=Z$?Y$.Buffer:void 0,mC=fC?fC.allocUnsafe:void 0;function eq(e,t){if(t)return e.slice();var r=e.length,n=mC?mC(r):new e.constructor(r);return e.copy(n),n}Qi.exports=eq});var bC=g((xJ,yC)=>{var vC=yp();function tq(e){var t=new e.constructor(e.byteLength);return new vC(t).set(new vC(e)),t}yC.exports=tq});var AC=g((RJ,wC)=>{var rq=bC();function nq(e,t){var r=t?rq(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}wC.exports=nq});var SC=g((LJ,CC)=>{function iq(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}CC.exports=iq});var DC=g((FJ,EC)=>{var aq=zr(),NC=Object.create,oq=(function(){function e(){}return function(t){if(!aq(t))return{};if(NC)return NC(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})();EC.exports=oq});var Rp=g((kJ,IC)=>{var sq=Np(),lq=sq(Object.getPrototypeOf,Object);IC.exports=lq});var PC=g((MJ,_C)=>{var uq=DC(),cq=Rp(),dq=El();function pq(e){return typeof e.constructor=="function"&&!dq(e)?uq(cq(e)):{}}_C.exports=pq});var OC=g((UJ,TC)=>{var fq=_o(),mq=vn();function hq(e){return mq(e)&&fq(e)}TC.exports=hq});var LC=g((BJ,RC)=>{var gq=Qn(),vq=Rp(),yq=vn(),bq="[object Object]",wq=Function.prototype,Aq=Object.prototype,xC=wq.toString,Cq=Aq.hasOwnProperty,Sq=xC.call(Object);function Nq(e){if(!yq(e)||gq(e)!=bq)return!1;var t=vq(e);if(t===null)return!0;var r=Cq.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&xC.call(r)==Sq}RC.exports=Nq});var Lp=g(($J,FC)=>{function Eq(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}FC.exports=Eq});var Fp=g((qJ,kC)=>{var Dq=Il(),Iq=$i(),_q=Object.prototype,Pq=_q.hasOwnProperty;function Tq(e,t,r){var n=e[t];(!(Pq.call(e,t)&&Iq(n,r))||r===void 0&&!(t in e))&&Dq(e,t,r)}kC.exports=Tq});var UC=g((VJ,MC)=>{var Oq=Fp(),xq=Il();function Rq(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?xq(r,s,l):Oq(r,s,l)}return r}MC.exports=Rq});var $C=g((GJ,BC)=>{function Lq(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}BC.exports=Lq});var VC=g((zJ,qC)=>{var Fq=zr(),kq=El(),Mq=$C(),Uq=Object.prototype,Bq=Uq.hasOwnProperty;function $q(e){if(!Fq(e))return Mq(e);var t=kq(e),r=[];for(var n in e)n=="constructor"&&(t||!Bq.call(e,n))||r.push(n);return r}qC.exports=$q});var kp=g((WJ,GC)=>{var qq=Sp(),Vq=VC(),Gq=_o();function zq(e){return Gq(e)?qq(e,!0):Vq(e)}GC.exports=zq});var WC=g((jJ,zC)=>{var Wq=UC(),jq=kp();function Hq(e){return Wq(e,jq(e))}zC.exports=Hq});var KC=g((HJ,XC)=>{var jC=xp(),Qq=gC(),Jq=AC(),Xq=SC(),Kq=PC(),HC=wp(),QC=gn(),Yq=OC(),Zq=Cl(),e3=yl(),t3=zr(),r3=LC(),n3=Nl(),JC=Lp(),i3=WC();function a3(e,t,r,n,i,a,o){var s=JC(e,r),l=JC(t,r),u=o.get(l);if(u){jC(e,r,u);return}var c=a?a(s,l,r+"",e,t,o):void 0,d=c===void 0;if(d){var p=QC(l),f=!p&&Zq(l),h=!p&&!f&&n3(l);c=l,p||f||h?QC(s)?c=s:Yq(s)?c=Xq(s):f?(d=!1,c=Qq(l,!0)):h?(d=!1,c=Jq(l,!0)):c=[]:r3(l)||HC(l)?(c=s,HC(s)?c=i3(s):(!t3(s)||e3(s))&&(c=Kq(l))):d=!1}d&&(o.set(l,c),i(c,l,n,a,o),o.delete(l)),jC(e,r,c)}XC.exports=a3});var Mp=g((QJ,ZC)=>{var o3=gp(),s3=xp(),l3=dC(),u3=KC(),c3=zr(),d3=kp(),p3=Lp();function YC(e,t,r,n,i){e!==t&&l3(t,function(a,o){if(i||(i=new o3),c3(a))u3(e,t,o,r,YC,n,i);else{var s=n?n(p3(e,o),a,o+"",e,t,i):void 0;s===void 0&&(s=a),s3(e,o,s)}},d3)}ZC.exports=YC});var Up=g((JJ,eS)=>{function f3(e){return e}eS.exports=f3});var rS=g((XJ,tS)=>{function m3(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)}tS.exports=m3});var aS=g((KJ,iS)=>{var h3=rS(),nS=Math.max;function g3(e,t,r){return t=nS(t===void 0?e.length-1:t,0),function(){for(var n=arguments,i=-1,a=nS(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),h3(e,this,s)}}iS.exports=g3});var sS=g((YJ,oS)=>{function v3(e){return function(){return e}}oS.exports=v3});var cS=g((ZJ,uS)=>{var y3=sS(),lS=Op(),b3=Up(),w3=lS?function(e,t){return lS(e,"toString",{configurable:!0,enumerable:!1,value:y3(t),writable:!0})}:b3;uS.exports=w3});var pS=g((eX,dS)=>{var A3=800,C3=16,S3=Date.now;function N3(e){var t=0,r=0;return function(){var n=S3(),i=C3-(n-r);if(r=n,i>0){if(++t>=A3)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}dS.exports=N3});var mS=g((tX,fS)=>{var E3=cS(),D3=pS(),I3=D3(E3);fS.exports=I3});var gS=g((rX,hS)=>{var _3=Up(),P3=aS(),T3=mS();function O3(e,t){return T3(P3(e,t,_3),e+"")}hS.exports=O3});var yS=g((nX,vS)=>{var x3=$i(),R3=_o(),L3=Sl(),F3=zr();function k3(e,t,r){if(!F3(r))return!1;var n=typeof t;return(n=="number"?R3(r)&&L3(t,r.length):n=="string"&&t in r)?x3(r[t],e):!1}vS.exports=k3});var Bp=g((iX,bS)=>{var M3=gS(),U3=yS();function B3(e){return M3(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&&U3(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})}bS.exports=B3});var AS=g((aX,wS)=>{var $3=Mp(),q3=Bp(),V3=q3(function(e,t,r,n){$3(e,t,r,n)});wS.exports=V3});var Lt,To=I(()=>{"use strict";(function(e){e[e.NotLoaded=0]="NotLoaded",e[e.Initialized=1]="Initialized",e[e.ConfigsLoaded=2]="ConfigsLoaded",e[e.Error=3]="Error"})(Lt||(Lt={}))});function SS(e,t,r="PROD"){let n=i=>`ShellSettings_ECS_ClientCache_${e}_${CS.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 CS,G3,NS=I(()=>{"use strict";CS=se(pp()),G3=se(dp());});var $p,ES=I(()=>{"use strict";al();$p=po({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 IS,_S,PS,TS,qp,z3,_l,DS,Vp=I(()=>{"use strict";IS=se(dp()),_S=se(ky()),PS=se(pp()),TS=se(nC()),qp=se(AS());To();NS();ES();z3=60*1e3,_l=class{clientName;logger;ecsEndpoint;resolveLoadingPromise;loadingPromise=new Promise(t=>this.resolveLoadingPromise=t);_status=Lt.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"?$p.prodEcsEndpoint:$p.integrationEcsEndpoint}client=new _S.default;init=async({clientVersion:t,getFilters:r,cacheStorage:n=IS.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:[PS.EcsConfigType.Default],hosts:[this.ecsEndpoint],initialAppActiveState:!0,getEcsParameters:o,databaseInterface:SS(this.clientName,n,this.endpointType),...a}),this.client.requestUpdate(),this._status===Lt.NotLoaded&&(this._status=Lt.Initialized)}catch(s){this._status=Lt.Error,this.resolveLoadingPromise(),this.logEvent("FeaturesClient/initializationFailed",{ecsClientName:this.clientName,error:s},"Error")}i&&window.setInterval(()=>this.client.requestUpdate(),i*z3)};getConfig=t=>{let r=this.getMergedClientConfigByTeamName(t.teamName),n=r?t.extractConfig(r):{};return(0,qp.default)({},t.fallback,n,t.override,DS)};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,TS.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,qp.default)({},this.client.getConfig()?.config,this.clientConfigOverride,DS);getMergedClientConfigByTeamName=t=>this.getMergedClientConfig()?.[t];handleConfigUpdated=()=>{let t=this.client.getConfig();if(t===void 0)return;this.resolveLoadingPromise(),this._status=Lt.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})}},DS=(e,t)=>{if(Array.isArray(t))return t}});var xS=g((mX,OS)=>{"use strict";var W3=()=>{let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e};OS.exports=W3});var Gp=g((hX,LS)=>{var Oo=new Proxy(function(){return Oo},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Oo},apply:function(){return Oo},construct:function(){return{}}}),RS=function(){return Oo};Object.setPrototypeOf(RS,Oo);LS.exports=RS});var MS=g((gX,kS)=>{var xo=new Proxy(function(){return xo},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:xo},apply:function(){return xo},construct:function(){return{}}}),FS=function(){return xo};Object.setPrototypeOf(FS,xo);kS.exports=FS});var zS=g((vX,GS)=>{"use strict";var zp=MS(),j3={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},H3={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},Q3={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},qS={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},Wp={};Wp[zp.ForwardRef]=Q3;Wp[zp.Memo]=qS;function US(e){return zp.isMemo(e)?qS:Wp[e.$$typeof]||j3}var J3=Object.defineProperty,X3=Object.getOwnPropertyNames,BS=Object.getOwnPropertySymbols,K3=Object.getOwnPropertyDescriptor,Y3=Object.getPrototypeOf,$S=Object.prototype;function VS(e,t,r){if(typeof t!="string"){if($S){var n=Y3(t);n&&n!==$S&&VS(e,n,r)}var i=X3(t);BS&&(i=i.concat(BS(t)));for(var a=US(e),o=US(t),s=0;s<i.length;++s){var l=i[s];if(!H3[l]&&!(r&&r[l])&&!(o&&o[l])&&!(a&&a[l])){var u=K3(t,l);try{J3(e,l,u)}catch{}}}}return e}GS.exports=VS});function jS(e,t,r){let[n,i]=(0,Ji.useState)(e.getConfig(t));return(0,Ji.useEffect)(()=>{if(!r?.subscribe&&e.status===Lt.ConfigsLoaded)return;let a=e.subscribe(t,o=>{i(o),r?.subscribe||a.unsubscribe()});return a?.unsubscribe},[]),n}function HS(e){return function(t,r){return jS(e,t,r)}}function QS(e,t,r,n){let i=a=>{let o=jS(e,t,n),s={...a,...o};return Ji.default.createElement(r,{...s})};return(0,WS.default)(i,r),i.displayName=`WithFeature(${r.name})`,i}function JS(e,t,r,n){return t.reduce((i,a)=>QS(e,a,i,n),r)}function XS(e){return function(t,r,n){return QS(e,t,r,n)}}var WS,Ji,jp=I(()=>{"use strict";WS=se(zS()),Ji=se(Gp());To();});var YS=g((wX,KS)=>{var Z3=Mp(),e4=Bp(),t4=e4(function(e,t,r){Z3(e,t,r)});KS.exports=t4});var Pl=g((AX,ZS)=>{var r4=Qn(),n4=vn(),i4="[object Symbol]";function a4(e){return typeof e=="symbol"||n4(e)&&r4(e)==i4}ZS.exports=a4});var tN=g((CX,eN)=>{var o4=gn(),s4=Pl(),l4=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,u4=/^\w*$/;function c4(e,t){if(o4(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||s4(e)?!0:u4.test(e)||!l4.test(e)||t!=null&&e in Object(t)}eN.exports=c4});var iN=g((SX,nN)=>{var rN=wl(),d4="Expected a function";function Hp(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(d4);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(Hp.Cache||rN),r}Hp.Cache=rN;nN.exports=Hp});var oN=g((NX,aN)=>{var p4=iN(),f4=500;function m4(e){var t=p4(e,function(n){return r.size===f4&&r.clear(),n}),r=t.cache;return t}aN.exports=m4});var lN=g((EX,sN)=>{var h4=oN(),g4=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,v4=/\\(\\)?/g,y4=h4(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(g4,function(r,n,i,a){t.push(i?a.replace(v4,"$1"):n||r)}),t});sN.exports=y4});var cN=g((DX,uN)=>{function b4(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}uN.exports=b4});var gN=g((IX,hN)=>{var dN=Ao(),w4=cN(),A4=gn(),C4=Pl(),S4=1/0,pN=dN?dN.prototype:void 0,fN=pN?pN.toString:void 0;function mN(e){if(typeof e=="string")return e;if(A4(e))return w4(e,mN)+"";if(C4(e))return fN?fN.call(e):"";var t=e+"";return t=="0"&&1/e==-S4?"-0":t}hN.exports=mN});var yN=g((_X,vN)=>{var N4=gN();function E4(e){return e==null?"":N4(e)}vN.exports=E4});var wN=g((PX,bN)=>{var D4=gn(),I4=tN(),_4=lN(),P4=yN();function T4(e,t){return D4(e)?e:I4(e,t)?[e]:_4(P4(e))}bN.exports=T4});var CN=g((TX,AN)=>{var O4=Pl(),x4=1/0;function R4(e){if(typeof e=="string"||O4(e))return e;var t=e+"";return t=="0"&&1/e==-x4?"-0":t}AN.exports=R4});var EN=g((OX,NN)=>{var L4=Fp(),F4=wN(),k4=Sl(),SN=zr(),M4=CN();function U4(e,t,r,n){if(!SN(e))return e;t=F4(t,e);for(var i=-1,a=t.length,o=a-1,s=e;s!=null&&++i<a;){var l=M4(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=SN(c)?c:k4(t[i+1])?[]:{})}L4(s,l,u),s=s[l]}return e}NN.exports=U4});var IN=g((xX,DN)=>{var B4=EN();function $4(e,t,r){return e==null?e:B4(e,t,r)}DN.exports=$4});function ON(e){let{query:t}=(0,TN.default)(window.location.href,!0);return V4(e,t),e}function V4(e,t){let r=q4+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+xN,u={};if(a===r)u=s;else if(a.startsWith(l)){let c=a.substring(l.length);(0,PN.default)(u,c,s)}(0,_N.default)(i,u)}catch{}}),Object.keys(i).length>0&&e.overrideClientConfig(i)}var _N,PN,TN,xN,q4,RN=I(()=>{"use strict";_N=se(YS()),PN=se(IN()),TN=se(Yd());xN=".",q4="ecs"+xN});function Ol(e,t,r){let n=ON(new _l(e,t,r));function i(a){(0,Tl.useEffect)(()=>{n.init(a)},[])}return{featuresClient:n,createFeature:z4(n),useFeaturesClientInitParams:i,withFeatures:(a,o,s)=>JS(n,a,o,s)}}function z4(e){let t=HS(e),r=XS(e);return function(i){let a=Oy(i);return a.getConfig=()=>e.getConfig(a),a.isLoaded=()=>e.status===Lt.ConfigsLoaded,tp.register(a,e.clientName),{useFeature:o=>t(a,o),withFeature:(o,s)=>r(a,o,s),feature:a}}}var G4,Tl,Qp=I(()=>{"use strict";G4=se(xS()),Tl=se(Gp());cp();Vp();To();jp();RN();rp();});var LN=I(()=>{"use strict";cp();Vp();Qp();To();jp();ul();np();});function xl(e){return{logEvent:(t,r,n)=>{switch(n){case"Error":(0,Xi.trackErrorTrace)(e,{eventName:t,eventData:r});break;case"Warning":(0,Xi.trackWarningTrace)(e,{eventName:t,eventData:r});break;default:(0,Xi.trackInfoTrace)(e,{eventName:t,eventData:r});break}}}}var Xi,Jp=I(()=>{"use strict";Xi=se(Vn());});var YX,ZX,eK,FN=I(()=>{"use strict";LN();Jp();({featuresClient:YX,createFeature:ZX,useFeaturesClientInitParams:eK}=Ol("PowerApps-Shell-Test",xl("shell-features")))});var UN=g((rK,MN)=>{var Ro=new Proxy(function(){return Ro},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Ro},apply:function(){return Ro},construct:function(){return{}}}),kN=function(){return Ro};Object.setPrototypeOf(kN,Ro);MN.exports=kN});var W4,j4,BN=I(()=>{"use strict";lo();W4=se(UN()),j4=se(Vn());});var $N=I(()=>{"use strict";FN();Jp();BN();});var dK,Ki,pK,qN=I(()=>{"use strict";$N();Qp();({featuresClient:dK,createFeature:Ki,useFeaturesClientInitParams:pK}=Ol("PowerApps-MakerPortal",xl("powerapps-features")))});var VN,GN,gK,vK,yK,bK,Xp=I(()=>{"use strict";Ty();qN();({feature:VN}=Ki({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:Bi.enableAutoInsertionOfCellInRow}})),{feature:GN}=Ki({teamName:"MakerPortal",owners:["aansu"],description:"Enable the one grid events for form designer",createdOn:"08/21/2024",fallback:{enableOneGridEventsForFormDesigner:Bi.enableOneGridEvents}}),{feature:gK}=Ki({teamName:"MakerPortal",owners:["adekulkarni"],description:"Disables PBI components and cleans them up from the form",createdOn:"01/03/2023",fallback:{enableFallbackFormTemplate:Bi.disablePBIComponents}}),{feature:vK}=Ki({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:Bi.enableAgentResponse}}),{feature:yK,useFeature:bK}=Ki({teamName:"MakerPortal",owners:["aansu"],description:"Enables delayed localization of custom control",createdOn:"06/08/2025",fallback:{enableDelayedLocalizationForCustomControls:Bi.enableDelayedLocalizationForCustomControls}})});var jN=g((AK,WN)=>{var Lo=new Proxy(function(){return Lo},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Lo},apply:function(){return Lo},construct:function(){return{}}}),zN=function(){return Lo};Object.setPrototypeOf(zN,Lo);WN.exports=zN});var nt,yn=I(()=>{"use strict";xe();Pe();rt();gl();J();Ge();nt=class extends W{static HighestUsedIndexByClass=new Map;get colspan(){let t=this.getProperty(m.colspan);return N.IsNullOrUndefined(t)?null:parseInt(t,10)}set colspan(t){N.IsNullOrUndefined(t)||this.setProperty(m.colspan,String(t))}constructor(t,r){super(t,r)}get id(){let t=this.getProperty(m.id);return t==null?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new P(t.substr(1,t.length-2)):new P(t)}set id(t){this.setProperty(m.id,`{${t.ToString()}}`)}set labelId(t){this.setProperty(m.labelId,`{${t.ToString()}}`)}get labelId(){let t=this.getProperty(m.labelId);return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new P(t.substr(1,t.length-2)):new P(t)}get Name(){return this.getProperty(m.Name)}set Name(t){this.setProperty(m.Name,t)}setDisplayName(t,r){for(let i of this.getAllLabels())if(+i.getProperty(m.languagecode)===r){i.setProperty(m.description,t);return}let n=new W(v.formLabel,null);n.setProperty(m.description,t),n.setProperty(m.languagecode,String(r)),this.addGrandChild("labels",n)}getDisplayName(t){for(let r of this.getAllLabels())if(+r.getProperty(m.languagecode)===t)return r.getProperty(m.description)}getAllLabels(){let t=this.getChildren("labels");return t.length!==1?[]:t[0].getChildren("label")}get isLocked(){return+this.getProperty(m.locklevel)==1}set isLocked(t){!this.IsUnboundControl&&this.setProperty(m.locklevel,t?"1":"0")}get availableforphone(){return this.getProcessedValue(m.availableforphone)}set availableforphone(t){N.IsNullOrUndefined(t)||!this.IsAllowedUBCForAvailableOnPhone()||this.setProperty(m.availableforphone,String(t))}get visible(){return this.getProcessedValue(m.visible)}set visible(t){N.IsNullOrUndefined(t)||!this.IsAllowedUBCForVisibleByDefault()||this.setProperty(m.visible,String(t))}isLockLevelSettable(){return!this.IsUnboundControl}get showlabel(){return this.getProcessedValue(m.showlabel)}set showlabel(t){N.IsNullOrUndefined(t)||this.setProperty(m.showlabel,String(t))}isAvailableForPhoneSettable(){return this.IsAllowedUBCForAvailableOnPhone()}isVisibleSettable(){return this.IsAllowedUBCForVisibleByDefault()}getProcessedValue(t){let r=this.getProperty(t);return N.IsNullOrUndefined(r)||this.getProperty(t)==="true"}get readonly(){let t=this.getFirstChild(v.formControl);return t?t.disabled:!1}set readonly(t){let r=this.getFirstChild(v.formControl);r&&(r.disabled=t)}get allowfilteroff(){let t=this.getFirstChild(v.formControl);if(t)return t.getParam(m.AllowFilterOff)==="true"}set allowfilteroff(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(m.AllowFilterOff,t)}get autoresolve(){let t=this.getFirstChild(v.formControl);if(t)return t.getParam(m.AutoResolve)==="true"}set autoresolve(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(m.AutoResolve,t)}get defaultviewid(){let t=this.getFirstChild(v.formControl);return t?t.getParam(m.DefaultViewId):T.EmptyString}set defaultviewid(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(m.DefaultViewId,t)}get dependentattributename(){let t=this.getFirstChild(v.formControl);return t?t.getParam(m.DependentAttributeName):T.EmptyString}set dependentattributename(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(m.DependentAttributeName,t)}get dependentattributetype(){let t=this.getFirstChild(v.formControl);return t?t.getParam(m.DependentAttributeType):T.EmptyString}set dependentattributetype(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(m.DependentAttributeType,t)}get disablequickfind(){let t=this.getFirstChild(v.formControl);if(t)return t.getParam(m.DisableQuickFind)==="true"}set disablequickfind(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(m.DisableQuickFind,t)}get disableviewpicker(){let t=this.getFirstChild(v.formControl);if(t)return t.getParam(m.DisableViewPicker)==="true"}set disableviewpicker(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(m.DisableViewPicker,t)}get filterrelationshipname(){let t=this.getFirstChild(v.formControl);return t?t.getParam(m.FilterRelationshipName):T.EmptyString}set filterrelationshipname(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(m.FilterRelationshipName,t)}get availableviewids(){let t=this.getFirstChild(v.formControl);return t?t.getParam(m.AvailableViewIds):T.EmptyString}set availableviewids(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(m.AvailableViewIds,t)}get IsUnboundControl(){let t=this.getFirstChild(v.formControl);if(t&&t.ClassId){let r=Le.getUniqueIdentifierForControl(t);return!N.IsNullOrUndefined(r)&&Le.isUnboundFormControlByIdentifier(r)}else return!1}IsAllowedUBCForAvailableOnPhone(){let t=this.getFirstChild(v.formControl);if(t){let n=Le.getUniqueIdentifierForControl(t).guidString,i=n===x.GridControl||n===x.TimeLineControl||n===x.TimeLineControlUC;return this.IsUnboundControl?i:!0}return this.NodeName===v.formSection||this.NodeName===v.formTab}IsAllowedUBCForVisibleByDefault(){let t=this.getFirstChild(v.formControl);if(t){let n=Le.getUniqueIdentifierForControl(t).guidString,i=n===x.MapsControl||n===x.WebResourceHtmlControl||n===x.WebResourceImageControl||n===x.IframeControl||n===x.SocialInsightControl;return this.IsUnboundControl?i:!0}else return!0}get events(){let t=this.getChildren(v.formEvents);return t.length===1?t[0].getAllChildren():[]}addEvent(t){this.addGrandChild(v.formEvents,t)}getUsedNodeNameSet(t){return null}getHighestIndexById(t,r){return null}}});var Yi,Kp=I(()=>{"use strict";rt();J();Ge();Yi=class extends W{constructor(t,r){super(v.dependency,t),T.IsNullOrEmpty(r)||this.setDefaultProperties(r)}set id(t){this.setProperty(m.id,t)}get id(){return this.getProperty(m.id)}setDefaultProperties(t){this.id=t}}});var HN,Zi,Yp=I(()=>{"use strict";Pe();Kp();J();Ge();yn();(function(e){e[e.Form=0]="Form",e[e.Cell=1]="Cell",e[e.Tab=2]="Tab",e[e.Control=3]="Control"})(HN||(HN={}));Zi=class extends nt{constructor(t,r){super(v.formEvent,t),r&&(this.eventName=r,this.application="false",this.active="false")}set eventName(t){this.setProperty(m.Name,t)}get eventName(){return this.getProperty(m.Name)}set application(t){this.setProperty(m.application,t)}get application(){return this.getProperty(m.application)}set attribute(t){this.setProperty(m.EventAttribute,t)}get attribute(){return this.getProperty(m.EventAttribute)}set relationship(t){this.setProperty(m.Relationship,t)}get relationship(){return this.getProperty(m.Relationship)}set control(t){this.setProperty(m.Control,t)}get control(){return this.getProperty(m.Control)}set active(t){this.setProperty(m.EventActive,t)}get active(){return this.getProperty(m.EventActive)}getAllHandlers(){let t=this.getChildren(v.EventHandlers);return t&&t.length?t[0].getChildren(v.handler):[]}getAllDependencies(){let t=this.getChildren(v.formDependencies);return t.length===0?[]:t[0].getAllChildren()}setDependencies(t){let r=this.getFirstChild(v.formDependencies);if(N.IsNullOrUndefined(r)){if(t.length===0)return;this.addChild(new W(v.formDependencies,this)),r=this.getFirstChild(v.formDependencies)}if(t.length===0)r.getParentNode().deleteChild(r);else{r.deleteAllChildren();for(let n of t)r.addChild(new Yi(r,n.toString()))}}}});var nr,Fo=I(()=>{"use strict";xe();so();Pe();qn();J();Ge();er();nr=class extends W{previewVersion;constructor(t){super(v.formControl,t)}updatePreview(){this.previewVersion=Date.now()}get ClassId(){let t=this.getProperty(m.classid);return t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new P(t)}set ClassId(t){this.setProperty(m.classid,`{${t.ToString()}}`)}get dataFieldName(){return this.getProperty(m.datafieldname)}set dataFieldName(t){this.setProperty(m.datafieldname,t)}set id(t){this.setProperty(m.id,t)}get id(){return this.getProperty(m.id)}get UniqueId(){let t=this.getProperty(m.uniqueid);return N.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new P(t))}set UniqueId(t){this.setProperty(m.uniqueid,`{${t.ToString()}}`)}get isRequired(){return this.getProperty(m.isRequired)==="true"}set isRequired(t){N.IsNullOrUndefined(t)||this.setProperty(m.isRequired,String(t))}get disableMru(){return this.getParam(m.DisableMru)==="true"}set disableMru(t){N.IsNullOrUndefined(t)||this.setParameter(m.DisableMru,t)}get useMFDForCreate(){return this.getParam(m.UseMFDForCreate)==="true"}set useMFDForCreate(t){N.IsNullOrUndefined(t)||this.setParameter(m.UseMFDForCreate,t)}get useMFDForEdit(){return this.getParam(m.UseMFDForEdit)==="true"}set useMFDForEdit(t){N.IsNullOrUndefined(t)||this.setParameter(m.UseMFDForEdit,t)}get disabled(){return this.getProperty(m.disabled)==="true"}set disabled(t){N.IsNullOrUndefined(t)||this.setProperty(m.disabled,String(t))}get indicationOfSubgrid(){return this.getProperty(m.indicationOfSubgrid)==="true"}set indicationOfSubgrid(t){this.setProperty(m.indicationOfSubgrid,String(t))}getAllParameters(){let t=new st,r=this.getFirstChild(m.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=(Gr.StartTag+r).toString(),a=this.parametersNode;if(a){let o=a.findFirst(s=>s&&s.getNodeName()===t);if(o)if(n){this.deleteFirstGrandChildOfName(v.controlParameters,o);return}else{let s=o.getAllChildren();s&&s.length>0&&s[0]?s[0].setNodeName(i):o.addChild(new W(i,o))}else n||(o=new W(t,a),o.addChild(new W(i,o)),a.addChild(o))}else if(!n){a=new W("parameters",this);let o=new W(t,a);o.addChild(new W(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)===Gr.StartTag?a.substring(1):a}}}return null}get parametersNode(){let t=this.getChildren(m.parameters);return t.length===0?null:t[0]}async serializeParameters(t,r){let n=new st;switch(this.ClassId.guidString.toUpperCase()){case S.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(m.isUnbound)==="true"}getAttributeTypeFromClassId(t){if(t)switch(t.toUpperCase()){case S.BooleanControl:case S.CheckboxControl:return 0;case S.DateTimeControl:return 2;case S.DecimalControl:return 3;case S.FloatingNumberControl:return 4;case S.IntegerControl:case S.DurationControl:case S.LanguageControl:case S.TimezoneControl:return 5;case S.LookupControl:return 6;case S.CurrencyControl:return 8;case S.PartyListControl:return 10;case S.ChoiceControl:case S.RelationshipRoleChoiceControl:return 11;case S.ChoiceStatusControl:return 13;case S.TextAreaControl:case S.TextboxControl:case S.LabelControl:case S.EmailAddressControl:case S.UrlControl:case S.TickerControl:case S.ButtonControl:case S.PhoneNumberControl:return 14;case S.ChoicesControl:return 24;default:return}return 14}async toJSON(t){let r=this.getParent(),n=t&&t.formModelService&&t.formModelService.getFormType()===Re.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 ea,Zp=I(()=>{"use strict";rt();Ri();Fo();J();Ge();ea=class extends nr{constructor(t){super(t)}get targetEntityType(){return this.getParam(m.targetEntityType)||T.EmptyString}set targetEntityType(t){this.setParameter(m.targetEntityType,t)}get viewId(){return T.StripBraces(this.getParam(m.viewId))||T.EmptyString}set viewId(t){this.setParameter(m.viewId,T.AddBraces(t))}get viewIds(){return this.getParam(m.viewIds)||T.EmptyString}set viewIds(t){this.setParameter(m.viewIds,t)}get relationshipName(){return this.getParam(m.RelationshipName)||T.EmptyString}set relationshipName(t){this.setParameter(m.RelationshipName,t)}get isUserView(){return T.IsStrictTrue(this.getParam(m.isUserView))}set isUserView(t){this.setParameter(m.isUserView,t.toString())}get enableViewPicker(){return T.IsStrictTrue(this.getParam(m.enableViewPicker))}set enableViewPicker(t){this.setParameter(m.enableViewPicker,t)}get autoExpand(){return this.getParent().autoexpand&&this.getParam(m.autoExpand)===m.Auto}set autoExpand(t){let r=this.getParent();this.setParameter(m.autoExpand,t?m.Auto:m.Fixed),r.autoexpand=t}get recordsPerPage(){return this.getParam(m.recordsPerPage)?Number(this.getParam(m.recordsPerPage)):Number(m.RecordsPerPageRAControlDefault)}set recordsPerPage(t){this.setParameter(m.recordsPerPage,String(t))}get enableQuickFind(){return T.IsStrictTrue(this.getParam(m.enableQuickFind))}set enableQuickFind(t){this.setParameter(m.enableQuickFind,t)}get teamTemplateId(){return T.StripBraces(this.getParam(m.teamTemplateId))||T.EmptyString}set teamTemplateId(t){this.setParameter(m.teamTemplateId,T.AddBraces(t))}get chartId(){return this.getParam(m.visualizationId)||T.EmptyString}set chartId(t){this.setParameter(m.visualizationId,t)}get enableChartPicker(){return T.IsStrictTrue(this.getParam(m.enableChartPicker))}set enableChartPicker(t){this.setParameter(m.enableChartPicker,t)}get chartGridMode(){switch(this.getParam(m.chartGridMode)){case Rt.Chart:return Rt.Chart;case Rt.Grid:return Rt.Grid;default:return Rt.All}}set chartGridMode(t){this.setParameter(m.chartGridMode,t)}updateChartGridMode(t){t?this.chartGridMode=Rt.Chart:this.chartGridMode=this.enableChartPicker?Rt.All:Rt.Grid}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case m.targetEntityType:n.getAllChildren()[0].setNodeName("<"+r.targetEntityType);break;case m.viewId:n.getAllChildren()[0].setNodeName("<"+T.AddBraces(r.viewId));break;case m.isUserView:n.getAllChildren()[0].setNodeName("<"+r.isUserView);break;case m.enableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.enableViewPicker);break;case m.RelationshipName:let i=n.getAllChildren(),a="<"+r.relationshipName;i.length?n.getAllChildren()[0].setNodeName(a):n.addChild(new W(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(lt.dataset)?n[i].getParameters().get(lt.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 ta,ef=I(()=>{"use strict";rt();Ri();Fo();J();ta=class extends nr{constructor(t){super(t)}get defaultViewId(){return T.StripBraces(this.getParam(m.DefaultViewId))||T.EmptyString}set defaultViewId(t){this.setParameter(m.DefaultViewId,T.AddBraces(t))}get autoResolve(){return T.IsStrictTrue(this.getParam(m.AutoResolve))}set autoResolve(t){this.setParameter(m.AutoResolve,t)}get disableQuickFind(){return T.IsStrictTrue(this.getParam(m.DisableQuickFind))}set disableQuickFind(t){this.setParameter(m.DisableQuickFind,t)}get disableViewPicker(){return T.IsStrictTrue(this.getParam(m.DisableViewPicker))}set disableViewPicker(t){this.setParameter(m.DisableViewPicker,t)}get allowFilterOff(){return T.IsStrictTrue(this.getParam(m.AllowFilterOff))}set allowFilterOff(t){this.setParameter(m.AllowFilterOff,t)}get disableMru(){return T.IsStrictTrue(this.getParam(m.DisableMru))}set disableMru(t){this.setParameter(m.DisableMru,t)}get dependentAttributeName(){return this.getParam(m.DependentAttributeName)||T.EmptyString}set dependentAttributeName(t){this.setParameter(m.DependentAttributeName,t)}get dependentAttributeType(){return this.getParam(m.DependentAttributeType)||T.EmptyString}set dependentAttributeType(t){this.setParameter(m.DependentAttributeType,t)}get filterRelationshipName(){return this.getParam(m.FilterRelationshipName)||T.EmptyString}set filterRelationshipName(t){this.setParameter(m.FilterRelationshipName,t)}get availableViewIds(){return this.getParam(m.AvailableViewIds)||T.EmptyString}set availableViewIds(t){this.setParameter(m.AvailableViewIds,t)}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case m.datafieldname:case m.bindAttribute:n.getAllChildren()[0].setNodeName("<"+r.dataFieldName);break;case m.DefaultViewId:n.getAllChildren()[0].setNodeName("<"+T.AddBraces(r.defaultViewId));break;case m.AllowFilterOff:n.getAllChildren()[0].setNodeName("<"+r.allowFilterOff);break;case m.DisableQuickFind:n.getAllChildren()[0].setNodeName("<"+r.disableQuickFind);break;case m.DisableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.disableViewPicker);break;case m.FilterRelationshipName:n.getAllChildren()[0].setNodeName("<"+r.filterRelationshipName);break;case m.DependentAttributeName:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeName);break;case m.DependentAttributeType:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeType);break;case m.AvailableViewIds:n.getAllChildren()[0].setNodeName("<"+r.availableViewIds);break;case m.DisableMru:n.getAllChildren()[0].setNodeName("<"+r.disableMru);break;case m.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(lt.value)?n[i].getParameters().get(lt.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 QN,tf,bt,ko=I(()=>{"use strict";QN=se(jN());yn();J();Pe();xe();Yp();Fo();gl();lp();$d();er();qn();Ti();Zp();ef();rf();mo();tf="_",bt=class e extends nt{fieldPlaceholder;fieldRequiredLevel;isNewField;cellColType;dependentFields=[];constructor(t){super(v.formCell,t),this.isNewField=!1}get cellType(){return this.cellColType}set cellType(t){this.cellColType=t}setDefaultProperties(t){this.showlabel=t,this.isLocked=!1,N.IsNullOrUndefined(this.getProperty(m.id))&&(this.id=new P(P.NewGuid()))}addControl(t,r,n,i,a,o,s){n instanceof nr?this.addChild(n):n instanceof P&&this.addChild(this.getControlWithControlSpecificProperties(t,r,n,i,a,o,s))}removeControl(){return this.deleteChild(this.control)>=0}get isIndependent(){if(!N.IsNullOrUndefined(this.control))return N.IsNullOrUndefined(this.control.dataFieldName)?N.IsNullOrUndefined(this.control.id)?!0:!Gn.dependencyFieldCount.containsKey(this.control.id):!Gn.dependencyFieldCount.containsKey(this.control.dataFieldName)}createOnLoadEvent(){this.addEvent(new Zi(this,ao.onLoad))}get dependencies(){let t=this.getChildren(v.formEvents);for(let r of t){let n=r.getChildren(v.formEvent);for(let i of n)this.buildDependencyList(i,this.dependentFields)}return this.dependentFields}getNextAvailableControlName(t,r,n,i){let a;if(i&&el[i])a=el[i].replace(/ /g,tf)+tf;else{a="Control_";let u=new Error("Control class id does not exist or is undefined");(0,QN.trackErrorTrace)(ot,{eventName:`${O0}/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,m.isUnbound,"true"),e.prototype.setProperty.call(t,m.isRequired,"false")}getControlWithControlSpecificProperties(t,r,n,i,a,o,s){let l;a===Ft.Grid?(l=new ea(this),l.indicationOfSubgrid=!0):a===Ft.Lookup?l=new ta(this):l=new nr(this);let u=n.guidString,c=o||this.getNextAvailableControlName(t,i,this.getUsedNodeNameSet(t),u);if(e.prototype.setProperty.call(l,m.id,c),l.ClassId=n,!N.IsNullOrUndefined(s)&&(l.UniqueId=s),!o&&r)this.getUnboundControlProperties(l);else{let d=Le.getUniqueIdentifierForControl(l);N.IsNullOrUndefined(d)||(Le.getControlDataTypeByControlOrUniqueId(d)===q.QuickFormCollectionControl||!Le.isUnboundFormControlByIdentifier(d)?a!==Ft.Grid&&o&&u!==S.IframeControl&&u!==S.SubgridControl&&u!==S.ReferencePanelSubgridControl&&(l.dataFieldName=o,e.prototype.setProperty.call(l,m.disabled,"false")):(this.rowspan=Le.GetRowSpan(l),(Le.getControlDataTypeByControlOrUniqueId(d)===q.NotesControl||Le.getControlDataTypeByControlOrUniqueId(d)===q.TimeLineControl)&&(e.prototype.setProperty.call(l,m.disabled,"false"),l.id=q.NotesControl)),(Le.getUnboundControlNameFromIdentifier(n)===q.SubGridControl||Le.getUnboundControlNameFromIdentifier(n)===q.NotesControl||Le.getUnboundControlNameFromIdentifier(n)===q.TimeLineControl)&&(this.availableforphone=!0))}return l}buildDependencyList(t,r){if(N.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(m.id);o.getNodeName()===v.dependency&&s?r.push(s):this.buildDependencyList(o,r)}}}get control(){return this.getFirstChild(v.formControl)}set rowspan(t){this.setProperty(m.rowspan,String(t))}get rowspan(){let t=this.getProperty(m.rowspan);return N.IsNullOrUndefined(t)?1:parseInt(t,10)}set autoexpand(t){this.setProperty(m.auto,String(t))}get autoexpand(){return this.getProperty(m.auto)==="true"}set colspan(t){let r=Number(op.ONE_COLUMN),n=Number(op.FOUR_COLUMN);N.IsNullOrUndefined(t)||t>n||t<r||this.setProperty(m.colspan,String(t))}get colspan(){let t=this.getProperty(m.colspan);return N.IsNullOrUndefined(t)?1:parseInt(t,10)}getParentRow(){return this.getAncestor(v.formRow)}getParentSection(){return this.getAncestor(v.formSection)}getParentTab(){return this.getAncestor(v.formTab)}getParentForm(){return this.getAncestor(v.form)}isInHeader(){let t=this.getAncestor(v.formHeader);return!N.IsNullOrUndefined(t)}isInFooter(){let t=this.getAncestor(v.formFooter);return!N.IsNullOrUndefined(t)}isEmpty(){return N.IsNullOrUndefined(this.control)&&!this.IsUserSpacer}getHeaderFooter(){return this.isInHeader()?this.getAncestor(v.formHeader):this.isInFooter()?this.getAncestor(v.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(m.userspacer);return N.IsNullOrUndefined(t)?!1:t==="true"}SetUserSpacer(){this.setProperty(m.userspacer,"true")}ClearUserSpacer(){this.setProperty(m.userspacer,"false")}get columns(){let t=this.getProperty(m.columnName);return N.IsNullOrUndefined(t)?null:parseInt(t,10)}getColumnLayoutValue(t){let r;switch(t){case be.TWO_COLUMN:r="11";break;case be.THREE_COLUMN:r="111";break;case be.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(!N.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();N.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===Wn.ApplicationRequired||o===Wn.SystemRequired)&&!a||this.isCellLockedByExternal(t)&&!a)return!0}}return!1}getRequiredLevel(t){return!this.control?.dataFieldName||!this.control?.id||this.IsNewField||!this.control?.ClassId?Wn.None:t.getEntityAttributeByName(this.control.dataFieldName)?.requiredLevel?.toString()??Wn.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()===v.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()===v.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)===tf&&(r++,n=parseInt(t.substr(r,t.length-r),10)),n}}});var ra,nf=I(()=>{"use strict";rt();J();Ge();ra=class extends W{isInternal;constructor(t,r,n,i){super(v.library,t),this.isInternal=!!i,T.IsNullOrEmpty(n)||(this.name=r,this.libraryUniqueId=n)}get libraryUniqueId(){let t=this.getProperty(m.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(m.libraryUniqueId,t)}get name(){return this.getProperty(m.libraryName)}set name(t){this.setProperty(m.libraryName,t)}get displayName(){return this.getProperty(m.displayName)}set displayName(t){this.setProperty(m.displayName,t)}get description(){return this.getProperty(m.description)}set description(t){this.setProperty(m.description,t)}}});var Xn,af=I(()=>{"use strict";Pe();ko();J();Ge();Xn=class extends W{isRowAddedOnDragOver;constructor(t){super(v.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 N.IsNullOrUndefined(t)?!1:this.deleteChild(t)>=0}insertCellAtIndex(t,r){return N.IsNullOrUndefined(t)?!1:(this.insertChildAtIndex(t,r),!0)}isEmpty(){return!this.cells||this.cells.every(t=>t.isEmpty())}getParentSection(){return this.getAncestor(v.formSection)}insertPaddingCellAtIndex(t){let r=new bt(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(v.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 H4(e){switch(e){case jn.Left:return Hn.Left;case jn.Right:return Hn.Right;case jn.Center:return Hn.Center;default:return Hn.Left}}function Q4(e){switch(e){case ki.Left:return Ui.Left;case ki.Top:return Ui.Top;default:return Ui.Left}}function JN(e){switch(e){case 1:return 1;case 2:return 11;case 3:return 111;case 4:return 1111;default:return 1}}var J4,br,Mo=I(()=>{"use strict";up();xe();Pe();rt();Xp();ko();J();er();yn();af();J4=115,br=class e extends nt{colSpan=1;constructor(t,r){super(t,r)}getSectionType(){let t;switch(this.columns){case 1:t=be.ONE_COLUMN;break;case 11:t=be.TWO_COLUMN;break;case 111:t=be.THREE_COLUMN;break;case 1111:t=be.FOUR_COLUMN;break;default:t=this.colSpan-1}return t}setUniqueName(){let t=this.getParentTab(),r=ge.namePrefix;if(t){let n=t.Name,i=t.TotalSectionsCount+1;r=n+ge.namePrefix+i.toString()}else r+=Math.floor(Math.random()*1e3);this.setProperty(m.Name,r)}initializeDefaultProperties(t,r,n){if(n===be.REFERENCE_PANEL){this.addProperty(m.rowheight,"25");let i=`${ge.referencePanelNamePrefix}${P.NewGuid()}${ge.namePrefix}`;this.addProperty(m.Name,i)}else this.setUniqueName();if(this.addProperty(m.id,new P(P.NewGuid()).guidString),this.addProperty(m.IsUserDefined,ge.IsUserDefined),this.addProperty(m.locklevel,ge.LockLevel),this.addProperty(m.showlabel,ge.ShowLabel),this.addProperty(m.showbar,ge.ShowBar),this.addProperty(m.layout,ge.Layout),this.addProperty(m.Fieldlabelalignment,ge.labelAlignment),this.addProperty(m.Fieldlabelposition,ge.labelPosition),N.IsNullOrUndefined(n))this.addProperty(m.columnName,ge.columns);else{let i=this.getColumnLayoutValue(n);this.addProperty(m.columnName,i)}this.addProperty(m.LabelWidth,ge.LabelWidth),this.setDisplayName(r,t)}getColumnLayoutValue(t){let r;switch(t){case be.TWO_COLUMN:r="11";break;case be.THREE_COLUMN:r="111";break;case be.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 N.IsNullOrUndefined(this.columns)?t=this.ColSpan:this.columns.toString().split(T.EmptyString).forEach(r=>{t+=parseInt(r,10)}),t}get ColSpan(){return this.colSpan}initializeRow(t){if(t>0&&t<5){let r=new Xn(null);if(this.addGrandChild(v.formRows,r),VN.getConfig().enableAutoInsertionOfCellInRow)for(let n=0;n<t;n++){let i=new bt(r);i.setDefaultProperties(!1),r.addCell(i)}}}initialize(t,r,n){this.initializeDefaultProperties(t,r,n),n===be.REFERENCE_PANEL&&(n=be.ONE_COLUMN),this.initializeRow(n+1)}setColSpan(t){this.colSpan=t}appendRow(t){this.addGrandChild(v.formRows,t)}insertRowAtIndex(t,r){this.addGrandChildAtIndex(v.formRows,t,r)}insertRowsAtIndex(t,r){if(t&&t.length>0)for(let n=0;n<t.length;n++)this.addGrandChildAtIndex(v.formRows,t[n],r+n)}indexOfRow(t){return this.rows.indexOf(t)}deleteRow(t){return this.deleteFirstGrandChildOfName(v.formRows,t)}deleteRows(t,r){this.deleteGrandChildren(v.formRows,t,r)}get rows(){return this.getRows()}getRows(){let t=this.getChildren(v.formRows);return t.length===0?[]:t[0].getChildren(v.formRow)}get columns(){let t=this.getProperty(m.columnName),r=N.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 JN(n)}return r}set columns(t){N.IsNullOrUndefined(t)||this.setProperty(m.columnName,String(t))}get rowHeight(){let t=this.getProperty(m.rowheight);return N.IsNullOrUndefined(t)?null:parseInt(t,10)}set rowHeight(t){this.setProperty(m.rowheight,String(t))}set autoexpand(t){this.setProperty(m.autoExpand.toLowerCase(),String(t))}get autoexpand(){return this.getProperty(m.autoExpand.toLowerCase())==="true"}get isUserDefined(){return+this.getProperty(m.IsUserDefined)!=0}set isUserDefined(t){t?this.setProperty(m.IsUserDefined,"1"):this.setProperty(m.IsUserDefined,"0")}getParentColumn(){return this.getAncestor(v.formColumn)}getParentTab(){return this.getAncestor(v.formTab)}get hasMultiColumnRow(){return this.getColumnCountValue()>1}get showlabel(){return this.getProperty(m.showlabel)==="true"}set showlabel(t){N.IsNullOrUndefined(t)||this.setProperty(m.showlabel,String(t))}get fieldLabelAlignment(){let t=ge.labelAlignment,r=this.getProperty(m.Fieldlabelalignment);return N.IsNullOrUndefined(r)?t:r}set fieldLabelAlignment(t){N.IsNullOrUndefined(t)||this.setProperty(m.Fieldlabelalignment,t)}get fieldLabelPosition(){let t=this.getProperty(m.Fieldlabelposition);return N.IsNullOrUndefined(t)?ge.labelPosition:t}set fieldLabelPosition(t){N.IsNullOrUndefined(t)||this.setProperty(m.Fieldlabelposition,String(t))}get showbar(){return this.getProperty(m.showbar)==="true"}set showbar(t){N.IsNullOrUndefined(t)||this.setProperty(m.showbar,String(t))}get labelwidth(){let t=+this.getProperty(m.LabelWidth);return t===0?J4:t}set labelwidth(t){N.IsNullOrUndefined(t)||t>283&&t<57||this.setProperty(m.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:H4(this.fieldLabelAlignment),Position:Q4(this.fieldLabelPosition)},Columns:JN(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()===v.formSection){let i=n;i.Name&&!T.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}isReferencePanelSection(){return!N.IsNullOrUndefined(this)&&!N.IsNullOrUndefined(this.Name)&&this.Name.indexOf(ge.referencePanelNamePrefix)===0}getAllMultiRowCells(){return this.findAll(t=>{if(t.getNodeName()===v.formCell){let r=t;return!r.isEmpty()&&r.rowspan>1}return!1})}isHeaderOrFooterSection(){return this.NodeName===v.formFooter||this.NodeName===v.formHeader}}});var bn,Rl=I(()=>{"use strict";J();Ge();Mo();bn=class e extends W{constructor(t){super(v.formColumn,t)}initializeDefaultProperties(t){this.addProperty(m.width,t.toString()+"%")}insertSectionAtIndex(t,r){this.addGrandChildAtIndex(v.formSections,t,r)}static createAndInitNewSection(t,r,n){let i=new br(v.formSection,null);return i.initialize(t,r,n),i}addSectionAtIndex(t,r){this.addGrandChildAtIndex(v.formSections,t,r)}initialize(t,r,n,i=be.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(v.formTab)}get sections(){let t=this.getChildren("sections");return t.length!==1?[]:t[0].getChildren(v.formSection)}get width(){return this.getProperty(m.width)}set width(t){this.setProperty(m.width,t)}deleteSection(t){return this.deleteFirstGrandChildOfName(v.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(m.Name),Id:this.getProperty(m.id),Label:null,ShowLabel:!1,Visible:!0,LabelId:null,PreviewId:this.getProperty(m.id),Sections:await this.getSectionsJSON(t),Width:this.width}}}});var Ll,XN=I(()=>{"use strict";xe();J();er();Mo();Ll=class extends br{initializeNavArea(t,r,n){this.initializeNavAreaProps(t,r,n)}get AreaName(){return this.Name}initializeNavAreaProps(t,r,n){this.addProperty(m.Name,n),this.addProperty(m.id,new P(P.NewGuid()).guidString),this.addProperty(m.columnName,ge.columns),this.setDisplayName(r,t)}}});var Fl,KN=I(()=>{"use strict";Rl();J();XN();Fl=class extends bn{addAndIntializeNavBarSection(t,r,n,i){let a=new Ll(v.formSection,null);return a.initializeNavArea(t,r,i),this.addGrandChildAtIndex(v.formSections,a,n),a}}});var Wr,kl=I(()=>{"use strict";xe();Pe();rt();Rl();J();Ge();yn();Wr=class extends nt{tabContainsAutoExpandControl;autoExpandCell;constructor(t,r){super(v.formTab,t),this.tabContainsAutoExpandControl=!1}getParentForm(){return this.getAncestor(v.form)}getTabLayoutType(){let t;switch(this.columns.length){case 1:t=ye.ONE_COLUMN;break;case 2:if(parseInt(this.columns[0].width,10)===50&&parseInt(this.columns[1].width,10)===50){t=ye.TWO_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===67&&parseInt(this.columns[1].width,10)===33){t=ye.TWO_COLUMN_WIDER_LEFT;break}if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===66){t=ye.TWO_COLUMN_WIDER_RIGHT;break}t=ye.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=ye.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=ye.THREE_COLUMN_WIDER_MID;break}t=ye.THREE_COLUMN_CUSTOM_LAYOUT;break;default:}return t}initializeProperties(t,r,n){this.addProperty(m.Name,dn.namePrefix+t.toString()),this.addProperty(m.id,new P(P.NewGuid()).guidString),this.addProperty(m.IsUserDefined,dn.IsUserDefined),this.addProperty(m.locklevel,dn.LockLevel),this.addProperty(m.showlabel,dn.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=be.ONE_COLUMN,a=!0,o){let s=this.getChildren(v.formColumns)[0],l=[];switch(t){case ye.ONE_COLUMN:l.push(100);break;case ye.TWO_COLUMN_EQUAL:l.push(50),l.push(50);break;case ye.TWO_COLUMN_WIDER_LEFT:l.push(67),l.push(33);break;case ye.TWO_COLUMN_WIDER_RIGHT:l.push(34),l.push(66);break;case ye.THREE_COLUMN_EQUAL:l.push(34),l.push(33),l.push(33);break;case ye.THREE_COLUMN_WIDER_MID:l.push(28),l.push(44),l.push(28);break;default:}for(let u of l){let c=new bn(s);c.initialize(u,r,n,i),this.addGrandChild(v.formColumns,c)}}initialize(t,r,n,i,a,o=be.ONE_COLUMN,s=!0,l){this.addChild(new W(v.formColumns,this)),this.initializeProperties(r,n,i),this.initializeColumns(t,n,a,o,s,l)}get columns(){let t=this.getChildren(v.formColumns);return t.length!==1?[]:t[0].getChildren(v.formColumn)}get expanded(){return this.getProcessedValue(m.expanded)}set expanded(t){N.IsNullOrUndefined(t)||this.setProperty(m.expanded,String(t))}get groupName(){return this.getProperty(m.groupName)}get contentType(){return this.getProperty(m.contentType)}set contentType(t){this.setProperty(m.contentType,t)}insertNewColumnAtIndex(t,r,n,i,a){t.initialize(n,i,a),this.addGrandChildAtIndex(v.formColumns,t,r)}insertColumnAtIndex(t,r){this.addGrandChildAtIndex(v.formColumns,t,r)}deleteColumn(t){return this.deleteFirstGrandChildOfName(v.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()===v.formTab){let i=n;i.Name&&!T.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}}});var Kn,of=I(()=>{"use strict";xe();J();Ge();er();KN();kl();Kn=class extends Wr{constructor(t,r,n){super(t,ye.THREE_COLUMN_EQUAL),this.setDisplayName(r,n),this.id=new P(P.NewGuid())}initializeDefaultProps(){this.addChild(new W(v.formColumns,this)),this.initializeFiveColumns()}get columns(){let t=this.getChildren("columns");return t.length!==1?[]:t[0].getChildren(v.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<pl.FIVE_COLUMN;t++){let r=new Fl(this.getChildren(v.formColumns)[0]);r.initializeDefaultProperties(sv.FiveEqColumn),this.addGrandChild(v.formColumns,r)}}}});function K4(e){switch(e){case Re.Main:return mn.Main;case Re.QuickCreate:return mn.QuickCreate;case Re.QuickViewForm:return mn.Quick;case Re.Dialog:return mn.Dialog;default:return mn.None}}function Y4(e,t){if(t===Re.Main){if(e)switch(e.toLowerCase()){case"low":return cn.Low;case"highreadonlyvalues":return cn.HighReadOnlyValues;default:return cn.HighWithControls}return cn.Low}}var Ul,X4,Ml,YN=I(()=>{"use strict";Ey();Ul=se(Vn());up();Pe();rt();Ti();Xp();J();Ri();Id();qn();ko();J();yn();nf();of();kl();X4="1920";Ml=class e extends nt{_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(v.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 Xs,this._metadataChangeEvent=new vl}get FormLibraries(){let t=this.getFirstChild(v.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 bt).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 bt){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()===v.internalLibraries),r=[],n="src";return t.length>0&&(r=t.map(i=>{let a=i.GetPropertyByParameter(n).replace("$webresource:",""),o=new ra(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,Ul.trackErrorTrace)(x0,{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 T.IsNullOrEmpty(this.getProperty(m.ShowImage))?!0:this.getProperty(m.ShowImage)!=="false"}set ShowImagecheck(t){t?this.setProperty(m.ShowImage,String(t)):this.setProperty(m.ShowImage,"false")}get ShowNavigation(){return T.IsNullOrEmpty(this.getProperty(m.ShowNavigationbar))?!0:this.getProperty(m.ShowNavigationbar)!=="false"}set ShowNavigation(t){t?this.setProperty(m.ShowNavigationbar,String(t)):this.setProperty(m.ShowNavigationbar,"false")}get MaxWidth(){return T.IsNullOrEmpty(this.getProperty(m.MaxWidth))?X4:this.getProperty(m.MaxWidth)}set MaxWidth(t){this.setProperty(m.MaxWidth,t)}get headerDensityType(){return this.getProperty(m.HeaderDensityType)}set headerDensityType(t){t&&this.formType===Re.Main?this.setProperty(m.HeaderDensityType,t):this.formType!==Re.Main&&this.headerDensityType&&this.removeProperty(m.HeaderDensityType)}IsMainOrQuickCreateForm(){return this.formType===Re.Main||this.formType===Re.QuickCreate}get FormPresentation(){return this._formPresentation}get LanguageCode(){return this._langCode}set LanguageCode(t){this._langCode=t}get header(){let t=this.getChildren(v.formHeader);return t.length!==1?null:t[0]}set header(t){N.IsNullOrUndefined(t)||(this.deleteChild(this.header),this.addChild(t))}getAllDependencies(){return this.getChildren(v.quickFormDependencies).length===0?[]:this.ConvertModelToArray(this.getChildren(v.quickFormDependencies)[0].getAllChildren())}ConvertModelToArray(t){let r=[];return N.IsNullOrUndefined(t)||t.forEach(n=>{r.push(n.id)}),r}get footer(){let t=this.getChildren(v.formFooter);return t.length!==1?null:t[0]}set footer(t){N.IsNullOrUndefined(t)||(this.deleteChild(this.footer),this.addChild(t))}createAndInitNewTab(t,r,n){let i=new Wr(null,t),a=this.getNextTabCounter(this.tabs.length+1);return i.initialize(t,a,this.LanguageCode,r,n),i}addTabAtIndex(t,r){this.addGrandChildAtIndex(v.formTabs,t,r)}createAndInitNewTabWithMarginalControl(t,r,n,i,a){let o=new Wr(null,ye.ONE_COLUMN),s=this.getNextTabCounter(this.tabs.length+1);o.initialize(ye.ONE_COLUMN,s,this.LanguageCode,r,n,a,!1),this.addGrandChildAtIndex(v.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===dn.namePrefix+t.toString())return this.getNextTabCounter(t+1);return t}get allTabs(){let t=this.getChildren(v.formTabs);return t.length!==1?[]:t[0].getChildren(v.formTab)}get CanvasNavigationTab(){if(this.tabs.length>0){let t=this.tabs[this.tabs.length-1];if(t instanceof Kn)return t}return null}get NavigationNode(){let t=this.getChildren(v.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(v.formTabs,t)}insertTabAtIndex(t,r){this.addGrandChildAtIndex(v.formTabs,t,r)}insertRelatedTab(t){let r=this.getAllGrandChildren(v.formTabs);if(!N.IsNullOrUndefined(r)){let n=r.length;this.insertTabAtIndex(t,n)}}get isfooterPresent(){return this.getChildren(v.formFooter).length>0}get displayCondition(){let t=this.getChildren(v.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(v.formTabs).indexOf(t)}get ControlDescriptions(){return this.getAllGrandChildren(v.controlDescriptions)}addControlDescriptionNode(t){this.addGrandChild(v.controlDescriptions,t)}deleteControlDescByForControlId(t){let r=this.getControlDescriptionByForControl(t);N.IsNullOrUndefined(r)||this.deleteFirstGrandChildOfName(v.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 bt))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 bt&&i.control&&t.control&&a&&i.control.dataFieldName===t.control.dataFieldName})}isCellEditableGridControl(t){return!t?.control?.indicationOfSubgrid||t.control.ClassId.guidString.toUpperCase()!==S.CustomControl?!1:this.cellHasCustomControlWithName(t,pn.EditableGridControl)||GN.getConfig()?.enableOneGridEventsForFormDesigner&&this.cellHasCustomControlWithName(t,pn.PowerAppsOneGrid)}isCellCanvasAppControl(t){return t?.control?.ClassId.guidString.toUpperCase()===S.CustomControl&&this.cellHasCustomControlWithName(t,pn.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()===v.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 Kn)){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,Ul.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===Re.Main?{HeaderDensity:Y4(this.headerDensityType,this.formType)}:{},InlineEditGridRow:[],InlineQuickForms:[],QuickFormEntities:[],EventHandlers:[],LinkControlSections:[],FormType:K4(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 Bl,sf,ZN=I(()=>{"use strict";xe();Pe();J();Ge();yn();Bl=class extends nt{constructor(t){super(v.formDisplayConditions,t)}get Order(){let t=this.getProperty(m.Order);return N.IsNullOrUndefined(t)?null:parseInt(t,10)}set Order(t){this.setProperty(m.Order,t.toString())}get FallbackForm(){return this.getProperty(m.FallbackForm)==="true"}set FallbackForm(t){this.setProperty(m.FallbackForm,t.toString())}addRoles(t){this.deleteAllChildren();for(let r=0;r<t.length;r++)this.addChild(t[r])}isRoleEveryone(){return!!(this.getChildren(v.formEveryOne)&&this.getChildren(v.formEveryOne)[0])}setRoleEveryone(){this.deleteAllChildren(),this.addChild(new sf(this))}},sf=class extends W{constructor(t){super(v.formEveryOne,t)}}});var $l,eE=I(()=>{"use strict";J();Ge();$l=class extends W{constructor(t,r){super(v.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(m.HandlerUniqueId)}set HandlerUniqueID(t){this.setProperty(m.HandlerUniqueId,t)}get FunctionName(){return this.getProperty(m.functionName)}set FunctionName(t){this.setProperty(m.functionName,t)}get LibraryName(){return this.getProperty(m.libraryNameEventHandler)}set LibraryName(t){this.setProperty(m.libraryNameEventHandler,t)}get Enabled(){return this.getProperty(m.enabledForField)}set Enabled(t){this.setProperty(m.enabledForField,t)}get PassExecutionContext(){return this.getProperty(m.passExecutionContext)}set PassExecutionContext(t){this.setProperty(m.passExecutionContext,t)}get Parameters(){return this.getProperty(m.parameters)}set Parameters(t){this.setProperty(m.parameters,t)}}});var na,lf=I(()=>{"use strict";J();Mo();na=class extends br{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(v.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 Uo,tE=I(()=>{"use strict";J();lf();Uo=class extends na{_customFooter;constructor(t,r){super(v.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 Bo,rE=I(()=>{"use strict";J();lf();Bo=class extends na{_customHeader;constructor(t,r){super(v.formHeader,t),this._customHeader=r}get customHeader(){return this._customHeader}set customHeader(t){this._customHeader=t}get showCommandBar(){return this.getProcessedValue(m.showCommandBar)}set showCommandBar(t){t!=null&&this.setProperty(m.showCommandBar,String(t))}get showBody(){return this.getProcessedValue(m.showBody)}set showBody(t){t!=null&&this.setProperty(m.showBody,String(t))}get showTabNavigator(){return this.getProcessedValue(m.showTabNavigator)}set showTabNavigator(t){t!=null&&this.setProperty(m.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 wt,Yn=I(()=>{"use strict";xe();rt();J();yn();wt=class e extends nt{constructor(t,r){super(t,r)}getTitle(t){for(let r of this.getAllTitles())if(+r.getProperty(m.LCID)===t)return r.getProperty(m.text);return null}getAllTitles(){let t=this.getChildren(v.Titles);return t.length===0?[]:t[0].getChildren(v.Title)}setTitle(t,r){for(let i of this.getAllTitles())if(+i.getProperty(m.LCID)===r){i.setProperty(m.text,t);return}let n=new e(v.Title,null);n.setProperty(m.text,t),n.setProperty(m.LCID,String(r)),this.addGrandChild(v.Titles,n)}get Sequence(){return+this.getProperty(m.Sequence)}set Sequence(t){this.setProperty(m.Sequence,t.toString())}get Area(){return this.getProperty(m.Area)}set Area(t){this.setProperty(m.Area,t)}set Id(t){this.setProperty(m.Id,t)}get Id(){return this.getProperty(m.Id)}get id(){return new P(this.Id??"",!0)}set id(t){this.Id=t.guidString}get Show(){return!0}get Icon(){return this.getProperty(m.icon)}set Icon(t){t=t||T.EmptyString,this.setProperty(m.icon,t)}updateCommonProperties(t,r){this.Area=t.Area,this.Sequence=t.Sequence,this.setTitle(t.getDisplayName(r),r)}}});var $o,nE=I(()=>{"use strict";(function(e){e[e.NavLinkNotAvailable=-1]="NavLinkNotAvailable",e[e.NavLinkIdConflict=-2]="NavLinkIdConflict",e[e.NavBarNotAvailable=-3]="NavBarNotAvailable"})($o||($o={}))});var ql,iE=I(()=>{"use strict";Pe();J();Yn();nE();ql=class extends wt{constructor(t){super(v.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 N.IsNullOrUndefined(r)?$o.NavLinkNotAvailable:r.length===1?this.deleteChild(r[0]):$o.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 pe,Z4,aE,cee,ia,uf=I(()=>{"use strict";xe();J();Yn();(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"})(pe||(pe={}));Z4=new Map([[pe.Info,"Info"],[pe.Sales,"Sales"],[pe.Service,"Service"],[pe.Marketing,"Marketing"],[pe.ProcessCenter,"ProcessCenter"]]),aE=new Map([["Info",pe.Info],["Sales",pe.Sales],["Service",pe.Service],["Marketing",pe.Marketing],["ProcessCenter",pe.ProcessCenter]]),cee=new Map([[pe.Info,9e3],[pe.Sales,9200],[pe.Service,9400],[pe.Marketing,9600],[pe.ProcessCenter,9800],[pe.InternetMarketing,1e4],[pe.Async,10200]]),ia=class extends wt{constructor(t,r){super(v.formNavBarArea,r)}setDefaultPropertiesByType(t,r,n){this.AreaId=Z4.get(t);let i=n?.(`navBarArea.title.${this.AreaId}`)??this.AreaId;this.setTitle(i,r)}get ParentNavigation(){return this.getAncestor(v.formNavigation)}get AreaId(){return this.getProperty(m.Id)}set AreaId(t){this.setProperty(m.Id,t)}get id(){return new P(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 aa,cf=I(()=>{"use strict";J();Yn();aa=class extends wt{constructor(t,r){super(v.formNavBarAreas,r)}get AllNavBarAreaItems(){return this.getChildren(v.formNavBarArea)}get ParentNavigation(){return this.getAncestor(v.formNavigation)}addNavBarArea(t){this.addChild(t)}}});var Vl,oE=I(()=>{"use strict";Pe();J();Yn();Vl=class extends wt{RelationshipNameUCIRuntime;constructor(t){super(v.formNavBarByRelationshipItem,t)}get RelationshipName(){return this.getProperty(m.RelationshipName)}set RelationshipName(t){this.setProperty(m.RelationshipName,t)}set Show(t){this.setProperty(m.Show,String(t))}get Show(){let t=this.getProperty(m.Show);return N.IsNullOrUndefined(t)||t==="true"}get TitleResourceId(){return this.getProperty(m.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 Gl,sE=I(()=>{"use strict";J();Yn();Gl=class extends wt{constructor(t){super(v.formNavBarItem,t)}get Url(){return this.getProperty(m.url)}set Url(t){this.setProperty(m.url,t)}}});var zl,lE=I(()=>{"use strict";xe();J();uf();cf();Yn();zl=class extends wt{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(v.formNavBarAreas)}setDefaultNavBarAreas(t,r){let n=[pe.Info,pe.Sales,pe.Service,pe.Marketing,pe.ProcessCenter];if(this.navBarAreas){let i=this.navBarAreas?.AllNavBarAreaItems;if(i&&i.length>0){let a=new Set(i.map(o=>aE.get(o.AreaId)));n=n.filter(o=>!a.has(o))}}else{let i=new aa(v.formNavBarAreas,this);i.isTransient=!0,this.addChild(i)}return n.length>0?(n.forEach(i=>{let a=new ia(v.formNavBarArea,this.navBarAreas);a.setDefaultPropertiesByType(i,t,r),this.navBarAreas.addNavBarArea(a)}),!0):!1}get navBar(){return this.getFirstChild(v.formNavBar)}get id(){return new P(Bd,!0)}replaceNavAreaToGivenIndex(t,r){this.navBarAreas?.AllNavBarAreaItems.indexOf(r)!==-1&&(this.deleteFirstGrandChildOfName(v.formNavBarAreas,r),this.addGrandChildAtIndex(v.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 uE={};sr(uE,{ControlType:()=>Ft,DeserializationService:()=>ff,DeserializationServiceScope:()=>pf,DeserializedFormElementNode:()=>At});var df,At,pf,Ft,ff,rf=I(()=>{"use strict";df=se(Vn());xe();Pe();rt();Ti();$d();qn();R0();Ny();gl();YN();ko();Rl();Fo();Kp();J();J();ZN();Ge();er();Yp();eE();tE();Zp();ef();rE();nf();af();Mo();kl();iE();uf();cf();oE();sE();lE();At=class extends W{constructor(t,r){super(t,r)}insertProperty(t,r){this.addProperty(t,r)}insertChild(t){this.addChild(t)}},pf="DeserializationService";(function(e){e.Grid="Grid",e.Lookup="Lookup",e.Base="Base"})(Ft||(Ft={}));ff=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,df.trackErrorTrace)(ot,{eventName:pf,eventData:{error:f}}),new Error(f)}let p=this.createFormModel(d.item(0),r,n,i,a,o,s,l,u,c);return N.IsNullOrUndefined(p.displayCondition)&&s!==Re.Dialog&&this.appendDefaultDisplayCondition(p),p}upsertFieldCount(t,r){let n=Gn.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(!N.IsNullOrUndefined(t)){let n=N.ParseXml(r);n!==null&&this.populateElementChildren(t,n.childNodes)}}createFormModel(t,r,n,i,a,o,s,l,u,c){let d=new Ml(r,n,i,a,o,s,l,u,c);return this.populateElementProperties(d,t.attributes),this.populateElementChildren(d,t.childNodes),s===Re.Main&&(this.insertHeaderFooterElementProperties(v.formHeader,d,d.header),this.insertHeaderFooterElementProperties(v.formFooter,d,d.footer)),d}insertHeaderFooterElementProperties(t,r,n){if(N.IsNullOrUndefined(n)){let i=t===v.formHeader?new Bo(r,!0):new Uo(r,!0);At.prototype.insertProperty.call(i,m.id,"{"+P.NewGuid()+"}"),At.prototype.insertProperty.call(i,m.Fieldlabelposition,"Top"),At.prototype.insertProperty.call(i,m.columnName,ge.MarginalControlColumns),At.prototype.insertProperty.call(i,m.LabelWidth,ge.LabelWidth),At.prototype.insertProperty.call(i,m.Fieldlabelalignment,"Left");let a=null,o=new Xn(a);for(let s=0;s<i.maxColumns;s++){let l=new bt(o);At.prototype.insertProperty.call(l,m.id,"{"+P.NewGuid()+"}"),l.setDisplayName(T.EmptyString,this.lcid),At.prototype.insertProperty.call(l,m.showlabel,"false"),o.addCell(l)}i.appendRow(o),t===v.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 At(`<${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,df.trackErrorTrace)(ot,{eventName:pf,eventData:{error:n}}),new Error(n)}for(let n=0;n<r.length;n++){let i=r.item(n);i&&(At.prototype.insertProperty.call(t,i.name,i.value),t.getNodeName()===v.formCell&&i.name===m.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&&At.prototype.insertChild.call(t,a)}}createModelNode(t,r){switch(t.nodeName){case v.form:throw new Error("Form node shouldn't be created using this method");case v.formTab:return new Wr(r);case v.formColumn:return new bn(r);case v.formHeader:return new Bo(r,!1);case v.formFooter:return new Uo(r,!1);case v.formSection:return new br(v.formSection,r);case v.formRow:return new Xn(r);case v.formCell:return new bt(r);case v.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===m.indicationOfSubgrid&&l.value==="true"||l.name===m.classid&&(l.value?.toLocaleUpperCase()===`{${S.SubgridControl}}`||l.value?.toLocaleUpperCase()===`{${S.ReferencePanelSubgridControl}}`))a=Ft.Grid;else if(l.name===m.classid&&l.value?.toLocaleUpperCase()===`{${S.LookupControl}}`)a=Ft.Lookup;else if(l.name===m.classid&&l.value?.toLocaleUpperCase()===`{${S.CustomControl}}`)for(let u=0;u<i?.length;u++)i[u].nodeName===m.DefaultViewId&&(a=Ft.Lookup)}return a===Ft.Grid?new ea(r):a===Ft.Lookup?new ta(r):new nr(r);case v.formEvent:return new Zi(r,T.EmptyString);case v.dependency:return this.populateDependencyTable(t),new Yi(r,T.EmptyString);case v.Handler:let o=[];return new $l(o,r);case v.formNavigation:return new zl(t.nodeName,r);case v.formNavBarArea:return new ia(t.nodeName,r);case v.formNavBarAreas:return new aa(t.nodeName,r);case v.formNavBar:return new ql(r);case v.formNavBarByRelationshipItem:return new Vl(r);case v.formNavBarItem:return new Gl(r);case v.formDisplayConditions:return new Bl(r);case v.library:return new ra(r,T.EmptyString,T.EmptyString);case v.controlDescription:return new tl(r);case v.customControl:return this.populateCustomControlConfigurationId(t),new hl(r);default:return new At(t.nodeName,r)}}populateDependencyTable(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);i.name===m.id&&this.upsertFieldCount(i.value,hr.DependencyFieldTable)}}populateCustomControlConfigurationId(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);if(i.name===m.id){let a=new P(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===m.ForControl){let l=s.value.substr(1,i.value.length-2);Le.CustomControlIdMap.upsert(l,a);break}}break}}}}});var cE={};sr(cE,{SerializationService:()=>mf,SerializationServiceScope:()=>e5,SerializedFormElementNode:()=>oa});var e5,oa,mf,dE=I(()=>{"use strict";rt();Ge();er();of();e5="SerializationService",oa=class extends W{fetchNodeName(){return this.getNodeName()}enumerateProperties(){return this.getAllProperties()}enumerateChildren(){return this.getAllChildren()}},mf=class{langCode;constructor(t){this.langCode=t}serializeFormXmlNode(t){let r=oa.prototype.fetchNodeName.call(t);if(r.charAt(0)===Gr.StartTag)return T.EscapeXml(r.substr(1),!1);if(t.isTransient&&!t.isDirty())return T.EmptyString;let n=oa.prototype.enumerateProperties.call(t),i=oa.prototype.enumerateChildren.call(t);if(!(t instanceof Kn)){let a=`<${r}`;if(n.length!==0&&(a+=` ${this.getPropertiesString(n)}`),i.length===0)a+=" />";else{let o=T.EmptyString;for(let s of i)o+=this.serializeFormXmlNode(s);a+=`>${o}</${r}>`}return a}return T.EmptyString}getPropertiesString(t){let r=T.EmptyString;return t.forEach((n,i)=>{i!==0&&(r+=" "),r+=`${n.key}="${T.EscapeXml(n.value,!0)}"`}),r}}});var An=g(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.rebuildRaw=Ct.assembleChildren=Ct.spliceChildren=Ct.mergeAttrs=Ct.rawFromNode=Ct.emptyBag=void 0;var wn=le(),pE=1e6,jl=512;function t5(){return{a:[],c:[]}}Ct.emptyBag=t5;function fE(e,t=0){if(t>jl)throw new wn.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${jl}`);return{n:e.getNodeName(),a:e.getAllProperties().map(r=>[r.key,r.value]),c:e.getAllChildren().map(r=>fE(r,t+1))}}Ct.rawFromNode=fE;function r5(e,t){let r=new Map;for(let[a,o]of t)r.set(a,o);let n=new Set,i=[];for(let[a,o]of e)r.has(a)?i.push([a,r.get(a)]):i.push([a,o]),n.add(a);for(let[a,o]of t)n.has(a)||(i.push([a,o]),n.add(a));return i}Ct.mergeAttrs=r5;function Wl(e,t){let r=new Set;for(let s of e){let l=s.i;if(!Number.isInteger(l)||l<0||l>pE)throw new wn.InvalidArgumentError(`Bag child index must be an integer in [0, ${pE}] (got ${String(l)})`);if(r.has(l))throw new wn.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}Ct.spliceChildren=Wl;function n5(e,t){if(e.w){let r={n:e.w.n,a:e.w.a.map(n=>[n[0],n[1]]),c:Wl(e.w.c,t)};return Wl(e.c,[r])}return Wl(e.c,t)}Ct.assembleChildren=n5;function mE(e,t,r,n=0){if(n>jl)throw new wn.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${jl}`);i5(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,mE(a,t,i,n+1));return i}Ct.rebuildRaw=mE;function i5(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new wn.InvalidArgumentError(`Malformed hybrid node at depth ${t}: expected a JSON object`);let r=e;if(typeof r.n!="string")throw new wn.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 wn.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 wn.InvalidArgumentError(`Malformed hybrid node '${r.n}': each attribute must be a [string, string] pair`)}});var wr=g(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.childObjects=St.optionalGuidId=St.optionalEnum=St.eachObject=St.issue=St.isJsonObject=void 0;function hE(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}St.isJsonObject=hE;function qo(e,t,r,n){return n?{pointer:e,rule:t,message:r,fatal:n}:{pointer:e,rule:t,message:r}}St.issue=qo;function gE(e,t,r,n){if(!Array.isArray(e))return[];let i=[];return e.forEach((a,o)=>{hE(a)?i.push({node:a,index:o}):n.push(qo(`${t}/${o}`,`${r}-must-be-object`,`a ${r} must be a JSON object, got ${a===null?"null":typeof a}`))}),i}St.eachObject=gE;function a5(e,t,r,n,i,a){let o=e[t];o!==void 0&&(typeof o!="string"||!r.includes(o))&&a.push(qo(`${n}/${t}`,i,`${t} must be one of ${r.map(s=>`'${s}'`).join(", ")}, got ${JSON.stringify(o)}`))}St.optionalEnum=a5;var o5=/^(?:\{[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 s5(e,t,r,n,i){let a=e[t];typeof a=="string"&&a!==""&&!o5.test(a)&&i.push(qo(`${r}/${t}`,n,`${t} must be a GUID or empty, got '${a}'`))}St.optionalGuidId=s5;function l5(e,t,r,n,i){let a=e[t],o=`${r}/${t}`;return a===void 0?[]:Array.isArray(a)?gE(a,o,n,i):(i.push(qo(o,`${n}-list-must-be-array`,`${t} must be an array when present, got ${typeof a}`)),[])}St.childObjects=l5});var vE=g(Hl=>{"use strict";Object.defineProperty(Hl,"__esModule",{value:!0});Hl.formApi=void 0;var u5=Xt(),kt=he(),Vo=Z(),c5="formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber",d5="formid,name,type,objecttypecode",p5=2;Hl.formApi={async get(e,t){let n=`/systemforms(${(0,Vo.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Vo.odataQuery)([["$select",c5]]),i=(0,kt.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,kt.readEtag)(i)}},async list(e,t){let r=[`type eq ${p5}`];t?.entityLogicalName&&r.push(`objecttypecode eq '${(0,Vo.odataLiteral)(t.entityLogicalName)}'`);let n=`/systemforms${(0,Vo.odataQuery)([["$select",d5],["$filter",r.join(" and ")]])}`;return(await(0,u5.collectPages)(e,n,"listArtifacts('form')")).map(a=>{var o,s;return{type:"form",id:(o=a.formid)!==null&&o!==void 0?o:"",name:(s=a.name)!==null&&s!==void 0?s:"",entityLogicalName:a.objecttypecode,isDirty:!1}})},async create(e,t,r){let n=(0,kt.echoWrite)("formid"),i=`/systemforms${n.query}`,a=(0,kt.ensureSuccess)(await e.post(i,(0,kt.withClientMintedId)(t,"formid",r),n.options),e.apiUrl(i));return{id:(0,kt.resolveCreatedId)(a,"formid","form",r),etag:(0,kt.readEtag)(a)}},async update(e,t,r,n){let i=(0,Vo.normalizeGuid)(t,"id"),a=(0,kt.echoWrite)("formid",{"If-Match":(0,kt.requireEtag)(n,"form",i)}),o=`/systemforms(${i})${a.query}`,s=(0,kt.ensureSuccess)(await e.patch(o,r,a.options),e.apiUrl(o));return{id:i,etag:(0,kt.readEtag)(s)}},delete(e,t){return(0,kt.deleteRecord)(e,"systemforms",t)}}});var Cn=g(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});Ql.installDomShim=void 0;var yE=js(),bE=!1,f5={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 m5(){if(bE)return;let e=globalThis;typeof e.DOMParser>"u"&&(e.DOMParser=yE.DOMParser),typeof e.XMLSerializer>"u"&&(e.XMLSerializer=yE.XMLSerializer),typeof e.Node>"u"&&(e.Node=f5),bE=!0}Ql.installDomShim=m5});var FE=g(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.classIdForAttributeType=Nt.QUICK_VIEW_CLASS_ID=Nt.NOTES_CLASS_ID=Nt.SUBGRID_CLASS_ID=Nt.formRegistration=Nt.FormAdapter=void 0;var Mt=(xe(),lr(N0)),h5=(Pe(),lr(E0)),g5=(Ge(),lr(I0)),it=(J(),lr(D0)),Fe=(qn(),lr(_0)),v5=(rf(),lr(uE)),y5=(dE(),lr(cE)),ke=An(),wE=Yt(),Zn=wr(),b5=vE(),w5=mt(),yf=Z(),EE=Cn(),DE=fi(),A5={[it.FormType.Main]:"Main",[it.FormType.QuickCreate]:"QuickCreate",[it.FormType.QuickViewForm]:"QuickView",[it.FormType.Card]:"Card"},hf={Main:it.FormType.Main,QuickCreate:it.FormType.QuickCreate,QuickView:it.FormType.QuickViewForm,Card:it.FormType.Card},C5=new Map(Object.entries(Fe.ControlClassId).map(([e,t])=>[String(t).toUpperCase(),e]));function IE(e){var t;return e&&(t=C5.get(e.toUpperCase()))!==null&&t!==void 0?t:"Unknown"}function Go(e){return e.getAllProperties().map(t=>[t.key,t.value])}function ei(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 bf(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=>ei(s).get("languagecode")===String(t)))!==null&&r!==void 0?r:a[0];return o&&(n=ei(o).get("description"))!==null&&n!==void 0?n:""}function S5(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 PE(e){return/^1+$/.test(e)&&e.length>=1&&e.length<=4?e.length:1}function gf(e){let t=Math.min(Math.max(Math.trunc(e),1),4);return"1".repeat(t)}function ti(e){return e.replace(/[{}]/g,"")}function vf(e){return`{${ti(e)}}`}function AE(e,t){if(e===void 0||e==="")return t;let r=Number(e);return Number.isNaN(r)?t:r}function Xl(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:Go(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:Go(e),c:a,w:{n:o.getNodeName(),a:Go(o),c:l}}}}function TE(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:Go(e),c:i}}}function N5(e,t){let{modeled:r,bag:n}=Xl(e,"tabs","tab");return{tabs:r.map(i=>E5(i,t)),bag:n}}function E5(e,t){var r,n;let i=ei(e),{modeled:a,bag:o}=Xl(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:bf(e,t),expanded:i.get("expanded")==="true",visible:i.has("visible")?i.get("visible")==="true":!0,columns:a.map(s=>D5(s,t)),bag:o}}function D5(e,t){let r=ei(e),{modeled:n,bag:i}=Xl(e,"sections","section");return{width:r.get("width"),sections:n.map(a=>I5(a,t)),bag:i}}function I5(e,t){var r,n,i;let a=ei(e),{modeled:o,bag:s}=Xl(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:bf(e,t),visible:a.has("visible")?a.get("visible")==="true":!0,showLabel:a.get("showlabel")==="true",columns:PE((i=a.get("columns"))!==null&&i!==void 0?i:"1"),rows:o.map(l=>_5(l,t)),bag:s}}function _5(e,t){let{modeled:r,bag:n}=TE(e,"cell",!1);return{cells:r.map(i=>P5(i,t)),bag:n}}function P5(e,t){var r;let n=ei(e),{modeled:i,bag:a}=TE(e,"control",!0),o=bf(e,t),s=n.get("showlabel")==="true",l=i[0]?T5(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:AE(n.get("colspan"),1),rowspan:AE(n.get("rowspan"),1),control:l,bag:a}}function T5(e,t,r){var n,i;let a=ei(e),o=ti((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:IE(o),isRequired:a.get("isrequired")==="true",isReadOnly:a.get("disabled")==="true",label:t,showLabel:r,parameters:S5(e),bag:{a:Go(e),c:e.getAllChildren().map((l,u)=>({i:u,node:(0,ke.rawFromNode)(l)}))}}}function sa(e){return e.a.length===0&&e.c.length===0&&!e.w}function OE(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function ri(e,t){var r;let n=new Set(e.a.map(o=>o[0])),i=sa(e),a=[];for(let o of t)if(n.has(o.key)){let s=(r=OE(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 Sn=(e,t)=>({key:e,matches:r=>r===t,render:()=>t,absentDefault:""}),Nn=(e,t,r=!1)=>({key:e,matches:n=>n==="true"===t,render:()=>String(t),absentDefault:String(r)}),CE=(e,t,r=1)=>({key:e,matches:n=>Number(n)===t,render:()=>String(t),absentDefault:String(r)});function wf(e,t){return{n:"labels",a:[],c:[{n:"label",a:[["description",e],["languagecode",String(t)]],c:[]}]}}function xE(e){return{n:"parameters",a:[],c:Object.keys(e).map(t=>({n:(0,yf.assertXmlName)(t,"Form control parameter name"),a:[],c:[{n:`<${e[t]}`,a:[],c:[]}]}))}}function O5(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 x5(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 Af(e,t,r){let n=e.c.findIndex(a=>a.node.n==="labels");if(n<0||O5(e.c[n].node,r)===t)return e;let i=x5(e.c[n].node,t,r);return{...e,c:e.c.map((a,o)=>o===n?{...a,node:i}:a)}}function R5(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 L5(e,t){let r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every(i=>e[i]===t[i])}function F5(e,t){return e.a.some(r=>r[0]===t)?{...e,a:e.a.filter(r=>r[0]!==t)}:e}function k5(e,t){let r=e.c.findIndex(i=>i.node.n==="parameters");if(r<0||L5(R5(e.c[r].node),t))return e;let n=xE(t);return{...e,c:e.c.map((i,a)=>a===r?{...i,node:n}:i)}}function Kl(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 M5(e,t){let r=e.tabs.map(n=>U5(n,t));return{n:"form",a:ri(e.bag,[]),c:e.tabs.length===0&&sa(e.bag)?[]:Kl(e.bag,"tabs",r,()=>[])}}function U5(e,t){let r=[Sn("id",e.id),Sn("name",e.name),Nn("expanded",e.expanded),Nn("visible",e.visible,!0)],n=e.columns.map(a=>B5(a,t)),i=Af(e.bag,e.label,t);return{n:"tab",a:ri(i,r),c:Kl(i,"columns",n,()=>e.label?[wf(e.label,t)]:[])}}function B5(e,t){let r=e.width!==void 0?[Sn("width",e.width)]:[],n=e.sections.map(i=>$5(i,t));return{n:"column",a:ri(e.bag,r),c:Kl(e.bag,"sections",n,()=>[])}}function $5(e,t){let r=[Sn("id",e.id),Sn("name",e.name),Nn("showlabel",e.showLabel),Nn("visible",e.visible,!0),{key:"columns",matches:a=>PE(a)===e.columns,render:()=>gf(e.columns),absentDefault:gf(1)}],n=e.rows.map(a=>q5(a,t)),i=Af(e.bag,e.label,t);return{n:"section",a:ri(i,r),c:Kl(i,"rows",n,()=>e.label?[wf(e.label,t)]:[])}}function q5(e,t){let r=e.cells.map(n=>V5(n,t));return{n:"row",a:ri(e.bag,[]),c:sa(e.bag)?r:(0,ke.assembleChildren)(e.bag,r)}}function V5(e,t){let r=e.control?e.control.showLabel:OE(e.bag,"showlabel")==="true",n=[Sn("id",e.id),Nn("showlabel",r),Nn("visible",e.visible,!0),CE("colspan",e.colspan),CE("rowspan",e.rowspan)],i=e.control?[G5(e.control)]:[],a;if(sa(e.bag))a=[...e.control&&e.control.label?[wf(e.control.label,t)]:[],...i];else{let o=e.control?Af(e.bag,e.control.label,t):e.bag;a=(0,ke.assembleChildren)(o,i)}return{n:"cell",a:ri(e.bag,n),c:a}}function G5(e){let t=[Sn("id",e.id),{key:"classid",matches:i=>ti(i)===e.classId,render:()=>vf(e.classId),absentDefault:""}];e.fieldName!==null&&t.push(Sn("datafieldname",e.fieldName)),t.push(Nn("disabled",e.isReadOnly)),t.push(Nn("isrequired",e.isRequired));let r=e.fieldName===null?F5(e.bag,"datafieldname"):e.bag,n;return sa(r)?n=Object.keys(e.parameters).length>0?[xE(e.parameters)]:[]:n=(0,ke.assembleChildren)(k5(r,e.parameters),[]),{n:"control",a:ri(r,t),c:n}}var z5={make:(e,t)=>new g5.FormElementNode(e,t),setProp:(e,t,r)=>e.setProperty(t,r),addChild:(e,t)=>e.addChild(t)};function SE(e,t,r){(0,EE.installDomShim)();let n=j5(e,r),i=(0,ke.rebuildRaw)(M5(n,t),z5,null);return new y5.SerializationService(t).serializeFormXmlNode(i)}function W5(e){return JSON.parse(JSON.stringify(e))}function j5(e,t){var r;let n=W5(e);n.bag||(n.bag=(0,ke.emptyBag)()),e9(n.bag),t&&H5(n,t);for(let i of(r=n.tabs)!==null&&r!==void 0?r:[])Q5(i);return n}function H5(e,t){var r;let n=(r=e.entityLogicalName)!==null&&r!==void 0?r:"";RE(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=LE(s.attributeType)))})}function RE(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 Q5(e){e.id||(e.id=Mt.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)J5(t);e.bag||(e.bag=(0,ke.emptyBag)())}function J5(e){e.sections||(e.sections=[]);for(let t of e.sections)X5(t);e.bag||(e.bag=(0,ke.emptyBag)()),e.width===void 0&&sa(e.bag)&&(e.width="100%")}function X5(e){e.id||(e.id=Mt.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)K5(t);e.bag||(e.bag=(0,ke.emptyBag)())}function K5(e){e.cells||(e.cells=[]);for(let t of e.cells)Y5(t);e.bag||(e.bag=(0,ke.emptyBag)())}function Y5(e){e.id||(e.id=Mt.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&&Z5(e.control),e.bag||(e.bag=(0,ke.emptyBag)())}function Z5(e){var t;e.id||(e.id=Mt.Guid.NewGuid()),e.classId===void 0&&(e.classId=String(Fe.ControlClassId.TextboxControl)),e.fieldName===void 0&&(e.fieldName=null),e.type===void 0&&(e.type=e.fieldName?"Field":IE(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,yf.assertXmlName)(r,"Form control parameter name");e.bag||(e.bag=(0,ke.emptyBag)())}function e9(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"&&!NE(a,"handlerUniqueId")&&a.a.push(["handlerUniqueId",vf(Mt.Guid.NewGuid())])}}else if(r.n==="formLibraries")for(let n of r.c)n.n==="Library"&&!NE(n,"libraryUniqueId")&&n.a.push(["libraryUniqueId",vf(Mt.Guid.NewGuid())])}}var Jl=class{constructor(t=DE.DEFAULT_LCID){this.lcid=t}toArtifact(t){var r,n,i;let{tabs:a,bag:o}=N5(t,this.lcid);return{id:t.formId?t.formId.guidString:"",name:(r=t.formName)!==null&&r!==void 0?r:"",entityLogicalName:(n=t.entityName)!==null&&n!==void 0?n:"",formType:(i=A5[t.formType])!==null&&i!==void 0?i:"Main",status:this.readActivationStatus(t),tabs:a,bag:o}}fromArtifact(t){return this.deserialize({formxml:SE(t,this.lcid),formid:t.id||Mt.Guid.NewGuid(),objecttypecode:t.entityLogicalName,type:hf[t.formType],name:t.name,uniquename:t.name,description:"",formpresentation:it.FormPresentation.AirForm,formactivationstate:t.status==="Active"?it.FormActivationState.Active:it.FormActivationState.InActive})}fromApiResponse(t){var r,n,i,a,o,s;let l=t,u=this.deserialize({formxml:(r=l.formxml)!==null&&r!==void 0?r:"",formid:(n=l.formid)!==null&&n!==void 0?n:Mt.Guid.NewGuid(),objecttypecode:(i=l.objecttypecode)!==null&&i!==void 0?i:"",type:l.type,name:(a=l.name)!==null&&a!==void 0?a:"",uniquename:(o=l.uniquename)!==null&&o!==void 0?o:"",description:(s=l.description)!==null&&s!==void 0?s:"",formpresentation:l.formpresentation,formactivationstate:l.formactivationstate});return this.toArtifact(u)}toApiPayload(t,r,n){return{formxml:SE(t,this.lcid,n),name:t.name,type:hf[t.formType],objecttypecode:t.entityLogicalName}}metadataNeeds(t){let r=t.entityLogicalName;if(!r)return[];let n=new Set,i=[];return RE(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;let p=t.tabs&&t.tabs.length>0?void 0:u9(this.lcid),f=p!==void 0?p:t.tabs.map(w=>t9(w,this.lcid)).join(""),h=this.deserialize({formxml:`<form><tabs>${f}</tabs></form>`,formid:t.id||Mt.Guid.NewGuid(),objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",type:hf[(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:"",formpresentation:it.FormPresentation.AirForm,formactivationstate:((o=t.status)!==null&&o!==void 0?o:"Active")==="Active"?it.FormActivationState.Active:it.FormActivationState.InActive}),b=this.toArtifact(h);return{id:(s=t.id)!==null&&s!==void 0?s:b.id,name:(l=t.name)!==null&&l!==void 0?l:"New Form",entityLogicalName:(u=t.entityLogicalName)!==null&&u!==void 0?u:"",formType:(c=t.formType)!==null&&c!==void 0?c:"Main",status:(d=t.status)!==null&&d!==void 0?d:"Active",tabs:b.tabs,bag:b.bag}}assignMissingIds(t){return(0,w5.assignMissingIds)(t)}validate(t){return d9(t)}deserialize(t){(0,EE.installDomShim)();let r=h5.ScriptUtilities.ParseXml(t.formxml),n=new v5.DeserializationService(this.lcid).deSerializeFormXml(r,new Mt.Guid(t.formid),t.objecttypecode,it.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===it.FormActivationState.InActive?"Inactive":"Active"}};Nt.FormAdapter=Jl;function ir(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Cf(e,t){return e?`<labels><label description="${ir(e)}" languagecode="${t}" /></labels>`:""}function t9(e,t){let r=(e.columns.length>0?e.columns:[l9()]).map(n=>r9(n,t)).join("");return`<tab id="{${ir(ti(e.id))}}" name="${ir(e.name)}" expanded="${e.expanded}" visible="${e.visible}">${Cf(e.label,t)}<columns>${r}</columns></tab>`}function r9(e,t){var r;let n=e.sections.map(i=>n9(i,t)).join("");return`<column width="${ir((r=e.width)!==null&&r!==void 0?r:"100%")}"><sections>${n}</sections></column>`}function n9(e,t){let r=e.rows.map(n=>i9(n,t)).join("");return`<section id="{${ir(ti(e.id))}}" name="${ir(e.name)}" showlabel="${e.showLabel}" visible="${e.visible}" columns="${gf(e.columns)}">${Cf(e.label,t)}<rows>${r}</rows></section>`}function i9(e,t){return`<row>${e.cells.map(r=>a9(r,t)).join("")}</row>`}function a9(e,t){let r=e.control,n=r?Cf(r.label,t):"",i=r?o9(r):"";return`<cell id="{${ir(ti(e.id))}}" showlabel="${r?r.showLabel:!1}" visible="${e.visible}" colspan="${e.colspan}" rowspan="${e.rowspan}">${n}${i}</cell>`}function o9(e){let t=e.fieldName?` datafieldname="${ir(e.fieldName)}"`:"",r=s9(e.parameters);return`<control id="${ir(e.id)}" classid="{${ir(ti(e.classId))}}"${t} disabled="${e.isReadOnly}" isrequired="${e.isRequired}">${r}</control>`}function s9(e){let t=Object.keys(e);return t.length===0?"":(t.forEach(n=>(0,yf.assertXmlName)(n,"Form control parameter name")),`<parameters>${t.map(n=>`<${n}>${ir(e[n])}</${n}>`).join("")}</parameters>`)}function l9(){return{width:"100%",sections:[],bag:{a:[],c:[]}}}function u9(e){return`<tab id="{${Mt.Guid.NewGuid()}}" name="tab_general" expanded="true" visible="true"><labels><label description="General" languagecode="${e}" /></labels><columns><column width="100%"><sections><section id="{${Mt.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 c9(e=DE.DEFAULT_LCID){return{adapter:new Jl(e),api:b5.formApi,languageSensitive:!0,publish:(t,r,n)=>(0,wE.publishBoundEntity)(t,n),publishScope:(t,r)=>(0,wE.boundEntityPublishScope)(r)}}Nt.formRegistration=c9;function d9(e){let t=[];return(0,Zn.childObjects)(e,"tabs","","tab",t).forEach(({node:n,index:i})=>{(0,Zn.childObjects)(n,"columns",`/tabs/${i}`,"column",t).forEach(({node:o,index:s})=>{let l=`/tabs/${i}/columns/${s}`;(0,Zn.childObjects)(o,"sections",l,"section",t).forEach(({node:c,index:d})=>{let p=`${l}/sections/${d}`;(0,Zn.childObjects)(c,"rows",p,"row",t).forEach(({node:h,index:b})=>{let w=`${p}/rows/${b}`;(0,Zn.childObjects)(h,"cells",w,"cell",t).forEach(({node:D,index:L})=>{let R=D.control;R!=null&&!(0,Zn.isJsonObject)(R)&&t.push((0,Zn.issue)(`${w}/cells/${L}/control`,"control-must-be-object-or-null",`a cell control must be a JSON object or null, got ${typeof R}`))})})})})}),t}Nt.SUBGRID_CLASS_ID=Fe.ControlClassId.SubgridControl;Nt.NOTES_CLASS_ID=Fe.ControlClassId.TimelineControl;Nt.QUICK_VIEW_CLASS_ID=Fe.ControlClassId.QuickViewControl;var p9={Lookup:String(Fe.ControlClassId.LookupControl),Customer:String(Fe.ControlClassId.LookupControl),Owner:String(Fe.ControlClassId.LookupControl),PartyList:String(Fe.ControlClassId.PartyListControl),Boolean:String(Fe.ControlClassId.BooleanControl),DateTime:String(Fe.ControlClassId.DateTimeControl),Decimal:String(Fe.ControlClassId.DecimalControl),Double:String(Fe.ControlClassId.FloatingNumberControl),Money:String(Fe.ControlClassId.CurrencyControl),Integer:String(Fe.ControlClassId.IntegerControl),BigInt:String(Fe.ControlClassId.IntegerControl),Memo:String(Fe.ControlClassId.TextAreaControl),String:String(Fe.ControlClassId.TextboxControl)},f9="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE";function LE(e){return e==="Picklist"||e==="State"||e==="Status"?f9:e&&p9[e]||String(Fe.ControlClassId.TextboxControl)}Nt.classIdForAttributeType=LE;function NE(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}});var la=g(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.projectElementBag=De.serializeNode=De.domEngine=De.nodeLikeFromDom=De.parseXmlRoot=De.EMPTY_FORM_SENTINEL=De.TEXT_SENTINEL=void 0;var m9=An(),zo=le();De.TEXT_SENTINEL="#text";De.EMPTY_FORM_SENTINEL="#empty";var Zl=new WeakSet;function h9(e,t){let r=e&&e.trim()!==""?e:t,i=new DOMParser().parseFromString(r,"text/xml").documentElement;if(!i)throw new zo.InvalidArgumentError("XML source has no root element (empty or malformed input)");return v9(i),y9(i),A9(i,r),i}De.parseXmlRoot=h9;var g9=new Set([1,3]);function v9(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(!g9.has(a.nodeType))throw new zo.InvalidArgumentError(`Unsupported XML node type ${a.nodeType} (CDATA / comment / processing-instruction) is outside the hybrid projection's lossless grammar and cannot be round-tripped`);t.push(a)}}}function y9(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 zo.InvalidArgumentError(`Unsupported document-level XML node (type ${o.nodeType}: declaration / comment / processing-instruction outside the root element) cannot be round-tripped`)}}function b9(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 w9(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 ME(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 A9(e,t){let r=b9(t),n=w9(e),i=Math.min(r.length,n.length);for(let a=0;a<i;a+=1){if(r[a])continue;let o=n[a];ME(o)||Zl.add(o)}}function Sf(e){let t=e.nodeType===3;return{getNodeName:()=>t?De.TEXT_SENTINEL:e.tagName,getAllProperties:()=>{var r;if(t)return[{key:De.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 Zl.has(e)&&!ME(e)&&i.push({key:De.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(Sf(a))}return r}}}De.nodeLikeFromDom=Sf;function C9(e){return{make:t=>t===De.TEXT_SENTINEL?e.createTextNode(""):e.createElement(t),setProp:(t,r,n)=>{t.nodeType===3?t.nodeValue=n:r===De.EMPTY_FORM_SENTINEL?Zl.add(t):t.setAttribute(r,n)},addChild:(t,r)=>{t.appendChild(r)}}}De.domEngine=C9;function UE(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 Yl(r);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))throw Yl(r);t+=1;continue}if(r>=56320&&r<=57343)throw Yl(r)}}function Yl(e){let t=e.toString(16).toUpperCase().padStart(4,"0");return new zo.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 S9(e){return UE(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/\r/g,"
").replace(/\n/g,"
").replace(/\t/g,"	")}function N9(e){return UE(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function E9(e){return BE(e,0)}De.serializeNode=E9;var kE=512;function BE(e,t){var r;if(t>kE)throw new zo.InvalidArgumentError(`XML nesting exceeds the maximum supported depth of ${kE}`);if(e.nodeType===3)return N9((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+'="'+S9(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 Zl.has(n)?i+"></"+n.tagName+">":i+" />";i+=">";for(let l of o)i+=BE(l,t+1);return i+"</"+n.tagName+">"}function D9(e){let t=Sf(e);return{a:t.getAllProperties().map(r=>[r.key,r.value]),c:t.getAllChildren().map((r,n)=>({i:n,node:(0,m9.rawFromNode)(r)}))}}De.projectElementBag=D9});var Nf=g(ua=>{"use strict";Object.defineProperty(ua,"__esModule",{value:!0});ua.viewApi=ua.findDefaultViews=void 0;var qE=Xt(),Ut=he(),jr=Z(),I9="savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault",_9="savedqueryid,name,returnedtypecode,querytype,isdefault";async function P9(e,t,r={}){var n;let i=new Set(((n=r.excludeViewIds)!==null&&n!==void 0?n:[]).filter(Boolean)),a=`returnedtypecode eq '${(0,jr.odataLiteral)(t)}' and querytype eq 0`,o=`/savedqueries${(0,jr.odataQuery)([["$select","savedqueryid,name,isdefault"],["$filter",a]])}`;return(await(0,qE.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:"")}})}ua.findDefaultViews=P9;async function T9(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,jr.odataLiteral)(t)}')${(0,jr.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(e,t,r){if(!r||!/<grid\b/.test(t)||/<grid[^>]*\bobject=/.test(t))return t;let n=await T9(e,r);return n===void 0?t:t.replace(/<grid\b/,`<grid object="${n}"`)}ua.viewApi={async get(e,t){let n=`/savedqueries(${(0,jr.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,jr.odataQuery)([["$select",I9]]),i=(0,Ut.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,Ut.readEtag)(i)}},async list(e,t){let r=`/savedqueries${(0,jr.odataQuery)([["$select",_9],["$filter",t?.entityLogicalName?`returnedtypecode eq '${(0,jr.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,qE.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,Ut.echoWrite)("savedqueryid"),a=`/savedqueries${i.query}`,o=await $E(e,n.layoutxml,n.returnedtypecode),s=(0,Ut.ensureSuccess)(await e.post(a,(0,Ut.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,Ut.resolveCreatedId)(s,"savedqueryid","view",r),etag:(0,Ut.readEtag)(s)}},async update(e,t,r,n){let i=r,a=(0,jr.normalizeGuid)(t,"id"),o=(0,Ut.echoWrite)("savedqueryid",{"If-Match":(0,Ut.requireEtag)(n,"view",a)}),s=`/savedqueries(${a})${o.query}`,l=await $E(e,i.layoutxml,i.returnedtypecode),u=(0,Ut.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,Ut.readEtag)(u)}},delete(e,t){return(0,Ut.deleteRecord)(e,"savedqueries",t)}}});var eD=g(da=>{"use strict";Object.defineProperty(da,"__esModule",{value:!0});da.viewRegistration=da.ViewAdapter=void 0;var ca=wr(),Ef=An(),ni=la(),VE=Yt(),O9=Nf(),Df=Cn(),x9=mt(),jE=100,eu=class{toArtifact(t){var r,n,i,a,o,s,l,u;(0,Df.installDomShim)();let c=(r=t.fetchxml)!==null&&r!==void 0?r:"",d=(n=t.layoutxml)!==null&&n!==void 0?n:"",p=(0,ni.parseXmlRoot)(c,"<fetch/>"),f=(0,ni.parseXmlRoot)(d,"<grid/>");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:R9(p),queryType:(l=t.querytype)!==null&&l!==void 0?l:0,isDefault:(u=t.isdefault)!==null&&u!==void 0?u:!1,columns:QE(f,p),filters:KE(p),sort:XE(p),fetchBag:c?(0,ni.projectElementBag)(p):void 0,layoutBag:d?(0,ni.projectElementBag)(f):void 0}}fromArtifact(t){(0,Df.installDomShim)();let{fetchxml:r,layoutxml:n}=GE(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,Df.installDomShim)();let{fetchxml:s,layoutxml:l}=GE(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,x9.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:[]}}assignMissingIds(t){return t}validate(t){let r=[],n=t;(0,ca.childObjects)(n,"columns","","column",r),(0,ca.childObjects)(n,"sort","","sort",r);let i=n.filters;return i!=null&&((0,ca.isJsonObject)(i)?HE(i,"/filters",r):r.push((0,ca.issue)("/filters","filters-must-be-object",`filters must be a JSON object, got ${typeof i}`))),r}};da.ViewAdapter=eu;function HE(e,t,r){(0,ca.childObjects)(e,"conditions",t,"condition",r),(0,ca.childObjects)(e,"groups",t,"filterGroup",r).forEach(({node:i,index:a})=>HE(i,`${t}/groups/${a}`,r))}function R9(e){var t;let r=e.getElementsByTagName("entity")[0];return(t=r?.getAttribute("name"))!==null&&t!==void 0?t:""}function QE(e,t){var r;let n=JE(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)?jE:c,order:o},p=n.get(u);p&&(d.relatedEntity=p),o+=1,a.push(d)}return a}function JE(e){var t;let r=new Map,n=e.getElementsByTagName("link-entity");for(let i=0;i<n.length;i+=1){let a=n[i],o=a.getAttribute("name");if(!o)continue;let s=a.getElementsByTagName("attribute");for(let l=0;l<s.length;l+=1){let u=s[l],c=(t=u.getAttribute("alias"))!==null&&t!==void 0?t:u.getAttribute("name");c&&r.set(c,o)}}return r}function XE(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"})}}return n}function KE(e){let t=e.getElementsByTagName("entity")[0],r={type:"and",conditions:[],groups:[]};if(!t)return r;let n=Bt(t,"filter").filter(i=>!YE(i)).map(ZE);return n.length===0?r:n.length===1?n[0]:{type:"and",conditions:[],groups:n}}function YE(e){if(Bt(e,"filter").length>0)return!1;let t=Bt(e,"condition");return t.length===0?!1:t.some(r=>r.getAttribute("isquickfindfields")==="1"||Bt(r,"value").length>0)}function ZE(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),i.push(c)}else l.tagName==="filter"&&a.push(ZE(l))}return{type:n,conditions:i,groups:a}}function Bt(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 GE(e){let t=L9(e.columns);if(!zE(e.fetchBag)||!zE(e.layoutBag))return{fetchxml:z9({...e,columns:t}),layoutxml:W9({...e,columns:t},`${e.entityLogicalName}id`)};let r=new DOMParser().parseFromString("<root/>","text/xml"),n=WE(e.fetchBag,"fetch",r),i=WE(e.layoutBag,"grid",r),a=QE(i,n),o=!If(t,a),s=!If(e.sort,XE(n)),l=!If(e.filters,KE(n));return o&&(F9(r,n,t,a),B9(r,i,t)),s&&V9(r,n,e.sort),l&&G9(r,n,e.filters),{fetchxml:(0,ni.serializeNode)(n),layoutxml:(0,ni.serializeNode)(i)}}function L9(e){return(e??[]).map((t,r)=>{var n,i;return{name:String(t.name).toLowerCase(),width:(n=t.width)!==null&&n!==void 0?n:jE,order:(i=t.order)!==null&&i!==void 0?i:r,...t.relatedEntity?{relatedEntity:t.relatedEntity}:{}}})}function zE(e){return!!e&&(e.c.length>0||e.a.length>0)}function WE(e,t,r){let n={n:t,a:(0,Ef.mergeAttrs)(e.a,[]),c:(0,Ef.spliceChildren)(e.c,[])};return(0,Ef.rebuildRaw)(n,(0,ni.domEngine)(r),null)}function F9(e,t,r,n){var i;let a=t.getElementsByTagName("entity")[0];if(!a)return;let o=new Set(r.map(u=>{var c;return`${(c=u.relatedEntity)!==null&&c!==void 0?c:""}:${u.name}`}));for(let u of n)o.has(`${(i=u.relatedEntity)!==null&&i!==void 0?i:""}:${u.name}`)||k9(a,u);let s=JE(t),l=new Set(Bt(a,"attribute").map(u=>u.getAttribute("name")).filter(u=>!!u));for(let u of[...r].sort((c,d)=>c.order-d.order))if(u.relatedEntity){if(s.get(u.name)===u.relatedEntity)continue;let c=M9(e,a,u.relatedEntity),d=e.createElement("attribute");d.setAttribute("name",u.name),c.appendChild(d),s.set(u.name,u.relatedEntity)}else{if(l.has(u.name))continue;let c=e.createElement("attribute");c.setAttribute("name",u.name),U9(a,c),l.add(u.name)}}function k9(e,t){var r;if(t.relatedEntity){for(let n of Bt(e,"link-entity"))if(n.getAttribute("name")===t.relatedEntity){for(let i of Bt(n,"attribute"))if(((r=i.getAttribute("alias"))!==null&&r!==void 0?r:i.getAttribute("name"))===t.name){n.removeChild(i);return}}return}for(let n of Bt(e,"attribute"))if(n.getAttribute("name")===t.name){e.removeChild(n);return}}function M9(e,t,r){for(let i of Bt(t,"link-entity"))if(i.getAttribute("name")===r)return i;let n=e.createElement("link-entity");return n.setAttribute("name",r),t.appendChild(n),n}function U9(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 B9(e,t,r){let n=t.getElementsByTagName("row")[0];if(!n)return;let i=[...r].sort((s,l)=>s.order-l.order),a=$9(n);if(q9(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 $9(e){return Bt(e,"cell").filter(t=>!!t.getAttribute("name")&&t.getAttribute("ishidden")!=="1")}function q9(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 V9(e,t,r){let n=t.getElementsByTagName("entity")[0];if(n){for(let i of Bt(n,"order"))n.removeChild(i);for(let i of r){let a=e.createElement("order");a.setAttribute("attribute",i.attribute),a.setAttribute("descending",String(i.descending)),n.appendChild(a)}}}function G9(e,t,r){let n=t.getElementsByTagName("entity")[0];if(n){for(let i of Bt(n,"filter"))YE(i)||n.removeChild(i);(r.conditions.length>0||r.groups.length>0)&&n.appendChild(_f(e,r))}}function If(e,t){return JSON.stringify(e)===JSON.stringify(t)}function z9(e){let t=new DOMParser().parseFromString("<fetch/>","text/xml"),r=t.documentElement;r.setAttribute("version","1.0"),r.setAttribute("mapping","logical");let n=t.createElement("entity");n.setAttribute("name",e.entityLogicalName),r.appendChild(n);let i=new Map;for(let a of[...e.columns].sort((o,s)=>o.order-s.order)){let o=t.createElement("attribute");if(o.setAttribute("name",a.name),a.relatedEntity){let s=i.get(a.relatedEntity);s||(s=t.createElement("link-entity"),s.setAttribute("name",a.relatedEntity),n.appendChild(s),i.set(a.relatedEntity,s)),s.appendChild(o)}else n.appendChild(o)}for(let a of e.sort){let o=t.createElement("order");o.setAttribute("attribute",a.attribute),o.setAttribute("descending",String(a.descending)),n.appendChild(o)}return(e.filters.conditions.length>0||e.filters.groups.length>0)&&n.appendChild(_f(t,e.filters)),new XMLSerializer().serializeToString(t)}function _f(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.value!==void 0&&i.setAttribute("value",n.value),r.appendChild(i)}for(let n of t.groups)r.appendChild(_f(e,n));return r}function W9(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 j9(){return{adapter:new eu,api:O9.viewApi,publish:(e,t,r)=>(0,VE.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,VE.boundEntityPublishScope)(t)}}da.viewRegistration=j9});function tD(e,t=0){return(Ke[e[t+0]]+Ke[e[t+1]]+Ke[e[t+2]]+Ke[e[t+3]]+"-"+Ke[e[t+4]]+Ke[e[t+5]]+"-"+Ke[e[t+6]]+Ke[e[t+7]]+"-"+Ke[e[t+8]]+Ke[e[t+9]]+"-"+Ke[e[t+10]]+Ke[e[t+11]]+Ke[e[t+12]]+Ke[e[t+13]]+Ke[e[t+14]]+Ke[e[t+15]]).toLowerCase()}var Ke,rD=I(()=>{Ke=[];for(let e=0;e<256;++e)Ke.push((e+256).toString(16).slice(1))});function Pf(){return tu>ru.length-16&&((0,nD.randomFillSync)(ru),tu=0),ru.slice(tu,tu+=16)}var nD,ru,tu,iD=I(()=>{nD=require("crypto"),ru=new Uint8Array(256),tu=ru.length});var aD,Tf,oD=I(()=>{aD=require("crypto"),Tf={randomUUID:aD.randomUUID}});function H9(e,t,r){if(Tf.randomUUID&&!t&&!e)return Tf.randomUUID();e=e||{};let n=e.random??e.rng?.()??Pf();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 tD(n)}var ut,sD=I(()=>{oD();iD();rD();ut=H9});var Of=I(()=>{sD()});var lD=I(()=>{"use strict";});var xf=g($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.WorkflowConditionOperator=$t.WorkflowAttributeType=$t.SystemStep=$t.FieldRequiredLevelTypes=$t.AttributeDateTimeBehavior=void 0;$t.AttributeDateTimeBehavior={None:0,Dynamic:1,DateOnly:2,StaticTimeZoneInvariant:3,UserLocal:4};$t.FieldRequiredLevelTypes={None:"0",Required:"1",Recommended:"2"};$t.SystemStep={IdentifyContact:"IdentifyContact",IdentifyAccount:"IdentifyAccount",IdentifyCustomer:"IdentifyCustomer",IdentifyCase:"IdentifyCase",Solution:"Solution",Resolve:"Resolve"};$t.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"};$t.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 yD(e){return e&&e!==Ar.WorkflowAttributeType.String?e:void 0}function X9(e){return{__class:vD,parameterName:"primaryEntity",entityName:e}}function uD(e){return{__class:Lf,type:Rf,typeSet:!1,behavior:Ar.AttributeDateTimeBehavior.None,method:pD,parameters:[e]}}function cD(e,t,r=Ar.WorkflowAttributeType.String){return{__class:mD,type:r,behavior:Ar.AttributeDateTimeBehavior.None,typeSet:!1,entity:X9(t),attributeName:e}}function K9(e,t=Ar.WorkflowAttributeType.String){return{__class:hD,type:t,behavior:Ar.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function Y9(e){return{__class:gD,type:Rf,typeSet:!1,behavior:Ar.AttributeDateTimeBehavior.None,days:e,hours:"0",minutes:"0",months:"0",years:"0"}}function bD(e,t){let r=Q9[e.operator],n=uD(cD(e.leftField,t,e.leftWorkflowType)),i;e.dateArithmetic?i=Y9(e.right.value??"0"):e.right.kind==="field"?i=cD(e.right.field??"",t,e.right.workflowType):i=K9(e.right.value??"",e.right.workflowType??e.leftWorkflowType);let a=uD(i);return{__class:Lf,type:Rf,typeSet:!1,behavior:Ar.AttributeDateTimeBehavior.None,method:fD,parameters:[r,n,a]}}function wD(e){return typeof e=="object"&&e.__class===Lf}function Z9(e){return typeof e=="object"&&e.__class===gD}function nu(e){return wD(e)&&e.method===pD&&e.parameters.length>0?nu(e.parameters[0]):e}function dD(e){if(typeof e!="object"||e.__class!==mD)return null;let t=e.entity;if(t&&t.__class&&t.__class!==vD)return null;let r=e.attributeName;return r?{field:r,workflowType:yD(e.type)}:null}function AD(e){if(!e)return null;let t=nu(e);if(!wD(t)||t.method!==fD||t.parameters.length!==3)return null;let r=t.parameters[0],n=J9[String(r)];if(!n)return null;let i=dD(nu(t.parameters[1]));if(!i)return null;let a=nu(t.parameters[2]);if(Z9(a))return n!=="+"&&n!=="-"?null:{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:String(a.days??"")},dateArithmetic:!0};let o=dD(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===hD){let s=a.primitiveValue;return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:s!=null?String(s):"",workflowType:yD(a.type)}}}return null}function iu(e){return!e||!e.leftField?!1:e.right.kind==="field"?!!(e.right.field&&e.right.field.trim()):!!(e.right.value&&e.right.value.trim())}var Ar,pD,fD,Rf,mD,hD,Lf,gD,vD,Q9,J9,Ff=I(()=>{"use strict";Ar=se(xf());pD="0",fD="3",Rf="0",mD="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",hD="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",Lf="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",gD="TimeSpanExpression:#Microsoft.Crm.Workflow.Expressions",vD="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions";Q9={"+":0,"-":1,"*":2,"/":3},J9={0:"+",1:"-",2:"*",3:"/"}});var xD={};sr(xD,{DEFAULT_DESERIALIZE_LABELS:()=>OD,WorkflowJsonMapper:()=>Ho,deserializeWorkflowJson:()=>a8,serializeToWorkflowJson:()=>i8});function CD(e){return e.__class==="BinaryExpression:#Microsoft.Crm.Workflow.Expressions"}function e8(e){return e.__class==="ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel"}function Wo(){return{list:[]}}function SD(e,t,r){return e&&e.list.length>0?{list:[{...e.list[0],description:t},...e.list.slice(1)]}:{list:[{labelId:ut(),languageCode:r,description:t}]}}function Bf(e){return{__class:"PrimaryEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:"primaryEntity",entityName:e}}function $f(e,t,r){return{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,entity:Bf(t),attributeName:e}}function jo(e,t){return{__class:"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",type:t,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function TD(e){return{__class:"LookupExpression:#Microsoft.Crm.Workflow.Expressions",type:e.workflowType??z.WorkflowAttributeType.Lookup,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,entityType:e.entityType,label:e.label,staticValue:jo(e.id.replace(/[{}]/g,""),z.WorkflowAttributeType.UniqueIdentifier)}}function ND(e,t){let r=e.valueType==="Lookup"?e.lookupValue?.workflowType??z.WorkflowAttributeType.Lookup:e.valueType==="Clear"?e.valueWorkflowType??z.WorkflowAttributeType.String:z.WorkflowAttributeType.String,n=Uf[e.operator]??z.WorkflowConditionOperator.Equal,i=$f(e.field,t,r),a;if(e.operator==="ContainsData"||e.operator==="DoesNotContainData")a=[];else if(e.valueType==="Field"&&e.valueField)a=[$f(e.valueField,t,r)];else if(e.valueType==="Lookup"){if(!e.lookupValue)throw new Error("Lookup condition is missing its record value.");a=[TD(e.lookupValue)]}else e.valueType==="Clear"?a=[jo(null,r)]:e.valueType==="Expression"?a=[ou(e.valueType,e.value,e.valueField,t,e.expression,e.rawExpression)]:a=[jo(e.value??"",r)];return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:i,right:a}}function t8(e,t,r){if(e.length===0)return null;if(e.length===1)return ND(e[0],r);let n=t==="AND"?z.WorkflowConditionOperator.LogicalAnd:z.WorkflowConditionOperator.LogicalOr,[i,...a]=e.map(o=>ND(o,r));return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.String,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:i,right:a}}function au(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!==z.WorkflowAttributeType.Lookup?{workflowType:e.type}:{}}}}if(e.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"){let t=AD(e);return t?{valueType:"Expression",expression:t}:{valueType:"Expression",rawExpression:e}}return{valueType:"Value",value:""}}function kf(e){let t=PD[e.conditionOperatoroperator]??"Equals",r=e.left.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"?e.left.attributeName:"",i=t==="ContainsData"||t==="DoesNotContainData"?{valueType:"Value"}:au(e.right[0]);return{id:ut(),field:r,fieldDisplayName:r,operator:t,...i}}function ED(e){if(!e||e.__class!=="BinaryExpression:#Microsoft.Crm.Workflow.Expressions")return{clauses:[],logic:"AND"};let t=e.conditionOperatoroperator;if(t===z.WorkflowConditionOperator.LogicalAnd||t===z.WorkflowConditionOperator.LogicalOr){let r=t===z.WorkflowConditionOperator.LogicalAnd?"AND":"OR";return{clauses:[...CD(e.left)?[kf(e.left)]:[],...e.right.filter(CD).map(kf)],logic:r}}return{clauses:[kf(e)],logic:"AND"}}function ou(e,t,r,n,i,a,o,s){if(e==="Field"&&r)return $f(r,n,z.WorkflowAttributeType.String);if(e==="Expression"){if(i)return bD(i,n);if(a!=null)return a}return e==="Lookup"&&o?TD(o):e==="Clear"?jo(null,s??z.WorkflowAttributeType.String):jo(t??"",z.WorkflowAttributeType.String)}function Mf(e,t){return{propertyName:e,propertyValueExpr:t}}function pa(e){return`Step_${e.value++}`}function qt(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 DD(e,t,r){return e&&!r.used.has(e)?(r.used.add(e),e):qt(t,r)}function r8(e){return e===_D.StateCode.Activated?"Active":"Draft"}function n8(e,t){let r=e.processtriggerscope,n=e.processtriggerformid;return r===1&&n?n:r===2?"Entity":t??"Entity"}function i8(e,t=1033){return new Ho({languageCode:t}).serialize(e)}function a8(e){return new Ho().deserialize(e)}var _D,z,Uf,PD,OD,Ho,RD=I(()=>{"use strict";Of();_D=se(fn());lD();Ff();z=se(xf());Uf={Equals:z.WorkflowConditionOperator.Equal,DoesNotEqual:z.WorkflowConditionOperator.NotEqual,IsGreaterThan:z.WorkflowConditionOperator.GreaterThan,IsLessThan:z.WorkflowConditionOperator.LessThan,IsGreaterThanEqualTo:z.WorkflowConditionOperator.GreaterThanOrEqual,IsLessThanEqualTo:z.WorkflowConditionOperator.LessThanOrEqual,Contains:z.WorkflowConditionOperator.Contains,DoesNotContain:z.WorkflowConditionOperator.DoesNotContain,BeginsWith:z.WorkflowConditionOperator.BeginsWith,DoesNotBeginWith:z.WorkflowConditionOperator.DoesNotBeginWith,EndsWith:z.WorkflowConditionOperator.EndsWith,DoesNotEndWith:z.WorkflowConditionOperator.DoesNotEndWith,On:z.WorkflowConditionOperator.On,NotOn:z.WorkflowConditionOperator.NotOn,ContainsData:z.WorkflowConditionOperator.NotNull,DoesNotContainData:z.WorkflowConditionOperator.IsNull},PD={};for(let e of Object.keys(Uf))PD[Uf[e]]=e;OD={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"};Ho=class{resolveLabel;languageCode;entityName="";stepCounter={value:0};idCounter={counts:{},used:new Set};constructor(t={}){this.resolveLabel=t.resolveLabel??(r=>OD[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={__class:"WorkflowStep:#Microsoft.Crm.Workflow.ObjectModel",id:r?.id??t.ruleId??ut(),name:r?.name??"Step_0",description:r!==void 0?r.description:t.description||null,stepLabels:Wo(),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:qt("SetAttributeValueStep",this.idCounter),description:t.displayName||"New Action",name:t.stepName??pa(this.stepCounter),stepLabels:{list:[]},specification:Mf(t.field,ou(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType)),entity:Bf(this.entityName)}}makeRecommendationActionStep(t,r,n){let i=r.map(l=>this.makeApplyActionStep(l)),a=t??"",o=n?.stepLabels,s=SD(o,a,this.languageCode);return{__class:"ActionStep:#Microsoft.Crm.Workflow.ObjectModel",id:DD(n?.id,"ActionStep",this.idCounter),name:n?.name??pa(this.stepCounter),description:n?.description??"Action step",stepLabels:s,steps:{list:i},actionId:null,actionType:n?.actionType??"4",processId:n?.processId??ut(),uniqueName:n?.uniqueName??`id_${ut().replace(/-/g,"")}ActionStep`}}serializeAction(t){let r=Bf(this.entityName),n=t.stepName??pa(this.stepCounter),i=t.stepLabels??Wo(),a={name:n,stepLabels:i,description:t.displayName},o=t.type;switch(o){case"SetFieldValue":return{...a,id:qt("SetAttributeValueStep",this.idCounter),__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:Mf(t.field,ou(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"SetDefaultValue":return{...a,id:qt("SetDefaultValueStep",this.idCounter),__class:"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:Mf(t.field,ou(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"LockUnlock":return{...a,id:qt("SetDisplayModeStep",this.idCounter),__class:"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"attribute",isReadOnly:t.lock,entity:r};case"SetBusinessRequired":return{...a,id:qt("SetFieldRequiredLevelStep",this.idCounter),__class:"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"attribute",requiredLevel:t.required?z.FieldRequiredLevelTypes.Required:z.FieldRequiredLevelTypes.None,entity:r};case"SetVisibility":return{...a,id:qt("SetVisibilityStep",this.idCounter),__class:"SetVisibilityStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"attribute",isVisible:t.visible,entity:r};case"ShowErrorMessage":{let s=t.errorMessage||t.displayName,l=t.stepLabels&&t.stepLabels.list.length>0?t.stepLabels:{list:[{labelId:ut(),languageCode:this.languageCode,description:s}]};return{...a,id:qt("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=SD(t.stepLabels,s,this.languageCode),u={list:[this.makeRecommendationActionStep(t.acceptanceText,t.applyActions??[],t.recommendationActionStepMeta)]};return{...a,id:qt("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??pa(this.stepCounter),n=qt("ConditionStep",this.idCounter),i=[],a=t,o=!0;for(;a;){let s=t8(a.clauses,a.logic,this.entityName),l=o?a.branchName??pa(this.stepCounter):pa(this.stepCounter),c={__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:o?DD(a.branchId,"ConditionBranchStep",this.idCounter):qt("ConditionBranchStep",this.idCounter),name:l,description:a.displayName,stepLabels:Wo(),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:Wo(),containsElsebranch:i.length>1,steps:{list:i}}}makeTerminalElseBranch(t){return{__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:qt("ConditionBranchStep",this.idCounter),name:"Else",description:null,stepLabels:Wo(),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??ut():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};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:n8(r,i?.formId),status:r8(t.statecode),rootCondition:n,wfomRoot:i}}deserializeConditionStep(t){let r=(t.steps?.list??[]).filter(e8);return this.buildConditionNodeFromBranches(r,t,!0)}buildConditionNodeFromBranches(t,r,n){let[i,...a]=t,{clauses:o,logic:s}=ED(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)??ut(),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}}deserializeElseChain(t,r){if(t.length===0)return[];let[n]=t,{clauses:i}=ED(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||ut(),field:u?.propertyName??"",stepName:l.name??void 0,displayName:l.description??void 0,...au(u?.propertyValueExpr)}}),meta:i,acceptanceText:o}}deserializeAction(t){switch(t.__class){case"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=au(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=au(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!==z.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}}}});function LD(e,t){return e==="SetFieldValue"&&t!==void 0&&o8.has(t.attributeType)&&(t.requiredLevel==="None"||t.requiredLevel==="Recommended")}var o8,FD=I(()=>{"use strict";o8=new Set(["Integer","Double","Decimal","Money","String","Memo","DateTime","Picklist","Lookup"])});function fa(e){return!s8.has(e)}function kD(e){return l8.has(e)?"string":e==="Money"?"money":e==="Integer"||e==="BigInt"?"integer":e==="Decimal"||e==="Double"?"decimal":u8.has(e)?"date":c8.has(e)?"boolean":"other"}function MD(e,t){let r=kD(e),n=kD(t);return r==="other"||n==="other"?e===t:r===n}var s8,l8,u8,c8,UD=I(()=>{"use strict";s8=new Set(["ContainsData","DoesNotContainData"]);l8=new Set(["String","Memo","EntityName"]),u8=new Set(["DateTime"]),c8=new Set(["Boolean"])});var QD={};sr(QD,{addElseIfInTree:()=>h8,appendToBranch:()=>f8,buildBreadcrumb:()=>C8,collectUsedFields:()=>w8,createEmptyAction:()=>b8,createEmptyCondition:()=>WD,findNode:()=>VD,findParent:()=>ma,getBranchPosition:()=>y8,hasAnyTriggerGeneratingAction:()=>zf,isTriggerGeneratingAction:()=>qD,moveBranchItemInTree:()=>v8,removeElseIfInTree:()=>g8,removeNodeFromTree:()=>GD,updateActionInTree:()=>Vf,updateConditionInTree:()=>ii,validateTree:()=>A8});function qD(e){return d8.has(e.type)}function qf(e,t,r,n,i,a){let o=i.get(r);o&&p8.has(o.attributeType)&&n==="Value"&&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.`})}function BD(e,t,r,n,i,a,o){if(i!=="Clear")return;let s=a.get(n);LD(r,s)||o.push({nodeId:e,kind:"INVALID_CLEAR_FOR_FIELD",message:`${t}: Clear is only supported for optional fields with a legacy-compatible type.`})}function zf(e){if(!e)return!1;for(let t of[...e.trueBranch,...e.falseBranch])if(t.kind==="action"){if(qD(t))return!0}else if(zf(t))return!0;return!1}function VD(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=VD(r,t);if(n)return n}}return null}function ma(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=ma(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=ma(n,t);if(i)return i}}return null}function GD(e,t){return{...e,trueBranch:$D(e.trueBranch,t),falseBranch:$D(e.falseBranch,t)}}function $D(e,t){return e.filter(r=>r.id!==t).map(r=>r.kind==="condition"?GD(r,t):r)}function ii(e,t,r){return e.id===t?r(e):{...e,trueBranch:e.trueBranch.map(n=>n.kind==="condition"?ii(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="condition"?ii(n,t,r):n)}}function Vf(e,t,r){return{...e,trueBranch:e.trueBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?Vf(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?Vf(n,t,r):n)}}function f8(e,t,r,n){return ii(e,t,i=>({...i,trueBranch:r==="true"?[...i.trueBranch,n]:i.trueBranch,falseBranch:r==="false"?[...i.falseBranch,n]:i.falseBranch}))}function m8(e){return e.length===1&&e[0].kind==="condition"}function h8(e,t,r){return ii(e,t,n=>zD(n,r))}function zD(e,t){if(m8(e.falseBranch))return{...e,falseBranch:[zD(e.falseBranch[0],t)]};let r=WD(t);return r.falseBranch=e.falseBranch,{...e,falseBranch:[r]}}function g8(e,t){let r=ma(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 ii(e,r.node.id,a=>({...a,falseBranch:i}))}function v8(e,t,r){let n=ma(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 ii(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 y8(e,t){let r=ma(e,t);if(!r)return null;let n=r.branch==="true"?r.node.trueBranch:r.node.falseBranch;return{isFirst:r.index===0,isLast:r.index===n.length-1}}function WD(e){return{kind:"condition",id:ut(),displayName:e??"New Condition",clauses:[],logic:"AND",trueBranch:[],falseBranch:[],isCollapsed:!1}}function b8(e,t){let r={kind:"action",id:ut(),type:e,displayName:t??`New ${e}`};switch(e){case"Recommendation":return{...r,type:"Recommendation",field:"",recommendationTitle:"",messageText:"",applyActions:[{id:ut(),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 w8(e){if(!e)return[];let t=[];return jD(e,t),[...new Set(t)]}function jD(e,t){e.clauses.forEach(r=>{r.field&&t.push(r.field)}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"?jD(r,t):"field"in r&&r.field&&t.push(r.field)})}function A8(e,t=[]){if(!e)return[{nodeId:"root",kind:"NO_CONDITION",message:"A business rule must include at least one condition."}];let r=[],n=new Map(t.map(i=>[i.logicalName,i]));return HD(e,r,n),zf(e)||r.push({nodeId:"root",kind:"NO_ACTION",message:"A business rule must include at least one action step."}),r}function HD(e,t,r){e.clauses.length===0&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Add at least one clause to this condition."}),e.clauses.forEach(n=>{if(!n.field)t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a field for this clause."});else if(fa(n.operator)&&n.valueType==="Value"&&!n.value)t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause."});else if(fa(n.operator)&&n.valueType==="Value"&&n.value){let i=r.get(n.field);i?.maxLength&&n.value.length>i.maxLength&&t.push({nodeId:e.id,kind:"CLAUSE_VALUE_TOO_LONG",message:`Value exceeds the field's maximum length of ${i.maxLength} characters.`})}else fa(n.operator)&&n.valueType==="Expression"&&!n.rawExpression&&!iu(n.expression)&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please complete the formula for this clause."});fa(n.operator)&&n.valueType==="Lookup"&&(!n.lookupValue?.entityType||!n.lookupValue.id||!n.lookupValue.label)&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a lookup record for this clause."}),fa(n.operator)&&qf(e.id,"Condition",n.field,n.valueType,r,t)}),[...e.trueBranch,...e.falseBranch].forEach(n=>{if(n.kind==="condition")HD(n,t,r);else{if(!("field"in n)||!n.field)t.push({nodeId:n.id,kind:"EMPTY_ACTION_FIELD",message:`${n.type}: a target field is required.`});else if((n.type==="SetFieldValue"||n.type==="SetDefaultValue")&&n.valueType==="Value"&&n.value){let i=r.get(n.field);i?.maxLength&&n.value.length>i.maxLength&&t.push({nodeId:n.id,kind:"ACTION_VALUE_TOO_LONG",message:`${n.type}: value exceeds the field's maximum length of ${i.maxLength} characters.`})}else if((n.type==="SetFieldValue"||n.type==="SetDefaultValue")&&n.valueType==="Field"){if(!n.valueField)t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:`${n.type}: please select a field to copy from.`});else if(r.size>0){let i=r.get(n.field),a=r.get(n.valueField);i&&a&&!MD(i.attributeType,a.attributeType)&&t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:`${n.type}: the source field's type is not compatible with the target field.`})}}else(n.type==="SetFieldValue"||n.type==="SetDefaultValue")&&n.valueType==="Expression"?!n.rawExpression&&!iu(n.expression)&&t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:`${n.type}: please complete the formula.`}):(n.type==="SetFieldValue"||n.type==="SetDefaultValue")&&n.valueType==="Lookup"&&(!n.lookupValue?.entityType||!n.lookupValue.id||!n.lookupValue.label)&&t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:`${n.type}: please complete the lookup record.`});if((n.type==="SetFieldValue"||n.type==="SetDefaultValue")&&n.field&&(qf(n.id,n.type,n.field,n.valueType,r,t),BD(n.id,n.type,n.type,n.field,n.valueType,r,t)),n.type==="Recommendation"){let i=n.applyActions??[];i.length===0&&t.push({nodeId:n.id,kind:"RECOMMENDATION_NO_APPLY_ACTION",message:"Recommendation: add at least one action to apply."}),i.forEach(a=>{a.field?a.valueType==="Field"?a.valueField||t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please select a field to copy from."}):a.valueType==="Expression"?!a.rawExpression&&!iu(a.expression)&&t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the formula."}):a.valueType==="Lookup"?(!a.lookupValue?.entityType||!a.lookupValue.id||!a.lookupValue.label)&&t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the lookup record."}):a.valueType==="Clear"||a.value||t.push({nodeId:n.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please enter a value for each action to apply."}):t.push({nodeId:n.id,kind:"EMPTY_ACTION_FIELD",message:"Recommendation: a target field is required for each action to apply."}),a.field&&(qf(n.id,"Recommendation",a.field,a.valueType,r,t),BD(n.id,"Recommendation","SetFieldValue",a.field,a.valueType,r,t))})}}})}function C8(e,t){let r=[];return Gf(e,t,r),r}function Gf(e,t,r){if(e.id===t)return r.push({conditionId:e.id,label:e.displayName}),!0;for(let n of e.trueBranch)if(n.kind==="condition"){if(r.push({conditionId:e.id,label:e.displayName}),Gf(n,t,r))return!0;r.pop()}for(let n of e.falseBranch)if(n.kind==="condition"){if(r.push({conditionId:e.id,label:e.displayName}),Gf(n,t,r))return!0;r.pop()}return!1}var d8,p8,JD=I(()=>{"use strict";Of();FD();UD();Ff();d8=new Set(["LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]);p8=new Set(["Lookup","Customer","Owner"])});var t2=g(Hr=>{"use strict";Object.defineProperty(Hr,"__esModule",{value:!0});Hr.SUPPORTED_OPERATORS=Hr.SUPPORTED_ACTION_TYPES=Hr.buildBusinessRuleXaml=void 0;var S8=fn(),Vt=le(),N8=Z(),E8=['xmlns="http://schemas.microsoft.com/netfx/2009/xaml/activities"','xmlns:mcwc="clr-namespace:Microsoft.Crm.Workflow.ClientActivities;assembly=Microsoft.Crm.Workflow, 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:mxsq="clr-namespace:Microsoft.Xrm.Sdk.Query;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:s="clr-namespace:System;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"','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"'].join(" "),Qo=e=>`Microsoft.Crm.Workflow.Activities.${e}, Microsoft.Crm.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35`,YD="[InputEntities("primaryEntity")]",jf={Equals:"Equal",DoesNotEqual:"NotEqual",ContainsData:"NotNull",DoesNotContainData:"Null"},D8=new Set(["NotNull","Null"]),ZD={SetVisibility:{element:"SetVisibility",attribute:"IsVisible",value:e=>XD(e.visible,"SetVisibility","visible")},LockUnlock:{element:"SetDisplayMode",attribute:"IsReadOnly",value:e=>XD(e.lock,"LockUnlock","lock")},SetBusinessRequired:{element:"SetFieldRequiredLevel",attribute:"RequiredLevel",value:e=>I8(e.required)}};function Et(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Wf(e){return Et(`"${String(e??"").replace(/"/g,'""')}"`)}function XD(e,t,r){if(typeof e!="boolean")throw new Vt.ValidationError("businessRule",t,`/${r}`,`${t} requires a boolean '${r}'`);return e?"True":"False"}function I8(e){if(typeof e=="boolean")return e?"Required":"None";if(e==="Required"||e==="None"||e==="Recommended")return e;throw new Vt.ValidationError("businessRule","SetBusinessRequired","/required","SetBusinessRequired requires a boolean 'required', or one of 'Required' | 'Recommended' | 'None'")}function _8(e){if(!(e===void 0||e===""))return/^\d+$/.test(e)?S8.AttributeTypeCodeNum[Number(e)]:e}function e2(e){var t,r;if(e.valueType!==void 0&&e.valueType!=="Value")throw new Vt.ValidationError("businessRule",e.id||e.field||"value",`/${(t=e.field)!==null&&t!==void 0?t:"value"}`,`valueType '${e.valueType}' is not compiled by this increment (only a literal 'Value'). Compiling it as a literal would silently change what the rule compares.`);let n=_8(e.valueWorkflowType),i={Picklist:{propertyType:"OptionSetValue",attributeType:"Picklist",targetType:"mxs:OptionSetValue"},State:{propertyType:"OptionSetValue",attributeType:"State",targetType:"mxs:OptionSetValue"},Status:{propertyType:"OptionSetValue",attributeType:"Status",targetType:"mxs:OptionSetValue"},Boolean:{propertyType:"Boolean",attributeType:"Boolean",targetType:"x:Boolean"},String:{propertyType:"String",attributeType:"String",targetType:"x:String"},Memo:{propertyType:"String",attributeType:"Memo",targetType:"x:String"},Integer:{propertyType:"Int",attributeType:"Integer",targetType:"x:Int32"},Double:{propertyType:"Double",attributeType:"Double",targetType:"x:Double"},Decimal:{propertyType:"Decimal",attributeType:"Decimal",targetType:"x:Decimal"},Money:{propertyType:"Money",attributeType:"Money",targetType:"mxs:Money"}};if(n&&i[n])return i[n];throw new Vt.ValidationError("businessRule",e.id||e.field||"value",`/${(r=e.field)!==null&&r!==void 0?r:"value"}`,`set 'valueWorkflowType' explicitly (got '${n??""}'); one of ${Object.keys(i).join(", ")}. It cannot be inferred from the literal \u2014 "1" is both a valid Integer and a valid Picklist value.`)}function Hf(e,t,r,n=!1){let i=n?`[New Object() { Microsoft.Xrm.Sdk.Workflow.WorkflowPropertyType.${e.propertyType}, ${Wf(t)} }]`:`[New Object() { Microsoft.Xrm.Sdk.Workflow.WorkflowPropertyType.${e.propertyType}, ${Wf(t)}, ${Wf(e.attributeType)} }]`;return`<mxswa:ActivityReference AssemblyQualifiedName="${Qo("EvaluateExpression")}" DisplayName="EvaluateExpression"><mxswa:ActivityReference.Arguments><InArgument x:TypeArguments="x:String" x:Key="ExpressionOperator">CreateCrmType</InArgument><InArgument x:TypeArguments="s:Object[]" x:Key="Parameters">${i}</InArgument><InArgument x:TypeArguments="s:Type" x:Key="TargetType"><mxswa:ReferenceLiteral x:TypeArguments="s:Type" Value="${e.targetType}" /></InArgument><OutArgument x:TypeArguments="x:Object" x:Key="Result">[${r}]</OutArgument></mxswa:ActivityReference.Arguments></mxswa:ActivityReference>`}var su="[CreatedEntities("primaryEntity#Temp")]";function P8(e,t,r){let n=typeof e.value=="string"?e.value:"",i=e2({id:e.id,field:e.field,value:n,valueType:e.valueType,valueWorkflowType:e.valueWorkflowType}),a=`SetAttributeValueStep${r}`,o=`${a}_1`,s=e.displayName?`${a}: ${e.displayName}`:a;return`<Sequence DisplayName="${Et(s)}"><Sequence.Variables><Variable x:TypeArguments="x:Object" Name="${o}" /></Sequence.Variables><Assign x:TypeArguments="mxs:Entity" To="${su}" Value="[New Entity(${Et(`"${t}"`)})]" /><Assign x:TypeArguments="s:Guid" To="[CreatedEntities("primaryEntity#Temp").Id]" Value="[InputEntities("primaryEntity").Id]" />`+Hf(i,n,o)+`<mxswa:SetEntityProperty Attribute="${Et(e.field)}" Entity="${su}" EntityName="${Et(t)}" Value="[${o}]"><mxswa:SetEntityProperty.TargetType><InArgument x:TypeArguments="s:Type"><mxswa:ReferenceLiteral x:TypeArguments="s:Type" Value="${i.targetType}" /></InArgument></mxswa:SetEntityProperty.TargetType></mxswa:SetEntityProperty><mcwc:SetAttributeValue DisplayName="${a}" Entity="${su}" EntityName="${Et(t)}" /><Assign x:TypeArguments="mxs:Entity" To="[InputEntities("primaryEntity")]" Value="${su}" /></Sequence>`}function T8(e){return e.type!==void 0&&e.clauses===void 0}function O8(e,t,r){if(!e.field)throw new Vt.ValidationError("businessRule",e.id||e.type,"/field",`${e.type} requires a 'field'`);if(e.type==="SetFieldValue")return P8(e,t,r);let n=ZD[e.type];if(!n)throw new Vt.ValidationError("businessRule",e.id||e.type,"/type",`unsupported action '${e.type}'. This increment supports ${Hr.SUPPORTED_ACTION_TYPES.join(", ")}.`);let i=e.displayName?`${n.element}Step${r}: ${e.displayName}`:`${n.element}Step${r}`;return`<Sequence DisplayName="${Et(i)}"><mcwc:${n.element} ControlId="${Et(e.field)}" ControlType="standard" Entity="${YD}" EntityName="${Et(t)}" ${n.attribute}="${Et(n.value(e))}" /></Sequence>`}function x8(e,t,r,n){let i=t.map((a,o)=>{if(!T8(a))throw new Vt.ValidationError("businessRule",a.id||e,`/${e}/${o}`,"nested conditions (else-if) are not compiled by this increment. Rejecting rather than emitting XAML that silently drops the branch.");return O8(a,r,n+o)}).join("");return`<mxswa:ActivityReference x:Key="Then" AssemblyQualifiedName="${Qo("Composite")}" DisplayName="${Et(e)}"><mxswa:ActivityReference.Properties><sco:Collection x:TypeArguments="Variable" x:Key="Variables" /><sco:Collection x:TypeArguments="Activity" x:Key="Activities">${i}</sco:Collection></mxswa:ActivityReference.Properties></mxswa:ActivityReference>`}function KD(e,t,r,n,i,a){return`<mxswa:ActivityReference AssemblyQualifiedName="${Qo("ConditionBranch")}" DisplayName="${Et(e)}"><mxswa:ActivityReference.Arguments><InArgument x:TypeArguments="x:Boolean" x:Key="Condition">${t}</InArgument></mxswa:ActivityReference.Arguments><mxswa:ActivityReference.Properties>`+x8(e,r,n,i)+`<x:Null x:Key="Else" /><x:String x:Key="Description">${(0,N8.xmlText)(a)}</x:String></mxswa:ActivityReference.Properties></mxswa:ActivityReference>`}function R8(e,t){var r,n,i,a;let o=e.entityLogicalName,s=t.clauses[0],l=jf[s.operator];if(!l)throw new Vt.ValidationError("businessRule",s.id||s.field,"/clauses/operator",`unsupported operator '${s.operator}'. This increment supports ${Object.keys(jf).join(", ")}.`);let u="ConditionBranchStep2",c=!D8.has(l),d=`<mxswa:GetEntityProperty Attribute="${Et(s.field)}" Entity="${YD}" EntityName="${Et(o)}" Value="[${u}_1]"><mxswa:GetEntityProperty.TargetType><InArgument x:TypeArguments="s:Type"><mxswa:ReferenceLiteral x:TypeArguments="s:Type"><x:Null /></mxswa:ReferenceLiteral></InArgument></mxswa:GetEntityProperty.TargetType></mxswa:GetEntityProperty>`,p="",f="[New Object() { }]";if(c){let V=e2({id:s.id,field:s.field,value:s.value,valueType:s.valueType,valueWorkflowType:s.valueWorkflowType});p=Hf(V,(r=s.value)!==null&&r!==void 0?r:"",`${u}_2`),f=`[New Object() { ${u}_2 }]`}let h=`<mxswa:ActivityReference AssemblyQualifiedName="${Qo("EvaluateCondition")}" DisplayName="EvaluateCondition"><mxswa:ActivityReference.Arguments><InArgument x:TypeArguments="mxsq:ConditionOperator" x:Key="ConditionOperator">${l}</InArgument><InArgument x:TypeArguments="s:Object[]" x:Key="Parameters">${f}</InArgument><InArgument x:TypeArguments="x:Object" x:Key="Operand">[${u}_1]</InArgument><OutArgument x:TypeArguments="x:Boolean" x:Key="Result">[${u}_condition]</OutArgument></mxswa:ActivityReference.Arguments></mxswa:ActivityReference>`,b=(n=t.trueBranch)!==null&&n!==void 0?n:[],w=(i=t.falseBranch)!==null&&i!==void 0?i:[],E=w.length>0,D="ConditionBranchStep3",L=`<Variable x:TypeArguments="x:Boolean" Default="False" Name="${u}_condition" /><Variable x:TypeArguments="x:Object" Name="${u}_1" />`+(c?`<Variable x:TypeArguments="x:Object" Name="${u}_2" />`:"")+(E?`<Variable x:TypeArguments="x:Boolean" Default="False" Name="True" /><Variable x:TypeArguments="x:Object" Name="${D}_1" />`:""),R=KD(u,`[${u}_condition]`,b,o,2,(a=t.displayName)!==null&&a!==void 0?a:""),B=E?Hf({propertyType:"Boolean",attributeType:"",targetType:"x:Boolean"},"True",`${D}_1`,!0)+KD(D,"[True]",w,o,2+b.length,""):"";return`<mxswa:ActivityReference AssemblyQualifiedName="${Qo("ConditionSequence")}" DisplayName="ConditionStep1"><mxswa:ActivityReference.Arguments><InArgument x:TypeArguments="x:Boolean" x:Key="Wait">False</InArgument></mxswa:ActivityReference.Arguments><mxswa:ActivityReference.Properties><sco:Collection x:TypeArguments="Variable" x:Key="Variables">${L}</sco:Collection><sco:Collection x:TypeArguments="Activity" x:Key="Activities">${d}${p}${h}${R}${B}</sco:Collection></mxswa:ActivityReference.Properties></mxswa:ActivityReference>`}function L8(e,t){var r,n,i,a,o,s,l,u,c,d;if(!e.entityLogicalName)throw new Vt.ValidationError("businessRule",(r=e.id)!==null&&r!==void 0?r:e.name,"/entityLogicalName","a business rule needs an entityLogicalName");let p=e.rootCondition;if(p&&Array.isArray(p.clauses)&&p.clauses.length>1)throw new Vt.ValidationError("businessRule",(n=e.id)!==null&&n!==void 0?n:e.name,"/rootCondition/clauses",`this increment supports a single clause (got ${p.clauses.length}); multi-clause AND/OR is a follow-up`);if(((i=p?.clauses)===null||i===void 0?void 0:i.length)===1&&!p.clauses[0].field)throw new Vt.ValidationError("businessRule",(a=e.id)!==null&&a!==void 0?a:e.name,"/rootCondition/clauses/0/field","a clause needs a field");let f=`XrmWorkflow${String(t).replace(/-/g,"")}`,h='<InArgument x:TypeArguments="scg:IDictionary(x:String, mxs:Entity)" />',b=!!(!((o=p?.clauses)===null||o===void 0)&&o.length);if(p&&!b){let E=((l=(s=p.trueBranch)===null||s===void 0?void 0:s.length)!==null&&l!==void 0?l:0)+((c=(u=p.falseBranch)===null||u===void 0?void 0:u.length)!==null&&c!==void 0?c:0);if(E>0)throw new Vt.ValidationError("businessRule",(d=e.id)!==null&&d!==void 0?d:e.name,"/rootCondition/clauses",`the condition has ${E} branch item(s) but no clause, so there is nothing to evaluate. Emitting an empty rule would silently discard them.`)}let w=b?`<mxswa:Workflow>${R8(e,p)}</mxswa:Workflow>`:"<mxswa:Workflow />";return`<?xml version="1.0" encoding="utf-16"?><Activity x:Class="${f}" ${E8}><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:${f}.InputEntities>${h}</this:${f}.InputEntities><this:${f}.CreatedEntities>${h}</this:${f}.CreatedEntities><mva:VisualBasic.Settings>Assembly references and imported namespaces for internal implementation</mva:VisualBasic.Settings>`+w+"</Activity>"}Hr.buildBusinessRuleXaml=L8;Hr.SUPPORTED_ACTION_TYPES=[...Object.keys(ZD),"SetFieldValue"];Hr.SUPPORTED_OPERATORS=Object.keys(jf)});var o2=g(uu=>{"use strict";Object.defineProperty(uu,"__esModule",{value:!0});uu.businessRuleApi=void 0;var Cr=fn(),F8=Xt(),ct=he(),ar=Z(),k8=t2(),r2="00000000-0000-0000-0000-000000000000",ai={"Content-Type":"application/json",Accept:"application/json","OData-Version":"4.0","OData-MaxVersion":"4.0"},M8="workflowid,name,description,primaryentity,statecode,category,type",a2="category eq 2 and type eq 1";async function n2(e,t,r){var n;if(r==="Draft")return null;let i=(0,ar.normalizeGuid)(t,"workflowid"),a=r==="Active",o={statecode:a?Cr.StateCode.Activated:Cr.StateCode.Draft,statuscode:a?Cr.StatusCode.Activated:Cr.StatusCode.Draft},s=`/workflows(${i})`,l=(0,ct.ensureSuccess)(await e.patch(s,o,{headers:ai}),e.apiUrl(s));return(n=(0,ct.readEtag)(l))!==null&&n!==void 0?n:await Qf(e,i)}async function Qf(e,t){let r=`/workflows(${t})${(0,ar.odataQuery)([["$select","workflowid"]])}`,n=await e.get(r);return n.status>=200&&n.status<300?(0,ct.readEtag)(n):null}async function U8(e,t,r,n){var i,a,o,s;let l=(i=lu(t.Entity.name))!==null&&i!==void 0?i:lu(t.artifact.name),u=(a=lu(t.Entity.primaryentity))!==null&&a!==void 0?a:lu(t.artifact.entityLogicalName);if(!l||!u)return{ok:!1};let c=[a2,`name eq '${(0,ar.odataLiteral)(l)}'`,`primaryentity eq '${(0,ar.odataLiteral)(u)}'`,`createdon ge ${n}`],d=`/workflows${(0,ar.odataQuery)([["$select","workflowid,createdon"],["$filter",c.join(" and ")],["$orderby","createdon desc"],["$top","2"]])}`,p;try{p=await e.get(d)}catch{return{ok:!1}}if(p.status<200||p.status>=300)return{ok:!1};let f=(s=(o=p.body)===null||o===void 0?void 0:o.value)!==null&&s!==void 0?s:[],h=[];for(let b of f)if(!(typeof b.workflowid!="string"||b.workflowid===""))try{let w=(0,ar.normalizeGuid)(b.workflowid,"workflowid");w!==r&&h.push(w)}catch{return{ok:!1}}return{ok:!0,ids:h}}function lu(e){return typeof e=="string"&&e!==""?e:void 0}function B8(){return new Date(Date.now()-3e5).toISOString().replace(/\.\d{3}Z$/,"Z")}function $8(e){var t;let r=e?.statusCode;if(r===404)return!0;if(r!==400)return!1;let n=e?.cause;return((t=n?.error)===null||t===void 0?void 0:t.code)==="0x80040216"}function q8(e){return e?.statusCode===400}async function i2(e,t,r,n,i,a){try{return(0,ct.ensureSuccess)(await e.post(n.path,{Entity:t.Entity,WfomJson:t.WfomJson},{headers:n.headers}),e.apiUrl(n.path))}catch(o){if(!$8(o))throw o;if(a&&q8(o))try{await a()}catch{throw o}let s;try{s=(0,k8.buildBusinessRuleXaml)(t.artifact,r)}catch{throw o}return i(s)}}async function V8(e,t,r,n){let i=await U8(e,t,r,n);if(!i.ok)throw new Error("business-rule leftover probe was indeterminate");if(i.ids.length===0)return;if(i.ids.length>1)throw new Error(`business-rule leftover probe matched ${i.ids.length} rows; refusing to guess`);let a=i.ids[0];try{await e.patch(`/workflows(${a})`,{statecode:Cr.StateCode.Draft,statuscode:Cr.StatusCode.Draft},{headers:ai})}catch{}await(0,ct.deleteRecord)(e,"workflows",a)}uu.businessRuleApi={async get(e,t){let n=`/workflows(${(0,ar.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveProcessWithWfomJson`,i=(0,ct.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,ct.readEtag)(i)}},async list(e,t){let r=[a2];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,ar.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,ar.odataQuery)([["$select",M8],["$filter",r.join(" and ")]])}`;return(await(0,F8.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=String(n.Entity.workflowid),a=(0,ar.normalizeGuid)(n.Entity.workflowid,"workflowid"),o=B8(),s=await i2(e,n,i,{path:`/workflows(${r2})/Microsoft.Dynamics.CRM.CreateProcessWithWfomJson`,headers:ai},async c=>{let{"@odata.type":d,...p}=n.Entity,f="/workflows";return(0,ct.ensureSuccess)(await e.post(f,{...p,xaml:c},{headers:ai}),e.apiUrl(f))},()=>V8(e,n,a,o)),l=(0,ct.resolveCreatedId)(s,"workflowid","business rule",a),u=null;try{u=await n2(e,l,n.status)}catch(c){try{await(0,ct.deleteRecord)(e,"workflows",l)}catch{}throw c}return{id:l,etag:(r=u??(0,ct.readEtag)(s))!==null&&r!==void 0?r:await Qf(e,l)}},async update(e,t,r,n){var i;let a=r,o=(0,ar.normalizeGuid)(t,"id"),s=`/workflows(${o})`,l={...ai};n&&(l["If-Match"]=n);let{name:u,description:c,processtriggerscope:d,processtriggerformid:p}=a.Entity,f=await i2(e,a,o,{path:`/workflows(${r2})/Microsoft.Dynamics.CRM.UpdateProcessWithWfomJson`,headers:l},async b=>{(0,ct.ensureSuccess)(await e.patch(s,{statecode:Cr.StateCode.Draft,statuscode:Cr.StatusCode.Draft},{headers:l}),e.apiUrl(s));try{return(0,ct.ensureSuccess)(await e.patch(s,{name:u,description:c,xaml:b,processtriggerscope:d,processtriggerformid:p??null},{headers:ai}),e.apiUrl(s))}catch(w){if(a.status==="Active")try{await e.patch(s,{statecode:Cr.StateCode.Activated,statuscode:Cr.StatusCode.Activated},{headers:ai})}catch{}throw w}}),h=await n2(e,o,a.status);return{id:o,etag:(i=h??(0,ct.readEtag)(f))!==null&&i!==void 0?i:await Qf(e,o)}},delete(e,t){return(0,ct.deleteRecord)(e,"workflows",t)}}});var p2=g(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.BUSINESS_RULE_NULL_GUID=Dn.businessRuleRegistration=Dn.BusinessRuleAdapter=void 0;var s2=As(),Jf=fn(),l2=(RD(),lr(xD)),G8=(JD(),lr(QD)),u2=Yt(),En=wr(),z8=o2(),W8=mt(),j8="00000000-0000-0000-0000-000000000000";Dn.BUSINESS_RULE_NULL_GUID=j8;var H8=new Set(["Recommendation","LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]),Q8=["ruleId","name","description","entityLogicalName","scope","status","rootCondition"],J8=["kind","id","displayName","logic","clauses","trueBranch","falseBranch"],X8=["id","field","fieldDisplayName","operator","valueType","value","valueField","lookupValue","expression","rawExpression","valueWorkflowType"];function c2(e){var t;return(0,En.isJsonObject)(e)?{...e,label:(t=e.label)!==null&&t!==void 0?t:""}:e}function K8(e){return{...e,...e.lookupValue!==void 0?{lookupValue:c2(e.lookupValue)}:{},...Array.isArray(e.applyActions)?{applyActions:e.applyActions.map(t=>(0,En.isJsonObject)(t)&&t.lookupValue!==void 0?{...t,lookupValue:c2(t.lookupValue)}:t)}:{}}}var cu=class{toArtifact(t){let r=this.residualBag(t,Q8),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){var r;let n=t.rootCondition?this.conditionFromJson(t.rootCondition):null;return{...(r=t.bag)!==null&&r!==void 0?r:{},ruleId:t.id,name:t.name,description:t.description,entityLogicalName:t.entityLogicalName,scope:t.scope,status:t.status,rootCondition:n}}fromApiResponse(t){var r;let n=t??{},i={...(r=n.Entity)!==null&&r!==void 0?r:{},wfomJson:n.WfomJson},a=(0,l2.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,l2.serializeToWorkflowJson)(n),a=(r=n.ruleId)!==null&&r!==void 0?r:(0,s2.v4)();return{Entity:this.buildWorkflowEntity(n,a),WfomJson:i,status:t.status,artifact:t}}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:(0,G8.createEmptyCondition)()},u=this.toArtifact(l);return u.id||(u.id=(0,s2.v4)()),u}assignMissingIds(t){return(0,W8.assignMissingIds)(t)}validate(t){let r=[],n=t.rootCondition;return n==null?r:(0,En.isJsonObject)(n)?(d2(n,"/rootCondition",r),r):(r.push((0,En.issue)("/rootCondition","condition-must-be-object",`rootCondition must be a JSON object or null, got ${typeof n}`)),r)}residualBag(t,r){let n=new Set(r),i={};for(let a of Object.keys(t)){if(n.has(a))continue;let o=t[a];o!==void 0&&(i[a]=o)}return Object.keys(i).length>0?i:void 0}buildWorkflowEntity(t,r){let n=t.scope!=="Entity"&&t.scope!=="AllForms";return{"@odata.type":"#Microsoft.Dynamics.CRM.workflow",name:t.name,description:t.description,workflowid:r,ondemand:!1,subprocess:!1,triggeroncreate:!1,triggerondelete:!1,category:Jf.WorkflowCategory.BusinessRule,type:Jf.WorkflowTypeCode.Definition,mode:1,scope:Jf.WorkflowScope.Organization,primaryentity:t.entityLogicalName,iscrmuiworkflow:!0,processtriggerscope:n?1:2,...n?{processtriggerformid:t.scope}:{}}}conditionToJson(t){let r=this.residualBag(t,J8),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,X8),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){return{...t}}conditionFromJson(t){var r;return{kind:"condition",isCollapsed:!1,...(r=t.bag)!==null&&r!==void 0?r:{},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,n,i;return{...(r=t.bag)!==null&&r!==void 0?r:{},id:t.id,field:t.field,fieldDisplayName:(n=t.fieldDisplayName)!==null&&n!==void 0?n:t.field,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,label:(i=t.lookupValue.label)!==null&&i!==void 0?i:""}}:{},...t.expression!==void 0?{expression:t.expression}:{},...t.rawExpression!==void 0?{rawExpression:t.rawExpression}:{},...t.valueWorkflowType!==void 0?{valueWorkflowType:t.valueWorkflowType}:{}}}branchItemFromJson(t){return this.isConditionJson(t)?this.conditionFromJson(t):this.actionFromJson(t)}actionFromJson(t){if(!H8.has(t.type))throw new Error(`Unsupported business-rule action type: ${t.type}`);return Z8(t),{...K8(t),kind:"action",type:t.type}}isConditionJson(t){return Object.prototype.hasOwnProperty.call(t,"clauses")&&Object.prototype.hasOwnProperty.call(t,"logic")&&!Object.prototype.hasOwnProperty.call(t,"type")}};Dn.BusinessRuleAdapter=cu;function d2(e,t,r){(0,En.optionalEnum)(e,"logic",["AND","OR"],t,"condition-logic-invalid",r),(0,En.childObjects)(e,"clauses",t,"clause",r);for(let n of["trueBranch","falseBranch"])(0,En.childObjects)(e,n,t,"branchItem",r).forEach(({node:a,index:o})=>{"clauses"in a||"trueBranch"in a||"falseBranch"in a?d2(a,`${t}/${n}/${o}`,r):Y8(a,`${t}/${n}/${o}`,r)})}function Y8(e,t,r){e.type==="SetDefaultValue"&&e.valueType==="Clear"&&r.push((0,En.issue)(`${t}/valueType`,"clear-only-set-field-value","Clear is only supported for SetFieldValue actions."))}function Z8(e){if(e.type==="SetDefaultValue"&&e.valueType==="Clear")throw new Error("Clear is only supported for SetFieldValue actions.")}function eV(){return{adapter:new cu,api:z8.businessRuleApi,publish:(e,t,r)=>(0,u2.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,u2.boundEntityPublishScope)(t)}}Dn.businessRuleRegistration=eV});var S2=g(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.appRegistration=In.AppAdapter=In.HEADER_NAV_BOOLEAN_RULE=void 0;var Qr=wr(),ze=An(),Xo=la(),tV=Yt(),rV=Rs(),Xf=_s(),Kf=Cn(),nV=mt(),iV=Z(),y2=fi(),aV=le(),b2=Ts();Object.defineProperty(In,"HEADER_NAV_BOOLEAN_RULE",{enumerable:!0,get:function(){return b2.HEADER_NAV_BOOLEAN_RULE}});var fu="7.0.0.0",f2=`<SiteMap IntroducedVersion="${fu}"></SiteMap>`,oV="/_imgs/imagestrips/transparent_spacer.gif",sV="/_imgs/TableIconsFluentV9/document_one_page_sparkle.svg",lV=["Entity","Url","DefaultDashboard","Page","GenPageId"],Jo="sitemapId",m2="sitemapName",uV="sitemapNameUnique";function h2(e,t,r){if(e===void 0)return r;if(typeof e!="boolean")throw new aV.ValidationError("app",t,[w2(e)]);return e}function w2(e){return(0,Qr.issue)("/headerAndNavigationRefresh",b2.HEADER_NAV_BOOLEAN_RULE,`headerAndNavigationRefresh must be a boolean, got ${typeof e}`)}function cV(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,iV.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 mu=class{constructor(t=y2.DEFAULT_LCID){this.lcid=t}toArtifact(t){let{bag:r,modeledEls:n}=du(t,"Area");return{id:"",name:"",uniqueName:"",description:"",siteMap:{areas:n.map(i=>this.areaToJson(i)),bag:r},bag:(0,ze.emptyBag)()}}fromArtifact(t){(0,Kf.installDomShim)();let r=this.assignMissingIds(JSON.parse(JSON.stringify(t))),n=new DOMParser().parseFromString("<root/>","text/xml"),i=this.rootToRaw(r);return(0,ze.rebuildRaw)(i,(0,Xo.domEngine)(n),null)}fromApiResponse(t){var r,n,i,a,o,s,l,u,c,d;(0,Kf.installDomShim)();let p=t??{},f=(r=p.$sitemap)!==null&&r!==void 0?r:p,h=(0,Xo.parseXmlRoot)((n=f.sitemapxml)!==null&&n!==void 0?n:f2,f2),b=this.toArtifact(h);return b.id=(i=p.appmoduleid)!==null&&i!==void 0?i:"",b.name=(a=p.name)!==null&&a!==void 0?a:"",b.uniqueName=(o=p.uniquename)!==null&&o!==void 0?o:"",b.description=(s=p.description)!==null&&s!==void 0?s:"",b.bag={a:[[Jo,(u=(l=f.sitemapid)!==null&&l!==void 0?l:p._sitemapid_value)!==null&&u!==void 0?u:""],[m2,(c=f.sitemapname)!==null&&c!==void 0?c:""],[uV,(d=f.sitemapnameunique)!==null&&d!==void 0?d:""]],c:[]},b}toApiPayload(t){var r,n,i,a,o,s,l,u,c,d,p,f,h,b,w;(0,Kf.installDomShim)();let E=(0,Xo.serializeNode)(this.fromArtifact(t)),D=[],L=[];for(let B of(n=(r=t.siteMap)===null||r===void 0?void 0:r.areas)!==null&&n!==void 0?n:[])for(let V of(i=B.groups)!==null&&i!==void 0?i:[])for(let M of(a=V.subAreas)!==null&&a!==void 0?a:[])M.type==="Entity"&&M.entity?D.push(M.entity):M.type==="DashBoard"&&M.dashboardId&&L.push(M.dashboardId);let R=(o=t.bag)!==null&&o!==void 0?o:(0,ze.emptyBag)();return{sitemapId:(s=v2(R,Jo))!==null&&s!==void 0?s:"",sitemapxml:E,sitemapname:v2(R,m2)||t.name,appModuleId:t.id,appModuleName:t.name,appModuleDescription:t.description,appModuleUniqueName:t.uniqueName,...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},...t.headerAndNavigationRefresh===void 0?{}:{appSettings:{[Xf.HEADER_AND_NAVIGATION_REFRESH]:h2(t.headerAndNavigationRefresh,(l=t.id)!==null&&l!==void 0?l:"(unknown)",!0)?Xf.APP_SETTING_ON:Xf.APP_SETTING_OFF}},...typeof t.published=="boolean"?{published:t.published}:{},entities:D,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:(h=(f=t.components)===null||f===void 0?void 0:f.charts)!==null&&h!==void 0?h:[],dashboards:[...(w=(b=t.components)===null||b===void 0?void 0:b.dashboards)!==null&&w!==void 0?w:[],...L]}}}createDefault(t){var r,n,i,a,o;let s=t.siteMap&&t.siteMap.areas.length>0?t.siteMap.areas:[{id:"",title:"Area",groups:[{id:"",title:"Group",subAreas:[]}]}];return{id:(r=t.id)!==null&&r!==void 0?r:(0,nV.newId)(),name:(n=t.name)!==null&&n!==void 0?n:"New App",uniqueName:(i=t.uniqueName)!==null&&i!==void 0?i:"",description:(a=t.description)!==null&&a!==void 0?a:"",siteMap:{areas:s},...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},headerAndNavigationRefresh:h2(t.headerAndNavigationRefresh,(o=t.id)!==null&&o!==void 0?o:"(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(em):Array.isArray(r.areas)?r.areas.forEach(em):Array.isArray(r.groups)?em(r):Array.isArray(r.subAreas)?C2(r):"type"in r&&hu(r,"subarea"),t}validate(t){let r=[],n=t.published;n!==void 0&&typeof n!="boolean"&&r.push((0,Qr.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(w2(a)),i==null)return r;if(!(0,Qr.isJsonObject)(i))return r.push((0,Qr.issue)("/siteMap","sitemap-must-be-object",`siteMap must be a JSON object, got ${typeof i}`)),r;let o=(0,Qr.childObjects)(i,"areas","/siteMap","area",r),s=new Map;return o.forEach(({node:l,index:u})=>{let c=`/siteMap/areas/${u}`;(0,Qr.childObjects)(l,"groups",c,"group",r).forEach(({node:p,index:f})=>{let h=`${c}/groups/${f}`;(0,Qr.childObjects)(p,"subAreas",h,"subArea",r).forEach(({node:w,index:E})=>{let D=`${h}/subAreas/${E}`;(0,Qr.optionalEnum)(w,"type",["Entity","URL","DashBoard","CustomPage","GenPage"],D,"subarea-type-invalid",r);let L=cV(w);if(!L)return;let R=s.get(L);if(R===void 0){s.set(L,D);return}r.push((0,Qr.issue)(D,"subarea-duplicate-target",`the sitemap already navigates to this target at ${R}; a duplicate SubArea would pin it twice and a single removeElement would leave one behind`))})})}),r}applyServerIdentity(t,r){let n=r[Jo];if(!n)return;t.bag||(t.bag=(0,ze.emptyBag)());let i=t.bag.a.find(a=>a[0]===Jo);i?i[1]=n:t.bag.a.push([Jo,n])}areaToJson(t){var r;let{bag:n,modeledEls:i}=du(t,"Group"),a={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:Yf(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}=du(t,"SubArea");return{id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:Yf(t,this.lcid),subAreas:i.map(a=>this.subAreaToJson(a)),bag:n}}subAreaToJson(t){var r;let{bag:n}=du(t,null),i=dV(t),a={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",type:i,title:Yf(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!==oV&&(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,ze.emptyBag)(),l=pu(o)?[["IntroducedVersion",fu]]:[],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,ze.mergeAttrs)(o.a,l),c:(0,ze.spliceChildren)(o.c,u)}}areaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,ze.emptyBag)(),i=pu(n),a=[];t.id&&a.push(["Id",t.id]),i&&a.push(["ShowGroups","true"],["ResourceId","SitemapDesigner.NewTitle"],["DescriptionResourceId","SitemapDesigner.NewTitle"],["IntroducedVersion",fu]),t.icon!==void 0&&a.push(["Icon",t.icon]),t.vectorIcon!==void 0&&a.push(["VectorIcon",t.vectorIcon]);let o=t.groups.map(l=>this.groupToRaw(l)),s=Zf((0,ze.spliceChildren)(n.c,o),t.title,i,this.lcid);return{n:"Area",a:(0,ze.mergeAttrs)(n.a,a),c:s}}groupToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,ze.emptyBag)(),i=pu(n),a=[];t.id&&a.push(["Id",t.id]),i&&a.push(["ResourceId","SitemapDesigner.NewGroup"],["DescriptionResourceId","SitemapDesigner.NewGroup"],["ToolTipResourseId","SitemapDesigner.Unknown"],["IntroducedVersion",fu],["IsProfile","false"]);let o=t.subAreas.map(l=>this.subAreaToRaw(l)),s=Zf((0,ze.spliceChildren)(n.c,o),t.title,i,this.lcid);return{n:"Group",a:(0,ze.mergeAttrs)(n.a,a),c:s}}subAreaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,ze.emptyBag)(),i=pu(n),a=fV(n.a,t.type),o=[];t.id&&o.push(["Id",t.id]),hV(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]),t.vectorIcon!==void 0?o.push(["VectorIcon",t.vectorIcon]):t.type==="GenPage"&&!pV(a,"VectorIcon")&&o.push(["VectorIcon",sV]);let s=Zf((0,ze.spliceChildren)(n.c,[]),t.title,i,this.lcid);return{n:"SubArea",a:(0,ze.mergeAttrs)(a,o),c:s}}};In.AppAdapter=mu;function du(e,t){let r=(0,Xo.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,ze.rawFromNode)((0,Xo.nodeLikeFromDom)(l))}),o+=1)}return{bag:{a:r,c:n},modeledEls:i}}function g2(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 Yf(e,t){var r;let n=g2(e,"Titles")[0];if(!n)return"";let a=g2(n,"Title").find(o=>o.getAttribute("LCID")===String(t));return a&&(r=a.getAttribute("Title"))!==null&&r!==void 0?r:""}function dV(e){return e.getAttribute("GenPageId")?"GenPage":e.getAttribute("Entity")?"Entity":e.getAttribute("Page")?"CustomPage":e.getAttribute("DefaultDashboard")?"DashBoard":"URL"}function pu(e){return e.a.length===0&&e.c.length===0}function pV(e,t){return e.some(([r])=>r===t)}function v2(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function fV(e,t){let r=mV(t);return e.filter(([n])=>!lV.includes(n)||r.has(n)).map(n=>[n[0],n[1]])}function mV(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 hV(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 Zf(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]=gV(e[i],t,n),a}return r?[vV(t,n),...e]:e}function gV(e,t,r){let n=!1,i=e.c.map(a=>!n&&a.n==="Title"&&yV(a,"LCID")===String(r)?(n=!0,{n:a.n,a:(0,ze.mergeAttrs)(a.a,[["Title",t]]),c:a.c}):a);return n||i.unshift(A2(t,r)),{n:e.n,a:e.a.map(a=>[a[0],a[1]]),c:i}}function vV(e,t){return{n:"Titles",a:[],c:[A2(e,t)]}}function A2(e,t){return{n:"Title",a:[["LCID",String(t)],["Title",e]],c:[]}}function yV(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function bV(e){let t="0123456789abcdef",r="";for(let n=0;n<e;n+=1)r+=t[Math.floor(Math.random()*t.length)];return r}function hu(e,t){e&&(typeof e.id!="string"||e.id.length===0)&&(e.id=`${t}_${bV(8)}`)}function em(e){var t;hu(e,"area");for(let r of(t=e.groups)!==null&&t!==void 0?t:[])C2(r)}function C2(e){var t;hu(e,"group");for(let r of(t=e.subAreas)!==null&&t!==void 0?t:[])hu(r,"subarea")}function wV(e=y2.DEFAULT_LCID){return{adapter:new mu(e),api:rV.appApi,languageSensitive:!0,publish:(t,r)=>(0,tV.publishAppModule)(t,r),publishScope:t=>({envelope:"appmodule",targetIds:[t]})}}In.appRegistration=wV});var N2={};sr(N2,{ActionType:()=>rm,AppActionOrigin:()=>cm,AppActionVisibilityType:()=>um,ButtonType:()=>im,CannotUpdateAppActionColumns:()=>AV,Context:()=>om,IconType:()=>nm,Location:()=>am,OnClickEventType:()=>lm,Scope:()=>sm,VisibilityType:()=>tm});var tm,rm,nm,im,am,om,sm,lm,um,cm,AV,E2=I(()=>{"use strict";(function(e){e[e.NotSupported=0]="NotSupported",e[e.Show=1]="Show",e[e.ClassicRules=2]="ClassicRules",e[e.Expression=3]="Expression"})(tm||(tm={}));(function(e){e[e.NotSupported=0]="NotSupported",e[e.None=1]="None",e[e.JavaScript=2]="JavaScript",e[e.Expression=3]="Expression"})(rm||(rm={}));(function(e){e[e.NoIcon=0]="NoIcon",e[e.UseIcon=1]="UseIcon",e[e.UseWebResource=2]="UseWebResource"})(nm||(nm={}));(function(e){e[e.Standard=0]="Standard",e[e.Dropdown=1]="Dropdown",e[e.Split=2]="Split",e[e.Group=3]="Group"})(im||(im={}));(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"})(am||(am={}));(function(e){e[e.All=0]="All",e[e.Entity=1]="Entity"})(om||(om={}));(function(e){e[e.App=0]="App",e[e.Entity=1]="Entity",e[e.Global=2]="Global"})(sm||(sm={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.JavaScript=2]="JavaScript"})(lm||(lm={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.ClassicRules=2]="ClassicRules"})(um||(um={}));(function(e){e[e.Default=0]="Default",e[e.Migrated=1]="Migrated",e[e.MigratedClone=2]="MigratedClone"})(cm||(cm={}));AV=["appactionid","appmoduleid","context","contextvalue","location","name","type","uniquename","isdisabled","origin"]});var I2=g(gu=>{"use strict";Object.defineProperty(gu,"__esModule",{value:!0});gu.commandApi=void 0;var Tt=he(),CV=le(),Gt=Z(),SV="OnClickEventJavaScriptWebResourceId($select=name,webresourceid),IconWebResourceId($select=name,webresourceid)";async function dm(e,t){let r=`/EntityDefinitions(LogicalName='${(0,Gt.odataLiteral)(t)}')${(0,Gt.odataQuery)([["$select","MetadataId"]])}`,i=(0,Tt.ensureSuccess)(await e.get(r),e.apiUrl(r)).body,a=i?.MetadataId;return a?(0,Gt.normalizeGuid)(a,"entityMetadataId"):""}gu.commandApi={async get(e,t){var r;let n=t,i=await dm(e,n),a=i?`_contextentity_value eq ${i}`:`contextvalue eq '${(0,Gt.odataLiteral)(n)}'`,o=`/appactions${(0,Gt.odataQuery)([["$expand",SV],["$filter",a]])}`,s=(0,Tt.ensureSuccess)(await e.get(o),e.apiUrl(o)),l=s.body,u=(r=l?.value)!==null&&r!==void 0?r:[],c={entityLogicalName:n,entityMetadataId:i,appActions:u},d={};for(let p of u){let f=typeof p.appactionid=="string"?p.appactionid:void 0;if(f){let h=p["@odata.etag"];d[(0,Gt.normalizeGuid)(f,"appactionid")]=typeof h=="string"?h:null}}return{raw:c,etag:(0,Tt.readEtag)(s),memberEtags:d}},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 dm(e,r.entityLogicalName);return D2(e,{...r,entityMetadataId:n},!1)},async update(e,t,r,n,i){return D2(e,r,!0,i)},async delete(e,t){var r,n;let i=await dm(e,t),a=i?`_contextentity_value eq ${i}`:`contextvalue eq '${(0,Gt.odataLiteral)(t)}'`,o=`/appactions${(0,Gt.odataQuery)([["$select","appactionid"],["$filter",a]])}`,l=(n=(r=(0,Tt.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[];for(let u of l)u.appactionid&&await(0,Tt.deleteRecord)(e,"appactions",u.appactionid)}};async function D2(e,t,r,n){let i=t.entityMetadataId?(0,Gt.normalizeGuid)(t.entityMetadataId,"entityMetadataId"):"",a=EV(t.rows),o={};try{await NV(e,t,a,i,r,n,o)}catch(s){throw(0,CV.withPartialTokens)(s,{memberEtags:o})}return{id:t.entityLogicalName,etag:null,memberEtags:o}}async function NV(e,t,r,n,i,a,o){var s,l,u;for(let c of r)if(i&&c.exists){let d=(0,Gt.normalizeGuid)(c.appactionid,"id"),p=(s=a?.[d])!==null&&s!==void 0?s:c.etag,f=(0,Tt.echoWrite)("appactionid",p?{"If-Match":p}:void 0),h=`/appactions(${d})${f.query}`,b=(0,Tt.ensureSuccess)(await e.patch(h,c.body,f.options),e.apiUrl(h));o[d]=(0,Tt.readEtag)(b)}else{let d=(0,Tt.echoWrite)("appactionid"),p=`/appactions${d.query}`,f={...c.body};n&&f["[email protected]"]===void 0&&(f["[email protected]"]=`/entities(${n})`);let h=(0,Tt.ensureSuccess)(await e.post(p,f,d.options),e.apiUrl(p)),b=(0,Tt.readCreatedId)(h,"appactionid");b&&(o[(0,Gt.normalizeGuid)(b,"appactionid")]=(0,Tt.readEtag)(h))}for(let c of[...(l=t.deletedRowIds)!==null&&l!==void 0?l:[]].reverse()){let d=(0,Gt.normalizeGuid)(c,"id");await(0,Tt.deleteRecord)(e,"appactions",d,(u=a?.[d])!==null&&u!==void 0?u:void 0),delete o[d]}}function EV(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 V2=g(ha=>{"use strict";Object.defineProperty(ha,"__esModule",{value:!0});ha.commandRegistration=ha.CommandAdapter=void 0;var Me=(E2(),lr(N2)),_2=Yt(),zt=wr(),DV=I2(),T2=mt(),ga=Z(),fm="$ClientSvg:",mm=".svg",IV=2,_V=1,PV=1,O2="entityMetadataId",TV=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"]),vu=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 h=typeof f._parentappactionid_value=="string"&&f._parentappactionid_value?f._parentappactionid_value:"",b=(i=c.get(h))!==null&&i!==void 0?i:[];b.push(f),c.set(h,b)}let d=new Map;for(let f of(a=c.get(""))!==null&&a!==void 0?a:[]){let h=FV(f.location),b=(o=d.get(h))!==null&&o!==void 0?o:[];b.push(f),d.set(h,b)}let p=[];for(let[f,h]of d)p.push({location:f,groups:xV(h,c,k2(f),u)});return{id:u,entityLogicalName:u,commandBars:LV(p),bag:{a:[[O2,(s=t.entityMetadataId)!==null&&s!==void 0?s:""]]}}}fromArtifact(t){return{entityLogicalName:t.entityLogicalName,entityMetadataId:gm(t),appActions:pm(t).map(r=>r.row)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t,r){let n=new Set(r?pm(r).map(l=>l.appactionid):[]),i=pm(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?HV(l.row):q2(l.row)}}),s=[...n].filter(l=>!a.has(l));return{entityLogicalName:t.entityLogicalName,entityMetadataId:gm(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,T2.assignMissingIds)(t)}validate(t){let r=[];return(0,zt.childObjects)(t,"commandBars","","commandBar",r).forEach(({node:i,index:a})=>{let o=`/commandBars/${a}`;(0,zt.optionalEnum)(i,"location",["MainTab","ContextualTab","HomeTab"],o,"bar-location-invalid",r),(0,zt.childObjects)(i,"groups",o,"group",r).forEach(({node:l,index:u})=>{let c=`${o}/groups/${u}`;(0,zt.optionalGuidId)(l,"id",c,"group-id-invalid",r),x2((0,zt.childObjects)(l,"controls",c,"control",r),`${c}/controls`,r)})}),r}};ha.CommandAdapter=vu;function x2(e,t,r){e.forEach(({node:n,index:i})=>{let a=`${t}/${i}`;(0,zt.optionalGuidId)(n,"id",a,"control-id-invalid",r),(0,zt.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,zt.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,zt.isJsonObject)(n.action)?(0,zt.optionalEnum)(n.action,"type",["javascript"],`${a}/action`,"action-type-invalid",r):r.push((0,zt.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,zt.childObjects)(n,"children",a,"control",r);s.length>0&&x2(s,`${a}/children`,r)})}function R2(e){return{a:Object.entries(e)}}function OV(e){return Object.fromEntries(e.a)}function hm(e,t){if(e){for(let[r,n]of e.a)if(r===t)return n}}function gm(e){let t=hm(e.bag,O2);return typeof t=="string"?t:""}function xV(e,t,r,n){var i,a;let o=[],s=[];for(let l of bu(e))l.type===Me.ButtonType.Group?o.push({id:F2(l.name,n),title:typeof l.grouptitle=="string"?l.grouptitle:"",controls:bu((a=t.get((i=l.appactionid)!==null&&i!==void 0?i:""))!==null&&a!==void 0?a:[]).map(u=>yu(u,t,r,n)),bag:R2(l)}):s.push(yu(l,t,r,n));return s.length>0&&o.unshift({id:(0,T2.newId)(),title:"",controls:s}),o}function yu(e,t,r,n){var i,a,o,s;let l=F2(e.name,n),u={id:l,type:kV(e.type),label:typeof e.buttonlabeltext=="string"?e.buttonlabeltext:"",command:typeof e.appactionid=="string"?e.appactionid:l,bag:R2(e)},c=L2(e);c&&(u.icon=c);let d=RV(e);d&&(u.action=d),typeof e.hidden=="boolean"&&(u.hidden=e.hidden),typeof e.isdisabled=="boolean"&&(u.disabled=e.isdisabled),typeof e.location=="number"&&e.location!==r&&(u.location=e.location);let p=t.get((i=e.appactionid)!==null&&i!==void 0?i:"");if(p&&p.length>0){let f=[];for(let h of bu(p))if(h.type===Me.ButtonType.Group){u.flyoutGroupId=(a=h.appactionid)!==null&&a!==void 0?a:void 0;for(let b of bu((s=t.get((o=h.appactionid)!==null&&o!==void 0?o:""))!==null&&s!==void 0?s:[]))f.push(yu(b,t,r,n))}else f.push(yu(h,t,r,n));u.children=f}return u}function L2(e){var t;if(!((t=e.IconWebResourceId)===null||t===void 0)&&t.name)return e.IconWebResourceId.name;if(e.fonticon)return e.fonticon.startsWith(fm)?e.fonticon.slice(fm.length)+mm:e.fonticon}function RV(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 P2(e){return typeof e.sequence=="number"?e.sequence:typeof e.buttonsequencepriority=="number"?e.buttonsequencepriority:0}function bu(e){return[...e].sort((t,r)=>P2(t)-P2(r))}function LV(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 F2(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 FV(e){switch(e){case Me.Location.Form:case Me.Location.QuickForm:return"MainTab";case Me.Location.HomePageGrid:case Me.Location.Dashboard:return"HomeTab";default:return"ContextualTab"}}function k2(e){switch(e){case"MainTab":return Me.Location.Form;case"HomeTab":return Me.Location.HomePageGrid;default:return Me.Location.SubGridStandard}}function kV(e){switch(e){case Me.ButtonType.Dropdown:return"FlyoutAnchor";case Me.ButtonType.Split:return"SplitButton";default:return"Button"}}function MV(e){switch(e){case"FlyoutAnchor":return Me.ButtonType.Dropdown;case"SplitButton":return Me.ButtonType.Split;default:return Me.ButtonType.Standard}}function UV(e){var t;return e.bag&&e.bag.a.length>0?!0:((t=e.title)!==null&&t!==void 0?t:"").length>0}function M2(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 pm(e,t=new Set){var r,n,i,a;let o=[],s=gm(e);for(let l of(r=e.commandBars)!==null&&r!==void 0?r:[]){let u=k2(l.location),c=((n=l.groups)!==null&&n!==void 0?n:[]).flatMap(f=>{var h;return(h=f.controls)!==null&&h!==void 0?h:[]}),d=c.length>0&&c.every(f=>!M2(f,t)),p=0;for(let f of(i=l.groups)!==null&&i!==void 0?i:[]){let h;if(UV(f)){let b=$V(f,u,void 0,e,s);o.push(b),h=b.appactionid}for(let b of(a=f.controls)!==null&&a!==void 0?a:[])U2(b,u,h,e,s,o,d?p:void 0,t),p+=1}}return o}function U2(e,t,r,n,i,a,o,s=new Set){var l;let u=BV(e,t,r,n,i,o);a.push(u);let c=(l=e.children)!==null&&l!==void 0?l:[];if(c.length===0)return;let d=e.flyoutGroupId||jV(u.appactionid);a.push(qV(d,t,u.appactionid,n,i));let p=c.every(f=>!M2(f,s));for(let[f,h]of c.entries())U2(h,t,d,n,i,a,p?f:void 0,s)}function BV(e,t,r,n,i,a){let o=B2(e,t,r,n,i),s=o.row;a!==void 0&&typeof s.sequence!="number"&&(s.sequence=a);let l=L2(s);return e.location!==void 0&&(s.location=e.location),s.type=MV(e.type),s.buttonlabeltext=e.label,VV(s,e.icon,l),zV(s,e.action),GV(s),e.hidden!==void 0&&(s.hidden=e.hidden),e.disabled!==void 0&&(s.isdisabled=e.disabled),{...o,row:s}}function $V(e,t,r,n,i){let a=B2(e,t,r,n,i);return a.row.type=Me.ButtonType.Group,a.row.grouptitle=e.title,a}function qV(e,t,r,n,i){let a=$2(e,t,n,i);return a["[email protected]"]=`/appactions(${(0,ga.normalizeGuid)(r,"Command flyout group id")})`,a.type=Me.ButtonType.Group,a.grouptitle===void 0&&(a.grouptitle=""),a.isgrouptitlehidden=!0,{appactionid:e,exists:!1,etag:null,row:a}}function B2(e,t,r,n,i){let a,o,s,l;if(e.bag&&e.bag.a.length>0){a=OV(e.bag),o=!0;let u=hm(e.bag,"@odata.etag");s=typeof u=="string"?u:null;let c=hm(e.bag,"appactionid");l=typeof c=="string"&&c?c:e.id}else l=e.id,a=$2(l,t,n,i),o=!1,s=null;return r&&(a["[email protected]"]=`/appactions(${(0,ga.normalizeGuid)(r,"Command parent appaction id")})`),{appactionid:l,exists:o,etag:s,row:a}}function $2(e,t,r,n){let i={appactionid:e,name:`${e}!${e.replace(/-/g,"").slice(0,32)}`,uniquename:"",location:t,context:Me.Context.Entity,contextvalue:r.entityLogicalName,scope:Me.Scope.Entity};return n&&(i["[email protected]"]=`/entities(${(0,ga.normalizeGuid)(n,"Command context entity metadata id")})`),i}function VV(e,t,r){if(t===r){let n=e._iconwebresourceid_value;typeof n=="string"&&n&&!e.fonticon&&(e["[email protected]"]=`/webresourceset(${(0,ga.normalizeGuid)(n,"Command icon web resource id")})`);return}if(t===void 0){e.fonticon="",e.IconWebResourceId=null;return}e.fonticon=t.toLowerCase().endsWith(mm)?fm+t.slice(0,t.length-mm.length):t,e.IconWebResourceId=null}function GV(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,ga.normalizeGuid)(a,`Command ${i}`);e[`${i}@odata.bind`]=`/canvasapps(${o})`};e.onclickeventtype===_V&&t("_onclickeventformulacomponentlibraryid_value","OnClickEventFormulaComponentLibraryId");let r=e.visibilitytype;(!r||r===PV)&&t("_visibilityformulacomponentlibraryid_value","VisibilityFormulaComponentLibraryId")}function zV(e,t){if(!(!t||t.type!=="javascript")){if(e.onclickeventtype=IV,t.webResourceId){let r=(0,ga.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 WV(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 jV(e){let t="";for(let r=0;r<4;r+=1)t+=WV(`${r}:flyout-group:${e}`).toString(16).padStart(8,"0");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20,32)}`}function q2(e){let t={...e};for(let r of TV)delete t[r];return t}function HV(e){let t=q2(e);for(let r of Me.CannotUpdateAppActionColumns)delete t[r];return t}function QV(){return{adapter:new vu,api:DV.commandApi,publish:(e,t,r)=>(0,_2.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,_2.boundEntityPublishScope)(t)}}ha.commandRegistration=QV});var G2=g(wu=>{"use strict";Object.defineProperty(wu,"__esModule",{value:!0});wu.chartApi=void 0;var JV=Xt(),Wt=he(),Ko=Z(),XV="savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault",KV="savedqueryvisualizationid,name,primaryentitytypecode,charttype,isdefault";wu.chartApi={async get(e,t){let n=`/savedqueryvisualizations(${(0,Ko.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Ko.odataQuery)([["$select",XV]]),i=(0,Wt.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,Wt.readEtag)(i)}},async list(e,t){let r=`/savedqueryvisualizations${(0,Ko.odataQuery)([["$select",KV],["$filter",t?.entityLogicalName?`primaryentitytypecode eq '${(0,Ko.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,JV.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,Wt.echoWrite)("savedqueryvisualizationid"),a=`/savedqueryvisualizations${i.query}`,o=(0,Wt.ensureSuccess)(await e.post(a,(0,Wt.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,Wt.resolveCreatedId)(o,"savedqueryvisualizationid","chart",r),etag:(0,Wt.readEtag)(o)}},async update(e,t,r,n){let i=r,a=(0,Ko.normalizeGuid)(t,"id"),o=(0,Wt.echoWrite)("savedqueryvisualizationid",{"If-Match":(0,Wt.requireEtag)(n,"chart",a)}),s=`/savedqueryvisualizations(${a})${o.query}`,l=(0,Wt.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,Wt.readEtag)(l)}},delete(e,t){return(0,Wt.deleteRecord)(e,"savedqueryvisualizations",t)}}});var aI=g(va=>{"use strict";Object.defineProperty(va,"__esModule",{value:!0});va.chartRegistration=va.ChartAdapter=void 0;var vm=An(),z2=wr(),Jr=la(),W2=Yt(),YV=G2(),ym=Cn(),ZV=mt(),e6=["Column","StackedColumn","StackedColumn100","Bar","StackedBar","StackedBar100","Area","StackedArea","StackedArea100","Line","Pie","Doughnut","Funnel","Tag"],t6=new Map(e6.map(e=>[e.toLowerCase(),e]));function J2(e){var t;return e&&(t=t6.get(e.toLowerCase()))!==null&&t!==void 0?t:"Column"}function r6(){return'<Chart Palette="BrightPastel"><Series><Series ChartType="Column" ChartArea="Default" /></Series><ChartAreas><ChartArea Name="Default" /></ChartAreas><Legends><Legend Name="Default" /></Legends></Chart>'}function n6(e){var t,r;let n=e.entityLogicalName,i=e.series.map((u,c)=>({alias:`agg_${c}`,series:u})),a=e.categories.map((u,c)=>({alias:`grp_${c}`,category:u})),o=i.map(u=>`<attribute alias="${u.alias}" name="${Yo(u.series.attribute)}" aggregate="${Yo(u.series.aggregate)}" />`).join("")+a.map(u=>`<attribute alias="${u.alias}" name="${Yo(u.category.attribute)}" groupby="true"${u.category.dateGrouping?` dategrouping="${Yo(u.category.dateGrouping)}"`:""} />`).join(""),s=i.map(u=>`<measure alias="${u.alias}" />`).join(""),l=(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="${Yo(n)}">${o}</entity></fetch></fetchcollection><categorycollection><category alias="${l}"><measurecollection>${s}</measurecollection></category></categorycollection></datadefinition>`}var Au=class{toArtifact(t){var r,n,i,a,o,s,l;(0,ym.installDomShim)();let u=(r=t.datadescription)!==null&&r!==void 0?r:"",c=(n=t.presentationdescription)!==null&&n!==void 0?n:"",d=(0,Jr.parseXmlRoot)(u,"<datadefinition/>"),p=(0,Jr.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:X2(p),isDefault:(l=t.isdefault)!==null&&l!==void 0?l:!1,series:Z2(d),categories:eI(d),presentation:K2(p),dataBag:u?(0,Jr.projectElementBag)(d):void 0,presentationBag:c?(0,Jr.projectElementBag)(p):void 0,rowBag:i6(t.charttype,t.type)}}fromArtifact(t){(0,ym.installDomShim)();let{datadescription:r,presentationdescription:n}=a6(t);return{savedqueryvisualizationid:t.id,name:t.name,description:t.description,primaryentitytypecode:t.entityLogicalName,datadescription:r,presentationdescription:n,charttype:j2(t.rowBag,"charttype"),type:j2(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,ym.installDomShim)();let u=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,ZV.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,z2.childObjects)(n,"series","","series",r),(0,z2.childObjects)(n,"categories","","category",r),r}};va.ChartAdapter=Au;function i6(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 j2(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 X2(e){let t=e.getElementsByTagName("Series");for(let r=0;r<t.length;r+=1)if(t[r].getAttribute("ChartType"))return J2(t[r].getAttribute("ChartType"));return"Column"}function K2(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 Cu(e){return e.getElementsByTagName("fetch")[0]}function Y2(e){var t;let r=new Map;if(!e)return r;let n=e.getElementsByTagName("link-entity");for(let i=0;i<n.length;i+=1){let a=n[i],o=a.getAttribute("name");if(!o)continue;let s=a.getElementsByTagName("attribute");for(let l=0;l<s.length;l+=1){let u=s[l],c=(t=u.getAttribute("alias"))!==null&&t!==void 0?t:u.getAttribute("name");c&&r.set(c,o)}}return r}function Z2(e){let t=Cu(e);if(!t)return[];let r=Y2(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=J2(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 eI(e){var t;let r=Cu(e);if(!r)return[];let n=Y2(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 a6(e){if(!H2(e.dataBag)||!H2(e.presentationBag))return{datadescription:n6(e),presentationdescription:E6(e)};let t=new DOMParser().parseFromString("<root/>","text/xml"),r=Q2(e.dataBag,"datadefinition",t),n=Q2(e.presentationBag,"Chart",t);return bm(e.series,Z2(r))||(s6(t,r,e.series),o6(t,n,e.series.length,e.chartType)),bm(e.categories,eI(r))||l6(t,r,e.categories),e.chartType!==X2(n)&&nI(n,e.chartType),bm(e.presentation,K2(n))||iI(n,e.presentation),{datadescription:(0,Jr.serializeNode)(r),presentationdescription:(0,Jr.serializeNode)(n)}}function H2(e){return!!e&&(e.c.length>0||e.a.length>0)}function o6(e,t,r,n){let i,a=t.childNodes;for(let l=0;l<a.length;l+=1)if(a[l].nodeType===1&&a[l].tagName==="Series"){i=a[l];break}i||(i=e.createElement("Series"),t.insertBefore(i,t.firstChild));let o=[],s=i.childNodes;for(let l=0;l<s.length;l+=1)s[l].nodeType===1&&s[l].tagName==="Series"&&o.push(s[l]);for(let l=o.length;l<r;l+=1){let u=e.createElement("Series");u.setAttribute("ChartType",n),i.appendChild(u)}for(let l=r;l<o.length;l+=1)i.removeChild(o[l])}function Q2(e,t,r){let n={n:t,a:(0,vm.mergeAttrs)(e.a,[]),c:(0,vm.spliceChildren)(e.c,[])};return(0,vm.rebuildRaw)(n,(0,Jr.domEngine)(r),null)}function s6(e,t,r){let n=Cu(t),i=n?.getElementsByTagName("entity")[0];!n||!i||tI(e,t,i,h6(n),r,v6,{aliasPrefix:"aggregate_column",addRef:d6,removeRef:m6})}function l6(e,t,r){let n=Cu(t),i=n?.getElementsByTagName("entity")[0];!n||!i||tI(e,t,i,g6(n),r,y6,{aliasPrefix:"groupby_column",addRef:p6,removeRef:f6})}function tI(e,t,r,n,i,a,o){let s=new Map;for(let p of n){let f=p.getAttribute("alias");f&&s.set(f,p)}let l=new Set,u=[];for(let p of i){let f=p.alias?s.get(p.alias):void 0;f&&!l.has(f)?(a(f,p),l.add(f)):u.push(p)}let c=n.filter(p=>!l.has(p)),d=0;for(let p of u)if(d<c.length){let f=c[d];a(f,p),l.add(f),d+=1}else{let f=e.createElement("attribute"),h=p.alias||c6(t,o.aliasPrefix);f.setAttribute("alias",h),a(f,p),b6(e,r,f,p.relatedEntity),o.addRef(e,t,h)}for(let p of n)if(!l.has(p)){let f=p.getAttribute("alias");f&&o.removeRef(t,f),A6(p)}}function u6(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 c6(e,t){let r=u6(e);if(!r.has(t))return t;for(let n=2;;n+=1){let i=`${t}_${n}`;if(!r.has(i))return i}}function rI(e,t){let r=t.getElementsByTagName("categorycollection")[0];if(r)return r;let n=e.createElement("categorycollection");return t.appendChild(n),n}function d6(e,t,r){let n=rI(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 p6(e,t,r){let n=rI(e,t),i=e.createElement("category");i.setAttribute("alias",r),n.appendChild(i)}function f6(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 m6(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"&&!S6(o)&&((r=o.parentNode)===null||r===void 0||r.removeChild(o))}}function h6(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 g6(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 v6(e,t){e.setAttribute("name",t.attribute),e.setAttribute("aggregate",t.aggregate),t.seriesType&&e.setAttribute("charttype",t.seriesType)}function y6(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 b6(e,t,r,n){n?w6(e,t,n).appendChild(r):t.appendChild(r)}function w6(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 A6(e){let t=e.parentNode;if(t&&(t.removeChild(e),t.tagName==="link-entity"&&!C6(t))){let r=t.parentNode;r&&r.removeChild(t)}}function C6(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 S6(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1)if(t[r].nodeType===1)return!0;return!1}function nI(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(!N6(r[i])){r[i].setAttribute("ChartType",t);return}}}function N6(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 iI(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 E6(e){let t=(0,Jr.parseXmlRoot)(r6(),"<Chart/>");return nI(t,e.chartType),iI(t,e.presentation),(0,Jr.serializeNode)(t)}function bm(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Yo(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function D6(){return{adapter:new Au,api:YV.chartApi,publish:(e,t,r)=>(0,W2.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,W2.boundEntityPublishScope)(t)}}va.chartRegistration=D6});var oI=g(Su=>{"use strict";Object.defineProperty(Su,"__esModule",{value:!0});Su.dashboardApi=void 0;var I6=Xt(),jt=he(),Zo=Z(),_6="formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber",P6="formid,name,type,objecttypecode",T6=0,O6=10;Su.dashboardApi={async get(e,t){let n=`/systemforms(${(0,Zo.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Zo.odataQuery)([["$select",_6]]),i=(0,jt.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,jt.readEtag)(i)}},async list(e,t){let r=[`(type eq ${T6} or type eq ${O6})`];t?.entityLogicalName&&r.push(`objecttypecode eq '${(0,Zo.odataLiteral)(t.entityLogicalName)}'`);let n=`/systemforms${(0,Zo.odataQuery)([["$select",P6],["$filter",r.join(" and ")]])}`;return(await(0,I6.collectPages)(e,n,"listArtifacts('dashboard')")).map(a=>{var o,s;return{type:"dashboard",id:(o=a.formid)!==null&&o!==void 0?o:"",name:(s=a.name)!==null&&s!==void 0?s:"",entityLogicalName:a.objecttypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,jt.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,jt.ensureSuccess)(await e.post(a,(0,jt.withClientMintedId)(o,"formid",r),i.options),e.apiUrl(a));return{id:(0,jt.resolveCreatedId)(s,"formid","dashboard",r),etag:(0,jt.readEtag)(s)}},async update(e,t,r,n){let i=r,a=(0,Zo.normalizeGuid)(t,"id"),o=(0,jt.echoWrite)("formid",{"If-Match":(0,jt.requireEtag)(n,"dashboard",a)}),s=`/systemforms(${a})${o.query}`,l=(0,jt.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,formxml:i.formxml,istabletenabled:i.istabletenabled},o.options),e.apiUrl(s));return{id:a,etag:(0,jt.readEtag)(l)}},delete(e,t){return(0,jt.deleteRecord)(e,"systemforms",t)}}});var yI=g(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.dashboardRegistration=Sr.TILE_CLASS_ID=Sr.DashboardAdapter=void 0;var ts=An(),Ht=la(),wm=Yt(),es=wr(),x6=oI(),Am=Cn(),oi=mt(),pI=Z(),fI=fi(),sI="0",Cm="10",R6=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"]]),L6="{3FF9A528-DD50-4ACA-8F10-2E5ED73513AD}",Eu=class{constructor(t=fI.DEFAULT_LCID){this.lcid=t}toArtifact(t){var r,n,i,a;(0,Am.installDomShim)();let o=(r=t.formxml)!==null&&r!==void 0?r:"",s=(0,Ht.parseXmlRoot)(o,"<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:F6(t.type),entityLogicalName:t.objecttypecode?t.objecttypecode:null,enabledForMobile:!!t.istabletenabled,layoutType:k6(s),components:lI(s,this.lcid),bag:(0,Ht.projectElementBag)(s)}}fromArtifact(t){var r;return(0,Am.installDomShim)(),{formid:t.id,name:t.name,description:t.description,type:t.dashboardType==="Interactive"?Cm:sI,objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",istabletenabled:t.enabledForMobile,formxml:uI(t,this.lcid)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){return{name:t.name,description:t.description,formxml:uI(t,this.lcid),istabletenabled:t.enabledForMobile,type:t.dashboardType==="Interactive"?Cm:sI,objecttypecode:t.entityLogicalName}}createDefault(t){var r,n,i,a,o,s,l,u;(0,Am.installDomShim)();let c=(0,Ht.parseXmlRoot)(J6(),"<form/>");return{id:(r=t.id)!==null&&r!==void 0?r:(0,oi.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:lI(c,this.lcid),bag:(0,Ht.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,oi.newId)())}return t}validate(t){let r=[],n=(0,es.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,es.isJsonObject)(u)&&r.push((0,es.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,es.isJsonObject)(a.position)){let l=rs(a.position);i.has(l)?r.push((0,es.issue)(`${s}/position`,"component-position-collision",`two components occupy the same dashboard position (${l}); move one to a free cell`)):i.add(l)}}),r}};Sr.DashboardAdapter=Eu;function F6(e){return String(e??"")===Cm?"Interactive":"Standard"}function k6(e){var t;let r=(t=e?.getAttribute("formLayout"))!==null&&t!==void 0?t:e?.getAttribute("layoutType"),n=parseInt(r??"",10);return Number.isNaN(n)?0:n}function H(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 lI(e,t){let r=[];return H(e,"tabs").flatMap(i=>H(i,"tab")).forEach((i,a)=>{H(i,"columns").flatMap(s=>H(s,"column")).forEach((s,l)=>{H(s,"sections").flatMap(c=>H(c,"section")).forEach((c,d)=>{M6(c,{tabIndex:a,columnIndex:l,sectionIndex:d},r,t)})})}),r}function M6(e,t,r,n){H(e,"rows").flatMap(a=>H(a,"row")).forEach((a,o)=>{H(a,"cell").forEach((s,l)=>{let u=U6(s,{...t,rowIndex:o,cellIndex:l},n);u&&r.push(u)})})}function U6(e,t,r){var n,i,a;let o=gI((n=e.getAttribute("id"))!==null&&n!==void 0?n:"");if(o.toLowerCase().startsWith("spacer"))return null;let s=H(e,"control")[0];if(!s)return null;let l=(i=s.getAttribute("classid"))!==null&&i!==void 0?i:"",u=q6(s),c=V6(l,u,s),d=B6(s);return{id:(a=s.getAttribute("id"))!==null&&a!==void 0?a:o,type:c,name:hI(e,r),classId:l,position:t,colspan:Sm(e,"colspan",1),rowspan:Sm(e,"rowspan",1),parameters:u,bag:(0,Ht.projectElementBag)(e),...d?{icProperties:d}:{}}}function mI(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 B6(e){let t=mI(e);return t?(0,Ht.serializeNode)(t):void 0}function $6(e,t,r){let n=mI(t);if(!r){n&&t.removeChild(n);return}let i=new DOMParser().parseFromString(r,"text/xml").documentElement,a=(0,ts.rebuildRaw)((0,ts.rawFromNode)((0,Ht.nodeLikeFromDom)(i)),(0,Ht.domEngine)(e),null);n&&(0,Ht.serializeNode)(n)===(0,Ht.serializeNode)(a)||(n?t.replaceChild(a,n):t.appendChild(a))}function hI(e,t){var r,n;let i=H(e,"labels")[0];if(!i)return"";let a=H(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 q6(e){var t;let r={},n=H(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 V6(e,t,r){var n;let i=R6.get(e.toUpperCase());return i?i==="chart"?t.ChartGridMode==="Chart"?"chart":"list":i==="assistant"&&((n=r.getAttribute("uniqueid"))!==null&&n!==void 0?n:"").toUpperCase()===L6?"assistant":i:"unknown"}function Sm(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 gI(e){return e.replace(/^\{/,"").replace(/\}$/,"")}function G6(e,t){let r={n:"form",a:(0,ts.mergeAttrs)(e.bag.a,[]),c:(0,ts.spliceChildren)(e.bag.c,[])};return(0,ts.rebuildRaw)(r,(0,Ht.domEngine)(t),null)}function uI(e,t){let r=new DOMParser().parseFromString("<root/>","text/xml"),n=G6(e,r);return j6(r,n,e.components,t),z6(r,n,e.components,t),(0,Ht.serializeNode)(n)}function z6(e,t,r,n){let i=vI(t);for(let a of r)i.has(rs(a.position))||W6(e,t,a,n)}function W6(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=X6(t,e,l);for(let X of H(u,"row"))H(X,"cell").some(U=>H(U,"control").length>0)||u.removeChild(X);let c=r.classId||Sr.TILE_CLASS_ID[r.type]||Sr.TILE_CLASS_ID.iframe,d=r.rowspan&&r.rowspan>0?r.rowspan:4,p=r.bag&&cI(r.bag,"id")?String(cI(r.bag,"id")):Nu((0,oi.newId)()),f=r.id?Nu(r.id):Nu((0,oi.newId)()),h=u.parentNode,b=Math.max(1,parseInt(h&&h.getAttribute&&h.getAttribute("columns")||"1",10)||1),w=Math.min(Math.max(1,r.colspan&&r.colspan>0?r.colspan:1),b),E=H(u,"row"),D=E[E.length-1],L=D?H(D,"cell").reduce((X,U)=>X+Sm(U,"colspan",1),0):0;(!D||L+w>b)&&(D=e.createElement("row"),u.appendChild(D));let R=e.createElement("cell");R.setAttribute("id",p),R.setAttribute("colspan",String(w)),R.setAttribute("rowspan",String(d)),R.setAttribute("showlabel","true");let B=e.createElement("labels"),V=e.createElement("label");V.setAttribute("description",(o=r.name)!==null&&o!==void 0?o:""),V.setAttribute("languagecode",String(n)),B.appendChild(V),R.appendChild(B);let M=e.createElement("control");M.setAttribute("id",f),M.setAttribute("classid",Nu(c));let $=e.createElement("parameters"),G=(s=r.parameters)!==null&&s!==void 0?s:{};for(let X of Object.keys(G)){let U=(0,pI.createSafeXmlElement)(e,X,"dashboard tile parameter");U.textContent=G[X],$.appendChild(U)}M.appendChild($),R.appendChild(M),D.appendChild(R)}function cI(e,t){if(!e)return;let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function j6(e,t,r,n){var i;let a=vI(t),o=new Set(r.map(s=>rs(s.position)));for(let s of r){let l=a.get(rs(s.position));if(!l)continue;let u=H(l,"control")[0];u&&(H6(e,l,s.name,n),Q6(e,u,s.parameters),dI(l,"colspan",s.colspan),dI(l,"rowspan",s.rowspan),s.icProperties!==void 0&&$6(e,u,s.icProperties))}for(let[s,l]of a)o.has(s)||(i=l.parentNode)===null||i===void 0||i.removeChild(l)}function vI(e){let t=new Map;return H(e,"tabs").flatMap(n=>H(n,"tab")).forEach((n,i)=>{H(n,"columns").flatMap(o=>H(o,"column")).forEach((o,s)=>{H(o,"sections").flatMap(u=>H(u,"section")).forEach((u,c)=>{H(u,"rows").flatMap(p=>H(p,"row")).forEach((p,f)=>{H(p,"cell").forEach((h,b)=>{var w;gI((w=h.getAttribute("id"))!==null&&w!==void 0?w:"").toLowerCase().startsWith("spacer")||H(h,"control")[0]&&t.set(rs({tabIndex:i,columnIndex:s,sectionIndex:c,rowIndex:f,cellIndex:b}),h)})})})})}),t}function rs(e){let t=e??{};return`${t.tabIndex}.${t.columnIndex}.${t.sectionIndex}.${t.rowIndex}.${t.cellIndex}`}function H6(e,t,r,n){if(r===hI(t,n))return;let i=H(t,"labels")[0];i||(i=e.createElement("labels"),t.appendChild(i));let a=H(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 Q6(e,t,r){var n;if(!r)return;let i=Object.keys(r);if(i.length===0)return;let a=H(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,pI.createSafeXmlElement)(e,l,"dashboard component parameter");d.textContent=u,a.appendChild(d)}}}function dI(e,t,r){var n;((n=e.getAttribute(t))!==null&&n!==void 0?n:"")!==String(r)&&e.setAttribute(t,String(r))}function J6(e=2){let t=`{${(0,oi.newId)()}}`,r=`{${(0,oi.newId)()}}`,n=`{${(0,oi.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>`}Sr.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 Nu(e){return`{${e.replace(/[{}]/g,"")}}`}function X6(e,t,r){var n;let i=H(e,"tabs").flatMap(u=>H(u,"tab"))[0];if(!i)throw new Error("addDashboardTile: dashboard formxml has no <tab>");let a=H(i,"columns").flatMap(u=>H(u,"column"))[0];if(!a)throw new Error("addDashboardTile: dashboard formxml has no <column>");let o=H(a,"sections").flatMap(u=>H(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=H(s,"rows")[0];return l||(l=t.createElement("rows"),s.appendChild(l)),l}function K6(e=fI.DEFAULT_LCID){return{adapter:new Eu(e),api:x6.dashboardApi,languageSensitive:!0,publish:(t,r,n)=>n?.entityLogicalName?(0,wm.publishBoundEntity)(t,n):(0,wm.publishDashboardById)(t,r),publishScope:(t,r)=>r?.entityLogicalName?(0,wm.boundEntityPublishScope)(r):{envelope:"dashboard",targetIds:[t]}}}Sr.dashboardRegistration=K6});var NI=g(Iu=>{"use strict";Object.defineProperty(Iu,"__esModule",{value:!0});Iu.genPageApi=void 0;var SI=Xt(),Ce=he(),Dt=Z(),Nr=le(),_n="uxagentprojects",ba="uxagentprojectfiles",ya="uxagentprojectid",Er="uxagentprojectfileid",Du=`${ya},name`,Y6=`${Er},filename,filetype`;async function Nm(e,t,r,n){var i;let a=`/${t}(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Dt.odataQuery)([["$select",n]]),o=(0,Ce.ensureSuccess)(await e.get(a),e.apiUrl(a));return{row:(i=o.body)!==null&&i!==void 0?i:{},etag:(0,Ce.readEtag)(o)}}async function Z6(e,t){let r=`/${ba}(${t})/filecontent/$value`,n=await e.get(r);if(n.status===404)return{status:"unavailable",reason:"unpublished"};(0,Ce.ensureSuccess)(n,e.apiUrl(r));let i=n.body;if(i instanceof Uint8Array||Buffer.isBuffer(i))return{status:"available",data:Buffer.from(i).toString("base64")};if(i instanceof ArrayBuffer)return{status:"available",data:Buffer.from(new Uint8Array(i)).toString("base64")};if(typeof i=="string")return{status:"available",data:Buffer.from(i,"utf8").toString("base64")};throw new Nr.SdkError("GENPAGE_CONTENT_UNREADABLE",`Read the content of file '${t}' but the injected HttpClient returned a body this SDK cannot encode (${typeof i}). Return the response as a string, Uint8Array, Buffer, or ArrayBuffer; a byte-returning transport is required to round-trip non-UTF8 assets.`)}async function eG(e,t,r,n){if(!e.supportsBinaryPatch)throw new Nr.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 i=`/${ba}(${t})/filecontent`,a=new Uint8Array(Buffer.from(n,"base64"));(0,Dt.assertNoControlChars)(r,"generative-page file name"),(0,Ce.ensureSuccess)(await e.patchRaw(i,a,{headers:{"Content-Type":"application/octet-stream","Content-Length":String(a.byteLength),"x-ms-file-name":r}}),e.apiUrl(i))}async function Em(e,t){let r=`/${ba}/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()`+(0,Dt.odataQuery)([["$select",Y6],["$filter",`_${ya}_value eq ${t}`]]);return(await(0,SI.collectPages)(e,r,"fetchArtifact('genPage')")).map(i=>({row:i,etag:typeof i["@odata.etag"]=="string"?i["@odata.etag"]:null}))}async function bI(e,t,r){var n;let{etag:i}=await Nm(e,_n,t,Du),a={};for(let{row:l,etag:u}of await Em(e,t))a[(0,Dt.normalizeGuid)(String((n=l[Er])!==null&&n!==void 0?n:""),Er)]=u;let o=Object.keys(a),s=!i||o.length!==r.size||o.some(l=>!r.has(l))||Object.values(a).some(l=>!l);return{etag:i,memberEtags:a,mismatch:s}}function wI(e,t){return t.mismatch?{etag:null,memberEtags:{},warnings:[`Generative page '${e}' 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.`]}:{etag:t.etag,memberEtags:t.memberEtags}}Iu.genPageApi={async get(e,t){var r;let n=(0,Dt.normalizeGuid)(t,"id"),{row:i,etag:a}=await Nm(e,_n,n,Du),o=await Em(e,n),s={},l=[];for(let{row:u,etag:c}of o){let d=(0,Dt.normalizeGuid)(String((r=u[Er])!==null&&r!==void 0?r:""),Er);s[d]=c;let p=await Z6(e,d);l.push({...u,content:p})}return{raw:{project:i,files:l},etag:a,memberEtags:s}},async list(e,t){let r=`/${_n}/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()`+(0,Dt.odataQuery)([["$select",Du]]);return(await(0,SI.collectPages)(e,r,"listArtifacts('genPage')")).map(i=>{var a,o;return{type:"genPage",id:String((a=i[ya])!==null&&a!==void 0?a:""),name:String((o=i.name)!==null&&o!==void 0?o:""),isDirty:!1}})},async create(e,t,r){let n=t;AI(e,n);let i=`/${_n}`,a=(0,Ce.ensureSuccess)(await e.post(i,(0,Ce.withClientMintedId)({name:n.name},ya,r)),e.apiUrl(i)),o=(0,Ce.resolveCreatedId)(a,ya,"generative page",r),s=new Set;for(let l of n.files){let u=await CI(e,o,l,!0);s.add((0,Dt.normalizeGuid)(u.id,"file id"))}try{return{id:o,...wI(o,await bI(e,o,s))}}catch(l){return{id:o,etag:null,memberEtags:{},warnings:[`The generative page was created, but re-reading its concurrency tokens failed (${l instanceof Error?l.message:String(l)}). The local baseline is unusable: re-fetch the page before editing it \u2014 the next push will refuse rather than overwrite blind.`]}}},async update(e,t,r,n,i){let a=r,o=(0,Dt.normalizeGuid)(t,"id");AI(e,a);let s=await Em(e,o),{etag:l}=await Nm(e,_n,o,Du);if(n&&l&&n!==l)throw new Nr.SdkError(Ce.VERSION_CONFLICT_CODE,`Generative page '${o}' changed on the server after it was fetched (baseline ${n}, server ${l}) \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||!l)throw new Nr.SdkError(Ce.VERSION_CONFLICT_CODE,`Cannot verify generative page '${o}' 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 u=new Set(s.map(({row:f})=>{var h;return(0,Dt.normalizeGuid)(String((h=f[Er])!==null&&h!==void 0?h:""),Er)})),c=new Set(a.files.map(f=>(0,Dt.normalizeGuid)(f.id,"file id")));if(!i)throw new Nr.SdkError(Ce.VERSION_CONFLICT_CODE,`Cannot verify the files of generative page '${o}' 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 d=new Set(Object.keys(i).map(f=>f.toLowerCase()));{for(let h of c)if(!u.has(h)&&d.has(h))throw new Nr.SdkError(Ce.VERSION_CONFLICT_CODE,`Generative-page file '${h}' 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 and, for an unpublished page, restore the row WITHOUT its content. Re-fetch the page and re-apply the edit.`);for(let h of u)if(!d.has(h))throw new Nr.SdkError(Ce.VERSION_CONFLICT_CODE,`Generative-page file '${h}' 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 f=new Map(s.map(({row:h,etag:b})=>{var w;return[(0,Dt.normalizeGuid)(String((w=h[Er])!==null&&w!==void 0?w:""),Er),b]}));for(let[h,b]of Object.entries(i??{})){let w=h.toLowerCase();if(!u.has(w))continue;let E=f.get(w);if(!b||!E)throw new Nr.SdkError(Ce.VERSION_CONFLICT_CODE,`Cannot verify generative-page file '${w}' before writing: ${b?"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(b!==E)throw new Nr.SdkError(Ce.VERSION_CONFLICT_CODE,`Generative-page file '${w}' changed on the server after this page was fetched (baseline ${b}, server ${E}) \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 p=`/${_n}(${o})`;(0,Ce.ensureSuccess)(await e.patch(p,{name:a.name},{headers:{"If-Match":"*"}}),e.apiUrl(p));for(let f of a.files){let h=(0,Dt.normalizeGuid)(f.id,"file id");await CI(e,o,f,!u.has(h))}for(let f of u)c.has(f)||await(0,Ce.deleteRecord)(e,ba,f);try{return{id:o,...wI(o,await bI(e,o,c))}}catch(f){return{id:o,etag:null,memberEtags:{},warnings:[`The generative page was written, but re-reading its concurrency tokens failed (${f instanceof Error?f.message:String(f)}). The local baseline is now unusable: re-fetch the page before editing it again \u2014 the next push will refuse rather than overwrite blind.`]}}},delete(e,t){return(0,Ce.deleteRecord)(e,_n,t)}};function AI(e,t){var r;if(((r=t.files)!==null&&r!==void 0?r:[]).some(i=>i.content.status==="available")&&!e.supportsBinaryPatch)throw new Nr.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: it has file content to upload, but the injected HttpClient does not implement patchRaw(). 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.")}async function CI(e,t,r,n){let i=(0,Dt.normalizeGuid)(r.id,"file id"),a;if(n){let o=`/${ba}`,s=(0,Ce.ensureSuccess)(await e.post(o,(0,Ce.withClientMintedId)({filename:r.name,filetype:r.fileType,[`${ya}@odata.bind`]:`/${_n}(${t})`},Er,i)),e.apiUrl(o));a=(0,Ce.readEtag)(s)}else{let o=`/${ba}(${i})`,s=(0,Ce.ensureSuccess)(await e.patch(o,{filename:r.name,filetype:r.fileType},{headers:{"If-Match":"*"}}),e.apiUrl(o));a=(0,Ce.readEtag)(s)}return r.content.status==="available"&&await eG(e,i,r.name,r.content.data),{id:i,etag:a}}});var _I=g(Aa=>{"use strict";Object.defineProperty(Aa,"__esModule",{value:!0});Aa.genPageRegistration=Aa.GenPageAdapter=void 0;var tG=NI(),rG=Yt(),Pn=wr(),II=mt(),EI=2e8;function DI(e){return typeof e=="string"&&e.trim()!==""?e:(0,II.newId)()}function wa(e){return(0,Pn.isJsonObject)(e)?e:{}}function nG(e){let t=wa(e);return t.status==="available"&&typeof t.data=="string"?{status:"available",data:t.data}:{status:"unavailable",reason:"unpublished"}}var _u=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var r,n;let i=t,a=wa(i?.project),o=Array.isArray(i?.files)?i.files:[];return{id:String((r=a.uxagentprojectid)!==null&&r!==void 0?r:""),name:String((n=a.name)!==null&&n!==void 0?n:""),files:o.map(s=>{var l,u,c;let d=wa(s);return{id:String((l=d.uxagentprojectfileid)!==null&&l!==void 0?l:""),name:String((u=d.filename)!==null&&u!==void 0?u:""),fileType:Number((c=d.filetype)!==null&&c!==void 0?c:EI),content:nG(d.content)}})}}toApiPayload(t){var r;return{name:t.name,files:((r=t.files)!==null&&r!==void 0?r:[]).map(n=>({id:n.id,name:n.name,fileType:n.fileType,content:n.content}))}}createDefault(t){var r,n;return{id:DI(t.id),name:(r=t.name)!==null&&r!==void 0?r:"New page",files:((n=t.files)!==null&&n!==void 0?n:[]).map(i=>{var a,o,s;return{id:DI(i.id),name:(a=i.name)!==null&&a!==void 0?a:"index.tsx",fileType:(o=i.fileType)!==null&&o!==void 0?o:EI,content:(s=i.content)!==null&&s!==void 0?s:{status:"available",data:""}}})}}assignMissingIds(t){let r=wa(t);return(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,II.newId)()),r}validate(t){let r=[],n=t.files;if(n!==void 0&&!Array.isArray(n))return r.push((0,Pn.issue)("/files","files-must-be-array",`files must be an array, got ${typeof n}`)),r;let i=new Map;return(Array.isArray(n)?n:[]).forEach((a,o)=>{let s=`/files/${o}`,l=wa(a),u=typeof l.id=="string"?l.id.trim().toLowerCase():"";if(u==="")r.push((0,Pn.issue)(s,"file-id-required","a generative-page file needs an id"));else{let f=i.get(u);f!==void 0?r.push((0,Pn.issue)(s,"file-id-duplicate",`two files share the id '${l.id}' (also at /files/${f}); a file's id is its identity, so a duplicate makes an edit ambiguous`)):i.set(u,o)}let c=typeof l.name=="string"?l.name:"";(c===""||/[\u0000-\u001F\u007F]/.test(c)||/[\\/]/.test(c))&&r.push((0,Pn.issue)(s+"/name","file-name-invalid",`a file name must be a non-empty single path segment with no control characters or path separators (it is sent as an HTTP header on upload); got '${c}'`));let d=l.content;if(d===void 0){r.push((0,Pn.issue)(s+"/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 p=wa(d);p.status==="available"?typeof p.data!="string"&&r.push((0,Pn.issue)(s+"/content/data","file-content-data-invalid","available content needs base64 `data`")):p.status!=="unavailable"&&r.push((0,Pn.issue)(s+"/content/status","file-content-status-invalid",`content.status must be 'available' or 'unavailable', got ${String(p.status)}`))}),r}};Aa.GenPageAdapter=_u;function iG(){return{adapter:new _u,api:tG.genPageApi,publish:(e,t)=>(0,rG.publishGenPageById)(e,t),publishScope:e=>({envelope:"uxagentproject",targetIds:[e]})}}Aa.genPageRegistration=iG});var TI=g(Tu=>{"use strict";Object.defineProperty(Tu,"__esModule",{value:!0});Tu.reconcileBpfSecurityRoles=void 0;var Pu=he(),Dm=Z(),aG="Global",PI={create:"Create",read:"Read",write:"Write",delete:"Delete"};async function oG(e,t){var r,n;let i=`/EntityDefinitions(LogicalName='${t}')?$select=LogicalName,Privileges`,o=(n=(r=(0,Pu.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(PI).forEach(u=>{let c=o.find(d=>d.PrivilegeType===PI[u]);if(c){let d=(0,Dm.normalizeGuid)(c.PrivilegeId,"PrivilegeId");s[u]=d,l.add(d)}}),{byAccess:s,all:l}}async function sG(e,t){var r,n;let i=`/RetrieveRolePrivilegesRole(RoleId=${t})`,o=(n=(r=(0,Pu.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,Dm.normalizeGuid)(s.PrivilegeId,"PrivilegeId")))}async function lG(e,t,r){if(r.length===0)return;let n={Privileges:r.map(a=>({Depth:aG,PrivilegeId:a}))},i=`/roles(${t})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;(0,Pu.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function uG(e,t,r){let n={Privilege:{"@odata.type":"Microsoft.Dynamics.CRM.privilege",privilegeid:r}},i=`/roles(${t})/Microsoft.Dynamics.CRM.RemovePrivilegeRole`;(0,Pu.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function cG(e,t,r){var n;if(!r||r.length===0)return;let i=await oG(e,t.toLowerCase());for(let a of r){let o=(0,Dm.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 sG(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 lG(e,o,c);for(let p of d)await uG(e,o,p)}}Tu.reconcileBpfSecurityRoles=cG});var FI=g(xu=>{"use strict";Object.defineProperty(xu,"__esModule",{value:!0});xu.bpfApi=void 0;var Tn=fn(),dG=Xt(),Qt=he(),Dr=Z(),pG=TI(),Ou={"Content-Type":"application/json",Accept:"application/json"},fG=`category eq ${Tn.WorkflowCategory.BusinessProcessFlow} and type eq ${Tn.WorkflowTypeCode.Definition} and businessprocesstype eq ${Tn.BusinessProcessType.BusinessFlow}`,mG="workflowid,name,description,primaryentity,statecode,category,type,businessprocesstype,processorder",hG="workflowid,name,uniquename,description,primaryentity,statecode,statuscode,category,type,businessprocesstype,processorder,xaml,clientdata",gG=["xaml","name","description","processorder"];async function OI(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,pG.reconcileBpfSecurityRoles)(e,n,t.securityRoles)}async function Im(e,t,r){var n;if(r==="Draft")return null;let i=(0,Dr.normalizeGuid)(t,"workflowid"),a={statecode:Tn.StateCode.Activated,statuscode:Tn.StatusCode.Activated},o=`/workflows(${i})`,s=(0,Qt.ensureSuccess)(await e.patch(o,a,{headers:Ou}),e.apiUrl(o));return(n=(0,Qt.readEtag)(s))!==null&&n!==void 0?n:await LI(e,i)}async function LI(e,t){let r=`/workflows(${t})${(0,Dr.odataQuery)([["$select","workflowid"]])}`,n=await e.get(r);return n.status>=200&&n.status<300?(0,Qt.readEtag)(n):null}async function vG(e,t){var r;let n=`/workflows(${t})${(0,Dr.odataQuery)([["$select","statecode"]])}`,i=await e.get(n);if(i.status<200||i.status>=300)return null;let a=(r=i.body)===null||r===void 0?void 0:r.statecode;return a==null?null:Number(a)}async function xI(e,t,r){if(await vG(e,t)!==Tn.StateCode.Activated)return!1;let n={statecode:Tn.StateCode.Draft,statuscode:Tn.StatusCode.Draft},i=`/workflows(${t})`,a={...Ou};return r&&(a["If-Match"]=r),(0,Qt.ensureSuccess)(await e.patch(i,n,{headers:a}),e.apiUrl(i)),!0}async function RI(e,t){try{await Im(e,t,"Active")}catch{}}function yG(e){let t={};for(let r of gG)e[r]!==void 0&&(t[r]=e[r]);return t}xu.bpfApi={async get(e,t){let n=`/workflows(${(0,Dr.normalizeGuid)(t,"id")})${(0,Dr.odataQuery)([["$select",hG]])}`,i=(0,Qt.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,Qt.readEtag)(i)}},async list(e,t){let r=[fG];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,Dr.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,Dr.odataQuery)([["$select",mG],["$filter",r.join(" and ")]])}`;return(await(0,dG.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,Dr.normalizeGuid)(r.record.workflowid,"workflowid"),i="/workflows",a=(0,Qt.ensureSuccess)(await e.post(i,r.record,{headers:Ou}),e.apiUrl(i)),o=null;try{o=await Im(e,n,r.status),await OI(e,r)}catch(s){try{await(0,Qt.deleteRecord)(e,"workflows",n)}catch{}throw s}return{id:n,etag:o??(0,Qt.readEtag)(a)}},async update(e,t,r,n){var i;let a=r,o=(0,Dr.normalizeGuid)(t,"id"),s=await xI(e,o,n);try{let l=`/workflows(${o})`,u={...Ou};n&&!s&&(u["If-Match"]=n);let c=(0,Qt.ensureSuccess)(await e.patch(l,yG(a.record),{headers:u}),e.apiUrl(l)),d=await Im(e,o,a.status);return await OI(e,a),{id:o,etag:(i=d??(0,Qt.readEtag)(c))!==null&&i!==void 0?i:await LI(e,o)}}catch(l){throw s&&await RI(e,o),l}},async delete(e,t){let r=(0,Dr.normalizeGuid)(t,"id"),n=await xI(e,r,null);try{await(0,Qt.deleteRecord)(e,"workflows",r)}catch(i){throw n&&await RI(e,r),i}}}});var y_=g(Na=>{"use strict";Object.defineProperty(Na,"__esModule",{value:!0});Na.bpfRegistration=Na.BpfAdapter=void 0;var Ca=As(),bG=js(),Ru=fn(),wG=FI(),_m=An(),si=la(),QI=Cn(),Ot=wr(),On=mt(),Ir=le(),AG=100,Tm='<?xml version="1.0" encoding="utf-16"?>',kI=1033,JI="mxswa:Workflow",CG="mxswa:ActivityReference.Properties",SG="mcwo:StepLabel",NG="mcwb:Control",MI="mcwb:Control.ControlDisplayName",XI="mcwb:Control.DataFieldName",KI="DataFieldName",UI="ControlDisplayName",YI="Literal",Lu="x:Null",BI="x:String",Om="x:Key",xm="DisplayName",ku="Activities",EG="StepLabels",ZI="StageId",e_="StageCategory",t_="NextStageId",r_="ProcessStepId",Rm="IsProcessRequired",n_="EntityComposite",i_="StageComposite",a_="StepComposite";function Pm(e){return(0,Ot.isJsonObject)(e)?e:{}}function _r(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 li(e,t){var r;return(r=_r(e).find(n=>n.tagName===t))!==null&&r!==void 0?r:null}function Pr(e){return li(e,CG)}function dt(e,t){var r;return(r=_r(e).find(n=>n.getAttribute(Om)===t))!==null&&r!==void 0?r:null}function Sa(e,t){var r;return((r=e.getAttribute("AssemblyQualifiedName"))!==null&&r!==void 0?r:"").includes(t)}function Kr(e){var t;return!e||!e.firstChild?"":(t=e.firstChild.nodeValue)!==null&&t!==void 0?t:""}function o_(e,t,r){e.firstChild?e.firstChild.nodeValue=r:e.appendChild(t.createTextNode(r))}function ns(e){var t;let r=(t=e.getAttribute(xm))!==null&&t!==void 0?t:"",n=r.indexOf(": ");return n>=0?r.slice(n+2):r}function s_(e,t){var r;let n=(r=e.getAttribute(xm))!==null&&r!==void 0?r:"",i=n.indexOf(": ");e.setAttribute(xm,i>=0?n.slice(0,i+2)+t:t)}function l_(e,t){let r=dt(e,EG),n=li(r,SG);n&&n.setAttribute("Description",t)}function DG(e){let t=dt(e,e_);if(!t||t.tagName===Lu)return;let r=Kr(t).trim();return r===""?void 0:Number(r)}function IG(e){let t=dt(e,t_);if(!t||t.tagName===Lu)return;let r=Kr(t).trim();return r===""?void 0:r}function u_(e){let t=c_(e);if(!t)return;let r=p_(t,KI,XI);return r===""?void 0:r}function Lm(e,t){let r=_r(e);for(;r.length>0;){let n=r.pop();if(n.tagName===t)return n;for(let i of _r(n))r.push(i)}return null}function c_(e){let t=dt(Pr(e),ku);return t?Lm(t,NG):null}function d_(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 p_(e,t,r){var n;return d_(e,t)?(n=e.getAttribute(t))!==null&&n!==void 0?n:"":xG(e,r)}function $I(e,t,r,n){if(d_(e,t)){e.setAttribute(t,n);return}if(li(e,r)){_G(e,r,n);return}throw new Ir.InvalidArgumentError(`BPF step control exposes neither a '${t}' attribute nor a <${r}> wrapper to bind a column`)}function _G(e,t,r){let n=li(e,t),i=n?Lm(n,YI):null;i&&i.setAttribute("Value",r)}function f_(e){return ns(e)}function Mu(e){let t=li(e,JI),r=[];for(let n of _r(t).filter(i=>Sa(i,n_))){let i=dt(Pr(n),ku);for(let a of _r(i).filter(o=>Sa(o,i_)))r.push({el:a,entity:f_(n)})}return r}function Fm(e){let t=dt(Pr(e),ku);return _r(t).filter(r=>Sa(r,a_))}function PG(e){let t=Pr(e),r=Kr(dt(t,Rm)).trim().toLowerCase(),n=u_(e),i={id:Kr(dt(t,r_)),name:ns(e)};return n!==void 0&&(i.fieldName=n),r==="true"&&(i.required=!0),i}function TG(e,t){let r=Pr(e),n=DG(r),i=IG(r),a={id:Kr(dt(r,ZI)),name:ns(e),entityLogicalName:t,steps:Fm(e).map(PG)};return n!==void 0&&(a.category=n),i!==void 0&&(a.nextStageId=i),a}function OG(e){return Mu(e).map(({el:t,entity:r})=>TG(t,r))}function Xr(e){return new Ir.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 xG(e,t){var r;let n=li(e,t),i=n?Lm(n,YI):null;return(r=i?.getAttribute("Value"))!==null&&r!==void 0?r:""}function km(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(km(e,s)):s.nodeType===3&&n.appendChild(e.createTextNode((r=s.nodeValue)!==null&&r!==void 0?r:""))}return n}function m_(e){return dt(Pr(e),ku)}function RG(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,On.newId)(),{body:o}=Uu(Mm(i,(0,Ca.v4)(),t.id,a));return km(e,Mu((0,si.parseXmlRoot)(o,"<Activity/>"))[0].el)}function LG(e,t){let{body:r}=Uu(Mm("account",(0,Ca.v4)(),(0,Ca.v4)(),t.id));return km(e,Fm(Mu((0,si.parseXmlRoot)(r,"<Activity/>"))[0].el)[0])}function h_(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);for(let r of t)e.appendChild(r)}function g_(e,t,r,n){let i=dt(e,r);if(!i||!i.parentNode){if(n!==void 0&&n!=="")throw Xr(`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!==Lu){let s=t.createElement(Lu);s.setAttribute(Om,r),a.replaceChild(s,i)}return}if(i.tagName===BI){Kr(i)!==n&&o_(i,t,n);return}let o=t.createElement(BI);o.setAttribute(Om,r),o.appendChild(t.createTextNode(n)),a.replaceChild(o,i)}function FG(e,t,r){g_(e,t,e_,r===void 0?void 0:String(r))}function kG(e,t,r){g_(e,t,t_,r)}function v_(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 qI(e){return Kr(dt(Pr(e),ZI))}function VI(e){return Kr(dt(Pr(e),r_))}function GI(e,t,r){var n,i,a,o;let s=Pr(e);r.name!==ns(e)&&(s_(e,r.name),l_(s,r.name));let l=Kr(dt(s,Rm)).trim().toLowerCase()==="true";if(((n=r.required)!==null&&n!==void 0?n:!1)!==l){let u=dt(s,Rm);u&&o_(u,t,r.required?"True":"False")}if(((i=r.fieldName)!==null&&i!==void 0?i:"")!==((a=u_(e))!==null&&a!==void 0?a:"")){let u=c_(e);if(!u)throw new Ir.InvalidArgumentError("BPF step has no <mcwb:Control> element to bind a column to");let c=(o=r.fieldName)!==null&&o!==void 0?o:"";$I(u,KI,XI,c),c!==""&&p_(u,UI,MI)===""&&$I(u,UI,MI,c)}}function zI(e,t,r,n){var i;let a=Pr(e);if(!a)throw new Ir.InvalidArgumentError("BPF stage composite has no <\u2026ActivityReference.Properties>");if(r.name!==ns(e)&&(s_(e,r.name),l_(a,r.name)),FG(a,t,r.category),kG(a,t,n),r.relationshipName&&r.relationshipName.trim()!=="")throw Xr("a stage relationship / table change (multi-table authoring)");if(r.actions&&r.actions.length>0||r.branch)throw Xr("stage actions or conditional branching");let o=m_(e);if(!o)throw new Ir.InvalidArgumentError("BPF stage has no [Activities] collection");let s=(i=r.steps)!==null&&i!==void 0?i:[];if(s.length===0)throw new Ir.InvalidArgumentError(`BPF stage '${r.name}' must have at least one step`);let l=Fm(e);if(v_(l,s.map(d=>d.id),VI)){l.forEach((d,p)=>GI(d,t,s[p]));return}let u=new Map(l.map(d=>[VI(d),d]));if(_r(o).some(d=>!Sa(d,a_)))throw Xr("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:LG(t,d)});h_(o,c),c.forEach((d,p)=>GI(d,t,s[p]))}function MG(e,t,r){let n=li(e,JI);if(!n)throw new Ir.InvalidArgumentError("BPF xaml has no <mxswa:Workflow> root activity");if(r.globalActions&&r.globalActions.length>0)throw Xr("global (process-completed/abandoned) actions");if(!r.stages||r.stages.length===0)throw new Ir.InvalidArgumentError("a BPF must have at least one stage");let i=Mu(e),a=i.map(p=>p.el);if(v_(a,r.stages.map(p=>p.id),qI)){i.forEach(({el:p,entity:f},h)=>{let b=r.stages[h];if(b.entityLogicalName&&b.entityLogicalName.trim()!==""&&b.entityLogicalName!==f)throw Xr(`changing a stage's table ('${b.entityLogicalName}' vs the process's '${f}')`);zI(p,t,b,b.nextStageId)});return}let o=_r(n).filter(p=>Sa(p,n_));if(o.length!==1)throw Xr("adding, removing or reordering stages on a multi-table process");let s=o[0],l=f_(s),u=m_(s);if(!u)throw new Ir.InvalidArgumentError("BPF primary entity composite has no [Activities] collection");if(_r(u).some(p=>!Sa(p,i_)))throw Xr("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 Xr(`a stage on a different table ('${p.entityLogicalName}') than the process primary ('${l}')`);let c=new Map(a.map(p=>[qI(p),p])),d=r.stages.map(p=>{var f;return(f=c.get(p.id))!==null&&f!==void 0?f:RG(t,p,l)});h_(u,d),d.forEach((p,f)=>{let h=f<d.length-1?r.stages[f+1].id:void 0;zI(p,t,r.stages[f],h)})}function Uu(e){let t=e.match(/^<\?xml[^>]*\?>\s*/),r=t?t[0]:"";return{prolog:r,body:e.slice(r.length)}}function UG(e){var t,r,n,i,a,o;(0,QI.installDomShim)();let s=(t=e.bag)===null||t===void 0?void 0:t.xaml;if(s){let p=new bG.DOMParser().parseFromString("<root/>","text/xml"),f={n:"Activity",a:(0,_m.mergeAttrs)(s.a,[]),c:(0,_m.spliceChildren)(s.c,[])};return{root:(0,_m.rebuildRaw)(f,(0,si.domEngine)(p),null),prolog:(n=(r=e.bag)===null||r===void 0?void 0:r.xamlProlog)!==null&&n!==void 0?n:Tm,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=Mm(e.entityLogicalName,(0,Ca.v4)(),l?.id&&l.id.trim()!==""?l.id:(0,Ca.v4)(),u?.id&&u.id.trim()!==""?u.id:(0,Ca.v4)()),{body:d}=Uu(c);return{root:(0,si.parseXmlRoot)(d,"<Activity/>"),prolog:Tm,eol:"lf"}}function BG(e){let{root:t,prolog:r,eol:n}=UG(e);MG(t,t.ownerDocument,e);let i=(0,si.serializeNode)(t);return n==="crlf"&&(i=i.replace(/\n/g,`\r+`)),r+i}function $G(e){return e.uniqueName&&e.uniqueName.trim()!==""?e.uniqueName:`new_${(e.name||"businessprocessflow").toLowerCase().replace(/[^a-z0-9]/g,"")||"businessprocessflow"}`}var Fu=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var r,n;(0,QI.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}=Uu(a),u=(0,si.parseXmlRoot)(l,"<Activity/>");o.stages=OG(u),o.bag={xaml:(0,si.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,On.newId)(),name:t.name,uniquename:$G(t),primaryentity:t.entityLogicalName,xaml:BG(t),category:Ru.WorkflowCategory.BusinessProcessFlow,type:Ru.WorkflowTypeCode.Definition,businessprocesstype:Ru.BusinessProcessType.BusinessFlow,scope:Ru.WorkflowScope.Organization,processorder:(r=t.order)!==null&&r!==void 0?r:AG};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 Ir.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(jI):[jI({id:(0,On.newId)(),name:"New Stage",steps:[]})],o={id:t.id&&t.id.trim()!==""?t.id:(0,On.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=Pm(t);(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,On.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,Ot.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,Ot.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=Pm(l),p=typeof d.id=="string"?d.id.trim():"";p===""?r.push((0,Ot.issue)(`${c}/id`,"stage-id-required","a stage needs an id")):o.has(p.toLowerCase())?r.push((0,Ot.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,Ot.issue)(`${c}/steps`,"stage-needs-step","a BPF stage must have at least one step")),f.length>30&&r.push((0,Ot.issue)(`${c}/steps`,"too-many-steps",`a stage allows at most 30 steps, got ${f.length}`));let h=new Map;f.forEach((b,w)=>{let E=`${c}/steps/${w}`,D=typeof Pm(b).id=="string"?b.id.trim():"";D===""?r.push((0,Ot.issue)(`${E}/id`,"step-id-required","a step needs an id")):h.has(D.toLowerCase())?r.push((0,Ot.issue)(`${E}/id`,"step-id-duplicate",`two steps in this stage share the id '${b.id}'`)):h.set(D.toLowerCase(),w)}),l.branch&&!WI(i,l.branch.nextStageId)&&r.push((0,Ot.issue)(`${c}/branch/nextStageId`,"branch-target-unknown",`branch nextStageId '${l.branch.nextStageId}' does not match any stage id`)),typeof l.nextStageId=="string"&&l.nextStageId!==""&&!WI(i,l.nextStageId)&&r.push((0,Ot.issue)(`${c}/nextStageId`,"next-stage-unknown",`nextStageId '${l.nextStageId}' does not match any stage id`))}),a.size>5&&r.push((0,Ot.issue)("/stages","too-many-tables",`a BPF spans at most 5 tables, got ${a.size}`));let s=qG(i);return s>=0&&r.push((0,Ot.issue)(`/stages/${s}/nextStageId`,"next-stage-cycle","the stage nextStageId links form a cycle; the flow must be acyclic")),r}};Na.BpfAdapter=Fu;function qG(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 WI(e,t){return e.some(r=>r.id===t)}function jI(e){var t,r;let n=e.steps&&e.steps.length>0?e.steps.map(HI):[HI({id:(0,On.newId)(),name:"New Step"})],i={id:e.id&&e.id.trim()!==""?e.id:(0,On.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 HI(e){var t;let r={id:e.id&&e.id.trim()!==""?e.id:(0,On.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 Mm(e,t,r,n){return`${Tm}<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="${kI}" /></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="${kI}" /></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 VG(){return{adapter:new Fu,api:wG.bpfApi,languageSensitive:!0}}Na.bpfRegistration=VG});var b_=g(Bu=>{"use strict";Object.defineProperty(Bu,"__esModule",{value:!0});Bu.buildRegistrations=void 0;var GG=FE(),zG=eD(),WG=p2(),jG=S2(),HG=V2(),QG=aI(),JG=yI(),XG=_I(),KG=y_();function YG(e){let t=new Map;return t.set("form",(0,GG.formRegistration)(e)),t.set("view",(0,zG.viewRegistration)()),t.set("businessRule",(0,WG.businessRuleRegistration)()),t.set("app",(0,jG.appRegistration)(e)),t.set("command",(0,HG.commandRegistration)()),t.set("chart",(0,QG.chartRegistration)()),t.set("dashboard",(0,JG.dashboardRegistration)(e)),t.set("genPage",(0,XG.genPageRegistration)()),t.set("bpf",(0,KG.bpfRegistration)()),t}Bu.buildRegistrations=YG});var w_=g($u=>{"use strict";Object.defineProperty($u,"__esModule",{value:!0});$u.cloneJson=void 0;function ZG(e){return JSON.parse(JSON.stringify(e))}$u.cloneJson=ZG});var __=g(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.removeRowSummary=Te.configureRowSummary=Te.buildGptDynamicPrompt=Te.setAppAiFeatures=Te.getAiReadiness=Te.saveSettingValue=Te.retrieveSetting=Te.AI_GATE=void 0;var or=he(),We=Z(),A_=mt(),Yr=le();Te.AI_GATE={formFill:"FormFillBarUXEnabled",nlSearch:"EnableNLGridSearch",nlChart:"NLChartVisualizationSetting",summaries:"EnableFormInsights",m365:"m365copilotmodelappenabled"};var e7={formFill:"FormFillBarUXEnabled",nlSearch:"NLGridSearchSetting",nlChart:"NLChartDataVisualizationSetting",m365:"m365copilotmodelappenabled"},qu=1e6;function t7(e,t){let r=()=>{throw new Yr.InvalidArgumentError(`setAppAiFeatures: '${t}' must be a boolean or an integer between 0 and ${qu} (e.g. 0, 1, 2); got '${String(e)}'.`)};if(typeof e=="boolean")return e?"1":"0";if(typeof e=="number")return!Number.isSafeInteger(e)||e<0||e>qu?r():String(e);if(typeof e=="string"){let n=e.trim(),i=n.toLowerCase();if(i==="true")return"1";if(i==="false")return"0";if(/^[0-9]+$/.test(n)){let a=n.replace(/^0+(?=[0-9])/,"");return a.length>String(qu).length||Number(a)>qu?r():a}}return r()}function r7(e){return e!=="0"}async function n7(e,t){var r,n,i;let a=`/appmodules${(0,We.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,We.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 i7(e,t){var r,n;let i=`/appmodules${(0,We.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,We.odataLiteral)(t)}'`]])}`,a;try{a=await e.get(i)}catch(l){throw new Yr.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 Yr.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 Yr.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 Yr.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a row with no appmoduleid.`);return s}var C_=new WeakMap;async function a7(e,t){var r,n,i;let a=C_.get(e);if(a||(a=new Map,C_.set(e,a)),a.has(t))return a.get(t);let o=`/settingdefinitions${(0,We.odataQuery)([["$select","settingdefinitionid"],["$filter",`uniquename eq '${(0,We.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 o7(e,t,r){var n,i;let a=await a7(e,r);if(!t||!a)return;let o=`/appsettings${(0,We.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 s7=4,l7=500,S_=20,N_=3e4;function u7(e){if(e===void 0)return s7;if(!Number.isFinite(e))throw new Yr.InvalidArgumentError(`setAppAiFeatures: verifyAttempts must be a finite integer between 1 and ${S_}; got ${e}.`);return Math.min(S_,Math.max(1,Math.floor(e)))}function c7(e){if(e===void 0)return l7;if(!Number.isFinite(e))throw new Yr.InvalidArgumentError(`setAppAiFeatures: verifyDelayMs must be a finite number between 0 and ${N_}; got ${e}.`);return Math.min(N_,Math.max(0,Math.floor(e)))}function d7(e){return e>0?new Promise(t=>setTimeout(t,e)):Promise.resolve()}async function p7(e,t,r,n,i,a,o){let s,l,u,c=!1;for(let d=0;d<a;d+=1){d>0&&await d7(o*d);let p;try{let f=await t();f?(p=await o7(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 Vu(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 E_(e,t){return t===2?String(e).toLowerCase()==="true":e!=null&&e!=="0"&&e!==""}async function Vu(e,t,r={}){var n,i;let a=[`SettingName='${(0,We.odataPathLiteral)(t)}'`];r.appUniqueName&&a.push(`AppUniqueName='${(0,We.odataPathLiteral)(r.appUniqueName)}'`);let o=`/RetrieveSetting(${a.join(",")})`,l=(i=(n=(0,or.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}}Te.retrieveSetting=Vu;async function D_(e,t,r,n={}){let i={SettingName:t,Value:r};n.appUniqueName&&(i.AppUniqueName=n.appUniqueName),n.solutionUniqueName&&(i.SolutionUniqueName=n.solutionUniqueName),(0,or.ensureSuccess)(await e.post("/SaveSettingValue",i),e.apiUrl("/SaveSettingValue"))}Te.saveSettingValue=D_;async function f7(e,t={}){let r={};for(let[n,i]of Object.entries(Te.AI_GATE)){let{value:a,dataType:o}=await Vu(e,i,t);r[n]={enabled:E_(a,o),setting:i,value:a}}return r}Te.getAiReadiness=f7;async function m7(e,t,r,n={}){var i,a,o;if(!t||!t.trim())throw new Yr.InvalidArgumentError("setAppAiFeatures: a non-empty appUniqueName is required (an empty value would write the setting at organization scope, affecting every app).");let s=u7(n.verifyAttempts),l=c7(n.verifyDelayMs),u=[];for(let[w,E]of Object.entries(r)){if(E===void 0)continue;let D=e7[w];D&&u.push({feature:w,setting:D,requestedValue:t7(E,w)})}let c=[],d=n.appModuleId?(0,We.normalizeGuid)(n.appModuleId,"appModuleId"):void 0;if(d){let w=await i7(e,t);if(w&&(0,We.normalizeGuid)(w,"appModuleId")!==d)throw new Yr.InvalidArgumentError(`setAppAiFeatures: appModuleId '${d}' does not belong to app '${t}' (which resolves to '${w}'). Settings are written by unique name, so verifying against a different app would report success for a write that never landed.`)}let p,f=async()=>d||(p||(p=await n7(e,t)),p),h=new Map,b=async w=>{let E=Te.AI_GATE[w];if(E){if(!h.has(E)){let{value:D,dataType:L}=await Vu(e,E);h.set(E,{enabled:E_(D,L),setting:E,value:D})}return h.get(E)}};for(let{feature:w,setting:E,requestedValue:D}of u)try{if(r7(D)){let B=await b(w);if(!B?.enabled){c.push({feature:w,setting:E,requestedValue:D,status:"skipped",reason:`the org readiness gate '${(i=B?.setting)!==null&&i!==void 0?i:w}' is off, so the feature cannot be enabled for this app`});continue}}await D_(e,E,D,{appUniqueName:t,solutionUniqueName:n.solutionUniqueName});let L=await p7(e,f,t,E,D,s,l),R={feature:w,setting:E,requestedValue:D,effectiveValue:L.effectiveValue,appOverrideExists:L.appOverrideExists};L.result==="proven"?c.push({...R,status:"applied"}):L.result==="absent"?c.push({...R,status:"notPersisted",reason:`the write reported success but no app-scope override holding '${D}' was observed for '${E}' after ${s} attempt(s) \u2014 it reads '${(a=L.effectiveValue)!==null&&a!==void 0?a:""}' for this app (Dataverse can accept an app-scope write without storing it)`}):c.push({...R,status:"unverified",reason:`the write was issued but could not be confirmed: ${(o=L.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(L){c.push({feature:w,setting:E,requestedValue:D,status:"failed",reason:L.message})}return{applied:c.filter(w=>w.status==="applied").map(w=>w.feature),skipped:c.filter(w=>w.status==="skipped").map(w=>w.feature),notPersisted:c.filter(w=>w.status==="notPersisted").map(w=>w.feature),unverified:c.filter(w=>w.status==="unverified").map(w=>w.feature),failed:c.filter(w=>w.status==="failed").map(w=>w.feature),outcomes:c}}Te.setAppAiFeatures=m7;var h7="GptPowerPrompt",g7='{ "consumptionSource": "Api", "partnerSource": "AIBuilder", "consumptionSourceVersion": "GptApiClient"}';function I_(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:""}}Te.buildGptDynamicPrompt=I_;async function v7(e,t){var r,n;let i=`/EntityDefinitions(LogicalName='${(0,We.odataPathLiteral)(t)}')${(0,We.odataQuery)([["$select","MetadataId"]])}`;return(n=(r=(0,or.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.MetadataId)!==null&&n!==void 0?n:""}async function y7(e,t,r={}){var n,i,a,o,s;let l=`ais_RowSummary_${t.entityLogicalName}`,u=`/aiskillconfigs${(0,We.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,We.odataLiteral)(l)}'`],["$top",1]])}`,c=((i=(n=(0,or.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,We.odataQuery)([["$select","msdyn_aitemplateid"],["$filter",`msdyn_uniquename eq '${h7}'`],["$top",1]])}`,p=((s=(o=(a=(0,or.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,A_.newId)(),h=(0,A_.newId)(),b=JSON.stringify(I_(t)),w={ModelId:f,RunConfigurationId:h,ModelName:`${t.entityLogicalName} row summary`,TemplateId:p,CustomConfiguration:b,Source:g7,RunConfiguration:""};(0,or.ensureSuccess)(await e.post("/AIModelPublish",w),e.apiUrl("/AIModelPublish"));try{let E=await v7(e,t.entityLogicalName),D={uniquename:l,description:`${t.entityLogicalName} row summary`,"[email protected]":`/entities(${E})`,"[email protected]":`/msdyn_aimodels(${f})`,aiskill:"RowSummary"},L=(0,or.ensureSuccess)(await e.post("/aiskillconfigs",D),e.apiUrl("/aiskillconfigs")),R=(0,or.requireCreatedId)(L,"aiskillconfigid","row-summary skill");return{modelId:f,aiSkillConfigId:R}}catch(E){try{await e.delete(`/msdyn_aimodels(${f})`)}catch{}throw E}}Te.configureRowSummary=y7;async function b7(e,t){var r,n;let i=`ais_RowSummary_${t.entityLogicalName}`,a=`/aiskillconfigs${(0,We.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,We.odataLiteral)(i)}'`],["$top",1]])}`,o=((n=(r=(0,or.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=`/aiskillconfigs(${o.aiskillconfigid})`;if((0,or.ensureSuccess)(await e.delete(s),e.apiUrl(s)),o._aimodel_value){let l=`/msdyn_aimodels(${o._aimodel_value})`;(0,or.ensureSuccess)(await e.delete(l),e.apiUrl(l))}}Te.removeRowSummary=b7});var P_=g(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});Ea.findArtifact=Ea.resolveArtifact=void 0;var pt=Z(),Zr=Ds(),w7=Rs(),A7=he(),C7=le();async function S7(e,t,r){var n,i,a,o,s,l,u,c,d,p,f,h;switch(t){case"app":{let b=(0,w7.unpublishedAppModulesQuery)("appmoduleid,name,appmoduleidunique",`uniquename eq '${(0,pt.odataLiteral)((n=r.uniqueName)!==null&&n!==void 0?n:"")}'`,1),E=(i=(0,A7.ensureSuccess)(await e.get(b),e.apiUrl(b)).body)===null||i===void 0?void 0:i.value,D=E&&E[0];return D?[{id:String(D.appmoduleid),name:String(D.name),appModuleIdUnique:String(D.appmoduleidunique)}]:[]}case"dashboard":return(await(0,Zr.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,pt.odataLiteral)((a=r.name)!==null&&a!==void 0?a:"")}' and type eq 0`,top:10})||[]).map(w=>({id:String(w.formid),name:String(w.name)}));case"command":{let b=await(0,Zr.queryRecords)(e,"appaction",{select:["appactionid","buttonlabeltext"],filter:`contextvalue eq '${(0,pt.odataLiteral)((o=r.entity)!==null&&o!==void 0?o:"")}'`,top:1});return b&&b.length?[{id:String(r.entity),entity:String(r.entity)}]:[]}case"form":return(await(0,Zr.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,pt.odataLiteral)((s=r.name)!==null&&s!==void 0?s:"")}' and objecttypecode eq '${(0,pt.odataLiteral)((l=r.entity)!==null&&l!==void 0?l:"")}'`,top:10})||[]).map(w=>({id:String(w.formid),name:String(w.name)}));case"chart":return(await(0,Zr.queryRecords)(e,"savedqueryvisualization",{select:["savedqueryvisualizationid","name"],filter:`name eq '${(0,pt.odataLiteral)((u=r.name)!==null&&u!==void 0?u:"")}' and primaryentitytypecode eq '${(0,pt.odataLiteral)((c=r.entity)!==null&&c!==void 0?c:"")}'`,top:10})||[]).map(w=>({id:String(w.savedqueryvisualizationid),name:String(w.name)}));case"view":return(await(0,Zr.queryRecords)(e,"savedquery",{select:["savedqueryid","name"],filter:`name eq '${(0,pt.odataLiteral)((d=r.name)!==null&&d!==void 0?d:"")}' and returnedtypecode eq '${(0,pt.odataLiteral)((p=r.entity)!==null&&p!==void 0?p:"")}'`,top:10})||[]).map(w=>({id:String(w.savedqueryid),name:String(w.name)}));case"webResource":return(await(0,Zr.queryRecords)(e,"webresource",{select:["webresourceid","name"],filter:`name eq '${(0,pt.odataLiteral)((f=r.name)!==null&&f!==void 0?f:"")}'`,top:1})||[]).map(w=>({id:String(w.webresourceid),name:String(w.name)}));case"solution":return(await(0,Zr.queryRecords)(e,"solution",{select:["solutionid","uniquename"],filter:`uniquename eq '${(0,pt.odataLiteral)((h=r.uniqueName)!==null&&h!==void 0?h:"")}'`,top:1})||[]).map(w=>({id:String(w.solutionid),name:String(w.uniquename)}));default:return[]}}Ea.resolveArtifact=S7;async function N7(e,t,r){var n,i,a,o,s;let l=(0,pt.odataLiteral)((n=r.name)!==null&&n!==void 0?n:""),u=(0,pt.odataLiteral)((i=r.entity)!==null&&i!==void 0?i:"");if(t==="command"){let h=await(0,Zr.queryRecords)(e,"appaction",{select:["appactionid"],filter:`contextvalue eq '${(0,pt.odataLiteral)((a=r.entity)!==null&&a!==void 0?a:"")}'`,top:1});return h&&h.length?String(r.entity):null}let c=E7(t,l,u,r),d=t!=="app",p=await(0,Zr.queryRecords)(e,c.set,{select:[c.idField],filter:c.filter,top:d?2:1});if(d&&p&&p.length>1)throw new C7.AmbiguousArtifactError(t,(s=(o=r.name)!==null&&o!==void 0?o:r.uniqueName)!==null&&s!==void 0?s:"",p.length);let f=p&&p[0]&&p[0][c.idField];return f!=null?String(f):null}Ea.findArtifact=N7;function E7(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,pt.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 O_=g(zu=>{"use strict";Object.defineProperty(zu,"__esModule",{value:!0});zu.seedRecordGraph=void 0;var T_=Ds(),D7=Ss(),Gu=Z(),I7=le();async function _7(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,D7.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(),h=(a=p.matchOn)===null||a===void 0?void 0:a.toLowerCase(),b=[];for(let V of p.records){let M={...V.body};for(let $ of(o=V.binds)!==null&&o!==void 0?o:[]){let G=$.parentEntity.toLowerCase(),X=(s=d(G))===null||s===void 0?void 0:s[$.parentIndex];if(!X)throw new I7.InvalidArgumentError(`Cannot resolve bind '${$.navProperty}' on a '${f}' record: parent '${$.parentEntity}'[${$.parentIndex}] has no created id. Seed the parent group before the child, or supply it via options.createdIds.`);let U=(0,Gu.assertODataName)(await u(G),`entity set for parent '${$.parentEntity}'`),Oe=(0,Gu.normalizeGuid)(X,`parent id for bind '${$.navProperty}'`);M[`${$.navProperty}@odata.bind`]=`/${U}(${Oe})`}b.push(M)}let w=h?b.map(V=>{let M=V[h];return M!=null&&M!==""?String(M):null}):b.map(()=>null),E=new Map;if(h){let V=(0,Gu.assertODataName)(h,"RecordGraph matchOn key"),M=[...new Set(w.filter($=>$!==null))];if(M.length){let $=M.map(X=>`${V} eq '${(0,Gu.odataLiteral)(X)}'`).join(" or "),G=await(0,T_.queryRecords)(e,f,{select:[V,`${f}id`],filter:$,top:5e3});for(let X of G??[]){let U=X[V];U!=null&&E.set(String(U).toLowerCase(),String(X[`${f}id`]))}}}let D=[],L=new Map,R=b.map((V,M)=>{let $=w[M];if($&&E.has($.toLowerCase()))return null;if($){let G=$.toLowerCase(),X=L.get(G);if(X!==void 0)return X;let U=D.push(V)-1;return L.set(G,U),U}return D.push(V)-1}),B=D.length?await(0,T_.createRecordsBulk)(e,f,D):[];c[f]=b.map((V,M)=>{let $=w[M];return $&&E.has($.toLowerCase())?E.get($.toLowerCase()):B[R[M]]})}return{createdIds:c}}zu.seedRecordGraph=_7});var $_=g(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.getEntityPrivileges=It.deleteSecurityRole=It.createPersonaRole=It.createSecurityRole=It.SDK_ROLE_MARKER=void 0;var Tr=he(),Ye=Z(),Jt=le(),Wu={read:"Read",create:"Create",write:"Write",delete:"Delete",append:"Append",appendTo:"AppendTo",assign:"Assign",share:"Share"},M_={user:"Basic",businessUnit:"Local",parentChild:"Deep",organization:"Global"},x_={user:1,businessUnit:2,parentChild:3,organization:4},Um={user:"CanBeBasic",businessUnit:"CanBeLocal",parentChild:"CanBeDeep",organization:"CanBeGlobal"};It.SDK_ROLE_MARKER="Authored by @maker-studio/cds-maker-sdk (persona/security role).";function P7(e){return Object.prototype.hasOwnProperty.call(Wu,e)?Wu[e]:void 0}function T7(e){return Object.prototype.hasOwnProperty.call(M_,e)}var R_=new WeakMap,L_=new WeakMap;async function U_(e,t){var r,n;(0,Ye.assertODataName)(t,"entity logical name");let i=R_.get(e);i||(i=new Map,R_.set(e,i));let a=i.get(t);if(a)return a;let o=`/EntityDefinitions(LogicalName='${(0,Ye.odataPathLiteral)(t)}')${(0,Ye.odataQuery)([["$select","LogicalName,Privileges"]])}`,l=(n=(r=(0,Tr.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 Jt.InvalidArgumentError(`Entity '${t}' exposes no privileges (unknown or non-securable entity).`);return i.set(t,l),l}async function O7(e){var t,r,n;let i=L_.get(e);if(i)return i;let a=`/businessunits${(0,Ye.odataQuery)([["$select","businessunitid"],["$filter","_parentbusinessunitid_value eq null"],["$top",1]])}`,l=(n=((r=(t=(0,Tr.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 Jt.InvalidArgumentError("Could not resolve the root business unit.");let u=(0,Ye.normalizeGuid)(l,"businessUnitId");return L_.set(e,u),u}async function x7(e,t){var r;let n=new Map;for(let i of t){if(!i.access||i.access.length===0)throw new Jt.InvalidArgumentError(`Entity '${i.entity}' privilege request has no access levels.`);let a=(r=i.scope)!==null&&r!==void 0?r:"user";if(!T7(a))throw new Jt.InvalidArgumentError(`Unknown privilege scope '${a}' for entity '${i.entity}'.`);let o=await U_(e,i.entity);for(let s of i.access){let l=P7(s);if(!l)throw new Jt.InvalidArgumentError(`Unknown access level '${s}' for entity '${i.entity}'.`);let u=o.find(h=>h.PrivilegeType===l);if(!u)throw new Jt.InvalidArgumentError(`Entity '${i.entity}' does not support '${s}' access.`);let c=Um[a];if(u[c]===!1)throw new Jt.InvalidArgumentError(`Privilege '${u.Name}' on '${i.entity}' does not support the '${a}' scope.`);let d=(0,Ye.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 h=[...p.entities].sort().join(", ");throw new Jt.InvalidArgumentError(`Entities '${h}' 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=x_[a]>x_[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 R7(e,t,r,n){if(r.length===0&&!n)return;let i={Privileges:r.map(o=>({Depth:M_[o.scope],PrivilegeId:o.privilegeId}))},a=`/roles(${t})/Microsoft.Dynamics.CRM.ReplacePrivilegesRole`;(0,Tr.ensureSuccess)(await e.post(a,i),e.apiUrl(a))}async function F_(e,t,r,n,i){var a,o;let s=`/${t}(${r})/${n}${(0,Ye.odataQuery)([["$select","roleid"],["$filter",`roleid eq ${i}`]])}`;return((o=(a=(0,Tr.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 L7(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,Ye.normalizeGuid)(l,"teamId");if(!await F_(e,"teams",u,"teamroles_association",t)){let c=`/teams(${u})/teamroles_association/$ref`;(0,Tr.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,Ye.normalizeGuid)(l,"userId");if(!await F_(e,"systemusers",u,"systemuserroles_association",t)){let c=`/systemusers(${u})/systemuserroles_association/$ref`;(0,Tr.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}o.push(u)}return{teams:a,users:o}}async function k_(e,t,r){var n,i;let a=`/roles${(0,Ye.odataQuery)([["$select","roleid,description,ismanaged"],["$filter",`name eq '${(0,Ye.odataLiteral)(t)}' and _businessunitid_value eq ${r}`]])}`,l=((i=(n=(0,Tr.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:"")===It.SDK_ROLE_MARKER};if(l.some(d=>!u(d)))throw new Jt.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 Jt.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,Ye.normalizeGuid)(c,"roleId"):void 0}function F7(e){var t,r;return{teams:((t=e?.teams)!==null&&t!==void 0?t:[]).map(n=>(0,Ye.normalizeGuid)(n,"teamId")),users:((r=e?.users)!==null&&r!==void 0?r:[]).map(n=>(0,Ye.normalizeGuid)(n,"userId"))}}function k7(e){return e.map(t=>({entity:t.entity,privilegeName:t.privilegeName,privilegeType:t.privilegeType,scope:t.scope}))}async function B_(e,t){var r,n;let i=(r=t.name)===null||r===void 0?void 0:r.trim();if(!i)throw new Jt.InvalidArgumentError("createSecurityRole: a non-empty role name is required.");let a=t.businessUnitId?(0,Ye.normalizeGuid)(t.businessUnitId,"businessUnitId"):await O7(e),o=await x7(e,(n=t.privileges)!==null&&n!==void 0?n:[]),s=F7(t.assignTo),l=await k_(e,i,a),u=l!==void 0;if(!l){let d="/roles",p={name:i,description:It.SDK_ROLE_MARKER,"[email protected]":`/businessunits(${a})`};try{let f=(0,Tr.ensureSuccess)(await e.post(d,p),e.apiUrl(d));l=(0,Ye.normalizeGuid)((0,Tr.requireCreatedId)(f,"roleid","role"),"roleId")}catch(f){let h;try{h=await k_(e,i,a)}catch{h=void 0}if(!h)throw f;l=h}}await R7(e,l,o,u);let c=await L7(e,l,s);return{roleId:l,name:i,reused:u,appliedPrivileges:k7(o),assignedTeams:c.teams,assignedUsers:c.users}}It.createSecurityRole=B_;async function M7(e,t){var r,n;let i=(r=t.persona)===null||r===void 0?void 0:r.trim();if(!i)throw new Jt.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 B_(e,{name:i,businessUnitId:t.businessUnitId,privileges:a,assignTo:t.assignTo})}It.createPersonaRole=M7;async function U7(e,t){let n=`/roles(${(0,Ye.normalizeGuid)(t,"roleId")})`;(0,Tr.ensureSuccess)(await e.delete(n),e.apiUrl(n))}It.deleteSecurityRole=U7;var B7=new Map(Object.keys(Wu).map(e=>[Wu[e],e]));async function $7(e,t){return(await U_(e,t)).map(n=>{let i=Object.keys(Um).filter(o=>n[Um[o]]!==!1),a=B7.get(n.PrivilegeType);return{name:n.Name,privilegeId:n.PrivilegeId,privilegeType:n.PrivilegeType,...a?{access:a}:{},scopes:i}})}It.getEntityPrivileges=$7});var G_=g(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.createMakerSdk=Or.MakerSdk=Or.ALREADY_EXISTS_CODE=void 0;var fe=le(),en=ss(),q7=Gm(),q_=jm(),V7=Ym(),G7=vh(),Bm=Ah(),je=Ss(),tn=Ds(),ju=pg(),Da=_s(),z7=Ts(),at=bg(),W7=ld(),j7=b_(),H7=Cn(),Q7=mt(),J7=fi(),xn=w_(),X7=gc(),K7=3e5,rn=he(),Rn=Z(),Ia=__(),V_=P_(),Y7=O_(),Z7=Nf(),Hu=$_();Or.ALREADY_EXISTS_CODE="ARTIFACT_ALREADY_EXISTS";var Ju=class{constructor(t){var r,n;this.artifactLocks=new Map,(0,H7.installDomShim)(),this.languageCode=(r=t.languageCode)!==null&&r!==void 0?r:J7.DEFAULT_LCID,this.cacheStalenessMs=(n=t.cacheStalenessMs)!==null&&n!==void 0?n:K7,this.workspace=new q_.WorkspaceManager(t.workspacePath,t.instanceUrl),this.versions=new V7.VersionManager(this.workspace),this.dataverse=new G7.DataverseClient(t.instanceUrl,t.httpClient,t.solutionUniqueName),this.registrations=(0,j7.buildRegistrations)(this.languageCode)}initWorkspace(){this.workspace.init()}getManifest(){return this.workspace.getManifest()}cleanWorkspace(){this.workspace.clean()}withArtifactLock(t,r,n){var i;let a=`${t}\0${(0,q_.canonicalArtifactId)(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,()=>this.fetchArtifactUnlocked(t,r,n))}async fetchArtifactUnlocked(t,r,n){var i,a;let o=this.requireRegistration(t,"fetchArtifact"),{raw:s,etag:l,memberEtags:u,siblingEtags:c}=await o.api.get(this.dataverse,r),d=o.adapter.fromApiResponse(s);if(!n?.overwrite&&this.versions.isDirty(t,r)){let p=(a=(i=this.versions.getMeta(t,r))===null||i===void 0?void 0:i.etag)!==null&&a!==void 0?a:null;if(p&&l&&p!==l)throw new fe.LocalEditsWouldBeLostError(t,r,p,l);let f=this.workspace.readArtifact(t,r);if(f)return(0,xn.cloneJson)(f)}return this.workspace.writeArtifact(t,r,d),this.versions.storeMeta(t,r,{etag:l,languageCode:this.languageCode,fetchedAt:(0,rn.nowIso)(),snapshot:(0,xn.cloneJson)(d),...u?{memberEtags:u}:{},...c?{siblingEtags:c}:{}}),(0,xn.cloneJson)(d)}async fetchArtifactList(t,r){return this.requireRegistration(t,"fetchArtifactList").api.list(this.dataverse,r)}async fetchSolution(t){var r;let n=await(0,at.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,rn.nowIso)(),isDirty:!1})}catch(s){a.push({componentId:o.objectId,componentType:o.componentType,workflowCategory:o.workflowCategory,reason:"failed",error:Qu(s)})}return this.workspace.updateManifest({lastSyncAt:(0,rn.nowIso)()}),{summaries:i,skipped:a}}async fetchEntityMetadata(t){let r=await(0,Bm.fetchEntityMetadataFromApi)(this.dataverse,t);return this.workspace.writeEntityMetadata(t,r),r}findTables(t,r){return(0,Bm.findTables)(this.dataverse,t,r)}findColumns(t,r,n){return(0,Bm.findColumns)(this.dataverse,t,r,n)}createTable(t){return(0,je.createTable)(this.dataverse,t)}createColumn(t,r){return(0,je.createColumn)(this.dataverse,t,r)}createColumns(t,r){return(0,je.createColumns)(this.dataverse,t,r)}updateColumn(t,r,n){return(0,je.updateColumn)(this.dataverse,t,r,n)}deleteColumn(t,r){return(0,je.deleteColumn)(this.dataverse,t,r)}setColumnVisualization(t,r,n){return(0,je.setColumnVisualization)(this.dataverse,t,r,n)}getColumnVisualization(t,r){return(0,je.getColumnVisualization)(this.dataverse,t,r)}createCustomerColumn(t,r){return(0,je.createCustomerColumn)(this.dataverse,t,r)}insertStatusValue(t,r){return(0,je.insertStatusValue)(this.dataverse,t,r)}updateTable(t,r){return(0,je.updateTable)(this.dataverse,t,r)}async setEntityIcon(t,r){if(await(0,je.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,Rn.xmlText)(t)}</entity></entities></importexportxml>`;(0,rn.ensureSuccess)(await this.dataverse.post("/PublishXml",{ParameterXml:n}),this.dataverse.apiUrl("/PublishXml"))}}createAlternateKey(t,r){return(0,je.createAlternateKey)(this.dataverse,t,r)}deleteAlternateKey(t,r){return(0,je.deleteAlternateKey)(this.dataverse,t,r)}createRelationship(t){return(0,je.createRelationship)(this.dataverse,t)}deleteRelationship(t){return(0,je.deleteRelationship)(this.dataverse,t)}createGlobalOptionSet(t){return(0,je.createGlobalOptionSet)(this.dataverse,t)}deleteGlobalOptionSet(t){return(0,je.deleteGlobalOptionSet)(this.dataverse,t)}deleteTable(t){return(0,je.deleteTable)(this.dataverse,t)}createSecurityRole(t){return(0,Hu.createSecurityRole)(this.dataverse,t)}createPersonaRole(t){return(0,Hu.createPersonaRole)(this.dataverse,t)}deleteSecurityRole(t){return(0,Hu.deleteSecurityRole)(this.dataverse,t)}getEntityPrivileges(t){return(0,Hu.getEntityPrivileges)(this.dataverse,t)}createRecord(t,r){return(0,tn.createRecord)(this.dataverse,t,r)}createRecordsBulk(t,r){return(0,tn.createRecordsBulk)(this.dataverse,t,r)}updateRecord(t,r,n){return(0,tn.updateRecord)(this.dataverse,t,r,n)}upsertRecord(t,r,n){return(0,tn.upsertRecord)(this.dataverse,t,r,n)}deleteRecord(t,r){return(0,tn.deleteRecord)(this.dataverse,t,r)}getRecord(t,r,n){return(0,tn.getRecord)(this.dataverse,t,r,n)}queryRecords(t,r){return(0,tn.queryRecords)(this.dataverse,t,r)}seedRecordGraph(t,r){return(0,Y7.seedRecordGraph)(this.dataverse,t,r)}resolveArtifact(t,r){return(0,V_.resolveArtifact)(this.dataverse,t,r)}findArtifact(t,r){return(0,V_.findArtifact)(this.dataverse,t,r)}async deleteAppCascade(t,r){let n=await(0,W7.deleteAppCascade)(this.dataverse,t,r),i=(0,Rn.normalizeGuid)(t,"appModuleId");return this.workspace.readArtifact("app",i)&&this.workspace.deleteArtifact("app",i),n}associateRecords(t,r,n){return(0,tn.associateRecords)(this.dataverse,t,r,n)}disassociateRecords(t,r,n,i){return(0,tn.disassociateRecords)(this.dataverse,t,r,n,i)}createWebResource(t){return(0,ju.createWebResource)(this.dataverse,t)}updateWebResource(t,r){return(0,ju.updateWebResource)(this.dataverse,t,r)}getWebResource(t){return(0,ju.getWebResource)(this.dataverse,t)}deleteWebResource(t){return(0,ju.deleteWebResource)(this.dataverse,t)}getAppSettings(t){return(0,Da.readAppSettings)(this.dataverse,t)}setAppSetting(t,r,n){return(0,Da.setAppSetting)(this.dataverse,t,r,n)}setHeaderAndNavigationRefresh(t,r){if(typeof r!="boolean")throw new fe.ValidationError("app",t,[{pointer:"/headerAndNavigationRefresh",rule:z7.HEADER_NAV_BOOLEAN_RULE,message:`enabled must be a boolean, got ${typeof r}`}]);return(0,Da.setAppSetting)(this.dataverse,t,Da.HEADER_AND_NAVIGATION_REFRESH,r?Da.APP_SETTING_ON:Da.APP_SETTING_OFF)}getSolution(t){return(0,at.getSolution)(this.dataverse,t)}createPublisher(t){return(0,at.createPublisher)(this.dataverse,t)}createSolution(t){return(0,at.createSolution)(this.dataverse,t)}setSolutionVersion(t,r){return(0,at.setSolutionVersion)(this.dataverse,t,r)}addSolutionComponent(t){return(0,at.addSolutionComponent)(this.dataverse,t)}removeSolutionComponent(t,r,n){return(0,at.removeSolutionComponent)(this.dataverse,t,r,n)}exportSolution(t){return(0,at.exportSolution)(this.dataverse,t)}importSolution(t){return(0,at.importSolution)(this.dataverse,t)}deleteSolution(t){return(0,at.deleteSolution)(this.dataverse,t)}async getArtifact(t,r){return this.withArtifactLock(t,r,()=>this.getArtifactUnlocked(t,r))}async getArtifactUnlocked(t,r){return(0,xn.cloneJson)(await this.readRaw(t,r))}async readRaw(t,r){return await this.revalidateIfStale(t,r),this.readLocal(t,r)}async readForMutation(t,r,n){if(await this.revalidateIfStale(t,r)==="refreshed-changed")throw new fe.StaleArtifactError(t,r,n);return this.readLocal(t,r)}readLocal(t,r){let n=this.workspace.readArtifact(t,r);if(!n)throw new fe.ArtifactNotFoundError(t,r);return n}async revalidateIfStale(t,r){let n=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(this.versions.isDirty(t,r))return"skipped";let o=this.workspace.readArtifact(t,r);await this.fetchArtifactUnlocked(t,r);let s=this.workspace.readArtifact(t,r);return(0,X7.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=en.JsonPointer.resolve(i,n);if(a===void 0)throw new fe.PathNotFoundError(t,r,n);return a})}async findElements(t,r,n){return this.withArtifactLock(t,r,async()=>(0,q7.findElements)(await this.getArtifactUnlocked(t,r),n))}listArtifacts(t,r){return this.workspace.listArtifacts(t,r).map(n=>({...n,isDirty:this.versions.isDirty(n.type,n.id)}))}getEntityMetadata(t){let r=this.workspace.readEntityMetadata(t);if(!r)throw new fe.ArtifactNotFoundError("entityMetadata",t);return r}getFieldMetadata(t,r){let i=this.getEntityMetadata(t).attributes.find(a=>a.logicalName===r);if(!i)throw new fe.PathNotFoundError("entityMetadata",t,r);return i}async updateElement(t,r,n,i){return this.withArtifactLock(t,r,async()=>{let a=await this.readForMutation(t,r,n),o=en.JsonPointer.resolve(a,n);if(o===void 0)throw new fe.PathNotFoundError(t,r,n);let s=Xu(o)&&Xu(i)?{...o,...i}:i;return en.JsonPointer.set(a,n,(0,xn.cloneJson)(s)),this.assertStructurallyValid(t,r,a,n),this.workspace.writeArtifact(t,r,a),this.getArtifactUnlocked(t,r)})}async addElement(t,r,n,i,a){return this.withArtifactLock(t,r,async()=>{let o=await this.readForMutation(t,r,n),s=en.JsonPointer.resolve(o,n);if(s===void 0)throw new fe.PathNotFoundError(t,r,n);if(!Array.isArray(s))throw new fe.ValidationError(t,r,n,"parent must be an array");let l=this.assignMissingIds(t,(0,xn.cloneJson)(i)),u=rz(s,a?.position);return s.splice(u,0,l),this.assertStructurallyValid(t,r,o,n),this.workspace.writeArtifact(t,r,o),this.getArtifactUnlocked(t,r)})}async moveElement(t,r,n,i,a){return this.withArtifactLock(t,r,async()=>{var o;let s=await this.readForMutation(t,r,n),l=en.JsonPointer.resolve(s,n);if(l===void 0)throw new fe.PathNotFoundError(t,r,n);let u=en.JsonPointer.resolve(s,i);if(u===void 0)throw new fe.PathNotFoundError(t,r,i);if(!Array.isArray(u))throw new fe.ValidationError(t,r,i,"move target must be an array");if(i===n||i.startsWith(`${n}/`))throw new fe.ValidationError(t,r,i,"cannot move an element into its own subtree");en.JsonPointer.remove(s,n);let c=(o=a?.index)!==null&&o!==void 0?o:u.length;return u.splice(Math.max(0,Math.min(c,u.length)),0,l),this.assertStructurallyValid(t,r,s,i),this.workspace.writeArtifact(t,r,s),this.getArtifactUnlocked(t,r)})}async removeElement(t,r,n){return this.withArtifactLock(t,r,async()=>{let i=await this.readForMutation(t,r,n);if(en.JsonPointer.resolve(i,n)===void 0)throw new fe.PathNotFoundError(t,r,n);return en.JsonPointer.remove(i,n),this.assertStructurallyValid(t,r,i,tz(n)),this.workspace.writeArtifact(t,r,i),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 fe.ValidationError(t,r,u)}retrieveSetting(t,r){return(0,Ia.retrieveSetting)(this.dataverse,t,r)}saveSettingValue(t,r,n){return(0,Ia.saveSettingValue)(this.dataverse,t,r,n)}getAiReadiness(t){return(0,Ia.getAiReadiness)(this.dataverse,t)}setAppAiFeatures(t,r,n){return(0,Ia.setAppAiFeatures)(this.dataverse,t,r,n)}configureRowSummary(t,r){return(0,Ia.configureRowSummary)(this.dataverse,t,r)}removeRowSummary(t){return(0,Ia.removeRowSummary)(this.dataverse,t)}async enrichDefaultViews(t,r,n={}){let i=await(0,Z7.findDefaultViews)(this.dataverse,t,n);for(let a of i)await this.fetchArtifact("view",a.id),await this.updateElement("view",a.id,"/columns",r),await this.pushArtifact("view",a.id);return i.length&&await this.publishArtifact("view",i[0].id),{updated:i.map(a=>a.id)}}createArtifact(t,r){let n=this.requireRegistration(t,"createArtifact"),i=n.adapter.assignMissingIds(n.adapter.createDefault(r)),a=i.id;if(!a)throw new fe.ValidationError(t,"(new)","/id","created artifact must have an id");return this.workspace.writeArtifact(t,a,i),(0,xn.cloneJson)(i)}deleteArtifact(t,r){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),this.workspace.readArtifact(t,r)&&this.workspace.deleteArtifact(t,r)})}async publishArtifact(t,r,n){return this.withArtifactLock(t,r,()=>this.publishArtifactUnlocked(t,r,n))}async publishArtifactUnlocked(t,r,n){var i;let a=await this.readRaw(t,r),o=this.registrations.get(t);if(!o?.publish)return{type:t,id:r,shipped:!1,publish:{kind:"notApplicable"}};let s=(i=o.publishScope)===null||i===void 0?void 0:i.call(o,r,a);try{await o.publish(this.dataverse,r,a)}catch(u){return{type:t,id:r,shipped:!1,publish:{kind:"failed",error:Qu(u)},...s?{publishScope:s}:{}}}if(!n?.verify)return{type:t,id:r,shipped:!1,publish:{kind:"submitted"},...s?{publishScope:s}:{}};let l=await this.verifyPublished(t,r);return{type:t,id:r,shipped:l.kind==="verified",publish:l,...s?{publishScope:s}:{}}}async verifyPublished(t,r){if(t!=="app")return{kind:"unverifiable",reason:`published-projection verification is not characterised for '${t}'; the publish was submitted`};try{let n=`/appmodules(${(0,Rn.normalizeGuid)(r,"id")})${(0,Rn.odataQuery)([["$select","appmoduleid"]])}`,i=await this.dataverse.get(n);return i.status>=200&&i.status<300?{kind:"verified"}:{kind:"unverifiable",reason:`the published projection answered HTTP ${i.status}`}}catch(n){return{kind:"unverifiable",reason:Qu(n).message}}}async pushArtifact(t,r){return this.withArtifactLock(t,r,()=>this.pushArtifactUnlocked(t,r))}async pushArtifactUnlocked(t,r){var n,i,a,o,s,l;let u=this.requireRegistration(t,"pushArtifact"),c=this.readLocal(t,r),d=this.versions.getMeta(t,r);this.assertLanguageMatches(t,r,d,u);let p=await this.buildMetadataContext(u.adapter,c),f=u.adapter.toApiPayload(c,d?.snapshot,p);try{let h=d?await u.api.update(this.dataverse,r,f,d.etag,d.memberEtags,d.siblingEtags):await this.createWithMintedId(u,t,r,f),b=r;return d||(h.serverIdentity&&u.adapter.applyServerIdentity&&u.adapter.applyServerIdentity(c,h.serverIdentity),h.id&&h.id!==r&&(c.id=h.id,this.workspace.deleteArtifact(t,r),b=h.id),this.workspace.writeArtifact(t,b,c)),this.versions.storeMeta(t,b,{etag:h.etag,languageCode:this.languageCode,fetchedAt:(0,rn.nowIso)(),snapshot:(0,xn.cloneJson)(c),...h.memberEtags?{memberEtags:h.memberEtags}:{},...h.siblingEtags?{siblingEtags:h.siblingEtags}:{}}),{type:t,id:b,saved:!0,shipped:!1,publish:(n=h.publish)!==null&&n!==void 0?n:{kind:"notRequested"},...h.publish&&h.publish.kind!=="notRequested"?(()=>{var w;let E=(w=u.publishScope)===null||w===void 0?void 0:w.call(u,b,c);return E?{publishScope:E}:{}})():{},...h.warnings&&h.warnings.length>0?{warnings:h.warnings}:{}}}catch(h){let b=(0,fe.readPartialTokens)(h);if(b&&d){let w={...(i=d.memberEtags)!==null&&i!==void 0?i:{},...(a=b.memberEtags)!==null&&a!==void 0?a:{}},E={...(o=d.siblingEtags)!==null&&o!==void 0?o:{},...(s=b.siblingEtags)!==null&&s!==void 0?s:{}};this.versions.storeMeta(t,r,{...d,...Object.keys(w).length>0?{memberEtags:w}:{},...Object.keys(E).length>0?{siblingEtags:E}:{}})}if(h instanceof fe.SdkError&&h.code===Or.ALREADY_EXISTS_CODE)return{type:t,id:r,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:h};if(h instanceof fe.SdkError&&h.code===rn.VERSION_CONFLICT_CODE)return{type:t,id:r,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:new fe.VersionConflictError(t,r,(l=d?.etag)!==null&&l!==void 0?l:null,null,h.message)};throw h}}assertLanguageMatches(t,r,n,i){if(i?.languageSensitive&&!(n?.languageCode===void 0||n.languageCode===this.languageCode))throw new fe.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}.`)}async createWithMintedId(t,r,n,i){try{return await t.api.create(this.dataverse,i,n)}catch(a){throw!(a instanceof fe.SdkError)||a.code!==rn.VERSION_CONFLICT_CODE?a:new fe.SdkError(Or.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}') to adopt the existing record's identity, etag and snapshot, then push again \u2014 that push will be a conditional update. 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:[];if(a.length===0)return;let o=new Set(a.map(s=>s.entityLogicalName).filter(s=>!!s));for(let s of o)if(!this.workspace.readEntityMetadata(s))try{await this.fetchEntityMetadata(s)}catch{}return{resolveField:(s,l)=>{let u=this.workspace.readEntityMetadata(s),c=u?.attributes.find(d=>d.logicalName===l);return c?{displayName:c.displayName,attributeType:c.attributeType}:void 0}}}async pushAll(){let t=this.getDirtyArtifacts(),r=[];for(let n of t)try{r.push(await this.pushArtifact(n.type,n.id))}catch(i){r.push({type:n.type,id:n.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:Qu(i)})}return r}getDirtyArtifacts(){return this.workspace.listArtifacts().filter(t=>this.versions.isDirty(t.type,t.id)).map(t=>({...t,isDirty:!0}))}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,Q7.assignMissingIds)(r)}async resolveComponentType(t){switch(t.componentType){case at.SolutionComponentType.SavedQuery:return"view";case at.SolutionComponentType.SavedQueryVisualization:return"chart";case at.SolutionComponentType.AppModule:return"app";case at.SolutionComponentType.UxAgentProject:return"genPage";case at.SolutionComponentType.Workflow:return t.workflowCategory===2?"businessRule":t.workflowCategory===4&&await this.isBusinessFlowWorkflow(t.objectId)?"bpf":void 0;case at.SolutionComponentType.SystemForm:return await this.isDashboardForm(t.objectId)?"dashboard":"form";default:return}}async isDashboardForm(t){let n=`/systemforms(${(0,Rn.normalizeGuid)(t,"formId")})${(0,Rn.odataQuery)([["$select","type"]])}`,i=(0,rn.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,Rn.normalizeGuid)(t,"workflowId")})${(0,Rn.odataQuery)([["$select","businessprocesstype"]])}`,i=(0,rn.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 fe.NotImplementedError(r,`no adapter registered for artifact type '${t}'`);return n}};Or.MakerSdk=Ju;function ez(e){return new Ju(e)}Or.createMakerSdk=ez;function Qu(e){return e instanceof Error?e:new Error(String(e))}function Xu(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function tz(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function rz(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=>Xu(i)&&i.id===t.before);return n<0?e.length:n}let r=e.findIndex(n=>Xu(n)&&n.id===t.after);return r<0?e.length:r+1}});var z_=g(Ku=>{"use strict";Object.defineProperty(Ku,"__esModule",{value:!0});Ku.ARTIFACT_TYPES=void 0;Ku.ARTIFACT_TYPES=["form","view","businessRule","app","command","chart","dashboard","genPage","bpf"]});var j_=g(W_=>{"use strict";Object.defineProperty(W_,"__esModule",{value:!0})});var Q_=g(H_=>{"use strict";Object.defineProperty(H_,"__esModule",{value:!0})});var X_=g(J_=>{"use strict";Object.defineProperty(J_,"__esModule",{value:!0})});var Y_=g(K_=>{"use strict";Object.defineProperty(K_,"__esModule",{value:!0})});var e1=g(Z_=>{"use strict";Object.defineProperty(Z_,"__esModule",{value:!0})});var r1=g(t1=>{"use strict";Object.defineProperty(t1,"__esModule",{value:!0})});var i1=g(n1=>{"use strict";Object.defineProperty(n1,"__esModule",{value:!0})});var o1=g(a1=>{"use strict";Object.defineProperty(a1,"__esModule",{value:!0})});var l1=g(s1=>{"use strict";Object.defineProperty(s1,"__esModule",{value:!0})});var c1=g(u1=>{"use strict";Object.defineProperty(u1,"__esModule",{value:!0})});var p1=g(d1=>{"use strict";Object.defineProperty(d1,"__esModule",{value:!0})});var m1=g(f1=>{"use strict";Object.defineProperty(f1,"__esModule",{value:!0})});var g1=g(h1=>{"use strict";Object.defineProperty(h1,"__esModule",{value:!0})});var y1=g(v1=>{"use strict";Object.defineProperty(v1,"__esModule",{value:!0})});var w1=g(b1=>{"use strict";Object.defineProperty(b1,"__esModule",{value:!0})});var C1=g(A1=>{"use strict";Object.defineProperty(A1,"__esModule",{value:!0})});var N1=g(S1=>{"use strict";Object.defineProperty(S1,"__esModule",{value:!0})});var D1=g(E1=>{"use strict";Object.defineProperty(E1,"__esModule",{value:!0})});var _1=g(I1=>{"use strict";Object.defineProperty(I1,"__esModule",{value:!0})});var nz=exports&&exports.__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]})),Se=exports&&exports.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&nz(t,e,r)};Object.defineProperty(exports,"__esModule",{value:!0});exports.createMakerSdk=void 0;var iz=G_();Object.defineProperty(exports,"createMakerSdk",{enumerable:!0,get:function(){return iz.createMakerSdk}});Se(z_(),exports);Se(j_(),exports);Se(Q_(),exports);Se(X_(),exports);Se(Y_(),exports);Se(e1(),exports);Se(r1(),exports);Se(i1(),exports);Se(o1(),exports);Se(l1(),exports);Se(c1(),exports);Se(p1(),exports);Se(m1(),exports);Se(Ts(),exports);Se(g1(),exports);Se(y1(),exports);Se(w1(),exports);Se(C1(),exports);Se(N1(),exports);Se(D1(),exports);Se(_1(),exports);Se(le(),exports);diff --git a/plugins/model-apps/scripts/verify-model-app.js b/plugins/model-apps/scripts/verify-model-app.jsindex a0ce490dd..1b5445434 100644--- a/plugins/model-apps/scripts/verify-model-app.js+++ b/plugins/model-apps/scripts/verify-model-app.js@@ -73,6 +73,10 @@ function readerFor(sdk, appUnique, opts) {const base = {findTable: async (logical) => { const l = String(logical).toLowerCase(); const t = await sdk.findTables(l); return (t || []).find((x) => String(x.logicalName).toLowerCase() === l) || null; },findColumns: async (logical) => sdk.findColumns(logical),+ // Grid data visualization (preview) for one column. Passed straight through — including the raw+ // 404 the SDK emits on an environment where the preview is not provisioned, which verify-spec+ // interprets (it must stay distinguishable from the legitimate 'None' answer).+ columnVisualization: async (logical, columnLogical) => sdk.getColumnVisualization(String(logical).toLowerCase(), String(columnLogical).toLowerCase()),queryRecords: (set, o) => sdk.queryRecords(set, o),// entityRelationships(childLogical): the relationship SCHEMA NAMES defined on a child entity, for the// content-verify relationship-existence check. Best-effort — a metadata read failure yields [] so thediff --git a/plugins/model-apps/skills/app-builder/SKILL.md b/plugins/model-apps/skills/app-builder/SKILL.mdindex c8a5972b6..8860a31cf 100644--- a/plugins/model-apps/skills/app-builder/SKILL.md+++ b/plugins/model-apps/skills/app-builder/SKILL.md@@ -52,10 +52,33 @@ prod-ready** app; don't under-build (a bare table list) or over-build (surfaces- **Data model** — tables (give each custom table a **meaningful Fluent-style SVG table icon by default**; propose what the glyph will **depict** in words — never a Fluent token name — and record it as `iconDescription` before drawing the SVG — see [`references/authoring-flow.md`](../../references/authoring-flow.md) → *Table icons*), columns (all types), relationships (1:N / N:N + junctions), sample data- **Record UI** — forms (sub-grids, quick-create / quick-view), views (with enriched default columns), charts-- **Actions** — modern command-bar buttons (incl. flyout / split menus), web resources (form JS / HTML / CSS)+- **Custom grid rendering** (preview) — `entities[].columns[].visualization`: render a column as a+ `RadialDial`, `LineChart`, `HeatMap` or `StarRating` in **every** grid and view that shows it,+ instead of plain text. Reach for it when a column is a *magnitude a user scans* (a score, a+ utilization %, a rating, a priority) rather than a value they read exactly — it makes a list+ scannable at a glance for one line of spec. It is per-*column*, so set it once on the column, not+ on each view. **Preview:** on an environment where it is not provisioned the build skips it and+ everything else still deploys, so it is always safe to include.+- **Actions** — modern command-bar buttons (incl. flyout / split menus), web resources (form JS / HTML / CSS).+ Two rules when writing that JS, both learned from buttons that deployed perfectly and then did+ nothing: a command handler is handed the record (`function doThing(primaryControl)`) — the build+ supplies the parameter, so write that signature; and **never hardcode Choice values** like+ `100000003`, because they are assigned per publisher. Resolve by label via `getOptions()`+ (see `references/app-spec-schema.md` → webResources). Note also that command and web-resource+ **edits do not redeploy on rebuild** — the phases reuse what exists, so changing a button or a+ script means deleting it first.+- **Form logic without code** — `businessRules[]`: show/hide, lock/unlock, set-required and+ set-value, driven by a condition on the record. **Reach for a business rule before form JS** when+ the requirement is field-level and declarative — it is visible in the maker, survives solution+ export, and needs no web resource. Use form JS when the logic needs a real API call, cross-record+ work, or anything beyond the four supported actions.- **Surfaces** — **generative pages** (modern dashboards / overviews / analytics / landing — the default),classic dashboards (opt-in), external URLs-- **App shell** — the app module + sitemap, with per-subarea icons+- **App shell** — the app module + sitemap, with per-subarea icons. Turn on the **modern shell** with+ `app.newLook: true` unless the user asks for the classic one; it is opt-in and best-effort, so a+ tenant without the setting still gets a working app. `app.headerNavigationRefresh` controls the+ **Wave 2 header/navigation refresh** — a *separate, independent* setting whose platform default is+ **ON**, so set it to `false` only when the user explicitly wants the classic header.- **Security & access** — one **security role per persona**, sized from that persona's jobs-to-be-done(the entity access each job needs, unioned into the role), so the app **opens for non-admins**.- **AI-first features** (admin-gated) — form-fill assist, natural-language grid/view search, NL chart@@ -92,6 +115,13 @@ Rules:- **Every page in `pages[]` must be sitemap-placed** — validation rejects any page absent from thesitemap. A "detail" page that receives a caller-supplied id is a normal sitemap page; it reads itsinput via `pageInput?.data?.<field>`. Navigation-only (headless) pages are not supported.+- **A page that declares `pageInput` MUST declare `directEntry`.** Because every page is+ sitemap-placed, a detail page is also reachable straight from the app navigation with **no input**+ — a state a user reaches by clicking. Say what happens then: `{ "behavior": "selector" }` shows a+ picker and then the record, `{ "behavior": "emptyState" }` explains and renders nothing broken.+ Prefer `selector` when the table is browsable; it is the more useful landing. Every key in+ `pageInput.data` must also be produced by some page's `navigatesTo[].data`, or the generated page+ reads a key nothing ever sets.- **Three-authority page identity** (build + download + verify all follow this): (1) **IDENTITY** —the durable `<app>_pagemanifest` (`key → pageId`); a downloaded spec's own `pages[].pageId`outranks it for that rebuild. (2) **EXISTENCE** — env-wide `pac model genpage list` (crash-safe;@@ -288,12 +318,22 @@ their phase ranges are not dependency-closed and are rejected on `--apply`.Data-model labels arestamped with the organization's own base language, read once per build. Pass it only to authorlabels in a different **provisioned** language, or if the build warns that it could not determine-the base language and fell back to 1033. If a build fails with *"The language code N is not a valid-language for this organization"*, that is this setting — re-run with `--language-code <an LCID the-org actually has>`, listing them with+the base language and fell back to 1033.++If you pass an LCID the organization has **not** provisioned, the build now stops in the data-model+phase, before any label is written, and lists the ones it does have. That check exists because+Dataverse handles this **inconsistently**: table and choice labels are accepted (HTTP 204) and+silently stored under the organization's base language, while `DateTime` and `Memo` columns are+rejected with *"The language code N is not a valid language for this organization"*. Without the+check a build therefore creates the table with the wrong labels and then dies partway through the+columns, phases away from the flag that caused it — which reads like an environment fault. List the+provisioned set with`node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET RetrieveProvisionedLanguages`.-The App Spec field `languageCode` pins the same value across runs. Note this covers the data-model-phase only; form and sitemap labels still carry 1033 (SDK limitation, issue #455).+The check is best-effort: if that read fails the build proceeds unchanged.++The App Spec field `languageCode` pins the same value across runs. It now covers the **whole** build:+data-model labels, and form, dashboard and sitemap labels — the SDK serializers that used to hardcode+1033 take the authoring language as an option ([#455](https://github.com/microsoft/power-platform-skills/issues/455)).Narrate progress as it runs. Transient env errors (429 customization-lock, 503 SQL-timeout,concurrent-op guards) are **auto-retried** with backoff on `--apply` (the build is idempotent, so a@@ -465,6 +505,8 @@ solution (idempotent) → data model — **discover** existing tables/columns/re`createWebResource` for form JS/HTML/CSS) → **views** → **charts** → **forms** (primary + columnslaid out, explicit `tabs` honored; sub-grids, quick-views, and form JS (`events[]`) applied ascanonical control cells / the `/bag/c` events region via the SDK's generic `addElement` surface)+→ **business rules** (`businessRules[]`; compiled to classic workflow XAML and activated) →+**command bar** (`commands[]`) → **classic dashboards** (opt-in)→ **app module + sitemap** → **generative pages** (each page's `.tsx` was generated in Phase 1.5;the build uploads each `pages[]` page via `pac model genpage upload`, no `--add-to-sitemap`; thenthe SDK rewrites the sitemap once to add the `GenPage` subareas) → **AI features** (opt-in) →@@ -498,7 +540,7 @@ child view id. Each step emits `[n/total]`.apply a structural edit, `teardown --apply` then rebuild fresh.** `--verify` catches this: itchecks **content** (a view's column set, relationship + command existence), so an unapplied editsurfaces as a loud `verify FAIL`, not a false pass. Full in-place convergence is tracked in- `docs/app-builder-roadmap.md`.+ `docs/app-builder-capabilities.md`.- Not in scope (later): business rules, **conditional** command visibility (Power-Fx-only), **titledcommand groups** (from-scratch — needs an SDK-synthesized parent row), lookup/associated views,multi-area sitemaps, **column-level (field) security**, **access teams / hierarchy security** (the@@ -513,7 +555,8 @@ child view id. Each step emits `[n/total]`.`pac model genpage upload` and surfaced as `GenPage` sitemap subareas; full **create + edit**round-trip via `download-model-app.js`); **modern command-bar buttons** (`commands[]`) incl.**flyout / split-button menus**; **rich view filters** (`eq-userid`/`this-week`/`in`/`not-in`);- web resources + form JS event handlers; sample data with **multi-parent `$parents`** +- **`statusReason`**. See [`docs/app-builder-roadmap.md`](../../docs/app-builder-roadmap.md) and+ **custom grid rendering** (`entities[].columns[].visualization` — radial dial / line chart /+ heat map / star rating, preview); web resources + form JS event handlers; sample data with+ **multi-parent `$parents`** + **`statusReason`**. See [`docs/app-builder-capabilities.md`](../../docs/app-builder-capabilities.md) and[`references/app-spec-schema.md`](../../references/app-spec-schema.md) — author from that **single**doc; you should not need to read the SDK, lint, or engine to write a spec.