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
model-apps: SDK uptake + bugs triaged — per-field form control, RequiredLevel reconcile, description read-back (2.5.1) (#491)
Akshay Maloo9de213bc33ab
diff --git a/plugins/model-apps/.claude-plugin/plugin.json b/plugins/model-apps/.claude-plugin/plugin.jsonindex 315fb7ff7..413dd8d76 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.5.0",+ "version": "2.5.1","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 315fb7ff7..413dd8d76 100644--- a/plugins/model-apps/.plugin/plugin.json+++ b/plugins/model-apps/.plugin/plugin.json@@ -1,6 +1,6 @@{"name": "model-apps",- "version": "2.5.0",+ "version": "2.5.1","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/CHANGELOG.md b/plugins/model-apps/CHANGELOG.mdindex 831c0c36b..7a26307c7 100644--- a/plugins/model-apps/CHANGELOG.md+++ b/plugins/model-apps/CHANGELOG.md@@ -5,7 +5,78 @@ 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+## [Unreleased] — 2.5.1++SDK uptake. Adds per-form security roles and three column capabilities; **business rules now require+an environment that supports them**.++### Changed++- **Business rules are environment-gated.** The SDK writes a rule only through the bound+ `CreateProcessWithWfomJson` member; the workflow-XAML fallback was removed upstream because it+ silently narrowed a rule into something you did not write. An environment that does not declare+ that member **cannot host business rules at all** — the common case, not an edge case. Such rules+ are **skipped** with a warning; everything else builds normally, and `--verify` reports them as+ *not applicable on this environment* rather than failing the build.++### Added++- **Per-form security roles** — `forms[].securityRoles`: offer a form to named `personas[]` or to+ `everyone`. A form with no assignment is visible to **every** role, so this *restricts* a form;+ undo with `everyone: true`, not by deleting the block. Takes effect after a publish. (AB#6648526)+- **Boolean `defaultValue`, whole-number `integerFormat`, and per-column `isValidForCreate` /+ `isValidForUpdate` / `isValidForRead`** — the last of these is how you make a column read-only.+ ([#495], AB#6648523, AB#6648522, AB#6651276)+- **Twelve more business-rule operators** and **multi-condition rules** (ANDed). Spelling matters:+ `IsGreaterThan`, not `GreaterThan` — the SDK resolves an unknown operator to `Equals`, so the spec+ rejects anything outside its table and suggests the right spelling.+- **A `description` on every artifact that accepts one.** Written at create time and omitted when+ absent, so a rebuild never blanks text typed in the maker.+- **Per-field form control** — `readOnly`, `hidden` and `after` (reposition), via a form-level+ `fieldOptions` map or inline on an explicit layout. `prune: false` edits a subset of a form without+ re-declaring every field, and only the enabled state is written, so a designer edit survives.+- **The AI form-fill family is controllable per capability** — assist toolbar, edit-form predictions,+ smart paste and file upload, instead of one flag that only governed the toolbar.++### Fixed++- **Dashboards survive a download again** — the SDK could not deserialize a dashboard it had+ serialized, so no tiles were recovered and the download failed without `--allow-lossy-download`.+ ([#478])+- **Descriptions converge on existing views and charts** — previously written only at create, so the+ platform's auto-created *"Active <Plural>"* view never got one. ([#496])+- **Downloaded specs preserve deployed descriptions** where the artifact is reconstructed, and list+ the rest in a read-only inventory. ([#494])+- **Teardown removes the activated copy of a business rule**, which previously stranded an+ undeletable row. ([#493])+- **Existing columns honour an explicit `required` change on rebuild**; an omitted `required` still+ leaves the live column alone.+- **Big Integer columns are no longer placed on auto-generated forms** — Big Integer has no Unified+ Interface control, so the field rendered *"Error loading control"* on every record.+- **AI on/off is read with the platform's semantics** — `0` = platform default, `1` = disabled,+ `2` = enabled. Treating any non-zero value as "on" reported a disabled feature as enabled.+- **Presence operators** (`ContainsData` / `DoesNotContainData`) deploy; the compiler bug behind the+ `HTTP 500 — Error generating UiData` failures is gone with the compiler. ([#481])+- **The async-surface guard is AST-based** — a regex could not decide the remaining cases. ([#475])+- **`ai.summaries.default: "off"` no longer discards a per-table `enabled: true`**, and a+ differently-cased `tables[]` key keeps its `instruction` and `columns`.+- **A row summary an environment cannot license is skipped, not fatal** — and the AI model row the+ refused publish leaves behind is swept, so a rebuild does not then fail on a duplicate key.+- **A spec with no `appShell` reports what to add** instead of dying with+ `Cannot read properties of undefined (reading 'areas')` after the app was already half-created.+- **A malformed `businessRules` is a validation error**, not a raw `TypeError`; duplicate-cleanup+ warnings report the real failure instead of asserting a wedged platform row.+- **Column visualizations are cleared on teardown for a table the spec keeps** (`existing: true`).++[#475]: https://github.com/microsoft/power-platform-skills/issues/475+[#478]: https://github.com/microsoft/power-platform-skills/issues/478+[#481]: https://github.com/microsoft/power-platform-skills/issues/481+[#493]: https://github.com/microsoft/power-platform-skills/issues/493+[#494]: https://github.com/microsoft/power-platform-skills/issues/494+[#495]: https://github.com/microsoft/power-platform-skills/issues/495+[#496]: https://github.com/microsoft/power-platform-skills/issues/496++## [2.5.0]Takes up the current maker SDK, adds modern-shell and navigation controls, labels Dataversemetadata in the organization's own language instead of a hardcoded 1033, makes persona rolesdiff --git a/plugins/model-apps/docs/app-builder-capabilities.md b/plugins/model-apps/docs/app-builder-capabilities.mdindex aa6d9df6d..c59096d1c 100644--- a/plugins/model-apps/docs/app-builder-capabilities.md+++ b/plugins/model-apps/docs/app-builder-capabilities.md@@ -30,17 +30,48 @@ apart deliberately.- 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**.+- ⚠ Calculated / Rollup formula columns — `source` + `formula` plumbed through, **not live-verified**.+- **Per-column write permissions** (`isValidForCreate` / `isValidForUpdate` / `isValidForRead`) —+ this is how a column is made read-only. Applied on create **and** reconciled on rebuild, and each+ flag is sent independently so setting one does not disturb the others. Live-verified by reading the+ deployed metadata back: `IsValidForUpdate: false` with Create/Read untouched at `true`, and+ unchanged through a download → rebuild round trip (an omitted setting means *leave alone*, never+ *reset*). Not available on `Customer` columns — the SDK has no update path for that type at all.+ (AB#6651276)+- **Boolean `defaultValue`** — which option a Yes/No column starts on; the SDK previously hardcoded+ `false`. An explicit `false` is preserved rather than treated as absent. Live-verified.+ (AB#6648523)+- **Whole-number `integerFormat`** — `None` · `Duration` · `TimeZone` · `Language` · `Locale`; the+ SDK previously hardcoded `None`, so a column holding minutes could not render as a duration.+ Live-verified as `Duration`. (AB#6648522)- **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+### Business rules — ⚠️ environment-gated- `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.+ (`LockUnlock`), set-required (`SetBusinessRequired`) and set-value (`SetFieldValue`), gated on one+ or more conditions over the record (ANDed). Sixteen operators, taken from the SDK's own table:+ `Equals` · `DoesNotEqual` · `IsGreaterThan` · `IsGreaterThanEqualTo` · `IsLessThan` ·+ `IsLessThanEqualTo` · `Contains` · `DoesNotContain` · `BeginsWith` · `DoesNotBeginWith` ·+ `EndsWith` · `DoesNotEndWith` · `On` · `NotOn` · `ContainsData` · `DoesNotContainData`.+- **The SDK writes a rule through the bound `CreateProcessWithWfomJson` member, or not at all.** The+ client-side workflow-XAML compiler it used to fall back on was removed upstream, because it covered+ 4 of the 7 action types and a single clause and therefore silently narrowed a rule into something+ that did not say what the author wrote. An environment that does not declare that member **cannot+ host business rules** — and that is the common case rather than an edge case. Where the member is+ declared, a rule can still fail with a server-side MissingMethodException, which is a platform+ defect on that environment rather than a rule-shape problem. The build then skips them,+ warns once naming the member, and builds everything else normally; `--verify` reports them as *not+ applicable on this environment* rather than missing, so the exit code, the deployed baseline and+ the `--changed-only` snapshot are unaffected.+- The operator allowlist is load-bearing rather than cosmetic: the SDK resolves an operator it does+ not recognise to **Equals**, so `GreaterThan` (the natural misspelling of `IsGreaterThan`) would+ deploy, activate and quietly test equality. The spec pins the list against the bundle's own table+ in both directions.+- `dataType` is currently **decorative** — measured across every accepted token, on both the+ condition and the action path, the SDK types every literal as `String`. It is still validated as a+ closed set so a typo is caught.+- 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 thedefinition (`type 1`, no parent) and an activated copy (`type 2`, parented to it). Live-measured: a@@ -48,12 +79,24 @@ apart deliberately.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 duplicatethat 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.+- Live-verified end to end through the App Spec on an environment that supports it: 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[]`).+- Quick-create + quick-view forms (`forms[].formType`); quick-view **placement** on a host form via a lookup (`forms[].quickViews[]`).+- **Per-form security roles** (`forms[].securityRoles`) — offer a form to named `personas[]`, or to+ `everyone`, with optional `fallbackForm` and `order`. The roles are **not** a relationship+ (`systemform` reports `CanBeInManyToMany: { Value: false, CanBeChanged: false }` and there is no+ `systemformrole` entity, so no association shape can ever work); they live inside `formxml` as a+ `<DisplayConditions>` element. Note the direction: a form with **no** assignment is offered to+ **every** role, so this **restricts** a form rather than granting it — and removing a restriction+ is an explicit `everyone: true`, not deleting the block. Applied in the **security** phase, because+ the persona's role does not exist until then, and the write lands on the **unpublished** layer, so+ it takes effect after a publish. Live-verified: the persona's real role id inside+ `<DisplayConditions Order="2">` on the restricted form, `<Everyone />` on its unrestricted sibling.+ (AB#6648526)- 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.@@ -124,12 +167,12 @@ apart deliberately.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.+- `download-model-app.js` pulls a **deployed app** back into an editable App Spec (+ page code, icons, referenced entities, and the app's **real unmanaged solution** — `recoverAppSolution` enumerates the app's solution memberships and excludes the built-in `Active`/`Default`/`Basic` system solutions, so the spec names the right container for a later clean teardown); edit the spec and re-run the idempotent build — **create and edit share one path** (reuses app/tables, updates pages in place, keeps `GenPage` subareas). The app-shell phase **re-syncs the sitemap + components of any existing app** (fetch → recompute-from-spec → push → publish), so subarea add/rename/reorder edits land for **page-less apps too** — not just generative-page apps — and `--only app-shell` can force the rewrite. **Classic DashBoard subareas are *designed* to round-trip** — the dashboard is reconstructed into `dashboards[]` with **id-passthrough tiles** (each tile carries the deployed view/chart ids), so a rebuild recreates it against the existing views/charts without re-declaring them. **This now works end to end.** It previously did not: the vendored SDK’s `fetchArtifact(‘dashboard’, …)` threw `Cannot read properties of null (reading ‘length’)` while deserializing the `<parameters>` block it had itself serialized, so no tiles were recovered and the subarea was dropped — which failed the whole download unless `--allow-lossy-download` was passed. Root cause upstream: the grammar walk descended into **text** nodes, and the bundled XML parser returns `null` for a text node’s children. Fixed in the SDK and re-vendored; measured across the re-vendor as **0/4 → 4/4** round-trips (list tile, both chart-parameter spellings, and a tile with an empty parameter value), and pinned by `scripts/tests/dashboard-roundtrip.test.js`, which feeds a serialized dashboard straight back in. ([#478](https://github.com/microsoft/power-platform-skills/issues/478)) **Round-trip scope (not yet "complete"):** tables, sitemap/appShell, generative pages, icons, dashboards, and solution round-trip; **forms, views, charts, and commands do NOT yet** — view hydration was tried and reverted (LIVE-verified the deployed savedquery set can't reliably distinguish author views from Dataverse's auto-generated Active/Inactive/QuickFind system views). All survive on the live app (a rebuild preserves them by discovery) but are absent from the downloaded spec, so edit them in Maker or a fresh spec.- 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).+- `teardown-model-app.js` deletes exactly what an App Spec declares, in dependency-safe order (app → dashboards → commands → forms → **security roles** → 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 livediff --git a/plugins/model-apps/references/app-spec-schema.md b/plugins/model-apps/references/app-spec-schema.mdindex 630e15069..fbb19c7b6 100644--- a/plugins/model-apps/references/app-spec-schema.md+++ b/plugins/model-apps/references/app-spec-schema.md@@ -130,6 +130,59 @@ sample data (incl. multi-parent junction links + status reasons), and publish.pin is not silently lost — losing it would leave newly created columns in the org default whilethe existing ones keep the pinned language, with no error anywhere.+## `description` — write one on everything that takes one++`description` is optional on every artifact below and **recommended on all of them**. It is written+to Dataverse **at create time**, so it costs nothing extra and needs no backfill pass.++| Accepts `description` | Notes |+|---|---|+| `entities[]` · `entities[].columns[]` | The highest-value ones — table and column names are cryptic (`new_col3`) without them |+| `views[]` · `charts[]` · `forms[]` · `dashboards[]` | What the artifact is *for*, not what it contains |+| `businessRules[]` | Why the rule exists — the logic itself is already visible |+| `solution` · `globalChoices[]` · `webResources[]` · `app.description` | |++**Accepted by the spec but NOT written to Dataverse** (you get a build **warning**, never silent+loss) — the vendored SDK's create surface has nowhere to put them:+- **`commands[]`** — `createArtifact('command', …)` drops the field.+- **`Customer` columns** — `createCustomerColumn`'s payload is only `{ Lookup, OneToManyRelationships }`.++**Not accepted at all, deliberately:** **`personas[]`**. The SDK stamps its own ownership marker into+a security role's `description` and then requires an *exact* match on it before it will touch that+role, so a custom description would make the SDK disown the role it created and refuse to update it.++**Why it matters beyond tidiness.** A description is the only durable, machine-readable statement of+*intent* an app carries. Names say what a thing is called; descriptions say what it is for. When an+agent later inspects an app it did not build — to extend it, debug it, or answer a question about it+— descriptions are the grounding it has. Write them for that reader.++Good: `"Severity 1-5; drives the escalation rule and the SLA clock."`+Weak: `"The priority column."` (restates the name and adds nothing)++**Rules:** must be a non-empty string, max 2000 characters (the Dataverse ceiling — the platform+truncates silently past it, so it is rejected at author time instead). Omit the field entirely rather+than setting `""`; every write site omits an absent description, so **a rebuild never blanks one a+maker typed in the UI**.++**Download/read-back:** `download-model-app` preserves descriptions on artifacts it can already+reconstruct as rebuildable spec (`solution`, `entities[]`, `entities[].columns[]`, `dashboards[]`).+Views, charts, forms, business rules and global choices are not fully reconstructed yet, so their+deployed descriptions are exposed under `descriptionInventory` for inspection only rather than as+partial rebuildable artifacts. Null or absent Dataverse descriptions are omitted, never written as+`""`.++**Rebuild behaviour:** a description is written at CREATE, and is additionally **reconciled on an+artifact that already exists** for **views and charts** — so authoring one on a table whose+Dataverse-generated *"Active <Plural>"* view the build reconciles onto still lands. Those two+write only when the spec **explicitly sets** a description **and** it differs from the deployed+value, so an ordinary rebuild issues no extra write and an omitted description never blanks text a+maker typed in the UI.++Everything else is **create-only** — the description reaches Dataverse when the artifact is first+created and is not revisited: tables, columns, the solution, global choices, `webResources[]`,+`app.description`, forms, dashboards and business rules. Adding a description to one of those *after*+it exists is accepted by validation, builds green, and does not change the deployed artifact.+## entities[]```jsonc{@@ -173,15 +226,24 @@ sample data (incl. multi-parent junction links + status reasons), and publish.// The build reuses it; teardown NEVER deletes it. System// tables are auto-detected and skipped by teardown even// without this flag — set it for a REUSED CUSTOM table- // you want protected from teardown.+ // you want protected from teardown. ALSO skips+ // default-view enrichment (which replaces a view's+ // column set) — override with enrichDefaultViews: true.+ "description": "A customer support ticket, from intake through resolution.",+ // RECOMMENDED — see "description" below. Written to+ // Dataverse at create time; the grounding an agent reads+ // when it later inspects an app it did not build."primaryAttribute": { "schemaName": "new_subject", "displayName": "Subject" },// primary can be auto-numbered (the number IS the record identity — recommended for orders/cases):// "primaryAttribute": { "schemaName": "new_ordernumber", "displayName": "Order Number", "autoNumberFormat": "WO-{SEQNUM:5}" },"columns": [- { "schemaName": "new_priority", "displayName": "Priority", "type": "Choice", "options": ["Low","High"] },+ { "schemaName": "new_priority", "displayName": "Priority", "type": "Choice", "options": ["Low","High"],+ "description": "How urgently the ticket needs attention." }, // RECOMMENDED — see below{ "schemaName": "new_duedate", "displayName": "Due Date", "type": "DateTime" },{ "schemaName": "new_score", "displayName": "Score", "type": "Integer",- "visualization": "RadialDial" } // optional — CUSTOM GRID RENDERING (preview), below+ "visualization": "RadialDial" }, // optional — CUSTOM GRID RENDERING (preview), below+ { "schemaName": "new_externalref", "displayName": "External Reference", "type": "Text",+ "isValidForUpdate": false } // optional — WRITE-ONCE after creation, below]}```@@ -190,9 +252,34 @@ sample data (incl. multi-parent junction links + status reasons), and publish.**Lookups are NOT columns** — declare a `OneToMany` relationship instead.- **Per-type options** (all optional): `required: true` / `"recommended"`; Text → `maxLength`,`format` (`Text`/`Email`/`Url`/`Phone`); numeric → `minValue`/`maxValue`/`precision`;- DateTime → `dateFormat` (`DateOnly`/`DateAndTime`); Boolean → `trueLabel`/`falseLabel`;- File/Image → `maxSizeKb`, Image → `isPrimaryImage`; AutoNumber → `autoNumberFormat`- (e.g. `"C-{SEQNUM:5}"`); Calculated/Rollup → `source: "Calculated"|"Rollup"` + `formula`.+ Integer → also `integerFormat` (`None`/`Duration`/`TimeZone`/`Language`/`Locale` — e.g. render a+ raw minute count as a Duration picker instead of a plain number); DateTime → `dateFormat`+ (`DateOnly`/`DateAndTime`); Boolean → `trueLabel`/`falseLabel`/`defaultValue` (explicit `true` or+ `false` — see note below); File/Image → `maxSizeKb`, Image → `isPrimaryImage`; AutoNumber →+ `autoNumberFormat` (e.g. `"C-{SEQNUM:5}"`); Calculated/Rollup → `source: "Calculated"|"Rollup"` ++ `formula`.+- **Write permissions** (optional, every column type **except Customer**): `isValidForCreate` /+ `isValidForUpdate` / `isValidForRead` — see `isValidForCreate / isValidForUpdate /+ isValidForRead` below.+- **`defaultValue` and `integerFormat` are boolean-typed / enum-typed spec-gate checks, not+ free-form.** `defaultValue` must be a literal `true`/`false` and only applies to a `Boolean`+ column; `integerFormat` must be one of the five literals above and only applies to an `Integer`+ column (not `BigInt`/`Decimal`/`Double`/`Money`, even though they share the same numeric+ `minValue`/`maxValue`/`precision` options) — either mismatch is rejected by name at validation+ time rather than surfacing as a mid-build SDK error.+- **`required` converges on rebuild only when authored explicitly.** For a new column, `true` creates+ Dataverse `ApplicationRequired` and `"recommended"` creates `Recommended`. For a column that+ already exists (including the primary/name column), a rebuild first reads its current+ `RequiredLevel` and only writes when the explicit spec value differs. If `required` is omitted,+ the build leaves the existing column alone instead of treating omission as `None`, so it never+ silently demotes a field a maker already made Business Required.+- **`defaultValue`, `integerFormat`, and `isValidFor*` converge differently: by re-assertion, not+ by diff.** Unlike `required` above, a rebuild does not read the column's current state first —+ it simply re-sends whichever of these fields the spec sets explicitly, on every build, for both a+ brand-new column and one that already exists. This is safe because re-sending an already-correct+ value is a no-op on the wire; it does mean (unlike `required`) there is no "leave it alone if+ omitted" behavior to rely on for a value set by hand in the portal — omit the field entirely to+ leave portal-set state untouched, exactly as for `visualization` below.- **Choice / MultiChoice** need `options[]` (string labels) **or** a `globalChoice` reference(see `globalChoices` below). **Customer** is a polymorphic account/contact lookup.- **AutoNumber** can also be the **primary** column — put `autoNumberFormat` on `primaryAttribute`@@ -226,6 +313,36 @@ on each `views[]` entry.only 1 of 18 test environments. If a renderer does not appear, check the environment first — thesame spec succeeds unchanged on a provisioned org.+### `isValidForCreate` / `isValidForUpdate` / `isValidForRead` — per-verb write/read permissions (optional)++Governs which API verbs Dataverse allows against the column, independent of the table-level+security a `personas[]` role grants. The common case is **write-once**: a column that should be+populated at creation (an external system id, an intake source) and never touched again —+`"isValidForUpdate": false` blocks every later write, whether from a form, a flow, or the API,+without needing a business rule or a plug-in to enforce it.++```jsonc+{ "schemaName": "new_externalref", "displayName": "External Reference", "type": "Text",+ "isValidForUpdate": false }+```++- **All three are independently optional booleans** — set only the ones you mean to constrain.+ Omitting all three leaves the column at the Dataverse default (valid for create, update, AND+ read).+- **`false` is the entire point of the feature, and is honoured exactly like `true`.** The spec+ validation and the build both use an explicit-value check (`!== undefined`), never a truthy+ check, specifically so `isValidForUpdate: false` is never silently dropped the way a naive+ `if (value)` guard would drop it.+- **Every buildable column type accepts these EXCEPT Customer.** A `Customer` column is created+ through a separate Dataverse API path (a polymorphic account/contact lookup) that carries no+ such option. Setting any of the three on a Customer column does not fail the build — it+ **warns** and the flag is silently not written, the same treatment `description` gets on a+ Customer column elsewhere in this doc.+- **Rebuild-safe, by re-assertion (see the reconcile note above).** Whichever of the three fields+ the spec sets explicitly is re-sent on every build for an existing column, not just a newly+ created one — so tightening `isValidForUpdate` to `false` in the spec and rebuilding converges an+ already-shipped table, not only a fresh one.+### entity sub-sections (optional)```jsonc"statusReasons": [ { "label": "In Review", "state": "Active" } ], // custom status values@@ -303,6 +420,7 @@ Reference from a column via `"globalChoice": "new_priority"` (built before the c```jsonc{ "entity": "new_ticket", "name": "Active Tickets", "columns": ["new_subject","new_priority"],"sort": [{ "attr": "new_subject", "dir": "asc" }], "activeOnly": true,+ "description": "Unresolved tickets, most urgent first — the queue agents work from.",// optional rich filters (beyond the default active-records condition):"filters": [{ "attr": "ownerid", "op": "eq-userid" }, // "my" records — no value@@ -319,14 +437,18 @@ Reference from a column via `"globalChoice": "new_priority"` (built before the c- **Default-view enrichment (automatic):** the auto-generated **"Active <Entity>"** and**"Inactive <Entity>"** system views ship with only the primary column. The build enrichesthem with the primary column plus up to 6 meaningful declared columns (in declared order, skipping- wide/opaque types like MultilineText). This runs by default for every table that has extra columns;- opt a table out with **`"enrichDefaultViews": false`** on its `entities[]` entry. Author-declared- `views[]` are separate and always win.+ wide/opaque types like MultilineText). This runs by default for every table the build **owns** that+ has extra columns; opt a table out with **`"enrichDefaultViews": false`** on its `entities[]` entry.+ A table marked **`"existing": true`** is skipped by default — enrichment *replaces* a view's column+ set, and `existing` means the build cannot prove it owns the table, so rewriting another app's+ default views is not a safe default. Set **`"enrichDefaultViews": true`** to override that when you+ know the reused table is yours. Author-declared `views[]` are separate and always win.## charts[]```jsonc{ "entity": "new_ticket", "name": "Tickets by Priority", "chartType": "Pie",- "groupBy": "new_priority", "measure": "count" }+ "groupBy": "new_priority", "measure": "count",+ "description": "Where the open workload is concentrated." }```- `chartType`: `Column · Bar · Pie · Line`. **`groupBy` MUST be a Choice column** on `entity`.@@ -334,6 +456,7 @@ Reference from a column via `"globalChoice": "new_priority"` (built before the c```jsonc// auto layout (default): primary + all scalar columns + 1:N parent lookups; opt-in child grids{ "entity": "new_customer", "type": "main", "name": "Customer", "layout": "auto",+ "description": "The main customer record — profile, contacts and open tickets.","notes": true, // optional — add a Notes section"autoSubgrids": true, // optional — a sub-grid for every child relationship"deactivateOtherMainForms": true, // optional — see below (own custom tables only)@@ -344,6 +467,25 @@ Reference from a column via `"globalChoice": "new_priority"` (built before the c"tabs": [ { "label": "General", "sections": [{ "label": "Details", "columns": 2, "fields": ["new_name","new_budget","new_status"] } ] } ] }+// per-field control options: read-only, hidden, and targeted positioning+{ "entity": "new_workitem", "name": "Work Item", "layout": "auto",+ "fieldOptions": {+ "new_workitemnumber": { "readOnly": true }, // visible but locked (e.g. an AutoNumber)+ "new_storypoints": { "hidden": true }, // on the form for scripts, not shown+ "new_daysremaining": { "after": "new_duedate" } // move it directly after Due Date+ } }++// offer this form only to particular personas (a form with no assignment is offered to EVERY role)+{ "entity": "new_ticket", "name": "Dispatcher Ticket", "layout": "auto",+ "securityRoles": { "personas": ["Dispatcher"], "fallbackForm": false, "order": 1 } }++// the same options inline, when an explicit layout already lists the fields+{ "entity": "new_workitem", "name": "Work Item", "layout": "explicit", "prune": false,+ "tabs": [ { "label": "General", "sections": [ { "columns": 1, "fields": [+ "new_name",+ { "name": "new_workitemnumber", "readOnly": true },+ { "name": "new_storypoints", "hidden": true } ] } ] } ] }+// form JS: wire onload/onsave/onchange handlers to a web-resource library{ "entity": "new_ticket", "type": "main", "name": "Ticket", "layout": "auto","events": [@@ -394,6 +536,88 @@ Reference from a column via `"globalChoice": "new_priority"` (built before the cis 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.+### Per-field control options — `readOnly`, `hidden`, `after`++A form field can carry three per-control options. Declare them **form-level** in `fieldOptions`+(keyed by column logical name) — the only route under an `auto` layout, which has no field list —+or **inline** on an explicit layout's `fields[]` entry as `{ "name": …, "readOnly": …, "hidden": … }`.+Where both apply to one field the inline entry wins; a plain string entry keeps working unchanged.++- **`readOnly: true`** locks the control (`disabled="true"`), leaving it visible. Use it for a value+ the platform generates but does **not** make immutable — an AutoNumber column is writable through+ the API, so "read-only" for it is a form-level statement, not a metadata one.+- **`hidden: true`** places the field as a hidden control (`visible="false"`) — present for form+ scripts and business rules, not shown to the user.+- **`after: "<logical>"`** moves the field so it immediately follows the named anchor. This is the+ **non-destructive** way to reposition one control: it works on an already-deployed form and does+ not require re-declaring the rest of the form. An anchor that is not on the form is ignored.+ Only valid in `fieldOptions` — inside an explicit `tabs` layout the listed order already positions+ the field, so `after` there is rejected rather than silently overriding the list.+ Two anchor shapes are **rejected**, because neither has a satisfiable answer: only **one** field may+ sit immediately after a given anchor (to place several in sequence, *chain* them — anchor the second+ after the first), and anchors may not form a **cycle**.++**Only the enabled state is ever written.** The build emits `readOnly`/`hidden` when you ask for+them and writes *nothing* when you do not, so a rebuild never clears a lock or a hide someone applied+in the form designer. The corollary is that `readOnly: false` / `hidden: false` cannot turn a flag+back off — they are rejected at author time rather than accepted and ignored. To un-set one, clear it+in the designer, or drop the field and let the next build re-add it.++- **`prune`** *(optional, default `true`, explicit layouts only)* — an explicit `tabs` layout is+ normally the complete desired state, so a rebuild removes any deployed field it does not list. Set+ `prune: false` to keep those fields, which lets you restyle or reorder a **subset** of a form+ without re-declaring every other field just to preserve it. It has no effect on an `auto` layout+ (already additive) and is warned about there.++### `securityRoles` — who the form is offered to++A form with **no** `securityRoles` block is offered to **every** security role. Declaring one is+therefore a **restriction**, not a grant, and that direction is what makes each mistake here+access-relevant: an empty list or a mistyped persona would hide the form from everyone, not simply+fail to add anyone. Every malformed shape is a hard error for that reason.++```jsonc+{ "securityRoles": { "personas": ["Dispatcher", "Supervisor"] } } // only these roles see it+{ "securityRoles": { "everyone": true } } // explicitly every role+{ "securityRoles": { "personas": ["Dispatcher"], "fallbackForm": true, "order": 2 } }+```++- **`personas[]`** — names from this spec's `personas[]`, **not** role GUIDs. The build resolves each+ to the role it created. A name that is not declared is rejected at the spec gate, and would halt the+ build if it somehow reached it.+- **`everyone`** — mutually exclusive with `personas`. That is the *platform's* model, not a rule of+ this spec: `<Everyone />` **replaces** the role list rather than adding to it. `everyone: false` is+ rejected, because it looks like "restrict to nobody" and means nothing.+- **Removing a restriction needs `everyone: true`, not deleting the block.** A build only visits+ forms that *declare* `securityRoles`, so deleting the block leaves the deployed+ `<DisplayConditions>` exactly as it was — the form stays hidden from everyone outside the old list.+ This direction fails closed (access never silently widens), but it does mean "undo" is an explicit+ `{ "everyone": true }`.+- **`fallbackForm`** *(optional)* — show this form to users whose roles have no form of their own.+- **`order`** *(optional, non-negative integer)* — display order among the entity's forms.+- Both `fallbackForm` and `order` are **preserved** when omitted, so a later build that sets only+ `personas` does not reset them.++**Two things worth knowing.** The roles are stored **inside `formxml`**, as a `<DisplayConditions>`+element — `systemform` has no role relationship at all (it reports+`CanBeInManyToMany: { Value: false, CanBeChanged: false }`), which is why no association-style API+ever worked and why this needs a dedicated call. And the write lands on the **unpublished** layer:+live-measured, the published form still reported `<Everyone />` until the customization was+published, so the restriction takes effect only after a publish. The build publishes the entity when+publishing is enabled.++Assignment happens in the **security** phase, not the forms phase, because the roles do not exist+until then. If you build with `--phases` excluding `forms`, the assignment is skipped with a message+rather than applied to a form this run did not build.++### Column types that cannot go on a form++**Big Integer (`BigInt`) has no Unified Interface form control.** A BigInt placed on a form renders+the text *"Error loading control"* on every record. The `auto` layout therefore **skips BigInt+columns** — the column is still created and still readable/writable through the API, it just is not+placed. An explicit layout still honours a BigInt you list by name (you may be pairing it with a+custom control), but the spec validator emits a warning.+## commands[] (optional — modern command-bar buttons)```jsonc{ "entity": "new_order", "label": "Escalate", "location": "MainTab",@@ -438,9 +662,10 @@ Reference from a column via `"globalChoice": "new_priority"` (built before the c```jsonc{ "entity": "new_ticket", "name": "Hide notes on closed tickets",+ "description": "Closed tickets are read-only history, so the working fields are hidden.","scope": "Entity", // only Entity today"status": "Active", // Active (default) | Draft — a Draft rule is deployed but inert- "conditions": [ // ALL must hold (ANDed)+ "conditions": [ // ALL must hold (ANDed); more than one is allowed{ "field": "new_status", "operator": "Equals", "value": "100000001", "dataType": "Picklist" }], "actions": [{ "type": "SetVisibility", "field": "new_notes", "visible": false },@@ -450,29 +675,47 @@ Reference from a column via `"globalChoice": "new_priority"` (built before the c] }```-- **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.+- **Environment gate — read this first.** The SDK writes a rule through the bound+ `CreateProcessWithWfomJson` member, the same one the modern business-rule designer uses, and has+ **no fallback**. An environment that does not declare that member cannot host business rules at+ all, and that is the common case rather than an edge case. The build then+ **skips** `businessRules[]`, warns once naming the member, and builds everything else normally —+ so you get a working app without the rules, not a half-built one. `--verify` will report those+ rules as not deployed, which is the truth.+- **Operators**, all of which the SDK's own table defines:+ `Equals` · `DoesNotEqual` · `IsGreaterThan` · `IsGreaterThanEqualTo` · `IsLessThan` ·+ `IsLessThanEqualTo` · `Contains` · `DoesNotContain` · `BeginsWith` · `DoesNotBeginWith` ·+ `EndsWith` · `DoesNotEndWith` · `On` · `NotOn` (all carry a `value`), plus the presence operators+ `ContainsData` · `DoesNotContainData`, which must **not** carry one.+ Mind the spelling: it is `IsGreaterThan`, **not** `GreaterThan`. The SDK resolves an operator it+ does not recognise to **Equals** rather than rejecting it, so a misspelling would deploy, activate,+ and quietly test equality. The spec rejects anything outside the table for exactly that reason, and+ suggests the correct spelling when it can.- **Actions**: `SetVisibility` (`visible`) · `LockUnlock` (`lock`) · `SetBusinessRequired`(`required`) · `SetFieldValue` (`value`). The three boolean payloads must be **real booleans** — astring `"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.+ The SDK also models `SetDefaultValue`, `ShowErrorMessage` and `Recommendation`. They are not+ exposed yet: each needs mapping that cannot be exercised end to end on an environment without the+ bound member, and shipping unverified mapping is how a rule deploys and does the wrong thing.+- **`conditions[]` are ANDed**, and there may be **more than one** — they are folded with the+ platform's `LogicalAnd`. (An earlier single-condition limit came from a client-side XAML compiler+ that has since been deleted upstream; it was never a platform limit.) `OR` is not exposed.+- **`dataType`** (optional) — accepted values are `String` · `Memo` · `Picklist` · `State` ·+ `Status` · `Boolean` · `Integer` · `Double` · `Decimal` · `Money`.+ **It currently has no effect.** Measured across every accepted value, on both the condition and the+ action path, the SDK types every literal as `String` and never consults this field. It is still+ validated as a closed set so a typo is caught and so the surface stays forward-compatible, but do+ not expect it to change the deployed rule. For a Choice column, give the option's **integer+ value**, not its label — that part matters regardless.- Every `field` must be a column on the rule's own `entity` (its own columns, its primary name, or alookup a relationship creates). A rule naming a column that does not exist is accepted by theplatform 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": [+{ "name": "Operations", "description": "Daily queue health for the support lead.", "tiles": [{ "type": "chart", "chart": "Orders by Status", "view": "Active Orders" }, // chart needs both{ "type": "list", "view": "Active Orders", "name": "Recent" }, // list needs a view{ "type": "iframe", "url": "https://…", "name": "Map" },diff --git a/plugins/model-apps/scripts/ai-preflight.js b/plugins/model-apps/scripts/ai-preflight.jsindex 7cea960af..cf2a496c8 100644--- a/plugins/model-apps/scripts/ai-preflight.js+++ b/plugins/model-apps/scripts/ai-preflight.js@@ -9,7 +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 { AI_APP_SETTING, AI_SETTING_CODEC, resolveAppModuleId, effectiveSettingValue, settingIsOn } = require('./lib/ai-app-settings.js');const fs = require('node:fs');const os = require('node:os');const path = require('node:path');@@ -17,15 +17,22 @@ const path = require('node:path');// Human-readable label + admin-action hint for each feature key returned by getAiReadiness.const FEATURE_META = {formFill: {- // 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.+ // `FormFillBarUXEnabled` is the assist TOOLBAR only. The SDK now models the whole AI form-fill+ // family, so each capability is reported separately rather than one label implying all four.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.`,+ action: (f) => `Enable "Form fill assist toolbar" (setting: ${f.setting}) in Power Platform Admin Center → Environments → Settings → Product → Features.`,+ },+ formFillSuggestions: {+ label: 'Form fill predictions (edit forms)',+ action: (f) => `Enable "AI form fill predictions" (setting: ${f.setting}) in Power Platform Admin Center → Environments → Settings → Product → Features.`,+ },+ formFillSmartPaste: {+ label: 'Form fill smart paste',+ action: (f) => `Enable "Smart paste" (setting: ${f.setting}) in Power Platform Admin Center → Environments → Settings → Product → Features.`,+ },+ formFillFiles: {+ label: 'Form fill from files',+ action: (f) => `Enable "Form fill from files" (setting: ${f.setting}) in Power Platform Admin Center → Environments → Settings → Product → Features.`,},nlSearch: {label: 'Natural language search',@@ -71,12 +78,22 @@ function runPreflight(readiness, effective = {}) {// 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;+ // "Platform default" is a SPECIFIC state, not a synonym for "we could not decide". Only a+ // codec-governed feature sitting at its default value ('0') defers to flighting; an+ // unrecognised value like '3' or 'yes' is simply indeterminate, and calling that "the platform+ // decides" would invent a fact. Both suppress the ✓/✗ claim, but only one earns the explanation.+ const codec = AI_SETTING_CODEC[key];+ const effectiveDefault = eff.on === undefined && !eff.error && codec+ && eff.value !== undefined && String(eff.value).trim() === '0';+ const effectiveIndeterminate = eff.on === undefined && !eff.error && eff.value !== undefined && !effectiveDefault;features.push({feature: key,enabled: f.enabled,setting: f.setting,...(eff.value !== undefined ? { effectiveValue: eff.value, effectiveScope: eff.scope } : {}),...(inEffect ? { inEffect: true } : {}),+ ...(effectiveDefault ? { effectiveDefault: true } : {}),+ ...(effectiveIndeterminate ? { effectiveIndeterminate: true } : {}),});if (!f.enabled && !inEffect) {adminActions.push(meta.action(f));@@ -131,7 +148,7 @@ async function main() {if (!setting) continue; // `summaries` is not a per-app on/off settingif (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) };+ effective[key] = res.error ? { error: res.error } : { value: res.value, scope: res.scope, on: settingIsOn(res.value, key) };}if (appLookup.error) {process.stderr.write(`\nWarning: could not resolve app '${app}' (${appLookup.error}); reporting readiness gates only.\n`);@@ -145,6 +162,12 @@ async function main() {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 if (f.effectiveDefault) {+ // "Platform default" is not off. For the AI form-fill family `0` means "defer to flighting",+ // so the feature may well be running; printing ✗ would assert something we cannot see.+ process.stderr.write(` ? ${label} (${f.setting}) — set to the platform default ("${f.effectiveValue}"), so whether it runs is decided by service flighting, not by this environment\n`);+ } else if (f.effectiveIndeterminate) {+ process.stderr.write(` ? ${label} (${f.setting}) — holds an unrecognised value ("${f.effectiveValue}"), so its state cannot be determined from here\n`);} else {process.stderr.write(` ${f.enabled ? '✓' : '✗'} ${label} (${f.setting})\n`);}diff --git a/plugins/model-apps/scripts/build-model-app.js b/plugins/model-apps/scripts/build-model-app.jsindex 7455466d7..84969195e 100644--- a/plugins/model-apps/scripts/build-model-app.js+++ b/plugins/model-apps/scripts/build-model-app.js@@ -342,16 +342,34 @@ async function buildModelApp(spec, opts, deps) {// opts.verify without mustVerifyPages and no verifier → silently skip (no pages to enforce).} else {try {- const vr = await deps.verify(spec);+ // Hand verify what the BUILD could not do on this environment, and which phases actually+ // ran. Without the first, an environment-gated business-rule skip reports `not deployed`+ // and drives `verify.ok` false forever — and that value gates the exit code,+ // `.last-applied.json` AND the `--changed-only` snapshot, so the baseline would never be+ // written and every later run would fall back to a full build. Without the second, the+ // `--changed-only` FAST path (which runs `phases: ['pages']`, so it produces no skip list+ // at all) fails the same way on every run after the first.+ const vr = await deps.verify(spec, { environmentSkipped: r.skipped, phases: opts.phases });const present = vr.checks.length - vr.missing.length;log(`\n${vr.ok ? '✓ verify PASS' : `✗ verify FAIL — ${vr.missing.length} missing`} (${present}/${vr.checks.length} present)`);+ // Named explicitly rather than folded into the pass, so a green verify never reads as+ // "everything the spec asked for is deployed" when part of it could not be. Two distinct+ // causes get two distinct messages: telling an operator on a HEALTHY environment that it+ // cannot host business rules — which is what a single shared message did on every+ // `--changed-only` fast apply — is worse than saying nothing.+ if (vr.environmentSkipped && vr.environmentSkipped.length) {+ log(` ⊘ ${vr.environmentSkipped.length} check(s) not applicable on this environment: ${vr.environmentSkipped.join(', ')}`);+ }+ if (vr.phaseSkipped && vr.phaseSkipped.length) {+ log(` ⊘ ${vr.phaseSkipped.length} check(s) not verified because their phase did not run in this build: ${vr.phaseSkipped.join(', ')}`);+ }// Include `detail` on a failure so a READ that failed (throttling, auth expiry, a 5xx) is// not reported identically to an artifact that is genuinely absent.if (!vr.ok) for (const m of vr.missing) log(` ✗ ${m.kind}: ${m.name}${m.detail ? ` — ${m.detail}` : ''}`);// Propagate unableToRun from verifySpec (RECONCILIATION 1): verifySpec itself sets// unableToRun when the reader lacks pages/pageCode methods. Only include the property// when truthy so existing callers using deepStrictEqual are not affected on the normal path.- r.verify = { ok: vr.ok, present, total: vr.checks.length, missing: vr.missing.map((m) => `${m.kind}:${m.name}${m.detail ? ` (${m.detail})` : ''}`), ...(vr.unableToRun ? { unableToRun: true } : {}) };+ r.verify = { ok: vr.ok, present, total: vr.checks.length, missing: vr.missing.map((m) => `${m.kind}:${m.name}${m.detail ? ` (${m.detail})` : ''}`), ...(vr.unableToRun ? { unableToRun: true } : {}), ...(vr.environmentSkipped && vr.environmentSkipped.length ? { environmentSkipped: vr.environmentSkipped } : {}), ...(vr.phaseSkipped && vr.phaseSkipped.length ? { phaseSkipped: vr.phaseSkipped } : {}) };if (journal) journal.record({ phase: 'verify', status: vr.ok ? 'ok' : 'error', label: `verify ${present}/${vr.checks.length} present`, ...(vr.ok ? {} : { detail: r.verify.missing.join(', ') }) });} catch (e) {if (mustVerifyPages) {@@ -573,7 +591,7 @@ async function main() {// EntityDefinitions request. Omitting them degraded silently: `--apply --verify` reported a// 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 })),+ verify: (s, verifyOpts) => verifySpec(s, readerFor(provisionSdk, appUniqueName(s), { genpageCli: makeGenpageCli(env), workspaceDir, httpClient, envUrl: env }), verifyOpts),// 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),diff --git a/plugins/model-apps/scripts/download-model-app.js b/plugins/model-apps/scripts/download-model-app.jsindex 00c6ded79..05837c867 100644--- a/plugins/model-apps/scripts/download-model-app.js+++ b/plugins/model-apps/scripts/download-model-app.js@@ -11,7 +11,7 @@ const fs = require('node:fs');const path = require('node:path');const { parseArgs, emitResult } = require('./lib/dataverse-auth.js');const { createAzHttpClient } = require('./lib/sdk-http-client.js');-const { hydrateSpec } = require('./lib/hydrate-spec.js');+const { hydrateSpec, descriptionFromDataverse, withDescription } = require('./lib/hydrate-spec.js');const { makeGenpageCli } = require('./lib/genpage-cli.js');const { parseManifestBase64, manifestResourceName, reconcilePageIds } = require('./lib/page-manifest.js');const { reverseResolveNavIds } = require('./lib/pageref-resolver.js');@@ -51,7 +51,12 @@ async function readDashboards(sdk, app, warn) {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 */ }+ let description;+ try {+ const rows = await sdk.queryRecords('systemform', { select: ['name', 'description'], filter: `formid eq ${id}`, top: 1 });+ if (rows && rows[0] && rows[0].name) name = rows[0].name;+ description = rows && rows[0] && rows[0].description;+ } catch { /* keep fallback */ }const tiles = [];for (const c of art.components || []) {const p = c.parameters || {};@@ -64,7 +69,7 @@ async function readDashboards(sdk, app, warn) {}// 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 });+ if (tiles.length) out.push(withDescription({ id, name, tiles }, description));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.`);@@ -109,8 +114,8 @@ async function resolveAppId(sdk, appArg) {return { error: `'${appArg}' is a DISPLAY name shared by ${matches.length} apps — display names are not unique, so re-run --app with one of these unique names: ${names}` };}return { error: `app '${appArg}' not found — --app takes the app's id (GUID), its unique name (e.g. new_myapp), or an unambiguous display name` };-}-+}+// The distinct entity logical names + icon web-resource NAMES referenced by the app's sitemap. Returns// TWO name sets:// `icons` — BARE-NAME icon references (a locally-declared image web resource); fetched and@@ -230,6 +235,110 @@ async function appComponentEntities(sdk, appId) {}}+async function rowsByIds(sdk, set, idField, ids, select, mapRow) {+ const out = [];+ const clean = [...new Set((ids || []).map((id) => String(id || '').replace(/[{}]/g, '')).filter(Boolean))];+ for (let i = 0; i < clean.length; i += 20) {+ const filter = clean.slice(i, i + 20).map((id) => `${idField} eq ${id}`).join(' or ');+ const rows = await sdk.queryRecords(set, { select, filter, top: 1000 });+ for (const r of rows || []) out.push(mapRow(r));+ }+ return out;+}++async function readDescriptionInventory(sdk, appId, solutionUniqueName) {+ const inventory = { views: [], charts: [], forms: [], businessRules: [], globalChoices: [], roleRestrictedForms: [] };+ try {+ const appRows = await sdk.queryRecords('appmodule', { select: ['appmoduleidunique'], filter: `appmoduleid eq ${appId}`, top: 1 });+ const appUniqueId = appRows && appRows[0] && appRows[0].appmoduleidunique;+ const parent = appUniqueId ? String(appUniqueId).replace(/[{}]/g, '') : null;+ if (parent) {+ for (const src of APP_COMPONENT_ENTITY_SOURCES) {+ const rows = await sdk.queryRecords('appmodulecomponent', {+ select: ['objectid', 'componenttype'],+ filter: `_appmoduleidunique_value eq ${parent} and componenttype eq ${src.componentType}`,+ top: COMPONENT_PAGE_CAP,+ });+ const ids = (rows || []).map((r) => r && r.objectid).filter(Boolean);+ if (src.set === 'savedquery') {+ inventory.views.push(...await rowsByIds(sdk, 'savedquery', 'savedqueryid', ids, ['savedqueryid', 'name', 'returnedtypecode', 'description'], (r) =>+ withDescription({ id: r.savedqueryid, name: r.name, entity: r.returnedtypecode }, r.description)));+ } else if (src.set === 'savedqueryvisualization') {+ inventory.charts.push(...await rowsByIds(sdk, 'savedqueryvisualization', 'savedqueryvisualizationid', ids, ['savedqueryvisualizationid', 'name', 'primaryentitytypecode', 'description'], (r) =>+ withDescription({ id: r.savedqueryvisualizationid, name: r.name, entity: r.primaryentitytypecode }, r.description)));+ } else if (src.set === 'systemform') {+ // `formxml` is pulled ONLY to detect a role restriction — it is never stored. A form's+ // security roles live inside formxml as `<DisplayConditions>` (there is no+ // systemform↔role relationship), and `forms[]` is not reconstructed by this download at+ // all, so a restricted form would come back as one every role can see. That is a silent+ // WIDENING of access on a cross-environment rebuild, which is why it is worth one extra+ // column on a query this download already makes.+ //+ // The flag is kept OFF the form entries and on a sibling key, because+ // `sanitizeDescriptionInventory` whitelists exactly five keys — so this reaches the+ // download CLI for its warning without leaking a new field into `app-spec.json`.+ const rawForms = await rowsByIds(sdk, 'systemform', 'formid', ids, ['formid', 'name', 'objecttypecode', 'description', 'formxml'], (r) => r);+ for (const r of rawForms) {+ if (!r || !r.objecttypecode || r.objecttypecode === 'none') continue;+ inventory.forms.push(withDescription({ id: r.formid, name: r.name, entity: r.objecttypecode }, r.description));+ if (isRoleRestrictedFormXml(r.formxml)) {+ inventory.roleRestrictedForms.push({ name: r.name, entity: r.objecttypecode });+ }+ }+ }+ }+ }+ } catch { /* inventory is best-effort; structural download still carries the rebuildable app spec */ }++ try {+ if (solutionUniqueName && !isRestrictedSolution(solutionUniqueName)) {+ const esc = String(solutionUniqueName).replace(/'/g, "''");+ const sols = await sdk.queryRecords('solution', { select: ['solutionid'], filter: `uniquename eq '${esc}'`, top: 1 });+ const solId = sols && sols[0] && sols[0].solutionid;+ if (solId) {+ // Solution component type 29 is Workflow — which is EVERY process kind, not just business+ // rules: classic workflows, actions, business process flows and modern flows all land here.+ // See component type values: https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/solutioncomponent+ //+ // So the rows must be narrowed after the fetch. A business rule is `category 2`, and `type 1`+ // is the DEFINITION — activating one makes Dataverse create a second `type 2` copy of it, so+ // without the type filter every active rule would appear twice in the inventory.+ //+ // Filtered client-side rather than in the query because `rowsByIds` batches on the id column;+ // both fields are requested in the select so the decision is made on real values, and a row+ // that reports NEITHER field is dropped rather than assumed to be a rule — fail closed, since+ // mislabelling somebody's classic workflow as a business rule is the failure mode here.+ const comps = await sdk.queryRecords('solutioncomponent', { select: ['objectid', 'componenttype'], filter: `_solutionid_value eq ${solId} and componenttype eq 29`, top: 1000 });+ const ids = (comps || []).map((r) => r && r.objectid).filter(Boolean);+ const processes = await rowsByIds(sdk, 'workflow', 'workflowid', ids, ['workflowid', 'name', 'primaryentity', 'description', 'category', 'type'], (r) => r);+ for (const r of processes) {+ if (Number(r && r.category) !== 2 || Number(r && r.type) !== 1) continue;+ inventory.businessRules.push(withDescription({ id: r.workflowid, name: r.name, entity: r.primaryentity }, r.description));+ }+ }+ }+ } catch { /* business-rule descriptions are an inspection aid, not a rebuild prerequisite */ }++ try {+ // Global option sets are not app components, but their Description is another Dataverse Label. This+ // is intentionally an inventory, not `globalChoices[]`: without options we cannot safely claim a+ // rebuildable choice definition.+ //+ // Read through the RAW client, NOT `sdk.queryRecords`. `queryRecords` resolves its first argument+ // to an entity SET name via `EntityDefinitions(LogicalName='<arg>')?$select=EntitySetName`, and+ // `GlobalOptionSetDefinitions` is a metadata collection rather than a table, so that lookup 404s+ // and the catch below would swallow it — leaving this inventory permanently empty while the+ // download still reported success. Same trap, and same fix, as readEntityWithDescriptions.+ //+ // `dataverse.get` RESOLVES on a non-2xx instead of throwing, so the status is checked explicitly.+ const res = await sdk.dataverse.get('/GlobalOptionSetDefinitions?$select=Name,Description');+ const rows = (res && res.status >= 200 && res.status < 300 && res.body && res.body.value) || [];+ inventory.globalChoices.push(...rows.map((r) => withDescription({ name: r.Name }, r.Description)));+ } catch { /* optional inventory */ }++ return Object.fromEntries(Object.entries(inventory).filter(([, value]) => value.length));+}+// Read pac's downloaded page tree (<pagesRoot>/<pageId>/{page.tsx,config.json,prompt.txt}) into// pages[] entries with codeFile paths relative to `outDir`.function parseDownloadedPages(pagesRoot, outDir, nameById) {@@ -325,15 +434,114 @@ function missingDownloads(a, b) {// missing primary name as a hard download failure, which is actionable at the point it happens rather// than as a confusing validation error later. Returns `null` for `primaryAttribute` so the caller can// detect and report it.+// Dataverse `AttributeType` -> App Spec column type. Only types the App Spec can actually declare+// are mapped; anything else (Lookup, Owner, State, Status, Uniqueidentifier, Virtual, ...) is a+// column the author never wrote — a Lookup comes from `relationships[]`, and the rest are platform+// plumbing — so it is left out of the hydrated spec entirely.+// See: https://learn.microsoft.com/en-us/dotnet/api/microsoft.xrm.sdk.metadata.attributetypecode+const SPEC_TYPE_FROM_ATTRIBUTE_TYPE = {+ String: 'Text', Memo: 'Memo', Picklist: 'Choice', MultiSelectPicklist: 'MultiChoice',+ Boolean: 'Boolean', Money: 'Money', DateTime: 'DateTime', Integer: 'Integer',+ BigInt: 'BigInt', Decimal: 'Decimal', Double: 'Double', File: 'File', Image: 'Image',+};++// Types whose App Spec declaration REQUIRES a companion field this hydrator cannot supply: a+// `Choice`/`MultiChoice` column must carry `options[]` or a `globalChoice` reference, and reading+// those needs a per-column typed-metadata expand the download does not perform. (Verified to be the+// ONLY such dependency: every other companion rule in `validateAppSpec` / `spec-lint` — AutoNumber's+// format, Calculated/Rollup's formula, Customer's description — is a warning, not an error.)+//+// So the column is emitted WITHOUT a type rather than with one that makes the whole spec fail+// validation ("column X: Choice needs options[] or a globalChoice reference") — which is what+// happened the moment types started being carried, live.+//+// This is NOT free, and the cost is surfaced rather than described as harmless. On a rebuild into an+// org that does NOT already have the table, `provisionDataModel` decides create-vs-reuse from org+// DISCOVERY (not from `existing`) and computes buildable columns as `SDK_COLUMN_TYPE[c.type ||+// 'Text']` — so a type-less Choice column is created as TEXT. The now-asymmetric result (Memo, Money+// and DateTime round-trip while Choice quietly degrades) is harder to notice than the old+// everything-is-Text, so the affected columns are warned about by name.+const TYPES_NEEDING_COMPANION_DATA = new Set(['Choice', 'MultiChoice']);++// Does this form's `formxml` restrict it to particular security roles?+//+// The roles live INSIDE formxml, as a `<DisplayConditions>` child of `<form>` — `systemform` has no+// role relationship at all — e.g.:+//+// <DisplayConditions Order="2" FallbackForm="false"><Role Id="{GUID}" /></DisplayConditions>+//+// The unrestricted default is the sibling shape `<DisplayConditions ...><Everyone /></...>`, or no+// element at all. Only the `<Role>` form is a restriction, so match on that specifically rather than+// on the presence of `<DisplayConditions>`, which every form has.+//+// Attribute order and casing vary between platform-authored and SDK-authored xml, so this matches+// the element name case-insensitively and does not assume `Id` is the first attribute.+function isRoleRestrictedFormXml(formxml) {+ const xml = String(formxml || '');+ const block = xml.match(/<DisplayConditions[\s\S]*?<\/DisplayConditions>/i);+ if (!block) return false;+ return /<Role\b/i.test(block[0]);+}++// Columns whose type could not be substantiated, so a `download -> rebuild into a fresh org` round+// trip does not silently create them as Text. `type` is absent for a Choice/MultiChoice (above), or+// for an attribute whose metadata carried no `attributeType` at all — an attribute with a type that+// simply has no App Spec equivalent is filtered out of `columns[]` entirely, so it never gets here.+function untypedColumnNames(entities) {+ const out = [];+ for (const e of entities || []) {+ for (const c of (e.columns || [])) {+ if (c && c.schemaName && c.type === undefined) out.push(`${e.schemaName}.${c.schemaName}`);+ }+ }+ return out;+}+function entityFromMetadata(meta, logical) {const primary = meta && (meta.primaryNameAttribute || meta.primaryNameLogicalName);+ const attrs = Array.isArray(meta && meta.attributes) ? meta.attributes : (Array.isArray(meta && meta.Attributes) ? meta.Attributes : []);+ const primaryLower = String(primary || '').toLowerCase();+ const columns = attrs.filter((a) => {+ if (!a) return false;+ const name = String(a.schemaName || a.SchemaName || a.logicalName || a.LogicalName || '').toLowerCase();+ // The primary name column is declared separately as `primaryAttribute`, so it must not ALSO+ // appear in `columns[]`.+ if (!name || name === primaryLower) return false;+ // CUSTOM attributes only. `fetchEntityMetadata` returns the FULL attribute list — `createdon`,+ // `versionnumber`, `importsequencenumber`, `owningbusinessunit` and the rest — and emitting+ // those as spec columns is not merely noisy, it is destructive: `columns[]` feeds+ // `defaultViewColumns`, which `enrichDefaultViews` uses to REPLACE the Active/Inactive views'+ // column set. A downloaded spec that listed system attributes would rewrite a customer's+ // default views to `Created On` / `Import Sequence Number` on the next rebuild, undoing fix #7+ // ("drop Created On from enriched default views") whose invariant is stated at+ // sdk-build.js `defaultViewColumns`: the set only ever contains DECLARED spec columns.+ const isCustom = a.isCustomAttribute !== undefined ? a.isCustomAttribute : a.IsCustomAttribute;+ if (isCustom === false) return false;+ // Keep only attribute types the App Spec can declare (see the map above).+ const at = a.attributeType || a.AttributeType;+ return at === undefined || SPEC_TYPE_FROM_ATTRIBUTE_TYPE[at] !== undefined;+ }).map((a) => {+ const schemaName = (a && (a.schemaName || a.SchemaName || a.logicalName || a.LogicalName)) || '';+ // The SDK projects `attributeType`, NOT `type`. Reading `a.type` yielded `undefined` on every+ // column, which silently disabled every type-based filter downstream (`DEFAULT_VIEW_SKIP_TYPES`+ // skips Memo/File/Image; `SDK_COLUMN_TYPE` decides what an auto form layout places).+ const at = a && (a.attributeType || a.AttributeType);+ const mapped = a && a.type ? a.type : SPEC_TYPE_FROM_ATTRIBUTE_TYPE[at];+ const specType = TYPES_NEEDING_COMPANION_DATA.has(mapped) ? undefined : mapped;+ return withDescription({+ schemaName,+ ...(a && (a.displayName || a.DisplayName) ? { displayName: descriptionFromDataverse(a.displayName || a.DisplayName) || a.displayName || a.DisplayName } : {}),+ ...(specType ? { type: specType } : {}),+ }, a && (a.description !== undefined ? a.description : a.Description));+ }).filter((c) => c.schemaName);return {schemaName: (meta && (meta.schemaName || meta.logicalName)) || logical,displayName: (meta && meta.displayName) || logical,+ ...(descriptionFromDataverse(meta && (meta.description !== undefined ? meta.description : meta.Description)) ? { description: descriptionFromDataverse(meta && (meta.description !== undefined ? meta.description : meta.Description)) } : {}),// Never synthesized: a fabricated attribute name yields a spec that references a column Dataverse// does not have, which is exactly the bug this fixes.primaryAttribute: primary ? { schemaName: primary, displayName: 'Name' } : null,- columns: [],+ columns,// Flag every recovered table as pre-existing so a teardown of THIS downloaded spec never deletes the// table (+ its data). Download cannot prove which tables the app CREATED vs merely REFERENCED, and// deleting a customer's table/data is unrecoverable while an orphaned table is not — so fail safe.@@ -343,6 +551,51 @@ function entityFromMetadata(meta, logical) {};}+function metadataEntityPath(logical) {+ return `EntityDefinitions(LogicalName='${String(logical).replace(/'/g, "''")}')`;+}++async function readEntityWithDescriptions(sdk, logical) {+ const meta = { ...(await sdk.fetchEntityMetadata(logical)) };+ // The SDK's fetchEntityMetadata projection is enough for identity but carries NO descriptions —+ // measured against a live org, its entity keys are logicalName/schemaName/displayName/+ // entitySetName/primaryNameAttribute/primaryIdAttribute/isCustomEntity/attributes/relationships,+ // and each attribute is {logicalName, displayName, attributeType, isCustomAttribute, targets}.+ // So descriptions require a second read against the metadata endpoints.+ //+ // This deliberately does NOT go through `sdk.queryRecords`. That helper first resolves its+ // argument to an entity SET name via `EntityDefinitions(LogicalName='<arg>')?$select=EntitySetName`,+ // so handing it a metadata path produces a nested nonsense URL and a 404:+ // .../EntityDefinitions(LogicalName='EntityDefinitions(LogicalName=''contoso_workitem'')')?$select=EntitySetName+ // Combined with the best-effort catch below, that failed silently for EVERY table — the download+ // reported success and dropped every table and column description. `sdk.dataverse` is the raw+ // client and takes an API-relative path verbatim.+ //+ // NOTE `dataverse.get` RESOLVES with `{ status, headers, body }` on a non-2xx rather than throwing+ // (a 404 returns status 404), so the status MUST be checked explicitly. A try/catch alone would+ // reintroduce exactly the silence this replaces.+ const entityPath = `/${metadataEntityPath(logical)}`;+ try {+ const res = await sdk.dataverse.get(`${entityPath}?$select=LogicalName,Description`);+ if (res && res.status >= 200 && res.status < 300 && res.body) meta.Description = res.body.Description;+ } catch { /* description best-effort — never sink an otherwise usable download */ }+ try {+ // Merge onto the SDK's attribute list rather than replacing it: `fetchEntityMetadata` supplies+ // `targets` (lookup target tables) and `attributeType`, which this projection does not, and+ // entityFromMetadata/other callers rely on them.+ const res = await sdk.dataverse.get(`${entityPath}/Attributes?$select=LogicalName,Description`);+ const rows = (res && res.status >= 200 && res.status < 300 && res.body && res.body.value) || null;+ if (Array.isArray(rows)) {+ const byLogical = new Map(rows.filter((r) => r && r.LogicalName).map((r) => [String(r.LogicalName).toLowerCase(), r.Description]));+ meta.attributes = (meta.attributes || []).map((a) => {+ const key = String((a && (a.logicalName || a.LogicalName)) || '').toLowerCase();+ return byLogical.has(key) ? { ...a, Description: byLogical.get(key) } : a;+ });+ }+ } catch { /* column descriptions are best-effort */ }+ return meta;+}+// Image webresourcetypes (png/jpg/gif/ico/svg) — an icon reference must resolve to one of these to be// re-declared. See WR_TYPE. Guards against re-declaring a non-image WR that a path happens to name.const IMAGE_WR_TYPES = new Set([5, 6, 7, 10, 11]);@@ -485,10 +738,10 @@ async function recoverAppSolution(sdk, appId) {// One OR-batched lookup for all candidate solutions (solutionid is a Guid, so it is unquoted in// the OData filter — mirrors the existing `solutionid eq ${id}` usage elsewhere in this file).const filter = solIds.map((id) => `solutionid eq ${id}`).join(' or ');- const sols = await sdk.queryRecords('solution', { select: ['solutionid', 'uniquename', 'ismanaged'], filter, top: 500 });+ const sols = await sdk.queryRecords('solution', { select: ['solutionid', 'uniquename', 'ismanaged', 'description'], filter, top: 500 });const real = (sols || []).find((s) => s && s.ismanaged === false && !isRestrictedSolution(s.uniquename));if (!real) return null;- const out = { uniqueName: real.uniquename };+ const out = withDescription({ uniqueName: real.uniquename }, real.description);// Authoritative publisher prefix for anything authored into THIS solution. Guarded on the method// existing so an older vendored bundle (pre-getSolution) degrades to the caller's fallback instead// of throwing away the solution we just recovered.@@ -662,7 +915,7 @@ async function runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLos// the confusing downstream error the explicit branch below exists to avoid. Bucket it by origin// exactly like the no-primary-name case, so the user is told the table AND the reason.try {- e = entityFromMetadata(await sdk.fetchEntityMetadata(logical), logical);+ e = entityFromMetadata(await readEntityWithDescriptions(sdk, logical), logical);} catch (err) {metadataErrors.set(logical, (err && err.message) || String(err));(sitemapSet.has(logical) ? noPrimaryName : droppedComponents).push(logical);@@ -697,6 +950,15 @@ async function runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLosif (droppedComponents.length) {process.stderr.write(`WARNING: ${droppedComponents.length} app component table(s) were omitted from the spec because Dataverse reported no primary-name column (${withReason(droppedComponents)}) — they are NOT in the app's navigation, and the deployed app still references them; declare them by hand if a rebuild needs them.\n`);}+ // A column whose App Spec type could not be substantiated — a Choice/MultiChoice (whose options+ // this download does not read) or an attribute type the spec cannot declare. Rebuilding into an+ // org that ALREADY has the table reuses the column and this is inert; rebuilding into a FRESH org+ // creates it as Text, because the data-model phase falls back to `c.type || 'Text'`. That silent+ // downgrade is the reason this is announced by name rather than left to be discovered later.+ const untyped = untypedColumnNames(entities);+ if (untyped.length) {+ process.stderr.write(`WARNING: ${untyped.length} column(s) were captured WITHOUT a type (${untyped.join(', ')}) — most likely Choice/MultiChoice columns, whose options this download does not read. Rebuilding this spec into an environment that already has the table is unaffected, but rebuilding into a FRESH environment would create them as single-line Text. Add the type and options[] (or a globalChoice reference) by hand before a cross-environment rebuild.\n`);+ }// App identity comes from the app's REAL, immutable uniquename (`appUnique`, captured from Dataverse as// `appmodule.uniquename`; guaranteed present here because runDownload bails at the sitemap gate above).@@ -725,6 +987,11 @@ async function runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLosconst trustedPrefix = solutionPrefix || appDerivedPrefix;const solution = { uniqueName: 'Default', publisherPrefix: trustedPrefix || 'new', prefixResolved: !!trustedPrefix };if (recovered && recovered.uniqueName) solution.uniqueName = recovered.uniqueName;+ // `recoverAppSolution` already unwraps the solution's description; carry it across. This object is+ // built fresh (rather than spread from `recovered`) so an unrecovered solution still gets its+ // required defaults, which is why each field has to be copied deliberately — a field added to+ // `recoverAppSolution` and not copied here is silently dropped, as this one was.+ if (recovered && recovered.description) solution.description = recovered.description;// Icon web resources — looked up by NAME (the sitemap stores the web-resource name, not its id).// Bare-name icons are re-declared as-is; a CUSTOM (unmanaged) web resource referenced by a PLATFORM@@ -760,6 +1027,9 @@ async function runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLosprocess.stderr.write(`(dashboards reconstruction skipped: ${e.message})\n`);}+ // Captured by the descriptionInventory accessor below so the role-restriction warning can read it+ // without making a second query.+ let capturedInventory;const read = {// Ensure the app's REAL uniquename reaches hydrateSpec (→ spec.app.uniqueName) even if the artifact// read didn't surface it: `appUnique` is the authoritative value (from the appmodule query) and is@@ -772,8 +1042,23 @@ async function runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLosdashboards: async () => dashboards,solution: async () => solution,design: async () => (manifest ? manifest.design : undefined),+ // Captured on the way past so the role-restriction warning below can read it. The accessor stays+ // a function (hydrateSpec's contract) and is still called exactly once, so this adds no query.+ descriptionInventory: async () => {+ capturedInventory = await readDescriptionInventory(sdk, appId, solution.uniqueName);+ return capturedInventory;+ },};const spec = await hydrateSpec(read);++ // A form restricted to particular security roles. `forms[]` is not reconstructed by this download,+ // so nothing carries the restriction forward: rebuilding into a FRESH environment regenerates the+ // form with no `<DisplayConditions>`, and a form with none is offered to EVERY role. Every other+ // download gap loses a customization; this one silently WIDENS access, so it is named explicitly.+ const restricted = (capturedInventory && capturedInventory.roleRestrictedForms) || [];+ if (restricted.length) {+ process.stderr.write(`WARNING: ${restricted.length} form(s) are restricted to specific security roles (${restricted.map((f) => `${f.entity}.${f.name}`).join(', ')}). This download does not reconstruct forms[], so that restriction is NOT carried into the spec — rebuilding into a fresh environment would recreate them visible to EVERY role. Re-declare it with forms[].securityRoles before a cross-environment rebuild.\n`);+ }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, dashboardWarnings };@@ -895,4 +1180,4 @@ if (require.main === module) {main().catch((err) => emitResult(false, err));}-module.exports = { resolveAppId, collectSitemap, appComponentEntities, parseDownloadedPages, assignPageKeys, missingDownloads, entityFromMetadata, iconWebResources, readDashboards, droppedSubareaCount, recoverAppSolution, runDownload, preserveAuthoredLanguageCode };+module.exports = { untypedColumnNames, isRoleRestrictedFormXml, resolveAppId, collectSitemap, appComponentEntities, parseDownloadedPages, assignPageKeys, missingDownloads, entityFromMetadata, readEntityWithDescriptions, readDescriptionInventory, 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 4b170e911..2de8d307a 100644--- a/plugins/model-apps/scripts/lib/ai-app-settings.js+++ b/plugins/model-apps/scripts/lib/ai-app-settings.js@@ -24,18 +24,38 @@ 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.+ // The AI form-fill FAMILY. `FormFillBarUXEnabled` is only the assist toolbar; the SDK now models+ // the three siblings as first-class features too, so the App Spec exposes them rather than+ // pretending "form fill" is one switch.+ //+ // Note `formFillSmartPaste` writes `FormPredictSmartPasteEnabledOnByDefault` per app while its ORG+ // GATE is `FormPredictSmartPasteEnabled` — a different row, like nlSearch. Mirrors the SDK's+ // `APP_SETTING`; the gate names live in the SDK's `AI_GATE`.formFill: 'FormFillBarUXEnabled',+ formFillSuggestions: 'FormPredictEnabled',+ formFillSmartPaste: 'FormPredictSmartPasteEnabledOnByDefault',+ formFillFiles: 'FormFillFileUploadEnabled',nlSearch: 'NLGridSearchSetting',nlChart: 'NLChartDataVisualizationSetting',m365: 'm365copilotmodelappenabled',};+// ON/OFF values are NOT uniform across these settings, and `1` is not universally "on".+//+// MIRRORS the SDK's `SETTING_CODEC` (api/AiApi.ts), which cites the first-party admin UI:+// FormFillBarUXEnabled / formPredictEnabled / smart-paste-on-by-default:+// 0 = default (defer to flighting) 1 = DISABLED 2 = ENABLED+// So the obvious `true -> '1'` mapping writes DISABLED for every one of them, and `0` means+// "platform default", which is NOT the same as off. Settings absent from this table keep the plain+// numeric convention ('1' on, '0' off) — deliberately, because their semantics are not evidenced+// the same way.+const AI_SETTING_CODEC = {+ formFill: { enabled: '2', disabled: '1' },+ formFillSuggestions: { enabled: '2', disabled: '1' },+ formFillSmartPaste: { enabled: '2', disabled: '1' },+ formFillFiles: { enabled: '2', disabled: '1' },+};+// Derived, never hand-maintained: the validator's allow-list IS the set of features we can write.const AI_FEATURE_KEYS = new Set(Object.keys(AI_APP_SETTING));@@ -65,13 +85,22 @@ function resolveAiFlags(spec) {}/**- * Normalize a requested flag to the string the numeric setting stores. `true`/`false` are the- * ergonomic spellings of `'1'`/`'0'`; any other integer (e.g. 2 = "on for everyone") is used- * verbatim. Mirrors the SDK's `settingValueOf`, minus its throwing validation — the spec validator- * has already rejected out-of-range values by the time this runs.+ * Normalize a requested flag to the string the setting actually stores.+ *+ * `true`/`false` are ergonomic spellings, but what they MEAN is per setting: for the AI form-fill+ * family on is `'2'` and off is `'1'` (`'0'` is the platform default, not off), while everything else+ * keeps the plain `'1'`/`'0'` convention. Any explicit integer is used verbatim.+ *+ * `feature` is required for a codec-governed setting. Without it a boolean maps to `'1'`, which for+ * the form-fill family means DISABLED — and since the build writes through the SDK (which applies+ * the codec), a verifier using the wrong spelling reports a correctly-applied feature as missing.+ * That mismatch is the reason this takes a feature at all.*/-function featureWantValue(requested) {- return typeof requested === 'boolean' ? (requested ? '1' : '0') : String(requested).trim();+function featureWantValue(requested, feature) {+ if (typeof requested !== 'boolean') return String(requested).trim();+ const codec = feature && AI_SETTING_CODEC[feature];+ if (codec) return requested ? codec.enabled : codec.disabled;+ return requested ? '1' : '0';}/**@@ -212,16 +241,29 @@ async function effectiveSettingValue(read, appModuleId, setting) {}/**- * 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.+ * Is a setting value "on" FOR THIS FEATURE?+ *+ * Values are stored as STRINGS ("0"/"1"/"2"/"true"/"false"), so plain JS truthiness is wrong twice+ * over — it calls "0" true and "false" true. Worse, the numeric meaning is not uniform: for the+ * AI form-fill family `1` means DISABLED and `2` means ENABLED, so a "non-zero is on" rule reports a+ * deliberately disabled feature as running. `0` there means "platform default" (defer to flighting),+ * which is genuinely UNKNOWN rather than off — reporting it as off overstates what we know.+ *+ * `feature` is optional so existing callers keep the plain numeric convention; pass it whenever the+ * feature is known, which is every caller inside this plugin.*/-function settingIsOn(value) {+function settingIsOn(value, feature) {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 codec = feature && AI_SETTING_CODEC[feature];+ if (codec) {+ if (s === codec.enabled) return true;+ if (s === codec.disabled) return false;+ // '0' = platform default: not a claim either way.+ return undefined;+ }const n = Number(s);return Number.isNaN(n) ? undefined : n !== 0;}@@ -238,7 +280,8 @@ function odataGuid(id) {}module.exports = {- AI_APP_SETTING,+ AI_APP_SETTING,+ AI_SETTING_CODEC,AI_FEATURE_KEYS,AI_FEATURE_MAX_VALUE,DEFAULT_APP_FEATURES,diff --git a/plugins/model-apps/scripts/lib/app-spec.js b/plugins/model-apps/scripts/lib/app-spec.jsindex 932b9dd6e..d5e210663 100644--- a/plugins/model-apps/scripts/lib/app-spec.js+++ b/plugins/model-apps/scripts/lib/app-spec.js@@ -379,27 +379,52 @@ const DIRECT_ENTRY_BEHAVIORS = ['selector', 'emptyState'];// 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.+// Whole Number display Format (AB#6648522). MIRRORS the vendored SDK's `integerFormat` union+// (types/schema.ts) exactly, same reasoning as COLUMN_VISUALIZATIONS above — widening one without+// the other produces a mid-build InvalidArgumentError instead of a spec-gate rejection.//-// 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.+// 'None' is the platform default (plain integer). It is accepted here, same as visualization's+// 'None', so a spec can explicitly clear a Format set by an earlier build or a maker in the portal.+// Unlike visualization, this is Integer-type-only — the SDK throws InvalidArgumentError for any+// other numeric type (BigInt/Decimal/Double/Money), so validated below alongside the enum check.+const INTEGER_FORMATS = ['None', 'Duration', 'TimeZone', 'Language', 'Locale'];++// Business rules. These MIRROR the vendored SDK's supported slice.+//+// The list is the SDK's operator TABLE, not a subset of it, and that table is the authority for a+// sharp reason: the serializer resolves an operator with+// `Uf[operator] ?? WorkflowConditionOperator.Equal`, so an operator it does not know becomes+// **Equals**. `IsGreaterThan` is in the table; `GreaterThan` is not — writing the latter silently+// deploys an equality test. That is a wrong rule behind a green build, which is exactly what this+// gate exists to prevent, so `business-rules.test.js` pins this list against the bundle's own table.+//+// The list was four entries long for a long time. That was never a platform limit: the SDK used to+// fall back to a client-side workflow-XAML compiler that could only express those four, and the+// restriction outlived it. The compiler has been deleted upstream, so the JSON path's full table is+// available.+const BUSINESS_RULE_OPERATORS = [+ 'Equals', 'DoesNotEqual',+ 'IsGreaterThan', 'IsGreaterThanEqualTo', 'IsLessThan', 'IsLessThanEqualTo',+ 'Contains', 'DoesNotContain',+ 'BeginsWith', 'DoesNotBeginWith', 'EndsWith', 'DoesNotEndWith',+ 'On', 'NotOn',+ 'ContainsData', 'DoesNotContainData',+];+// Nothing is blocked at present. Kept (empty) so a future platform-side breakage can be re-declared+// here with an explanation, rather than being folded into "unknown operator".+const BUSINESS_RULE_BLOCKED_OPERATORS = new Set();+// Operators that take NO value: they test presence, so a `value` would be meaningless. Measured —+// the serializer emits an EMPTY right-hand operand list for exactly these two.const BUSINESS_RULE_VALUELESS_OPERATORS = new Set(['ContainsData', 'DoesNotContainData']);// action type -> the field carrying its payload. `null` = no payload (none currently).+//+// The SDK models seven action types (adding `SetDefaultValue`, `ShowErrorMessage` and+// `Recommendation`), and all seven were measured serializing correctly through the real bundle.+// They are deliberately NOT exposed yet: each needs new mapping in `businessRuleDef`, and business+// rules cannot be exercised end to end on an environment that does not declare+// `CreateProcessWithWfomJson` — which is the environment this was developed against. Shipping+// mapping code that has never round-tripped against the platform is how a rule deploys and quietly+// does the wrong thing. Expose them from an environment where they can be live-verified.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@@ -409,12 +434,18 @@ const BUSINESS_RULE_BOOLEAN_ACTIONS = new Set(['SetVisibility', 'LockUnlock', 'S// 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.+// This list has NO counterpart in the bundle any more, and nothing pins it. It used to mirror the+// XAML compiler's literal-type map, which this SDK uptake deleted along with the compiler.+//+// MEASURED against the replacement JSON path: `dataType` is IGNORED. Across all ten tokens below —+// and a made-up one — on both the condition path and the SetFieldValue action path, the serializer+// emits WorkflowAttributeType String ("14") every time:+// let r = valueType==='Lookup' ? … : valueType==='Clear' ? (valueWorkflowType ?? String)+// : WorkflowAttributeType.String+// So this is a curated closed set kept for two reasons only: it catches a typo at the spec gate, and+// it keeps the surface forward-compatible if the SDK starts honouring the field. Do NOT add a token+// on the assumption a test will validate it against the SDK — no such test can exist while there is+// nothing to validate against. `business-rules.test.js` instead pins the measured no-op.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.@@ -488,6 +519,282 @@ function quickCreateEnabledFor(spec, entity) {);}+// A maker-facing `description`, supported on every artifact whose SDK create surface accepts one+// (table, column, view, chart, form, dashboard, business rule, app, web resource).+//+// Deliberately a soft contract: descriptions are OPTIONAL, because making them mandatory would fail+// every spec authored before they existed. What is validated is only that a supplied value is usable+// — a number or an object here means the author meant something else, and silently stringifying it+// would write "[object Object]" into Dataverse.+//+// 2000 is the Dataverse ceiling for a description Label; the platform truncates past it rather than+// erroring, so catching it here is the only place the author finds out.+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/entity-attribute-metadata+const DESCRIPTION_MAX = 2000;+function validateDescription(value, label, errors, opts = {}) {+ if (value === undefined || value === null) return;+ if (typeof value !== 'string') {+ errors.push(`${label}: description must be a string`);+ return;+ }+ // `app.description` predates this contract and countless existing specs (and every spec emitted by+ // `download-model-app`) carry it as `""`. Rejecting that would fail specs that are otherwise fine,+ // so emptiness is tolerated exactly where it is already established — never for a NEW surface,+ // where an empty string is the one value that could blank a maker's text on rebuild.+ if (!value.trim()) {+ if (opts.allowEmpty) return;+ errors.push(`${label}: description must not be blank — omit the field instead of setting an empty string`);+ return;+ }+ if (value.length > DESCRIPTION_MAX) {+ errors.push(`${label}: description is ${value.length} characters (max ${DESCRIPTION_MAX})`);+ }+}++// Per-control form-field options: `readOnly`, `hidden`, `after`.+//+// Reachable two ways — inline on an EXPLICIT layout's `sections[].fields[]` entry, or via the+// form-level `fieldOptions` map (the only route under an AUTO layout, which has no field list).+//+// Only the ENABLED state is written by the build (`isReadOnly: true` / `visible: false`); `false` is+// a no-op rather than an un-set, so it is rejected here instead of being accepted and quietly+// ignored — an author who writes `readOnly: false` expecting it to clear an existing lock would+// otherwise get a green build and no change.+// `forms[].securityRoles` — who a form is offered to. AB#6648526.+//+// Direction matters and is easy to get backwards: a form with NO assignment is offered to EVERY+// role, so declaring this RESTRICTS the form. That makes every failure mode here access-relevant —+// a typo'd persona or an empty list narrows a form to nobody — so each is a hard error rather than+// a warning, and the build additionally halts on an unresolvable persona.+//+// `everyone` and `roleIds` are mutually exclusive in the PLATFORM's model (`<Everyone />` replaces+// the `<Role>` list rather than adding to it), not merely in this validator; the SDK rejects the+// combination with INVALID_ARGUMENT, so catching it here just names the form.+function validateFormSecurityRoles(f, spec, errors) {+ const sr = f.securityRoles;+ if (sr === undefined) return;+ const label = `form '${f.name || f.entity}'`;+ if (!sr || typeof sr !== 'object' || Array.isArray(sr)) {+ errors.push(`${label}: securityRoles must be an object like { "personas": ["Dispatcher"] } or { "everyone": true }`);+ return;+ }+ const known = new Set(['personas', 'everyone', 'fallbackForm', 'order']);+ for (const k of Object.keys(sr)) {+ if (!known.has(k)) errors.push(`${label}: securityRoles has unknown key '${k}' — expected ${[...known].join(', ')}`);+ }++ const hasEveryone = sr.everyone !== undefined;+ if (hasEveryone && typeof sr.everyone !== 'boolean') {+ errors.push(`${label}: securityRoles.everyone must be a boolean`);+ }+ // `everyone: false` is not "restrict to nobody" — it is an author reaching for a switch that does+ // not exist.+ if (sr.everyone === false) {+ errors.push(`${label}: securityRoles.everyone: false does nothing — use "everyone": true to make the form available to every role again, or list personas to restrict it`);+ }++ if (sr.personas !== undefined) {+ if (!Array.isArray(sr.personas) || sr.personas.some((p) => typeof p !== 'string' || !p.trim())) {+ errors.push(`${label}: securityRoles.personas must be an array of persona names`);+ } else if (!sr.personas.length) {+ errors.push(`${label}: securityRoles.personas is empty — that would offer the form to NO role. List at least one persona, or use "everyone": true.`);+ } else {+ // Resolved against `personas[]` at author time so a typo is a spec error naming the form,+ // rather than a build halt two minutes into a run.+ const declared = new Set((spec.personas || []).map((p) => String(canonicalPersonaName(p) || '').toLowerCase()));+ for (const p of sr.personas) {+ if (!declared.has(String(p).trim().toLowerCase())) {+ errors.push(`${label}: securityRoles names persona '${p}', which is not declared in personas[]`);+ }+ }+ const dupes = sr.personas.map((p) => String(p).trim().toLowerCase()).filter((p, i, a) => a.indexOf(p) !== i);+ if (dupes.length) errors.push(`${label}: securityRoles lists persona '${dupes[0]}' more than once`);+ }+ }++ if (sr.everyone === true && sr.personas !== undefined) {+ errors.push(`${label}: securityRoles cannot set both 'everyone' and 'personas' — the platform models <Everyone /> as a replacement for the role list, not an addition to it`);+ }+ if (!hasEveryone && sr.personas === undefined) {+ errors.push(`${label}: securityRoles must say who the form is for — set 'personas' or 'everyone': true`);+ }++ if (sr.fallbackForm !== undefined && typeof sr.fallbackForm !== 'boolean') {+ errors.push(`${label}: securityRoles.fallbackForm must be a boolean`);+ }+ if (sr.order !== undefined && (!Number.isInteger(sr.order) || sr.order < 0)) {+ errors.push(`${label}: securityRoles.order must be a non-negative integer (got ${JSON.stringify(sr.order)})`);+ }++ // The build addresses this form by (entity, formType, name) — `created.forms` is keyed by entity+ // and holds only the Main form, so a later phase cannot reach a sibling any other way. Duplicate+ // (entity, formType, name) is otherwise LEGAL here: only QuickView forms are checked for a unique+ // (entity, name), because Main and Card may both be called "Information" harmlessly.+ //+ // Harmless, that is, until one of them declares securityRoles: the map would keep whichever was+ // built last, and the restriction would land on the wrong form while every structural check passed+ // and the build reported success. Reject the ambiguity instead of picking a winner.+ const twin = (spec.forms || []).filter((o) => o+ && String(o.entity || '').toLowerCase() === String(f.entity || '').toLowerCase()+ && (o.formType || 'Main') === (f.formType || 'Main')+ && String(o.name || '') === String(f.name || ''));+ if (twin.length > 1) {+ errors.push(`${label}: securityRoles needs a form this spec can identify unambiguously, but ${twin.length} forms share (entity ${f.entity}, type ${f.formType || 'Main'}, name '${f.name || ''}') — rename one, or move the assignment to the form you meant`);+ }+}++function validateFormFieldOptions(f, entityByLower, errors, warnings) {+ const label = `form '${f.name || f.entity}'`;+ const entity = entityByLower.get(String(f.entity || '').toLowerCase());+ const columnType = (logical) => {+ if (!entity) return undefined;+ const c = (entity.columns || []).find((x) => x && x.schemaName && x.schemaName.toLowerCase() === logical);+ return c && (c.type || 'Text');+ };+ const explicit = Array.isArray(f.tabs) || f.layout === 'explicit';+ // Every field this form declares an option for, from either route, so the checks below run once+ // per (field, source) pair with a source-accurate message.+ const seen = [];+ // Fields the EXPLICIT layout lists by position. An `after` anchor for one of these — from either+ // route — would give the form two competing orderings.+ const listedByLayout = new Set();++ for (const t of (Array.isArray(f.tabs) ? f.tabs : [])) {+ for (const s of ((t && t.sections) || [])) {+ if (s && s.fields !== undefined && !Array.isArray(s.fields)) {+ // Guard the compiler, which does `(s.fields || []).map(...)`. A string is ITERABLE and every+ // character of it IS a string, so a `fields: "new_name"` typo would pass a naive per-entry+ // check and then throw a raw TypeError at compile time instead of producing a finding. A+ // non-iterable value (`{}`, `3`) would throw right here. Note `spec-shape.js` does not model+ // `fields`, so `normalizeSpecShape` does not coerce it — this check is load-bearing.+ errors.push(`${label}: a section's fields must be an array of column logical names`);+ continue;+ }+ for (const entry of ((s && s.fields) || [])) {+ if (entry && typeof entry === 'object' && !Array.isArray(entry)) {+ if (!entry.name || typeof entry.name !== 'string') {+ errors.push(`${label}: a field entry object is missing a string 'name'`);+ continue;+ }+ listedByLayout.add(String(entry.name).toLowerCase());+ seen.push({ name: String(entry.name).toLowerCase(), opt: entry, where: `field '${entry.name}'`, inline: true });+ } else if (typeof entry === 'string') {+ listedByLayout.add(entry.toLowerCase());+ } else {+ errors.push(`${label}: a field entry must be a column logical name or an object { name, readOnly?, hidden?, after? }`);+ }+ }+ }+ }++ if (f.fieldOptions !== undefined) {+ if (!f.fieldOptions || typeof f.fieldOptions !== 'object' || Array.isArray(f.fieldOptions)) {+ errors.push(`${label}: fieldOptions must be an object keyed by column logical name`);+ } else {+ for (const key of Object.keys(f.fieldOptions)) {+ const v = f.fieldOptions[key];+ if (!v || typeof v !== 'object' || Array.isArray(v)) {+ errors.push(`${label}: fieldOptions['${key}'] must be an object { readOnly?, hidden?, after? }`);+ continue;+ }+ seen.push({ name: String(key).toLowerCase(), opt: v, where: `fieldOptions['${key}']`, inline: false });+ }+ }+ }++ for (const { name, opt, where, inline } of seen) {+ for (const flag of ['readOnly', 'hidden']) {+ if (opt[flag] === undefined) continue;+ if (typeof opt[flag] !== 'boolean') {+ errors.push(`${label}: ${where} ${flag} must be a boolean`);+ } else if (opt[flag] === false) {+ errors.push(`${label}: ${where} sets ${flag}: false, which the build cannot apply — it only ever writes the ENABLED state, so a maker's existing setting is never silently cleared. Omit the flag, or clear it in the form designer.`);+ }+ }+ if (opt.after !== undefined) {+ if (typeof opt.after !== 'string' || !opt.after.trim()) {+ errors.push(`${label}: ${where} after must be the logical name of another field on this form`);+ } else if (String(opt.after).toLowerCase() === name) {+ errors.push(`${label}: ${where} anchors '${name}' after itself`);+ } else if (inline || listedByLayout.has(name)) {+ // An explicit layout already expresses order by listing position, so honouring `after` for a+ // listed field would give the form two competing orderings — and they would DISAGREE: the+ // create path follows the authored list, while the reconcile applies the anchor, so the same+ // spec would produce one order on a new form and another on the first rebuild.+ // A form-level anchor for a field the layout does NOT list stays legal: that is the+ // `prune: false` case, where the point is to position a control on a deployed form without+ // re-declaring the rest of it.+ errors.push(`${label}: ${where} cannot use 'after' for a field an explicit tabs layout already lists — the listed order positions it. Move it in the list instead, or drop it from the list if you mean to position it against fields this layout does not declare.`);+ }+ }+ // A BigInt has no Unified Interface control, so a form placement renders "Error loading control".+ // Auto layout skips them outright; an explicit layout still honours the author, but declaring+ // per-control options for one is almost certainly a mistake worth surfacing.+ if (columnType(name) === 'BigInt') {+ warnings.push(`${label}: ${where} targets '${name}', a BigInt column — Big Integer has no Unified Interface form control, so it renders "Error loading control" wherever it is placed`);+ }+ }++ // Two contradictory anchor shapes. Both are silently unstable rather than wrong-but-stable: the+ // reconcile moves each field to its anchor on every build and they undo each other, so the form+ // never converges and a rebuild issues writes forever. Neither can be resolved automatically —+ // "immediately after X" cannot be true of two fields at once, and a cycle has no valid order — so+ // they are rejected at author time instead of being papered over by the placement code.+ const anchorOf = new Map();+ for (const { name, opt } of seen) {+ if (opt.after && typeof opt.after === 'string') anchorOf.set(name, String(opt.after).toLowerCase());+ }+ const claimants = new Map();+ for (const [name, anchor] of anchorOf) {+ if (!claimants.has(anchor)) claimants.set(anchor, []);+ claimants.get(anchor).push(name);+ }+ for (const [anchor, names] of claimants) {+ if (names.length > 1) {+ errors.push(`${label}: ${names.map((n) => `'${n}'`).join(' and ')} are both anchored after '${anchor}' — only one field can sit immediately after another. Chain them instead (anchor the second one after the first).`);+ }+ }+ for (const start of anchorOf.keys()) {+ const seenInWalk = new Set([start]);+ let cur = anchorOf.get(start);+ while (cur !== undefined) {+ if (seenInWalk.has(cur)) {+ if (cur === start) errors.push(`${label}: the 'after' anchors form a cycle through '${start}' — there is no order that satisfies them all.`);+ break;+ }+ seenInWalk.add(cur);+ cur = anchorOf.get(cur);+ }+ }++ if (f.prune !== undefined) {+ if (typeof f.prune !== 'boolean') {+ errors.push(`${label}: prune must be a boolean`);+ } else if (f.prune === false && !explicit) {+ warnings.push(`${label}: prune: false has no effect on an auto layout — an auto layout is already additive and never removes a field`);+ }+ }++ // An explicit layout that names a BigInt column produces a broken control on a live record. It is a+ // warning, not an error: the author asked for it by name and may be pairing it with a custom control.+ if (explicit) {+ for (const t of (Array.isArray(f.tabs) ? f.tabs : [])) {+ for (const s of ((t && t.sections) || [])) {+ // Re-guard: the array check in the first loop `continue`s that loop only. Without repeating+ // it here a non-iterable `fields` (e.g. `{}` or `3`) throws a raw TypeError out of+ // validateAppSpec — discarding the correct finding the first loop already pushed.+ if (!Array.isArray(s && s.fields)) continue;+ for (const entry of s.fields) {+ const nm = String((entry && typeof entry === 'object' ? entry.name : entry) || '').toLowerCase();+ if (nm && columnType(nm) === 'BigInt') {+ warnings.push(`${label}: field '${nm}' is a BigInt column — Big Integer has no Unified Interface form control, so it will render "Error loading control" on every record. Keep it off the form (it stays readable through the API).`);+ }+ }+ }+ }+ }+}+function validateAppSpec(spec, opts = {}) {const profile = opts.profile || 'deploy';const errors = [];@@ -515,6 +822,12 @@ function validateAppSpec(spec, opts = {}) {if (!spec.app || !spec.app.name) {errors.push('app.name is required');}+ validateDescription(spec.solution && spec.solution.description, 'solution', errors);+ // allowEmpty: `app.description: ""` is the established shape (download-model-app emits it).+ validateDescription(spec.app && spec.app.description, 'app', errors, { allowEmpty: true });+ for (const gc of spec.globalChoices || []) {+ validateDescription(gc && gc.description, `globalChoice '${(gc && gc.name) || '(unnamed)'}'`, errors);+ }// 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@@ -546,10 +859,19 @@ function validateAppSpec(spec, opts = {}) {if (e.quickCreate !== undefined && typeof e.quickCreate !== 'boolean') {errors.push(`entity ${e.schemaName}: quickCreate must be a boolean`);}+ validateDescription(e.description, `entity ${e.schemaName}`, errors);for (const c of e.columns || []) {if (!c.schemaName) {errors.push(`entity ${e.schemaName}: a column is missing schemaName`);}+ validateDescription(c.description, `entity ${e.schemaName}: column ${c.schemaName}`, errors);+ // A Customer column is created through `createCustomerColumn`, whose payload is only+ // { Lookup, OneToManyRelationships } — the SDK has nowhere to put a description, so one+ // authored here is silently discarded. Warn rather than error: the spec is still valid and+ // still builds; the author just needs to know the value will not appear in Dataverse.+ if (c.type === 'Customer' && c.description) {+ warnings.push(`entity ${e.schemaName}: column ${c.schemaName} is a Customer column — the SDK's createCustomerColumn accepts no description, so this one will NOT be written to Dataverse`);+ }if (c.type && !TYPE_MAP[c.type]) {errors.push(`entity ${e.schemaName}: column ${c.schemaName} has unknown type '${c.type}'`);}@@ -564,6 +886,52 @@ function validateAppSpec(spec, opts = {}) {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('|')}`);}+ // AB#6648523: Boolean default value. The SDK used to hardcode `DefaultValue: false`; the+ // vendored bundle now honours an explicit value on create AND update (measured against+ // cds-maker-sdk.cjs). Boolean-only for the same reason as the form-event flags below — a+ // truthy-but-non-boolean value (e.g. the string "false") must be rejected, not coerced — and+ // type-gated to the exact 'Boolean' column: the SDK itself throws InvalidArgumentError for+ // defaultValue on any other type, so this just moves that same failure to the spec gate and+ // names the column instead of surfacing mid-build.+ if (c.defaultValue !== undefined) {+ if (typeof c.defaultValue !== 'boolean') {+ errors.push(`entity ${e.schemaName}: column ${c.schemaName} defaultValue must be a boolean (got ${JSON.stringify(c.defaultValue)})`);+ } else if (c.type !== 'Boolean') {+ errors.push(`entity ${e.schemaName}: column ${c.schemaName} defaultValue is only valid on a Boolean column (this one is '${c.type || 'Text'}')`);+ }+ }+ // AB#6648522: Whole Number display Format (e.g. render a raw integer count of minutes as a+ // Duration picker in the maker UI). Restricted to the exact 'Integer' App Spec type, NOT the+ // wider Integer/BigInt/Decimal/Double/Money switch case columnOptions() shares for min/max/+ // precision — the SDK's Format option is Integer-only, so a spec targeting Decimal would+ // otherwise pass this gate and hit the SDK's own InvalidArgumentError deep inside the+ // data-model phase instead of here.+ if (c.integerFormat !== undefined) {+ if (!INTEGER_FORMATS.includes(c.integerFormat)) {+ errors.push(`entity ${e.schemaName}: column ${c.schemaName} has unknown integerFormat '${c.integerFormat}' — must be one of ${INTEGER_FORMATS.join('|')}`);+ } else if (c.type !== 'Integer') {+ errors.push(`entity ${e.schemaName}: column ${c.schemaName} integerFormat is only valid on an Integer column (this one is '${c.type || 'Text'}')`);+ }+ }+ // AB#6651276: per-verb write/read permissions (e.g. isValidForUpdate:false makes a column+ // write-once after creation — the entire point of the feature, so `false` must validate and+ // build identically to `true`). Boolean-only, same reasoning as the form-event flags below.+ // Type-agnostic per the SDK — every buildable column type accepts these on BOTH create and+ // update (measured) — EXCEPT Customer, which is created through createCustomerColumn, a+ // wholly separate SDK call whose options carry no such fields. Warned rather than rejected+ // there, matching the Customer + description precedent above: the spec stays valid and still+ // builds, the author just needs to know the flag will not reach Dataverse.+ let hasValidForFlag = false;+ for (const flag of ['isValidForCreate', 'isValidForUpdate', 'isValidForRead']) {+ if (c[flag] === undefined) continue;+ hasValidForFlag = true;+ if (typeof c[flag] !== 'boolean') {+ errors.push(`entity ${e.schemaName}: column ${c.schemaName} ${flag} must be a boolean (got ${JSON.stringify(c[flag])})`);+ }+ }+ if (hasValidForFlag && c.type === 'Customer') {+ warnings.push(`entity ${e.schemaName}: column ${c.schemaName} is a Customer column — the SDK's createCustomerColumn accepts no isValidForCreate/isValidForUpdate/isValidForRead, so these will NOT be written to Dataverse`);+ }}}if (!entityNames.size) {@@ -579,6 +947,7 @@ function validateAppSpec(spec, opts = {}) {const rasterWebResourceNames = new Set(); // png/jpg/gif/ico — valid for a table's raster iconfor (const wr of spec.webResources || []) {if (!wr || !wr.name) { errors.push('a webResource is missing a name'); continue; }+ validateDescription(wr.description, `webResource '${wr.name}'`, errors);webResourceNames.add(wr.name.toLowerCase());const wrType = String(wr.type || '').toLowerCase();if (IMAGE_WR_TYPES.has(wrType)) imageWebResourceNames.add(wr.name.toLowerCase());@@ -614,6 +983,7 @@ function validateAppSpec(spec, opts = {}) {}}for (const f of spec.forms || []) {+ validateDescription(f.description, `form '${f.name || f.entity}'`, errors);if (!entityNames.has(f.entity)) {errors.push(`form references unknown entity '${f.entity}'`);}@@ -689,6 +1059,16 @@ function validateAppSpec(spec, opts = {}) {}}}+ validateFormFieldOptions(f, entityByLower, errors, warnings);+ validateFormSecurityRoles(f, spec, errors);+ // `layout: 'explicit'` with no `tabs[]` is a spec that asks for one thing and builds another.+ // `compileFormIntent` takes the explicit path only when `tabs` is an ARRAY, so this combination+ // silently compiles an AUTO layout — while `prune` and the field-positioning rules read as+ // explicit-layout behaviour to the author. Rejected rather than warned: the two layouts differ in+ // whether a rebuild REMOVES deployed fields, so guessing wrong is destructive.+ if (f && f.layout === 'explicit' && !Array.isArray(f.tabs)) {+ errors.push(`form '${f.name || f.entity}': layout is 'explicit' but no tabs[] were authored — an explicit layout IS its tabs. Author tabs[], or drop layout: 'explicit' to use the auto layout.`);+ }}// Two QuickView forms sharing (entity, name) make a quick-view reference — which resolves a QuickView by// (targetEntity, name) — ambiguous (the build map keeps only one, order-dependently). Reject the@@ -702,6 +1082,7 @@ function validateAppSpec(spec, opts = {}) {qvIdentity.add(key);}for (const ch of spec.charts || []) {+ validateDescription(ch && ch.description, `chart '${(ch && (ch.name || ch.entity)) || '(unnamed)'}'`, errors);if (!ch || !ch.entity || !entityByLower.has(String(ch.entity).toLowerCase())) {errors.push(`chart references unknown entity '${ch && ch.entity}'`);continue;@@ -723,6 +1104,7 @@ function validateAppSpec(spec, opts = {}) {}}for (const v of spec.views || []) {+ validateDescription(v && v.description, `view '${(v && (v.name || v.entity)) || '(unnamed)'}'`, errors);if (!entityNames.has(v.entity)) {errors.push(`view references unknown entity '${v.entity}'`);}@@ -740,6 +1122,12 @@ function validateAppSpec(spec, opts = {}) {};for (const c of spec.commands || []) {if (!c || !c.entity || !entityNames.has(c.entity)) { errors.push(`command references unknown entity '${c && c.entity}'`); continue; }+ // The SDK's command surface drops `description` (the artifact it returns carries only+ // commandBars/entityLogicalName/id), so one authored here never reaches Dataverse. Warn rather+ // than error — the spec is otherwise valid — but do not let it pass silently.+ if (c.description) {+ warnings.push(`command '${c.label || c.entity}': the SDK's command surface accepts no description, so this one will NOT be written to Dataverse`);+ }if (!c.label) errors.push(`command on ${c.entity}: label is required`);if (c.location && !COMMAND_LOCATIONS.has(c.location)) errors.push(`command '${c.label}' on ${c.entity}: location must be MainTab|HomeTab|ContextualTab`);const type = c.type || 'Button';@@ -761,6 +1149,7 @@ function validateAppSpec(spec, opts = {}) {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; }+ validateDescription(r.description, label, errors);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)) {@@ -789,18 +1178,25 @@ function validateAppSpec(spec, opts = {}) {};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)`);+ errors.push(`${label}: conditions[] is required (a rule with no condition would apply unconditionally, which the SDK serializes 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.+ // who reaches for a blocked operator 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`);+ errors.push(`${label}: operator '${c.operator}' is not usable — see 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}')`);+ // The near-misses matter more than the nonsense here. `GreaterThan` is a natural thing to+ // write and is NOT in the SDK's table, and the serializer resolves an unknown operator to+ // Equals — so without this gate that spec would deploy an equality test. Name the closest+ // legal spelling so the fix is obvious.+ const near = BUSINESS_RULE_OPERATORS.find((o) => o.toLowerCase() === `is${String(c.operator).toLowerCase()}`+ || o.toLowerCase().replace(/^is/, '') === String(c.operator).toLowerCase()+ || o.toLowerCase() === String(c.operator).toLowerCase());+ errors.push(`${label}: condition operator must be one of ${BUSINESS_RULE_OPERATORS.join('|')} (got '${c.operator}')${near ? ` — did you mean '${near}'?` : ''}`);}continue;}@@ -812,9 +1208,9 @@ function validateAppSpec(spec, opts = {}) {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.+ // Name the offending value: this is a curated closed set with no bundle counterpart, 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('|')}`);}}@@ -848,6 +1244,7 @@ function validateAppSpec(spec, opts = {}) {const chartNamesSet = new Set((spec.charts || []).map((c) => c.name));for (const d of spec.dashboards || []) {if (!d || !d.name) { errors.push('a dashboard is missing a name'); continue; }+ validateDescription(d.description, `dashboard '${d.name}'`, errors);if (!Array.isArray(d.tiles) || !d.tiles.length) { errors.push(`dashboard '${d.name}': needs tiles[]`); continue; }for (const t of d.tiles) {if (!t || !DASH_TILE_TYPES.has(t.type)) { errors.push(`dashboard '${d.name}': tile type must be chart|list|iframe|webresource`); continue; }@@ -1546,6 +1943,7 @@ module.exports = {VALIDATION_PROFILES,DIRECT_ENTRY_BEHAVIORS,COLUMN_VISUALIZATIONS,+ INTEGER_FORMATS,BUSINESS_RULE_OPERATORS,BUSINESS_RULE_VALUELESS_OPERATORS,BUSINESS_RULE_ACTIONS,diff --git a/plugins/model-apps/scripts/lib/artifact-intent.js b/plugins/model-apps/scripts/lib/artifact-intent.jsindex 3792ff58f..9b9780fd1 100644--- a/plugins/model-apps/scripts/lib/artifact-intent.js+++ b/plugins/model-apps/scripts/lib/artifact-intent.js@@ -40,6 +40,13 @@ function rowsFromCells(cells, columns) {// supply an explicit label override (e.g. a renamed lookup whose display name in// Dataverse differs from what the App Spec wants to show). Do not pass it for ordinary// fields — the adapter handles them.+//+// opts.readOnly / opts.hidden are the two per-control attributes the SDK's FormXml serializer+// actually reads (measured against the vendored bundle, not inferred from its types):+// <cell id="…" showlabel="…" visible="${cell.visible}" colspan="…" rowspan="…">+// <control id="…" classid="…" datafieldname="…" disabled="${control.isReadOnly}" isrequired="…">+// So visibility lives on the CELL and read-only lives on the CONTROL — they are not siblings, and+// writing either to the wrong object is silently dropped at serialize time.function fieldCellIntent(logical, opts) {opts = opts || {};const control = { fieldName: String(logical).toLowerCase() };@@ -48,7 +55,72 @@ function fieldCellIntent(logical, opts) {if (opts.isRequired) control.isRequired = true;// label override: rare; callers should normally let the adapter derive it from metadata.if (opts.label) control.label = opts.label;- return { control };+ // Only the ENABLED state is ever written, never the disabled one. Emitting `isReadOnly: false`+ // for every ordinary field would look harmless but is destructive on a rebuild: it would+ // overwrite a lock a maker applied by hand in the designer, on a form the spec never claimed to+ // own that attribute of. Omitting the key leaves the adapter's default (editable) in place.+ if (opts.readOnly) control.isReadOnly = true;+ const cell = { control };+ // Same asymmetry, same reason: only `visible: false` is written. An explicit `true` would+ // un-hide a control someone deliberately hid outside the spec.+ if (opts.hidden) cell.visible = false;+ return cell;+}++// Column types that have NO Unified Interface form control.+//+// A Big Integer column placed on a form renders the literal text "Error loading control" on every+// record — UCI has no editor registered for the type, so the control host fails at bind time. The+// column itself is perfectly valid and stays readable/writable through the API; it simply cannot be+// shown. Auto layout therefore skips these types rather than producing a visibly broken form out of+// the box (ADO 6651696). An EXPLICIT layout still honours the author — they may be targeting a+// custom control — but validateAppSpec emits a warning so the choice is deliberate rather than accidental.+const NON_FORM_RENDERABLE_TYPES = new Set(['BigInt']);++// Normalize one entry of `tabs[].sections[].fields[]`.+//+// An entry is either a bare logical name (the original and still most common shape) or an object+// carrying per-control options:+// "co_duedate"+// { "name": "co_ticketnumber", "readOnly": true }+// { "name": "co_storypoints", "hidden": true }+// { "name": "co_daysremaining", "after": "co_duedate" }+// Returns a canonical { name, readOnly, hidden, after } with `name`/`after` lower-cased, because+// every downstream comparison (form field logicals, cell pointers, Dataverse attribute logical+// names) is lower-case.+function normalizeFieldEntry(entry) {+ if (entry && typeof entry === 'object' && !Array.isArray(entry)) {+ return {+ name: String(entry.name || '').toLowerCase(),+ readOnly: entry.readOnly === true,+ hidden: entry.hidden === true,+ after: entry.after ? String(entry.after).toLowerCase() : undefined,+ };+ }+ return { name: String(entry || '').toLowerCase(), readOnly: false, hidden: false, after: undefined };+}++// Form-level per-field control options, keyed by column logical name:+// "fieldOptions": { "co_ticketnumber": { "readOnly": true }, "co_daysremaining": { "after": "co_duedate" } }+//+// This is the ONLY way to reach these attributes under an AUTO layout, which has no field list to+// hang an inline object off. Under an EXPLICIT layout both work and the inline entry wins, because+// the more specific declaration should not be silently overridden by a form-wide default.+function fieldOptionsMap(formSpec) {+ const map = {};+ const fo = formSpec && formSpec.fieldOptions;+ if (!fo || typeof fo !== 'object' || Array.isArray(fo)) return map;+ for (const key of Object.keys(fo)) {+ const v = fo[key];+ if (!v || typeof v !== 'object' || Array.isArray(v)) continue;+ map[String(key).toLowerCase()] = {+ name: String(key).toLowerCase(),+ readOnly: v.readOnly === true,+ hidden: v.hidden === true,+ after: v.after ? String(v.after).toLowerCase() : undefined,+ };+ }+ return map;}// Cell for the Notes/activity-timeline control.@@ -209,6 +281,49 @@ function viewColumnsIntent(cols) {});}+// Reorder a flat auto-layout cell list in place so each anchored field immediately follows its+// anchor. `positions` is { <logical>: <anchorLogical> }.+//+// Runs to a FIXED POINT rather than a single pass. A single pass walks `positions` in key order —+// which is entity-column order, not dependency order — so when a field's anchor is itself relocated+// LATER in the same walk, the earlier placement is silently invalidated. Given `y after a` and+// `x after y`, one pass can emit `[a][y][n][x]`: x is not after y, the create order violates its own+// anchors, and the first rebuild then "fixes" it — precisely the create/rebuild divergence this+// function exists to prevent.+//+// Bounded by the number of anchors: each pass either changes nothing (done) or applies at least one+// move, and a contradictory spec (a cycle, or two fields claiming the same anchor) simply exhausts+// the bound with a deterministic result rather than spinning. Both of those shapes are rejected at+// author time, so the bound is a safety net, not the normal path.+//+// An anchor that is absent (or that resolves to the field itself) is skipped rather than treated as+// an error — the anchor may name a column that is not on this form.+function reorderCellsByAnchors(cells, positions) {+ const keys = Object.keys(positions || {});+ const indexOfField = function (logical) {+ return cells.findIndex(function (c) {+ return c.control && String(c.control.fieldName || '').toLowerCase() === logical;+ });+ };+ for (let pass = 0; pass < keys.length; pass++) {+ let moved = false;+ for (const logical of keys) {+ const anchor = positions[logical];+ const from = indexOfField(logical);+ const at = indexOfField(anchor);+ if (from < 0 || at < 0 || from === at) continue;+ if (from === at + 1) continue; // already immediately after its anchor+ const [el] = cells.splice(from, 1);+ // Recompute the anchor AFTER the removal: splicing out an earlier element shifts the anchor+ // down by one, and inserting at the stale index would land the field one slot too far right.+ cells.splice(indexOfField(anchor) + 1, 0, el);+ moved = true;+ }+ if (!moved) break;+ }+ return cells;+}+// Compile an App Spec form entry into the SDK's canonical desired-state intent.//// NEW topology: tabs[] → columns[] → sections[] → rows[] → cells[].@@ -251,6 +366,30 @@ function compileFormIntent(spec, formSpec, opts) {return !!(c && c.required === true);};+ // Per-field control options come from two places; the inline entry wins (see fieldOptionsMap).+ const formOptions = fieldOptionsMap(formSpec);+ // Ordering anchors are collected here rather than written onto the cells. A cell object is pushed+ // verbatim to the SDK via addElement, and `after` is NOT part of the SDK's cell model — it would+ // either be rejected by the structural validator or silently serialized into the FormXml. The+ // engine-only `__`-prefixed keys on the returned def are never sent (createFormShell hand-picks+ // the fields it passes to createArtifact), so that is where positioning intent belongs.+ const positions = {};+ const recordPosition = function (opt) {+ if (opt && opt.after && opt.name && opt.after !== opt.name) positions[opt.name] = opt.after;+ };+ // Merge a form-level default with an inline override for one field.+ const optionsFor = function (logical, inline) {+ const base = formOptions[logical];+ if (!base) return inline || { name: logical, readOnly: false, hidden: false, after: undefined };+ if (!inline) return base;+ return {+ name: logical,+ readOnly: inline.readOnly || base.readOnly,+ hidden: inline.hidden || base.hidden,+ after: inline.after !== undefined ? inline.after : base.after,+ };+ };+let tabs;if (explicit && Array.isArray(formSpec.tabs)) {@@ -271,8 +410,10 @@ function compileFormIntent(spec, formSpec, opts) {width: '100%',sections: (t.sections || []).map(function (s, si) {const cells = (s.fields || []).map(function (fl) {- const lg = String(fl).toLowerCase();- return fieldCellIntent(lg, { isRequired: requiredFor(lg) });+ const inline = normalizeFieldEntry(fl);+ const opt = optionsFor(inline.name, inline);+ recordPosition(opt);+ return fieldCellIntent(inline.name, { isRequired: requiredFor(inline.name), readOnly: opt.readOnly, hidden: opt.hidden });});const secCols = Math.min(s.columns || 1, maxCols);return {@@ -293,20 +434,35 @@ function compileFormIntent(spec, formSpec, opts) {// Falsy (undefined) means non-scalar (Lookup, Customer, …) — skip them; they// come from relationships[], not columns[], and are added via lookupColumnsFor.const cells = [];+ const autoCell = function (logical, extra) {+ const opt = optionsFor(logical, null);+ recordPosition(opt);+ return fieldCellIntent(logical, Object.assign({ readOnly: opt.readOnly, hidden: opt.hidden }, extra || {}));+ };if (entity) {- cells.push(fieldCellIntent(entity.primaryAttribute.schemaName.toLowerCase(), { isRequired: true }));+ cells.push(autoCell(entity.primaryAttribute.schemaName.toLowerCase(), { isRequired: true }));for (let i = 0; i < (entity.columns || []).length; i++) {const c = entity.columns[i];if (!SDK_COLUMN_TYPE[c.type || 'Text']) continue;- cells.push(fieldCellIntent(c.schemaName.toLowerCase(), { isRequired: c.required === true }));+ // Skip types UCI cannot render. Auto layout is the DEFAULT, so including one of these+ // would ship a form with a broken control to every author who never asked for the column+ // to be on a form in the first place (ADO 6651696). The column is still created and still+ // reachable through the API — only the form placement is withheld.+ if (NON_FORM_RENDERABLE_TYPES.has(c.type)) continue;+ cells.push(autoCell(c.schemaName.toLowerCase(), { isRequired: c.required === true }));}// Parent lookups live on relationships[], not columns[]. Surface them so the parent// link is visible on the form; otherwise a first build shows no way to set the parent.const lookups = lookupColumnsFor(spec, entityLogical);for (let i = 0; i < lookups.length; i++) {- cells.push(fieldCellIntent(lookups[i].logical, {}));+ cells.push(autoCell(lookups[i].logical));}}+ // Apply `after` anchors to the CREATE order as well, not just the reconcile. Auto layout has no+ // authored order, so without this a fresh build would place the field by column order and the+ // first rebuild would immediately move it — the same spec producing two different forms+ // depending on whether the form already existed.+ reorderCellsByAnchors(cells, positions);// 2-column when field-heavy (> 6 cells), else 1; always capped by maxCols.const columns = Math.min(cells.length > 6 ? 2 : 1, maxCols);tabs = [{@@ -331,6 +487,21 @@ function compileFormIntent(spec, formSpec, opts) {}];}+ // Every form-level anchor is recorded, not just those for fields THIS layout places. The reconcile+ // resolves anchors against the DEPLOYED form, and positioning a control an explicit layout does not+ // re-declare is precisely the `prune: false` case the anchor exists to serve — recording only+ // placed fields made that documented (and validation-permitted) combination silently do nothing.+ // Harmless for the compile-time reorder: it already ran above, and an unplaced field is simply not+ // found in the cell list.+ //+ // Existing keys are NOT overwritten: the explicit-layout loop records the MERGED option (an inline+ // entry beats the form-level default), and re-recording the raw form-level value here would invert+ // that documented precedence. Only reachable via a spec validation already rejects, but the+ // precedence rule should hold in the code that implements it, not only in the gate in front of it.+ for (const key of Object.keys(formOptions)) {+ if (!Object.prototype.hasOwnProperty.call(positions, key)) recordPosition(formOptions[key]);+ }+// Notes section (opt-in: formSpec.notes or entity.hasNotes) — Main forms only.// Quick-create / quick-view forms don't host the activity timeline.// Appended to the first tab's single FormColumn so it renders below the field sections.@@ -350,9 +521,27 @@ function compileFormIntent(spec, formSpec, opts) {// residual case type-scoped resolution can't disambiguate — the author sets forms[].formId to reconcile// that exact form. Carried verbatim (validated as a GUID at resolve time). Undefined for most forms.formId: formSpec.formId,+ // The maker-facing "what is this form for". Carried through to createArtifact, and omitted when+ // absent so an edit never blanks a description someone added in the maker.+ description: formSpec.description,status: 'Active',tabs: tabs,- __explicitLayout: explicit,+ // Whether an authored tabs layout was ACTUALLY used, which is NOT the same as `explicit` above.+ // `explicit` is also true for `layout: 'explicit'` with no `tabs`, and in that case the compiler+ // falls through to the AUTO branch — so reporting it as explicit would tell the engine's+ // reconcile to prune fields against a layout nobody authored. The spec gate rejects that+ // combination, but `compileFormIntent` is called directly too, so the flag states what actually+ // happened rather than what was asked for.+ __explicitLayout: Array.isArray(formSpec.tabs),+ // Ordering anchors: { <logical>: <anchorLogical> }. Consumed by the engine's reconcile, which+ // MOVES an existing control to sit immediately after its anchor. Kept off the cells because a+ // cell is pushed verbatim to the SDK and `after` is not part of its model (see `positions`).+ __fieldPositions: positions,+ // Whether an EXPLICIT layout may prune deployed fields it does not list. Defaults to true (the+ // long-standing behaviour: an explicit layout is the complete desired state). `prune: false`+ // lets an author reorder or restyle a SUBSET of the fields without having to re-declare the+ // whole form just to keep the rest — the destructive coupling reported in ADO 6651439.+ __prune: formSpec.prune !== false,__primaryField: entity ? entity.primaryAttribute.schemaName.toLowerCase() : undefined};}@@ -442,11 +631,13 @@ function sectionRowsPointer(ti, ci, si) {return '/tabs/' + ti + '/columns/' + ci + '/sections/' + si + '/rows';}-// JsonPointer to the cell hosting the BOUND field `logical`, or null if not present.-// Used by the engine's field-removal reconcile (removeElement(pointer) on the SDK). Non-field-// controls are skipped even if their fieldName matches, so a prune never targets a quick-view whose-// host lookup collides with a bound field name. Scans in declaration order — the first match wins.-function findFieldCellPointer(formJson, logical) {+// Full structural location of the cell hosting the BOUND field `logical`, or null if absent.+//+// findFieldCellPointer answers "where is it" for a remove; a MOVE additionally needs the containing+// arrays and the indices within them, and deriving those by string-splitting the pointer is both+// fragile and unreadable. Same scan and same non-field-control exclusions as findFieldCellPointer —+// that function is kept as the thin wrapper so existing callers are untouched.+function findFieldCellLocation(formJson, logical) {const lg = String(logical || '').toLowerCase();const tabs = formJson.tabs || [];for (let ti = 0; ti < tabs.length; ti++) {@@ -455,13 +646,31 @@ function findFieldCellPointer(formJson, logical) {const sections = cols[ci].sections || [];for (let si = 0; si < sections.length; si++) {const rows = sections[si].rows || [];+ // Row-major ordinal of each cell WITHIN the section. A section renders as a grid, so the+ // reading order that matters is flat — in a 2-column section `[a|b] [c|d]` reads a, b, c, d,+ // and "c immediately after b" is true even though they are in different rows. Row-local+ // adjacency is therefore the wrong test for "already in place": it reports a correctly+ // positioned field as misplaced and moves it on every rebuild.+ let flat = 0;for (let ri = 0; ri < rows.length; ri++) {const cells = rows[ri].cells || [];- for (let celli = 0; celli < cells.length; celli++) {+ for (let celli = 0; celli < cells.length; celli++, flat++) {const fn = cells[celli].control && cells[celli].control.fieldName;- if (fn && String(fn).toLowerCase() === lg && !isNonFieldControl(cells[celli].control)) {- return '/tabs/' + ti + '/columns/' + ci + '/sections/' + si + '/rows/' + ri + '/cells/' + celli;- }+ if (!fn || String(fn).toLowerCase() !== lg || isNonFieldControl(cells[celli].control)) continue;+ const sectionPointer = '/tabs/' + ti + '/columns/' + ci + '/sections/' + si;+ const rowsPointer = sectionPointer + '/rows';+ const rowPointer = rowsPointer + '/' + ri;+ return {+ sectionPointer,+ rowsPointer,+ rowPointer,+ cellsPointer: rowPointer + '/cells',+ cellPointer: rowPointer + '/cells/' + celli,+ rowIndex: ri,+ cellIndex: celli,+ flatIndex: flat,+ rowCellCount: cells.length,+ };}}}@@ -470,6 +679,15 @@ function findFieldCellPointer(formJson, logical) {return null;}+// JsonPointer to the cell hosting the BOUND field `logical`, or null if not present.+// Used by the engine's field-removal reconcile (removeElement(pointer) on the SDK). Non-field+// controls are skipped even if their fieldName matches, so a prune never targets a quick-view whose+// host lookup collides with a bound field name. Scans in declaration order — the first match wins.+function findFieldCellPointer(formJson, logical) {+ const loc = findFieldCellLocation(formJson, logical);+ return loc ? loc.cellPointer : null;+}+module.exports = {compileFormIntent,fieldCellIntent,@@ -484,5 +702,9 @@ module.exports = {firstSectionRowsPointer,firstColumnSectionsPointer,sectionRowsPointer,- findFieldCellPointer+ findFieldCellPointer,+ findFieldCellLocation,+ normalizeFieldEntry,+ fieldOptionsMap,+ NON_FORM_RENDERABLE_TYPES};diff --git a/plugins/model-apps/scripts/lib/entity-provision.js b/plugins/model-apps/scripts/lib/entity-provision.jsindex ed8679799..5baf9caf9 100644--- a/plugins/model-apps/scripts/lib/entity-provision.js+++ b/plugins/model-apps/scripts/lib/entity-provision.js@@ -136,15 +136,39 @@ async function resolveLanguageCode({ provision, spec, languageCode, warn, provis// name -> its metadataId (so a column can bind to a shared option set).function columnOptions(c, globalChoiceIds, globalChoices, languageCode) {const o = { schemaName: c.schemaName, displayName: c.displayName || c.schemaName, type: SDK_COLUMN_TYPE[c.type || 'Text'], required: REQUIRED(c), languageCode };+ // Description is the maker-facing "what is this column for". Written at CREATE time rather than+ // backfilled: `createColumn` accepts it, and a later PATCH is a second round trip that is easy to+ // skip and easy to forget — so the only reliable moment is the one where the column is authored.+ // Omitted when absent, so an existing column's description is never blanked by a rebuild.+ if (c.description) o.description = String(c.description);switch (c.type) {case 'Text': if (c.maxLength) o.maxLength = c.maxLength; if (c.format) o.stringFormat = c.format; break;case 'Memo': if (c.maxLength) o.maxLength = c.maxLength; break;case 'Integer': case 'BigInt': case 'Decimal': case 'Double': case 'Money':if (c.minValue !== undefined) o.minValue = c.minValue;if (c.maxValue !== undefined) o.maxValue = c.maxValue;- if (c.precision !== undefined) o.precision = c.precision; break;+ if (c.precision !== undefined) o.precision = c.precision;+ // AB#6648522: Whole Number display Format (e.g. a raw integer count of minutes rendered as a+ // Duration picker). Gated on the EXACT 'Integer' type, not the whole shared case: BigInt/+ // Decimal/Double/Money share this case only for min/max/precision, but the SDK's `integerFormat`+ // option is Integer-only and throws InvalidArgumentError for any of the others (app-spec.js's+ // spec-gate validation rejects that combination earlier, so this should never fire in practice —+ // but the gate is Integer-only for the same reason, so keep both narrow together).+ if (c.type === 'Integer' && c.integerFormat !== undefined) o.integerFormat = c.integerFormat;+ break;case 'DateTime': if (c.dateFormat) o.dateFormat = c.dateFormat; break;- case 'Boolean': if (c.trueLabel) o.trueLabel = c.trueLabel; if (c.falseLabel) o.falseLabel = c.falseLabel; break;+ case 'Boolean':+ if (c.trueLabel) o.trueLabel = c.trueLabel;+ if (c.falseLabel) o.falseLabel = c.falseLabel;+ // AB#6648523: an explicit `false` must reach the SDK exactly like an explicit `true` does.+ // `!== undefined`, NOT a truthy check — `if (c.defaultValue)` would silently drop the one value+ // (`false`) a maker-authored spec is most likely to set on purpose. Measured against the+ // vendored bundle: omitting the option sends no `DefaultValue` key different from an explicit+ // `false` (both resolve to the SDK's own `?? false`), so passing it through has no wire-visible+ // effect on create today — but the SAME `!== undefined` guard is reused for the update reconcile+ // below, where a bare truthy check would be an outright bug (see the reconcile block).+ if (c.defaultValue !== undefined) o.defaultValue = c.defaultValue;+ break;case 'Choice': case 'MultiChoice':if (c.globalChoice && globalChoiceIds[c.globalChoice]) { o.globalChoiceMetadataId = globalChoiceIds[c.globalChoice]; }// Defensive fallback: the global choice exists but its metadataId wasn't captured. With the now@@ -159,6 +183,19 @@ function columnOptions(c, globalChoiceIds, globalChoices, languageCode) {case 'AutoNumber': if (c.autoNumberFormat) o.autoNumberFormat = c.autoNumberFormat; break;}if (c.source === 'Calculated' || c.source === 'Rollup') { o.sourceType = c.source; if (c.formula) o.formulaDefinition = c.formula; }+ // AB#6651276: per-verb write/read permissions. Lives after the per-type switch, not inside it,+ // because the SDK accepts these on every buildable column type — this function is simply never+ // called for a Customer column (its caller routes those through createCustomerColumn instead,+ // whose options have no such fields; see the call site in provisionDataModel).+ //+ // `!== undefined`, NOT a truthy check, for each flag: measured against the vendored bundle, the+ // wire key is only sent when the option is explicitly set (unlike DefaultValue/Format above, which+ // the SDK always sends with its own default). `isValidForUpdate: false` — making a column read-only+ // after creation — is the ENTIRE POINT of this feature, so a naive `if (c.isValidForUpdate)` guard+ // would silently make every "lock this down" spec a no-op.+ if (c.isValidForCreate !== undefined) o.isValidForCreate = c.isValidForCreate;+ if (c.isValidForUpdate !== undefined) o.isValidForUpdate = c.isValidForUpdate;+ if (c.isValidForRead !== undefined) o.isValidForRead = c.isValidForRead;return o;}@@ -216,6 +253,68 @@ function isVisualizationUnsupported(err) {return /not found for the segment\s+'?controlconfigurations/i.test(msg);}+function hasExplicitRequired(c) {+ return c && Object.prototype.hasOwnProperty.call(c, 'required');+}++function requiredLevelValue(raw) {+ if (typeof raw === 'string') return raw;+ if (raw && typeof raw.Value === 'string') return raw.Value;+ if (raw && typeof raw.value === 'string') return raw.value;+ return undefined;+}++function columnRequiredLevel(c) {+ if (!c) return undefined;+ return requiredLevelValue(c.RequiredLevel) || requiredLevelValue(c.requiredLevel);+}++async function readAttributeRequiredLevels({ sdk, provision, logical }) {+ const client = (provision && provision.dataverse) || (sdk && sdk.dataverse);+ if (!client || typeof client.get !== 'function') return new Map();++ // The public SDK discovery methods currently project RequiredLevel away: `findColumns` returns+ // name/type/display fields, and `fetchEntityMetadata` returns its cached `attributes[]` in the+ // same reduced shape. `updateColumn` can write RequiredLevel but does not expose its internal GET,+ // so this is the narrow transport read that lets us avoid a blind metadata PUT. Dataverse returns:+ // {+ // "value": [{+ // "LogicalName": "contoso_title",+ // "RequiredLevel": { "Value": "ApplicationRequired", "CanBeChanged": true, ... }+ // }]+ // }+ // `RequiredLevel.Value` is the same AttributeRequiredLevelManagedProperty enum value accepted by+ // the SDK (`ApplicationRequired` | `Recommended` | `None`).+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/attributerequiredlevelmanagedproperty+ const path = `/EntityDefinitions(LogicalName='${odataLit(logical)}')/Attributes?$select=LogicalName,RequiredLevel`;+ const res = await client.get(path);+ if (!res || res.status < 200 || res.status >= 300) {+ const msg = res && res.body && res.body.error && res.body.error.message+ ? res.body.error.message+ : `HTTP ${res && res.status}`;+ throw new Error(`could not read RequiredLevel for ${logical}: ${msg}`);+ }+ const out = new Map();+ for (const a of (res.body && res.body.value) || []) {+ const name = a && (a.LogicalName || a.logicalName);+ const level = columnRequiredLevel(a);+ if (name && level) out.set(String(name).toLowerCase(), level);+ }+ return out;+}++async function runBestEffort(runner, phase, label, fn, warn, warning) {+ try {+ return await runner.run(phase, label, fn, { recoverable: true });+ } catch (err) {+ if (typeof warn === 'function') {+ const cause = err && err.cause ? err.cause : err;+ warn(`${warning}: ${(cause && cause.message) || cause}`);+ }+ return undefined;+ }+}+// 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) {@@ -246,7 +345,17 @@ function makeRunner({ emit, total }) {} catch (err) {// Idempotency escape hatch: a create that fails only because the component already// exists is a skip, not a halt (used where the SDK offers no check-first lister).- if (skipIf && skipIf(err)) { emit({ phase, status: 'skip', label: `${label} (exists)`, n: myN, total }); return undefined; }+ //+ // `skipIf` may answer `true` (the original contract — the reason is "exists") or a REASON+ // STRING. The string form exists because not every recoverable skip is an already-exists+ // collision: an environment that does not declare a platform member cannot host the artifact+ // at all, and labelling that "(exists)" would tell the operator the exact opposite of what+ // happened. Boolean callers are unaffected.+ const why = skipIf && skipIf(err);+ if (why) {+ emit({ phase, status: 'skip', label: `${label} (${typeof why === 'string' ? why : 'exists'})`, n: myN, total });+ return undefined;+ }emit({ phase, status: 'error', label, n: myN, total, detail: String((err && err.message) || err) });throw new BuildHalt(`${phase} failed: ${(err && err.message) || err}`, { phase, code: (err && err.code) || 'sdk-error', recoverable, cause: err });}@@ -326,7 +435,7 @@ async function provisionSolution({ sdk, provision, runner, solution }) {const pubs = await provision.queryRecords('publisher', { select: ['publisherid'], filter: `customizationprefix eq '${odataLit(solution.publisherPrefix)}'`, top: 1 });if (pubs && pubs[0] && pubs[0].publisherid) publisherId = pubs[0].publisherid;else publisherId = (await provision.createPublisher({ uniqueName: `${solution.publisherPrefix}publisher`, friendlyName: `${solution.publisherPrefix} publisher`, prefix: solution.publisherPrefix })).id;- await provision.createSolution({ uniqueName: solution.uniqueName, friendlyName: solution.displayName || solution.uniqueName, publisherId });+ await provision.createSolution({ uniqueName: solution.uniqueName, friendlyName: solution.displayName || solution.uniqueName, publisherId, ...(solution.description ? { description: solution.description } : {}) });}, { recoverable: true });}@@ -375,10 +484,10 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply, languag// 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;-+// 2a. Global option sets (shared choices) — built before columns that bind to them. The SDK's// createGlobalOptionSet is now IDEMPOTENT: it probes by Name and REUSES an existing set (returning// its MetadataId) instead of failing a duplicate-Name POST. So a rerun captures the existing set's@@ -388,27 +497,32 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply, languag// runner.run instead of being silently swallowed.for (const gc of spec.globalChoices || []) {await runner.run('data-model', `global choice ${gc.name}`, async () => {- const r = await sdk.createGlobalOptionSet({ name: gc.name, displayName: gc.displayName || gc.name, languageCode: resolvedLanguageCode, options: (gc.options || []).map((label, i) => ({ value: 100000000 + i, label })) });+ const r = await sdk.createGlobalOptionSet({ name: gc.name, displayName: gc.displayName || gc.name, languageCode: resolvedLanguageCode, ...(gc.description ? { description: gc.description } : {}), options: (gc.options || []).map((label, i) => ({ value: 100000000 + i, label })) });globalChoiceIds[gc.name] = r.metadataId;});}-+// 2b. Tables -> columns (all types + customer) -> status reasons -> alternate keys.for (const e of spec.entities) {const logical = e.schemaName.toLowerCase();const hits = await provision.findTables(e.schemaName, { top: 50 });const existingTable = (hits || []).find((t) => t.logicalName === logical);let existingCols = new Set();+ let existingColRows = [];if (existingTable) {runner.skip('data-model', `table ${e.schemaName} (exists — reuse)`);result.entities[e.schemaName] = { logicalName: logical, entitySetName: existingTable.entitySetName };- existingCols = new Set(((await provision.findColumns(logical)) || []).map((c) => c.logicalName));+ existingColRows = (await provision.findColumns(logical)) || [];+ existingCols = new Set(existingColRows.map((c) => String(c.logicalName || c.schemaName || '').toLowerCase()));} else {await runner.run('data-model', `table ${e.schemaName}`, async () => {const createOpts = { schemaName: e.schemaName, displayName: e.displayName, pluralName: e.pluralName || `${e.displayName}s`,primaryColumnSchemaName: e.primaryAttribute.schemaName, primaryColumnDisplayName: e.primaryAttribute.displayName || 'Name', hasNotes: e.hasNotes === true, languageCode: resolvedLanguageCode };// AutoNumber the primary/title column when requested (the order number IS the identity).if (e.primaryAttribute.autoNumberFormat) createOpts.primaryColumnAutoNumberFormat = e.primaryAttribute.autoNumberFormat;+ // Same reasoning as columns: set the description at CREATE time, and omit it when absent so+ // a rebuild never blanks a description someone added in the maker.+ if (e.description) createOpts.description = String(e.description);try {const t = await sdk.createTable(createOpts);result.entities[e.schemaName] = { logicalName: (t.logicalName || logical), entitySetName: t.entitySetName, metadataId: t.metadataId };@@ -448,6 +562,99 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply, languag? sdk.createCustomerColumn(logical, { schemaName: c.schemaName, displayName: c.displayName || c.schemaName, required: REQUIRED(c), languageCode: resolvedLanguageCode }): sdk.createColumn(logical, columnOptions(c, globalChoiceIds, spec.globalChoices, resolvedLanguageCode)),{ skipIf: isAlreadyExists }));+ if (existingTable) {+ const existingColMeta = new Map(existingColRows.map((c) => [String(c.logicalName || c.schemaName || '').toLowerCase(), c]));+ const requiredTargets = [+ e.primaryAttribute,+ ...buildable,+ ].filter((c) => c && c.schemaName && hasExplicitRequired(c) && existingCols.has(c.schemaName.toLowerCase()));+ const requiredLevels = new Map();+ for (const c of requiredTargets) {+ const current = columnRequiredLevel(existingColMeta.get(c.schemaName.toLowerCase()));+ if (current) requiredLevels.set(c.schemaName.toLowerCase(), current);+ }+ const missingLevels = requiredTargets.filter((c) => !requiredLevels.has(c.schemaName.toLowerCase()));+ if (missingLevels.length) {+ try {+ for (const [name, level] of await readAttributeRequiredLevels({ sdk, provision, logical })) {+ requiredLevels.set(name, level);+ }+ } catch (err) {+ if (typeof warn === 'function') {+ warn(`could not read required levels for ${logical}: ${(err && err.message) || err} — existing columns with explicit required values were left unchanged`);+ }+ }+ }+ const toUpdateRequired = [];+ for (const c of requiredTargets) {+ const columnLogical = c.schemaName.toLowerCase();+ const desired = REQUIRED(c);+ const current = requiredLevels.get(columnLogical);+ // Omitted `required` is intentionally NOT reconciled. REQUIRED(c) maps an absent property to+ // `None` for the CREATE payload, but applying that same default to an existing column would+ // demote a maker-authored Business Required field on a rebuild — a destructive surprise. Only+ // an explicit spec value owns the existing column's RequiredLevel.+ if (!current) {+ runner.skip('data-model', `required ${e.schemaName}.${c.schemaName} (current level unknown — skipped)`);+ } else if (current === desired) {+ runner.skip('data-model', `required ${e.schemaName}.${c.schemaName} (already ${desired})`);+ } else {+ toUpdateRequired.push({ schemaName: c.schemaName, logicalName: columnLogical, required: desired });+ }+ }+ await runner.mapLimit(toUpdateRequired, 1, (c) => runBestEffort(+ runner,+ 'data-model',+ `required ${e.schemaName}.${c.schemaName} -> ${c.required}`,+ () => sdk.updateColumn(logical, c.logicalName, { required: c.required }),+ warn,+ `could not update required level for ${logical}.${c.logicalName} to ${c.required} — the rest of the build continues`+ ));+ // AB#6648523 / AB#6648522 / AB#6651276: reconcile the three new column capabilities+ // (defaultValue, integerFormat, isValidForCreate/Update/Read) on an EXISTING table, so a+ // rebuild converges a column that already exists, not only one just created above.+ //+ // Deliberately a SEPARATE block from the `required` reconcile above rather than folded into+ // it, and with a DIFFERENT strategy: `required` reads the column's CURRENT level first so it+ // can skip a no-op update and, more importantly, avoid demoting an omitted value (a maker may+ // have set Business Required by hand, and the spec staying silent must not undo that). These+ // three have no equivalent maker-authored surface to protect, and `updateColumn` performs its+ // own GET-mutate-PUT round trip per call (measured against the vendored bundle — replaying an+ // already-correct value is a harmless no-op on the wire), so they are simply RE-ASSERTED+ // whenever the spec sets them explicitly — the same no-pre-read-diff strategy already used by+ // `setColumnVisualization` below for the same reason.+ //+ // Customer columns are excluded outright, not merely skipped for these three fields:+ // `updateColumn` refuses ANY change to a Customer column (measured — it throws "type+ // 'Customer' not supported"), because Customer has no entry in the SDK's attribute-type ->+ // OData-cast table (it is created through the wholly separate createCustomerColumn instead).+ const capabilityTargets = buildable.filter((c) => c.type !== 'Customer' && existingCols.has(c.schemaName.toLowerCase())+ && (c.defaultValue !== undefined || c.integerFormat !== undefined+ || c.isValidForCreate !== undefined || c.isValidForUpdate !== undefined || c.isValidForRead !== undefined));+ await runner.mapLimit(capabilityTargets, 1, (c) => {+ const columnLogical = c.schemaName.toLowerCase();+ const opts = {};+ // Same type gates as columnOptions() above (Boolean-only / Integer-only): the SDK's update+ // path throws the identical InvalidArgumentError as create for a type mismatch, and+ // app-spec.js's validation already rejects an impossible combination at the spec gate — this+ // just keeps the two call sites from drifting off that shared rule.+ if (c.type === 'Boolean' && c.defaultValue !== undefined) opts.defaultValue = c.defaultValue;+ if (c.type === 'Integer' && c.integerFormat !== undefined) opts.integerFormat = c.integerFormat;+ // `!== undefined`, not truthy — same reasoning as columnOptions(): an explicit `false` is the+ // whole point of isValidForUpdate/Create/Read, and of `defaultValue` too.+ if (c.isValidForCreate !== undefined) opts.isValidForCreate = c.isValidForCreate;+ if (c.isValidForUpdate !== undefined) opts.isValidForUpdate = c.isValidForUpdate;+ if (c.isValidForRead !== undefined) opts.isValidForRead = c.isValidForRead;+ return runBestEffort(+ runner,+ 'data-model',+ `column capabilities ${e.schemaName}.${c.schemaName}`,+ () => sdk.updateColumn(logical, columnLogical, opts),+ warn,+ `could not update column capabilities for ${logical}.${columnLogical} — the rest of the build continues`+ );+ });+ }// Capture real column results (logicalName + metadataId)toCreate.forEach((c, i) => {const res = colResults[i];@@ -512,7 +719,7 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply, languag{ recoverable: true, skipIf: isAlreadyExists });}}-+// 2c. Relationships — 1:N and N:N; skip those already present. The publisher prefix is threaded// into the schema-name defaulting so a relationship to a standard/system table gets a valid,// prefixed name Dataverse accepts (see prefixedRelationshipName).@@ -547,7 +754,7 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply, languag}, { skipIf: isAlreadyExists });}}-+return result;}diff --git a/plugins/model-apps/scripts/lib/hydrate-spec.js b/plugins/model-apps/scripts/lib/hydrate-spec.jsindex 7c8b49a51..84fdd7c6c 100644--- a/plugins/model-apps/scripts/lib/hydrate-spec.js+++ b/plugins/model-apps/scripts/lib/hydrate-spec.js@@ -57,19 +57,70 @@ function droppedSubareaDetail(sa) {};}+function descriptionFromDataverse(value) {+ if (value === undefined || value === null) return undefined;+ if (typeof value === 'string') return value.trim() ? value : undefined;+ if (typeof value !== 'object') return undefined;+ // Metadata descriptions arrive as a Dataverse Label, for example:+ // {+ // "LocalizedLabels": [{ "Label": "text", "LanguageCode": 1033 }],+ // "UserLocalizedLabel": { "Label": "text", "LanguageCode": 1033 }+ // }+ // Prefer the user-localized text because it is the platform's chosen label for this caller, then+ // fall back to the first localized label. A missing/null Label means "no description"; returning+ // undefined (not "") keeps the hydrated spec valid and avoids blanking a maker-authored value on+ // rebuild. Shape: https://learn.microsoft.com/power-apps/developer/data-platform/webapi/reference/label+ const user = value.UserLocalizedLabel && value.UserLocalizedLabel.Label;+ if (typeof user === 'string' && user.trim()) return user;+ const first = Array.isArray(value.LocalizedLabels)+ ? value.LocalizedLabels.find((l) => l && typeof l.Label === 'string' && l.Label.trim())+ : null;+ return first ? first.Label : undefined;+}++function withDescription(obj, rawDescription) {+ const out = { ...obj };+ delete out.description;+ delete out.Description;+ const description = descriptionFromDataverse(rawDescription);+ if (description !== undefined) out.description = description;+ return out;+}++function sanitizeDescriptionInventory(inv) {+ if (!inv || typeof inv !== 'object' || Array.isArray(inv)) return undefined;+ const out = {};+ for (const key of ['views', 'charts', 'forms', 'businessRules', 'globalChoices']) {+ if (!Array.isArray(inv[key])) continue;+ out[key] = inv[key].map((item) => {+ const { Description, description, ...rest } = item || {};+ return withDescription(rest, description !== undefined ? description : Description);+ });+ }+ return Object.keys(out).length ? out : undefined;+}+async function hydrateSpec(read) {const app = (await read.app()) || { name: '', description: '', siteMap: { areas: [] } };const pages = (await read.pages()) || [];- const entities = (await read.entities()) || [];- const webResources = (await read.webResources()) || [];- const dashboards = (read.dashboards ? await read.dashboards() : []) || [];+ const entities = ((await read.entities()) || []).map((e) => {+ const columns = Array.isArray(e && e.columns)+ ? e.columns.map((c) => withDescription(c || {}, (c && (c.description !== undefined ? c.description : c.Description))))+ : [];+ return withDescription({ ...(e || {}), columns }, e && (e.description !== undefined ? e.description : e.Description));+ });+ const webResources = ((await read.webResources()) || []).map((wr) => withDescription(wr || {}, wr && (wr.description !== undefined ? wr.description : wr.Description)));+ const dashboards = ((read.dashboards ? await read.dashboards() : []) || [])+ .map((d) => withDescription(d || {}, d && (d.description !== undefined ? d.description : d.Description)));// `prefixResolved` is a TRANSIENT download-time signal (whether recoverAppSolution trusted the publisher// prefix) consumed by iconWebResources BEFORE hydrate; strip it so it never leaks into the persisted,// user-facing spec — the build reads only uniqueName + publisherPrefix from solution.- const { prefixResolved, ...solution } = (await read.solution()) || { uniqueName: 'Default', publisherPrefix: 'new' };+ const { prefixResolved, ...solutionRaw } = (await read.solution()) || { uniqueName: 'Default', publisherPrefix: 'new' };+ const solution = withDescription(solutionRaw, solutionRaw.description !== undefined ? solutionRaw.description : solutionRaw.Description);void prefixResolved;// `design` is threaded through from the page manifest (§7.3) when present; undefined for legacy apps.const design = read.design ? await read.design() : undefined;+ const descriptionInventory = read.descriptionInventory ? sanitizeDescriptionInventory(await read.descriptionInventory()) : undefined;// When downloaded pages carry stable keys (assigned by assignPageKeys), emit the v2 shape;// legacy callers without keys fall back to the name-based shape for back-compat.const hasKeys = pages.some((p) => p.key);@@ -160,7 +211,7 @@ async function hydrateSpec(read) {// Dashboards are reconstructed with id-passthrough tiles (each tile carries the deployed// view/chart ids), so a rebuild recreates the dashboard against the EXISTING views/charts// without needing views[]/charts[] declared (which would else duplicate them or fail validation).- dashboards: dashboards.map((d) => ({ name: d.name, tiles: d.tiles })),+ dashboards: dashboards.map((d) => ({ name: d.name, ...(d.description ? { description: d.description } : {}), tiles: d.tiles })),pages: pages.map((p) => (hasKeys// v2 shape: key + name + optional semantics + source discriminant (kind:'tsx', codeFile)? {@@ -191,6 +242,11 @@ async function hydrateSpec(read) {appShell,// design from the page manifest (§7.3) — omit entirely when absent so the spec stays minimal....(design !== undefined ? { design } : {}),+ // Views, charts, forms, business rules, and global choices are not structurally reconstructed by+ // this hydrator today. Keep their descriptions in a read-only inventory so an inspecting agent can+ // still see the deployed intent without pretending these partial records are rebuildable spec+ // entries.+ ...(descriptionInventory !== undefined ? { descriptionInventory } : {}),};// These diagnostics are intentionally non-enumerable: hydrateSpec returns them to the download CLI,// but `app-spec.json` must stay the user-facing contract rather than gaining transient loss metadata.@@ -205,4 +261,4 @@ async function hydrateSpec(read) {return spec;}-module.exports = { hydrateSpec, subAreaToSpec };+module.exports = { hydrateSpec, subAreaToSpec, descriptionFromDataverse, withDescription };diff --git a/plugins/model-apps/scripts/lib/sdk-build.js b/plugins/model-apps/scripts/lib/sdk-build.jsindex ae74b5d9d..9349c29fe 100644--- a/plugins/model-apps/scripts/lib/sdk-build.js+++ b/plugins/model-apps/scripts/lib/sdk-build.js@@ -54,6 +54,7 @@ const {formFieldLogicals,firstSectionRowsPointer,findFieldCellPointer,+ findFieldCellLocation,subgridCellIntent,subgridSectionIntent,quickViewCellIntent,@@ -106,6 +107,15 @@ 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 ONLY supported way to author a business rule: the bound member the modern business-rule+// designer itself uses. Named here for the warning text so the operator can search for it, and so a+// rename shows up in one place rather than inside a string.+//+// The vendored SDK writes rules through this member or refuses — it no longer compiles a client-side+// WWF XAML substitute. Environments where the member is undeclared therefore cannot host business+// rules at all; that is a platform-side rollout, not something a spec can work around.+const BUSINESS_RULE_MEMBER = 'Microsoft.Dynamics.CRM.CreateProcessWithWfomJson';+// 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.@@ -358,16 +368,23 @@ function planFor(spec, opts) {if (has('pages') && (spec.pages || []).length && appHasPageSubareas(spec)) items.push({ phase: 'pages', label: 'finalize sitemap (genpage subareas)' });if (has('ai-features') && spec.ai !== undefined && spec.ai !== null) {items.push({ phase: 'ai-features', label: 'enable app AI features' });- if (!(spec.ai.summaries && spec.ai.summaries.default === 'off')) {- for (const logical of selectSummaryTables(spec)) {- items.push({ phase: 'ai-features', label: `row summary for ${logical}` });- }+ // Do NOT short-circuit on `summaries.default === 'off'`. `selectSummaryTables` already implements+ // the documented semantics — `default` is the app-level DEFAULT and `tables[x].enabled: true` is+ // a per-table OVERRIDE that wins over it — and bailing here made that opt-in branch unreachable,+ // silently dropping a summary the author explicitly asked for.+ for (const logical of selectSummaryTables(spec)) {+ items.push({ phase: 'ai-features', label: `row summary for ${logical}` });}}if (has('security')) for (const p of spec.personas || []) {const n = (p.jobs || []).length;items.push({ phase: 'security', label: `security role "${p.persona}" (${n} job${n === 1 ? '' : 's'})` });}+ // Form role assignment is planned under `security` (not `forms`) because it can only run once the+ // roles exist — see the 7b block in the engine for why.+ if (has('security')) for (const f of spec.forms || []) {+ if (f && f.securityRoles) items.push({ phase: 'security', label: `form roles for ${f.name || f.formType || 'Main'} on ${f.entity}` });+ }if (has('publish') && opts.publish) items.push({ phase: 'publish', label: 'publish customizations' });return items;}@@ -416,7 +433,7 @@ function viewDef(spec, v) {conditions.push(cond);}}- return { name: v.name, description: '', entityLogicalName: entityLogical, queryType: 0, isDefault: false, columns: cols,+ return { name: v.name, description: String(v.description || '').trim(), entityLogicalName: entityLogical, queryType: 0, isDefault: false, columns: cols,filters: { type: 'and', conditions, groups },sort: (v.sort || []).map((s) => ({ attribute: String(s.attr).toLowerCase(), descending: s.dir === 'desc' })) };}@@ -472,8 +489,26 @@ function subgridLabel(spec, sg) {}// True when a table has enough declared columns to make enriching its default views worthwhile// (opt out per-entity with enrichDefaultViews:false).+//+// `existing: true` tables are excluded outright. Enrichment REPLACES the Active/Inactive views'+// column set, and `existing` means "this build did not create this table and cannot prove it owns+// it" — the same reasoning that stops teardown from deleting such a table. Rewriting another app's+// default views is destructive and unrecoverable from here, whereas leaving them alone costs+// nothing. This matters most for a `download -> rebuild` round trip: `download-model-app` flags+// every recovered table `existing: true` precisely because ownership is unprovable.function enrichesDefaultViews(spec, entity) {- return !!entity && entity.enrichDefaultViews !== false && defaultViewColumns(spec, entity).length >= 2;+ if (!entity) return false;+ // An `existing: true` table is excluded UNLESS the author explicitly opts in. Enrichment REPLACES+ // the Active/Inactive views' column set, and `existing` means this build did not create the table+ // and cannot prove it owns it — the same reasoning that stops teardown from deleting it. Rewriting+ // another app's default views is destructive and unrecoverable from here. This matters most for a+ // `download -> rebuild` round trip: `download-model-app` flags every recovered table `existing`+ // precisely because ownership is unprovable.+ //+ // `enrichDefaultViews: true` is honoured as a deliberate override, because judging "this reused+ // table really is mine" is exactly the call an author can make and this code cannot.+ if (entity.existing === true && entity.enrichDefaultViews !== true) return false;+ return entity.enrichDefaultViews !== false && defaultViewColumns(spec, entity).length >= 2;}// Resolve the id of an EXISTING deployed form to reconcile, disambiguating by TYPE (form names are unique@@ -568,7 +603,7 @@ function artifactIdentityQuery(type, def) {}function chartDef(spec, ch) { const entityLogical = ch.entity.toLowerCase();- return { name: ch.name, description: '', entityLogicalName: entityLogical, chartType: ch.chartType, isDefault: false,+ return { name: ch.name, description: String(ch.description || '').trim(), entityLogicalName: entityLogical, chartType: ch.chartType, isDefault: false,series: [{ attribute: `${entityLogical}id`, aggregate: ch.measure || 'count' }],categories: [{ attribute: String(ch.groupBy).toLowerCase() }], presentation: { showLegend: true, title: ch.name } };}@@ -781,6 +816,16 @@ function appDef(spec, result, opts = {}) {if (s.url) return { ...withVector, type: 'URL', url: s.url };return { ...withVector, type: 'Entity', entity: s.entity && s.entity.toLowerCase() };};+ // `appShell` is OPTIONAL to validation (the deploy profile deliberately accepts a spec without+ // one — download and many callers rely on that), but it is NOT optional here: without it there is+ // no sitemap to build. Dereferencing it unguarded produced a bare+ // `Cannot read properties of undefined (reading 'areas')` at this phase, AFTER the solution,+ // tables, columns, views and the generated app icon were already created — a half-built app plus+ // an error naming nothing the author could act on. Fail with the same actionable shape the+ // subarea errors above use.+ if (!spec.appShell || !Array.isArray(spec.appShell.areas)) {+ throw new Error("the spec has no appShell.areas, so the app has no navigation to build — add appShell: { areas: [ { label, groups: [ { label, subAreas: [ { entity: '<table>', title: '<label>' } ] } ] } ] }");+ }const areas = (spec.appShell.areas || []).map((a, ai) => ({ id: `area_${ai}`, title: a.label,// Same rule as subAreaJson: preserve a platform icon path VERBATIM (case-sensitive OOB/WebResources// path); lower-case only a bare local web-resource NAME. Leaving the area icon unconditionally@@ -794,18 +839,6 @@ 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:@@ -824,8 +857,34 @@ 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.+// The (entity, formType, name) triple the App Spec uses to identify a form. Used to address a form+// from a LATER phase: `forms[].securityRoles` is applied during `security`, because a persona's role+// does not exist until then, and by that point the forms phase has finished and only the entity's+// Main form is reachable through `created.forms`.+//+// `name` is included because one entity may declare several forms of the same type, and the id must+// bind to the form the author annotated rather than to whichever sibling was built last.+function formIdentityKey(f) {+ return `${String(f.entity).toLowerCase()}|${f.formType || 'Main'}|${f.name || ''}`;+}++// 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 serializer ignores them, and the push succeeds with a+// workflow object model 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 SDK's other axes (`Field`, `Lookup`, `Expression`, `Clear`)+// need shapes the App Spec does not model, so exposing the name would offer authors a choice they+// cannot use. The App Spec calls the type hint `dataType` rather than the SDK's `valueWorkflowType`,+// because `valueType` already means that other thing here — and note it is currently DECORATIVE:+// measured across every accepted token, on both the condition and the action path, the SDK types+// every literal as String. See BUSINESS_RULE_DATA_TYPES in app-spec.js.function businessRuleDef(rule) {const ids = (prefix) => { let n = 0; return () => `${prefix}${++n}`; };const clauseId = ids('c');@@ -835,6 +894,8 @@ function businessRuleDef(rule) {name: rule.name,entityLogicalName: String(rule.entity).toLowerCase(),scope: rule.scope || 'Entity',+ // Omitted when the spec has none, so a rebuild never blanks one added in the maker.+ ...(rule.description ? { description: rule.description } : {}),// 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',@@ -1005,7 +1066,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: {}, businessRules: {}, commands: {}, dashboards: {}, pages: {}, pageDeployedShas: {}, ai: { appFeatures: null, summaries: {} }, roles: {}, app: null } };+ const result = { ok: true, created: { entities: {}, relationships: {}, records: {}, webResources: {}, views: {}, charts: {}, forms: {}, formIds: {}, businessRules: {}, commands: {}, dashboards: {}, pages: {}, pageDeployedShas: {}, ai: { appFeatures: null, summaries: {} }, roles: {}, app: null }, skipped: { businessRules: [], aiSummaries: [] } };// #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@@ -1095,7 +1156,10 @@ async function runSdkBuild(spec, opts = {}) {// 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 = async (def) => {- const art = provision.createArtifact('form', { name: def.name, entityLogicalName: def.entityLogicalName, formType: def.formType, status: def.status });+ // `description` is new on forms in this SDK uptake (dashboards, rows in the same systemform+ // table, always had it). Passed only when the spec sets one: omitted on push it is not written,+ // so an existing server-side description survives an edit that did not set one.+ const art = provision.createArtifact('form', { name: def.name, entityLogicalName: def.entityLogicalName, formType: def.formType, status: def.status, ...(def.description ? { description: def.description } : {}) });const tabs = def.tabs || [];// 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);@@ -1177,6 +1241,118 @@ async function runSdkBuild(spec, opts = {}) {// (semantic identity = bound fieldName / relationship, so a rebuild never duplicates), PRUNE fields// an explicit layout dropped, then push (halt on a 412 conflict), publish, and ensure it's a// solution component. This is what makes editing a deployed form actually land.++ // Re-assert `readOnly` / `hidden` on fields already placed on a deployed form.+ //+ // Only the ENABLED state is ever written (`isReadOnly: true`, `visible: false`) — never the+ // negation. A spec that omits the flag means "I am not expressing an opinion", not "make it+ // editable/visible", so blanking here would silently undo a lock or a hide a maker applied in the+ // designer on a field the spec merely happens to list.+ //+ // Consequence, documented rather than worked around: turning a flag back OFF through the spec is+ // not supported — remove the field and let the next build re-add it, or clear it in the designer.+ const applyFieldControlOptions = async (formId, def, want, wantCellByLogical) => {+ for (const logical of want) {+ const wantCell = wantCellByLogical[logical];+ if (!wantCell) continue;+ const wantReadOnly = !!(wantCell.control && wantCell.control.isReadOnly);+ const wantHidden = wantCell.visible === false;+ if (!wantReadOnly && !wantHidden) continue; // nothing asserted for this field+ // Re-read per field: each updateElement rewrites the artifact, and a stale pointer would+ // patch whatever now sits at that index.+ const loc = findFieldCellLocation(await provision.getArtifact('form', formId) || {}, logical);+ if (!loc) continue;+ if (wantReadOnly) await provision.updateElement('form', formId, `${loc.cellPointer}/control`, { isReadOnly: true });+ if (wantHidden) await provision.updateElement('form', formId, loc.cellPointer, { visible: false });+ }+ };++ // Resolve a `/tabs/T/columns/C/sections/S/rows/R` pointer to the row object. Deliberately narrow —+ // it exists only so the reconcile can tell whether a cell move emptied the row it came from.+ const jsonPointerRow = (formJson, pointer) => {+ const t = String(pointer).split('/').filter(Boolean);+ // ['tabs', T, 'columns', C, 'sections', S, 'rows', R]+ if (t.length !== 8 || t[0] !== 'tabs' || t[2] !== 'columns' || t[4] !== 'sections' || t[6] !== 'rows') return null;+ const tab = (formJson.tabs || [])[Number(t[1])];+ const col = tab && (tab.columns || [])[Number(t[3])];+ const sec = col && (col.sections || [])[Number(t[5])];+ return (sec && (sec.rows || [])[Number(t[7])]) || null;+ };++ // Move each anchored field so it immediately follows its anchor (`fieldOptions[x].after`).+ //+ // This is the non-destructive alternative to re-declaring a whole form just to move one control+ // (ADO 6651439). It is a no-op when the field is already in place, so a rebuild converges instead+ // of shuffling the form on every run.+ //+ // "Immediately after" is measured in SECTION-FLAT reading order, because a section is a grid: in a+ // 2-column section `[a|b] [c|d]` the order is a, b, c, d. Two mechanics, chosen by whether one can+ // actually reach that position (see the branch comments below) rather than by row shape alone:+ // * ROW move — the field is alone in its row AND the anchor is the last cell of its row. The+ // field's row is inserted after the anchor's row, which is flat-adjacent only under that+ // second condition.+ // * CELL move — everything else. The cell is spliced into the anchor's own row directly after+ // it, which always satisfies flat adjacency. The anchor's row then holds one extra cell — an+ // over-full row for the section's column count. The SDK accepts that (its form validator+ // imposes no row/cell cardinality rule, only "a cell control must be an object or null"), and+ // Dataverse accepts the push; how UCI lays the overflow out is NOT verified here. A row+ // emptied by the move is removed so blank rows cannot accumulate.+ const applyFieldPositions = async (formId, def) => {+ const positions = def.__fieldPositions || {};+ for (const logical of Object.keys(positions)) {+ const anchor = positions[logical];+ // Re-read before every move: moveElement rewrites the artifact and shifts sibling indices.+ const form = await provision.getArtifact('form', formId) || {};+ const from = findFieldCellLocation(form, logical);+ const to = findFieldCellLocation(form, anchor);+ // A missing field or anchor is not an error: the anchor may be a column this build did not+ // create, or the field may have been pruned. Positioning is a layout nicety — never fail a+ // build over it.+ if (!from || !to) continue;++ // "Already in place" is a SECTION-FLAT question, not a row-local one. A section is a grid: in+ // a 2-column section `[a|b] [c|d]` the reading order is a, b, c, d, so a field can sit+ // correctly immediately after its anchor while living in the NEXT row. Testing row adjacency+ // reported such a field as misplaced and moved it on every rebuild — the auto layout switches+ // to 2 columns above 6 fields, so this was the common case, not an edge case.+ if (from.sectionPointer === to.sectionPointer && from.flatIndex === to.flatIndex + 1) continue;++ // Which mechanic can actually SATISFY that check?+ //+ // A ROW move inserts the field's row after the anchor's row, so it lands after the LAST cell+ // of that row. That is flat-adjacent to the anchor only when the anchor IS the last cell in+ // its row — always true in a 1-column section, a coin-flip in a 2-column one. When the anchor+ // sits in a left-hand column the row move overshoots by the rest of the row, the flat check+ // stays false forever, and the reconcile re-issues a no-op move on every single rebuild.+ // So the row move is used only where it can succeed; otherwise the cell is moved into the+ // anchor's own row, directly after it, which always satisfies flat adjacency.+ const anchorIsLastInRow = to.cellIndex === to.rowCellCount - 1;+ if (from.rowCellCount === 1 && anchorIsLastInRow) {+ // moveElement resolves the TARGET ARRAY first, then removes the source, then splices. When+ // both live in the same array the removal shifts every later index down by one, so a target+ // computed against the pre-removal array overshoots by one. Compensate explicitly.+ let index = to.rowIndex + 1;+ if (from.rowsPointer === to.rowsPointer && from.rowIndex < index) index -= 1;+ await provision.moveElement('form', formId, from.rowPointer, to.rowsPointer, { index });+ continue;+ }++ let index = to.cellIndex + 1;+ if (from.cellsPointer === to.cellsPointer && from.cellIndex < index) index -= 1;+ await provision.moveElement('form', formId, from.cellPointer, to.cellsPointer, { index });+ // Moving the only cell out of a row leaves an empty `<row/>`, which renders as a blank line and+ // would accumulate one per anchored field. Row indices are unchanged by a cell move (cells+ // move between rows; the row count does not change), so the source row is still where it was.+ if (from.rowCellCount === 1 && from.rowPointer !== to.rowPointer) {+ const after = await provision.getArtifact('form', formId) || {};+ const stranded = jsonPointerRow(after, from.rowPointer);+ if (stranded && (stranded.cells || []).length === 0) {+ await provision.removeElement('form', formId, from.rowPointer);+ }+ }+ }+ };+const reconcileForm = async (formId, def) => {await provision.fetchArtifact('form', formId);// The def's field cells are already push-ready ({ control: { fieldName, isRequired? } }); index by@@ -1196,12 +1372,26 @@ async function runSdkBuild(spec, opts = {}) {have.add(logical);}await addSubgrids(formId, def.__subgrids);+ // Re-assert per-control attributes (read-only / hidden) on fields that were ALREADY on the form.+ // The add loop above only reaches fields it creates, so without this an author who marks an+ // existing field `readOnly: true` gets a successful build and no change — the same+ // create-only blind spot that made an existing column's RequiredLevel unchangeable.+ //+ // updateElement MERGES when both sides are objects (`{...current, ...patch}`), so patching+ // `/…/control` with `{ isReadOnly: true }` preserves classId, label and every other adapter-derived+ // value. It does NOT mint ids, which is exactly right here — the cell already has one.+ await applyFieldControlOptions(formId, def, want, wantCellByLogical);+ // Reposition any field the spec anchors after another (`fieldOptions[x].after`). Runs AFTER the+ // add/attribute passes so a field created in this same run can be positioned in the same run.+ await applyFieldPositions(formId, def);// 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.+ // `prune: false` opts out entirely, so a subset of the form can be restyled or reordered without+ // re-declaring every other field just to keep it (ADO 6651439).// removeElement is non-idempotent and shifts sibling indices, so re-locate each cell pointer from// a fresh read before removing it.- if (def.__explicitLayout) {+ if (def.__explicitLayout && def.__prune !== false) {const wantSet = new Set(want);const primary = def.__primaryField ? String(def.__primaryField).toLowerCase() : null;for (const logical of formFieldLogicals(await provision.getArtifact('form', formId) || {})) {@@ -1231,6 +1421,21 @@ async function runSdkBuild(spec, opts = {}) {merged.push({ name: n, width: col.width || 100, order: merged.length });}await provision.updateElement('view', viewId, '/columns', merged);+ // Reconcile the maker-facing description too (#496). Without this, a view's description reached+ // Dataverse only on CREATE — and the most-read view on a table is the platform's auto-generated+ // "Active <Plural>", which already exists, so the build reconciles onto it and the authored+ // description was never written.+ //+ // Two guards, both load-bearing:+ // * only when the spec EXPLICITLY sets one (`viewDef` emits `description: v.description || ''`,+ // so an unset description is `''` — writing that would blank text a maker typed in the UI);+ // * only when it DIFFERS, so an ordinary rebuild issues no extra write.+ // This rides the push below rather than a separate PATCH: the push rewrites `description` from+ // the artifact, so a standalone PATCH would be immediately overwritten by the stale fetched value.+ const wantDescription = typeof def.description === 'string' ? def.description.trim() : '';+ if (wantDescription && wantDescription !== String(current.description || '')) {+ await provision.updateElement('view', viewId, '/description', wantDescription);+ }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 });@@ -1355,19 +1560,89 @@ async function runSdkBuild(spec, opts = {}) {// Chart DEFINITION edits are not applied in place on a rebuild (there is no SDK chart-update// path yet), so an existing chart is skipped WITH A REASON rather than silently reported as// (re)built — recreate the chart to change it. New charts are created + added to the solution.+ //+ // Charts whose ENTITY should be published at the end. Keyed by entity so one publish covers it,+ // and holding the artifact id because `publishArtifact` requires the artifact to be+ // WORKSPACE-RESIDENT: it goes readRaw -> readLocal, which throws ArtifactNotFoundError rather+ // than lazily fetching. `findArtifact` does NOT populate the workspace, so an existing chart is+ // only publishable once something has created or fetched it. Recording it here — at the two+ // points that actually put it in the workspace — is what keeps phase 8 from handing publish an+ // id it cannot resolve. It is also the right SEMANTICS: publish exactly the entities whose charts+ // this run changed.+ const chartsToPublish = new Map();if (has('charts')) {const charts = spec.charts || [];const ids = await runner.mapLimit(charts, concurrency, async (c) => {const def = chartDef(spec, c);const existingId = await provision.findArtifact('chart', { name: def.name, entity: def.entityLogicalName });if (existingId) {- runner.skip('charts', `chart "${def.name}" (exists — chart edits aren't applied on rebuild; recreate to change)`);+ // The chart DEFINITION is still not reconciled — but its description is (#496), because a+ // description is the one thing an AI agent inspecting this app later reads, and it reached+ // Dataverse only on create.+ //+ // Written with a direct column PATCH rather than fetch -> updateElement -> pushArtifact,+ // which is what views use. The difference is deliberate: `reconcileView` already pushes an+ // existing view (for columns), so that round trip is proven in production, whereas the chart+ // phase has NEVER pushed an existing chart. A push regenerates `datadescription` and+ // `presentationdescription` from the deserialized model, so it would newly expose every+ // maker-customized chart to a serialize round trip — the same class of risk as #478. A+ // single-column PATCH cannot disturb the chart definition at all.+ //+ // Same two guards as views: only when the spec EXPLICITLY sets a description (chartDef emits+ // `|| ''`, and writing that would blank a maker's text), and only when it DIFFERS.+ const wantDescription = typeof def.description === 'string' ? def.description.trim() : '';+ let reconciled = false;+ if (wantDescription && typeof provision.updateRecord === 'function') {+ try {+ // Read through the SDK's artifact surface, NOT `queryRecords`. Measured live: a chart+ // description PATCH lands on the UNPUBLISHED layer, while a plain/filtered GET returns+ // the PUBLISHED row. Reading the published value would compare across layers — the guard+ // would see a difference on every rebuild and re-issue the identical PATCH forever, which+ // is non-convergence, not a blank. `chartApi.get` uses+ // `Microsoft.Dynamics.CRM.RetrieveUnpublished()`, which is exactly the layer the PATCH+ // writes to. Verified on a live org:+ // PATCH description -> plain GET: old value | RetrieveUnpublished(): new value+ // fetchArtifact only READS (it populates the local workspace); the chart is still never+ // pushed, so its definition is not exposed to a serialize round trip.+ await provision.fetchArtifact('chart', existingId);+ const current = await provision.getArtifact('chart', existingId) || {};+ if (String(current.description || '') !== wantDescription) {+ await provision.updateRecord('savedqueryvisualization', existingId, { description: wantDescription });+ reconciled = true;+ // The PATCH writes the UNPUBLISHED layer, so the entity must be published for the new+ // text to be served. Safe to queue only here: the fetch above has put the chart in the+ // workspace, which publishArtifact requires.+ chartsToPublish.set(String(def.entityLogicalName || '').toLowerCase(), existingId);+ }+ } catch (err) {+ // Best-effort — a description is an inspection aid and must not fail a build. But it must+ // not be SILENT either: the skip line below says "chart edits aren't applied on rebuild",+ // so an operator whose write was rejected would read that as expected and never look.+ // Silence here would recreate the exact non-convergence #496 exists to remove, one layer+ // down.+ if (typeof opts.warn === 'function') {+ opts.warn(`chart "${def.name}": could not reconcile its description (${(err && err.message) || err}); the deployed chart keeps its previous description.`);+ }+ }+ }+ // The label reports what actually happened, so "description written" and "nothing to do" are+ // not the same line.+ runner.skip('charts', `chart "${def.name}" (exists — ${reconciled ? 'description reconciled; other ' : ''}chart edits aren't applied on rebuild; recreate to change)`);+ // An existing chart the spec claims is still a component of this solution — otherwise it is+ // absent from the exported solution. (It was always visible to TEARDOWN, which resolves+ // charts by name from `spec.charts` rather than by solution membership.) Previously this+ // branch returned without adding it; the create path below and reconcileView both add theirs.+ try {+ await provision.addSolutionComponent({ componentId: existingId, componentType: COMPONENT_TYPE.chart, solutionUniqueName: sol.uniqueName });+ } catch { /* already a component, or not ours to add — never fail a build over it */ }return existingId;}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}`, opts.warn);await provision.addSolutionComponent({ componentId: pushed.id, componentType: COMPONENT_TYPE.chart, solutionUniqueName: sol.uniqueName });+ // Created here, so it IS workspace-resident and publishable.+ chartsToPublish.set(String(def.entityLogicalName || '').toLowerCase(), pushed.id);return pushed.id;});});@@ -1441,6 +1716,14 @@ async function runSdkBuild(spec, opts = {}) {// Key the entity's MAIN form by entity (the app wires one form per entity below); quick-create// / quick-view forms are still built + added to the solution, just not the entity's app form.defs.forEach((d, i) => { if ((d.f.formType || 'Main') === 'Main') result.created.forms[d.f.entity.toLowerCase()] = ids[i]; });+ // Every form, addressable individually. `created.forms` is keyed by ENTITY and holds only the+ // Main form, which is all the app shell needs — but `forms[].securityRoles` is applied in the+ // SECURITY phase (roles do not exist until then), by which time the forms phase is long over and+ // a non-Main form would be unreachable. Keyed on the same (entity, formType, name) triple the+ // spec uses to identify a form, so the lookup cannot silently bind to a same-named sibling.+ defs.forEach((d, i) => {+ result.created.formIds[formIdentityKey(d.f)] = ids[i];+ });// Quick-view placement: embed a built QuickView form onto a host form via a lookup column,// added as a canonical quick-view control cell (semantic identity = the lookup field, so a// rebuild doesn't duplicate it). Runs after ALL forms are built so a host can reference a@@ -1484,10 +1767,33 @@ async function runSdkBuild(spec, opts = {}) {// 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.+ // (entity, name), and re-pushing on every rebuild would stack duplicate rules on the table.+ //+ // The SDK writes rules ONLY through the bound `CreateProcessWithWfomJson` member — the same one the+ // modern business-rule designer uses. It used to compile a client-side WWF XAML fallback when that+ // member faulted; that fallback was DELETED upstream because it covered only 4 of the 7 action+ // types and one clause, so it silently narrowed a rule into something the platform would accept but+ // that did not say what the author wrote.+ //+ // The consequence is environment-visible and is handled below: an environment that does not declare+ // the member cannot host business rules AT ALL.+ //+ // MEASURED across a broad sample of environments: only a small minority declare the member, so the+ // gate is the COMMON case, not an edge case. Note also that declaring the member is NOT the same as+ // it working — some environments answer a real push with a server-side `MissingMethodException`,+ // which is a platform defect there rather than anything about the rule. See the+ // `businessRuleApiUnavailable` handling.if (has('business-rules')) {+ // Warn ONCE per build, not once per rule: on an environment without the member every rule skips,+ // and N copies of the same paragraph buries the rest of the build output.+ let businessRuleApiWarned = false;+ // A rule is skipped only for this ONE reason; anything else still halts. Matching is on the+ // SDK's documented `code`, never on `err.name` — the bundle is minified, so the class name is a+ // rebuild-unstable string (`Xe`, which is really the base SdkError), and matching it would+ // silently disarm this guard the next time the bundle is rebuilt.+ const businessRuleApiUnavailable = (err) => (err && err.code === 'BUSINESS_RULE_API_UNAVAILABLE'+ ? 'unsupported in this environment'+ : false);for (const rule of spec.businessRules || []) {const entityLogical = String(rule.entity).toLowerCase();const existing = await provision.queryRecords('workflow', {@@ -1516,11 +1822,16 @@ async function runSdkBuild(spec, opts = {}) {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 */ }+ let why = '';+ // Capture the REAL reason instead of asserting one. A 403 (no delete privilege), a 429, or+ // a transport failure look identical to the wedged-row case from the outside, and a warning+ // that names the wrong cause sends the reader to Maker to hand-delete a row they actually+ // lack rights to touch.+ try { await provision.deleteRecord('workflow', extra.workflowid); removed = true; } catch (e) { why = (e && e.message) ? String(e.message).replace(/\s+/g, ' ').slice(0, 200) : String(e); }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.`);+ : `business rule "${rule.name}": a duplicate left by an earlier build (${extra.workflowid}) could not be removed (${why}). Only one copy should run — remove it in Maker if the reason above is not transient. See issue #482.`);}}// Reuse — but a rule that EXISTS is not necessarily a rule that RUNS. A deployed rule left in@@ -1567,25 +1878,19 @@ async function runSdkBuild(spec, opts = {}) {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.+ // DE-DUPLICATE — legacy repair only.//- // 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+ // The SDK USED to fall back to a classic `workflows` row on a qualifying 400, and that+ // fallback assumed 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. 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.+ // The fallback no longer exists in the vendored SDK — business rules are written through the+ // bound member or not at all — so this sweep can no longer find a duplicate THIS build made.+ // It is KEPT because it still repairs an org that a PREVIOUS build damaged: those rows are+ // already committed and frequently refuse both deactivate and delete, so they will not+ // disappear on their own. On a clean org it costs exactly one query and finds nothing.//// 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@@ -1604,13 +1909,38 @@ async function runSdkBuild(spec, opts = {}) {// 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 */ }+ let why = '';+ // Report the REAL failure rather than asserting the wedged-row cause: a 403, 429 or+ // transport error is indistinguishable from outside, and naming the wrong one misdirects+ // whoever reads the warning.+ try { await provision.deleteRecord('workflow', extra.workflowid); removed = true; } catch (e) { why = (e && e.message) ? String(e.message).replace(/\s+/g, ' ').slice(0, 200) : String(e); }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.`);+ ? `business rule "${rule.name}": removed a duplicate left by an earlier build (${extra.workflowid})`+ : `business rule "${rule.name}": an earlier build left a duplicate (${extra.workflowid}) that could not be removed automatically (${why}). Only one copy should run — remove it in Maker if the reason above is not transient. See issue #482.`);}}+ }, {+ // An environment that does not declare the bound member cannot host business rules at all.+ // Halting here would abandon a build that has ALREADY created the solution, tables, columns,+ // forms, views and the app — leaving a half-built app and an error 90% of the way through a+ // run, for a cause the operator can do nothing about from here.+ //+ // So this degrades the way `app.newLook` already does for its tenant-gated setting: skip the+ // artifact, say so loudly and specifically, and let the rest of the app build. Nothing wrong+ // is written — the alternative the SDK deleted (compiling a narrowed rule) is precisely what+ // must not happen. The skip is recorded on the result so `--verify` and the run summary can+ // report it rather than implying the rules exist.+ skipIf: (err) => {+ const reason = businessRuleApiUnavailable(err);+ if (!reason) return false;+ result.skipped.businessRules.push(`${entityLogical}|${rule.name}`);+ if (!businessRuleApiWarned && typeof opts.warn === 'function') {+ businessRuleApiWarned = true;+ opts.warn(`business rules were NOT created: this environment does not expose the '${BUSINESS_RULE_MEMBER}' member that the modern business-rule designer uses, so there is no supported way to author them here. Everything else in the app was built normally. Re-run against an environment that exposes the member, or drop businessRules[] from the spec. Detail: ${String((err && err.message) || err).replace(/\s+/g, ' ').slice(0, 300)}`);+ }+ return reason;+ },});}}@@ -1659,7 +1989,7 @@ async function runSdkBuild(spec, opts = {}) {continue;}await runner.run('dashboards', `dashboard "${dash.name}" (${(dash.tiles || []).length} tile(s))`, async () => {- const art = provision.createArtifact('dashboard', { name: dash.name });+ const art = provision.createArtifact('dashboard', { name: dash.name, ...(dash.description ? { description: dash.description } : {}) });// 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 || [];@@ -2157,17 +2487,125 @@ async function runSdkBuild(spec, opts = {}) {if (pendingAiReconfirm.length) parts.push(`retrying after publish: ${pendingAiReconfirm.map((p) => p.feature).join(', ')}`);return parts.length ? parts.join('; ') : '(none \u2014 admin gate off)';});- const tables = (spec.ai.summaries && spec.ai.summaries.default === 'off') ? [] : selectSummaryTables(spec);- for (const logical of tables) {- const ent = (spec.entities || []).find((e) => String(e.schemaName).toLowerCase() === String(logical).toLowerCase());- if (!ent) continue;- const override = spec.ai.summaries && spec.ai.summaries.tables && (spec.ai.summaries.tables[logical] || spec.ai.summaries.tables[String(logical).toLowerCase()]);- await runner.run('ai-features', `row summary for ${logical}`, async () => {- const promptSpec = buildPromptSpec(ent, { spec, override });- const res = await provision.configureRowSummary(promptSpec, { solutionUniqueName });- result.created.ai.summaries[logical] = res;- return res.modelId;- });+ // Same rule as the plan: `selectSummaryTables` owns the default-vs-override decision, so calling+ // it unconditionally is what lets `default: 'off'` + `tables[x].enabled: true` opt a single table+ // back in. Short-circuiting here made the plan and the execution agree only by both being wrong.+ const tables = selectSummaryTables(spec);+ // Row summaries are an AI Builder / Copilot-LICENSED capability, gated per environment+ // INDEPENDENTLY of the `EnableFormInsights` org setting: an environment can report the feature+ // "on" and still refuse the publish. Live-observed on an environment whose gate reads on:+ // HTTP 403 from .../api/data/v9.0/AIModelPublish+ // {"operationStatus":"Error","error":{"type":"Error","code":"ModelNotSupported",+ // "message":"This scenario is not supported in this environment.",+ // "properties":{"exceptionStackTrace":" at Microsoft.PowerAI...LicenseChecker..."}}}+ // — i.e. a licence check, reported as a 6 KB .NET stack trace the operator can do nothing with.+ //+ // Halting there abandons a build that already created the solution, tables, columns, views, the+ // app and its AI feature settings, for a reason no change to the spec can fix. So degrade the way+ // business rules and `app.newLook` already do: skip the artifact, say so specifically, and let the+ // rest of the build finish. Nothing wrong is written — the summary simply does not exist, and the+ // skip is recorded on the result so the run summary reports it instead of implying it was created.+ let aiSummaryGateWarned = false;+ // Tables whose skipped publish may have left a committed `msdyn_aimodel` row behind.+ const pendingAiSummarySweeps = [];+ // `tables` keys are documented as entity schemaNames matched CASE-INSENSITIVELY, and+ // `selectSummaryTables` honours that when deciding what to build. Looking the override back up by+ // exact (or merely lower-cased) key therefore selected the table but dropped its `instruction` and+ // `columns` whenever the author's spelling differed from the entity's — silently substituting the+ // generated default prompt for the one they wrote. Build the same case-folded index the selector+ // uses so the two agree.+ const summaryOverrides = new Map();+ for (const [key, val] of Object.entries((spec.ai.summaries && spec.ai.summaries.tables) || {})) {+ summaryOverrides.set(String(key).toLowerCase(), val);+ }+ const DUPLICATE_MODEL_REASON = 'a model with this name already exists';+ const aiSummaryUnsupported = (err) => {+ const detail = `${(err && err.message) || ''} ${JSON.stringify((err && err.cause) || '')}`;+ // Match the platform's own error CODE, not the prose: the message is localized and the status+ // alone (403/400) is also what a plain privilege or validation failure returns, which must+ // still halt. `err.cause` carries the parsed error BODY (where `code` lives) while `err.message`+ // carries only the localized text, so both are searched — on a non-English org the code is+ // reachable only through `cause`.+ //+ // `DuplicateRecordKey` is in this set for a specific, measured reason. `configureRowSummary`+ // CREATES the `msdyn_aimodel` row and THEN publishes it, so on a gated environment the licence+ // check fails at publish with the row already committed:+ // HTTP 400 ... "code":"DuplicateRecordKey" ... Cannot insert duplicate key row in object+ // 'dbo.msdyn_AIModelBase' with unique index 'ndx_Uniquename'. The duplicate key value is+ // (<table> row summary, ...)+ // on the NEXT build. Without this, skipping the licence gate would make the first build pass+ // and every rebuild fail — strictly worse than failing consistently. The orphan is also swept+ // below so the row does not accumulate.+ //+ // The two are reported as DIFFERENT reasons: telling an operator their environment is+ // unlicensed when the real cause is a leftover row sends them to the wrong place entirely.+ if (/DuplicateRecordKey/i.test(detail)) return DUPLICATE_MODEL_REASON;+ return /ModelNotSupported|not supported in this environment/i.test(detail)+ ? 'unsupported in this environment'+ : false;+ };+ // Best-effort sweep of the row the failed publish left behind. The SDK names the model+ // "<entity> row summary" — which is also the value the platform quotes back in the duplicate-key+ // error above ("The duplicate key value is (zza_ticket row summary, ...)"), so this matches the+ // real stored name rather than a guess.+ //+ // FILTERED SERVER-SIDE, not fetched-and-scanned. `msdyn_aimodel` is a shared system table written+ // by AI Builder, Copilot Studio and other features, so a real org can hold far more rows than any+ // safety cap — an unfiltered page would silently fail to contain the orphan, leaving it forever+ // and making every rebuild fail on the duplicate key. That is the exact failure this sweep exists+ // to prevent, so the query must not depend on the orphan happening to land in the first page.+ //+ // Failure here is never fatal: the build already decided to skip, and a leftover row degrades the+ // next run at worst — it must not turn a warn-and-continue back into a halt.+ const sweepOrphanSummaryModel = async (logical) => {+ const modelName = `${String(logical).toLowerCase()} row summary`;+ try {+ const rows = await provision.queryRecords('msdyn_aimodel', {+ select: ['msdyn_aimodelid'],+ filter: `msdyn_name eq '${odataLit(modelName)}'`,+ top: 5,+ });+ for (const row of rows || []) {+ try { await provision.deleteRecord('msdyn_aimodel', row.msdyn_aimodelid); } catch { /* leave it; the next run reports it again */ }+ }+ } catch { /* no read access to msdyn_aimodel is not a build failure */ }+ };+ try {+ for (const logical of tables) {+ const ent = (spec.entities || []).find((e) => String(e.schemaName).toLowerCase() === String(logical).toLowerCase());+ if (!ent) continue;+ const override = summaryOverrides.get(String(logical).toLowerCase());+ await runner.run('ai-features', `row summary for ${logical}`, async () => {+ const promptSpec = buildPromptSpec(ent, { spec, override });+ const res = await provision.configureRowSummary(promptSpec, { solutionUniqueName });+ result.created.ai.summaries[logical] = res;+ return res.modelId;+ }, {+ skipIf: (err) => {+ const reason = aiSummaryUnsupported(err);+ if (!reason) return false;+ result.skipped.aiSummaries.push(logical);+ pendingAiSummarySweeps.push(logical);+ // Warn ONCE per build: on a gated environment every table skips for the same reason, and+ // N copies of the same paragraph buries the rest of the output.+ if (!aiSummaryGateWarned && typeof opts.warn === 'function') {+ aiSummaryGateWarned = true;+ opts.warn(reason === DUPLICATE_MODEL_REASON+ ? `AI row summaries were NOT created: an AI model named "<table> row summary" already exists for a table in this spec, so the platform refused to create another (duplicate key on 'ndx_Uniquename'). This is normally residue from an earlier run whose publish was refused after the model row was committed; the leftover row is removed so the next build can retry. Everything else in the app was built normally.`+ : `AI row summaries were NOT created: this environment does not license the row-summary (AI Builder) capability, so there is no supported way to author them here — the org's 'EnableFormInsights' setting can read ON and the publish still be refused. Everything else in the app was built normally. Re-run against a licensed environment, or set ai.summaries.default to "off" (with no per-table enabled:true) to stop requesting them.`);+ }+ return reason;+ },+ });+ }+ } finally {+ // In a `finally` on purpose: a LATER table failing for an unrelated (non-skippable) reason+ // throws out of the loop, and without this the orphan already queued by an EARLIER skipped+ // table would never be swept — leaving exactly the duplicate-key residue this sweep exists to+ // remove, and making every future rebuild fail on it.+ //+ // Swept here rather than inside `skipIf` because `skipIf` is synchronous and cannot await.+ for (const logical of pendingAiSummarySweeps) await sweepOrphanSummaryModel(logical);}}@@ -2218,6 +2656,72 @@ async function runSdkBuild(spec, opts = {}) {return `${rr.reused ? 'reused' : 'created'} — ${priv} privilege${priv === 1 ? '' : 's'}${appId && persona.appAccess !== false ? ', app access' : ''}${assigned ? `, ${assigned} assignment(s)` : ''}`;});}++ // 7b. Offer forms to specific security roles (`forms[].securityRoles`). AB#6648526.+ //+ // This runs in the SECURITY phase, not the forms phase, because a persona's role does not exist+ // until the loop above has run — `forms[]` is built at phase 6, `personas[]` at phase 13.+ //+ // The roles do NOT live in a relationship. MEASURED against a live environment: `systemform`+ // declares no many-to-many relationships and reports+ // `CanBeInManyToMany: { Value: false, CanBeChanged: false }`, there is no `systemformrole`+ // entity, and `role`'s six N:N partners are systemuser / privilege / appmodule / team /+ // application / applicationuser — none of them forms. They live INSIDE `formxml`, as a+ // `<DisplayConditions>` child of `<form>`, which is why only the SDK's dedicated call can write+ // them and why no `associateRecords` shape ever worked.+ //+ // A form with NO DisplayConditions is offered to every role, so this is a RESTRICTION: declaring+ // `securityRoles` narrows a form that was previously universal.+ const formsWithRoles = (spec.forms || []).filter((f) => f && f.securityRoles);+ for (const f of formsWithRoles) {+ const label = `${f.name || f.formType || 'Main'} on ${f.entity}`;+ const formId = result.created.formIds[formIdentityKey(f)];+ if (!formId) {+ // The forms phase did not run in this invocation (`--phases security`, or a --changed-only+ // apply). Skipping is right — silently doing nothing is not, because the author asked for a+ // restriction and its absence is a security-relevant difference.+ runner.skip('security', `form roles for ${label} (form not built in this run — re-run with the forms phase)`);+ continue;+ }+ await runner.run('security', `form roles for ${label}`, async () => {+ const sr = f.securityRoles;+ const opts2 = {};+ if (sr.everyone === true) opts2.everyone = true;+ else {+ // Personas, not GUIDs: the spec names roles the way an author does, and the build resolves+ // them against the roles it just created. An unresolved name is a HALT, not a warning — a+ // typo would otherwise silently produce a form offered to nobody.+ //+ // Matched CASE-INSENSITIVELY, because the spec gate that pre-checks these names is+ // case-insensitive. A case-sensitive lookup here made `personas: ["dispatcher"]` against a+ // declared `"Dispatcher"` pass validation and then halt in phase 7b — the LAST thing the+ // build does, after every table, form, view, chart, dashboard, page and role already+ // exists. That is precisely the half-built outcome the business-rule skip exists to avoid,+ // and it also falsified this function's own promise that a bad name is caught at the gate.+ //+ // This index is only UNAMBIGUOUS because `personas[]` already rejects two names differing+ // solely by case — a rule that lives elsewhere in app-spec.js and was written for an+ // unrelated reason. Nothing links the two, so form-security-roles.test.js pins it: relax+ // that rule and one of the two roles would silently win here, offering a form to the wrong+ // one with every other test still green.+ const roleByLower = new Map(Object.entries(result.created.roles || {})+ .map(([name, rr]) => [String(name).trim().toLowerCase(), rr]));+ opts2.roleIds = (sr.personas || []).map((p) => {+ const rr = roleByLower.get(String(canonicalPersonaName({ persona: p }) || '').toLowerCase());+ if (!rr || !rr.roleId) {+ throw new Error(`securityRoles names persona "${p}", which this build did not create a role for. Declare it in personas[], or use "everyone": true.`);+ }+ return rr.roleId;+ });+ }+ // Both are PRESERVED by the SDK when omitted, so only send what the author actually set —+ // sending `undefined` would be indistinguishable from "reset it" if that ever changes.+ if (sr.fallbackForm !== undefined) opts2.fallbackForm = sr.fallbackForm;+ if (sr.order !== undefined) opts2.order = sr.order;+ await provision.setFormSecurityRoles(formId, opts2);+ return sr.everyone === true ? 'every role' : `${opts2.roleIds.length} role(s)`;+ });+ }}// 8. Publish (opt-in). Publish ONE artifact per entity (covers that entity's customizations)@@ -2226,8 +2730,28 @@ async function runSdkBuild(spec, opts = {}) {await runner.run('publish', 'publish customizations', async () => {const seen = new Set();const perEntity = []; // [type, id] — first artifact found per entity- for (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 f of spec.forms || []) {+ const k = f.entity.toLowerCase();+ // Prefer the entity's Main form (what `created.forms` holds), but fall back to THIS form's+ // own id. A `securityRoles` assignment lands on the UNPUBLISHED layer — live-measured: the+ // published row still read `<Everyone />` until PublishXml ran — so an entity whose only+ // annotated form is, say, a QuickCreate would otherwise never be published and the+ // restriction would silently not take effect. Publishing is per-ENTITY, so any one of its+ // forms covers the rest.+ const id = result.created.forms[k] || result.created.formIds[formIdentityKey(f)];+ if (id && !seen.has(k)) { seen.add(k); 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]); } }+ // Charts too — but ONLY the ones this run created or fetched. `publishArtifact` requires the+ // artifact to be workspace-resident (readRaw -> readLocal throws ArtifactNotFoundError rather+ // than lazily fetching), and `findArtifact` does not populate the workspace. Deriving the id+ // from `result.created.charts` would therefore hand publish an id it cannot resolve for an+ // existing chart with no description to reconcile, and the throw escapes publishArtifact and+ // halts the phase. `chartsToPublish` is populated at exactly the two points that put a chart in+ // the workspace. It is also keyed by entity rather than by chart NAME, which sidesteps the+ // `result.created.charts` name-only keying (two same-named charts on different entities+ // collide there).+ for (const [k, cid] of chartsToPublish) { if (cid && !seen.has(k)) { seen.add(k); perEntity.push(['chart', cid]); } }await runner.mapLimit(perEntity, concurrency, (async ([type, id]) => reportPartialPush(await provision.publishArtifact(type, id), `${type} ${id}`, opts.warn)));if (result.created.app) reportPartialPush(await provision.publishArtifact('app', result.created.app), `app ${(spec.app && spec.app.name) || result.created.app}`, opts.warn);});@@ -2285,7 +2809,7 @@ async function runSdkBuild(spec, opts = {}) {const setting = AI_APP_SETTING[p.feature];let proof = { error: app.error };if (!app.error && setting) proof = await proveAppOverride(provision, app.appModuleId, setting);- if (!proof.error && proof.exists && sameSettingValue(proof.value, featureWantValue(flags && flags[p.feature]))) {+ if (!proof.error && proof.exists && sameSettingValue(proof.value, featureWantValue(flags && flags[p.feature], p.feature))) {reproven.push(p.feature);reprovenBy.set(p.feature, 'confirmed present after publish by the build\u2019s own override-row proof');continue;diff --git a/plugins/model-apps/scripts/lib/sdk-teardown.js b/plugins/model-apps/scripts/lib/sdk-teardown.jsindex a834eefec..c9f996c4c 100644--- a/plugins/model-apps/scripts/lib/sdk-teardown.js+++ b/plugins/model-apps/scripts/lib/sdk-teardown.js@@ -15,15 +15,23 @@// SDK reports them and the owner decides. Runs AFTER the app so the app's own// sitemap reference is already gone and the only dependency the platform can// still report is a GENUINE other consumer; such a page is SKIPPED, not deleted.-// 1b. roles — persona security roles. Deleted right after the app (BEFORE the data model): a-// role holding a soon-to-be-deleted table's privileges could otherwise block that-// table's delete. SEC-1: only roles the SDK itself authored (marked on the role-// description) are deleted — never a hand-built or managed same-name role.// 2. dashboards — systemform (type 0) rows, pinned as app components// 3. commands — appactions per entity (they reference the web-resource JS; delete first).// The SDK's command delete is ENTITY-keyed (removes every appaction on that// entity's bar in one call), so this passes the entity logical name, not an id.// 4. forms — systemform rows per entity (forms reference views/web-resources; deleted before tables)+// 4b. roles — persona security roles. Deleted AFTER the forms and BEFORE the data model, and+// both halves of that are load-bearing:+// * after forms, because `forms[].securityRoles` writes the role id into the+// form's own `formxml` as a `<DisplayConditions>` entry, which the platform+// treats as a real dependency. MEASURED: deleting the role first answered+// `HTTP 400 … The Role(<id>) component cannot be deleted because it is+// referenced by 1 other components`, and the identical delete returned 204+// with zero reported dependencies once the forms were gone.+// * before tables, because a role holding a soon-to-be-deleted table's+// privileges could otherwise block that table's delete.+// SEC-1: only roles the SDK itself authored (marked on the role description) are+// deleted — never a hand-built or managed same-name role.// 5. charts — savedqueryvisualization rows per entity (deleted before tables)// 6. views — savedquery rows per entity (deleted before tables)// 7. relationships — OneToMany/ManyToMany relationships (deleted before tables)@@ -45,7 +53,7 @@// the identical phase-grouped, status-marked log.const { topoOrderEntities } = require('./_graph.js');-const { appUniqueName, commandsByEntity, defaultViewColumns, resolveExistingFormId, resolveRoleBusinessUnit, roleBuClause, businessRuleFilter } = require('./sdk-build.js');+const { appUniqueName, commandsByEntity, defaultViewColumns, resolveExistingFormId, resolveRoleBusinessUnit, roleBuClause } = 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');@@ -74,8 +82,8 @@ function isNotFound(err) {// RelationshipDefinitions metadata id that no longer resolves — already cascaded away) does not// exist; treat it as already-gone. Only zero counts (">1 were found" is a genuine ambiguity error).return /not found|does not exist|could not find|but 0 were found/.test(msg);-}-+}+// Detect a system/managed artifact that Dataverse refuses to delete (e.g. the auto-generated// "Active <Entity>" view whose name a spec view may reuse). It is not ours to remove, so a// teardown skips it instead of failing — the same best-effort spirit as isNotFound. Deliberately@@ -316,20 +324,82 @@ const KIND_HANDLERS = {// 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) {+ // Built explicitly rather than by string-patching `businessRuleFilter()`'s output. It used to+ // be `businessRuleFilter(...).replace('type eq 1', '(type eq 1 or type eq 2)')`, which coupled+ // teardown to that function's exact spelling: any reordering or whitespace change there would+ // silently stop the widening, the type-2 row would survive, and #493's residue would come back+ // with every test still green. Same `odataLit` escaping, stated once, visible in full.+ const filter = `category eq 2 and (type eq 1 or type eq 2) and name eq '${odataLit(target.name)}' and primaryentity eq '${odataLit(String(target.entity).toLowerCase())}'`;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),+ select: ['workflowid', 'statecode', 'type', '_parentworkflowid_value'],+ // Teardown deliberately widens businessRuleFilter from the build's definition-only query:+ //+ // category eq 2 and (type eq 1 or type eq 2) and name eq '<rule>' and primaryentity eq '<entity>'+ //+ // Dataverse stores activated business rules as TWO `workflow` rows:+ // type=1, _parentworkflowid_value=(null) -> editable definition+ // type=2, _parentworkflowid_value=<def> -> activated copy+ //+ // Build/verify must ignore type 2 because it is platform-derived, but teardown owns both+ // rows while the table still exists. If the type-2 row survives until the table delete, its+ // entity ObjectTypeCode can no longer resolve and every later write fails with 400+ // 0x80041102 ("The entity with ObjectTypeCode = N was not found in the MetadataCache...").+ // Workflow row/type semantics: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/workflow+ //+ // The copy is NOT removed with its parent — live-measured: after a full teardown the type-2+ // row survives with `parent` pointing at the deleted definition, and once the table is gone+ // it can no longer be deleted at all (400 0x80041102, "entity with ObjectTypeCode = N was+ // not found in the MetadataCache"), because the platform cannot resolve the entity it+ // references. So every teardown of an ACTIVE rule strands one row while still reporting+ // `0 failed`. Tracking: https://github.com/microsoft/power-platform-skills/issues/493+ filter,top: 50,});- return (rows || []).map((r) => ({ id: r.workflowid, name: target.name, statecode: r.statecode }));+ const items = (rows || []).map((r) => ({+ id: r.workflowid,+ name: target.name,+ statecode: r.statecode,+ type: r.type,+ parentDefinitionId: r._parentworkflowid_value,+ }));+ // ORDER MATTERS, and it is the opposite of the intuitive one. Live-measured on a real org:+ //+ // * Deleting the type-2 copy FIRST is refused, because the definition still points at it:+ // 405 "Cascade Delete failed due to cascade restrict relation. Restricting entity+ // Workflow has Id: <type-1> and is collected by Relationship with name:+ // workflow_active_workflow."+ // * Deactivating the definition does NOT remove the copy — it only flips the copy to Draft+ // (statecode 0 / statuscode 1) alongside its parent.+ // * Deleting the DEFINITION succeeds and leaves the copy behind, now unreferenced.+ // * That orphaned copy then deletes cleanly — but ONLY while its table still exists. Once+ // the table is dropped it is undeletable forever (400 0x80041102).+ //+ // So: definition first, activated copy second, and both strictly before the tables phase.+ return [+ ...items.filter((r) => r.type !== 2),+ ...items.filter((r) => r.type === 2),+ ];},async del(sdk, item) {+ if (item.type === 2) {+ // Reached only AFTER the definition above was deleted, so the workflow_active_workflow+ // cascade-restrict no longer applies and the row deletes normally. A 404 here is success by+ // another name (a platform version may cascade the copy away with its parent) and+ // `tolerateNotFound` records it as already gone.+ //+ // There is deliberately NO 405 retry. An earlier version deactivated `parentDefinitionId`+ // and re-issued the same delete, which reads like defence in depth but cannot work: by this+ // point the definition row no longer EXISTS, so the deactivate 404s and the retry is+ // byte-identical to the call that just failed. It only passed review because the test mock+ // silently no-ops `updateRecord` on a missing row — a contract the real SDK does not have.+ // A genuine 405 here is a real leftover that becomes PERMANENTLY undeletable once the table+ // is dropped, so it must surface as a reported failure rather than be papered over by a+ // retry that can only ever fail the same way. See issue #493.+ return sdk.deleteRecord('workflow', item.id);+ }// Deactivate before delete. Dataverse refuses to delete an activated process, and the error it- // returns names neither the rule nor the reason clearly.+ // returns names neither the rule nor the reason clearly. This also flips the activated copy to+ // Draft, which is what makes the copy deletable in the step that follows.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 */ }}@@ -475,6 +545,35 @@ const KIND_HANDLERS = {},del: (sdk, item) => sdk.deleteWebResource(item.id),},+ // Clear a column visualization on a table that teardown deliberately KEEPS.+ //+ // FAIL-CLOSED on ownership. The configuration row is shared by every app that shows the column, and+ // the build PATCHes an existing row rather than creating a private one — so blindly writing 'None'+ // would erase a renderer another maker set after this spec built. The clear therefore only happens+ // when the CURRENT value still equals what this spec authored; anything else (someone changed it,+ // or the preview is not provisioned here) is left alone and reported as skipped.+ columnVisualization: {+ async resolve(sdk, target) {+ let current;+ try {+ current = await sdk.getColumnVisualization(target.entityLogical, target.columnLogical);+ } catch (err) {+ // A 404 means the preview is not provisioned on this environment, so there is nothing to+ // clear. Any other read failure means we cannot establish ownership — skip rather than guess.+ const status = (err && (err.statusCode || err.status)) || 0;+ return { items: [], skipReason: status === 404+ ? 'grid-visualization preview is not provisioned on this environment — nothing to clear'+ : `could not read the current visualization (${String((err && err.message) || err).slice(0, 120)}) — left alone rather than risk clearing another app's setting` };+ }+ if (current === 'None') return { items: [] };+ if (current !== target.authored) {+ return { items: [], skipReason: `column visualization on ${target.entityLogical}.${target.columnLogical} is now '${current}' but this spec authored '${target.authored}' — someone else changed it, so it is left as-is` };+ }+ return [{ id: `${target.entityLogical}.${target.columnLogical}`, entityLogical: target.entityLogical, columnLogical: target.columnLogical }];+ },+ del: (sdk, item) => sdk.setColumnVisualization(item.entityLogical, item.columnLogical, 'None'),+ tolerateNotFound: true,+ },table: {// Only tear down tables THIS build created. Skip (never delete):// · a table the spec explicitly flags as pre-existing (`existing: true`) — a reused custom@@ -560,14 +659,15 @@ function planTeardown(spec) {target: { manifestName: manifestResourceName(appUniqueName(spec)) },});}- // Persona security roles — deleted right after the app, before the data model (a role holding a- // table's privileges could block that table's delete). The role handler is SEC-1 safe (marker-gated)- // and BU-scoped. Uses the TRIMMED (canonical) persona name so it matches the name the SDK created.- for (const p of spec.personas || []) {- const name = canonicalPersonaName(p);- if (!name) continue;- steps.push({ kind: 'role', phase: 'security', label: `security role "${name}"`, target: { name, businessUnitId: p.businessUnitId } });- }+ // Persona security roles were once deleted right here, immediately after the app. They are now+ // ordered AFTER the forms below, because `forms[].securityRoles` writes the role into the form's+ // `formxml` as a `<DisplayConditions>` entry — which the platform treats as a real dependency.+ // MEASURED live: deleting the role while its form still existed answered+ // HTTP 400 ... The Role(<id>) component cannot be deleted because it is referenced by 1 other+ // components+ // and the same delete succeeded (204, zero dependencies) the moment the forms were gone. The+ // original constraint that put roles early — a role holding a table's privileges can block that+ // table's delete — is still satisfied, because forms are themselves deleted well before tables.for (const d of spec.dashboards || []) {steps.push({ kind: 'dashboard', phase: 'dashboards', label: `dashboard "${d.name}"`, target: { name: d.name } });}@@ -611,6 +711,16 @@ function planTeardown(spec) {const isMain = String(f.formType || f.type || 'main').toLowerCase() === 'main';steps.push({ kind: 'form', phase: 'forms', label: `form "${f.name}" (${f.entity})`, target: { name: f.name, entity: String(f.entity).toLowerCase(), formType: f.formType, formId: f.formId, isMain } });}+ // Persona security roles — AFTER the forms, BEFORE the data model. See the note above the+ // dashboards loop for why this moved: a form that names a role in its `<DisplayConditions>` holds a+ // platform dependency on that role, so the role cannot be deleted until the form is. The role+ // handler is SEC-1 safe (marker-gated) and BU-scoped. Uses the TRIMMED (canonical) persona name so+ // it matches the name the SDK created.+ for (const p of spec.personas || []) {+ const name = canonicalPersonaName(p);+ if (!name) continue;+ steps.push({ kind: 'role', phase: 'security', label: `security role "${name}"`, target: { name, businessUnitId: p.businessUnitId } });+ }for (const c of spec.charts || []) {steps.push({ kind: 'chart', phase: 'charts', label: `chart "${c.name}" (${c.entity})`, target: { name: c.name, entity: String(c.entity).toLowerCase() } });}@@ -638,6 +748,30 @@ function planTeardown(spec) {steps.push({ kind: 'aiSummary', phase: 'ai-summaries', label: `row summary ${logical}`, target: { entityLogicalName: logical } });}}+ // Column visualizations on tables that SURVIVE teardown. A visualization is a+ // `controlconfiguration` row bound to the attribute, so it is removed with the column when the+ // table is deleted — but a retained table keeps whatever renderer this spec applied, which is+ // residue on somebody else's table.+ //+ // A table is retained when the spec flags it `existing: true` OR when it turns out to be a+ // system/non-custom table (the table handler detects that live and skips the delete). Planning only+ // on the flag missed the second case, so a spec that declares a visualization on `account` without+ // the flag left the renderer behind. Plan a candidate for EVERY declared visualization; the+ // resolver above establishes ownership and skips a table whose value we did not author, and a+ // table this spec really does delete simply reports nothing left to clear.+ for (const e of spec.entities || []) {+ const logical = String(e.schemaName).toLowerCase();+ for (const c of e.columns || []) {+ if (!c || !c.schemaName || c.visualization === undefined || c.visualization === 'None') continue;+ steps.push({+ kind: 'columnVisualization',+ phase: 'data-model',+ label: `column visualization ${logical}.${String(c.schemaName).toLowerCase()}`,+ // `authored` is what makes the clear safe: teardown only removes a value this spec set.+ target: { entityLogical: logical, columnLogical: String(c.schemaName).toLowerCase(), authored: c.visualization },+ });+ }+ }// Tables in REVERSE topological order: topoOrderEntities lists parents-before-children (build// order); teardown deletes children-before-parents so a still-referenced parent never blocks.for (const e of topoOrderEntities(spec).slice().reverse()) {diff --git a/plugins/model-apps/scripts/lib/spec-shape.js b/plugins/model-apps/scripts/lib/spec-shape.jsindex 735121fbf..653253afb 100644--- a/plugins/model-apps/scripts/lib/spec-shape.js+++ b/plugins/model-apps/scripts/lib/spec-shape.js@@ -45,6 +45,11 @@ const COLLECTIONS = {charts: {},forms: { children: { subgrids: {}, events: {}, quickViews: {}, tabs: { children: { sections: {} } } } },commands: { children: { buttons: { children: { children: {} } } } },+ // Business rules and their nested collections. Omitted when `businessRules[]` was introduced, so+ // an object-valued `businessRules`, `conditions` or `actions` reached a raw `for...of` and threw a+ // TypeError instead of producing a validation error naming the field — the exact failure this map+ // exists to prevent.+ businessRules: { children: { conditions: {}, actions: {} } },dashboards: { children: { tiles: {} } },pages: { children: { navigatesTo: {}, dataSources: { scalar: true } } },personas: { children: { jobs: { children: { privileges: {} } }, additionalPrivileges: {} } },diff --git a/plugins/model-apps/scripts/lib/verify-spec.js b/plugins/model-apps/scripts/lib/verify-spec.jsindex f3a18857d..f7fbd0c91 100644--- a/plugins/model-apps/scripts/lib/verify-spec.js+++ b/plugins/model-apps/scripts/lib/verify-spec.js@@ -23,6 +23,31 @@ const { isVisualizationUnsupported } = require('./entity-provision.js');async function verifySpec(spec, read, opts = {}) {const checks = [];const add = (kind, name, present, detail) => checks.push({ kind, name, present: !!present, detail: detail || '' });+ // Artifacts the BUILD reported as impossible on this environment, keyed `entity|name`. Supplied by+ // the caller because verify is also runnable standalone, where no build result exists — in that+ // case the set is empty and every declared rule is checked, which is the right default: absent a+ // build's own report, "not deployed" is the honest verdict.+ const environmentSkippedRules = new Set(+ ((opts.environmentSkipped && opts.environmentSkipped.businessRules) || []).map((k) => String(k)));+ // The phases the invocation actually ran, when it ran a SUBSET. A `--changed-only` fast apply runs+ // `phases: ['pages']`, so the business-rules loop never executes and `skipped.businessRules` comes+ // back empty — which made the skip list above useless on exactly the runs that need it most, and+ // reported every rule as missing on an environment that can never host one.+ //+ // Scoped to business rules on purpose. Business rules are the only artifact class that can be+ // PERMANENTLY absent through no fault of the run; everything else is absent because something+ // failed or has not been built yet, which is precisely what verify exists to report. Generalising+ // this would turn "verify is spec-complete regardless of --phases" into "verify checks whatever+ // this run happened to touch", and the failure mode of getting THAT wrong is a verify that+ // silently checks nothing.+ const ranPhases = Array.isArray(opts.phases) ? new Set(opts.phases) : null;+ const businessRulesPhaseRan = !ranPhases || ranPhases.has('business-rules');+ // Two DIFFERENT reasons a check was not performed, kept apart because they warrant opposite+ // messages. Reporting a phase that simply did not run as "this environment cannot host it" tells+ // an operator on a perfectly healthy environment that their environment is broken — and on the+ // normal `--changed-only` fast-apply path that would be wrong every single time.+ const environmentSkipped = [];+ const phaseSkipped = [];// Entities + their declared columns.for (const e of spec.entities || []) {@@ -153,6 +178,36 @@ async function verifySpec(spec, read, opts = {}) {for (const rule of spec.businessRules || []) {const entityLogical = String(rule.entity).toLowerCase();const name = `${entityLogical}.${rule.name}`;+ // A rule the BUILD skipped because this environment cannot host business rules at all is not a+ // verification failure — it is a capability gap the operator was already told about, by name,+ // during the build. Checking it anyway would report `not deployed` forever on the 18-of-20+ // environments that lack the bound member.+ //+ // That is not merely noisy. `verify.ok` gates the process EXIT CODE, whether+ // `.last-applied.json` is written, and whether the `--changed-only` snapshot is persisted — and+ // page-bearing specs make verify MANDATORY. So a permanently-false `ok` would permanently+ // withhold the changed-only baseline, forcing a full build on every subsequent run forever.+ // Those three gates are built for TRANSIENT failures that a later run clears; this one never+ // clears.+ //+ // Reported as its own outcome rather than passed: nothing here claims the rule exists.+ if (environmentSkippedRules.has(`${entityLogical}|${rule.name}`)) {+ environmentSkipped.push(`business-rule:${name}`);+ continue;+ }+ // A phase-limited run (a `--changed-only` fast apply is `phases: ['pages']`) never executed the+ // business-rules phase, so it has no skip list to offer and demanding the rule here would fail+ // a run that never touched it. On a gated environment that turned every fast apply into a+ // non-zero exit plus an invalidated snapshot, alternating full/failing-fast forever, and the log+ // line blamed PAGES for a business-rule gate.+ //+ // Reported SEPARATELY from the environment gate: on a healthy environment the rules are deployed+ // and fine, and telling that operator their environment cannot host business rules would be+ // wrong on every fast apply they ever run.+ if (!businessRulesPhaseRan) {+ phaseSkipped.push(`business-rule:${name}`);+ continue;+ }let rows;try {// `top: 50`, not 1 — the whole point is to SEE duplicates. Scoped to DEFINITION rows only@@ -169,7 +224,20 @@ async function verifySpec(spec, read, opts = {}) {continue;}const list = rows || [];- if (!list.length) { add('business-rule', name, false, 'not deployed'); continue; }+ if (!list.length) {+ // Name the most likely cause instead of the bare fact. The SDK writes rules ONLY through the+ // bound `CreateProcessWithWfomJson` member and no longer compiles a workflow-XAML fallback, so+ // an environment that does not declare that member cannot host business rules at all — and+ // that is the COMMON case. The build already skips them with a warning, so+ // without this hint the operator reads "not deployed" as a build failure and goes looking for+ // one that is not there.+ //+ // It stays a FAIL, not a pass or a skip: the app genuinely does not have the rule the spec+ // asks for, and verify's job is to report the deployed truth.+ add('business-rule', name, false,+ 'not deployed — if the build reported "business rules were NOT created", this environment does not expose the CreateProcessWithWfomJson member and cannot host them');+ 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;@@ -402,7 +470,9 @@ async function verifySpec(spec, read, opts = {}) {for (const [feature, requested] of Object.entries(requestedFeatures)) {const setting = AI_APP_SETTING[feature];if (!setting) continue; // unknown key — validation already reports it- const want = featureWantValue(requested);+ // Feature-aware: `true` means '2' for the form-fill family and '1' elsewhere. Comparing+ // against the wrong spelling reports a correctly-applied feature as missing.+ const want = featureWantValue(requested, feature);// (1) Authoritative: does an app-scope override row exist, holding `want`?// A small retry on the ABSENT case only: an override row can lag briefly behind the write@@ -466,7 +536,15 @@ async function verifySpec(spec, read, opts = {}) {const missing2 = checks.filter((c) => !c.present);// Keep unableToRun absent (undefined) on the normal path so existing callers and tests are unaffected.- return { ok: missing2.length === 0 && !unableToRun, checks, missing: missing2, unableToRun: unableToRun || undefined };+ // `environmentSkipped` / `phaseSkipped` are likewise omitted when empty, for the same reason.+ return {+ ok: missing2.length === 0 && !unableToRun,+ checks,+ missing: missing2,+ unableToRun: unableToRun || undefined,+ ...(environmentSkipped.length ? { environmentSkipped } : {}),+ ...(phaseSkipped.length ? { phaseSkipped } : {}),+ };}function escapeRe(s) {diff --git a/plugins/model-apps/scripts/tests/ai-app-features-real-bundle.test.js b/plugins/model-apps/scripts/tests/ai-app-features-real-bundle.test.jsindex 23f3a8bdf..f78d77554 100644--- a/plugins/model-apps/scripts/tests/ai-app-features-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/ai-app-features-real-bundle.test.js@@ -1,185 +1,198 @@-'use strict';-// REAL-BUNDLE contract tests for `setAppAiFeatures` (ADO 6603383 / 6560699).-//-// The plugin's build engine branches on the SHAPE of this result — `applied` is the only success-// bucket, and `notPersisted` / `unverified` / `failed` each have to reach the user. Every other test-// of that branching drives a hand-written mock, so if a re-vendored SDK changed the bucket semantics-// the mocks would stay green while the real bundle behaved differently. That is exactly how the-// original false PASS shipped, so these drive the REAL vendored bundle over a fake httpClient and-// assert the semantics the engine relies on.-//-// The SDK's own Jest suite cannot run here (its `canvas` native module is built for the Node-20 ABI),-// which makes this the only executable check of the shipped bundle's behavior on this path.-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 = 'co_supportdesk';-const APP_ID = '11111111-1111-1111-1111-111111111111';-// The PER-APP setting for formFill. Note it doubles as its own org gate in the SDK's AI_GATE map,-// which is why the gate is deliberately read at ORG scope (an app-scope 0 must not look like "the-// environment forbids this" and permanently block re-enabling).-const SETTING = 'FormFillBarUXEnabled';-const DEF_ID = '22222222-2222-2222-2222-222222222222';--const tempDirs = [];-test.after(() => { for (const d of tempDirs) fs.rmSync(d, { recursive: true, force: true }); });--/**- * A real SDK over a fake Dataverse. `opts`:- * overrideRows - value[] returned by the /appsettings proof query. A FUNCTION is called with the- * 1-based attempt number so a test can model eventual consistency (empty, then- * the row appears). An array is returned verbatim every attempt.- * effective - what RetrieveSetting reports at APP scope (the environment-fallback value).- * gate - what RetrieveSetting reports at ORG scope (the readiness gate).- * failProof - throw from the /appsettings query (models missing read access).- * failWrite - throw from POST /SaveSettingValue.- */-function freshSdk(opts = {}) {- const { createMakerSdk } = require(BUNDLE);- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ai-real-'));- tempDirs.push(dir);- const calls = [];- let proofAttempts = 0;- const httpClient = {- get: async (url) => {- calls.push({ method: 'GET', url });- // /RetrieveSetting(SettingName='X') -> ORG scope (the readiness gate)- // /RetrieveSetting(SettingName='X',AppUniqueName='Y') -> APP scope (effective, may fall back)- if (url.includes('/RetrieveSetting(')) {- const scoped = url.includes('AppUniqueName=');- const value = scoped ? opts.effective : opts.gate;- return { status: 200, headers: {}, body: { SettingDetail: { Value: value, DataType: 0 } } };- }- if (url.includes('/appmodules')) {- return { status: 200, headers: {}, body: { value: opts.noApp ? [] : [{ appmoduleid: APP_ID }] } };- }- if (url.includes('/settingdefinitions')) {- return { status: 200, headers: {}, body: { value: [{ settingdefinitionid: DEF_ID }] } };- }- if (url.includes('/appsettings')) {- proofAttempts += 1;- if (opts.failProof) throw new Error('403 forbidden');- const rows = typeof opts.overrideRows === 'function' ? opts.overrideRows(proofAttempts) : (opts.overrideRows || []);- return { status: 200, headers: {}, body: { value: rows } };- }- return { status: 200, headers: {}, body: {} };- },- post: async (url, body) => {- calls.push({ method: 'POST', url, body });- if (url.includes('/SaveSettingValue') && opts.failWrite) throw new Error('boom from SaveSettingValue');- return { status: 204, headers: {}, 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();- return { sdk, calls, proofCount: () => proofAttempts };-}-// `verifyDelayMs: 0` keeps the retry budget instant — the real default backs off up to ~3s.-const FAST = { verifyDelayMs: 0 };--test('REAL BUNDLE: a proven app-scope override row is the only thing that yields `applied`', async () => {- const { sdk } = freshSdk({ gate: '1', effective: '1', overrideRows: [{ value: '1' }] });- const r = await sdk.setAppAiFeatures(APP, { formFill: true }, FAST);- assert.deepStrictEqual(r.applied, ['formFill']);- assert.deepStrictEqual([r.notPersisted, r.unverified, r.failed], [[], [], []]);- assert.strictEqual(r.outcomes[0].appOverrideExists, true);-});--test('REAL BUNDLE: an ENV-fallback match with NO override row is notPersisted, not applied', async () => {- // The false PASS the plugin's verify oracle also had to fix: RetrieveSetting at app scope returns- // the ENVIRONMENT value, so the write reads back as requested while `appsettings` holds no row.- const { sdk } = freshSdk({ gate: '1', effective: '1', overrideRows: [] });- const r = await sdk.setAppAiFeatures(APP, { formFill: true }, FAST);- assert.deepStrictEqual(r.applied, [], 'an env-fallback read must never count as applied');- assert.deepStrictEqual(r.notPersisted, ['formFill']);- assert.strictEqual(r.outcomes[0].status, 'notPersisted');-});--test('REAL BUNDLE: a write that becomes visible late is retried and reported applied', async () => {- // Eventual consistency: an immediate read can miss a write that DID land. Reporting that as failed- // produced a false `notPersisted` on first apply (a re-run then looked clean).- const { sdk, proofCount } = freshSdk({ gate: '1', effective: '1', overrideRows: (n) => (n >= 3 ? [{ value: '1' }] : []) });- const r = await sdk.setAppAiFeatures(APP, { formFill: true }, FAST);- assert.deepStrictEqual(r.applied, ['formFill'], 'the retry budget must absorb read lag');- assert.strictEqual(proofCount(), 3, 'stops as soon as the override is observed');-});--test('REAL BUNDLE: an unreadable override row is `unverified`, never applied and never notPersisted', async () => {- const { sdk } = freshSdk({ gate: '1', effective: '1', failProof: true });- const r = await sdk.setAppAiFeatures(APP, { formFill: true }, FAST);- assert.deepStrictEqual(r.unverified, ['formFill']);- assert.deepStrictEqual([r.applied, r.notPersisted], [[], []]);- assert.strictEqual(r.outcomes[0].appOverrideExists, undefined, 'no stale existence flag when we could not look');-});--test('REAL BUNDLE: a throwing write lands in `failed` and does not abort the batch', async () => {- const { sdk } = freshSdk({ gate: '1', effective: '1', failWrite: true });- const r = await sdk.setAppAiFeatures(APP, { formFill: true, nlChart: true }, FAST);- assert.deepStrictEqual(r.failed.sort(), ['formFill', 'nlChart'], 'every feature still reports');- assert.deepStrictEqual(r.applied, []);- assert.match(r.outcomes[0].reason, /boom from SaveSettingValue/);-});--test('REAL BUNDLE: an org gate that is off yields `skipped` and issues no write', async () => {- const { sdk, calls } = freshSdk({ gate: '0', effective: '0', overrideRows: [] });- const r = await sdk.setAppAiFeatures(APP, { formFill: true }, FAST);- assert.deepStrictEqual(r.skipped, ['formFill']);- assert.strictEqual(calls.filter((c) => c.method === 'POST' && c.url.includes('SaveSettingValue')).length, 0);-});--test('REAL BUNDLE: disabling is never gated — it writes even when the org gate is off', async () => {- const { sdk, calls } = freshSdk({ gate: '0', effective: '0', overrideRows: [{ value: '0' }] });- const r = await sdk.setAppAiFeatures(APP, { formFill: false }, FAST);- assert.deepStrictEqual(r.applied, ['formFill'], 'an explicit disable must always be applied');- const write = calls.find((c) => c.method === 'POST' && c.url.includes('SaveSettingValue'));- assert.strictEqual(write.body.Value, '0');-});--test('REAL BUNDLE: an explicit integer value (2 = on for everyone) is written verbatim', async () => {- // The plugin's spec schema allows this precisely because the SDK does; a boolean-only contract made- // the platform's documented `2` inexpressible (ADO 6560699).- const { sdk, calls } = freshSdk({ gate: '1', effective: '2', overrideRows: [{ value: '2' }] });- const r = await sdk.setAppAiFeatures(APP, { formFill: 2 }, FAST);- assert.deepStrictEqual(r.applied, ['formFill']);- assert.strictEqual(calls.find((c) => c.method === 'POST' && c.url.includes('SaveSettingValue')).body.Value, '2');-});--test('REAL BUNDLE: an out-of-range or non-numeric value throws BEFORE any write is issued', async () => {- // The plugin's validateAppSpec bound mirrors this, so a spec never reaches a half-applied batch.- for (const bad of [-1, 1.5, 1000001, 'off']) {- const { sdk, calls } = freshSdk({ gate: '1', effective: '1', overrideRows: [{ value: '1' }] });- await assert.rejects(() => sdk.setAppAiFeatures(APP, { formFill: bad }, FAST), /must be a boolean or an integer/, `expected ${bad} to be rejected`);- assert.strictEqual(calls.filter((c) => c.method === 'POST').length, 0, `no write may be issued for ${bad}`);- }-});--test('REAL BUNDLE: an empty appUniqueName throws rather than writing at ORGANIZATION scope', async () => {- // Silently omitting AppUniqueName changes the feature for the WHOLE environment. The plugin always- // passes appUniqueName(spec), but this is the backstop that makes a regression there loud.- const { sdk, calls } = freshSdk({ gate: '1', effective: '1', overrideRows: [{ value: '1' }] });- await assert.rejects(() => sdk.setAppAiFeatures('', { formFill: true }, FAST), /non-empty appUniqueName/);- assert.strictEqual(calls.filter((c) => c.method === 'POST').length, 0);-});--test('REAL BUNDLE: the override proof is scoped to THIS app and THIS setting', async () => {- const { sdk, calls } = freshSdk({ gate: '1', effective: '1', overrideRows: [{ value: '1' }] });- await sdk.setAppAiFeatures(APP, { formFill: true }, FAST);- const proof = calls.find((c) => c.url.includes('/appsettings'));- assert.ok(proof, 'the override row must actually be queried');- // GUID lookup values are compared UNQUOTED in an OData $filter.- assert.ok(proof.url.includes(`_parentappmoduleid_value%20eq%20${APP_ID}`) || proof.url.includes(`_parentappmoduleid_value eq ${APP_ID}`), `app not scoped: ${proof.url}`);- assert.ok(proof.url.includes(DEF_ID), `setting not scoped: ${proof.url}`);- // ...and the app id came from THIS app's unique name.- assert.ok(calls.some((c) => c.url.includes('/appmodules') && c.url.includes(APP)), 'app module resolved by unique name');-});+'use strict';+// REAL-BUNDLE contract tests for `setAppAiFeatures` (ADO 6603383 / 6560699).+//+// The plugin's build engine branches on the SHAPE of this result — `applied` is the only success+// bucket, and `notPersisted` / `unverified` / `failed` each have to reach the user. Every other test+// of that branching drives a hand-written mock, so if a re-vendored SDK changed the bucket semantics+// the mocks would stay green while the real bundle behaved differently. That is exactly how the+// original false PASS shipped, so these drive the REAL vendored bundle over a fake httpClient and+// assert the semantics the engine relies on.+//+// The SDK's own Jest suite cannot run here (its `canvas` native module is built for the Node-20 ABI),+// which makes this the only executable check of the shipped bundle's behavior on this path.+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 = 'co_supportdesk';+const APP_ID = '11111111-1111-1111-1111-111111111111';+// The PER-APP setting for formFill. Note it doubles as its own org gate in the SDK's AI_GATE map,+// which is why the gate is deliberately read at ORG scope (an app-scope 0 must not look like "the+// environment forbids this" and permanently block re-enabling).+const SETTING = 'FormFillBarUXEnabled';+const DEF_ID = '22222222-2222-2222-2222-222222222222';++const tempDirs = [];+test.after(() => { for (const d of tempDirs) fs.rmSync(d, { recursive: true, force: true }); });++/**+ * A real SDK over a fake Dataverse. `opts`:+ * overrideRows - value[] returned by the /appsettings proof query. A FUNCTION is called with the+ * 1-based attempt number so a test can model eventual consistency (empty, then+ * the row appears). An array is returned verbatim every attempt.+ * effective - what RetrieveSetting reports at APP scope (the environment-fallback value).+ * gate - what RetrieveSetting reports at ORG scope (the readiness gate).+ * failProof - throw from the /appsettings query (models missing read access).+ * failWrite - throw from POST /SaveSettingValue.+ */+function freshSdk(opts = {}) {+ const { createMakerSdk } = require(BUNDLE);+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ai-real-'));+ tempDirs.push(dir);+ const calls = [];+ let proofAttempts = 0;+ const httpClient = {+ get: async (url) => {+ calls.push({ method: 'GET', url });+ // /RetrieveSetting(SettingName='X') -> ORG scope (the readiness gate)+ // /RetrieveSetting(SettingName='X',AppUniqueName='Y') -> APP scope (effective, may fall back)+ if (url.includes('/RetrieveSetting(')) {+ const scoped = url.includes('AppUniqueName=');+ const value = scoped ? opts.effective : opts.gate;+ return { status: 200, headers: {}, body: { SettingDetail: { Value: value, DataType: 0 } } };+ }+ if (url.includes('/appmodules')) {+ return { status: 200, headers: {}, body: { value: opts.noApp ? [] : [{ appmoduleid: APP_ID }] } };+ }+ if (url.includes('/settingdefinitions')) {+ return { status: 200, headers: {}, body: { value: [{ settingdefinitionid: DEF_ID }] } };+ }+ if (url.includes('/appsettings')) {+ proofAttempts += 1;+ if (opts.failProof) throw new Error('403 forbidden');+ const rows = typeof opts.overrideRows === 'function' ? opts.overrideRows(proofAttempts) : (opts.overrideRows || []);+ return { status: 200, headers: {}, body: { value: rows } };+ }+ return { status: 200, headers: {}, body: {} };+ },+ post: async (url, body) => {+ calls.push({ method: 'POST', url, body });+ if (url.includes('/SaveSettingValue') && opts.failWrite) throw new Error('boom from SaveSettingValue');+ return { status: 204, headers: {}, 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();+ return { sdk, calls, proofCount: () => proofAttempts };+}+// `verifyDelayMs: 0` keeps the retry budget instant — the real default backs off up to ~3s.+const FAST = { verifyDelayMs: 0 };++test('REAL BUNDLE: a proven app-scope override row is the only thing that yields `applied`', async () => {+ const { sdk } = freshSdk({ gate: '2', effective: '2', overrideRows: [{ value: '2' }] });+ const r = await sdk.setAppAiFeatures(APP, { formFill: true }, FAST);+ assert.deepStrictEqual(r.applied, ['formFill']);+ assert.deepStrictEqual([r.notPersisted, r.unverified, r.failed], [[], [], []]);+ assert.strictEqual(r.outcomes[0].appOverrideExists, true);+});++test('REAL BUNDLE: an ENV-fallback match with NO override row is notPersisted, not applied', async () => {+ // The false PASS the plugin's verify oracle also had to fix: RetrieveSetting at app scope returns+ // the ENVIRONMENT value, so the write reads back as requested while `appsettings` holds no row.+ // The whole point is that the app-scope read MATCHES the request while no override row exists —+ // that is what makes the env-fallback read look like success. So `effective` must be the value the+ // request resolves to ('2' = enabled for this family); stubbing '1' would mean the read disagrees+ // with the request anyway, and the test would pass for the wrong reason.+ const { sdk } = freshSdk({ gate: '2', effective: '2', overrideRows: [] });+ const r = await sdk.setAppAiFeatures(APP, { formFill: true }, FAST);+ assert.deepStrictEqual(r.applied, [], 'an env-fallback read must never count as applied');+ assert.deepStrictEqual(r.notPersisted, ['formFill']);+ assert.strictEqual(r.outcomes[0].status, 'notPersisted');+});++test('REAL BUNDLE: a write that becomes visible late is retried and reported applied', async () => {+ // Eventual consistency: an immediate read can miss a write that DID land. Reporting that as failed+ // produced a false `notPersisted` on first apply (a re-run then looked clean).+ const { sdk, proofCount } = freshSdk({ gate: '2', effective: '2', overrideRows: (n) => (n >= 3 ? [{ value: '2' }] : []) });+ const r = await sdk.setAppAiFeatures(APP, { formFill: true }, FAST);+ assert.deepStrictEqual(r.applied, ['formFill'], 'the retry budget must absorb read lag');+ assert.strictEqual(proofCount(), 3, 'stops as soon as the override is observed');+});++test('REAL BUNDLE: an unreadable override row is `unverified`, never applied and never notPersisted', async () => {+ // The ORG GATE and the PER-APP setting use different encodings, which is easy to conflate: the+ // per-app form-fill value is 0=platform default / 1=disabled / 2=enabled, but the gate+ // short-circuits only on '0'. MEASURED by mutating this fixture: '0' makes both this test and the+ // next FAIL (the SDK skips before it writes or proves), while '1' and '2' both reach the path and+ // pass identically. '2' is used here purely so a fixture for a `formFill: true` request does not+ // read as "disabled".+ const { sdk } = freshSdk({ gate: '2', effective: '2', failProof: true });+ const r = await sdk.setAppAiFeatures(APP, { formFill: true }, FAST);+ assert.deepStrictEqual(r.unverified, ['formFill']);+ assert.deepStrictEqual([r.applied, r.notPersisted], [[], []]);+ assert.strictEqual(r.outcomes[0].appOverrideExists, undefined, 'no stale existence flag when we could not look');+});++test('REAL BUNDLE: a throwing write lands in `failed` and does not abort the batch', async () => {+ const { sdk } = freshSdk({ gate: '2', effective: '2', failWrite: true });+ const r = await sdk.setAppAiFeatures(APP, { formFill: true, nlChart: true }, FAST);+ assert.deepStrictEqual(r.failed.sort(), ['formFill', 'nlChart'], 'every feature still reports');+ assert.deepStrictEqual(r.applied, []);+ assert.match(r.outcomes[0].reason, /boom from SaveSettingValue/);+});++test('REAL BUNDLE: an org gate that is off yields `skipped` and issues no write', async () => {+ const { sdk, calls } = freshSdk({ gate: '0', effective: '0', overrideRows: [] });+ const r = await sdk.setAppAiFeatures(APP, { formFill: true }, FAST);+ assert.deepStrictEqual(r.skipped, ['formFill']);+ assert.strictEqual(calls.filter((c) => c.method === 'POST' && c.url.includes('SaveSettingValue')).length, 0);+});++test('REAL BUNDLE: disabling is never gated — it writes even when the org gate is off', async () => {+ const { sdk, calls } = freshSdk({ gate: '0', effective: '1', overrideRows: [{ value: '1' }] });+ const r = await sdk.setAppAiFeatures(APP, { formFill: false }, FAST);+ assert.deepStrictEqual(r.applied, ['formFill'], 'an explicit disable must always be applied');+ const write = calls.find((c) => c.method === 'POST' && c.url.includes('SaveSettingValue'));+ assert.strictEqual(write.body.Value, '1', "'1' is DISABLED for this family; '0' would mean platform default");+});++test('REAL BUNDLE: an explicit integer value (2 = on for everyone) is written verbatim', async () => {+ // The plugin's spec schema allows this precisely because the SDK does; a boolean-only contract made+ // the platform's documented `2` inexpressible (ADO 6560699).+ const { sdk, calls } = freshSdk({ gate: '2', effective: '2', overrideRows: [{ value: '2' }] });+ const r = await sdk.setAppAiFeatures(APP, { formFill: 2 }, FAST);+ assert.deepStrictEqual(r.applied, ['formFill']);+ assert.strictEqual(calls.find((c) => c.method === 'POST' && c.url.includes('SaveSettingValue')).body.Value, '2');+});++test('REAL BUNDLE: an out-of-range or non-numeric value throws BEFORE any write is issued', async () => {+ // The plugin's validateAppSpec bound mirrors this, so a spec never reaches a half-applied batch.+ for (const bad of [-1, 1.5, 1000001, 'off']) {+ const { sdk, calls } = freshSdk({ gate: '1', effective: '1', overrideRows: [{ value: '1' }] });+ await assert.rejects(() => sdk.setAppAiFeatures(APP, { formFill: bad }, FAST), /must be a boolean or an integer/, `expected ${bad} to be rejected`);+ assert.strictEqual(calls.filter((c) => c.method === 'POST').length, 0, `no write may be issued for ${bad}`);+ }+});++test('REAL BUNDLE: an empty appUniqueName throws rather than writing at ORGANIZATION scope', async () => {+ // Silently omitting AppUniqueName changes the feature for the WHOLE environment. The plugin always+ // passes appUniqueName(spec), but this is the backstop that makes a regression there loud.+ const { sdk, calls } = freshSdk({ gate: '1', effective: '1', overrideRows: [{ value: '1' }] });+ await assert.rejects(() => sdk.setAppAiFeatures('', { formFill: true }, FAST), /non-empty appUniqueName/);+ assert.strictEqual(calls.filter((c) => c.method === 'POST').length, 0);+});++test('REAL BUNDLE: the override proof is scoped to THIS app and THIS setting', async () => {+ // '2' (enabled), not '1' (disabled), for a `formFill: true` request — see the note above on the+ // gate vs per-app encodings. Measured to behave identically; this only removes the contradiction+ // between what the fixture says and what the request asks for.+ const { sdk, calls } = freshSdk({ gate: '2', effective: '2', overrideRows: [{ value: '2' }] });+ await sdk.setAppAiFeatures(APP, { formFill: true }, FAST);+ const proof = calls.find((c) => c.url.includes('/appsettings'));+ assert.ok(proof, 'the override row must actually be queried');+ // GUID lookup values are compared UNQUOTED in an OData $filter.+ assert.ok(proof.url.includes(`_parentappmoduleid_value%20eq%20${APP_ID}`) || proof.url.includes(`_parentappmoduleid_value eq ${APP_ID}`), `app not scoped: ${proof.url}`);+ assert.ok(proof.url.includes(DEF_ID), `setting not scoped: ${proof.url}`);+ // ...and the app id came from THIS app's unique name.+ assert.ok(calls.some((c) => c.url.includes('/appmodules') && c.url.includes(APP)), 'app module resolved by unique name');+});// --- pre-publish verification via an explicitly supplied appModuleId -------------------------// A freshly created appmodule is NOT readable until it is PUBLISHED: Dataverse omits it from list@@ -192,7 +205,7 @@ test('REAL BUNDLE: the override proof is scoped to THIS app and THIS setting', atest('REAL BUNDLE: a supplied appModuleId proves the override PRE-PUBLISH (app not yet listable)', async () => {// `noApp: true` models the pre-publish reality: the by-name appmodule query returns NO rows.// Without appModuleId this is unverifiable; with it, the proof succeeds.- const { sdk } = freshSdk({ noApp: true, gate: '1', effective: '1', overrideRows: [{ value: '1' }] });+ const { sdk } = freshSdk({ noApp: true, gate: '2', effective: '2', overrideRows: [{ value: '2' }] });const r = await sdk.setAppAiFeatures(APP, { formFill: true }, { ...FAST, appModuleId: APP_ID });assert.deepStrictEqual(r.applied, ['formFill'], `expected applied, got ${JSON.stringify(r)}`);assert.deepStrictEqual([r.notPersisted, r.unverified, r.failed], [[], [], []]);@@ -224,4 +237,4 @@ test('REAL BUNDLE: a supplied appModuleId that DISAGREES with the published apptest('REAL BUNDLE: a malformed appModuleId is rejected up front', async () => {const { sdk } = freshSdk({ gate: '1', effective: '1', overrideRows: [{ value: '1' }] });await assert.rejects(() => sdk.setAppAiFeatures(APP, { formFill: true }, { ...FAST, appModuleId: 'not-a-guid' }));-});+});diff --git a/plugins/model-apps/scripts/tests/ai-preflight.test.js b/plugins/model-apps/scripts/tests/ai-preflight.test.jsindex 1ef02022e..74038abb0 100644--- a/plugins/model-apps/scripts/tests/ai-preflight.test.js+++ b/plugins/model-apps/scripts/tests/ai-preflight.test.js@@ -298,3 +298,31 @@ test('an unresolvable --app makes effective values INDETERMINATE, not environmenassert.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');});++test('a platform-default value is reported as UNKNOWN, not as off', () => {+ // For the AI form-fill family `0` means "defer to service flighting", not "disabled". Printing ✗+ // asserts something the environment does not say — and it is exactly why a user saw form fill+ // working while an earlier report called it off across every org.+ const readiness = { formFill: { enabled: false, setting: 'FormFillBarUXEnabled', value: '0' } };+ const r = runPreflight(readiness, { formFill: { value: '0', scope: 'default', on: undefined } });+ const f = r.features.find((x) => x.feature === 'formFill');+ assert.strictEqual(f.effectiveDefault, true, 'a codec default must be flagged as the platform default');+ assert.ok(!f.effectiveIndeterminate, 'a known default is not the same as an unrecognised value');+ assert.ok(!f.inEffect, 'unknown is not a claim that it runs');+ // Still actionable: leaving it to flighting is not a deterministic choice.+ assert.strictEqual(r.adminActions.length, 1);+});++test('a codec DISABLED value is off, not on', () => {+ // The bug this replaces: any non-zero value counted as on, so `1` (DISABLED) reported as enabled.+ const { settingIsOn } = require('../lib/ai-app-settings.js');+ assert.strictEqual(settingIsOn('1', 'formFill'), false, "'1' is DISABLED for the form-fill family");+ assert.strictEqual(settingIsOn('2', 'formFill'), true, "'2' is ENABLED");+ assert.strictEqual(settingIsOn('0', 'formFill'), undefined, "'0' is the platform default, not off");+ // A feature with no codec keeps the plain numeric convention.+ assert.strictEqual(settingIsOn('1', 'nlSearch'), true);+ assert.strictEqual(settingIsOn('2', 'nlSearch'), true);+ assert.strictEqual(settingIsOn('0', 'nlSearch'), false);+ // And with no feature key at all, the old convention still applies for existing callers.+ assert.strictEqual(settingIsOn('1'), true);+});diff --git a/plugins/model-apps/scripts/tests/ai-summary-optin.test.js b/plugins/model-apps/scripts/tests/ai-summary-optin.test.jsnew file mode 100644index 000000000..f4395a50a--- /dev/null+++ b/plugins/model-apps/scripts/tests/ai-summary-optin.test.js@@ -0,0 +1,80 @@+'use strict';+// `ai.summaries.default: "off"` silently discarded an explicit per-table `enabled: true`.+//+// `selectSummaryTables` (lib/ai-candidates.js) already implements the documented semantics — its own+// comment reads "When default is 'off', only explicit opt-ins (handled above) are included", and the+// `override.enabled === true` branch runs BEFORE the `defaultOff` bail. But both call sites in+// sdk-build.js short-circuited ahead of it:+//+// const tables = (spec.ai.summaries && spec.ai.summaries.default === 'off') ? [] : selectSummaryTables(spec);+//+// so the opt-in branch was unreachable from a real build. The schema documents `default` as "the+// app-level default for all tables" and `tables` as "per-table OVERRIDES" — an override that cannot+// override is the same silent-intent-loss class this plugin exists to prevent.+//+// Found by live-running the ai-features phase: the build reported success with `summaries: {}` while+// the spec explicitly asked for one.+const test = require('node:test');+const assert = require('node:assert');++const { selectSummaryTables } = require('../lib/ai-candidates.js');+const { planFor } = require('../lib/sdk-build.js');++const specWith = (summaries) => ({+ solution: { uniqueName: 'ZZAi', publisherPrefix: 'zza' },+ app: { name: 'ZZ AI' },+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'R', subAreas: [{ entity: 'zza_ticket', title: 'Tickets' }] }] }] },+ entities: [+ {+ schemaName: 'zza_ticket',+ displayName: 'Ticket',+ pluralName: 'Tickets',+ primaryAttribute: { schemaName: 'zza_name', displayName: 'Name' },+ columns: [{ schemaName: 'zza_details', displayName: 'Details', type: 'Memo' }],+ },+ {+ schemaName: 'zza_lookupish',+ displayName: 'Lookupish',+ pluralName: 'Lookupishes',+ primaryAttribute: { schemaName: 'zza_code', displayName: 'Code' },+ // No columns at all — `hasDescriptive` is computed over `columns` only, and DESCRIPTIVE_TYPES+ // covers Integer/Money/DateTime too, so a numeric column would still qualify.+ columns: [],+ },+ ],+ ai: { summaries },+});++const OPT_IN = { default: 'off', tables: { zza_ticket: { enabled: true, instruction: 'Summarise it.' } } };++test('selectSummaryTables honours an explicit opt-in even when default is off (helper contract)', () => {+ assert.deepStrictEqual(selectSummaryTables(specWith(OPT_IN)), ['zza_ticket']);+});++test('default:off with NO opt-in still selects nothing', () => {+ assert.deepStrictEqual(selectSummaryTables(specWith({ default: 'off' })), []);+});++test('the BUILD PLAN includes the row summary for an explicit opt-in under default:off', () => {+ const labels = planFor(specWith(OPT_IN), {}).map((i) => i.label);+ assert.ok(+ labels.some((l) => /row summary for zza_ticket/.test(l)),+ `plan must include the opted-in table; got: ${JSON.stringify(labels)}`,+ );+});++test('the BUILD PLAN still includes NO row summary under default:off with no opt-in', () => {+ const labels = planFor(specWith({ default: 'off' }), {}).map((i) => i.label);+ assert.ok(!labels.some((l) => /row summary/.test(l)), `got: ${JSON.stringify(labels)}`);+});++test('an explicit enabled:false still opts a table OUT under default:auto', () => {+ const spec = specWith({ default: 'auto', tables: { zza_ticket: { enabled: false } } });+ assert.ok(!selectSummaryTables(spec).includes('zza_ticket'));+});++test('default:auto still auto-selects a descriptive table and skips a non-descriptive one', () => {+ const picked = selectSummaryTables(specWith({ default: 'auto' }));+ assert.ok(picked.includes('zza_ticket'), 'Memo column makes it a candidate');+ assert.ok(!picked.includes('zza_lookupish'), 'no descriptive column — not a candidate');+});diff --git a/plugins/model-apps/scripts/tests/appshell-required.test.js b/plugins/model-apps/scripts/tests/appshell-required.test.jsnew file mode 100644index 000000000..6db12e63f--- /dev/null+++ b/plugins/model-apps/scripts/tests/appshell-required.test.js@@ -0,0 +1,78 @@+'use strict';+// A spec with no `appShell` used to CRASH the build with a bare+// `Cannot read properties of undefined (reading 'areas')`, thrown from `appDef` at the app-shell+// phase — after the solution, tables, columns, views and the generated app icon had already been+// created in the environment. The operator got a half-built app and an error naming nothing they+// could act on.+//+// The fix is deliberately NOT "make validation require appShell". That was tried and reverted:+// 19 existing tests build minimal specs with no `appShell` under the default `deploy` profile and+// assert they validate clean, and the download round-trip depends on that permissiveness. So the+// contract stays "optional to validation", and the BUILD is what reports the problem — with a+// message that says exactly what to add.+//+// Found by live deep-testing the ai-features phase, whose spec legitimately declared no navigation.+const test = require('node:test');+const assert = require('node:assert');++const { validateAppSpec } = require('../lib/app-spec.js');+const { appDef } = require('../lib/sdk-build.js');++const base = () => ({+ solution: { uniqueName: 'ZZTest', publisherPrefix: 'zzt' },+ app: { name: 'ZZ Test' },+ entities: [{+ schemaName: 'zzt_thing',+ displayName: 'Thing',+ pluralName: 'Things',+ primaryAttribute: { schemaName: 'zzt_name', displayName: 'Name' },+ }],+});++const emptyResult = () => ({ forms: {}, views: {}, charts: {}, pages: {}, dashboards: {} });++test('validation still ACCEPTS a spec with no appShell (the permissive contract is intentional)', () => {+ const r = validateAppSpec(base());+ const shellErrors = ((r && r.errors) || []).filter((e) => /appShell/.test(e));+ assert.deepStrictEqual(shellErrors, [], 'requiring appShell breaks the download round-trip and 19 existing tests');+});++test('appDef throws an ACTIONABLE error for a missing appShell, not a raw TypeError', () => {+ let err;+ try { appDef(base(), emptyResult(), {}); } catch (e) { err = e; }+ assert.ok(err, 'a spec with no appShell must not build silently');+ // The regression witness: this is the exact string the old code produced.+ assert.ok(+ !/Cannot read properties of undefined/.test(err.message),+ `must not surface a raw TypeError; got: ${err.message}`,+ );+ assert.match(err.message, /appShell/, 'must name the key');+ assert.match(err.message, /areas/, 'must name the shape');+ assert.match(err.message, /subAreas/, 'must show the author what to add');+});++test('appDef throws the same actionable error when appShell.areas is not an array', () => {+ const spec = base();+ spec.appShell = {};+ let err;+ try { appDef(spec, emptyResult(), {}); } catch (e) { err = e; }+ assert.ok(err && /appShell/.test(err.message), 'an appShell with no areas cannot build a sitemap either');+ assert.ok(!/Cannot read properties of undefined/.test(err.message), 'still must not be a raw TypeError');+});++test('a valid appShell builds a sitemap — the guard is not a blanket reject', () => {+ const spec = base();+ spec.appShell = {+ areas: [{ label: 'Main', groups: [{ label: 'Records', subAreas: [{ entity: 'zzt_thing', title: 'Things' }] }] }],+ };+ const json = appDef(spec, emptyResult(), {});+ assert.strictEqual(json.siteMap.areas.length, 1);+ assert.strictEqual(json.siteMap.areas[0].groups[0].subAreas[0].entity, 'zzt_thing');+});++test('an EMPTY areas[] is still allowed through — it is a valid, if empty, sitemap', () => {+ const spec = base();+ spec.appShell = { areas: [] };+ const json = appDef(spec, emptyResult(), {});+ assert.deepStrictEqual(json.siteMap.areas, [], 'an explicit empty areas[] is a choice, not a mistake');+});diff --git a/plugins/model-apps/scripts/tests/artifact-descriptions.test.js b/plugins/model-apps/scripts/tests/artifact-descriptions.test.jsnew file mode 100644index 000000000..d95d4e28a--- /dev/null+++ b/plugins/model-apps/scripts/tests/artifact-descriptions.test.js@@ -0,0 +1,364 @@+'use strict';+// Descriptions on every artifact that accepts one.+//+// A description is the maker-facing "what is this for", and it is also the only grounding an agent+// has when it later inspects a deployed app it did not build. An app whose tables and columns are+// named `new_col3` and described nowhere is guessable by a human and opaque to a model, so the build+// engine writes descriptions at CREATE time rather than leaving them to a backfill nobody runs.+//+// Two invariants this file exists to protect, both discovered by MEASURING the vendored bundle+// rather than reading its types:+//+// 1. OMISSION IS NOT BLANKING. Every write site omits `description` when the spec has none. If a+// site ever sends `description: ''` instead, a rebuild silently erases a description a maker+// typed in the UI — a data-loss bug that no error message would ever surface.+//+// 2. SECURITY ROLES ARE EXCLUDED ON PURPOSE. The SDK hardcodes its own ownership marker into a+// role's description and then uses an EXACT match on that string to decide whether it may touch+// the role. Honouring an author-supplied role description would make the SDK disown its own+// role and refuse to update it. See the guard test at the bottom.+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 { viewDef, chartDef, businessRuleDef, compileFormIntent, personaRoleSpecFor } = require('../lib/sdk-build.js');+const { provisionDataModel, provisionSolution } = require('../lib/entity-provision.js');++const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');+const DESC = 'Tracks a customer support ticket from intake to resolution.';++// ------------------------------------------------------------------ spec fixtures++function baseSpec(over = {}) {+ return Object.assign({+ solution: { uniqueName: 'DESC', displayName: 'Desc', publisherPrefix: 'new' },+ app: { name: 'Desc App', description: '' },+ entities: [{+ schemaName: 'new_ticket', displayName: 'Ticket', pluralName: 'Tickets',+ primaryAttribute: { schemaName: 'new_subject', displayName: 'Subject' },+ columns: [{ schemaName: 'new_score', displayName: 'Score', type: 'Integer' }],+ }],+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Records', subAreas: [{ entity: 'new_ticket', title: 'Tickets' }] }] }] },+ }, over);+}++// ------------------------------------------------------------------ 1. validation++test('a description is accepted on every artifact that supports one', () => {+ const spec = baseSpec({+ entities: [{+ schemaName: 'new_ticket', displayName: 'Ticket', pluralName: 'Tickets', description: DESC,+ primaryAttribute: { schemaName: 'new_subject', displayName: 'Subject' },+ columns: [{ schemaName: 'new_score', displayName: 'Score', type: 'Integer', description: 'Severity 1-5.' }],+ }],+ views: [{ name: 'Open', entity: 'new_ticket', columns: [{ name: 'new_subject' }], description: 'Unresolved tickets.' }],+ charts: [{ name: 'By Score', entity: 'new_ticket', chartType: 'Column', groupBy: 'new_score', description: 'Volume by severity.' }],+ forms: [{ name: 'Ticket', entity: 'new_ticket', description: 'Primary intake form.' }],+ });+ const res = validateAppSpec(spec);+ assert.deepStrictEqual(res.errors.filter((e) => /description/i.test(e)), [], 'no description should be rejected');+});++test('a non-string description is rejected rather than stringified into Dataverse', () => {+ // `description: 42` or an accidental object would otherwise be written as "42"/"[object Object]".+ for (const bad of [42, { text: 'x' }, ['x']]) {+ const spec = baseSpec();+ spec.entities[0].description = bad;+ const res = validateAppSpec(spec);+ assert.ok(res.errors.some((e) => /description must be a string/.test(e)), `${JSON.stringify(bad)} must be rejected`);+ }+});++test('a blank description is rejected — omit the field instead', () => {+ // An empty string is the one value that would BLANK an existing description on rebuild, so it is+ // refused at author time rather than silently dropped.+ const spec = baseSpec();+ spec.entities[0].description = ' ';+ assert.ok(validateAppSpec(spec).errors.some((e) => /must not be blank/.test(e)));+});++test('a description past the Dataverse ceiling is rejected, not silently truncated', () => {+ const spec = baseSpec();+ spec.entities[0].description = 'x'.repeat(2001);+ assert.ok(validateAppSpec(spec).errors.some((e) => /2001 characters \(max 2000\)/.test(e)));+ spec.entities[0].description = 'x'.repeat(2000);+ assert.deepStrictEqual(validateAppSpec(spec).errors.filter((e) => /description/.test(e)), [], '2000 is inclusive');+});++test('descriptions stay OPTIONAL — a spec without any still validates', () => {+ // Making them mandatory would fail every spec authored before they existed.+ assert.deepStrictEqual(validateAppSpec(baseSpec()).errors.filter((e) => /description/i.test(e)), []);+});++// ------------------------------------------------------------------ 2. def builders++test('viewDef and chartDef carry the authored description', () => {+ const spec = baseSpec();+ const v = viewDef(spec, { name: 'Open', entity: 'new_ticket', description: DESC, columns: ['new_subject'] });+ assert.strictEqual(v.description, DESC);+ const c = chartDef(spec, { name: 'By Score', entity: 'new_ticket', chartType: 'Column', groupBy: 'new_score', description: DESC });+ assert.strictEqual(c.description, DESC);+});++test('viewDef and chartDef fall back to empty when none is authored', () => {+ // These two send `description` unconditionally (the SDK requires the key), so the fallback must be+ // '' rather than undefined — but the spec can never REACH that path with a blank, because a blank+ // is a validation error above.+ const spec = baseSpec();+ assert.strictEqual(viewDef(spec, { name: 'V', entity: 'new_ticket', columns: ['new_subject'] }).description, '');+ assert.strictEqual(chartDef(spec, { name: 'C', entity: 'new_ticket', chartType: 'Column', groupBy: 'new_score' }).description, '');+});++test('businessRuleDef carries a description and OMITS the key when absent', () => {+ const rule = { name: 'Escalate', entity: 'new_ticket', conditions: [], actions: [] };+ const withDesc = businessRuleDef(Object.assign({ description: DESC }, rule));+ assert.strictEqual(withDesc.description, DESC);+ assert.ok(!('description' in businessRuleDef(rule)), 'absent description must not appear as a key');+});++test('compileFormIntent carries the form description through to the SDK def', () => {+ const spec = baseSpec();+ const intent = compileFormIntent(spec, { name: 'Ticket', entity: 'new_ticket', description: DESC }, {});+ assert.strictEqual(intent.description, DESC);+ const bare = compileFormIntent(spec, { name: 'Ticket', entity: 'new_ticket' }, {});+ assert.strictEqual(bare.description, undefined, 'absent stays undefined so createArtifact omits it');+});++// ------------------------------------------------------------------ 3. table + column write path++function provisionHarness() {+ const calls = [];+ const sdk = {+ createTable: async (o) => { calls.push(['createTable', o]); return { logicalName: o.schemaName.toLowerCase(), entitySetName: `${o.schemaName.toLowerCase()}s` }; },+ createColumn: async (e, o) => { calls.push(['createColumn', o]); return { logicalName: o.schemaName.toLowerCase() }; },+ createCustomerColumn: async (e, o) => ({ logicalName: o.schemaName.toLowerCase() }),+ createGlobalOptionSet: async (o) => { calls.push(['createGlobalOptionSet', o]); return { name: o.name, metadataId: 'gc-1' }; },+ createRelationship: async (o) => ({ schemaName: o.schemaName }),+ createAlternateKey: async (e, o) => ({ logicalName: o.schemaName.toLowerCase() }),+ insertStatusValue: async () => 100000001,+ updateTable: async () => undefined,+ setColumnVisualization: async () => undefined,+ };+ const provision = {+ findTables: async () => [],+ findColumns: async () => [],+ fetchEntityMetadata: async (l) => ({ logicalName: l, entitySetName: `${l}s`, relationships: [] }),+ // Nothing pre-exists, so provisionSolution takes the create path (an existing solution returns+ // early and would never reach createSolution).+ queryRecords: async (entity) => (entity === 'solution' || entity === 'publisher' ? [] : [{ solutionid: 's' }]),+ createPublisher: async () => ({ id: '33333333-3333-3333-3333-333333333333' }),+ createSolution: async (o) => { calls.push(['createSolution', o]); return { id: 'sol-1' }; },+ };+ return { sdk, provision, calls };+}++async function runProvision(spec, h) {+ const runner = {+ run: async (phase, label, fn, o = {}) => {+ try { return await fn(); } catch (err) { if (o.skipIf && o.skipIf(err)) return undefined; throw err; }+ },+ skip: () => {},+ mapLimit: async (items, _n, fn) => { const out = []; for (const it of items) out.push(await fn(it)); return out; },+ };+ await provisionSolution({ sdk: h.sdk, provision: h.provision, runner, solution: spec.solution });+ await provisionDataModel({ spec, sdk: h.sdk, provision: h.provision, runner, preResolvedLanguageCode: 1033 });+}++test('a table and a column are CREATED with their descriptions', async () => {+ const spec = baseSpec();+ spec.entities[0].description = DESC;+ spec.entities[0].columns[0].description = 'Severity 1-5.';+ const h = provisionHarness();+ await runProvision(spec, h);+ assert.strictEqual(h.calls.find((c) => c[0] === 'createTable')[1].description, DESC);+ assert.strictEqual(h.calls.find((c) => c[0] === 'createColumn')[1].description, 'Severity 1-5.');+});++test('a table and a column with NO description omit the key entirely', async () => {+ // The blanking guard: sending `description: ''` here would wipe whatever a maker had typed.+ const h = provisionHarness();+ await runProvision(baseSpec(), h);+ assert.ok(!('description' in h.calls.find((c) => c[0] === 'createTable')[1]));+ assert.ok(!('description' in h.calls.find((c) => c[0] === 'createColumn')[1]));+});++// ------------------------------------------------------------------ 3b. solution + global choice++test('a solution and a global choice are CREATED with their descriptions', async () => {+ const spec = baseSpec();+ spec.solution.description = 'Everything the support desk needs.';+ spec.globalChoices = [{ name: 'new_severity', displayName: 'Severity', options: ['Low', 'High'], description: 'Shared severity scale.' }];+ const h = provisionHarness();+ await runProvision(spec, h);+ assert.strictEqual(h.calls.find((c) => c[0] === 'createSolution')[1].description, 'Everything the support desk needs.');+ assert.strictEqual(h.calls.find((c) => c[0] === 'createGlobalOptionSet')[1].description, 'Shared severity scale.');+});++test('a solution and a global choice with NO description omit the key', async () => {+ const spec = baseSpec();+ spec.globalChoices = [{ name: 'new_severity', displayName: 'Severity', options: ['Low', 'High'] }];+ const h = provisionHarness();+ await runProvision(spec, h);+ assert.ok(!('description' in h.calls.find((c) => c[0] === 'createSolution')[1]));+ assert.ok(!('description' in h.calls.find((c) => c[0] === 'createGlobalOptionSet')[1]));+});++// ------------------------------------------------------------------ 3c. accepted-but-inert warnings++test('a description the SDK cannot write is WARNED about, not silently dropped', async () => {+ // Both of these validate fine and build fine — the value just never reaches Dataverse. Silence+ // here is the worst outcome: the author believes the description exists.+ const spec = baseSpec();+ spec.entities[0].columns.push({ schemaName: 'new_client', displayName: 'Client', type: 'Customer', description: 'Who reported it.' });+ spec.webResources = [{ name: 'new_lib.js', type: 'script', content: 'dmFy' }];+ spec.commands = [{ entity: 'new_ticket', label: 'Escalate', library: 'new_lib.js', function: 'esc', description: 'Escalates the ticket.' }];+ const res = validateAppSpec(spec);+ assert.deepStrictEqual(res.errors.filter((e) => /description/i.test(e)), [], 'neither is an error');+ assert.ok(res.warnings.some((w) => /Customer column/.test(w) && /NOT be written/.test(w)), 'Customer column warned');+ assert.ok(res.warnings.some((w) => /command/.test(w) && /NOT be written/.test(w)), 'command warned');+});++test('app.description may be empty (legacy shape) but a new surface may not', () => {+ // download-model-app emits `app.description: ""`; rejecting it would fail specs that already work.+ const spec = baseSpec();+ spec.app.description = '';+ assert.deepStrictEqual(validateAppSpec(spec).errors.filter((e) => /description/.test(e)), []);+ // The same emptiness on a surface introduced WITH this contract is still refused.+ spec.solution.description = '';+ assert.ok(validateAppSpec(spec).errors.some((e) => /solution: description must not be blank/.test(e)));+});++// ------------------------------------------------------------------ 4. real bundle: does it reach the wire?++const dirs = [];+test.after(() => { for (const d of dirs) fs.rmSync(d, { recursive: true, force: true }); });++function sdkWithCapture() {+ const { createMakerSdk } = require(BUNDLE);+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'desc-'));+ dirs.push(dir);+ const writes = [];+ const httpClient = {+ get: async () => ({ status: 200, headers: {}, body: { value: [] } }),+ post: async (url, body) => {+ writes.push({ url: String(url), body });+ return { status: 200, headers: { 'odata-entityid': '/x(22222222-2222-2222-2222-222222222222)' }, body: {} };+ },+ postRaw: async (url, body) => { writes.push({ url: String(url), body }); return { status: 200, headers: {}, body: {} }; },+ patch: async (url, body) => { writes.push({ 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 };+}++test('REAL BUNDLE: description survives to the wire for every artifact we set it on', async () => {+ // The typed surface ACCEPTING a field proves nothing about the payload — a serializer that drops+ // it would leave every assertion above green while Dataverse received nothing. So push for real+ // against a recording client and look for the value in the request body.+ const MARK = 'WIRE_MARKER_UNIQUE';+ const cases = {+ view: { name: 'V', description: MARK, entityLogicalName: 'account', queryType: 0, isDefault: false, columns: [{ name: 'name', width: 100 }] },+ chart: { name: 'C', description: MARK, entityLogicalName: 'account', chartType: 'Column', isDefault: false, series: [{ field: 'name', aggregate: 'count' }], categories: [{ field: 'name' }] },+ form: { name: 'F', description: MARK, entityLogicalName: 'account', formType: 'main', status: 'draft' },+ dashboard: { name: 'D', description: MARK },+ businessRule: { name: 'BR', description: MARK, entityLogicalName: 'account', scope: 'Entity', status: 'Draft' },+ app: { name: 'A', uniqueName: 'cr_descapp', description: MARK, iconWebResourceId: '11111111-1111-1111-1111-111111111111' },+ };+ for (const [type, def] of Object.entries(cases)) {+ const { sdk, writes } = sdkWithCapture();+ const art = sdk.createArtifact(type, def);+ assert.strictEqual(art.description, MARK, `${type}: the typed surface keeps description`);+ // The push may fail late (the fake client returns no usable id); the write we care about has+ // already been recorded by then, so the outcome of the push is deliberately not asserted.+ try { await sdk.pushArtifact(type, art.id); } catch { /* payload already captured */ }+ assert.ok(writes.some((w) => JSON.stringify(w.body || '').includes(MARK)), `${type}: description must reach the wire`);+ }+});++// ------------------------------------------------------------------ 5. the two deliberate exclusions++test('REAL BUNDLE: a command does NOT accept a description — so the build never sends one', () => {+ // Pins why `commands[]` is absent from everything above. If a future bundle adds it, this fails+ // and the omission gets revisited on purpose instead of staying an unexplained gap.+ const { sdk } = sdkWithCapture();+ const art = sdk.createArtifact('command', { name: 'CMD', description: 'ignored', entityLogicalName: 'account', buttons: [] });+ assert.ok(!('description' in art), 'the command surface drops description; wiring one would be inert');+});++test('REAL BUNDLE: a view accepts /description as an updateElement pointer, and the push carries it (#496)', async () => {+ // The whole view mechanic in reconcileView rests on two bundle contracts that no mock can vouch+ // for, because the sdk-build mock's jpSet creates a missing key while the REAL updateElement+ // throws PathNotFoundError when its pointer resolves to undefined:+ // 1. `/description` is a resolvable pointer on a fetched view;+ // 2. the view push includes `description` in its PATCH body — which is WHY the description must+ // ride the push rather than be written as a separate record PATCH (that would be clobbered).+ // A re-vendor that changed either would otherwise go green. AGENTS.md treats re-vendoring as a+ // normal operation, so this is pinned here rather than assumed.+ const ID = '33333333-3333-3333-3333-333333333333';+ const { createMakerSdk } = require(BUNDLE);+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'view496-'));+ dirs.push(dir);+ const writes = [];+ // A deployed view as Dataverse returns it — note `description: null`, the shape a view that never+ // had one comes back as.+ const deployed = {+ savedqueryid: ID, name: 'Active Work Items', description: null,+ returnedtypecode: 'new_item', querytype: 0, isdefault: true,+ fetchxml: '<fetch><entity name="new_item"><attribute name="new_name"/></entity></fetch>',+ layoutxml: '<grid name="resultset" object="1" jump="new_name" select="1" icon="1" preview="1">'+ + '<row name="result" id="new_itemid"><cell name="new_name" width="150"/></row></grid>',+ };+ const sdk = createMakerSdk({+ workspacePath: dir,+ instanceUrl: 'https://contoso.crm.dynamics.com',+ httpClient: {+ get: async (url) => (/savedqueries\(/.test(String(url))+ ? { status: 200, headers: { etag: 'W/"1"' }, body: deployed }+ : { status: 200, headers: {}, body: { value: [] } }),+ post: async (url, body) => { writes.push({ verb: 'POST', url: String(url), body }); return { status: 200, headers: {}, 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: {} }),+ },+ });+ sdk.initWorkspace();++ await sdk.fetchArtifact('view', ID);+ const fetched = await sdk.getArtifact('view', ID);+ assert.strictEqual(fetched.description, '', 'the adapter must normalise a null description to "" — a missing key would make updateElement throw');++ await sdk.updateElement('view', ID, '/description', 'Authored text.');+ await sdk.pushArtifact('view', ID);++ const patch = writes.find((w) => w.verb === 'PATCH');+ assert.ok(patch, 'the view push must PATCH');+ assert.ok('description' in patch.body, `the push body must carry description; keys: ${Object.keys(patch.body).join(', ')}`);+ assert.strictEqual(patch.body.description, 'Authored text.');+});++test('a persona NEVER sends a description — it would break the SDK ownership guard', () => {+ // The bundle builds its role payload as+ // { name, description: SDK_ROLE_MARKER, '[email protected]': ... }+ // and gates reuse on+ // d.ismanaged !== true && (d.description ?? '') === SDK_ROLE_MARKER+ // so a role carrying an author's prose is treated as somebody else's role and the SDK THROWS+ // ("already exists ... and was not created by the SDK; refusing to modify or assign it").+ // Teardown and verify re-implement the same marker check, so all three would disagree at once.+ const spec = personaRoleSpecFor({+ persona: 'Agent', description: 'should be ignored',+ jobs: [{ name: 'Job', privileges: [{ entity: 'new_ticket', access: ['read'], scope: 'user' }] }],+ });+ assert.ok(!('description' in spec), 'persona description must not be forwarded to createPersonaRole');++ const bundle = fs.readFileSync(BUNDLE, 'utf8');+ assert.ok(+ bundle.includes('description:It.SDK_ROLE_MARKER'),+ 'the bundle still hardcodes the marker as the role description — if this changes, revisit the exclusion'+ );+});diff --git a/plugins/model-apps/scripts/tests/build-model-app.test.js b/plugins/model-apps/scripts/tests/build-model-app.test.jsindex 61a2a5fe8..11ed97269 100644--- a/plugins/model-apps/scripts/tests/build-model-app.test.js+++ b/plugins/model-apps/scripts/tests/build-model-app.test.js@@ -165,11 +165,25 @@ test('language resolution warns when org-language discovery fails but still falltest('auto-verify (opts.verify) runs the injected reconcile and attaches r.verify on pass', async () => {const { sdk } = mockSdk();let received = null;- const verify = async (s) => { received = s; return { ok: true, checks: [{ kind: 'entity', name: 'a', present: true }, { kind: 'form', name: 'b', present: true }], missing: [] }; };+ let receivedOpts = null;+ const verify = async (s, o) => { received = s; receivedOpts = o; return { ok: true, checks: [{ kind: 'entity', name: 'a', present: true }, { kind: 'form', name: 'b', present: true }], missing: [] }; };const r = await buildModelApp(desk, { apply: true, env: 'https://x', verify: true }, { sdk, verify });assert.strictEqual(r.ok, true);assert.strictEqual(received, desk, 'the injected verifier received the spec');assert.deepStrictEqual(r.verify, { ok: true, present: 2, total: 2, missing: [] });++ // The CALL SITE, which nothing covered until a reviewer pointed it out. Dropping the second+ // argument here leaves every other test green while verify goes back to reporting an+ // environment-gated business rule as `not deployed` — which drives verify.ok false, which withholds+ // the exit code, `.last-applied.json` and the `--changed-only` snapshot. The whole fix would be+ // inert and nothing would say so.+ assert.ok(receivedOpts, 'the caller must SUPPLY verify options, not just be able to forward them');+ assert.ok('environmentSkipped' in receivedOpts,+ 'the build must tell verify what this environment could not host');+ assert.deepStrictEqual(receivedOpts.environmentSkipped, r.skipped,+ 'and it must be the build result\'s own record, so the two cannot drift');+ assert.ok('phases' in receivedOpts,+ 'and which phases ran — a --changed-only fast apply produces an EMPTY skip list, so the skip list alone is not enough');});test('auto-verify surfaces a silent partial build (verify FAIL) in r.verify and the log; the build itself still succeeded', async () => {@@ -549,10 +563,18 @@ test('unableToRun is propagated from verifySpec into r.verify (RECONCILIATION 1)// the exact regression at zero cost.test('build --verify wires the role-privilege readers (httpClient + envUrl)', () => {const src = fs.readFileSync(path.join(__dirname, '..', 'build-model-app.js'), 'utf8');- const call = src.split(/\r?\n/).find((l) => l.includes('verify: (s) => verifySpec'));+ // Matched on the wiring, not the exact arity: the deps.verify lambda gained a second parameter so+ // the build can hand verify the artifacts this ENVIRONMENT could not host (an environment-gated+ // business-rule skip must not read as "not deployed"). Pinning `(s)` exactly made this test fail+ // for a change that did not touch what it is actually guarding.+ const call = src.split(/\r?\n/).find((l) => /verify: \([^)]*\) => verifySpec/.test(l));assert.ok(call, 'expected the deps.verify wiring line');assert.match(call, /httpClient/, 'entityPrivileges needs the raw client');assert.match(call, /envUrl: env/, 'entityPrivileges needs the org url to build an absolute request');+ // And the second argument must actually be forwarded, or the environment-skip list is silently+ // dropped and verify keeps failing on rules the build already reported it could not create.+ assert.match(call, /verifySpec\(\s*s\s*,[\s\S]*\)\s*,\s*verifyOpts\s*\)/,+ 'the caller-supplied verify options must reach verifySpec');});test('makeSdk returns the httpClient so the caller can wire verify', () => {@@ -1132,3 +1154,65 @@ test('--language-code only warns "no effect" for phases that genuinely create noassert.ok(!listed.includes(phase), `'${phase}' creates no labels and must not suppress the warning`);}});++test('the verify options carry the ACTUAL phase list, not a constant', () => {+ // The previous assertion was `'phases' in receivedOpts`, which any value satisfies — including a+ // hardcoded constant or an explicit undefined. A reviewer showed the --changed-only fast path+ // could be broken again with the suite green by replacing `opts.phases` with a literal.+ //+ // Asserted on the SOURCE because the value has to be the caller's own `opts.phases`: a test that+ // merely passes a phase list through would still accept `phases: PHASES`.+ const src = fs.readFileSync(path.join(__dirname, '..', 'build-model-app.js'), 'utf8');+ assert.match(src, /deps\.verify\(spec, \{ environmentSkipped: r\.skipped, phases: opts\.phases \}\)/,+ 'verify must receive the invocation\'s OWN phases — a constant re-breaks the --changed-only fast path');+});++test('a phase-limited build forwards its phase subset to verify', async () => {+ // The behavioural half: drive a real phase-limited build and confirm the subset arrives.+ // `--stage data` is used because `--apply` refuses arbitrary partial ranges — only a full build,+ // exactly `STAGES.data`, or the `--changed-only` pages fast apply are sanctioned (design §14), and+ // a refused build never reaches verify at all.+ const { STAGES } = require('../lib/stages.js');+ const { sdk } = mockSdk();+ let receivedOpts = null;+ const verify = async (s, o) => { receivedOpts = o; return { ok: true, checks: [], missing: [] }; };+ await buildModelApp(desk, { apply: true, env: 'https://x', verify: true, phases: STAGES.data }, { sdk, verify });+ assert.ok(receivedOpts, 'verify must run');+ assert.deepStrictEqual(receivedOpts.phases, STAGES.data,+ 'verify cannot tell which checks are inapplicable without the real phase list');+});++test('verify NARRATES an environment-gated skip — a green PASS must never hide one', async () => {+ // The guarantee that makes "not a check at all" safe rather than a lie. Without this line a gated+ // build prints "✓ verify PASS (14/14 present)" with no hint that a declared rule was never checked,+ // and the JSON result carries no trace either.+ const { sdk } = mockSdk();+ const cap = logCapture();+ const verify = async () => ({+ ok: true, checks: [{ kind: 'entity', name: 'a', present: true }], missing: [],+ environmentSkipped: ['business-rule:new_ticket.Lock notes'],+ });+ const r = await buildModelApp(desk, { apply: true, env: 'https://x', verify: true }, { sdk, verify, log: cap.log });+ assert.match(cap.logs.join('\n'), /not applicable on this environment/, 'the human channel');+ assert.match(cap.logs.join('\n'), /business-rule:new_ticket\.Lock notes/, 'and it must NAME what was skipped');+ assert.deepStrictEqual(r.verify.environmentSkipped, ['business-rule:new_ticket.Lock notes'],+ 'the machine channel — this is what emitResult serializes');+});++test('a phase-skipped check is narrated DIFFERENTLY from an environment-gated one', async () => {+ // Both used to share one message. On a HEALTHY environment every --changed-only fast apply runs+ // `phases: ['pages']`, so every business rule was reported as "not applicable on this environment"+ // — telling an operator whose environment works fine that it does not. Wrong 100% of the time on+ // the normal fast-apply path.+ const { sdk } = mockSdk();+ const cap = logCapture();+ const verify = async () => ({+ ok: true, checks: [{ kind: 'entity', name: 'a', present: true }], missing: [],+ phaseSkipped: ['business-rule:new_ticket.Lock notes'],+ });+ const r = await buildModelApp(desk, { apply: true, env: 'https://x', verify: true }, { sdk, verify, log: cap.log });+ assert.match(cap.logs.join('\n'), /phase did not run/, 'it must say the PHASE did not run');+ assert.doesNotMatch(cap.logs.join('\n'), /not applicable on this environment/,+ 'and must NOT blame the environment, which is working fine');+ assert.deepStrictEqual(r.verify.phaseSkipped, ['business-rule:new_ticket.Lock notes']);+});diff --git a/plugins/model-apps/scripts/tests/business-rules.test.js b/plugins/model-apps/scripts/tests/business-rules.test.jsindex b3a128e49..918734db5 100644--- a/plugins/model-apps/scripts/tests/business-rules.test.js+++ b/plugins/model-apps/scripts/tests/business-rules.test.js@@ -64,26 +64,31 @@ test('a rule must name a known entity and its own columns', () => {.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' }] }])+test('operators and actions are constrained to the slice the SDK supports', () => {+ // Outside the slice the SDK does something WORSE than throwing: an unknown operator resolves to+ // Equals, so the point of validating here is to stop a wrong rule rather than to name a field.+ assert.ok(errorsFor([{ ...RULE, conditions: [{ field: 'new_status', operator: 'NotARealOperator', value: 'x' }] }]).some((e) => /condition operator must be one of/.test(e)));+ // `ShowErrorMessage` is modelled by the SDK but deliberately not exposed yet — it needs mapping in+ // businessRuleDef that cannot be live-verified on an environment without the bound member.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']) {+ for (const operator of ['Equals', 'DoesNotEqual', 'BeginsWith', 'IsGreaterThan']) {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.+test('presence operators are ACCEPTED now that the compiler emits a null parameter list', () => {+ // These were blocked while the compiler emitted an EMPTY parameter array for a valueless operator+ // (`[New Object() { }]`) where every server-authored rule writes `<x:Null x:Key="Parameters" />`.+ // An empty Object[] is not null, and the UiData generator answered HTTP 500 on it (#481).+ //+ // Fixed upstream and re-verified LIVE on a real org with the vendored bundle: all four operators+ // push successfully in one run, where previously the two presence operators failed 500 while+ // `Equals` succeeded alongside them.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)}`);+ assert.deepStrictEqual(errs, [], `${operator} must now validate: ${JSON.stringify(errs)}`);}});@@ -154,7 +159,7 @@ test('a presence operator still MAPS correctly (the mapper is fine; the platform// --- 3. real bundle ----------------------------------------------------------------------------test('REAL BUNDLE: the mapped rule compiles to XAML naming the authored columns', async () => {+test('REAL BUNDLE: the mapped rule reaches the wire as WfomJson naming the authored columns', async () => {const { createMakerSdk } = require(BUNDLE);const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'br-spec-'));dirs.push(dir);@@ -165,8 +170,6 @@ test('REAL BUNDLE: the mapped rule compiles to XAML naming the authored columns'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: {} }),@@ -182,30 +185,143 @@ test('REAL BUNDLE: the mapped rule compiles to XAML naming the authored columns'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);+ const bound = calls.find((c) => /CreateProcessWithWfomJson/i.test(String(c.url)));+ assert.ok(bound, 'the bound member is the ONLY write path; urls: ' + JSON.stringify(calls.map((c) => c.url)));+ // There is no longer a classic `workflows` row to fall back to — the SDK deleted that compiler.+ assert.strictEqual(calls.some((c) => /\/workflows$/.test(String(c.url))), false,+ 'no classic XAML row is written any more');+ assert.deepStrictEqual(Object.keys(bound.body).sort(), ['Entity', 'WfomJson']);+// 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');+ const wfom = String(bound.body.WfomJson);+ assert.match(wfom, /new_status/, 'the condition column reaches the workflow object model');+ assert.match(wfom, /new_notes/, 'the action column reaches the workflow object model');+ assert.match(wfom, /new_ticket/, 'the rule is bound to the authored table');+});++test('REAL BUNDLE: a valueless operator emits an EMPTY operand list and the IsNull/NotNull opcode', async () => {+ // A presence operator has nothing to compare against, so the SDK must emit NO right-hand operand+ // and the dedicated opcode — not `Equals` against an empty string, which is a different question+ // and would silently answer false for a populated column.+ //+ // Measured opcodes (WorkflowConditionOperator in the bundle): NotNull "1", IsNull "0".+ const { createMakerSdk } = require(BUNDLE);+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'br-null-'));+ dirs.push(dir);++ for (const [operator, expectedOpcode] of [['ContainsData', '1'], ['DoesNotContainData', '0']]) {+ const calls = [];+ const sdk = createMakerSdk({+ workspacePath: fs.mkdtempSync(path.join(dir, 'w')), instanceUrl: 'https://contoso.crm.dynamics.com',+ httpClient: {+ get: async () => ({ status: 200, headers: {}, body: { value: [] } }),+ post: async (url, body) => {+ calls.push({ url, body });+ 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({+ name: 'Presence Rule', entity: 'new_ticket',+ conditions: [{ field: 'new_notes', operator }],+ actions: [{ type: 'SetVisibility', field: 'new_owner', visible: false }],+ });+ const art = sdk.createArtifact('businessRule', def);+ await sdk.updateElement('businessRule', art.id, '/rootCondition', def.rootCondition);+ await sdk.pushArtifact('businessRule', art.id);++ const bound = calls.find((c) => /CreateProcessWithWfomJson/i.test(String(c.url)));+ assert.ok(bound, `${operator}: the bound member must be called`);+ const wfom = JSON.parse(bound.body.WfomJson);+ const expr = wfom.steps.list[0].steps.list[0].conditionExpression;+ assert.strictEqual(expr.conditionOperatoroperator, expectedOpcode,+ `${operator} must emit opcode ${expectedOpcode}, got ${expr.conditionOperatoroperator}`);+ assert.deepStrictEqual(expr.right, [], `${operator} must carry NO right-hand operand`);+ assert.strictEqual(expr.left.attributeName, 'new_notes');+ }});// --- 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('REAL BUNDLE: dataType does NOT reach the wire — the SDK types every literal as String', async () => {+ // `dataType` used to be pinned against the XAML compiler's literal-type map. This uptake DELETED+ // that compiler, and the JSON path that replaced it does not consult the type at all: measured+ // across all 13 tokens the spec accepts (plus a made-up one), on BOTH the condition path and the+ // SetFieldValue action path, the SDK emits WorkflowAttributeType String ("14") every time.+ //+ // `let r = valueType==='Lookup' ? ... : valueType==='Clear' ? (valueWorkflowType ?? String)+ // : WorkflowAttributeType.String`+ //+ // So the field is currently DECORATIVE. It is still accepted and still validated — narrowly, so a+ // typo is caught and so the surface stays forward-compatible if the SDK starts honouring it — but+ // nothing downstream may claim it changes the deployed rule. This test exists to make that claim+ // impossible to make by accident: if the SDK begins emitting a real type, this fails and whoever+ // sees it must re-read the surface rather than discover the change in production.+ const { createMakerSdk } = require(BUNDLE);+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'br-dt-'));+ dirs.push(dir);++ const STRING_TOKEN = '14'; // WorkflowAttributeType.String, read from the bundle's own enum.+ const { BUSINESS_RULE_DATA_TYPES } = require('../lib/app-spec.js');+ // Every token the spec accepts, plus one that is not a type at all — if the SDK ever starts+ // consulting the field, a made-up value is the case most likely to behave differently.+ const TOKENS = [...BUSINESS_RULE_DATA_TYPES, 'NotAWorkflowType'];++ const push = async (def) => {+ const calls = [];+ const sdk = createMakerSdk({+ workspacePath: fs.mkdtempSync(path.join(dir, 'w')), instanceUrl: 'https://contoso.crm.dynamics.com',+ httpClient: {+ get: async () => ({ status: 200, headers: {}, body: { value: [] } }),+ post: async (url, body) => {+ calls.push({ url, body });+ 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 art = sdk.createArtifact('businessRule', def);+ await sdk.updateElement('businessRule', art.id, '/rootCondition', def.rootCondition);+ await sdk.pushArtifact('businessRule', art.id);+ return JSON.parse(calls.find((c) => /CreateProcessWithWfomJson/i.test(String(c.url))).body.WfomJson);+ };++ for (const dataType of TOKENS) {+ // 1. the CONDITION path+ const condWfom = await push(businessRuleDef({+ ...RULE, conditions: [{ field: 'new_status', operator: 'Equals', value: '1', dataType }],+ }));+ const expr = condWfom.steps.list[0].steps.list[0].conditionExpression;+ assert.strictEqual(expr.type, STRING_TOKEN, `condition dataType '${dataType}' unexpectedly reached the wire as ${expr.type}`);+ assert.strictEqual(expr.right[0].type, STRING_TOKEN, `condition dataType '${dataType}' unexpectedly typed the literal as ${expr.right[0].type}`);++ // 2. the SetFieldValue ACTION path, which reads a DIFFERENT field on a different code path — the+ // SDK does pass `valueWorkflowType` into the action serializer, so this is the one that could+ // plausibly differ, and asserting only the condition path would not have shown it.+ const actWfom = await push(businessRuleDef({+ ...RULE,+ conditions: [{ field: 'new_notes', operator: 'ContainsData' }],+ actions: [{ type: 'SetFieldValue', field: 'new_owner', value: 'x', dataType }],+ }));+ const types = [...JSON.stringify(actWfom.steps.list[0].steps.list[0].steps.list[0]).matchAll(/"type":"(\d+)"/g)].map((m) => m[1]);+ assert.ok(types.length > 0, `action dataType '${dataType}': no type token found on the wire`);+ assert.deepStrictEqual([...new Set(types)], [STRING_TOKEN],+ `action dataType '${dataType}' unexpectedly reached the wire as ${JSON.stringify([...new Set(types)])}`);+ }++ // The spec-level list stays a CLOSED set even though the SDK ignores it, so a typo is still a+ // spec-gate error rather than a silently-accepted no-op.+ assert.ok(Array.isArray(BUSINESS_RULE_DATA_TYPES) && BUSINESS_RULE_DATA_TYPES.length > 0);+ assert.ok(!BUSINESS_RULE_DATA_TYPES.includes('DateTime'),+ 'DateTime stays out: it was never exercised, and the SDK ignoring the field today is not a reason to promise a type we have not tested');});test('a DateTime dataType is rejected at the spec gate, not mid-build', () => {@@ -374,13 +490,13 @@ test('businessRuleFilter selects the definition only', () => {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.+test('every business-rule query constrains workflow type intentionally', () => {+ // A guard on the SOURCE, because the call sites are in different modules and it is the omission+ // — not a wrong value — that caused the defect. Build/verify must select definitions only; teardown+ // is the deliberate exception after #493, because it owns the activated copy before table deletion.const fs = require('node:fs');const path = require('node:path');- for (const file of ['sdk-build.js', 'verify-spec.js', 'sdk-teardown.js']) {+ for (const file of ['sdk-build.js', 'verify-spec.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@@ -388,6 +504,8 @@ test('every business-rule query in build, verify and teardown filters on type',// matching nothing.assert.deepStrictEqual(raw, [], `${file} has a business-rule query that does not constrain type: ${raw.join(' | ')}`);}+ const teardown = fs.readFileSync(path.resolve(__dirname, '..', 'lib', 'sdk-teardown.js'), 'utf8');+ assert.match(teardown, /type eq 1 or type eq 2/, 'teardown must include the activated-copy row it is responsible for deleting');});test('a rule with an activated copy present is NOT reported as duplicated', async () => {@@ -412,3 +530,367 @@ test('a rule with an activated copy present is NOT reported as duplicated', asynconst 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}`);});++// --- #488 follow-ups -----------------------------------------------------------------------------++test('a multi-condition rule is now ACCEPTED — the single-clause limit was the deleted compiler', () => {+ // This gate existed because `businessRuleXaml.ts` threw+ // "this increment supports a single clause (got N); multi-clause AND/OR is a follow-up", and+ // `bodyXml` only ever read clauses[0]. That compiler has been deleted upstream: the JSON path+ // folds N clauses with LogicalAnd, MEASURED through the real bundle (see the wire test below).+ //+ // Kept as a test rather than deleted, because re-introducing the gate would silently reject specs+ // that now deploy correctly.+ const errs = errorsFor([{+ ...RULE,+ conditions: [+ { field: 'new_status', operator: 'Equals', value: 'Closed', dataType: 'Picklist' },+ { field: 'new_owner', operator: 'Equals', value: 'x', dataType: 'String' },+ ],+ }]);+ assert.deepStrictEqual(errs, [], `a two-clause rule must validate, got ${JSON.stringify(errs)}`);+});++test('one condition still validates', () => {+ assert.deepStrictEqual(errorsFor([RULE]), []);+});++test('an object-valued businessRules is a validation error, not a TypeError', () => {+ // spec-shape normalises collections so a malformed spec fails at the gate with a message naming+ // the field. `businessRules`/`conditions`/`actions` were missing from that map, so an object where+ // an array belongs reached a raw `for...of` and threw.+ const { validateAppSpec: validate } = require('../lib/app-spec.js');+ const spec = specWith([]);+ spec.businessRules = { name: 'not an array' };+ const res = validate(spec); // must not throw+ assert.ok(Array.isArray(res.errors));+ assert.ok(res.errors.length > 0, 'a malformed businessRules must be reported');+});++test('object-valued conditions/actions are reported, not thrown', () => {+ const { validateAppSpec: validate } = require('../lib/app-spec.js');+ for (const field of ['conditions', 'actions']) {+ const spec = specWith([{ ...RULE, [field]: { bad: true } }]);+ const res = validate(spec); // must not throw+ assert.ok(Array.isArray(res.errors) && res.errors.length > 0, `${field} must be reported`);+ }+});++// --- an environment that cannot host business rules at all --------------------------------------+//+// The vendored SDK writes rules ONLY through the bound `CreateProcessWithWfomJson` member; the+// client-side XAML fallback it used to compile was deleted upstream because it covered 4 of the 7+// action types and one clause, so it silently narrowed a rule into something that did not say what+// the author wrote.+//+// The consequence is environment-visible. MEASURED live on a real environment: `$metadata` does not+// declare the member and every POST to it answers 404, and the SDK's own message reports 18 of 20+// environments in the same state. So this is the COMMON case, not an edge case.+//+// The build degrades the way `app.newLook` already does for its tenant-gated setting: skip, say so+// once and specifically, and let the rest of the app build. Halting would abandon a run that has+// already created everything else.+function provisionThatCannotAuthorRules(rows = []) {+ const calls = [];+ const err = Object.assign(new Error(+ "This environment does not expose 'Microsoft.Dynamics.CRM.CreateProcessWithWfomJson', so business rules cannot be authored here."),+ { code: 'BUSINESS_RULE_API_UNAVAILABLE' });+ 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 () => { calls.push(['pushArtifact']); throw err; },+ addSolutionComponent: async () => { calls.push(['addSolutionComponent']); },+ },+ };+}++test('an environment without the bound member SKIPS the rule instead of halting the build', async () => {+ const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();+ const { provision, calls } = provisionThatCannotAuthorRules();+ const warnings = [];+ const events = [];++ // The whole point: this resolves. Before the fix it rejected with a BuildHalt, and every phase+ // after business-rules never ran.+ const res = await runBuild(ruleOnlySpec(), {+ sdk, provisionSdk: provision, apply: true,+ phases: ['business-rules'], warn: (m) => warnings.push(m), emit: (e) => events.push(e),+ });+ assert.strictEqual(res.ok, true, 'the build must complete');++ // Nothing was written in the rule's place.+ assert.strictEqual(calls.some((c) => c[0] === 'addSolutionComponent'), false,+ 'a rule that was never created must not be added to the solution');++ // The operator is told exactly what happened and what to do, ONCE.+ assert.strictEqual(warnings.length, 1, `expected exactly one warning, got ${JSON.stringify(warnings)}`);+ assert.match(warnings[0], /business rules were NOT created/);+ assert.match(warnings[0], /CreateProcessWithWfomJson/, 'name the member so it can be searched for');+ assert.match(warnings[0], /Everything else in the app was built normally/);++ // The skip is visible in the event stream, and labelled for what it IS — not "(exists)".+ const skip = events.find((e) => e.phase === 'business-rules' && e.status === 'skip');+ assert.ok(skip, `expected a skip event; got ${JSON.stringify(events.map((e) => [e.phase, e.status, e.label]))}`);+ assert.match(skip.label, /unsupported in this environment/);+ assert.doesNotMatch(skip.label, /exists/, 'labelling this "(exists)" states the opposite of the truth');++ // And it is recorded on the result, so --verify and the summary can report it rather than+ // implying the rules are there. Keyed off the spec so a rename of the fixture cannot make this+ // assertion vacuous.+ const only = ruleOnlySpec().businessRules[0];+ assert.deepStrictEqual(res.skipped.businessRules, [`${only.entity.toLowerCase()}|${only.name}`]);+ assert.strictEqual(Object.keys(res.created.businessRules).length, 0);+});++test('the unsupported-environment warning is emitted ONCE, not once per rule', async () => {+ // On such an environment EVERY rule skips, so a per-rule paragraph would bury the rest of the+ // build output under copies of the same text.+ const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();+ const { provision } = provisionThatCannotAuthorRules();+ const warnings = [];+ const spec = ruleOnlySpec();+ spec.businessRules = [+ { ...RULE, name: 'Rule A' },+ { ...RULE, name: 'Rule B' },+ { ...RULE, name: 'Rule C' },+ ];+ const res = await runBuild(spec, {+ sdk, provisionSdk: provision, apply: true, phases: ['business-rules'], warn: (m) => warnings.push(m),+ });+ assert.strictEqual(res.ok, true);+ assert.strictEqual(warnings.length, 1, `expected one warning for three rules, got ${warnings.length}`);+ assert.strictEqual(res.skipped.businessRules.length, 3, 'but every skipped rule is still recorded');+});++test('any OTHER business-rule failure still HALTS — the skip is not a blanket catch', async () => {+ // The dangerous over-correction: swallowing every push failure would turn a real breakage (403,+ // 429, a malformed rule) into a silently ruleless app that reports success.+ const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();+ for (const code of ['CONNECTION_ERROR', 'VALIDATION_ERROR', undefined]) {+ const { provision } = provisionThatCannotAuthorRules();+ provision.pushArtifact = async () => { throw Object.assign(new Error('boom'), code ? { code } : {}); };+ await assert.rejects(+ () => runBuild(ruleOnlySpec(), { sdk, provisionSdk: provision, apply: true, phases: ['business-rules'], warn: () => {} }),+ `code ${String(code)} must still halt the build`);+ }+});++// --- the operator table, and why it must mirror the SDK exactly ---------------------------------++test('REAL BUNDLE: every spec operator EXISTS in the SDK table, and none silently becomes Equals', () => {+ // The sharp edge. The serializer resolves an operator with+ // `Uf[operator] ?? WorkflowConditionOperator.Equal`+ // so an operator the SDK does not know is not rejected — it becomes EQUALS. A spec written with+ // `GreaterThan` (which is NOT the table's spelling; it is `IsGreaterThan`) would deploy, activate,+ // and quietly test equality instead.+ //+ // Pinned against the bundle's own table so a re-vendor that renames or drops an operator fails+ // here rather than in production.+ const bundle = fs.readFileSync(BUNDLE, 'utf8');+ const m = bundle.match(/\b[A-Za-z_$][\w$]*=\{Equals:[^}]*\}/);+ assert.ok(m, 'the operator table must be present in the vendored bundle');+ const sdkOperators = [...m[0].matchAll(/(\w+):z\.WorkflowConditionOperator\./g)].map((x) => x[1]);+ assert.ok(sdkOperators.length >= 16, `expected the full table, got ${sdkOperators.length}: ${sdkOperators}`);++ const { BUSINESS_RULE_OPERATORS } = require('../lib/app-spec.js');+ const notInSdk = BUSINESS_RULE_OPERATORS.filter((o) => !sdkOperators.includes(o));+ assert.deepStrictEqual(notInSdk, [],+ `these spec operators are NOT in the SDK table, so they would silently deploy as Equals: ${notInSdk}`);++ // And the reverse, so an operator the SDK gains is noticed rather than quietly unavailable.+ const notInSpec = sdkOperators.filter((o) => !BUSINESS_RULE_OPERATORS.includes(o));+ assert.deepStrictEqual(notInSpec, [],+ `the SDK supports these operators the spec does not expose: ${notInSpec}`);+});++test('a near-miss operator spelling is rejected AND corrected', () => {+ // `GreaterThan` is the natural thing to write and is the exact input that would deploy as Equals.+ const errs = errorsFor([{ ...RULE, conditions: [{ field: 'new_status', operator: 'GreaterThan', value: '1' }] }]);+ assert.ok(errs.some((e) => /GreaterThan/.test(e)), `expected rejection: ${JSON.stringify(errs)}`);+ assert.ok(errs.some((e) => /did you mean 'IsGreaterThan'/.test(e)),+ `the message must name the legal spelling; got ${JSON.stringify(errs)}`);+});++test('the newly-unlocked operators all validate', () => {+ // These were blocked only because the deleted XAML compiler could not express them.+ for (const operator of ['IsGreaterThan', 'IsLessThanEqualTo', 'Contains', 'BeginsWith', 'DoesNotEndWith', 'On']) {+ const errs = errorsFor([{ ...RULE, conditions: [{ field: 'new_status', operator, value: '1' }] }]);+ assert.deepStrictEqual(errs, [], `${operator} must validate: ${JSON.stringify(errs)}`);+ }+});++// --- multi-clause AND ---------------------------------------------------------------------------++test('a multi-condition rule now validates', () => {+ // Previously rejected with "only ONE condition is supported", which was never a platform limit —+ // the deleted XAML compiler read `clauses[0]` and ignored the rest.+ const errs = errorsFor([{+ ...RULE,+ conditions: [+ { field: 'new_status', operator: 'Equals', value: '1' },+ { field: 'new_owner', operator: 'ContainsData' },+ ],+ }]);+ assert.deepStrictEqual(errs, [], JSON.stringify(errs));+});++test('REAL BUNDLE: BOTH conditions of a multi-clause rule reach the wire, joined by LogicalAnd', async () => {+ // The failure that matters is silent: a serializer that kept only the first clause would deploy a+ // rule that fires under half the intended circumstances, and every structural check would pass.+ //+ // WorkflowConditionOperator.LogicalAnd is "2" in the bundle's own enum.+ const { createMakerSdk } = require(BUNDLE);+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'br-multi-'));+ 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 }); 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,+ conditions: [+ { field: 'new_status', operator: 'Equals', value: '1' },+ { field: 'new_owner', operator: 'ContainsData' },+ ],+ });+ assert.strictEqual(def.rootCondition.clauses.length, 2, 'the mapper must carry both clauses');++ const art = sdk.createArtifact('businessRule', def);+ await sdk.updateElement('businessRule', art.id, '/rootCondition', def.rootCondition);+ await sdk.pushArtifact('businessRule', art.id);++ const bound = calls.find((c) => /CreateProcessWithWfomJson/i.test(String(c.url)));+ const expr = JSON.parse(bound.body.WfomJson).steps.list[0].steps.list[0].conditionExpression;+ assert.strictEqual(expr.conditionOperatoroperator, '2', 'two clauses must be folded with LogicalAnd');++ // Both operands, and both authored columns, must survive the fold.+ const flat = JSON.stringify(expr);+ assert.match(flat, /new_status/, 'the FIRST condition column must reach the wire');+ assert.match(flat, /new_owner/, 'the SECOND condition column must reach the wire — dropping it is the silent failure');+});++// --- verify must not punish an environment that cannot host business rules -----------------------+//+// Found in review, and the point is not tidiness. `verify.ok` gates THREE things: the process exit+// code, whether `.last-applied.json` is written, and whether the `--changed-only` snapshot is+// persisted. A spec with implemented pages makes verify MANDATORY. So on the 18-of-20 environments+// that cannot host business rules, a permanently-false `ok` would permanently withhold the+// changed-only baseline and force a full build on every subsequent run, forever — while the build+// itself reported success. Those gates are built for TRANSIENT failures; this one never clears.++test('verify SKIPS a rule the build reported as unsupported on this environment', async () => {+ const r = await verifySpec(ruleSpec(), baseReader([]), {+ environmentSkipped: { businessRules: ['new_ticket|Lock when closed'] },+ });+ // Asserted on the business-rule outcome specifically rather than on `r.ok`: this fixture's reader+ // also reports an unrelated missing subarea, so `ok` would be false either way and an `ok` check+ // would pass for the wrong reason.+ assert.strictEqual(ruleCheck(r), undefined,+ 'the rule must not be counted as a check at all — passing it would claim it exists');+ assert.strictEqual(r.missing.some((m) => m.kind === 'business-rule'), false,+ 'and it must not count toward `missing`, which is what drives verify.ok');+ assert.deepStrictEqual(r.environmentSkipped, ['business-rule:new_ticket.Lock when closed'],+ 'it is REPORTED, so a green verify never silently means "everything the spec asked for is deployed"');+});++test('verify still FAILS a missing rule when the build did NOT skip it', async () => {+ // The dangerous over-correction: treating every absent rule as environment-gated would turn a real+ // deployment failure into a pass.+ const r = await verifySpec(ruleSpec(), baseReader([]), { environmentSkipped: { businessRules: [] } });+ assert.strictEqual(ruleCheck(r).present, false);+ assert.ok(r.missing.some((m) => m.kind === 'business-rule'));+ assert.strictEqual(r.environmentSkipped, undefined, 'absent when nothing was skipped, so existing callers are unaffected');+});++test('verify run STANDALONE (no build result) checks every rule', async () => {+ // `verify-model-app.js` has no build result to consult. Absent one, "not deployed" is the honest+ // verdict — the alternative would be a verify that quietly stops checking business rules.+ const r = await verifySpec(ruleSpec(), baseReader([]));+ assert.strictEqual(ruleCheck(r).present, false);+ assert.ok(r.missing.some((m) => m.kind === 'business-rule'));+});++test('the skip key matches the shape the BUILD records', async () => {+ // The two sides must agree on `entity|name` or the wiring is silently inert: verify would keep+ // failing and nobody would notice the option is being ignored.+ const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();+ const { provision } = provisionThatCannotAuthorRules();+ const built = await runBuild(ruleOnlySpec(), {+ sdk, provisionSdk: provision, apply: true, phases: ['business-rules'], warn: () => {},+ });+ const r = await verifySpec(ruleSpec(), baseReader([]), { environmentSkipped: built.skipped });+ assert.strictEqual(ruleCheck(r), undefined,+ `the build recorded ${JSON.stringify(built.skipped.businessRules)}, which verify must recognise`);+});++test('a PHASE-LIMITED verify does not demand a rule whose phase never ran', async () => {+ // The `--changed-only` FAST path applies `phases: ['pages']`. The business-rules loop is gated on+ // `has('business-rules')`, so it never executes and `skipped.businessRules` comes back EMPTY —+ // which made the skip list useless on exactly the runs that need it most.+ //+ // The consequence was not "verify is noisy". A fast apply is only chosen when every change is a+ // page, which requires implemented .tsx pages, which makes verify MANDATORY. So on a gated+ // environment every fast apply failed verify, refused to re-bless the snapshot, and exited+ // non-zero — an alternating full / failing-fast cycle forever, with the log line blaming PAGES for+ // a business-rule gate. The page upload itself had succeeded.+ const r = await verifySpec(ruleSpec(), baseReader([]), { phases: ['pages'] });+ assert.strictEqual(ruleCheck(r), undefined, 'a phase that did not run must not be demanded');+ assert.strictEqual(r.missing.some((m) => m.kind === 'business-rule'), false);+ assert.deepStrictEqual(r.phaseSkipped, ['business-rule:new_ticket.Lock when closed'],+ 'still reported, so it is visible rather than silently dropped');+});++test('the two skip REASONS are reported separately — they warrant opposite messages', async () => {+ // Merging them was wrong in a way the live run could not surface, because it happened to read+ // correctly on a gated environment. On a HEALTHY one, every `--changed-only` fast apply runs+ // `phases: ['pages']`, so every business rule would be reported as "not applicable on this+ // environment" — telling an operator whose environment works perfectly well that it does not.+ // Wrong 100% of the time on the normal fast-apply path.+ const gated = await verifySpec(ruleSpec(), baseReader([]), {+ environmentSkipped: { businessRules: ['new_ticket|Lock when closed'] },+ });+ assert.deepStrictEqual(gated.environmentSkipped, ['business-rule:new_ticket.Lock when closed']);+ assert.strictEqual(gated.phaseSkipped, undefined, 'a gated environment is NOT a phase that did not run');++ const phased = await verifySpec(ruleSpec(), baseReader([]), { phases: ['pages'] });+ assert.deepStrictEqual(phased.phaseSkipped, ['business-rule:new_ticket.Lock when closed']);+ assert.strictEqual(phased.environmentSkipped, undefined, 'a skipped phase says NOTHING about the environment');+});++test('a FULL-phase verify still demands the rule', async () => {+ // The over-correction to avoid: treating every phase list as permission to stop checking. A full+ // build lists every phase, so nothing is relaxed there.+ const { PHASES } = require('../lib/stages.js');+ const r = await verifySpec(ruleSpec(), baseReader([]), { phases: PHASES });+ assert.strictEqual(ruleCheck(r).present, false);+ assert.ok(r.missing.some((m) => m.kind === 'business-rule'));+});++test('verify with NO phases supplied checks everything — standalone must not be relaxed', async () => {+ const r = await verifySpec(ruleSpec(), baseReader([]));+ assert.strictEqual(ruleCheck(r).present, false);+});++test('a phase list that INCLUDES business-rules still demands the rule', async () => {+ // The gate is "did this phase run", not "was a phase list supplied".+ const r = await verifySpec(ruleSpec(), baseReader([]), { phases: ['business-rules'] });+ assert.strictEqual(ruleCheck(r).present, false);+ assert.ok(r.missing.some((m) => m.kind === 'business-rule'));+});diff --git a/plugins/model-apps/scripts/tests/column-capabilities.test.js b/plugins/model-apps/scripts/tests/column-capabilities.test.jsnew file mode 100644index 000000000..21dcbd40e--- /dev/null+++ b/plugins/model-apps/scripts/tests/column-capabilities.test.js@@ -0,0 +1,491 @@+'use strict';+// Guards https://github.com/microsoft/power-platform-skills/issues/495 — the SDK could author+// neither a Boolean default, nor a whole-number Duration format, nor per-column IsValidFor* flags,+// so a maker had to finish every column by hand after a build. (AB#6648523, AB#6648522, AB#6651276)+// `entities[].columns[]` — three column capabilities the vendored SDK gained in the same bundle+// refresh (provenance commit 15bd1b16), one App Spec field each:+// AB#6648523 — defaultValue (Boolean columns: the SDK used to hardcode DefaultValue:false)+// AB#6648522 — integerFormat (Integer columns: the SDK used to hardcode Format:'None')+// AB#6651276 — isValidForCreate / isValidForUpdate / isValidForRead (per-verb write/read access)+//+// All three share the SAME hazard: each is a boolean-or-enum a maker can set to an EXPLICIT+// falsy/negative value on purpose (`defaultValue:false`, `isValidForUpdate:false` — the whole point+// of "make this column read-only after creation"). A naive `if (c.field)` truthy guard anywhere in+// the chain — validation, the create mapper, or the update reconciler — silently drops exactly that+// value and nothing else, which is why every wiring test below asserts the explicit-false case+// SEPARATELY from the omitted case, not just "some value round-trips".+//+// Four layers, same reasons column-visualization.test.js gives:+// 1. VALIDATION — reject the wrong shape at the spec gate, not mid-build.+// 2. BUILD (create) — the mapper must pass an explicit value through, and only an explicit value.+// 3. BUILD (reconcile) — a rebuild must converge an EXISTING column too (AB#6651276 says so+// explicitly), via a SEPARATE reconcile block from the pre-existing `required` one (different+// convergence strategy — see the comment on capabilityTargets in entity-provision.js).+// 4. REAL BUNDLE — the measured wire shape, pinned so a future SDK bump that changes the key names+// or the "omitted vs explicit" behaviour is caught here instead of downstream.+const test = require('node:test');+const assert = require('node:assert');+const path = require('node:path');+const os = require('node:os');+const fs = require('node:fs');++const { validateAppSpec, INTEGER_FORMATS } = require('../lib/app-spec.js');+const { makeRunner, provisionDataModel } = require('../lib/entity-provision.js');++const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');++function specWith(columns) {+ return {+ solution: { uniqueName: 'CC', displayName: 'CC', publisherPrefix: 'new' },+ app: { name: 'CC 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 VIP = { schemaName: 'new_isvip', displayName: 'VIP', type: 'Boolean' };+const MINUTES = { schemaName: 'new_minutes', displayName: 'Minutes', type: 'Integer' };+const SSN = { schemaName: 'new_ssn', displayName: 'SSN', type: 'Text' };++// ---------------------------------------------------------------- 1. validation++test('defaultValue: true and defaultValue: false both validate cleanly on a Boolean column', () => {+ for (const v of [true, false]) {+ const res = validateAppSpec(specWith([Object.assign({}, VIP, { defaultValue: v })]));+ assert.strictEqual(res.errors.filter((e) => /defaultValue/.test(e)).length, 0, `defaultValue:${v} should validate`);+ }+});++test('omitting defaultValue is valid', () => {+ const res = validateAppSpec(specWith([VIP]));+ assert.strictEqual(res.errors.filter((e) => /defaultValue/.test(e)).length, 0);+});++test('a non-boolean defaultValue is rejected and names the column and the bad value', () => {+ const res = validateAppSpec(specWith([Object.assign({}, VIP, { defaultValue: 'true' })]));+ const err = res.errors.find((e) => /defaultValue/.test(e));+ assert.ok(err, 'expected a validation error');+ assert.match(err, /new_isvip/);+ assert.match(err, /must be a boolean/);+ assert.match(err, /"true"/); // JSON.stringify('true') => "true", distinguishing it from the boolean true+});++test('defaultValue on a non-Boolean column is rejected and names the column and its actual type', () => {+ const res = validateAppSpec(specWith([Object.assign({}, SSN, { defaultValue: true })]));+ const err = res.errors.find((e) => /defaultValue/.test(e));+ assert.ok(err, 'expected a validation error');+ assert.match(err, /new_ssn/);+ assert.match(err, /Boolean column/);+ assert.match(err, /'Text'/);+});++test('every integerFormat literal validates cleanly on an Integer column', () => {+ for (const f of INTEGER_FORMATS) {+ const res = validateAppSpec(specWith([Object.assign({}, MINUTES, { integerFormat: f })]));+ assert.strictEqual(res.errors.filter((e) => /integerFormat/.test(e)).length, 0, `${f} should validate`);+ }+});++test('omitting integerFormat is valid', () => {+ const res = validateAppSpec(specWith([MINUTES]));+ assert.strictEqual(res.errors.filter((e) => /integerFormat/.test(e)).length, 0);+});++test('an unknown integerFormat is rejected and names the column, the bad value, and the allowed list', () => {+ const res = validateAppSpec(specWith([Object.assign({}, MINUTES, { integerFormat: 'Fortnight' })]));+ const err = res.errors.find((e) => /integerFormat/.test(e));+ assert.ok(err, 'expected a validation error');+ assert.match(err, /new_minutes/);+ assert.match(err, /Fortnight/);+ assert.match(err, /None\|Duration\|TimeZone\|Language\|Locale/);+});++test('integerFormat on a non-Integer numeric column (Decimal) is rejected and names the actual type', () => {+ const decimalCol = { schemaName: 'new_amount', displayName: 'Amount', type: 'Decimal' };+ const res = validateAppSpec(specWith([Object.assign({}, decimalCol, { integerFormat: 'Duration' })]));+ const err = res.errors.find((e) => /integerFormat/.test(e));+ assert.ok(err, 'expected a validation error — Format is Integer-only even though Decimal shares the min/max/precision switch case');+ assert.match(err, /new_amount/);+ assert.match(err, /'Decimal'/);+});++test('isValidForCreate / isValidForUpdate / isValidForRead each validate cleanly at true AND at false', () => {+ for (const flag of ['isValidForCreate', 'isValidForUpdate', 'isValidForRead']) {+ for (const v of [true, false]) {+ const res = validateAppSpec(specWith([Object.assign({}, SSN, { [flag]: v })]));+ assert.strictEqual(res.errors.filter((e) => e.includes(flag)).length, 0, `${flag}:${v} should validate`);+ }+ }+});++test('omitting all three isValidFor* flags is valid', () => {+ const res = validateAppSpec(specWith([SSN]));+ assert.strictEqual(res.errors.filter((e) => /isValidFor/.test(e)).length, 0);+});++test('a non-boolean isValidForUpdate is rejected and names the column, the flag, and the bad value', () => {+ const res = validateAppSpec(specWith([Object.assign({}, SSN, { isValidForUpdate: 'false' })]));+ const err = res.errors.find((e) => /isValidForUpdate/.test(e));+ assert.ok(err, 'expected a validation error — the string "false" is truthy in JS and must not be coerced');+ assert.match(err, /new_ssn/);+ assert.match(err, /must be a boolean/);+ assert.match(err, /"false"/);+});++test('isValidForUpdate:false on a Customer column WARNS (does not error) — createCustomerColumn cannot carry it', () => {+ const customerCol = { schemaName: 'new_owner', displayName: 'Owner', type: 'Customer' };+ const res = validateAppSpec(specWith([Object.assign({}, customerCol, { isValidForUpdate: false })]));+ assert.strictEqual(res.errors.filter((e) => /isValidFor/.test(e)).length, 0, 'still a valid spec');+ const warn = res.warnings.find((w) => /isValidFor/.test(w));+ assert.ok(warn, 'expected a warning');+ assert.match(warn, /new_owner/);+ assert.match(warn, /Customer column/);+ assert.match(warn, /will NOT be written/);+});++// ---------------------------------------------------------------- 2. build (create path)++// Captures the FULL options object handed to createColumn/createCustomerColumn/updateColumn (not+// just the schemaName, unlike entity-provision.test.js's own mockSdk) — these tests exist+// specifically to inspect which keys are present, so the harness must not throw that away.+function mockSdk(existingTables = {}) {+ const calls = [];+ return {+ calls,+ sdk: {+ createTable: async (o) => ({ logicalName: o.schemaName.toLowerCase(), entitySetName: `${o.schemaName.toLowerCase()}s`, metadataId: `tbl-${o.schemaName}` }),+ updateTable: async () => ({}),+ createColumn: async (l, o) => { calls.push(['createColumn', l, o]); return { logicalName: o.schemaName.toLowerCase(), metadataId: `col-${o.schemaName}` }; },+ updateColumn: async (l, c, o) => { calls.push(['updateColumn', l, c, o]); return {}; },+ createCustomerColumn: async (l, o) => { calls.push(['createCustomerColumn', l, o]); return { logicalName: o.schemaName.toLowerCase(), metadataId: `col-${o.schemaName}` }; },+ createRelationship: async (o) => ({ schemaName: o.schemaName, metadataId: `rel-${o.schemaName}` }),+ createGlobalOptionSet: async (o) => ({ metadataId: `gc-${o.name}` }),+ insertStatusValue: async () => 100000000,+ createAlternateKey: async () => ({}),+ },+ provision: {+ findTables: async (s) => (existingTables[s.toLowerCase()] ? [{ logicalName: s.toLowerCase(), entitySetName: `${s.toLowerCase()}s` }] : []),+ findColumns: async () => existingTables.__columns || [],+ fetchEntityMetadata: async (l) => ({ logicalName: l, entitySetName: `${l}s`, relationships: [] }),+ },+ };+}++function specForProvision(columns) {+ return {+ solution: { uniqueName: 'S', publisherPrefix: 'new' },+ entities: [{ schemaName: 'new_ticket', displayName: 'Ticket', primaryAttribute: { schemaName: 'new_name' }, columns }],+ relationships: [],+ };+}++async function runProvision(m, columns, warn) {+ const runner = makeRunner({ emit: () => {}, total: 50 });+ return provisionDataModel({ sdk: m.sdk, provision: m.provision, runner, spec: specForProvision(columns), apply: true, preResolvedLanguageCode: 1033, warn });+}++test('CREATE: an explicit defaultValue:true reaches createColumn', async () => {+ const m = mockSdk();+ await runProvision(m, [Object.assign({}, VIP, { defaultValue: true })]);+ const call = m.calls.find((c) => c[0] === 'createColumn');+ assert.strictEqual(call[2].defaultValue, true);+});++test('CREATE: an explicit defaultValue:false is PRESENT on the createColumn call, not dropped', async () => {+ // The critical truthiness-bug case: `false` must appear in the options object passed to the SDK,+ // not be indistinguishable from "the spec never mentioned it".+ const m = mockSdk();+ await runProvision(m, [Object.assign({}, VIP, { defaultValue: false })]);+ const call = m.calls.find((c) => c[0] === 'createColumn');+ assert.strictEqual(call[2].defaultValue, false);+ assert.ok(Object.prototype.hasOwnProperty.call(call[2], 'defaultValue'), 'the key itself must be present, not merely falsy');+});++test('CREATE: an omitted defaultValue sends no defaultValue key at all', async () => {+ const m = mockSdk();+ await runProvision(m, [VIP]);+ const call = m.calls.find((c) => c[0] === 'createColumn');+ assert.strictEqual(call[2].defaultValue, undefined);+ assert.ok(!Object.prototype.hasOwnProperty.call(call[2], 'defaultValue'), 'omitted in the spec must stay omitted for the SDK too — its own default applies');+});++test('CREATE: an explicit integerFormat reaches createColumn', async () => {+ const m = mockSdk();+ await runProvision(m, [Object.assign({}, MINUTES, { integerFormat: 'Duration' })]);+ const call = m.calls.find((c) => c[0] === 'createColumn');+ assert.strictEqual(call[2].integerFormat, 'Duration');+});++test('CREATE: an omitted integerFormat sends no integerFormat key at all', async () => {+ const m = mockSdk();+ await runProvision(m, [MINUTES]);+ const call = m.calls.find((c) => c[0] === 'createColumn');+ assert.ok(!Object.prototype.hasOwnProperty.call(call[2], 'integerFormat'));+});++test('CREATE: integerFormat is NOT applied to a sibling numeric type sharing the switch case', async () => {+ // Decimal/Double/BigInt/Money share columnOptions()'s min/max/precision case with Integer, but the+ // SDK's Format option is Integer-only — confirms the gate stayed narrow after refactor.+ const m = mockSdk();+ const decimalCol = { schemaName: 'new_amount', displayName: 'Amount', type: 'Decimal', integerFormat: 'Duration' };+ await runProvision(m, [decimalCol]);+ const call = m.calls.find((c) => c[0] === 'createColumn');+ assert.ok(!Object.prototype.hasOwnProperty.call(call[2], 'integerFormat'), 'integerFormat must not leak onto a Decimal column');+});++test('CREATE: isValidForCreate:true, isValidForUpdate:false, isValidForRead:true all reach createColumn — false included', async () => {+ const m = mockSdk();+ await runProvision(m, [Object.assign({}, SSN, { isValidForCreate: true, isValidForUpdate: false, isValidForRead: true })]);+ const call = m.calls.find((c) => c[0] === 'createColumn');+ assert.strictEqual(call[2].isValidForCreate, true);+ assert.strictEqual(call[2].isValidForUpdate, false);+ assert.strictEqual(call[2].isValidForRead, true);+});++test('CREATE: setting only isValidForUpdate:false sends ONLY that key, not the other two', async () => {+ const m = mockSdk();+ await runProvision(m, [Object.assign({}, SSN, { isValidForUpdate: false })]);+ const call = m.calls.find((c) => c[0] === 'createColumn');+ assert.strictEqual(call[2].isValidForUpdate, false);+ assert.ok(!Object.prototype.hasOwnProperty.call(call[2], 'isValidForCreate'));+ assert.ok(!Object.prototype.hasOwnProperty.call(call[2], 'isValidForRead'));+});++test('CREATE: omitting all three isValidFor* flags sends none of the three keys', async () => {+ const m = mockSdk();+ await runProvision(m, [SSN]);+ const call = m.calls.find((c) => c[0] === 'createColumn');+ for (const flag of ['isValidForCreate', 'isValidForUpdate', 'isValidForRead']) {+ assert.ok(!Object.prototype.hasOwnProperty.call(call[2], flag));+ }+});++test('CREATE: a Customer column routes through createCustomerColumn, which never receives the new fields', async () => {+ // Customer columns are structurally incompatible: createCustomerColumn's options have no+ // defaultValue/integerFormat/isValidFor* fields at all (measured against the vendored SDK).+ const m = mockSdk();+ const customerCol = { schemaName: 'new_owner', displayName: 'Owner', type: 'Customer', isValidForUpdate: false };+ await runProvision(m, [customerCol]);+ assert.ok(!m.calls.some((c) => c[0] === 'createColumn'), 'Customer must not go through createColumn');+ const call = m.calls.find((c) => c[0] === 'createCustomerColumn');+ assert.ok(call, 'createCustomerColumn must have been called');+ assert.ok(!Object.prototype.hasOwnProperty.call(call[2], 'isValidForUpdate'), 'the field has nowhere to go on this call and must not be invented');+});++// ---------------------------------------------------------------- 3. build (reconcile / update path)++test('RECONCILE: an existing Boolean column with explicit defaultValue:false calls updateColumn', async () => {+ const m = mockSdk({ new_ticket: true, __columns: [{ logicalName: 'new_isvip', schemaName: 'new_isvip' }] });+ await runProvision(m, [Object.assign({}, VIP, { defaultValue: false })]);+ assert.deepStrictEqual(+ m.calls.find((c) => c[0] === 'updateColumn'),+ ['updateColumn', 'new_ticket', 'new_isvip', { defaultValue: false }]);+});++test('RECONCILE: an existing Integer column with explicit integerFormat calls updateColumn', async () => {+ const m = mockSdk({ new_ticket: true, __columns: [{ logicalName: 'new_minutes', schemaName: 'new_minutes' }] });+ await runProvision(m, [Object.assign({}, MINUTES, { integerFormat: 'Duration' })]);+ assert.deepStrictEqual(+ m.calls.find((c) => c[0] === 'updateColumn'),+ ['updateColumn', 'new_ticket', 'new_minutes', { integerFormat: 'Duration' }]);+});++test('RECONCILE: an existing column with only isValidForUpdate:false set sends ONLY that key to updateColumn', async () => {+ const m = mockSdk({ new_ticket: true, __columns: [{ logicalName: 'new_ssn', schemaName: 'new_ssn' }] });+ await runProvision(m, [Object.assign({}, SSN, { isValidForUpdate: false })]);+ assert.deepStrictEqual(+ m.calls.find((c) => c[0] === 'updateColumn'),+ ['updateColumn', 'new_ticket', 'new_ssn', { isValidForUpdate: false }]);+});++test('RECONCILE: an existing column with all three isValidFor* flags sends all three, false included', async () => {+ const m = mockSdk({ new_ticket: true, __columns: [{ logicalName: 'new_ssn', schemaName: 'new_ssn' }] });+ await runProvision(m, [Object.assign({}, SSN, { isValidForCreate: false, isValidForUpdate: false, isValidForRead: false })]);+ assert.deepStrictEqual(+ m.calls.find((c) => c[0] === 'updateColumn'),+ ['updateColumn', 'new_ticket', 'new_ssn', { isValidForCreate: false, isValidForUpdate: false, isValidForRead: false }]);+});++test('RECONCILE: an existing column with none of the three capabilities set never calls updateColumn for them', async () => {+ const m = mockSdk({ new_ticket: true, __columns: [{ logicalName: 'new_ssn', schemaName: 'new_ssn' }] });+ await runProvision(m, [SSN]);+ assert.ok(!m.calls.some((c) => c[0] === 'updateColumn'), 'nothing to reconcile — must not spam updateColumn on every existing column');+});++test('RECONCILE: an existing Customer column is excluded even when isValidFor* is set — updateColumn refuses the type entirely', async () => {+ const m = mockSdk({ new_ticket: true, __columns: [{ logicalName: 'new_owner', schemaName: 'new_owner' }] });+ const customerCol = { schemaName: 'new_owner', displayName: 'Owner', type: 'Customer', isValidForUpdate: false };+ await runProvision(m, [customerCol]);+ assert.ok(!m.calls.some((c) => c[0] === 'updateColumn'), 'Customer columns have no update path at all (measured — the SDK throws "type not supported")');+});++test('RECONCILE: a failure updating column capabilities warns and continues rather than halting the build', async () => {+ const warnings = [];+ const m = mockSdk({ new_ticket: true, __columns: [{ logicalName: 'new_isvip', schemaName: 'new_isvip' }] });+ m.sdk.updateColumn = async (l, c, o) => {+ m.calls.push(['updateColumn', l, c, o]);+ const err = new Error('metadata lock busy');+ err.statusCode = 429;+ throw err;+ };+ await runProvision(m, [Object.assign({}, VIP, { defaultValue: false })], (msg) => warnings.push(msg));+ assert.ok(m.calls.some((c) => c[0] === 'updateColumn'), 'the reconcile was attempted');+ assert.ok(warnings.some((w) => /could not update column capabilities for new_ticket\.new_isvip/.test(w)));+});++test('RECONCILE: the new capability block and the pre-existing required block coexist as SEPARATE updateColumn calls', async () => {+ // Guards against accidentally folding the new block INTO the required block (or vice versa) —+ // they converge by different strategies (diff-then-skip vs always-reassert) and must stay+ // independent calls, not merged into one options object that could silently drop a field.+ const m = mockSdk({+ new_ticket: true,+ __columns: [{ logicalName: 'new_isvip', schemaName: 'new_isvip', RequiredLevel: { Value: 'None' } }],+ });+ await runProvision(m, [Object.assign({}, VIP, { required: true, defaultValue: false })]);+ const updateCalls = m.calls.filter((c) => c[0] === 'updateColumn');+ assert.strictEqual(updateCalls.length, 2, 'one call for required, one call for the new capabilities');+ assert.ok(updateCalls.some((c) => c[3].required === 'ApplicationRequired'));+ assert.ok(updateCalls.some((c) => c[3].defaultValue === false));+});++// ---------------------------------------------------------------- 4. real bundle (measured wire evidence)++// Fake httpClient that records every request. Mirrors lcid-real-bundle.test.js's pattern: drive the+// REAL vendored bundle (not a mock of it) so a future SDK bump that changes a key name or the+// omitted-vs-explicit behaviour breaks THIS test, not a downstream build.+function realSdk({ get } = {}) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cc-real-'));+ const requests = [];+ const rec = (verb) => async (url, body) => {+ requests.push({ verb, url, body });+ if (verb === 'post') return { status: 204, headers: {}, body: { MetadataId: '11111111-1111-1111-1111-111111111111' } };+ return { status: 204, headers: {}, body: {} };+ };+ const sdk = require(BUNDLE).createMakerSdk({+ workspacePath: dir,+ instanceUrl: 'https://contoso.crm.dynamics.com',+ httpClient: {+ get: get || (async (url) => { requests.push({ verb: 'get', url }); return { status: 200, headers: {}, body: { value: [] } }; }),+ post: rec('post'),+ patch: rec('patch'),+ put: rec('put'),+ delete: rec('delete'),+ },+ });+ return { sdk, requests, cleanup: () => fs.rmSync(dir, { recursive: true, force: true }) };+}++// updateColumn does two GETs before its PUT: (1) $select=MetadataId,AttributeType, (2) the full+// typed attribute. Position, not URL text, distinguishes them (measured against the real bundle).+function updateGetSequence(attributeType, currentBody) {+ let n = 0;+ return async (url) => {+ n += 1;+ if (n === 1) return { status: 200, headers: {}, body: { MetadataId: '22222222-2222-2222-2222-222222222222', AttributeType: attributeType } };+ return { status: 200, headers: {}, body: currentBody };+ };+}++test('REAL BUNDLE: createColumn sends DefaultValue:false on the wire for an EXPLICIT false (not omitted)', async () => {+ // `await`, not a returned promise inside try/finally: `finally` fires when the `return` is+ // EVALUATED, so `r.cleanup()` (an fs.rmSync of the workspace dir) would run before the SDK call+ // settled. Harmless while the assertions only read `r.requests`, and an intermittent ENOENT the+ // moment anything touches the workspace. Every sibling REAL BUNDLE test here awaits.+ const r = realSdk();+ try {+ await r.sdk.createColumn('new_ticket', { schemaName: 'new_isvip', displayName: 'VIP', type: 'boolean', defaultValue: false });+ const post = r.requests.find((x) => x.verb === 'post');+ assert.strictEqual(post.body.DefaultValue, false);+ assert.ok(Object.prototype.hasOwnProperty.call(post.body, 'DefaultValue'));+ } finally {+ r.cleanup();+ }+});++test('REAL BUNDLE: createColumn sends Format for an explicit integerFormat', async () => {+ const r = realSdk();+ try {+ await r.sdk.createColumn('new_ticket', { schemaName: 'new_minutes', displayName: 'Minutes', type: 'integer', integerFormat: 'Duration' });+ const post = r.requests.find((x) => x.verb === 'post');+ assert.strictEqual(post.body.Format, 'Duration');+ } finally {+ r.cleanup();+ }+});++test('REAL BUNDLE: createColumn sends ONLY the isValidFor* keys explicitly set, nothing implied', async () => {+ const r = realSdk();+ try {+ await r.sdk.createColumn('new_ticket', { schemaName: 'new_ssn', displayName: 'SSN', type: 'string', isValidForUpdate: false });+ const post = r.requests.find((x) => x.verb === 'post');+ assert.strictEqual(post.body.IsValidForUpdate, false);+ assert.ok(!Object.prototype.hasOwnProperty.call(post.body, 'IsValidForCreate'));+ assert.ok(!Object.prototype.hasOwnProperty.call(post.body, 'IsValidForRead'));+ } finally {+ r.cleanup();+ }+});++test('REAL BUNDLE: createColumn throws for defaultValue on a non-boolean column (spec-gate mirrors an SDK-side guard)', async () => {+ const r = realSdk();+ try {+ await assert.rejects(+ () => r.sdk.createColumn('new_ticket', { schemaName: 'new_name', displayName: 'Name', type: 'string', defaultValue: true }),+ /defaultValue.*boolean columns/);+ } finally {+ r.cleanup();+ }+});++test('REAL BUNDLE: updateColumn PUTs an explicit defaultValue:false, changing a previously-true value', async () => {+ const current = {+ '@odata.type': 'Microsoft.Dynamics.CRM.BooleanAttributeMetadata',+ SchemaName: 'new_isvip',+ DefaultValue: true,+ OptionSet: { '@odata.type': 'Microsoft.Dynamics.CRM.BooleanOptionSetMetadata', TrueOption: { Value: 1 }, FalseOption: { Value: 0 } },+ };+ const r = realSdk({ get: updateGetSequence('Boolean', current) });+ try {+ await r.sdk.updateColumn('new_ticket', 'new_isvip', { defaultValue: false });+ const put = r.requests.find((x) => x.verb === 'put');+ assert.strictEqual(put.body.DefaultValue, false);+ } finally {+ r.cleanup();+ }+});++test('REAL BUNDLE: updateColumn PUTs explicit isValidFor* flags, false included, alongside the untouched fields it read', async () => {+ const current = {+ '@odata.type': 'Microsoft.Dynamics.CRM.StringAttributeMetadata',+ SchemaName: 'new_ssn',+ MaxLength: 100,+ IsValidForCreate: true,+ IsValidForUpdate: true,+ IsValidForRead: true,+ };+ const r = realSdk({ get: updateGetSequence('String', current) });+ try {+ await r.sdk.updateColumn('new_ticket', 'new_ssn', { isValidForUpdate: false });+ const put = r.requests.find((x) => x.verb === 'put');+ assert.strictEqual(put.body.IsValidForUpdate, false);+ // The GET-mutate-PUT round trip forwards whatever it read for the untouched flags — confirms+ // the reconcile in entity-provision.js only needs to send the ONE flag it wants to change.+ assert.strictEqual(put.body.IsValidForCreate, true);+ assert.strictEqual(put.body.IsValidForRead, true);+ } finally {+ r.cleanup();+ }+});++test('REAL BUNDLE: updateColumn refuses a Customer column outright (no update path exists for it)', async () => {+ const r = realSdk({ get: updateGetSequence('Customer', {}) });+ try {+ await assert.rejects(() => r.sdk.updateColumn('new_ticket', 'new_owner', { isValidForUpdate: false }), /Customer/);+ } finally {+ r.cleanup();+ }+});diff --git a/plugins/model-apps/scripts/tests/dashboard-roundtrip.test.js b/plugins/model-apps/scripts/tests/dashboard-roundtrip.test.jsnew file mode 100644index 000000000..2e6965694--- /dev/null+++ b/plugins/model-apps/scripts/tests/dashboard-roundtrip.test.js@@ -0,0 +1,90 @@+'use strict';+// #478 — the vendored SDK could not deserialize a dashboard it had just serialized.+//+// `fetchArtifact('dashboard', id)` threw `Cannot read properties of null (reading 'length')` while+// parsing the `<parameters>` block the SAME bundle emitted, so `download-model-app.js` recovered no+// tiles, dropped the dashboard's sitemap subarea, and failed the whole download unless+// `--allow-lossy-download` was passed. Root cause upstream: the grammar walk descended into TEXT+// nodes, and the bundled @xmldom/xmldom returns `null` for a text node's `.childNodes`.+//+// MEASURED across the re-vendor, with this exact harness:+// bundle at HEAD before the uptake ... 0/4 round-tripped+// bundle after the uptake ............ 4/4 round-tripped+//+// There was NO regression test for this — the bug was found by live-verifying a PR, and it survived+// two separate SDK uptakes because nothing in the suite ever fed a serialized dashboard back in.+// That is exactly the gap this file closes: the transport REMEMBERS what was pushed and serves it+// back on read, so the assertion is "deserialize what you serialized" rather than "parse a fixture+// someone hand-wrote to match the parser".+//+// https://github.com/microsoft/power-platform-skills/issues/478+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 DASH_ID = '33333333-3333-3333-3333-333333333333';++const dirs = [];+test.after(() => { for (const d of dirs) fs.rmSync(d, { recursive: true, force: true }); });++function harness() {+ const { createMakerSdk } = require(BUNDLE);+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'dash-478-'));+ dirs.push(dir);+ const store = {};+ const httpClient = {+ // Serve back the row that was written, not a fixture. A recorder that never consults its own+ // store cannot model a round trip, and a mock that cannot model the failure will certify it.+ get: async (url) => {+ if (/systemforms\(/i.test(url)) {+ return { status: 200, headers: { etag: 'W/"1"' }, body: Object.assign({ formid: DASH_ID, name: 'Field Ops', type: 0 }, store.row || {}) };+ }+ return { status: 200, headers: {}, body: { value: [] } };+ },+ post: async (url, body) => {+ if (/systemforms/i.test(url)) { store.row = Object.assign({}, body); return { status: 204, headers: { 'odata-entityid': `https://x/systemforms(${DASH_ID})` }, body: {} }; }+ return { status: 204, headers: {}, body: {} };+ },+ patch: async (url, body) => {+ if (/systemforms\(/i.test(url)) store.row = Object.assign({}, store.row, body);+ return { status: 204, headers: { etag: 'W/"2"' }, 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, store };+}++// Every tile shape the plugin can emit. The bug was independent of tile type and of the+// `VisualizationId` vs `ChartId` spelling — both threw — so all of them are pinned.+const TILES = {+ 'list tile': { type: 'list', id: 'l1', name: 'Open', colspan: 1, rowspan: 1, parameters: { ViewId: '44444444-4444-4444-4444-444444444444', TargetEntityType: 'cfo_workorder' } },+ 'chart tile (VisualizationId)': { type: 'chart', id: 'c1', name: 'ByStatus', colspan: 1, rowspan: 1, parameters: { VisualizationId: '55555555-5555-5555-5555-555555555555', TargetEntityType: 'cfo_workorder' } },+ 'chart tile (ChartId spelling)': { type: 'chart', id: 'c2', name: 'ByOwner', colspan: 1, rowspan: 1, parameters: { ChartId: '66666666-6666-6666-6666-666666666666', TargetEntityType: 'cfo_workorder' } },+ // An EMPTY parameter value produces a childless text node, which is the shape that made the walk+ // read `.childNodes` off a text node in the first place.+ 'tile with an EMPTY parameter value': { type: 'list', id: 'l2', name: 'Empty', colspan: 1, rowspan: 1, parameters: { ViewId: '', TargetEntityType: 'cfo_workorder' } },+};++for (const [label, tile] of Object.entries(TILES)) {+ test(`REAL BUNDLE: a dashboard with a ${label} survives serialize -> deserialize`, async () => {+ const { sdk, store } = harness();+ const art = sdk.createArtifact('dashboard', { name: 'Field Ops' });+ await sdk.addElement('dashboard', art.id, '/components', tile);+ await sdk.pushArtifact('dashboard', art.id);++ // Guard the guard: if the push stopped emitting <parameters> the round trip would pass for the+ // wrong reason, since <parameters> is the block that used to throw.+ assert.match(String(store.row && store.row.formxml), /<parameters>/i,+ 'the pushed dashboard must actually contain a <parameters> block, or this test proves nothing');++ const back = await sdk.fetchArtifact('dashboard', DASH_ID);+ const comps = (back && (back.components || (back.artifact && back.artifact.components))) || [];+ assert.strictEqual(comps.length, 1, `the tile must come back; got ${JSON.stringify(comps)}`);+ });+}diff --git a/plugins/model-apps/scripts/tests/download-model-app.test.js b/plugins/model-apps/scripts/tests/download-model-app.test.jsindex 993e13374..a41aba7e4 100644--- a/plugins/model-apps/scripts/tests/download-model-app.test.js+++ b/plugins/model-apps/scripts/tests/download-model-app.test.js@@ -1,10 +1,12 @@'use strict';+// Also guards https://github.com/microsoft/power-platform-skills/issues/494 — download did not read+// artifact descriptions back, so a downloaded spec silently lost every description on rebuild.const { test } = require('node:test');const assert = require('node:assert');const fs = require('node:fs');const os = require('node:os');const path = require('node:path');-const { resolveAppId, collectSitemap, parseDownloadedPages, entityFromMetadata, iconWebResources, readDashboards, droppedSubareaCount, preserveAuthoredLanguageCode } = require('../download-model-app.js');+const { untypedColumnNames, resolveAppId, collectSitemap, parseDownloadedPages, entityFromMetadata, readEntityWithDescriptions, readDescriptionInventory, 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';@@ -177,6 +179,222 @@ test('entityFromMetadata builds a minimal (reuse-friendly) entity spec', () => {assert.strictEqual(e.existing, true, 'downloaded tables must be flagged existing:true (teardown data-loss guard)');});+test('entityFromMetadata carries table and column descriptions, unwrapping Dataverse Labels', () => {+ const e = entityFromMetadata({+ schemaName: 'new_order',+ displayName: 'Order',+ primaryNameAttribute: 'new_name',+ Description: {+ UserLocalizedLabel: { Label: 'Tracks orders through fulfillment.', LanguageCode: 1033 },+ LocalizedLabels: [{ Label: 'fallback table text', LanguageCode: 1033 }],+ },+ attributes: [+ {+ LogicalName: 'new_status',+ Description: {+ LocalizedLabels: [{ Label: 'Current fulfillment state.', LanguageCode: 1033 }],+ },+ },+ { LogicalName: 'new_internal', Description: null },+ ],+ }, 'new_order');++ assert.strictEqual(e.description, 'Tracks orders through fulfillment.');+ assert.strictEqual(e.columns[0].schemaName, 'new_status');+ assert.strictEqual(e.columns[0].description, 'Current fulfillment state.');+ assert.strictEqual('description' in e.columns[1], false, 'null Label descriptions must be omitted, not emitted as ""');+ assert.strictEqual(validateAppSpec({+ solution: { uniqueName: 'S', publisherPrefix: 'new' },+ app: { name: 'A' },+ entities: [e],+ appShell: { areas: [] },+ }).ok, true);+});++test('readEntityWithDescriptions reads descriptions through the RAW dataverse client, not queryRecords', async () => {+ // `sdk.queryRecords` cannot serve a metadata path: it first resolves its argument to an entity SET+ // name via `EntityDefinitions(LogicalName='<arg>')?$select=EntitySetName`, so a metadata path+ // becomes a nested nonsense URL that 404s. This mock FAILS any queryRecords attempt so the test+ // proves the raw client is used, rather than passing against a mock that models the wrong contract.+ const gets = [];+ const sdk = {+ fetchEntityMetadata: async (logical) => ({+ logicalName: logical,+ schemaName: 'new_order',+ displayName: 'Order',+ primaryNameAttribute: 'new_name',+ // The SDK supplies these; the description merge must PRESERVE them.+ attributes: [+ { logicalName: 'new_status', displayName: 'Status', attributeType: 'Picklist' },+ { logicalName: 'new_owner', displayName: 'Owner', attributeType: 'Lookup', targets: ['systemuser'] },+ ],+ }),+ queryRecords: async (set) => { throw new Error(`queryRecords must not be used for metadata paths (got '${set}')`); },+ dataverse: {+ get: async (url) => {+ gets.push(url);+ if (/\/Attributes\?/.test(url)) {+ return { status: 200, headers: {}, body: { value: [+ { LogicalName: 'new_status', Description: { LocalizedLabels: [{ Label: 'State shown to dispatchers.', LanguageCode: 1033 }] } },+ ] } };+ }+ return { status: 200, headers: {}, body: { Description: { UserLocalizedLabel: { Label: 'Order table purpose.', LanguageCode: 1033 }, LocalizedLabels: [] } } };+ },+ },+ };++ const meta = await readEntityWithDescriptions(sdk, 'new_order');+ const e = entityFromMetadata(meta, 'new_order');++ assert.ok(gets.some((u) => /^\/EntityDefinitions\(LogicalName='new_order'\)\?\$select=LogicalName,Description$/.test(u)), `table read URL wrong: ${gets.join(' | ')}`);+ assert.ok(gets.some((u) => /^\/EntityDefinitions\(LogicalName='new_order'\)\/Attributes\?\$select=LogicalName,Description$/.test(u)), `attribute read URL wrong: ${gets.join(' | ')}`);+ assert.strictEqual(e.description, 'Order table purpose.');+ const status = e.columns.find((c) => c.schemaName === 'new_status');+ assert.strictEqual(status.description, 'State shown to dispatchers.');+ // The merge must not discard SDK-only attribute facts (a replace would drop `targets`, breaking+ // lookup handling elsewhere) nor drop attributes the description read did not return.+ const owner = meta.attributes.find((a) => a.logicalName === 'new_owner');+ assert.ok(owner, 'an attribute with no description was dropped by the merge');+ assert.deepStrictEqual(owner.targets, ['systemuser'], 'the merge clobbered SDK-only attribute fields');+});++test('readEntityWithDescriptions treats a non-2xx from the raw client as "no description", not a crash', async () => {+ // dataverse.get RESOLVES with { status } on a 404 instead of throwing, so a bare try/catch would+ // let the error body through. The body here deliberately CARRIES a `Description` key: dropping the+ // status check must not be survivable just because a real 404 body usually lacks one.+ const sdk = {+ fetchEntityMetadata: async (logical) => ({ logicalName: logical, schemaName: 'new_order', displayName: 'Order', primaryNameAttribute: 'new_name', attributes: [{ logicalName: 'new_status' }] }),+ dataverse: {+ get: async () => ({+ status: 404,+ headers: {},+ body: { error: { code: '0x80060888', message: 'Resource not found' }, Description: { UserLocalizedLabel: { Label: 'GARBAGE FROM AN ERROR BODY', LanguageCode: 1033 } } },+ }),+ },+ };+ const e = entityFromMetadata(await readEntityWithDescriptions(sdk, 'new_order'), 'new_order');+ assert.ok(!('description' in e), `a 404 body must never supply a description (got ${JSON.stringify(e.description)})`);+ assert.ok(!('description' in e.columns[0]));+});++test('readEntityWithDescriptions survives a raw client that throws', async () => {+ const sdk = {+ fetchEntityMetadata: async (logical) => ({ logicalName: logical, schemaName: 'new_order', displayName: 'Order', primaryNameAttribute: 'new_name', attributes: [] }),+ dataverse: { get: async () => { throw new Error('network down'); } },+ };+ const e = entityFromMetadata(await readEntityWithDescriptions(sdk, 'new_order'), 'new_order');+ assert.strictEqual(e.schemaName, 'new_order', 'a description read failure must not sink the download');+ assert.ok(!('description' in e));+});++test('entityFromMetadata emits ONLY custom columns — a downloaded spec must not rewrite the org default views', async () => {+ // `fetchEntityMetadata` returns the FULL attribute list. Emitting system attributes as spec+ // columns is not merely noisy: `columns[]` feeds `defaultViewColumns`, and `enrichDefaultViews`+ // REPLACES the Active/Inactive views' column set — so a `download -> rebuild` round trip would+ // rewrite a customer's default views to Created On / Import Sequence Number, undoing fix #7.+ const meta = {+ logicalName: 'new_ticket', schemaName: 'new_ticket', displayName: 'Ticket', primaryNameAttribute: 'new_name',+ attributes: [+ { logicalName: 'new_name', displayName: 'Name', attributeType: 'String', isCustomAttribute: true },+ { logicalName: 'new_status', displayName: 'Status', attributeType: 'Picklist', isCustomAttribute: true },+ { logicalName: 'new_notes', displayName: 'Notes', attributeType: 'Memo', isCustomAttribute: true },+ { logicalName: 'new_owner', displayName: 'Owner', attributeType: 'Lookup', isCustomAttribute: true, targets: ['systemuser'] },+ { logicalName: 'createdon', displayName: 'Created On', attributeType: 'DateTime', isCustomAttribute: false },+ { logicalName: 'versionnumber', displayName: 'Version Number', attributeType: 'BigInt', isCustomAttribute: false },+ { logicalName: 'importsequencenumber', displayName: 'Import Sequence Number', attributeType: 'Integer', isCustomAttribute: false },+ { logicalName: 'owningbusinessunit', displayName: 'Owning Business Unit', attributeType: 'Lookup', isCustomAttribute: false },+ ],+ };+ const e = entityFromMetadata(meta, 'new_ticket');+ const names = e.columns.map((c) => c.schemaName);+ for (const sys of ['createdon', 'versionnumber', 'importsequencenumber', 'owningbusinessunit']) {+ assert.ok(!names.includes(sys), `system attribute '${sys}' leaked into columns[]: ${names.join(', ')}`);+ }+ // The primary name column is declared as `primaryAttribute`; it must not ALSO be a column.+ assert.ok(!names.includes('new_name'), 'the primary column must not be duplicated into columns[]');+ // A custom Lookup comes from relationships[], not columns[] — it has no App Spec column type.+ assert.ok(!names.includes('new_owner'), 'a Lookup is not an authorable spec column');+ assert.deepStrictEqual(names, ['new_status', 'new_notes']);+ // The SDK projects `attributeType`, not `type`. Reading the wrong key made every column type-less,+ // which silently disabled DEFAULT_VIEW_SKIP_TYPES and the auto-form-layout type filter.+ assert.strictEqual(e.columns.find((c) => c.schemaName === 'new_notes').type, 'Memo');+ // A Choice column is emitted WITHOUT a type: declaring `type: "Choice"` obliges the spec to carry+ // `options[]` or a `globalChoice`, which this hydrator cannot read, and the resulting spec fails+ // its own validation. Live-caught — the download errored with+ // "column contoso_status: Choice needs options[] or a globalChoice reference".+ assert.ok(!('type' in e.columns.find((c) => c.schemaName === 'new_status')),+ 'a Choice column must not claim a type it cannot substantiate');+});++test('a hydrated entity always survives validateAppSpec — a downloaded spec that cannot be validated is useless', () => {+ const meta = {+ logicalName: 'new_ticket', schemaName: 'new_ticket', displayName: 'Ticket', primaryNameAttribute: 'new_name',+ attributes: [+ { logicalName: 'new_status', displayName: 'Status', attributeType: 'Picklist', isCustomAttribute: true },+ { logicalName: 'new_choices', displayName: 'Choices', attributeType: 'MultiSelectPicklist', isCustomAttribute: true },+ { logicalName: 'new_notes', displayName: 'Notes', attributeType: 'Memo', isCustomAttribute: true },+ { logicalName: 'new_big', displayName: 'Big', attributeType: 'BigInt', isCustomAttribute: true },+ ],+ };+ const res = validateAppSpec({+ solution: { uniqueName: 'S', publisherPrefix: 'new' },+ app: { name: 'A' },+ entities: [entityFromMetadata(meta, 'new_ticket')],+ appShell: { areas: [] },+ }, { profile: 'deploy' });+ assert.deepStrictEqual(res.errors, [], res.errors.join(' | '));+});++test('enrichesDefaultViews is FALSE for an existing:true table (download flags every recovered table that way)', () => {+ const spec = {+ entities: [{+ schemaName: 'new_ticket', primaryAttribute: { schemaName: 'new_name' }, existing: true,+ columns: [{ schemaName: 'new_status', type: 'Choice' }, { schemaName: 'new_tier', type: 'Choice' }],+ }],+ relationships: [],+ };+ // Enrichment REPLACES a view's column set, and `existing` means this build cannot prove it owns+ // the table — the same reasoning that stops teardown from deleting it.+ assert.strictEqual(enrichesDefaultViews(spec, spec.entities[0]), false);+ const owned = { ...spec.entities[0], existing: false };+ assert.strictEqual(enrichesDefaultViews({ ...spec, entities: [owned] }, owned), true, 'a table this build owns still enriches');+ // The opt-in must remain reachable: judging "this reused table really is mine" is exactly the call+ // an author can make and this code cannot, and the gate ran BEFORE the flag check at first.+ const optedIn = { ...spec.entities[0], enrichDefaultViews: true };+ assert.strictEqual(enrichesDefaultViews({ ...spec, entities: [optedIn] }, optedIn), true,+ 'an explicit enrichDefaultViews:true must override the existing:true skip');+ const optedOut = { ...spec.entities[0], existing: false, enrichDefaultViews: false };+ assert.strictEqual(enrichesDefaultViews({ ...spec, entities: [optedOut] }, optedOut), false, 'the opt-out still works');+});++test('untypedColumnNames names every column whose type could not be substantiated', () => {+ // These are the columns a rebuild into a FRESH org would create as Text, because the data-model+ // phase falls back to `SDK_COLUMN_TYPE[c.type || 'Text']`. Rebuilding into an org that already has+ // the table reuses them and this is inert — which is why the loss has to be announced by name+ // rather than left for someone to discover after a cross-environment rebuild.+ assert.deepStrictEqual(untypedColumnNames([+ { schemaName: 'new_ticket', columns: [+ { schemaName: 'new_status' }, // Choice — options not read, so no type+ { schemaName: 'new_notes', type: 'Memo' },+ { schemaName: 'new_choices' }, // MultiChoice+ ] },+ { schemaName: 'new_order', columns: [{ schemaName: 'new_total', type: 'Money' }] },+ ]), ['new_ticket.new_status', 'new_ticket.new_choices']);+ assert.deepStrictEqual(untypedColumnNames([]), []);+ assert.deepStrictEqual(untypedColumnNames(undefined), []);+});++test('a downloaded Choice column is reported as untyped, so the Text downgrade is never silent', () => {+ const meta = {+ logicalName: 'new_ticket', schemaName: 'new_ticket', displayName: 'Ticket', primaryNameAttribute: 'new_name',+ attributes: [+ { logicalName: 'new_status', displayName: 'Status', attributeType: 'Picklist', isCustomAttribute: true },+ { logicalName: 'new_notes', displayName: 'Notes', attributeType: 'Memo', isCustomAttribute: true },+ ],+ };+ assert.deepStrictEqual(untypedColumnNames([entityFromMetadata(meta, 'new_ticket')]), ['new_ticket.new_status']);+});+test('iconWebResources looks up web resources by NAME (not id) and maps type from webresourcetype', async () => {const calls = [];const sdk = {@@ -227,13 +445,14 @@ test('readDashboards reconstructs supported tile shapes and skips unreadable das],};},- queryRecords: async () => [{ name: 'Executive Dashboard' }],+ queryRecords: async () => [{ name: 'Executive Dashboard', description: 'Leader view of revenue and work.' }],};const dashboards = await readDashboards(sdk, app);assert.strictEqual(dashboards.length, 1);assert.strictEqual(dashboards[0].name, 'Executive Dashboard');+ assert.strictEqual(dashboards[0].description, 'Leader view of revenue and work.');assert.deepStrictEqual(dashboards[0].tiles, [{ type: 'chart', name: 'Revenue', entity: 'account', viewId: '11111111-0000-4000-8000-000000000001', visualizationId: '22222222-0000-4000-8000-000000000002' },{ type: 'list', name: 'Open Accounts', entity: 'account', viewId: '33333333-0000-4000-8000-000000000003' },@@ -242,6 +461,118 @@ test('readDashboards reconstructs supported tile shapes and skips unreadable das]);});+test('readDashboards omits a null dashboard description instead of emitting a blank string', async () => {+ const sdk = {+ fetchArtifact: async () => ({ components: [{ type: 'iframe', name: 'Portal', parameters: { Url: 'https://contoso.example' } }] }),+ queryRecords: async (_set, opts) => {+ assert.ok(opts.select.includes('description'), 'dashboard name lookup also requests description');+ return [{ name: 'Operations', description: null }];+ },+ };+ const dashboards = await readDashboards(sdk, {+ siteMap: { areas: [{ groups: [{ subAreas: [{ type: 'DashBoard', dashboardId: 'dash-1', title: 'Operations' }] }] }] },+ });+ assert.strictEqual('description' in dashboards[0], false, 'null descriptions are absent, not empty strings');+});++test('readDescriptionInventory captures view, chart, form, business-rule, and global-choice descriptions', async () => {+ const APP_UNIQ_VALUE = '5111e0f2-0000-4000-8000-000000000001';+ const VIEW_ID = '5111e0f2-0000-4000-8000-000000000002';+ const CHART_ID = '5111e0f2-0000-4000-8000-000000000003';+ const FORM_ID = '5111e0f2-0000-4000-8000-000000000004';+ const RULE_ID = '5111e0f2-0000-4000-8000-000000000005';+ const SOL_ID = '5111e0f2-0000-4000-8000-000000000006';+ const FORM_ID_RESTRICTED = '5111e0f2-0000-4000-8000-000000000007';+ const RULE_COPY_ID = '5111e0f2-0000-4000-8000-000000000008';+ const CLASSIC_ID = '5111e0f2-0000-4000-8000-000000000009';+ const calls = [];+ const sdk = {+ // A real table logical name is the ONLY thing queryRecords can take: it resolves its argument+ // via `EntityDefinitions(LogicalName='<arg>')?$select=EntitySetName`. Anything else 404s. Fail+ // loudly on a metadata collection so this mock cannot certify a call the real SDK rejects —+ // which is exactly how the `GlobalOptionSetDefinitions` read passed review while always+ // returning empty in production.+ queryRecords: async (set, opts) => {+ if (!/^[a-z_][a-z0-9_]*$/.test(String(set))) {+ throw new Error(`queryRecords resolves an entity SET name and cannot take the metadata path '${set}' — use sdk.dataverse.get`);+ }+ calls.push({ set, opts });+ const filter = (opts && opts.filter) || '';+ if (set === 'appmodule') return [{ appmoduleidunique: APP_UNIQ_VALUE }];+ if (set === 'appmodulecomponent' && /componenttype eq 26/.test(filter)) return [{ objectid: VIEW_ID }];+ if (set === 'appmodulecomponent' && /componenttype eq 59/.test(filter)) return [{ objectid: CHART_ID }];+ if (set === 'appmodulecomponent' && /componenttype eq 60/.test(filter)) return [{ objectid: FORM_ID }, { objectid: FORM_ID_RESTRICTED }];+ if (set === 'savedquery') return [{ savedqueryid: VIEW_ID, name: 'Active Orders', returnedtypecode: 'new_order', description: 'Work queue.' }];+ if (set === 'savedqueryvisualization') return [{ savedqueryvisualizationid: CHART_ID, name: 'Orders by Status', primaryentitytypecode: 'new_order', description: null }];+ if (set === 'systemform') {+ return [+ { formid: FORM_ID, name: 'Main', objecttypecode: 'new_order', description: 'Primary form.' },+ // A form RESTRICTED to a security role. `formxml` is pulled purely to detect this, and the+ // detection is what feeds the download's access-widening warning.+ { formid: FORM_ID_RESTRICTED, name: 'Dispatcher', objecttypecode: 'new_order', description: 'Restricted.',+ formxml: '<form><tabs /><DisplayConditions Order="2" FallbackForm="false"><Role Id="{aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee}" /></DisplayConditions></form>' },+ ];+ }+ if (set === 'solution') return [{ solutionid: SOL_ID }];+ if (set === 'solutioncomponent') return [{ objectid: RULE_ID, componenttype: 29 }];+ if (set === 'workflow') {+ return [+ // A real business rule: category 2 (Business Rule), type 1 (the definition).+ { workflowid: RULE_ID, name: 'Lock Closed', primaryentity: 'new_order', description: 'Closed rows are read-only.', category: 2, type: 1 },+ // The platform's activated COPY of that same rule. Counting it would list every active+ // rule twice.+ { workflowid: RULE_COPY_ID, name: 'Lock Closed', primaryentity: 'new_order', description: 'Closed rows are read-only.', category: 2, type: 2 },+ // A CLASSIC WORKFLOW. Solution component type 29 is every process kind, so without the+ // category filter this would be mislabelled as a business rule in the inventory.+ { workflowid: CLASSIC_ID, name: 'Nightly Recalc', primaryentity: 'new_order', description: 'A classic workflow.', category: 0, type: 1 },+ ];+ }+ return [];+ },+ dataverse: {+ get: async (url) => {+ calls.push({ get: url });+ if (/^\/GlobalOptionSetDefinitions\?/.test(url)) {+ return { status: 200, headers: {}, body: { value: [{ Name: 'new_priority', Description: { LocalizedLabels: [{ Label: 'Shared priority choices.', LanguageCode: 1033 }] } }] } };+ }+ return { status: 404, headers: {}, body: {} };+ },+ },+ };++ const inv = await readDescriptionInventory(sdk, 'app-1', 'ContosoSolution');++ assert.deepStrictEqual(inv.views[0], { id: VIEW_ID, name: 'Active Orders', entity: 'new_order', description: 'Work queue.' });+ assert.strictEqual('description' in inv.charts[0], false, 'null chart descriptions are omitted');+ assert.deepStrictEqual(inv.forms[0], { id: FORM_ID, name: 'Main', entity: 'new_order', description: 'Primary form.' });+ // The role-restriction flag must NOT ride on the form entries: sanitizeDescriptionInventory spreads+ // those into `app-spec.json`, and a diagnostic has no business in the user-facing spec.+ assert.strictEqual('roleRestricted' in inv.forms[1], false,+ 'the flag belongs on the sibling key, not on each form entry');+ // BEHAVIOURAL: only the restricted form is recorded, and it is recorded by (entity, name) so the+ // warning can name it. A source regex could not catch dropping `formxml` from the $select —+ // isRoleRestrictedFormXml(undefined) is false, so the list would be silently empty forever.+ assert.deepStrictEqual(inv.roleRestrictedForms, [{ name: 'Dispatcher', entity: 'new_order' }],+ 'exactly the role-restricted form, and not the unrestricted one');+ assert.ok(calls.some((c) => c.set === 'systemform' && c.opts.select.includes('formxml')),+ 'the form read must select formxml — without it the restriction can never be detected');+ assert.deepStrictEqual(inv.businessRules[0], { id: RULE_ID, name: 'Lock Closed', entity: 'new_order', description: 'Closed rows are read-only.' });+ // Solution component type 29 is EVERY process kind, so the rows must be narrowed after the fetch.+ // A classic workflow listed as a business rule is misleading to any tool that reads the inventory,+ // and the activated type-2 copy would list every active rule twice.+ assert.strictEqual(inv.businessRules.length, 1,+ `only the type-1 category-2 definition may be listed; got ${JSON.stringify(inv.businessRules.map((r) => r.name))}`);+ assert.ok(calls.some((c) => c.set === 'workflow' && c.opts.select.includes('category') && c.opts.select.includes('type')),+ 'category and type must be REQUESTED, or the filter decides on undefined');+ assert.deepStrictEqual(inv.globalChoices[0], { name: 'new_priority', description: 'Shared priority choices.' });+ assert.ok(calls.some((c) => c.set === 'savedquery' && c.opts.select.includes('description')), 'view read selects description');+ assert.ok(calls.some((c) => c.set === 'savedqueryvisualization' && c.opts.select.includes('description')), 'chart read selects description');+ assert.ok(calls.some((c) => c.set === 'systemform' && c.opts.select.includes('description')), 'form read selects description');+ assert.ok(calls.some((c) => c.set === 'workflow' && c.opts.select.includes('description')), 'business-rule read selects description');+ assert.ok(calls.some((c) => c.get === '/GlobalOptionSetDefinitions?$select=Name,Description'),+ `global choices must be read through the RAW client (queryRecords cannot take a metadata path); calls: ${JSON.stringify(calls.map((c) => c.get || c.set))}`);+});+test('readDashboards keeps the sitemap title when the dashboard name lookup fails', async () => {const sdk = {fetchArtifact: async () => ({ components: [{ type: 'iframe', name: 'Portal', parameters: { Url: 'https://contoso.example' } }] }),@@ -258,6 +589,9 @@ const { assignPageKeys, missingDownloads, runDownload, recoverAppSolution, appCoconst { reconcilePageIds, buildManifest } = require('../lib/page-manifest.js');const { hydrateSpec } = require('../lib/hydrate-spec.js');const { validateAppSpec } = require('../lib/app-spec.js');+// `enrichesDefaultViews` gates the destructive default-view rewrite; a DOWNLOADED table is flagged+// `existing: true` because ownership is unprovable, so it must never trigger that rewrite.+const { enrichesDefaultViews } = require('../lib/sdk-build.js');const { appUniqueName } = require('../lib/sdk-build.js');const { resolvePageRefs, reverseResolveNavIds } = require('../lib/pageref-resolver.js');@@ -446,7 +780,7 @@ test('Task-6: full round-trip via runDownload → hydrateSpec → validateAppSpe// The app belongs to a real unmanaged solution — recoverAppSolution returns its uniquename, but the// publisher PREFIX must still come from the app uniquename ('test'), NOT this solution (Sol F2).if (logical === 'solutioncomponent') return [{ _solutionid_value: 'sol-x' }];- if (logical === 'solution') return [{ solutionid: 'sol-x', uniquename: 'ContosoSln', ismanaged: false }];+ if (logical === 'solution') return [{ solutionid: 'sol-x', uniquename: 'ContosoSln', ismanaged: false, description: 'The Contoso field-operations solution.' }];return [];},fetchEntityMetadata: async (logical) => ({@@ -486,6 +820,11 @@ test('Task-6: full round-trip via runDownload → hydrateSpec → validateAppSpe// existing app even after a display-name rename) and the publisher prefix is derived FROM it.assert.strictEqual(spec.app.uniqueName, APP_UNIQUE, 'the app real uniquename round-trips into spec.app.uniqueName');assert.strictEqual(spec.solution.uniqueName, 'ContosoSln', 'the real unmanaged solution uniquename is recovered for teardown');+ // `solution` is assembled field-by-field in runDownload (not spread from recoverAppSolution, so an+ // unrecovered solution still gets its required defaults). That makes every field an explicit copy,+ // and a field that is read but not copied is silently dropped — which is what happened here.+ assert.strictEqual(spec.solution.description, 'The Contoso field-operations solution.',+ 'the recovered solution description must be carried into the spec, not dropped by the field-by-field copy');assert.strictEqual(spec.solution.publisherPrefix, 'test', 'this mock SDK exposes no getSolution, so the prefix falls back to the app uniquename (test_roundtrip → test); when getSolution IS available the solution publisher wins — see the recoverAppSolution tests');assert.strictEqual(appUniqueName(spec), APP_UNIQUE, 'appUniqueName resolves the REAL uniquename (identity lookup finds the existing app, no duplicate) even though the display name is "Test App"');assert.ok(!('prefixResolved' in spec.solution), 'the transient prefixResolved flag is stripped from the persisted spec');@@ -599,12 +938,12 @@ test('recoverAppSolution recovers the publisher prefix from the SOLUTION, not thconst sdk = {queryRecords: async (set) => {if (set === 'solutioncomponent') return [{ _solutionid_value: 'sol-1' }];- if (set === 'solution') return [{ solutionid: 'sol-1', uniquename: 'ContosoCustomerManagement', ismanaged: false }];+ if (set === 'solution') return [{ solutionid: 'sol-1', uniquename: 'ContosoCustomerManagement', ismanaged: false, description: 'Customer management assets.' }];return [];},getSolution: async (uniqueName) => ({ uniqueName, publisherPrefix: 'contoso' }),};- assert.deepStrictEqual(await recoverAppSolution(sdk, 'app-1'), { uniqueName: 'ContosoCustomerManagement', publisherPrefix: 'contoso' });+ assert.deepStrictEqual(await recoverAppSolution(sdk, 'app-1'), { uniqueName: 'ContosoCustomerManagement', description: 'Customer management assets.', publisherPrefix: 'contoso' });});test('recoverAppSolution degrades to uniqueName-only when the prefix cannot be recovered', async () => {@@ -871,3 +1210,166 @@ test('a corrupt or invalid previous spec is ignored rather than failing the downassert.doesNotThrow(() => preserveAuthoredLanguageCode(spec, 'x', { existsSync: () => true, readFileSync: () => { throw new Error('EACCES'); } }));assert.strictEqual(spec.languageCode, undefined);});++// --- a form restricted to security roles must not be lost SILENTLY ------------------------------+//+// Every other download gap loses a customization. This one WIDENS ACCESS: form security roles live+// inside formxml as `<DisplayConditions>`, `forms[]` is not reconstructed by this download, and a+// form with no DisplayConditions is offered to EVERY role. So a restricted form, downloaded and+// rebuilt into a fresh environment, comes back visible to everyone.+//+// The fixtures below are the exact SHAPES measured on a live environment after a build — attribute+// order, casing and the platform's own default block. The role GUID is synthetic: this repo is+// public, and the test asserts nothing about the id's value.+const { isRoleRestrictedFormXml } = require('../download-model-app.js');++const XML_RESTRICTED = '<form><tabs /><DisplayConditions Order="2" FallbackForm="false"><Role Id="{aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee}" /></DisplayConditions></form>';+const XML_EVERYONE = '<form><tabs /><DisplayConditions Order="0" FallbackForm="true"><Everyone /></DisplayConditions></form>';+const XML_NONE = '<form><tabs /></form>';++test('a role-restricted form is detected', () => {+ assert.strictEqual(isRoleRestrictedFormXml(XML_RESTRICTED), true);+});++test('the DEFAULT shapes are NOT reported as restricted', () => {+ // Both of these mean "every role can see it". Warning on them would make the warning noise, and a+ // warning that fires on every form is a warning nobody reads.+ assert.strictEqual(isRoleRestrictedFormXml(XML_EVERYONE), false,+ '<Everyone /> is the unrestricted default, not a restriction');+ assert.strictEqual(isRoleRestrictedFormXml(XML_NONE), false,+ 'a form with no DisplayConditions at all is visible to every role');+});++test('detection does not depend on attribute order or element casing', () => {+ // Platform-authored and SDK-authored formxml differ in both, so matching either exactly would make+ // this fire on one source and not the other.+ assert.strictEqual(isRoleRestrictedFormXml('<form><displayconditions fallbackform="false" order="2"><role id="{A}" /></displayconditions></form>'), true);+ assert.strictEqual(isRoleRestrictedFormXml('<form><DisplayConditions><Role Id = "{A}" /></DisplayConditions></form>'), true);+});++test('a <Role> OUTSIDE DisplayConditions does not count', () => {+ // Scoped to the block deliberately: the word Role appears elsewhere in formxml (control names,+ // labels), and matching it loosely would report every such form as restricted.+ assert.strictEqual(isRoleRestrictedFormXml('<form><tabs><cell><control id="Role" /></cell></tabs></form>'), false);+ assert.strictEqual(isRoleRestrictedFormXml('<form><labels><label description="Role" /></labels></form>'), false);+});++test('missing or malformed formxml is not a restriction', () => {+ // Fail OPEN here, not closed: an unreadable form must not produce a spurious security warning that+ // sends someone hunting for a restriction that does not exist.+ for (const bad of [undefined, null, '', '<form', 123, {}]) {+ assert.strictEqual(isRoleRestrictedFormXml(bad), false, `${JSON.stringify(bad)} must not read as restricted`);+ }+});++test('runDownload WARNS on stderr about a role-restricted form, naming it', async () => {+ // BEHAVIOURAL. The two source-regex guards this replaces both stayed green under two realistic+ // edits — dropping `formxml` from the systemform $select, and collapsing the capturing+ // descriptionInventory accessor — either of which silences the warning completely.+ //+ // This is the single guard against a silent access WIDENING: `forms[]` is not reconstructed by the+ // download, so a restricted form rebuilt into another environment comes back visible to every role.+ const APP_ID = '6222e0f2-0000-4000-8000-000000000001';+ const APP_UNIQUE = 'new_rolewarn';+ const FORM_OPEN = '6222e0f2-0000-4000-8000-000000000002';+ const FORM_LOCKED = '6222e0f2-0000-4000-8000-000000000003';+ const SM_ID = '6222e0f2-0000-4000-8000-000000000004';+ const SM_XML = '<SiteMap><Area Id="A"><Group Id="G"><SubArea Id="S" Entity="new_order" /></Group></Area></SiteMap>';+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-rolewarn-'));++ const sdk = {+ fetchArtifact: async () => ({+ id: APP_ID, name: 'Role Warn', uniquename: APP_UNIQUE, description: '',+ siteMap: { areas: [{ title: 'M', groups: [{ title: 'G', subAreas: [{ type: 'Entity', entity: 'new_order' }] }] }] },+ }),+ queryRecords: async (logical, opts) => {+ const filter = (opts && opts.filter) || '';+ if (logical === 'appmodule') return [{ appmoduleid: APP_ID, appmoduleidunique: APP_ID, uniquename: APP_UNIQUE }];+ if (logical === 'appmodulecomponent') {+ if (/componenttype eq 60/.test(filter)) return [{ objectid: FORM_OPEN, componenttype: 60 }, { objectid: FORM_LOCKED, componenttype: 60 }];+ if (/componenttype eq 62/.test(filter)) return [{ objectid: SM_ID, componenttype: 62 }];+ return [];+ }+ if (logical === 'sitemap') return [{ sitemapxml: SM_XML }];+ if (logical === 'systemform') {+ return [+ { formid: FORM_OPEN, name: 'Everyone Form', objecttypecode: 'new_order', description: '',+ formxml: '<form><tabs /><DisplayConditions Order="0" FallbackForm="true"><Everyone /></DisplayConditions></form>' },+ { formid: FORM_LOCKED, name: 'Dispatcher Form', objecttypecode: 'new_order', description: '',+ formxml: '<form><tabs /><DisplayConditions Order="2" FallbackForm="false"><Role Id="{aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee}" /></DisplayConditions></form>' },+ ];+ }+ return [];+ },+ fetchEntityMetadata: async (logical) => ({+ logicalName: logical, schemaName: 'new_order', displayName: 'Order', primaryNameAttribute: 'new_name',+ attributes: [{ logicalName: 'new_name', displayName: 'Name', attributeType: 'String', isCustomAttribute: true }],+ relationships: [],+ }),+ dataverse: { get: async () => ({ status: 404, headers: {}, body: {} }) },+ };+ const genpageCli = { enumerateEnv: async () => ({ ok: true, ids: [], pages: [] }), download: async () => true };++ // The warning goes to stderr (non-fatal), the pattern used elsewhere in this suite.+ const origWrite = process.stderr.write.bind(process.stderr);+ const written = [];+ process.stderr.write = (chunk, ...rest) => { written.push(String(chunk)); return origWrite(chunk, ...rest); };+ let res;+ try {+ res = await runDownload({ sdk, genpageCli, outDir: out, appId: APP_ID, appUnique: APP_UNIQUE });+ } finally {+ process.stderr.write = origWrite;+ fs.rmSync(out, { recursive: true, force: true });+ }++ assert.strictEqual(res.ok, true, `the download itself must succeed; got ${res.error || ''}`);+ const text = written.join('');+ assert.match(text, /form\(s\) are restricted to specific security roles/, 'the warning must fire');+ assert.match(text, /new_order\.Dispatcher Form/, 'and must NAME the restricted form');+ assert.doesNotMatch(text, /Everyone Form/,+ 'the <Everyone /> form is the unrestricted DEFAULT — warning on it would make the warning noise');+ assert.match(text, /forms\[\]\.securityRoles/, 'and must say how to carry the restriction forward');+});++test('runDownload stays SILENT when no form is role-restricted', async () => {+ // A warning that fires on every download is a warning nobody reads.+ const APP_ID = '6333e0f2-0000-4000-8000-000000000001';+ const SM_ID = '6333e0f2-0000-4000-8000-000000000002';+ const FORM_ID = '6333e0f2-0000-4000-8000-000000000003';+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-nowarn-'));+ const sdk = {+ fetchArtifact: async () => ({+ id: APP_ID, name: 'No Warn', uniquename: 'new_nowarn', description: '',+ siteMap: { areas: [{ title: 'M', groups: [{ title: 'G', subAreas: [{ type: 'Entity', entity: 'new_order' }] }] }] },+ }),+ queryRecords: async (logical, opts) => {+ const filter = (opts && opts.filter) || '';+ if (logical === 'appmodule') return [{ appmoduleid: APP_ID, appmoduleidunique: APP_ID, uniquename: 'new_nowarn' }];+ if (logical === 'appmodulecomponent') {+ if (/componenttype eq 60/.test(filter)) return [{ objectid: FORM_ID, componenttype: 60 }];+ if (/componenttype eq 62/.test(filter)) return [{ objectid: SM_ID, componenttype: 62 }];+ return [];+ }+ if (logical === 'sitemap') return [{ sitemapxml: '<SiteMap><Area Id="A"><Group Id="G"><SubArea Id="S" Entity="new_order" /></Group></Area></SiteMap>' }];+ if (logical === 'systemform') return [{ formid: FORM_ID, name: 'Main', objecttypecode: 'new_order', description: '', formxml: '<form><tabs /></form>' }];+ return [];+ },+ fetchEntityMetadata: async (logical) => ({+ logicalName: logical, schemaName: 'new_order', displayName: 'Order', primaryNameAttribute: 'new_name',+ attributes: [{ logicalName: 'new_name', displayName: 'Name', attributeType: 'String', isCustomAttribute: true }],+ relationships: [],+ }),+ dataverse: { get: async () => ({ status: 404, headers: {}, body: {} }) },+ };+ const genpageCli = { enumerateEnv: async () => ({ ok: true, ids: [], pages: [] }), download: async () => true };+ const origWrite = process.stderr.write.bind(process.stderr);+ const written = [];+ process.stderr.write = (chunk, ...rest) => { written.push(String(chunk)); return origWrite(chunk, ...rest); };+ try {+ await runDownload({ sdk, genpageCli, outDir: out, appId: APP_ID, appUnique: 'new_nowarn' });+ } finally {+ process.stderr.write = origWrite;+ fs.rmSync(out, { recursive: true, force: true });+ }+ assert.doesNotMatch(written.join(''), /restricted to specific security roles/);+});diff --git a/plugins/model-apps/scripts/tests/entity-provision.test.js b/plugins/model-apps/scripts/tests/entity-provision.test.jsindex 0890a2016..fb22aac20 100644--- a/plugins/model-apps/scripts/tests/entity-provision.test.js+++ b/plugins/model-apps/scripts/tests/entity-provision.test.js@@ -1,4 +1,6 @@'use strict';+// Also guards AB#6648517 — RequiredLevel (Business Required) could not be set on an EXISTING+// column, so an explicit `required` change never converged on rebuild.const { test } = require('node:test');const assert = require('node:assert');const path = require('node:path');@@ -12,6 +14,7 @@ function mockSdk(existing = {}) {createTable: async (o) => { calls.push(['createTable', o.schemaName]); return { logicalName: o.schemaName.toLowerCase(), entitySetName: `${o.schemaName.toLowerCase()}s`, metadataId: `tbl-${o.schemaName}` }; },updateTable: async (l, o) => { calls.push(['updateTable', l, o]); return {}; },createColumn: async (l, o) => { calls.push(['createColumn', l, o.schemaName]); return { logicalName: o.schemaName.toLowerCase(), metadataId: `col-${o.schemaName}` }; },+ updateColumn: async (l, c, o) => { calls.push(['updateColumn', l, c, o]); return {}; },createCustomerColumn: async (l, o) => { calls.push(['createCustomerColumn', l, o.schemaName]); return { logicalName: o.schemaName.toLowerCase(), metadataId: `col-${o.schemaName}` }; },createRelationship: async (o) => { calls.push(['createRelationship', o.schemaName]); return { schemaName: o.schemaName, metadataId: `rel-${o.schemaName}`, lookupLogicalName: o.lookupSchemaName ? o.lookupSchemaName.toLowerCase() : undefined }; },createGlobalOptionSet: async (o) => { calls.push(['createGlobalOptionSet', o.name]); return { metadataId: `gc-${o.name}` }; },@@ -65,13 +68,13 @@ test('provisionDataModel recovers from createTable already-exists error and redi};// findTables returns the existing table with entitySetNamem.provision.findTables = async (s) => [{ logicalName: s.toLowerCase(), entitySetName: `${s.toLowerCase()}s_custom` }];-+const spec = { solution: { uniqueName: 'S', publisherPrefix: 'new' }, entities: [{ schemaName: 'new_ticket', displayName: 'Ticket', primaryAttribute: { schemaName: 'new_name' }, columns: [] },], relationships: [] };const runner = makeRunner({ emit: () => {}, total: 10 });const dm = await provisionDataModel({ sdk: m.sdk, provision: m.provision, runner, spec, apply: true, concurrency: 2 });-+assert.ok(dm.entities['new_ticket'], 'new_ticket entity present');assert.strictEqual(dm.entities['new_ticket'].entitySetName, 'new_tickets_custom', 'entitySetName recovered from findTables');assert.strictEqual(dm.entities['new_ticket'].logicalName, 'new_ticket', 'logicalName captured');@@ -99,21 +102,21 @@ test('provisionDataModel recovers from a transient-retry table duplicate ("Entittest('provisionDataModel recovers from createColumn already-exists error', async () => {const m = mockSdk();// createColumn throws an already-exists error- m.sdk.createColumn = async () => {+ m.sdk.createColumn = async () => {const err = new Error('Column already exists');err.statusCode = 409;throw err;};-+const spec = { solution: { uniqueName: 'S', publisherPrefix: 'new' }, entities: [{ schemaName: 'new_ticket', displayName: 'Ticket', primaryAttribute: { schemaName: 'new_name' },columns: [{ schemaName: 'new_priority', type: 'Text' }] },], relationships: [] };const runner = makeRunner({ emit: () => {}, total: 10 });-+// Should not throw - column create should skip on already-existsconst dm = await provisionDataModel({ sdk: m.sdk, provision: m.provision, runner, spec, apply: true, concurrency: 2 });-+assert.ok(dm.entities['new_ticket'], 'table created despite column error');// Column not captured because skipIf returned undefinedassert.ok(!dm.columns['new_ticket'] || dm.columns['new_ticket'].length === 0, 'column not captured on skip');@@ -141,6 +144,171 @@ test('provisionDataModel serializes column creation within an entity (per-entityassert.strictEqual(m.calls.filter((c) => c[0] === 'createColumn').length, 3, 'all three columns created');});+test('provisionDataModel updates an existing column when explicit required:true differs', async () => {+ const m = mockSdk({ new_ticket: true });+ m.provision.findColumns = async () => [+ { logicalName: 'new_priority', schemaName: 'new_priority', requiredLevel: 'None' },+ ];+ const spec = { solution: { uniqueName: 'S', publisherPrefix: 'new' }, entities: [+ { schemaName: 'new_ticket', displayName: 'Ticket', primaryAttribute: { schemaName: 'new_name' },+ columns: [{ schemaName: 'new_priority', type: 'Text', required: true }] },+ ], relationships: [] };+ const runner = makeRunner({ emit: () => {}, total: 10 });+ await provisionDataModel({ sdk: m.sdk, provision: m.provision, runner, spec, apply: true });+ assert.deepStrictEqual(+ m.calls.find((c) => c[0] === 'updateColumn'),+ ['updateColumn', 'new_ticket', 'new_priority', { required: 'ApplicationRequired' }]+ );+});++test('provisionDataModel updates an existing column when explicit required:"recommended" differs', async () => {+ const m = mockSdk({ new_ticket: true });+ m.provision.findColumns = async () => [+ { logicalName: 'new_priority', schemaName: 'new_priority', RequiredLevel: { Value: 'None' } },+ ];+ const spec = { solution: { uniqueName: 'S', publisherPrefix: 'new' }, entities: [+ { schemaName: 'new_ticket', displayName: 'Ticket', primaryAttribute: { schemaName: 'new_name' },+ columns: [{ schemaName: 'new_priority', type: 'Text', required: 'recommended' }] },+ ], relationships: [] };+ const runner = makeRunner({ emit: () => {}, total: 10 });+ await provisionDataModel({ sdk: m.sdk, provision: m.provision, runner, spec, apply: true });+ assert.deepStrictEqual(+ m.calls.find((c) => c[0] === 'updateColumn'),+ ['updateColumn', 'new_ticket', 'new_priority', { required: 'Recommended' }]+ );+});++test('provisionDataModel skips the required update when an existing column already matches', async () => {+ const events = [];+ const m = mockSdk({ new_ticket: true });+ m.provision.findColumns = async () => [+ { logicalName: 'new_priority', schemaName: 'new_priority', RequiredLevel: { Value: 'ApplicationRequired' } },+ ];+ const spec = { solution: { uniqueName: 'S', publisherPrefix: 'new' }, entities: [+ { schemaName: 'new_ticket', displayName: 'Ticket', primaryAttribute: { schemaName: 'new_name' },+ columns: [{ schemaName: 'new_priority', type: 'Text', required: true }] },+ ], relationships: [] };+ const runner = makeRunner({ emit: (e) => events.push(e), total: 10 });+ await provisionDataModel({ sdk: m.sdk, provision: m.provision, runner, spec, apply: true });+ assert.ok(!m.calls.some((c) => c[0] === 'updateColumn'), 'no metadata PUT when RequiredLevel already matches');+ assert.ok(events.some((e) => e.status === 'skip' && /required new_ticket\.new_priority \(already ApplicationRequired\)/.test(e.label)));+});++test('provisionDataModel does not demote an existing required column when the spec omits required', async () => {+ const m = mockSdk({ new_ticket: true });+ m.provision.findColumns = async () => [+ { logicalName: 'new_priority', schemaName: 'new_priority', RequiredLevel: { Value: 'ApplicationRequired' } },+ ];+ const spec = { solution: { uniqueName: 'S', publisherPrefix: 'new' }, entities: [+ { schemaName: 'new_ticket', displayName: 'Ticket', primaryAttribute: { schemaName: 'new_name' },+ columns: [{ schemaName: 'new_priority', type: 'Text' }] },+ ], relationships: [] };+ const runner = makeRunner({ emit: () => {}, total: 10 });+ await provisionDataModel({ sdk: m.sdk, provision: m.provision, runner, spec, apply: true });+ assert.ok(!m.calls.some((c) => c[0] === 'updateColumn'), 'omitted required is not interpreted as None on an existing column');+});++test('provisionDataModel leaves a new required column on the create path without updateColumn', async () => {+ const m = mockSdk();+ const spec = { solution: { uniqueName: 'S', publisherPrefix: 'new' }, entities: [+ { schemaName: 'new_ticket', displayName: 'Ticket', primaryAttribute: { schemaName: 'new_name' },+ columns: [{ schemaName: 'new_priority', type: 'Text', required: true }] },+ ], relationships: [] };+ const runner = makeRunner({ emit: () => {}, total: 10 });+ await provisionDataModel({ sdk: m.sdk, provision: m.provision, runner, spec, apply: true });+ assert.ok(m.calls.some((c) => c[0] === 'createColumn' && c[2] === 'new_priority'), 'new column still uses createColumn');+ assert.ok(!m.calls.some((c) => c[0] === 'updateColumn'), 'new column required is handled by createColumn only');+});++test('provisionDataModel warns and continues when an existing-column required update fails', async () => {+ const warnings = [];+ const events = [];+ const m = mockSdk({ new_ticket: true });+ m.provision.findColumns = async () => [+ { logicalName: 'new_priority', schemaName: 'new_priority', RequiredLevel: { Value: 'None' } },+ ];+ m.sdk.updateColumn = async (l, c, o) => {+ m.calls.push(['updateColumn', l, c, o]);+ const err = new Error('metadata lock busy');+ err.statusCode = 429;+ throw err;+ };+ const spec = { solution: { uniqueName: 'S', publisherPrefix: 'new' }, entities: [+ { schemaName: 'new_ticket', displayName: 'Ticket', primaryAttribute: { schemaName: 'new_name' },+ columns: [{ schemaName: 'new_priority', type: 'Text', required: true }] },+ ], relationships: [] };+ const runner = makeRunner({ emit: (e) => events.push(e), total: 10 });+ await provisionDataModel({ sdk: m.sdk, provision: m.provision, runner, spec, apply: true, warn: (m) => warnings.push(m) });+ assert.ok(m.calls.some((c) => c[0] === 'updateColumn'), 'the reconcile was attempted');+ assert.ok(events.some((e) => e.status === 'error' && /required new_ticket\.new_priority/.test(e.label)), 'the failed best-effort step is visible');+ assert.ok(warnings.some((w) => /could not update required level for new_ticket\.new_priority/.test(w)));+});++test('provisionDataModel serializes required-level updates within an entity', async () => {+ const m = mockSdk({ new_ticket: true });+ const mapLimits = [];+ m.provision.findColumns = async () => [+ { logicalName: 'new_a', schemaName: 'new_a', RequiredLevel: { Value: 'None' } },+ { logicalName: 'new_b', schemaName: 'new_b', RequiredLevel: { Value: 'None' } },+ ];+ const spec = { solution: { uniqueName: 'S', publisherPrefix: 'new' }, entities: [+ { schemaName: 'new_ticket', displayName: 'Ticket', primaryAttribute: { schemaName: 'new_name' },+ columns: [+ { schemaName: 'new_a', type: 'Text', required: true },+ { schemaName: 'new_b', type: 'Text', required: 'recommended' },+ ] },+ ], relationships: [] };+ const runner = makeRunner({ emit: () => {}, total: 10 });+ const realMapLimit = runner.mapLimit;+ runner.mapLimit = async (items, limit, fn) => { mapLimits.push({ count: items.length, limit }); return realMapLimit(items, limit, fn); };+ await provisionDataModel({ sdk: m.sdk, provision: m.provision, runner, spec, apply: true });+ assert.ok(mapLimits.some((m) => m.count === 2 && m.limit === 1), 'required-level metadata PUTs must be serialized');+ assert.strictEqual(m.calls.filter((c) => c[0] === 'updateColumn').length, 2);+});++test('provisionDataModel can reconcile required on the primary name column of an existing table', async () => {+ const m = mockSdk({ new_ticket: true });+ m.provision.findColumns = async () => [+ { logicalName: 'new_name', schemaName: 'new_name', RequiredLevel: { Value: 'None' } },+ ];+ const spec = { solution: { uniqueName: 'S', publisherPrefix: 'new' }, entities: [+ { schemaName: 'new_ticket', displayName: 'Ticket',+ primaryAttribute: { schemaName: 'new_name', displayName: 'Name', required: true }, columns: [] },+ ], relationships: [] };+ const runner = makeRunner({ emit: () => {}, total: 10 });+ await provisionDataModel({ sdk: m.sdk, provision: m.provision, runner, spec, apply: true });+ assert.deepStrictEqual(+ m.calls.find((c) => c[0] === 'updateColumn'),+ ['updateColumn', 'new_ticket', 'new_name', { required: 'ApplicationRequired' }]+ );+});++test('provisionDataModel reads RequiredLevel once when discovery omits it', async () => {+ const m = mockSdk({ new_ticket: true });+ const rawGets = [];+ m.provision.findColumns = async () => [+ { logicalName: 'new_priority', schemaName: 'new_priority' },+ ];+ m.sdk.dataverse = {+ get: async (url) => {+ rawGets.push(url);+ return {+ status: 200,+ body: { value: [{ LogicalName: 'new_priority', RequiredLevel: { Value: 'None' } }] },+ };+ },+ };+ const spec = { solution: { uniqueName: 'S', publisherPrefix: 'new' }, entities: [+ { schemaName: 'new_ticket', displayName: 'Ticket', primaryAttribute: { schemaName: 'new_name' },+ columns: [{ schemaName: 'new_priority', type: 'Text', required: true }] },+ ], relationships: [] };+ const runner = makeRunner({ emit: () => {}, total: 10 });+ await provisionDataModel({ sdk: m.sdk, provision: m.provision, runner, spec, apply: true });+ assert.strictEqual(rawGets.length, 1, 'one entity-level metadata read supplies all required levels');+ assert.match(rawGets[0], /\/EntityDefinitions\(LogicalName='new_ticket'\)\/Attributes\?\$select=LogicalName,RequiredLevel/);+ assert.ok(m.calls.some((c) => c[0] === 'updateColumn' && c[3].required === 'ApplicationRequired'));+});+test('provisionDataModel binds the reused global-choice metadataId on an idempotent re-run (SDK probe-then-reuse)', async () => {const m = mockSdk();// The global option set already exists. The SDK's createGlobalOptionSet is now IDEMPOTENT: it probes@@ -237,17 +405,17 @@ test('provisionDataModel enables quick-create even for an EXISTING (reused) tabltest('provisionDataModel still throws on NON-already-exists createTable error', async () => {const m = mockSdk();// createTable throws a different error (bad request, not already-exists)- m.sdk.createTable = async () => {+ m.sdk.createTable = async () => {const err = new Error('Invalid schema name');err.statusCode = 400;throw err;};-+const spec = { solution: { uniqueName: 'S', publisherPrefix: 'new' }, entities: [{ schemaName: 'new_ticket', displayName: 'Ticket', primaryAttribute: { schemaName: 'new_name' }, columns: [] },], relationships: [] };const runner = makeRunner({ emit: () => {}, total: 10 });-+// Should throw - this is NOT an already-exists errorawait assert.rejects(async () => await provisionDataModel({ sdk: m.sdk, provision: m.provision, runner, spec, apply: true, concurrency: 2 }),@@ -259,28 +427,28 @@ test('provisionDataModel still throws on NON-already-exists createTable error',test('provisionDataModel recovers from createRelationship already-exists error (1:N)', async () => {const m = mockSdk({ new_ticket: true, new_customer: true });// createRelationship throws an already-exists error- m.sdk.createRelationship = async () => {+ m.sdk.createRelationship = async () => {const err = new Error('Relationship with the same name already exists');err.statusCode = 409;throw err;};-- const spec = {- solution: { uniqueName: 'S', publisherPrefix: 'new' },++ const spec = {+ solution: { uniqueName: 'S', publisherPrefix: 'new' },entities: [{ schemaName: 'new_ticket', displayName: 'Ticket', primaryAttribute: { schemaName: 'new_name' }, columns: [] },{ schemaName: 'new_customer', displayName: 'Customer', primaryAttribute: { schemaName: 'new_name' }, columns: [] }],relationships: [- { type: 'OneToMany', referenced: 'new_customer', referencing: 'new_ticket',+ { type: 'OneToMany', referenced: 'new_customer', referencing: 'new_ticket',lookup: { schemaName: 'new_customerId', displayName: 'Customer' } }]};const runner = makeRunner({ emit: () => {}, total: 10 });-+// Should not throw - relationship create should skip on already-existsconst dm = await provisionDataModel({ sdk: m.sdk, provision: m.provision, runner, spec, apply: true, concurrency: 2 });-+assert.ok(dm.entities['new_ticket'], 'tables created despite relationship error');// Relationship not captured because skipIf returned undefinedassert.strictEqual(dm.relationships.length, 0, 'relationship not captured on skip');diff --git a/plugins/model-apps/scripts/tests/fixed-issues-coverage.test.js b/plugins/model-apps/scripts/tests/fixed-issues-coverage.test.jsnew file mode 100644index 000000000..6dde2e39e--- /dev/null+++ b/plugins/model-apps/scripts/tests/fixed-issues-coverage.test.js@@ -0,0 +1,105 @@+'use strict';+// Every bug this plugin has fixed must have a test that NAMES it.+//+// This is a coverage GUARD, not a coverage metric. The failure it prevents is specific and has+// happened here: a test whose purpose is invisible gets "simplified" by someone who cannot see what+// it guards, and the bug returns. #478 is the case in point — dashboards could not be deserialized,+// nothing in the suite fed a serialized dashboard back in, and the defect survived two separate SDK+// uptakes before a live run caught it.+//+// So the rule is: a fixed issue appears in MANIFEST, and at least one test or eval cites its id.+// Adding a fix without a citing test fails here, which is the point — the reminder arrives while the+// fix is still in your head, not months later.+//+// Citing means writing the id in the test: `#478`, `issues/478`, or `AB#6648526`. A citation is+// cheap and is the only durable link between a defect and the thing that stops it recurring.+const test = require('node:test');+const assert = require('node:assert');+const fs = require('node:fs');+const path = require('node:path');++const TESTS_DIR = __dirname;+const EVALS_DIR = path.resolve(__dirname, '..', '..', '..', '..', 'evals', 'model-apps');++// id -> what it was. Keep the description short; the issue itself holds the detail.+//+// ADO ids are recorded as `AB#NNNNNNN`, which is the standard Azure Boards <-> GitHub link syntax and+// is safe in this public repo (an opaque work-item id discloses nothing).+const MANIFEST = {+ '#475': 'the async-surface guard could not be decided by regex',+ '#478': 'the SDK could not deserialize a dashboard it had serialized',+ '#481': 'presence operators compiled to XAML the platform rejected (HTTP 500)',+ '#482': 'the business-rule fallback double-wrote — the qualifying 400 arrives AFTER the row commits',+ '#488': 'deferred review findings on business rules and column visualizations',+ '#493': 'teardown stranded the activated (type 2) copy of a business rule',+ '#494': 'download did not read artifact descriptions back',+ '#495': 'the SDK could not author Boolean default, Duration format, or per-column IsValidFor*',+ '#496': 'an existing view/chart never got its description reconciled',+ 'AB#6648516': 'no per-field read-only control on forms',+ 'AB#6648517': 'RequiredLevel could not be set on an existing column',+ 'AB#6648522': 'Whole Number had no Duration format option',+ 'AB#6648523': 'Boolean default value could not be set',+ 'AB#6648526': 'a form could not be assigned to security roles',+ 'AB#6651241': 'no per-field hidden/visibility control on forms',+ 'AB#6651276': 'no per-column IsValidForCreate/Update/Read',+ 'AB#6651439': 'no targeted form-control reordering',+ 'AB#6651696': 'auto form layout placed Big Integer columns that cannot render',+};++function walk(dir) {+ if (!fs.existsSync(dir)) return [];+ const out = [];+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ const p = path.join(dir, entry.name);+ if (entry.isDirectory()) out.push(...walk(p));+ else if (/\.(test\.js|md)$/.test(entry.name)) out.push(p);+ }+ return out;+}++// Read once — this scans the whole suite plus the evals, and doing it per-id would be O(ids × files).+const FILES = [...walk(TESTS_DIR), ...walk(EVALS_DIR)]+ // Exclude this file: it names every id by construction, so counting it would make the guard+ // trivially self-satisfying — the exact failure mode it exists to prevent.+ .filter((f) => path.resolve(f) !== path.resolve(__filename))+ .map((f) => ({ file: path.basename(f), body: fs.readFileSync(f, 'utf8') }));++function citingFiles(id) {+ // `#478` must not match `#4780`, and `AB#6648526` is matched with optional space after the hash so+ // prose spellings still count.+ const re = id.startsWith('AB#')+ ? new RegExp(`AB#\\s*${id.slice(3)}(?![0-9])`, 'i')+ : new RegExp(`(?:issues/${id.slice(1)}|#${id.slice(1)})(?![0-9])`);+ return FILES.filter((f) => re.test(f.body)).map((f) => f.file);+}++test('every fixed issue in the manifest is named by at least one test or eval', () => {+ const uncited = [];+ for (const [id, what] of Object.entries(MANIFEST)) {+ if (!citingFiles(id).length) uncited.push(`${id} — ${what}`);+ }+ assert.deepStrictEqual(uncited, [],+ 'these fixes have no test that names them, so nothing tells a future reader what the test is for:\n '+ + uncited.join('\n '));+});++test('the manifest itself is not silently empty', () => {+ // A guard that can be disarmed by emptying its own input is not a guard. Both halves are asserted:+ // the manifest has entries, and the scan actually found files to search.+ assert.ok(Object.keys(MANIFEST).length >= 18, `the manifest lost entries: ${Object.keys(MANIFEST).length}`);+ assert.ok(FILES.length > 50, `the file scan found only ${FILES.length} files — the walk is broken`);+});++test('the citation matcher does not match a longer id by prefix', () => {+ // `#478` inside `#4780` would make the guard pass on an unrelated citation. Verified directly+ // rather than trusted, because a false PASS here is invisible.+ const probe = FILES.length;+ assert.ok(probe > 0);+ const re = /(?:issues\/478|#478)(?![0-9])/;+ assert.ok(re.test('see #478 for the repro'), 'a real citation must match');+ assert.ok(re.test('https://github.com/microsoft/power-platform-skills/issues/478'), 'a link must match');+ assert.strictEqual(re.test('#4780'), false, 'a longer id must NOT match');+ const abRe = /AB#\s*6648526(?![0-9])/i;+ assert.ok(abRe.test('AB#6648526'), 'an ADO citation must match');+ assert.strictEqual(abRe.test('AB#66485260'), false, 'a longer ADO id must NOT match');+});diff --git a/plugins/model-apps/scripts/tests/form-field-options.test.js b/plugins/model-apps/scripts/tests/form-field-options.test.jsnew file mode 100644index 000000000..4c79602b9--- /dev/null+++ b/plugins/model-apps/scripts/tests/form-field-options.test.js@@ -0,0 +1,519 @@+'use strict';+// Guards four reported defects:+// AB#6648516 — no per-field read-only/locked control on forms+// AB#6651241 — no per-field hidden/visibility control on forms+// AB#6651439 — no targeted form-control reordering (explicit layout pruned unlisted fields)+// AB#6651696 — auto form layout added Big Integer columns that cannot render+// Per-field form control options: read-only, hidden, targeted repositioning, plus the auto-layout+// exclusion of column types the Unified Interface cannot render.+//+// Covers ADO 6648516 (no per-field read-only), 6651241 (no per-field hidden), 6651439 (no targeted+// reordering — explicit layout prunes unlisted fields), and 6651696 (auto layout places BigInt+// columns that render "Error loading control").+//+// The SDK-facing shapes asserted here were MEASURED against the vendored bundle, not read off its+// types. The FormXml serializer emits:+// <cell id="…" showlabel="…" visible="${cell.visible}" colspan="…" rowspan="…">+// <control id="…" classid="…" disabled="${control.isReadOnly}" isrequired="…">+// so visibility is a CELL property and read-only is a CONTROL property. Writing either onto the+// wrong object is silently dropped at serialize time, which is exactly the failure these tests pin.+const test = require('node:test');+const assert = require('node:assert');+const path = require('node:path');++const {+ compileFormIntent,+ fieldCellIntent,+ formFieldLogicals,+ findFieldCellLocation,+ normalizeFieldEntry,+ fieldOptionsMap,+ NON_FORM_RENDERABLE_TYPES,+} = require(path.join(__dirname, '..', 'lib', 'artifact-intent.js'));+const { validateAppSpec } = require(path.join(__dirname, '..', 'lib', 'app-spec.js'));++// ---------------------------------------------------------------------------+// Fixtures+// ---------------------------------------------------------------------------++// One table carrying a BigInt alongside ordinary scalars, so an exclusion test cannot pass merely+// because nothing else was on the form.+function specWithBigInt(formExtra) {+ return {+ solution: { uniqueName: 'S', publisherPrefix: 'new' },+ app: { name: 'A' },+ entities: [{+ schemaName: 'new_item',+ displayName: 'Item',+ primaryAttribute: { schemaName: 'new_name', displayName: 'Name' },+ columns: [+ { schemaName: 'new_duedate', displayName: 'Due Date', type: 'DateTime' },+ { schemaName: 'new_tracking', displayName: 'External Tracking Number', type: 'BigInt' },+ { schemaName: 'new_points', displayName: 'Story Points', type: 'Integer' },+ { schemaName: 'new_daysremaining', displayName: 'Days Remaining', type: 'Integer' },+ ],+ }],+ relationships: [],+ forms: [Object.assign({ entity: 'new_item', name: 'Item' }, formExtra || {})],+ };+}++const logicalsOf = (intent) => formFieldLogicals(intent);+// Walk to the single auto-layout section's cells so a test can assert on cell/control shape.+const autoCells = (intent) => intent.tabs[0].columns[0].sections[0].rows.flatMap((r) => r.cells);+const cellFor = (intent, logical) => autoCells(intent).find((c) => c.control && c.control.fieldName === logical);++// ---------------------------------------------------------------------------+// fieldCellIntent — the cell/control shape+// ---------------------------------------------------------------------------++test('fieldCellIntent: readOnly lands on the CONTROL as isReadOnly (the serializer reads control.isReadOnly)', () => {+ const cell = fieldCellIntent('new_number', { readOnly: true });+ assert.strictEqual(cell.control.isReadOnly, true);+ assert.strictEqual(cell.control.fieldName, 'new_number');+ assert.ok(!('visible' in cell), 'read-only must not touch cell visibility');+});++test('fieldCellIntent: hidden lands on the CELL as visible:false (the serializer reads cell.visible)', () => {+ const cell = fieldCellIntent('new_points', { hidden: true });+ assert.strictEqual(cell.visible, false);+ assert.ok(!('isReadOnly' in cell.control), 'hidden must not disable the control');+});++test('fieldCellIntent: neither flag is written when not asked for — the build never emits the negation', () => {+ const cell = fieldCellIntent('new_name', { isRequired: true });+ assert.ok(!('visible' in cell), 'an ordinary field must not pin visible:true');+ assert.ok(!('isReadOnly' in cell.control), 'an ordinary field must not pin isReadOnly:false');+ // Writing the negation would overwrite a lock/hide a maker applied by hand on every rebuild.+ assert.deepStrictEqual(Object.keys(cell), ['control']);+});++test('fieldCellIntent: both flags compose on one field', () => {+ const cell = fieldCellIntent('new_secret', { readOnly: true, hidden: true, isRequired: true });+ assert.strictEqual(cell.control.isReadOnly, true);+ assert.strictEqual(cell.control.isRequired, true);+ assert.strictEqual(cell.visible, false);+});++// ---------------------------------------------------------------------------+// 6651696 — BigInt is not form-renderable+// ---------------------------------------------------------------------------++test('auto layout omits BigInt columns — UCI has no control for them ("Error loading control")', () => {+ const spec = specWithBigInt();+ const intent = compileFormIntent(spec, spec.forms[0]);+ const fields = logicalsOf(intent);+ assert.ok(!fields.includes('new_tracking'), `BigInt placed on the auto form: ${fields.join(', ')}`);+});++test('auto layout still places every OTHER scalar type — the BigInt skip is not an over-broad filter', () => {+ const spec = specWithBigInt();+ const fields = logicalsOf(compileFormIntent(spec, spec.forms[0]));+ for (const expected of ['new_name', 'new_duedate', 'new_points', 'new_daysremaining']) {+ assert.ok(fields.includes(expected), `${expected} missing from the auto form: ${fields.join(', ')}`);+ }+});++test('an EXPLICIT layout still honours an authored BigInt — the author is not overridden, only warned', () => {+ const spec = specWithBigInt({+ layout: 'explicit',+ tabs: [{ label: 'General', sections: [{ label: 'D', columns: 1, fields: ['new_name', 'new_tracking'] }] }],+ });+ const fields = logicalsOf(compileFormIntent(spec, spec.forms[0]));+ assert.ok(fields.includes('new_tracking'), 'explicit layout must place what the author listed');+ const res = validateAppSpec(spec, { profile: 'deploy' });+ assert.ok(res.warnings.some((w) => /new_tracking/.test(w) && /BigInt/i.test(w)), `expected a BigInt warning, got: ${res.warnings.join(' | ')}`);+});++test('NON_FORM_RENDERABLE_TYPES is keyed by App Spec type name, matching entity.columns[].type', () => {+ assert.ok(NON_FORM_RENDERABLE_TYPES.has('BigInt'));+ assert.ok(!NON_FORM_RENDERABLE_TYPES.has('Integer'), 'Integer renders fine and must not be excluded');+});++// ---------------------------------------------------------------------------+// 6648516 / 6651241 — reaching the flags from both layouts+// ---------------------------------------------------------------------------++test('fieldOptions reaches an AUTO layout — the only route, since auto has no field list', () => {+ const spec = specWithBigInt({ fieldOptions: { new_points: { hidden: true }, new_duedate: { readOnly: true } } });+ const intent = compileFormIntent(spec, spec.forms[0]);+ assert.strictEqual(cellFor(intent, 'new_points').visible, false);+ assert.strictEqual(cellFor(intent, 'new_duedate').control.isReadOnly, true);+ assert.ok(!('visible' in cellFor(intent, 'new_name')), 'an unlisted field is untouched');+});++test('an EXPLICIT layout accepts an inline object field entry', () => {+ const spec = specWithBigInt({+ layout: 'explicit',+ tabs: [{ label: 'G', sections: [{ label: 'D', columns: 1, fields: ['new_name', { name: 'new_points', readOnly: true }, { name: 'new_duedate', hidden: true }] }] }],+ });+ const intent = compileFormIntent(spec, spec.forms[0]);+ const cells = intent.tabs[0].columns[0].sections[0].rows.flatMap((r) => r.cells);+ const byName = (n) => cells.find((c) => c.control.fieldName === n);+ assert.strictEqual(byName('new_points').control.isReadOnly, true);+ assert.strictEqual(byName('new_duedate').visible, false);+ assert.ok(!('isReadOnly' in byName('new_name').control));+});++test('a plain string field entry still works — the object form is additive, not a migration', () => {+ const spec = specWithBigInt({+ layout: 'explicit',+ tabs: [{ label: 'G', sections: [{ label: 'D', columns: 1, fields: ['new_name', 'new_points'] }] }],+ });+ const intent = compileFormIntent(spec, spec.forms[0]);+ assert.deepStrictEqual(logicalsOf(intent), ['new_name', 'new_points']);+});++test('an inline entry OVERRIDES the form-level fieldOptions default for the same field', () => {+ const spec = specWithBigInt({+ layout: 'explicit',+ fieldOptions: { new_points: { readOnly: true, hidden: true } },+ tabs: [{ label: 'G', sections: [{ label: 'D', columns: 1, fields: [{ name: 'new_points', readOnly: true }] }] }],+ });+ const intent = compileFormIntent(spec, spec.forms[0]);+ const cell = intent.tabs[0].columns[0].sections[0].rows[0].cells[0];+ assert.strictEqual(cell.control.isReadOnly, true);+ // hidden came only from the form-level default, which still applies where the inline entry is silent.+ assert.strictEqual(cell.visible, false);+});++test('normalizeFieldEntry lower-cases both name and anchor (every downstream compare is lower-case)', () => {+ assert.deepStrictEqual(normalizeFieldEntry('New_Name'), { name: 'new_name', readOnly: false, hidden: false, after: undefined });+ assert.deepStrictEqual(normalizeFieldEntry({ name: 'New_B', after: 'New_A' }), { name: 'new_b', readOnly: false, hidden: false, after: 'new_a' });+});++test('fieldOptionsMap ignores a non-object entry rather than throwing on a half-typed spec', () => {+ const map = fieldOptionsMap({ fieldOptions: { a: { readOnly: true }, b: 'nope', c: null } });+ assert.deepStrictEqual(Object.keys(map), ['a']);+});++// ---------------------------------------------------------------------------+// 6651439 — targeted repositioning+// ---------------------------------------------------------------------------++test('after: an anchored field is repositioned in the compiled AUTO order (create and rebuild agree)', () => {+ const spec = specWithBigInt({ fieldOptions: { new_daysremaining: { after: 'new_duedate' } } });+ const fields = logicalsOf(compileFormIntent(spec, spec.forms[0]));+ // Declaration order is name, duedate, points, daysremaining (tracking is excluded as BigInt).+ assert.deepStrictEqual(fields, ['new_name', 'new_duedate', 'new_daysremaining', 'new_points']);+});++test('after: the def carries __fieldPositions and NO cell leaks an `after` key to the SDK', () => {+ const spec = specWithBigInt({ fieldOptions: { new_daysremaining: { after: 'new_duedate' } } });+ const intent = compileFormIntent(spec, spec.forms[0]);+ assert.deepStrictEqual(intent.__fieldPositions, { new_daysremaining: 'new_duedate' });+ // A cell is pushed verbatim through addElement; `after` is not part of the SDK cell model, so it+ // must never appear there or it would be rejected or serialized into the FormXml.+ for (const cell of autoCells(intent)) {+ assert.ok(!('after' in cell), 'a cell leaked `after`');+ assert.ok(!('after' in cell.control), 'a control leaked `after`');+ }+});++test('after: a chain resolves against the running order, so b-after-a then c-after-b reads naturally', () => {+ const spec = specWithBigInt({ fieldOptions: { new_points: { after: 'new_name' }, new_daysremaining: { after: 'new_points' } } });+ const fields = logicalsOf(compileFormIntent(spec, spec.forms[0]));+ assert.deepStrictEqual(fields, ['new_name', 'new_points', 'new_daysremaining', 'new_duedate']);+});++test('after: a chain declared in REVERSE dependency order still produces a create order that satisfies it', () => {+ // The anchor walk is in entity-column order, not the author's fieldOptions order, so a single pass+ // can place a field against an anchor that is itself relocated later — leaving a create order that+ // violates its own anchors, which the first rebuild then silently "fixes". The reorder therefore+ // runs to a fixed point. Declaration order must not matter.+ //+ // The fixture matters: the chain must have a NON-PARTICIPATING cell between the anchor and its+ // dependent, or the dependency-violating move is a no-op and single-pass code passes too. Here the+ // second move must cross `new_duedate`. Verified red-green — the pre-fix single-pass body yields+ // `new_name, new_daysremaining, new_duedate, new_points`, which does not satisfy its own anchors.+ const forward = specWithBigInt({ fieldOptions: { new_daysremaining: { after: 'new_name' }, new_points: { after: 'new_daysremaining' } } });+ const reverse = specWithBigInt({ fieldOptions: { new_points: { after: 'new_daysremaining' }, new_daysremaining: { after: 'new_name' } } });+ const want = ['new_name', 'new_daysremaining', 'new_points', 'new_duedate'];+ assert.deepStrictEqual(logicalsOf(compileFormIntent(forward, forward.forms[0])), want);+ assert.deepStrictEqual(logicalsOf(compileFormIntent(reverse, reverse.forms[0])), want, 'declaration order changed the result');+});++test('validation rejects two fields anchored after the SAME field (they would fight forever)', () => {+ const spec = specWithBigInt({ fieldOptions: { new_points: { after: 'new_duedate' }, new_daysremaining: { after: 'new_duedate' } } });+ // Each build moves one to anchor+1 and then the other, displacing the first — a no-op pair+ // re-issued on every rebuild, which is exactly the non-convergence the anchor work exists to end.+ assert.ok(errsFor(spec).some((e) => /both anchored after 'new_duedate'/.test(e)), errsFor(spec).join(' | '));+});++test('validation rejects an anchor cycle — no order satisfies it', () => {+ const two = specWithBigInt({ fieldOptions: { new_points: { after: 'new_duedate' }, new_duedate: { after: 'new_points' } } });+ assert.ok(errsFor(two).some((e) => /form a cycle/.test(e)), errsFor(two).join(' | '));+ const three = specWithBigInt({ fieldOptions: { new_points: { after: 'new_duedate' }, new_duedate: { after: 'new_daysremaining' }, new_daysremaining: { after: 'new_points' } } });+ assert.ok(errsFor(three).some((e) => /form a cycle/.test(e)), errsFor(three).join(' | '));+ // A plain chain is NOT a cycle and must stay legal.+ const chain = specWithBigInt({ fieldOptions: { new_points: { after: 'new_duedate' }, new_daysremaining: { after: 'new_points' } } });+ assert.deepStrictEqual(errsFor(chain), []);+});++test('after: moving a field FORWARD (source before anchor) lands directly after the anchor, not one past it', () => {+ // The compensation case the naive implementation gets wrong: splicing the source out first shifts+ // the anchor DOWN by one, so an anchor index captured before the removal overshoots.+ // Declaration order: name(0), duedate(1), points(2), daysremaining(3).+ const spec = specWithBigInt({ fieldOptions: { new_name: { after: 'new_points' } } });+ const fields = logicalsOf(compileFormIntent(spec, spec.forms[0]));+ assert.deepStrictEqual(fields, ['new_duedate', 'new_points', 'new_name', 'new_daysremaining'],+ 'new_name must sit immediately after new_points, not after new_daysremaining');+});++test('after: a cell never carries the anchor, even if a caller passes one to fieldCellIntent', () => {+ // `after` is engine-only metadata. A cell is pushed verbatim through addElement, so any stray key+ // would be rejected by the structural validator or serialized into the FormXml.+ const cell = fieldCellIntent('new_points', { readOnly: true, hidden: true, after: 'new_name', isRequired: true });+ assert.deepStrictEqual(Object.keys(cell).sort(), ['control', 'visible']);+ assert.deepStrictEqual(Object.keys(cell.control).sort(), ['fieldName', 'isReadOnly', 'isRequired']);+});++test('after: an anchor that is not on the form is ignored, not an error (it may be a column we do not place)', () => {+ const spec = specWithBigInt({ fieldOptions: { new_points: { after: 'new_tracking' } } });+ const fields = logicalsOf(compileFormIntent(spec, spec.forms[0]));+ assert.deepStrictEqual(fields, ['new_name', 'new_duedate', 'new_points', 'new_daysremaining'], 'order unchanged');+});++test('after: an anchored field CONVERGES in a 2-column section — a rebuild of a correct form issues no move', () => {+ // The auto layout switches to 2 columns above 6 fields, so this is the common shape, not an edge+ // case. A section is a grid: `[a|b] [c|d]` reads a, b, c, d, so a field can sit correctly+ // immediately after its anchor while living in the NEXT row. Testing row-local adjacency reported+ // that as misplaced and moved it on every rebuild, leaving a 3-cell row in a 2-column section.+ const spec = {+ solution: { uniqueName: 'S', publisherPrefix: 'new' },+ app: { name: 'A' },+ entities: [{+ schemaName: 'new_item', displayName: 'Item',+ primaryAttribute: { schemaName: 'new_name', displayName: 'Name' },+ columns: ['new_c1', 'new_c2', 'new_c3', 'new_c4', 'new_c5', 'new_c6', 'new_c7'].map((n) => ({ schemaName: n, type: 'Text' })),+ }],+ relationships: [],+ forms: [{ entity: 'new_item', name: 'F', fieldOptions: { new_c6: { after: 'new_c1' } } }],+ };+ const intent = compileFormIntent(spec, spec.forms[0]);+ const section = intent.tabs[0].columns[0].sections[0];+ assert.strictEqual(section.columns, 2, 'this fixture must produce the 2-column layout the bug needs');++ // The compiled form is already correct: c6 sits flat-adjacent after c1, in the next row.+ const form = { tabs: intent.tabs };+ const from = findFieldCellLocation(form, 'new_c6');+ const to = findFieldCellLocation(form, 'new_c1');+ assert.notStrictEqual(from.rowIndex, to.rowIndex, 'the fixture must straddle a row boundary, or it proves nothing');+ assert.strictEqual(from.sectionPointer, to.sectionPointer);+ assert.strictEqual(from.flatIndex, to.flatIndex + 1,+ 'c6 must be flat-adjacent after c1 — this is the condition the reconcile uses to skip the move');+});++test('after: an anchor is recorded even for a field this layout does not place (the prune:false case)', () => {+ // Validation permits a form-level anchor for a field an explicit layout does not list — that IS+ // the documented `prune: false` use: position a control on a deployed form without re-declaring+ // the rest of it. Recording anchors only for PLACED fields made that combination silently inert.+ const spec = specWithBigInt({+ layout: 'explicit',+ prune: false,+ fieldOptions: { new_daysremaining: { after: 'new_duedate' } },+ tabs: [{ label: 'G', sections: [{ columns: 1, fields: ['new_name'] }] }],+ });+ const intent = compileFormIntent(spec, spec.forms[0]);+ assert.deepStrictEqual(logicalsOf(intent), ['new_name'], 'the layout still places only what it lists');+ assert.deepStrictEqual(intent.__fieldPositions, { new_daysremaining: 'new_duedate' },+ 'the anchor must survive for the reconcile to apply against the deployed form');+ assert.deepStrictEqual(validateAppSpec(spec, { profile: 'deploy' }).errors, []);+});++test('prune: __prune defaults true and is false only when the form opts out', () => {+ const base = specWithBigInt({ layout: 'explicit', tabs: [{ label: 'G', sections: [{ fields: ['new_name'] }] }] });+ assert.strictEqual(compileFormIntent(base, base.forms[0]).__prune, true);+ const opted = specWithBigInt({ layout: 'explicit', prune: false, tabs: [{ label: 'G', sections: [{ fields: ['new_name'] }] }] });+ assert.strictEqual(compileFormIntent(opted, opted.forms[0]).__prune, false);+});++// ---------------------------------------------------------------------------+// findFieldCellLocation — the move target maths+// ---------------------------------------------------------------------------++test('findFieldCellLocation returns the containing arrays, indices, and the SECTION-FLAT position', () => {+ const form = {+ tabs: [{ columns: [{ sections: [{ rows: [+ { cells: [{ control: { fieldName: 'a' } }, { control: { fieldName: 'b' } }] },+ { cells: [{ control: { fieldName: 'c' } }] },+ ] }] }] }],+ };+ assert.deepStrictEqual(findFieldCellLocation(form, 'b'), {+ sectionPointer: '/tabs/0/columns/0/sections/0',+ rowsPointer: '/tabs/0/columns/0/sections/0/rows',+ rowPointer: '/tabs/0/columns/0/sections/0/rows/0',+ cellsPointer: '/tabs/0/columns/0/sections/0/rows/0/cells',+ cellPointer: '/tabs/0/columns/0/sections/0/rows/0/cells/1',+ rowIndex: 0, cellIndex: 1, flatIndex: 1, rowCellCount: 2,+ });+ // `c` is in the NEXT row but is flat-adjacent to `b` — the case row-local adjacency gets wrong.+ const c = findFieldCellLocation(form, 'c');+ assert.strictEqual(c.flatIndex, 2, 'flatIndex must continue across rows, not reset per row');+ assert.strictEqual(c.rowIndex, 1);+ assert.strictEqual(c.rowCellCount, 1, 'a lone cell is detected so the ROW can be moved');+ assert.strictEqual(findFieldCellLocation(form, 'zzz'), null);+});++// ---------------------------------------------------------------------------+// Validation+// ---------------------------------------------------------------------------++const errsFor = (spec) => validateAppSpec(spec, { profile: 'deploy' }).errors;+const warnsFor = (spec) => validateAppSpec(spec, { profile: 'deploy' }).warnings;++test('validation rejects readOnly:false — the build only ever writes the ENABLED state', () => {+ const spec = specWithBigInt({ fieldOptions: { new_points: { readOnly: false } } });+ assert.ok(errsFor(spec).some((e) => /readOnly: false/.test(e)), errsFor(spec).join(' | '));+});++test('validation rejects hidden:false for the same reason', () => {+ const spec = specWithBigInt({ fieldOptions: { new_points: { hidden: false } } });+ assert.ok(errsFor(spec).some((e) => /hidden: false/.test(e)));+});++test('validation rejects a non-boolean flag rather than coercing it ("false" is truthy)', () => {+ const spec = specWithBigInt({ fieldOptions: { new_points: { readOnly: 'true' } } });+ assert.ok(errsFor(spec).some((e) => /readOnly must be a boolean/.test(e)));+});++test('validation rejects `after` inside an explicit tabs layout — two competing orderings', () => {+ const spec = specWithBigInt({+ layout: 'explicit',+ tabs: [{ label: 'G', sections: [{ fields: [{ name: 'new_points', after: 'new_name' }, 'new_name'] }] }],+ });+ assert.ok(errsFor(spec).some((e) => /cannot use 'after' for a field an explicit tabs layout already lists/.test(e)), errsFor(spec).join(' | '));+});++test('validation rejects a form-level `after` for a field the explicit layout LISTS (create and rebuild would disagree)', () => {+ // The create path honours the authored list; the reconcile applies the anchor. Allowing both makes+ // the same spec produce one order on a new form and another on its first rebuild.+ const spec = specWithBigInt({+ layout: 'explicit',+ fieldOptions: { new_points: { after: 'new_name' } },+ tabs: [{ label: 'G', sections: [{ fields: ['new_name', 'new_points'] }] }],+ });+ assert.ok(errsFor(spec).some((e) => /cannot use 'after' for a field an explicit tabs layout already lists/.test(e)), errsFor(spec).join(' | '));+});++test('validation ALLOWS a form-level `after` for a field the explicit layout does not list (the prune:false case)', () => {+ const spec = specWithBigInt({+ layout: 'explicit',+ prune: false,+ fieldOptions: { new_daysremaining: { after: 'new_duedate' } },+ tabs: [{ label: 'G', sections: [{ fields: ['new_name'] }] }],+ });+ assert.deepStrictEqual(errsFor(spec), [], 'positioning a control the layout does not re-declare is the whole point of prune:false');+});++test('validation rejects a non-array fields[] instead of letting the compiler throw a raw TypeError', () => {+ // A string is iterable and every character IS a string, so a naive per-entry check passes and the+ // compiler then dies on `(s.fields || []).map is not a function`.+ const spec = specWithBigInt({ layout: 'explicit', tabs: [{ label: 'G', sections: [{ fields: 'new_name' }] }] });+ assert.ok(errsFor(spec).some((e) => /fields must be an array/.test(e)), errsFor(spec).join(' | '));+});++test('validation rejects a self-anchor', () => {+ const spec = specWithBigInt({ fieldOptions: { new_points: { after: 'new_points' } } });+ assert.ok(errsFor(spec).some((e) => /after itself/.test(e)));+});++test('validation rejects a fieldOptions map that is not an object', () => {+ assert.ok(errsFor(specWithBigInt({ fieldOptions: ['new_points'] })).some((e) => /fieldOptions must be an object/.test(e)));+ assert.ok(errsFor(specWithBigInt({ fieldOptions: { new_points: 'readOnly' } })).some((e) => /must be an object/.test(e)));+});++test('validation rejects a field entry object with no name', () => {+ const spec = specWithBigInt({ layout: 'explicit', tabs: [{ label: 'G', sections: [{ fields: [{ readOnly: true }] }] }] });+ assert.ok(errsFor(spec).some((e) => /missing a string 'name'/.test(e)));+});++test('validation rejects a field entry that is neither a string nor an object', () => {+ const spec = specWithBigInt({ layout: 'explicit', tabs: [{ label: 'G', sections: [{ fields: [42] }] }] });+ assert.ok(errsFor(spec).some((e) => /must be a column logical name or an object/.test(e)));+});++test('validation warns that prune:false is meaningless on an auto layout', () => {+ assert.ok(warnsFor(specWithBigInt({ prune: false })).some((w) => /prune: false has no effect on an auto layout/.test(w)));+});++test('validation rejects a non-boolean prune', () => {+ assert.ok(errsFor(specWithBigInt({ prune: 'no' })).some((e) => /prune must be a boolean/.test(e)));+});++test('a spec using every new option validates clean', () => {+ const spec = specWithBigInt({ fieldOptions: { new_points: { readOnly: true }, new_duedate: { hidden: true }, new_daysremaining: { after: 'new_duedate' } } });+ const res = validateAppSpec(spec, { profile: 'deploy' });+ assert.deepStrictEqual(res.errors, [], res.errors.join(' | '));+});++test('validation does not THROW on a non-iterable fields (the BigInt scan re-iterates the same array)', () => {+ // The array guard `continue`s the FIRST loop only; the explicit-layout BigInt scan re-iterates+ // `s.fields`, so a non-iterable value threw a raw TypeError out of validateAppSpec and discarded+ // the correct finding the first loop had already pushed.+ for (const bad of [{}, 3, true]) {+ const spec = specWithBigInt({ layout: 'explicit', tabs: [{ label: 'G', sections: [{ fields: bad }] }] });+ let res;+ assert.doesNotThrow(() => { res = validateAppSpec(spec, { profile: 'deploy' }); }, `threw on fields: ${JSON.stringify(bad)}`);+ assert.ok(res.errors.some((e) => /fields must be an array/.test(e)), `no finding for fields: ${JSON.stringify(bad)}`);+ }+});++// --- layout: 'explicit' with no tabs -------------------------------------------------------------+//+// PR review: `validateFormFieldOptions` treats `layout: 'explicit'` as an explicit layout even+// without `tabs`, but `compileFormIntent` takes the explicit path only when `tabs` is an ARRAY. So+// such a spec validated green and then compiled an AUTO layout, while `prune` and the field+// positioning rules read to the author as explicit-layout behaviour.+//+// Rejected rather than warned: the two layouts differ in whether a rebuild REMOVES deployed fields,+// so guessing wrong is destructive.++const { validateAppSpec: validateSpec } = require('../lib/app-spec.js');+const { compileFormIntent: compileIntent } = require('../lib/artifact-intent.js');++function layoutSpec(form) {+ return {+ solution: { uniqueName: 'L', displayName: 'L', publisherPrefix: 'new' },+ app: { name: 'L App', description: 'd' },+ entities: [{+ schemaName: 'new_ticket', displayName: 'Ticket', pluralName: 'Tickets',+ primaryAttribute: { schemaName: 'new_subject', displayName: 'Subject' },+ columns: [{ schemaName: 'new_notes', displayName: 'Notes', type: 'Memo' }],+ }],+ forms: [{ entity: 'new_ticket', name: 'F', ...form }],+ appShell: { areas: [{ label: 'M', groups: [{ label: 'G', subAreas: [{ entity: 'new_ticket', title: 'T' }] }] }] },+ };+}++test("layout: 'explicit' with no tabs[] is a spec ERROR", () => {+ const errs = validateSpec(layoutSpec({ layout: 'explicit' }), { profile: 'plan' }).errors || [];+ assert.ok(errs.some((e) => /layout is 'explicit' but no tabs\[\] were authored/.test(e)),+ `expected an explicit-without-tabs error, got ${JSON.stringify(errs)}`);+});++test("layout: 'explicit' WITH tabs[] is fine, and so is the auto layout", () => {+ assert.deepStrictEqual(validateSpec(layoutSpec({+ layout: 'explicit',+ tabs: [{ label: 'General', sections: [{ label: 'D', columns: 1, fields: ['new_notes'] }] }],+ }), { profile: 'plan' }).errors || [], []);+ assert.deepStrictEqual(validateSpec(layoutSpec({ layout: 'auto' }), { profile: 'plan' }).errors || [], []);+ assert.deepStrictEqual(validateSpec(layoutSpec({}), { profile: 'plan' }).errors || [], []);+});++test('__explicitLayout reports what was COMPILED, not what was requested', () => {+ // The compiler falls through to the AUTO branch when `tabs` is not an array. Reporting that as an+ // explicit layout would tell the engine's reconcile to PRUNE deployed fields against a layout+ // nobody authored — a destructive action taken on the strength of a flag that was merely asked for.+ const askedSpec = layoutSpec({ layout: 'explicit' });+ const asked = compileIntent(askedSpec, askedSpec.forms[0]);+ assert.strictEqual(asked.__explicitLayout, false,+ 'no tabs were authored, so no explicit layout was compiled');++ const realSpec = layoutSpec({+ layout: 'explicit',+ tabs: [{ label: 'General', sections: [{ label: 'D', columns: 1, fields: ['new_notes'] }] }],+ });+ const real = compileIntent(realSpec, realSpec.forms[0]);+ assert.strictEqual(real.__explicitLayout, true, 'an authored tabs layout IS explicit');+});diff --git a/plugins/model-apps/scripts/tests/form-security-roles.test.js b/plugins/model-apps/scripts/tests/form-security-roles.test.jsnew file mode 100644index 000000000..20819760a--- /dev/null+++ b/plugins/model-apps/scripts/tests/form-security-roles.test.js@@ -0,0 +1,362 @@+'use strict';+// `forms[].securityRoles` — offering a form to specific security roles. AB#6648526.+//+// This capability was documented in SKILL.md as **impossible through any API**, with detailed live+// evidence, and that documentation was correct about the platform and wrong about the conclusion.+// The roles are not a relationship — `systemform` reports+// `CanBeInManyToMany: { Value: false, CanBeChanged: false }`, declares no many-to-many relationships,+// and there is no `systemformrole` entity — so every `associateRecords` shape genuinely does fail.+// They live INSIDE `formxml`, as a `<DisplayConditions>` child of `<form>`, and the vendored SDK now+// writes them there through `setFormSecurityRoles`.+//+// Two things make this surface easy to get silently wrong, so both are pinned here:+//+// 1. ORDERING. Roles do not exist until the `security` phase (13th), and forms are built at the+// `forms` phase (7th). Applying this in the forms phase would resolve every persona to nothing.+// 2. DIRECTION. A form with no `<DisplayConditions>` is offered to EVERY role. So declaring+// `securityRoles` RESTRICTS a form. A typo that silently resolved to an empty role list would+// hide the form from everyone — which is why an unresolvable persona halts rather than warns.+const test = require('node:test');+const assert = require('node:assert');++const { runSdkBuild } = require('../lib/sdk-build.js');+const { makeSimpleMockSdk } = require('./helpers/mock-sdk.js');++const ROLE_DISPATCHER = 'dddddddd-dddd-dddd-dddd-dddddddddddd';+const ROLE_TECH = 'tttttttt-tttt-tttt-tttt-tttttttttttt';++function specWithFormRoles(securityRoles, extra = {}) {+ return {+ solution: { uniqueName: 'FR', displayName: 'FR', publisherPrefix: 'new' },+ app: { name: 'FR App', description: 'd' },+ entities: [{+ schemaName: 'new_ticket', displayName: 'Ticket', pluralName: 'Tickets',+ primaryAttribute: { schemaName: 'new_subject', displayName: 'Subject' },+ columns: [{ schemaName: 'new_notes', displayName: 'Notes', type: 'Memo' }],+ }],+ forms: [{ entity: 'new_ticket', name: 'Main', formType: 'Main', ...(securityRoles ? { securityRoles } : {}) }],+ personas: [+ { persona: 'Dispatcher', jobs: [{ name: 'Assign', privileges: [{ entity: 'new_ticket', access: ['read'] }] }] },+ { persona: 'Technician', jobs: [{ name: 'Work', privileges: [{ entity: 'new_ticket', access: ['read'] }] }] },+ ],+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'R', subAreas: [{ entity: 'new_ticket', title: 'Tickets' }] }] }] },+ ...extra,+ };+}++// The provisioning client the security phase talks to. It must be a FULL mock SDK, because the same+// client drives the forms phase in these tests; layering only the two calls under test on top keeps+// the recorder honest without stubbing away the machinery that produces the form id.+//+// `setFormSecurityRoles` is RECORDED rather than stubbed away, because "was it called, with what,+// and after which role existed" is the entire contract.+function provisionForRoles({ failSet } = {}) {+ const calls = [];+ const { sdk } = makeSimpleMockSdk();+ const provision = Object.create(sdk);+ // The shared mock answers EVERY queryRecords with a truthy row, which makes `resolveExistingFormId`+ // believe a form already exists and reconcile onto an id of `undefined` — every form then gets the+ // same non-id, and an assertion that two forms differ passes vacuously. Answer `systemform`+ // honestly so the forms phase takes the CREATE path and mints distinct ids.+ provision.queryRecords = async (entity) => {+ if (entity === 'solution') return [];+ if (entity === 'systemform') return [];+ return [{ publisherid: 'pub-1' }];+ };+ provision.createPersonaRole = async (roleSpec) => {+ const name = roleSpec && (roleSpec.name || roleSpec.persona || roleSpec.displayName);+ calls.push(['createPersonaRole', name]);+ const id = /Dispatcher/i.test(JSON.stringify(roleSpec)) ? ROLE_DISPATCHER : ROLE_TECH;+ return { roleId: id, reused: false, appliedPrivileges: [], assignedTeams: [], assignedUsers: [] };+ };+ provision.addSolutionComponent = async () => undefined;+ provision.setFormSecurityRoles = async (formId, opts) => {+ calls.push(['setFormSecurityRoles', formId, opts]);+ if (failSet) throw new Error('setFormSecurityRoles exploded');+ };+ return { calls, provision };+}++// Drive forms THEN security so the form id exists, exactly as a real build does.+async function build(spec, { failSet } = {}) {+ const { sdk } = makeSimpleMockSdk();+ const { provision, calls } = provisionForRoles({ failSet });+ const events = [];+ const res = await runSdkBuild(spec, {+ sdk, provisionSdk: provision, apply: true,+ phases: ['forms', 'security'], emit: (e) => events.push(e), warn: () => {},+ });+ return { res, calls, events };+}++test('a form offered to two personas resolves them to the roles this build created', async () => {+ const { res, calls } = await build(specWithFormRoles({ personas: ['Dispatcher', 'Technician'] }));+ assert.strictEqual(res.ok, true);++ const set = calls.find((c) => c[0] === 'setFormSecurityRoles');+ assert.ok(set, `setFormSecurityRoles must be called; calls: ${JSON.stringify(calls.map((c) => c[0]))}`);+ assert.deepStrictEqual(set[2], { roleIds: [ROLE_DISPATCHER, ROLE_TECH] });++ // The id must be the FORM's, not the entity's or the app's.+ assert.strictEqual(set[1], res.created.forms['new_ticket']);+});++test('role assignment runs AFTER the roles are created, never before', async () => {+ // The ordering bug this surface invites: applied in the forms phase, every persona resolves to+ // nothing and the form is offered to no one. Assert on call ORDER, which is the only thing that+ // distinguishes the correct implementation from the broken one.+ const { calls } = await build(specWithFormRoles({ personas: ['Dispatcher'] }));+ const firstRole = calls.findIndex((c) => c[0] === 'createPersonaRole');+ const set = calls.findIndex((c) => c[0] === 'setFormSecurityRoles');+ assert.ok(firstRole > -1 && set > -1, JSON.stringify(calls.map((c) => c[0])));+ assert.ok(set > firstRole, 'the form may only be assigned once the role it names exists');+});++test('everyone: true emits the Everyone shape and no role list', async () => {+ const { calls } = await build(specWithFormRoles({ everyone: true }));+ const set = calls.find((c) => c[0] === 'setFormSecurityRoles');+ assert.deepStrictEqual(set[2], { everyone: true });+ assert.strictEqual('roleIds' in set[2], false,+ 'the platform models <Everyone /> as a REPLACEMENT for the role list, and the SDK rejects both together');+});++test('fallbackForm and order are sent only when the author set them', async () => {+ // The SDK PRESERVES both when omitted. Sending `undefined` would be indistinguishable from+ // "reset it" if that ever changes, so omission must stay omission.+ const bare = await build(specWithFormRoles({ personas: ['Dispatcher'] }));+ const bareOpts = bare.calls.find((c) => c[0] === 'setFormSecurityRoles')[2];+ assert.deepStrictEqual(Object.keys(bareOpts).sort(), ['roleIds']);++ const full = await build(specWithFormRoles({ personas: ['Dispatcher'], fallbackForm: true, order: 3 }));+ const fullOpts = full.calls.find((c) => c[0] === 'setFormSecurityRoles')[2];+ assert.deepStrictEqual(fullOpts, { roleIds: [ROLE_DISPATCHER], fallbackForm: true, order: 3 });++ // `false` and `0` must SURVIVE — they are meaningful values, not absence.+ const falsy = await build(specWithFormRoles({ personas: ['Dispatcher'], fallbackForm: false, order: 0 }));+ const falsyOpts = falsy.calls.find((c) => c[0] === 'setFormSecurityRoles')[2];+ assert.strictEqual(falsyOpts.fallbackForm, false);+ assert.strictEqual(falsyOpts.order, 0);+});++test('a persona the build did not create HALTS — it must never silently hide the form', async () => {+ // A form with no DisplayConditions is visible to every role, so an unresolved name that produced+ // an empty role list would REMOVE access rather than fail to add it. That is the one outcome this+ // surface must not reach quietly.+ await assert.rejects(+ () => build(specWithFormRoles({ personas: ['Dispatcher', 'Ghost'] })),+ (err) => /Ghost/.test(String(err.message)) && /personas\[\]/.test(String(err.message)),+ 'the halt must name the offending persona and how to fix it');+});++test('a form without securityRoles is left alone entirely', async () => {+ const { calls } = await build(specWithFormRoles(null));+ assert.strictEqual(calls.some((c) => c[0] === 'setFormSecurityRoles'), false,+ 'omitting securityRoles must not touch the form — every role can see it, which is the default');+});++test('a failure to assign roles HALTS the build', async () => {+ // Not a warning: the author asked for a restriction, and reporting success while the form stays+ // universally visible is a security-relevant lie.+ await assert.rejects(() => build(specWithFormRoles({ personas: ['Dispatcher'] }), { failSet: true }));+});++test('the dry-run plan lists form role assignment under security, not forms', async () => {+ const { sdk } = makeSimpleMockSdk();+ const events = [];+ const res = await runSdkBuild(specWithFormRoles({ personas: ['Dispatcher'] }), {+ sdk, apply: false, emit: (e) => events.push(e),+ });+ const item = res.plan.find((l) => /form roles for/.test(l));+ assert.ok(item, `the plan must mention it; plan: ${JSON.stringify(res.plan)}`);+ const ev = events.find((e) => /form roles for/.test(e.label || ''));+ assert.strictEqual(ev.phase, 'security',+ 'planning it under `forms` would put it before the roles exist, which is the bug this ordering avoids');+});++test('a non-Main form is addressed by its own identity, not the entity default', async () => {+ // `created.forms` is keyed by ENTITY and holds only the Main form. A QuickCreate form annotated+ // with securityRoles must resolve to ITS id — binding to the Main form would restrict the wrong+ // form, and every structural assertion would still pass.+ const spec = specWithFormRoles(null);+ spec.forms = [+ { entity: 'new_ticket', name: 'Main', formType: 'Main' },+ { entity: 'new_ticket', name: 'Quick', formType: 'QuickCreate', securityRoles: { personas: ['Dispatcher'] } },+ ];+ const { res, calls } = await build(spec);+ const set = calls.find((c) => c[0] === 'setFormSecurityRoles');+ assert.ok(set, 'the QuickCreate form must still be assignable');+ assert.notStrictEqual(set[1], res.created.forms['new_ticket'],+ 'it must NOT resolve to the entity Main form');+ assert.strictEqual(set[1], res.created.formIds['new_ticket|QuickCreate|Quick']);+});++// --- spec-gate validation -----------------------------------------------------------------------+//+// Every failure here is ACCESS-relevant, because the direction is counter-intuitive: a form with no+// assignment is offered to EVERY role, so a malformed or empty assignment REMOVES access rather than+// failing to add it. They are therefore hard errors, not warnings.++const { validateAppSpec } = require('../lib/app-spec.js');+const errorsFor = (securityRoles, mutate) => {+ const spec = specWithFormRoles(securityRoles);+ if (mutate) mutate(spec);+ return validateAppSpec(spec, { profile: 'plan' }).errors || [];+};++test('a well-formed assignment validates', () => {+ assert.deepStrictEqual(errorsFor({ personas: ['Dispatcher'] }), []);+ assert.deepStrictEqual(errorsFor({ everyone: true }), []);+ assert.deepStrictEqual(errorsFor({ personas: ['Dispatcher'], fallbackForm: true, order: 2 }), []);+});++test('a persona not declared in personas[] is caught at the GATE, not two minutes into a build', () => {+ const errs = errorsFor({ personas: ['Ghost'] });+ assert.ok(errs.some((e) => /'Ghost'/.test(e) && /not declared in personas\[\]/.test(e)),+ `expected a persona error, got ${JSON.stringify(errs)}`);+});++test('an EMPTY persona list is rejected — it would offer the form to nobody', () => {+ const errs = errorsFor({ personas: [] });+ assert.ok(errs.some((e) => /offer the form to NO role/.test(e)), JSON.stringify(errs));+});++test('everyone and personas together are rejected — the platform treats them as exclusive', () => {+ const errs = errorsFor({ everyone: true, personas: ['Dispatcher'] });+ assert.ok(errs.some((e) => /cannot set both/.test(e)), JSON.stringify(errs));+});++test('everyone: false is rejected, and the message names the way to actually undo a restriction', () => {+ // It looks like "restrict to nobody" and means nothing. The fix an author needs is+ // `everyone: true` — deleting the block does NOT undo a deployed restriction, because the build+ // only visits forms that declare `securityRoles`. Steering them to "just omit it" was wrong.+ const errs = errorsFor({ everyone: false });+ assert.ok(errs.some((e) => /does nothing/.test(e) && /"everyone": true/.test(e)), JSON.stringify(errs));+});++test('an assignment that says nothing at all is rejected', () => {+ const errs = errorsFor({ fallbackForm: true });+ assert.ok(errs.some((e) => /must say who the form is for/.test(e)), JSON.stringify(errs));+});++test('wrong types are rejected rather than coerced', () => {+ assert.ok(errorsFor(['Dispatcher']).some((e) => /securityRoles must be an object/.test(e)));+ assert.ok(errorsFor({ personas: 'Dispatcher' }).some((e) => /must be an array of persona names/.test(e)));+ assert.ok(errorsFor({ personas: ['Dispatcher'], fallbackForm: 'true' }).some((e) => /fallbackForm must be a boolean/.test(e)),+ 'the string "true" is truthy in JS, so coercing it would hide the mistake');+ assert.ok(errorsFor({ personas: ['Dispatcher'], order: -1 }).some((e) => /non-negative integer/.test(e)));+ assert.ok(errorsFor({ personas: ['Dispatcher'], order: 1.5 }).some((e) => /non-negative integer/.test(e)));+});++test('an unknown key is reported instead of silently ignored', () => {+ // A typo like `roles` instead of `personas` would otherwise validate, build, and restrict nothing.+ const errs = errorsFor({ personas: ['Dispatcher'], roles: ['Dispatcher'] });+ assert.ok(errs.some((e) => /unknown key 'roles'/.test(e)), JSON.stringify(errs));+});++test('a duplicated persona is reported', () => {+ const errs = errorsFor({ personas: ['Dispatcher', 'dispatcher'] });+ assert.ok(errs.some((e) => /more than once/.test(e)), JSON.stringify(errs));+});++test('an AMBIGUOUS form identity is rejected rather than resolved by build order', () => {+ // Only QuickView forms are checked for a unique (entity, name); Main and Card may both be called+ // "Information" harmlessly. Harmless, that is, until one declares securityRoles — the build's+ // (entity, formType, name) map would keep whichever was built last, so the restriction would land+ // on the WRONG form while every structural check passed and the build reported success.+ const spec = specWithFormRoles(null);+ spec.forms = [+ { entity: 'new_ticket', name: 'Information', formType: 'Main', securityRoles: { personas: ['Dispatcher'] } },+ { entity: 'new_ticket', name: 'Information', formType: 'Main' },+ ];+ const errs = validateAppSpec(spec, { profile: 'plan' }).errors || [];+ assert.ok(errs.some((e) => /unambiguously/.test(e) && /Information/.test(e)),+ `expected an ambiguity error naming the form, got ${JSON.stringify(errs)}`);+});++test('two forms with the SAME name but different types are fine', () => {+ // The identity includes formType, so this pair is unambiguous and must not be rejected — that is+ // exactly the Main/Card "Information" case the QuickView-only check was written to permit.+ const spec = specWithFormRoles(null);+ spec.forms = [+ { entity: 'new_ticket', name: 'Information', formType: 'Main', securityRoles: { personas: ['Dispatcher'] } },+ { entity: 'new_ticket', name: 'Information', formType: 'QuickCreate' },+ ];+ assert.deepStrictEqual(validateAppSpec(spec, { profile: 'plan' }).errors || [], []);+});++test('a persona named in a DIFFERENT CASE resolves — the gate and the build must agree', async () => {+ // Found in review. The spec gate lower-cases both sides; the build looked the role up in a+ // case-SENSITIVE map keyed by the persona's own casing. So `personas: ["dispatcher"]` against a+ // declared "Dispatcher" passed validation and then threw inside the security phase — which is the+ // LAST thing a build does, after every table, column, form, view, chart, dashboard, page and role+ // already exists. Exactly the half-built outcome the business-rule skip was written to avoid, and+ // it falsified this surface's own promise that a bad name is caught at the gate.+ const spec = specWithFormRoles({ personas: ['dispatcher'] }); // declared as 'Dispatcher'+ assert.deepStrictEqual(validateAppSpec(spec, { profile: 'plan' }).errors || [], [],+ 'the gate accepts it case-insensitively');++ const { res, calls } = await build(spec);+ assert.strictEqual(res.ok, true, 'so the build must too, rather than halting at the last phase');+ const set = calls.find((c) => c[0] === 'setFormSecurityRoles');+ assert.deepStrictEqual(set[2], { roleIds: [ROLE_DISPATCHER] });+});++test('surrounding whitespace in a persona name also resolves', async () => {+ // canonicalPersonaName trims, and the roles map is keyed by the trimmed name — so the lookup has+ // to trim too or this is the same bug wearing a different hat.+ const spec = specWithFormRoles({ personas: [' Dispatcher '] });+ const { res, calls } = await build(spec);+ assert.strictEqual(res.ok, true);+ assert.deepStrictEqual(calls.find((c) => c[0] === 'setFormSecurityRoles')[2], { roleIds: [ROLE_DISPATCHER] });+});++test('the case-insensitive persona lookup DEPENDS on personas[] being unique case-insensitively', () => {+ // The build resolves `securityRoles.personas` through a lower-cased index of the roles it created.+ // That is only unambiguous because `personas[]` already rejects two names that differ solely by+ // case — a check that lives in a completely different part of app-spec.js and was written for an+ // unrelated reason (the SDK trims and matches role names, so near-duplicates collapse onto one+ // role and the second silently replaces the first's privileges).+ //+ // Nothing connects the two. If that uniqueness rule were ever relaxed, the index would silently+ // keep one of the two roles and a form could be offered to the WRONG one, with every test here+ // still green. This pins the dependency so relaxing it fails loudly instead.+ const spec = specWithFormRoles({ personas: ['Dispatcher'] });+ spec.personas = [+ { persona: 'Dispatcher', jobs: [{ name: 'a', privileges: [{ entity: 'new_ticket', access: ['read'] }] }] },+ { persona: 'dispatcher', jobs: [{ name: 'b', privileges: [{ entity: 'new_ticket', access: ['read'] }] }] },+ ];+ const errs = validateAppSpec(spec, { profile: 'plan' }).errors || [];+ assert.ok(errs.some((e) => /duplicate persona name/.test(e)),+ `personas[] must keep rejecting case-only duplicates, or the role index below becomes ambiguous; got ${JSON.stringify(errs)}`);+});++test('an entity whose ONLY form is a QuickCreate is still PUBLISHED, or the restriction never lands', async () => {+ // `created.forms` is written only for MAIN forms, so for an entity whose sole declared form is a+ // QuickCreate carrying `securityRoles`, the publish phase's fallback to `created.formIds` is the+ // ONLY thing that puts that entity in the publish set.+ //+ // Why that matters: MEASURED live, `setFormSecurityRoles` writes to the UNPUBLISHED layer — the+ // published row still read `<Everyone />` until PublishXml ran. So without the fallback,+ // `--apply --publish` reports success, the security phase reports "1 role(s)", and the form stays+ // visible to every role. A silent widening of access behind a green build.+ const { sdk } = makeSimpleMockSdk();+ const { provision, calls } = provisionForRoles();+ const published = [];+ provision.publishArtifact = async (type, id) => { published.push([type, id]); return { shipped: true }; };++ const spec = specWithFormRoles(null);+ spec.forms = [{ entity: 'new_ticket', name: 'Quick', formType: 'QuickCreate', securityRoles: { personas: ['Dispatcher'] } }];++ const res = await runSdkBuild(spec, {+ sdk, provisionSdk: provision, apply: true, publish: true,+ phases: ['forms', 'security', 'publish'], emit: () => {}, warn: () => {},+ });+ assert.strictEqual(res.ok, true);++ const qcId = res.created.formIds['new_ticket|QuickCreate|Quick'];+ assert.ok(qcId, 'the QuickCreate form must have been built');+ assert.strictEqual(res.created.forms['new_ticket'], undefined,+ 'and created.forms must NOT hold it — that is the whole point of this test');+ assert.ok(published.some(([t, id]) => t === 'form' && id === qcId),+ `the entity must be published via its QuickCreate form; published: ${JSON.stringify(published)}`);+});diff --git a/plugins/model-apps/scripts/tests/hydrate-spec.test.js b/plugins/model-apps/scripts/tests/hydrate-spec.test.jsindex e0e6c7c3a..c522ea0af 100644--- a/plugins/model-apps/scripts/tests/hydrate-spec.test.js+++ b/plugins/model-apps/scripts/tests/hydrate-spec.test.js@@ -47,6 +47,83 @@ test('hydrateSpec reconstructs a valid, complete spec (entities + appShell + pagassert.strictEqual(r.ok, true, JSON.stringify(r.errors));});+test('hydrateSpec unwraps Dataverse Label descriptions and omits absent descriptions', async () => {+ const spec = await hydrateSpec({+ app: async () => ({ name: 'A', description: null, siteMap: { areas: [] } }),+ pages: async () => [],+ entities: async () => [{+ schemaName: 'new_order',+ displayName: 'Order',+ description: {+ LocalizedLabels: [{ Label: 'fallback table text', LanguageCode: 1033 }],+ UserLocalizedLabel: null,+ },+ primaryAttribute: { schemaName: 'new_name', displayName: 'Name' },+ columns: [+ {+ schemaName: 'new_score',+ displayName: 'Score',+ type: 'Integer',+ description: {+ LocalizedLabels: [{ Label: 'fallback column text', LanguageCode: 1033 }],+ },+ },+ { schemaName: 'new_notes', displayName: 'Notes', type: 'Memo', description: null },+ ],+ }],+ webResources: async () => [],+ dashboards: async () => [+ { id: 'd-1', name: 'Ops', description: 'Daily operating view.', tiles: [{ type: 'iframe', name: 'Portal', url: 'https://contoso.example' }] },+ { id: 'd-2', name: 'Empty Desc', description: null, tiles: [{ type: 'iframe', name: 'Portal', url: 'https://contoso.example' }] },+ ],+ solution: async () => ({+ uniqueName: 'S',+ publisherPrefix: 'new',+ description: {+ UserLocalizedLabel: { Label: 'solution label wins', LanguageCode: 1033 },+ LocalizedLabels: [{ Label: 'fallback solution text', LanguageCode: 1033 }],+ },+ }),+ });++ assert.strictEqual(spec.solution.description, 'solution label wins');+ assert.strictEqual(spec.entities[0].description, 'fallback table text');+ assert.strictEqual(spec.entities[0].columns[0].description, 'fallback column text');+ assert.strictEqual('description' in spec.entities[0].columns[1], false, 'null column descriptions must be omitted, not blanked');+ assert.strictEqual(spec.dashboards[0].description, 'Daily operating view.');+ assert.strictEqual('description' in spec.dashboards[1], false, 'null dashboard descriptions must be omitted, not blanked');++ const v = validateAppSpec(spec, { profile: 'plan', reconstructed: true });+ assert.strictEqual(v.ok, true, JSON.stringify(v.errors));+});++test('hydrateSpec carries description inventory for artifacts it does not structurally round-trip', async () => {+ const spec = await hydrateSpec({+ app: async () => ({ name: 'A', description: '', siteMap: { areas: [] } }),+ pages: async () => [],+ entities: async () => [{ schemaName: 'new_order', displayName: 'Order', primaryAttribute: { schemaName: 'new_name', displayName: 'Name' }, columns: [] }],+ webResources: async () => [],+ dashboards: async () => [],+ solution: async () => ({ uniqueName: 'S', publisherPrefix: 'new' }),+ descriptionInventory: async () => ({+ views: [{ id: 'v-1', name: 'Active Orders', entity: 'new_order', description: 'Work queue.' }],+ charts: [{ id: 'c-1', name: 'Orders by Status', entity: 'new_order', description: null }],+ forms: [{ id: 'f-1', name: 'Main', entity: 'new_order', description: { UserLocalizedLabel: { Label: 'Main form context.', LanguageCode: 1033 } } }],+ businessRules: [{ id: 'br-1', name: 'Lock Closed', entity: 'new_order', description: 'Closed orders are read-only.' }],+ globalChoices: [{ name: 'new_priority', description: { LocalizedLabels: [{ Label: 'Shared priority choices.', LanguageCode: 1033 }] } }],+ }),+ });++ assert.deepStrictEqual(spec.descriptionInventory.views[0], { id: 'v-1', name: 'Active Orders', entity: 'new_order', description: 'Work queue.' });+ assert.strictEqual('description' in spec.descriptionInventory.charts[0], false, 'null chart descriptions must be omitted, not blanked');+ assert.strictEqual(spec.descriptionInventory.forms[0].description, 'Main form context.');+ assert.strictEqual(spec.descriptionInventory.businessRules[0].description, 'Closed orders are read-only.');+ assert.strictEqual(spec.descriptionInventory.globalChoices[0].description, 'Shared priority choices.');++ const v = validateAppSpec(spec, { profile: 'plan', reconstructed: true });+ assert.strictEqual(v.ok, true, JSON.stringify(v.errors));+});+test('hydrateSpec maps a GenPage subarea back to a page target by name (case-insensitive id match)', async () => {const spec = await hydrateSpec(deployedRead());const subs = spec.appShell.areas[0].groups[0].subAreas;diff --git a/plugins/model-apps/scripts/tests/sdk-async-surface.test.js b/plugins/model-apps/scripts/tests/sdk-async-surface.test.jsindex 4b022d290..1045fedfc 100644--- a/plugins/model-apps/scripts/tests/sdk-async-surface.test.js+++ b/plugins/model-apps/scripts/tests/sdk-async-surface.test.js@@ -1,931 +1,831 @@-'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 });- }+'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.+ */+// markerInComment / isWaiverLine are defined by the AST scan below — the regex-era pair they+// replaced inferred "is this a comment?" from punctuation, which a template literal can forge.++/**+ * 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.+ */+const acorn = require('./vendor/acorn.cjs');++const PARSE_OPTS = {+ ecmaVersion: 'latest',+ sourceType: 'script',+ locations: true,+ // The corpus is made of fragments, and production files are CommonJS: both can legitimately have+ // top-level await or a bare return in the snippets we hand this.+ allowAwaitOutsideFunction: true,+ allowReturnOutsideFunction: true,+ allowHashBang: true,+};++/** Parse, collecting comments. Returns null when the source will not parse. */+function parseForGuard(raw) {+ const comments = [];+ for (const sourceType of ['script', 'module']) {+ comments.length = 0;+ try {+ const ast = acorn.parse(raw, { ...PARSE_OPTS, sourceType, onComment: comments });+ return { ast, comments: comments.slice() };+ } catch { /* try the other goal symbol */ }+ }+ return null;+}++/**+ * Is `marker` inside a WHOLE-LINE comment on this line?+ *+ * Decided from the parser's own comment list rather than inferred from punctuation: a line that+ * begins with `//` is not necessarily a comment (inside a template literal it is just text), and+ * that forgery previously silenced a real call. "Whole-line" means nothing but whitespace precedes+ * the comment — a trailing `// sdk-async-ok` after live code does not waive it.+ */+function markerInComment(rawLine, marker) {+ const parsed = parseForGuard(String(rawLine || ''));+ if (!parsed) return false;+ return parsed.comments.some((c) => {+ if (!String(c.value).includes(marker)) return false;+ return String(rawLine).slice(0, c.start).trim() === '';+ });+}+const isWaiverLine = (rawLine) => markerInComment(rawLine, OPT_OUT);++/** Walk every node, calling `visit(node, ancestors)` with the ancestor chain (closest first). */+function walk(node, visit, ancestors = []) {+ if (!node || typeof node.type !== 'string') return;+ visit(node, ancestors);+ const nextAncestors = [node, ...ancestors];+ for (const key of Object.keys(node)) {+ if (key === 'type' || key === 'loc' || key === 'start' || key === 'end') continue;+ const value = node[key];+ if (Array.isArray(value)) {+ for (const child of value) if (child && typeof child.type === 'string') walk(child, visit, nextAncestors);+ } else if (value && typeof value.type === 'string') {+ walk(value, visit, nextAncestors);+ }+ }+}++/** The method name a callee refers to, for both `x.m()` and `x['m']()`; null otherwise. */+function calleeMethodName(callee) {+ const target = callee && callee.type === 'ChainExpression' ? callee.expression : callee;+ if (!target || target.type !== 'MemberExpression') return null;+ const prop = target.property;+ if (!target.computed) return prop && prop.type === 'Identifier' ? prop.name : null;+ if (prop && prop.type === 'Literal' && typeof prop.value === 'string') return prop.value;+ // `x[\`getArtifact\`]()` — a template with no interpolation is a constant string.+ if (prop && prop.type === 'TemplateLiteral' && prop.expressions.length === 0 && prop.quasis.length === 1) {+ return prop.quasis[0].value.cooked;+ }+ return null;+}++/** Names bound by an ObjectPattern, covering rename, default, computed key and rest. */+function patternBoundNames(pattern, out) {+ if (!pattern || pattern.type !== 'ObjectPattern') return;+ for (const p of pattern.properties) {+ if (p.type === 'RestElement') continue;+ const k = p.key;+ if (!p.computed && k && k.type === 'Identifier') out.push(k.name);+ else if (k && k.type === 'Literal' && typeof k.value === 'string') out.push(k.value);+ }+}++function findUnawaitedCalls(raw) {+ const rawLines = raw.split('\n');+ const found = [];+ found.waivedLines = new Set();+ let candidates = 0;++ const parsed = parseForGuard(raw);+ if (!parsed) {+ // Unparseable source is reported rather than skipped: silently scanning nothing is precisely the+ // fail-open behaviour this guard exists to prevent.+ found.push({ line: 1, text: '(source did not parse — the guard could not inspect this file)', kind: 'parse error' });+ found.candidates = 0;+ found.waived = 0;+ return found;+ }++ // A waiver is a whole-line comment carrying the marker, taken from the parser's comment list.+ const waiverLines = new Map();+ for (const c of parsed.comments) {+ if (c.type !== 'Line') continue;+ const line = c.loc.start.line;+ if (String(rawLines[line - 1] || '').slice(0, c.loc.start.column).trim() !== '') continue;+ const existing = waiverLines.get(line) || [];+ existing.push(String(c.value));+ waiverLines.set(line, existing);+ }+ const waivedAbove = (line, marker) => (waiverLines.get(line - 1) || []).some((v) => v.includes(marker));++ const record = (line, kind) => {+ const text = rawLines[line - 1] || '';+ if (!found.some((f) => f.line === line && f.kind === kind)) found.push({ line, text: text.trim(), kind });+ };++ walk(parsed.ast, (node, ancestors) => {+ const parent = ancestors[0] || null;+ if (node.type === 'CallExpression') {+ const name = calleeMethodName(node.callee);+ if (!name || !ASYNC_SDK_METHODS.includes(name)) return;+ candidates += 1;+ // `await x.m()` is AwaitExpression -> CallExpression, but `await x?.m()` is+ // AwaitExpression -> ChainExpression -> CallExpression, so the await can be the GRANDparent.+ // Checking only the immediate parent flagged every correctly-awaited optional call.+ const awaited = (parent && parent.type === 'AwaitExpression')+ || (parent && parent.type === 'ChainExpression'+ && ancestors[1] && ancestors[1].type === 'AwaitExpression');+ if (awaited) return;+ const line = node.loc.start.line;+ if (waivedAbove(line, OPT_OUT)) { found.waivedLines.add(line); return; }+ record(line, 'call');+ return;+ }+ // Destructuring the async surface is banned outright: the resulting call sites have no receiver,+ // so nothing downstream could ever match them. Covers both `const { getArtifact } = sdk` and+ // `function use({ getArtifact })` — the parameter form is the case regexes could not decide.+ if (node.type === 'ObjectPattern') {+ const names = [];+ patternBoundNames(node, names);+ const hit = names.find((n) => ASYNC_SDK_METHODS.includes(n));+ if (!hit) return;+ const line = node.loc.start.line;+ // The ordinary waiver must NOT apply: one comment would hide every call made through the+ // binding. A dedicated marker exists for a genuine false positive.+ if (waivedAbove(line, OPT_OUT_BINDING)) return;+ record(line, 'destructured binding');+ }+ });++ found.candidates = candidates;+ found.waived = found.waivedLines.size;+ 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;",+ // Previously an ACCEPTED FALSE POSITIVE. The regex scan reported it because suppressing it would+ // have required deciding "this offset is inside a string" — the very lexing that could itself+ // desync. A parser decides it for free: this is a TemplateLiteral, not a CallExpression, so it+ // is now correctly silent. Kept as a pinned case so a regression back to text matching fails.+ 'a call written inside a template literal on a code line': 'log(`use x.getArtifact(y)`);',+ // The construct regexes genuinely could not decide (#475): an ObjectPattern in a PARAMETER list+ // is indistinguishable from an ObjectExpression by text, so catching it flagged every mock object+ // literal in this suite. The parser separates them.+ 'a mock object literal in a call argument (an ObjectExpression, not a pattern)':+ "use({ getArtifact: spy, addElement: spy2 });",+ };+ for (const [label, code] of Object.entries(MUST_NOT_FLAG)) {+ assert.strictEqual(check(code), false, `the matcher must NOT flag: ${label}`);+ }++ // Constructs the regex scan could not decide, now caught (#475).+ const AST_ONLY = {+ 'PARAMETER destructuring of the async surface': "function use({ getArtifact }) { getArtifact(id); }",+ 'parameter destructuring with a rename': "const use = ({ getArtifact: read }) => read(id);",+ 'nested parameter destructuring': "function use({ sdk: { addElement } }) { addElement(a, b); }",+ };+ for (const [label, code] of Object.entries(AST_ONLY)) {+ assert.strictEqual(check(code), true, `the AST scan must 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.+ // (The former ACCEPTED_FALSE_POSITIVES block is gone: the parser removed the only entry in it.)+++ 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 });+ }+});++// --- red-green: the AST scan must actually fire on a real un-awaited call --------------------------+//+// A guard that matches nothing "passes" forever. The corpus above proves the matcher, but this pins+// the end-to-end path the CI test uses: production source in, findings out.+test('MUTATION: dropping an await in real plugin source is caught', () => {+ const fsx = require('node:fs');+ const target = path.join(SCRIPTS_DIR, 'lib', 'sdk-build.js');+ const src = fsx.readFileSync(target, 'utf8');+ // Find a genuine awaited call on the guarded surface and remove just the `await`.+ const m = new RegExp(`await\\s+(\\w+)\\.(${ASYNC_SDK_METHODS.join('|')})\\(`).exec(src);+ assert.ok(m, 'expected at least one awaited generic-surface call in sdk-build.js');+ const mutated = src.slice(0, m.index) + src.slice(m.index + 'await '.length);+ const hits = findUnawaitedCalls(mutated).filter((h) => h.kind === 'call');+ assert.ok(hits.length > 0, 'removing an await must produce a finding');+ // And the unmutated file is clean, so the finding came from the mutation and not from noise.+ assert.deepStrictEqual(findUnawaitedCalls(src).filter((h) => h.kind === 'call'), []);+});++test('an unparseable file is REPORTED, never silently skipped', () => {+ // Failing open is the one thing this guard must not do: a file the scan cannot read is a file it+ // cannot vouch for.+ const hits = findUnawaitedCalls('const x = ;;;(');+ assert.ok(hits.some((h) => h.kind === 'parse error'), 'a parse failure must surface as a finding');});diff --git a/plugins/model-apps/scripts/tests/sdk-build.test.js b/plugins/model-apps/scripts/tests/sdk-build.test.jsindex 748ce0820..8ceacf797 100644--- a/plugins/model-apps/scripts/tests/sdk-build.test.js+++ b/plugins/model-apps/scripts/tests/sdk-build.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 { 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 { commandDef, chartDef, 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@@ -97,6 +97,12 @@ function mockSdk(opts = {}) {calls.push({ name: 'queryRecords', args: [e, o] });const filter = (o && o.filter) || '';if (e === 'solution') return opts.solutionExists ? [{ solutionid: 's' }] : [];+ // The chart description reconcile (#496) reads the deployed value before deciding to write, so+ // it must only PATCH when the spec's description actually differs.+ if (e === 'savedqueryvisualization') {+ const m = /savedqueryvisualizationid eq ([^\s]+)/.exec(filter);+ return [{ savedqueryvisualizationid: m ? m[1] : 'chart-existing', description: opts.existingChartDescription }];+ }if (e === 'webresource') {if (/_pagemanifest'/.test(filter)) return opts.pageManifest ? [{ webresourceid: opts.manifestId || 'wr-manifest', content: opts.pageManifest }] : [];return opts.existingWebResource ? [{ webresourceid: 'wr-existing' }] : [];@@ -194,8 +200,17 @@ function mockSdk(opts = {}) {// Seed the store to mimic a fetched, deployed artifact so reconcile can read + mutate it.if (!store[`${t}:${id}`]) {if (t === 'form') store[`${t}:${id}`] = seedForm(id, opts.existingFormFields || []);- else if (t === 'view') store[`${t}:${id}`] = { id, columns: (opts.existingViewColumns || []).slice() };+ // `description` is seeded UNCONDITIONALLY (default '') because the real ViewAdapter always+ // emits `description: t.description ?? ''`. A view artifact with no `description` key is a+ // shape production never produces — and the real `updateElement` THROWS PathNotFoundError+ // when its pointer resolves to undefined, whereas this mock's jpSet would happily create the+ // key. Omitting it would let a test pass against an artifact the SDK would have rejected.+ else if (t === 'view') store[`${t}:${id}`] = { id, columns: (opts.existingViewColumns || []).slice(), description: opts.existingViewDescription !== undefined ? opts.existingViewDescription : '' };else if (t === 'app') store[`${t}:${id}`] = { id, siteMap: opts.existingSitemap ? JSON.parse(JSON.stringify(opts.existingSitemap)) : { areas: [] } };+ // The chart description reconcile reads through fetchArtifact/getArtifact rather than+ // queryRecords, because a plain query returns the PUBLISHED row while the PATCH writes the+ // unpublished one (measured live). Seed `description` for the same reason as the view.+ else if (t === 'chart') store[`${t}:${id}`] = { id, description: opts.existingChartDescription !== undefined ? opts.existingChartDescription : '' };else store[`${t}:${id}`] = { id };}return store[`${t}:${id}`];@@ -254,7 +269,32 @@ function mockSdk(opts = {}) {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));+ // The real SDK MERGES when the current value and the patch are BOTH plain objects, and+ // replaces otherwise: `Xu(o) && Xu(i) ? {...o, ...i} : i`.+ // Measured against the vendored bundle: updateElement('/…/cells/0/control', {isReadOnly:true})+ // returns {"fieldName":"aaa","id":"…","isReadOnly":true} — the identity survives.+ // The mock used to REPLACE unconditionally, which is strictly more destructive than production:+ // a partial control patch would have looked like it wiped fieldName here while working fine on+ // a real org, so a test written against the old mock measured the wrong thing.+ // Arrays are NOT plain objects, so '/columns' and '/siteMap' still replace wholesale.+ const cur = jpGet(art, ptr);+ const mergeable = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);+ jpSet(art, ptr, mergeable(cur) && mergeable(patch) ? Object.assign({}, cur, clone(patch)) : clone(patch));+ return clone(art);+ },+ moveElement: async (t, id, fromPtr, toPtr, o) => { await Promise.resolve();+ calls.push({ name: 'moveElement', args: [t, id, fromPtr, toPtr, o] });+ const art = store[`${t}:${id}`] || (store[`${t}:${id}`] = { id });+ const el = jpGet(art, fromPtr);+ const target = jpGet(art, toPtr);+ if (el === undefined || !Array.isArray(target)) return clone(art);+ // Mirrors the bundle's order exactly — resolve the target array, REMOVE the source, THEN+ // splice. So when both live in the same array the index is interpreted against the+ // POST-removal array. Verified against the real bundle: moving index 0 to index 1 in+ // [aaa,bbb,ccc,ddd] yields [bbb,aaa,ccc,ddd].+ jpRemove(art, fromPtr);+ const idx = (o && o.index !== undefined) ? o.index : target.length;+ target.splice(Math.max(0, Math.min(idx, target.length)), 0, el);return clone(art);},removeElement: async (t, id, ptr) => { await Promise.resolve();@@ -266,7 +306,20 @@ function mockSdk(opts = {}) {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, 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] }); return { type: t, id, shipped: true, publish: { kind: 'verified' } }; },+ publishArtifact: async (t, id) => {+ calls.push({ name: 'publishArtifact', args: [t, id] });+ // The REAL publishArtifact goes readRaw -> readLocal, which THROWS ArtifactNotFoundError for an+ // artifact that is not workspace-resident — it does NOT lazily fetch. `findArtifact` does not+ // populate the workspace, so publishing a merely-discovered artifact is a hard failure that+ // escapes publishArtifact and halts the phase. A recorder that ignores the store cannot model+ // that, and hid exactly this bug once already.+ if (!store[`${t}:${id}`]) {+ const err = new Error(`Artifact ${t}/${id} not found in workspace`);+ err.name = 'ArtifactNotFoundError';+ throw err;+ }+ 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: [] }; },@@ -982,6 +1035,33 @@ test('dashboards: chart + list tiles resolve the created view/visualization ids'assert.ok(find(calls, 'addSolutionComponent').some((c) => c.args[0].componentType === 60));});+// Descriptions must survive the BUILD, not just the def builder. A def-builder unit test cannot see+// a phase that constructs its own createArtifact payload inline and forgets to forward the field —+// which is exactly what both of these did before they were wired.+test('descriptions: a form and a dashboard are CREATED with the authored description', async () => {+ const spec = makeSpec();+ spec.forms[0].description = 'Primary intake form for support agents.';+ spec.dashboards = [{ name: 'Ops', description: 'At-a-glance queue health.', tiles: [{ type: 'list', view: 'Active Tickets', name: 'Recent' }] }];+ const { sdk, calls } = mockSdk();+ await runSdkBuild(spec, { sdk, apply: true });+ const form = find(calls, 'createArtifact').find((c) => c.args[0] === 'form');+ assert.strictEqual(form.args[1].description, 'Primary intake form for support agents.');+ const dash = find(calls, 'createArtifact').find((c) => c.args[0] === 'dashboard');+ assert.strictEqual(dash.args[1].description, 'At-a-glance queue health.');+});++test('descriptions: a form and a dashboard with none OMIT the key (a rebuild must never blank one)', async () => {+ // Sending `description: ''` would erase whatever a maker typed in the UI on the next rebuild.+ const spec = makeSpec();+ spec.dashboards = [{ name: 'Ops', tiles: [{ type: 'list', view: 'Active Tickets', name: 'Recent' }] }];+ const { sdk, calls } = mockSdk();+ await runSdkBuild(spec, { sdk, apply: true });+ const form = find(calls, 'createArtifact').find((c) => c.args[0] === 'form');+ assert.ok(!('description' in form.args[1]), 'form payload omits description');+ const dash = find(calls, 'createArtifact').find((c) => c.args[0] === 'dashboard');+ assert.ok(!('description' in dash.args[1]), 'dashboard payload omits description');+});+test('dashboards: an existing dashboard is reused (no duplicate) and reported in result.created', async () => {const spec = makeSpec();spec.dashboards = [{ name: 'Ops', tiles: [{ type: 'list', view: 'Active Tickets', name: 'Recent' }] }];@@ -1458,6 +1538,441 @@ test('form reconcile: an AUTO layout is additive — a deployed field not in theassert.strictEqual(find(calls, 'removeElement').length, 0, 'auto layout never removes fields');});+// ---------------------------------------------------------------------------+// Per-field control options on a DEPLOYED form (ADO 6648516 / 6651241 / 6651439 / 6651696).+//+// These live here rather than in form-field-options.test.js because the compile-level tests cannot+// see this code path: reconcileForm builds its own updateElement/moveElement payloads inline, so a+// def-builder assertion would pass while the engine wrote nothing. Same gap that hid the dashboard+// and form description phases until build-level tests were added.+// ---------------------------------------------------------------------------++test('form reconcile: readOnly is applied to an EXISTING field via updateElement on the CONTROL', async () => {+ const spec = makeSpec();+ spec.forms = [{ entity: 'new_customer', name: 'Customer', fieldOptions: { new_tier: { readOnly: true } } }];+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormFields: ['new_name', 'new_tier'] });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });+ const patch = find(calls, 'updateElement').find((c) => /\/control$/.test(String(c.args[2])));+ assert.ok(patch, `no control patch issued; updateElement pointers: ${find(calls, 'updateElement').map((c) => c.args[2]).join(', ')}`);+ assert.deepStrictEqual(patch.args[3], { isReadOnly: true });+ // Row 1 is new_tier in the seeded form — proves the RIGHT field was targeted, not just any.+ assert.strictEqual(patch.args[2], '/tabs/0/columns/0/sections/0/rows/1/cells/0/control');+});++test('form reconcile: hidden is applied to an EXISTING field via updateElement on the CELL', async () => {+ const spec = makeSpec();+ spec.forms = [{ entity: 'new_customer', name: 'Customer', fieldOptions: { new_tier: { hidden: true } } }];+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormFields: ['new_name', 'new_tier'] });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });+ const patch = find(calls, 'updateElement').find((c) => /\/cells\/\d+$/.test(String(c.args[2])));+ assert.ok(patch, 'no cell patch issued');+ assert.deepStrictEqual(patch.args[3], { visible: false });+ assert.strictEqual(patch.args[2], '/tabs/0/columns/0/sections/0/rows/1/cells/0');+});++test('form reconcile: a partial control patch PRESERVES fieldName (updateElement merges, it does not replace)', async () => {+ const spec = makeSpec();+ spec.forms = [{ entity: 'new_customer', name: 'Customer', fieldOptions: { new_tier: { readOnly: true } } }];+ const { sdk } = mockSdk({ artifactsExist: true, existingFormFields: ['new_name', 'new_tier'] });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });+ // Read the mutated artifact back: if the patch had REPLACED the control, fieldName would be gone+ // and the field would silently vanish from the form on the next push.+ const form = await sdk.getArtifact('form', 'form-existing');+ const control = form.tabs[0].columns[0].sections[0].rows[1].cells[0].control;+ assert.strictEqual(control.fieldName, 'new_tier', 'the control lost its binding');+ assert.strictEqual(control.isReadOnly, true);+});++test('form reconcile: no control/cell patch is issued when the spec asserts neither flag', async () => {+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormFields: ['new_name', 'new_tier'] });+ await runSdkBuild(makeSpec(), { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });+ const patches = find(calls, 'updateElement').filter((c) => /\/(control|cells\/\d+)$/.test(String(c.args[2])));+ assert.deepStrictEqual(patches.map((c) => c.args[2]), [],+ 'an ordinary rebuild must not rewrite control attributes — that would clobber maker-applied locks/hides');+});++test('form reconcile: an anchored field is MOVED after its anchor, with the index compensated for same-array removal', async () => {+ const spec = makeSpec();+ spec.forms = [{ entity: 'new_customer', name: 'Customer', fieldOptions: { new_name: { after: 'new_tier' } } }];+ // Seeded order: new_name (row 0), new_tier (row 1). Moving new_name after new_tier.+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormFields: ['new_name', 'new_tier'] });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });+ const move = find(calls, 'moveElement')[0];+ assert.ok(move, 'no moveElement issued');+ assert.strictEqual(move.args[2], '/tabs/0/columns/0/sections/0/rows/0', 'moves the whole ROW (the cell is alone in it)');+ assert.strictEqual(move.args[3], '/tabs/0/columns/0/sections/0/rows');+ // Anchor is at row 1, so the naive target is 2; the source sits BEFORE it in the same array and+ // moveElement removes before splicing, so the correct index is 1. Verified against the real bundle.+ assert.deepStrictEqual(move.args[4], { index: 1 });+ const form = await sdk.getArtifact('form', 'form-existing');+ const order = form.tabs[0].columns[0].sections[0].rows.map((r) => r.cells[0].control.fieldName);+ assert.deepStrictEqual(order, ['new_tier', 'new_name'], 'the deployed form ends up in the authored order');+});++test('form reconcile: repositioning is idempotent — a second build issues no further move', async () => {+ const spec = makeSpec();+ spec.forms = [{ entity: 'new_customer', name: 'Customer', fieldOptions: { new_name: { after: 'new_tier' } } }];+ // Already in the anchored order, so the reconcile must recognise it and do nothing.+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormFields: ['new_tier', 'new_name'] });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });+ assert.strictEqual(find(calls, 'moveElement').length, 0, 'a converged form was reshuffled anyway');+});++test('form reconcile: a field SHARING a row is moved as a CELL, with the same index compensation', async () => {+ // The seeded form puts every field in its own row, so build a 2-cell row by hand to exercise the+ // other branch. Without this, the cell-move path (and its off-by-one guard) is never executed.+ const spec = makeSpec();+ spec.forms = [{ entity: 'new_customer', name: 'Customer', fieldOptions: { new_name: { after: 'new_tier' } } }];+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormFields: [] });+ // Pre-seed the deployed form with one row holding [new_name, new_tier, new_other].+ await sdk.fetchArtifact('form', 'form-existing');+ const seeded = await sdk.getArtifact('form', 'form-existing');+ seeded.tabs[0].columns[0].sections[0].rows = [{ cells: [+ { control: { fieldName: 'new_name' } },+ { control: { fieldName: 'new_tier' } },+ { control: { fieldName: 'new_other' } },+ ] }];+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });+ const move = find(calls, 'moveElement')[0];+ assert.ok(move, 'no moveElement issued for a shared-row field');+ assert.strictEqual(move.args[2], '/tabs/0/columns/0/sections/0/rows/0/cells/0', 'moves the CELL, not the row');+ assert.strictEqual(move.args[3], '/tabs/0/columns/0/sections/0/rows/0/cells');+ // Anchor new_tier is at cell index 1, so the naive target is 2; the source is earlier in the SAME+ // array and moveElement removes before splicing, so the correct index is 1.+ assert.deepStrictEqual(move.args[4], { index: 1 });+ const form = await sdk.getArtifact('form', 'form-existing');+ const order = form.tabs[0].columns[0].sections[0].rows[0].cells.map((c) => c.control.fieldName);+ assert.deepStrictEqual(order, ['new_tier', 'new_name', 'new_other'], 'cell landed one slot too far right');+});++test('form reconcile: a lone-row field anchored to a NON-last cell uses the CELL move, so it converges', async () => {+ // The row move inserts a row after the ANCHOR'S ROW, i.e. after the last cell of that row. That is+ // flat-adjacent only when the anchor IS the last cell. With a left-column anchor the row move+ // overshoots, the flat check never reports converged, and a no-op move is re-issued forever.+ const spec = makeSpec();+ spec.forms = [{ entity: 'new_customer', name: 'Customer', fieldOptions: { new_late: { after: 'new_tier' } } }];+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormFields: [] });+ await sdk.fetchArtifact('form', 'form-existing');+ const seeded = await sdk.getArtifact('form', 'form-existing');+ // A 2-column shape: new_tier is the LEFT cell of row 0; new_late is alone in its own row.+ seeded.tabs[0].columns[0].sections[0].rows = [+ { cells: [{ control: { fieldName: 'new_tier' } }, { control: { fieldName: 'new_name' } }] },+ { cells: [{ control: { fieldName: 'new_late' } }] },+ ];+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });++ const move = find(calls, 'moveElement')[0];+ assert.ok(move, 'no moveElement issued');+ assert.strictEqual(move.args[2], '/tabs/0/columns/0/sections/0/rows/1/cells/0', 'must move the CELL, not the row');+ assert.strictEqual(move.args[3], '/tabs/0/columns/0/sections/0/rows/0/cells');+ assert.deepStrictEqual(move.args[4], { index: 1 }, 'lands directly after the anchor cell');++ const form = await sdk.getArtifact('form', 'form-existing');+ const rows = form.tabs[0].columns[0].sections[0].rows;+ assert.deepStrictEqual(rows.map((r) => r.cells.map((c) => c.control.fieldName)), [['new_tier', 'new_late', 'new_name']],+ 'the emptied source row must also be removed, or a blank row accumulates per anchored field');+});++test('form reconcile: a lone-row field anchored to a LAST cell still uses the cheaper ROW move', async () => {+ const spec = makeSpec();+ spec.forms = [{ entity: 'new_customer', name: 'Customer', fieldOptions: { new_late: { after: 'new_tier' } } }];+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormFields: [] });+ await sdk.fetchArtifact('form', 'form-existing');+ const seeded = await sdk.getArtifact('form', 'form-existing');+ // new_tier is now the LAST cell of its row, so inserting the row after it IS flat-adjacent.+ seeded.tabs[0].columns[0].sections[0].rows = [+ { cells: [{ control: { fieldName: 'new_name' } }, { control: { fieldName: 'new_tier' } }] },+ { cells: [{ control: { fieldName: 'new_other' } }] },+ { cells: [{ control: { fieldName: 'new_late' } }] },+ ];+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });+ const move = find(calls, 'moveElement')[0];+ assert.ok(move, 'no moveElement issued');+ assert.strictEqual(move.args[2], '/tabs/0/columns/0/sections/0/rows/2', 'the whole ROW moves');+ assert.strictEqual(move.args[3], '/tabs/0/columns/0/sections/0/rows');+ // Pin the INDEX and the RESULT too. Asserting only that the call happened leaves the row-branch+ // index arithmetic unpinned in this orientation (source AFTER anchor, so the same-array+ // compensation must NOT fire): inverting the compensation would emit index 0, put new_late first,+ // and never converge — and a call-only assertion would still pass.+ assert.deepStrictEqual(move.args[4], { index: 1 });+ const form = await sdk.getArtifact('form', 'form-existing');+ assert.deepStrictEqual(+ form.tabs[0].columns[0].sections[0].rows.map((r) => r.cells.map((c) => c.control.fieldName)),+ [['new_name', 'new_tier'], ['new_late'], ['new_other']],+ 'the moved row must land directly after the anchor row'+ );+});++test('form reconcile: a second build over an anchored 2-column form issues NO move (it converges)', async () => {+ const spec = makeSpec();+ spec.forms = [{ entity: 'new_customer', name: 'Customer', fieldOptions: { new_late: { after: 'new_tier' } } }];+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormFields: [] });+ await sdk.fetchArtifact('form', 'form-existing');+ const seeded = await sdk.getArtifact('form', 'form-existing');+ // Already correct: new_late is flat-adjacent after new_tier, across a row boundary.+ seeded.tabs[0].columns[0].sections[0].rows = [+ { cells: [{ control: { fieldName: 'new_name' } }, { control: { fieldName: 'new_tier' } }] },+ { cells: [{ control: { fieldName: 'new_late' } }] },+ ];+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });+ assert.strictEqual(find(calls, 'moveElement').length, 0, 'a converged 2-column form was shuffled anyway');+});++// ---------------------------------------------------------------------------+// #496 — an EXISTING view/chart never got its description reconciled.+//+// The reported case is the platform's auto-generated "Active <Plural>" view: it already exists when+// the views phase runs, so the build reconciles onto it and the authored description was only ever+// written on CREATE. Charts are the same class, via a different mechanic (see the test comments).+// ---------------------------------------------------------------------------++test('view reconcile: an authored description is written to an EXISTING view', async () => {+ const spec = makeSpec();+ spec.views = [{ entity: 'new_ticket', name: 'Active Tickets', description: 'Open work, newest first.', columns: ['new_subject'] }];+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingViewColumns: [{ name: 'new_subject', width: 100, order: 0 }] });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'views'] });+ const patch = find(calls, 'updateElement').find((c) => c.args[0] === 'view' && c.args[2] === '/description');+ assert.ok(patch, `no description write; updateElement pointers: ${find(calls, 'updateElement').map((c) => c.args[2]).join(', ')}`);+ assert.strictEqual(patch.args[3], 'Open work, newest first.');+ // ORDER is the whole mechanic: the local artifact mutation reaches Dataverse ONLY via the push, so+ // a description write placed after `pushArtifact` would be a no-op that still looks correct.+ // Asserting "a push happened" does not catch that — assert the sequence.+ const push = find(calls, 'pushArtifact').find((c) => c.args[0] === 'view');+ assert.ok(push, 'the view must still be pushed');+ assert.ok(calls.indexOf(patch) < calls.indexOf(push),+ 'the description must be written BEFORE the push, or it never reaches Dataverse');+});++test('view reconcile: an UNSET description never blanks the deployed one', async () => {+ const spec = makeSpec();+ // viewDef emits `description: v.description || ''`, so an unset description is '' — writing that+ // would wipe text a maker typed in the UI. The deployed view MUST carry a description here, or the+ // guard is untested: with both sides empty the write is skipped either way.+ spec.views = [{ entity: 'new_ticket', name: 'Active Tickets', columns: ['new_subject'] }];+ const { sdk, calls } = mockSdk({+ artifactsExist: true,+ existingViewColumns: [{ name: 'new_subject', width: 100, order: 0 }],+ existingViewDescription: 'Text a maker typed in the UI.',+ });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'views'] });+ assert.strictEqual(find(calls, 'updateElement').filter((c) => c.args[2] === '/description').length, 0,+ 'an unset description must not be written at all');+ const view = await sdk.getArtifact('view', 'view-existing');+ assert.strictEqual(view.description, 'Text a maker typed in the UI.', 'the deployed description was blanked');+});++test('view reconcile: a description that already matches is not rewritten', async () => {+ const spec = makeSpec();+ spec.views = [{ entity: 'new_ticket', name: 'Active Tickets', description: 'Already correct.', columns: ['new_subject'] }];+ const { sdk, calls } = mockSdk({+ artifactsExist: true,+ existingViewColumns: [{ name: 'new_subject', width: 100, order: 0 }],+ existingViewDescription: 'Already correct.',+ });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'views'] });+ assert.strictEqual(find(calls, 'updateElement').filter((c) => c.args[2] === '/description').length, 0,+ 'an ordinary rebuild must issue no extra write');+});++test('chart reconcile: an authored description is PATCHed on an existing chart, without pushing the chart', async () => {+ const spec = makeSpec();+ spec.charts = [{ entity: 'new_ticket', name: 'By Priority', chartType: 'Pie', groupBy: 'new_priority', measure: 'count', description: 'Ticket mix by priority.' }];+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingChartDescription: 'stale text' });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'charts'] });+ const upd = find(calls, 'updateRecord').find((c) => c.args[0] === 'savedqueryvisualization');+ assert.ok(upd, `no chart description PATCH; updateRecord targets: ${find(calls, 'updateRecord').map((c) => c.args[0]).join(', ')}`);+ assert.deepStrictEqual(upd.args[2], { description: 'Ticket mix by priority.' });+ // Pushing an existing chart would regenerate datadescription/presentationdescription from the+ // deserialized model — a serialize round trip this phase has never subjected maker charts to.+ assert.ok(!find(calls, 'pushArtifact').some((c) => c.args[0] === 'chart'), 'an existing chart must NOT be pushed');+});++test('chart reconcile: an unset or already-matching description issues no write', async () => {+ const unset = makeSpec();+ unset.charts = [{ entity: 'new_ticket', name: 'By Priority', chartType: 'Pie', groupBy: 'new_priority', measure: 'count' }];+ let h = mockSdk({ artifactsExist: true, existingChartDescription: 'maker text' });+ await runSdkBuild(unset, { sdk: h.sdk, apply: true, phases: ['solution', 'data-model', 'charts'] });+ assert.strictEqual(find(h.calls, 'updateRecord').filter((c) => c.args[0] === 'savedqueryvisualization').length, 0,+ 'an unset description must not blank the deployed one');++ const same = makeSpec();+ same.charts = [{ entity: 'new_ticket', name: 'By Priority', chartType: 'Pie', groupBy: 'new_priority', measure: 'count', description: 'maker text' }];+ h = mockSdk({ artifactsExist: true, existingChartDescription: 'maker text' });+ await runSdkBuild(same, { sdk: h.sdk, apply: true, phases: ['solution', 'data-model', 'charts'] });+ assert.strictEqual(find(h.calls, 'updateRecord').filter((c) => c.args[0] === 'savedqueryvisualization').length, 0,+ 'a matching description must not be rewritten');+});++test('view reconcile: a description with surrounding whitespace converges in ONE build, not two', async () => {+ // validateDescription only rejects a FULLY blank description, so " text " is legal. The reconcile+ // compares and writes `.trim()`, so if the CREATE path stored the untrimmed value the two would+ // disagree and every first rebuild would issue one spurious write before settling. Both paths trim.+ const spec = makeSpec();+ spec.views = [{ entity: 'new_ticket', name: 'Active Tickets', description: ' Open work, newest first. ', columns: ['new_subject'] }];+ const { sdk, calls } = mockSdk({+ artifactsExist: true,+ existingViewColumns: [{ name: 'new_subject', width: 100, order: 0 }],+ // What the CREATE path would have stored for that same spec value.+ existingViewDescription: 'Open work, newest first.',+ });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'views'] });+ assert.strictEqual(find(calls, 'updateElement').filter((c) => c.args[2] === '/description').length, 0,+ 'an untrimmed spec value must match what create stored, or every rebuild rewrites it');+});++test('viewDef/chartDef trim the description they store, matching what the reconcile compares against', () => {+ const spec = makeSpec();+ assert.strictEqual(viewDef(spec, { entity: 'new_ticket', name: 'V', description: ' padded ', columns: ['new_subject'] }).description, 'padded');+ assert.strictEqual(chartDef(spec, { entity: 'new_ticket', name: 'C', chartType: 'Pie', groupBy: 'new_priority', measure: 'count', description: ' padded ' }).description, 'padded');+ // An absent description is still '' (not undefined) — the def shape the SDK requires.+ assert.strictEqual(viewDef(spec, { entity: 'new_ticket', name: 'V', columns: ['new_subject'] }).description, '');+});++test('chart reconcile: the CURRENT description is read from the UNPUBLISHED layer, not a plain query', async () => {+ // Measured on a live org: a chart description PATCH lands on the UNPUBLISHED layer, while a plain+ // or filtered GET returns the PUBLISHED row:+ // PATCH description -> plain GET: old value | RetrieveUnpublished(): new value+ // Reading the published value would compare across layers, so the guard would see a difference on+ // every rebuild and re-issue the identical PATCH forever. `chartApi.get` (behind fetchArtifact)+ // uses RetrieveUnpublished, which is the layer the PATCH writes to.+ const spec = makeSpec();+ spec.charts = [{ entity: 'new_ticket', name: 'By Priority', chartType: 'Pie', groupBy: 'new_priority', measure: 'count', description: 'Ticket mix by priority.' }];+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingChartDescription: 'Ticket mix by priority.' });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'charts'] });+ assert.ok(find(calls, 'fetchArtifact').some((c) => c.args[0] === 'chart'),+ 'the current description must be read through the artifact surface (RetrieveUnpublished)');+ assert.strictEqual(find(calls, 'queryRecords').filter((c) => c.args[0] === 'savedqueryvisualization').length, 0,+ 'a plain query reads the PUBLISHED row and would never converge');+ assert.strictEqual(find(calls, 'updateRecord').filter((c) => c.args[0] === 'savedqueryvisualization').length, 0,+ 'an already-matching description must not be rewritten');+ assert.ok(!find(calls, 'pushArtifact').some((c) => c.args[0] === 'chart'), 'reading must not push the chart');+});++test('publish: an EXISTING chart with no description to reconcile is never published (it is not in the workspace)', async () => {+ // publishArtifact requires the artifact to be workspace-resident — readRaw -> readLocal THROWS+ // ArtifactNotFoundError rather than lazily fetching — and `findArtifact` does not populate the+ // workspace. Handing publish a merely-discovered id therefore halts the phase. Nothing was+ // changed on this chart, so there is nothing to publish either: correctness and semantics agree.+ const spec = makeSpec();+ spec.forms = [];+ spec.views = [];+ spec.charts = [{ entity: 'new_ticket', name: 'By Priority', chartType: 'Pie', groupBy: 'new_priority', measure: 'count' }];+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingChartDescription: 'maker text' });+ const res = await runSdkBuild(spec, { sdk, apply: true, publish: true, phases: ['solution', 'data-model', 'charts', 'publish'] });+ assert.strictEqual(res.ok, true, `the build must not halt: ${JSON.stringify(res.errors)}`);+ assert.ok(!find(calls, 'publishArtifact').some((c) => c.args[0] === 'chart'),+ 'an untouched, unfetched chart must not be handed to publish');+});++test('publish: an existing chart whose description WAS reconciled is published (the write needs it)', async () => {+ // The PATCH lands on the unpublished layer, so the entity must be published for the new text to be+ // served — and the reconcile fetched the chart, so it IS workspace-resident and publishable.+ const spec = makeSpec();+ spec.forms = [];+ spec.views = [];+ spec.charts = [{ entity: 'new_ticket', name: 'By Priority', chartType: 'Pie', groupBy: 'new_priority', measure: 'count', description: 'New text.' }];+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingChartDescription: 'stale text' });+ const res = await runSdkBuild(spec, { sdk, apply: true, publish: true, phases: ['solution', 'data-model', 'charts', 'publish'] });+ assert.strictEqual(res.ok, true, JSON.stringify(res.errors));+ assert.ok(find(calls, 'publishArtifact').some((c) => c.args[0] === 'chart'),+ 'a reconciled description must be published or it stays on the unpublished layer');+});++test('publish: an entity carrying ONLY charts is still published', async () => {+ // perEntity was built from forms and views only, so a chart-only entity was never published by any+ // path — leaving a reconciled description written to the unpublished layer and invisible.+ const spec = makeSpec();+ spec.forms = [];+ spec.views = [];+ spec.charts = [{ entity: 'new_ticket', name: 'By Priority', chartType: 'Pie', groupBy: 'new_priority', measure: 'count' }];+ const { sdk, calls } = mockSdk();+ await runSdkBuild(spec, { sdk, apply: true, publish: true, phases: ['solution', 'data-model', 'charts', 'publish'] });+ assert.ok(find(calls, 'publishArtifact').some((c) => c.args[0] === 'chart'),+ `a chart-only entity was not published; published: ${JSON.stringify(find(calls, 'publishArtifact').map((c) => c.args[0]))}`);+});++test('chart reconcile: a FAILED description write is warned about and reflected in the skip line', async () => {+ const spec = makeSpec();+ spec.charts = [{ entity: 'new_ticket', name: 'By Priority', chartType: 'Pie', groupBy: 'new_priority', measure: 'count', description: 'Ticket mix by priority.' }];+ const { sdk } = mockSdk({ artifactsExist: true, existingChartDescription: 'stale text' });+ const base = sdk.updateRecord;+ sdk.updateRecord = async (e, id, data) => {+ if (e === 'savedqueryvisualization') throw new Error('403 write rejected');+ return base(e, id, data);+ };+ const warnings = [];+ const events = [];+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'charts'], warn: (m) => warnings.push(m), emit: (e) => events.push(e) });+ // Silence here would be the worst outcome: the skip line says "chart edits aren't applied on+ // rebuild", so an operator whose write was rejected would read that as expected and never look.+ assert.ok(warnings.some((w) => /By Priority/.test(w) && /description/.test(w)),+ `a rejected description write must warn; warnings: ${JSON.stringify(warnings)}`);+ // The title claims the skip line reflects it, so assert that too rather than leaving `events`+ // collected and unchecked. A REJECTED write must NOT claim it reconciled anything.+ const skip = events.find((e) => e.status === 'skip' && /By Priority/.test(e.label || ''));+ assert.ok(skip, 'the chart still emits a skip event');+ assert.doesNotMatch(skip.label, /description reconciled/,+ 'a failed write must not report a reconciled description');+});++test('chart reconcile: the skip line distinguishes "description reconciled" from "nothing to do"', async () => {+ const mk = async (existing, description) => {+ const spec = makeSpec();+ spec.charts = [{ entity: 'new_ticket', name: 'By Priority', chartType: 'Pie', groupBy: 'new_priority', measure: 'count', ...(description ? { description } : {}) }];+ const { sdk } = mockSdk({ artifactsExist: true, existingChartDescription: existing });+ const events = [];+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'charts'], emit: (e) => events.push(e) });+ return (events.find((e) => e.status === 'skip' && /By Priority/.test(e.label || '')) || {}).label || '';+ };+ assert.match(await mk('stale text', 'Ticket mix by priority.'), /description reconciled/);+ assert.doesNotMatch(await mk('already right', 'already right'), /description reconciled/);+ assert.doesNotMatch(await mk('maker text', null), /description reconciled/);+});++test('chart reconcile: an EXISTING chart is still added to the solution', async () => {+ // The branch used to return without adding it, so a chart the spec claims was absent from the+ // exported solution — and invisible to teardown. It is no longer a pure skip: it now mutates the+ // chart, so it must also own it.+ const spec = makeSpec();+ spec.charts = [{ entity: 'new_ticket', name: 'By Priority', chartType: 'Pie', groupBy: 'new_priority', measure: 'count' }];+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingChartDescription: 'x' });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'charts'] });+ assert.ok(find(calls, 'addSolutionComponent').some((c) => c.args[0] && c.args[0].componentType === 59),+ `existing chart not added to the solution; components: ${JSON.stringify(find(calls, 'addSolutionComponent').map((c) => c.args[0].componentType))} (chart is 59)`);+});++test('form reconcile: an explicit layout with prune:false keeps fields it does not list', async () => {+ const spec = makeSpec();+ spec.forms = [{ entity: 'new_customer', name: 'Customer', layout: 'explicit', prune: false,+ tabs: [{ label: 'General', sections: [{ label: 'Details', columns: 1, fields: ['new_name'] }] }] }];+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormFields: ['new_name', 'new_tier', 'new_manual'] });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });+ assert.strictEqual(find(calls, 'removeElement').length, 0,+ 'prune:false must let an author restyle/reorder a subset without re-declaring the whole form');+});++test('form reconcile: an explicit layout still prunes BY DEFAULT (prune:false is opt-in, not the new default)', async () => {+ const spec = makeSpec();+ spec.forms = [{ entity: 'new_customer', name: 'Customer', layout: 'explicit',+ tabs: [{ label: 'General', sections: [{ label: 'Details', columns: 1, fields: ['new_name'] }] }] }];+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormFields: ['new_name', 'new_tier', 'new_manual'] });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });+ assert.ok(find(calls, 'removeElement').length > 0, 'default explicit-layout pruning regressed');+});++test('form build: a BigInt column is never added to a form by the auto layout', async () => {+ const spec = makeSpec();+ spec.entities[0].columns.push({ schemaName: 'new_tracking', displayName: 'Tracking', type: 'BigInt' });+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormFields: ['new_name'] });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });+ const added = find(calls, 'addElement')+ .flatMap((c) => (c.args[3] && c.args[3].cells) || [])+ .map((cell) => cell.control && cell.control.fieldName);+ assert.ok(!added.includes('new_tracking'),+ `BigInt reached the form: ${added.filter(Boolean).join(', ')} — UCI cannot render it ("Error loading control")`);+ assert.ok(added.includes('new_tier'), 'the BigInt skip must not suppress ordinary columns');+});+test('form reconcile: the entity primary field is never pruned, even when an explicit layout omits it', async () => {const spec = makeSpec();// Explicit layout omits the primary (new_name) — authors often rely on the header primary field.@@ -1874,6 +2389,192 @@ test('ai-features phase: summaries.default=off skips all row-summary calls', asyassert.strictEqual(find(calls, 'configureRowSummary').length, 0, 'no row summaries when default is off');});+// `default` is the app-level DEFAULT; `tables[x]` is a per-table OVERRIDE that beats it. The build+// used to short-circuit on `default === 'off'` BEFORE calling `selectSummaryTables`, which made that+// helper's own `override.enabled === true` branch unreachable and silently dropped a summary the+// author had explicitly asked for. Live-found: a build reported success with `summaries: {}`.+test('ai-features phase: summaries.default=off still honours an explicit per-table opt-in', async () => {+ const spec = makeSpec({ ai: { summaries: { default: 'off', tables: { new_ticket: { enabled: true, instruction: 'Summarise the ticket.' } } } } });+ const { sdk, calls } = mockSdk();+ const result = await runSdkBuild(spec, { sdk, apply: true, phases: ['ai-features'] });+ const summaryCalls = find(calls, 'configureRowSummary');+ assert.strictEqual(summaryCalls.length, 1, 'exactly the opted-in table gets a summary');+ assert.strictEqual(summaryCalls[0].args[0].entityLogicalName, 'new_ticket', 'and it is the right table');+ assert.ok(result.created.ai.summaries.new_ticket, 'the opted-in summary is reported on the result');+});++// Row summaries are AI-Builder LICENSED, gated independently of the `EnableFormInsights` org setting:+// an environment can report the feature on and still answer the publish with+// HTTP 403 ... {"error":{"code":"ModelNotSupported","message":"This scenario is not supported in this environment."}}+// Halting there abandons a build that already created everything else, for a reason no spec change+// can fix — so it degrades like business rules and `app.newLook` do. Live-observed; without this the+// opt-in fix above would turn a previously-succeeding build into a failing one on unlicensed orgs.+const modelNotSupported = () => {+ const err = new Error('HTTP 403 from https://example.crm.dynamics.com/api/data/v9.0/AIModelPublish: {"operationStatus":"Error","error":{"type":"Error","code":"ModelNotSupported","message":"This scenario is not supported in this environment."}}');+ err.statusCode = 403;+ return err;+};++test('ai-features phase: an unlicensed row-summary environment SKIPS the summary and keeps building', async () => {+ const spec = makeSpec({ ai: { summaries: { default: 'off', tables: { new_ticket: { enabled: true } } } } });+ const { sdk } = mockSdk();+ sdk.configureRowSummary = async () => { throw modelNotSupported(); };+ const warnings = [];+ const result = await runSdkBuild(spec, { sdk, apply: true, phases: ['ai-features'], warn: (m) => warnings.push(m) });+ assert.ok(result.ok, 'the build must not fail for an environment gate');+ assert.deepStrictEqual(result.skipped.aiSummaries, ['new_ticket'], 'the skip is recorded, not silent');+ assert.ok(!result.created.ai.summaries.new_ticket, 'nothing is reported as created');+ assert.ok(warnings.some((w) => /row summaries were NOT created/i.test(w)), `expected a specific warning; got ${JSON.stringify(warnings)}`);+});++test('ai-features phase: the unlicensed warning is emitted ONCE even for several tables', async () => {+ const spec = makeSpec({ ai: { summaries: { default: 'off', tables: { new_ticket: { enabled: true }, new_customer: { enabled: true } } } } });+ const { sdk } = mockSdk();+ sdk.configureRowSummary = async () => { throw modelNotSupported(); };+ const warnings = [];+ const result = await runSdkBuild(spec, { sdk, apply: true, phases: ['ai-features'], warn: (m) => warnings.push(m) });+ assert.strictEqual(result.skipped.aiSummaries.length, 2, 'both tables recorded as skipped');+ assert.strictEqual(warnings.filter((w) => /row summaries were NOT created/i.test(w)).length, 1, 'but only one warning');+});++test('ai-features phase: an UNRELATED row-summary failure still halts — the skip is narrow', async () => {+ const spec = makeSpec({ ai: { summaries: { default: 'off', tables: { new_ticket: { enabled: true } } } } });+ const { sdk } = mockSdk();+ // A plain privilege failure is also a 403; it must NOT be swallowed as an environment gate.+ sdk.configureRowSummary = async () => { const e = new Error('HTTP 403 from .../AIModelPublish: principal does not have Create privilege'); e.statusCode = 403; throw e; };+ await assert.rejects(+ () => runSdkBuild(spec, { sdk, apply: true, phases: ['ai-features'], warn: () => {} }),+ /privilege/i,+ 'a non-gate failure must still surface',+ );+});++// `configureRowSummary` CREATES the msdyn_aimodel row and THEN publishes it, so a licence rejection+// at publish leaves the row committed. Skipping without sweeping made the FIRST build pass and every+// rebuild fail with DuplicateRecordKey — strictly worse than failing consistently. Live-observed.+test('ai-features phase: a skipped summary sweeps the orphan msdyn_aimodel row it left behind', async () => {+ const spec = makeSpec({ ai: { summaries: { default: 'off', tables: { new_ticket: { enabled: true } } } } });+ const { sdk, calls } = mockSdk();+ sdk.configureRowSummary = async () => { throw modelNotSupported(); };+ // The mock HONOURS `filter` and `top` on purpose. `msdyn_aimodel` is a shared system table that+ // other features also write, so an unfiltered page-scan would miss the orphan on any real org+ // holding more rows than the cap — and a mock that ignored query options would happily pass a+ // fetch-and-scan implementation that is broken in production. So: many decoy rows, a cap smaller+ // than the decoy count, and the orphan deliberately placed LAST.+ const decoys = Array.from({ length: 60 }, (_, i) => ({ msdyn_aimodelid: `decoy-${i}`, msdyn_name: `unrelated model ${i}` }));+ const table = [...decoys, { msdyn_aimodelid: 'orphan-1', msdyn_name: 'new_ticket row summary' }];+ const queries = [];+ sdk.queryRecords = async (entity, opts = {}) => {+ if (entity !== 'msdyn_aimodel') return [];+ queries.push(opts);+ // Model the server: apply $filter first, then $top — the order Dataverse uses.+ const m = /msdyn_name eq '(.*)'/.exec(opts.filter || '');+ const rows = m ? table.filter((r) => r.msdyn_name === m[1]) : table;+ return rows.slice(0, opts.top || rows.length);+ };+ sdk.deleteRecord = async (entity, id) => { calls.push({ name: 'deleteRecord', args: [entity, id] }); };+ const result = await runSdkBuild(spec, { sdk, apply: true, phases: ['ai-features'], warn: () => {} });+ assert.ok(result.ok, 'still a successful build');+ const deletes = find(calls, 'deleteRecord').filter((c) => c.args[0] === 'msdyn_aimodel');+ assert.deepStrictEqual(deletes.map((d) => d.args[1]), ['orphan-1'], 'sweeps the orphan and only the orphan');+ assert.ok(queries.length && queries[0].filter, 'the sweep MUST filter server-side, not page-scan');+});++test('ai-features phase: DuplicateRecordKey (the orphan from a previous gated run) also skips, not halts', async () => {+ const spec = makeSpec({ ai: { summaries: { default: 'off', tables: { new_ticket: { enabled: true } } } } });+ const { sdk } = mockSdk();+ const warnings = [];+ sdk.configureRowSummary = async () => {+ const e = new Error('HTTP 400 from .../AIModelPublish: {"error":{"code":"DuplicateRecordKey","message":"Cannot insert duplicate key row in object \'dbo.msdyn_AIModelBase\' with unique index \'ndx_Uniquename\'."}}');+ e.statusCode = 400;+ throw e;+ };+ const result = await runSdkBuild(spec, { sdk, apply: true, phases: ['ai-features'], warn: (m) => warnings.push(m) });+ assert.ok(result.ok, 'a rebuild against a gated org must not fail where the first build passed');+ assert.deepStrictEqual(result.skipped.aiSummaries, ['new_ticket']);+ // A leftover row is NOT a licensing problem. Telling the operator their environment is unlicensed+ // sends them to the Admin Center for a condition the build just cleaned up itself.+ assert.ok(warnings.some((w) => /already exists/i.test(w)), `expected a duplicate-specific warning; got ${JSON.stringify(warnings)}`);+ assert.ok(!warnings.some((w) => /does not license/i.test(w)), 'must NOT claim the environment is unlicensed');+});++// The org's language decides whether the platform's `code` reaches us via `message` or only via the+// parsed body on `cause`. A fixture that embeds the code in BOTH cannot tell the two apart, so this+// one puts it ONLY on `cause` — which is what a non-English tenant actually produces.+test('ai-features phase: the gate is recognised from err.cause alone (localized message)', async () => {+ const spec = makeSpec({ ai: { summaries: { default: 'off', tables: { new_ticket: { enabled: true } } } } });+ const { sdk } = mockSdk();+ sdk.configureRowSummary = async () => {+ const e = new Error('Ce scenario n est pas pris en charge dans cet environnement.');+ e.statusCode = 403;+ e.cause = { error: { code: 'ModelNotSupported', message: 'Ce scenario n est pas pris en charge dans cet environnement.' } };+ throw e;+ };+ const result = await runSdkBuild(spec, { sdk, apply: true, phases: ['ai-features'], warn: () => {} });+ assert.ok(result.ok, 'a localized gate error must still be recognised');+ assert.deepStrictEqual(result.skipped.aiSummaries, ['new_ticket']);+});++test('ai-features phase: a failing orphan sweep never turns the skip back into a halt', async () => {+ const spec = makeSpec({ ai: { summaries: { default: 'off', tables: { new_ticket: { enabled: true } } } } });+ const { sdk } = mockSdk();+ sdk.configureRowSummary = async () => { throw modelNotSupported(); };+ sdk.queryRecords = async () => { throw new Error('no read access to msdyn_aimodel'); };+ const result = await runSdkBuild(spec, { sdk, apply: true, phases: ['ai-features'], warn: () => {} });+ assert.ok(result.ok, 'cleanup is best-effort and must stay non-fatal');+ assert.deepStrictEqual(result.skipped.aiSummaries, ['new_ticket']);+});++// Distinct from the case above: there the QUERY fails, so the inner per-row catch is never reached.+// This one finds the row and fails the DELETE, which is the only thing that inner catch guards.+test('ai-features phase: a failing orphan DELETE is also non-fatal', async () => {+ const spec = makeSpec({ ai: { summaries: { default: 'off', tables: { new_ticket: { enabled: true } } } } });+ const { sdk } = mockSdk();+ sdk.configureRowSummary = async () => { throw modelNotSupported(); };+ sdk.queryRecords = async (entity) => (entity === 'msdyn_aimodel' ? [{ msdyn_aimodelid: 'orphan-1' }] : []);+ sdk.deleteRecord = async () => { throw new Error('HTTP 403: no delete privilege on msdyn_aimodel'); };+ const result = await runSdkBuild(spec, { sdk, apply: true, phases: ['ai-features'], warn: () => {} });+ assert.ok(result.ok, 'an undeletable orphan must not fail the build');+ assert.deepStrictEqual(result.skipped.aiSummaries, ['new_ticket']);+});++// A later table failing for an UNRELATED reason throws out of the loop. Without a `finally` the+// orphan already queued by an earlier skipped table is never swept, leaving exactly the duplicate-key+// residue the sweep exists to remove.+test('ai-features phase: an orphan queued before a LATER fatal error is still swept', async () => {+ const spec = makeSpec({ ai: { summaries: { default: 'off', tables: { new_customer: { enabled: true }, new_ticket: { enabled: true } } } } });+ const { sdk, calls } = mockSdk();+ const seen = [];+ sdk.configureRowSummary = async (promptSpec) => {+ seen.push(promptSpec.entityLogicalName);+ // First table hits the environment gate (queues a sweep); the second dies for another reason.+ if (seen.length === 1) throw modelNotSupported();+ throw new Error('HTTP 500 from .../AIModelPublish: internal server error');+ };+ sdk.queryRecords = async (entity) => (entity === 'msdyn_aimodel' ? [{ msdyn_aimodelid: 'orphan-1' }] : []);+ sdk.deleteRecord = async (entity, id) => { calls.push({ name: 'deleteRecord', args: [entity, id] }); };+ await assert.rejects(+ () => runSdkBuild(spec, { sdk, apply: true, phases: ['ai-features'], warn: () => {} }),+ /internal server error/,+ 'the unrelated failure must still surface',+ );+ const deletes = find(calls, 'deleteRecord').filter((c) => c.args[0] === 'msdyn_aimodel');+ assert.strictEqual(deletes.length, 1, 'the queued orphan is swept even though the build then failed');+});++// `tables` keys are documented as case-insensitive, and `selectSummaryTables` honours that when+// choosing what to build. Looking the override back up by exact key selected the table but dropped+// the author's `instruction`/`columns`, silently substituting the generated default prompt.+test('ai-features phase: a differently-cased tables[] key keeps its instruction', async () => {+ const spec = makeSpec({ ai: { summaries: { default: 'off', tables: { NEW_Ticket: { enabled: true, instruction: 'Summarise the ticket in two sentences.' } } } } });+ const { sdk, calls } = mockSdk();+ const result = await runSdkBuild(spec, { sdk, apply: true, phases: ['ai-features'] });+ assert.ok(result.ok);+ const summaryCalls = find(calls, 'configureRowSummary');+ assert.strictEqual(summaryCalls.length, 1, 'the case-insensitive key still selects the table');+ assert.match(String(summaryCalls[0].args[0].instruction || ''), /two sentences/, 'the AUTHORED instruction must reach the SDK, not the generated default');+});+test('ai-features phase: spec without spec.ai is a no-op', async () => {const { sdk, calls } = mockSdk();await runSdkBuild(makeSpec(), { sdk, apply: true, phases: ['ai-features'] });@@ -2066,7 +2767,9 @@ test('ai-features phase: the recovery reason names the path that actually recovesdk.queryRecords = async (logical) => {if (logical === 'appmodule') return [{ appmoduleid: 'app-guid' }];if (logical === 'settingdefinition') return [{ settingdefinitionid: 'def-guid' }];- if (logical === 'appsetting') return [{ value: '1' }];+ // '2' is ENABLED for the form-fill family ('1' is DISABLED, '0' the platform default), so this+ // is what a successful `formFill: true` actually writes.+ if (logical === 'appsetting') return [{ value: '2' }];return [];};const result = await runSdkBuild(spec, { sdk, apply: true, phases: ['app-shell', 'ai-features'] });@@ -2120,7 +2823,7 @@ test('ai-features phase: a feature the SDK mis-reports is RE-PROVEN against thesdk.queryRecords = async (set) => {if (set === 'appmodule') return [{ appmoduleid: 'APPID' }];if (set === 'settingdefinition') return [{ settingdefinitionid: 'DEFID' }];- if (set === 'appsetting') return [{ value: '1' }]; // the row IS there+ if (set === 'appsetting') return [{ value: '2' }]; // the row IS there, holding ENABLED for this familyreturn [];};const events = [];diff --git a/plugins/model-apps/scripts/tests/sdk-surface-contract.test.js b/plugins/model-apps/scripts/tests/sdk-surface-contract.test.jsindex 76631b23d..9929d79aa 100644--- a/plugins/model-apps/scripts/tests/sdk-surface-contract.test.js+++ b/plugins/model-apps/scripts/tests/sdk-surface-contract.test.js@@ -69,6 +69,7 @@ const SKILL_SDK_SURFACE = ['getSolution','initWorkspace','insertStatusValue',+ 'moveElement','publishArtifact','pushArtifact','queryRecords',@@ -79,6 +80,11 @@ const SKILL_SDK_SURFACE = ['seedRecordGraph','setAppAiFeatures','setColumnVisualization',+ // Offers a form to specific security roles (AB#6648526). The roles are NOT a relationship —+ // `systemform` reports `CanBeInManyToMany: { Value: false, CanBeChanged: false }` and there is no+ // `systemformrole` entity — they live inside `formxml` as `<DisplayConditions>`, so this dedicated+ // call is the only way to write them.+ 'setFormSecurityRoles',// Written by the app-shell phase for `app.newLook` — the modern shell is a per-app SETTING// (`NewLookAlwaysOn`), not an appmodule column.'saveSettingValue',@@ -87,6 +93,7 @@ const SKILL_SDK_SURFACE = [// 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',+ 'updateColumn','updateElement','updateRecord','updateTable',diff --git a/plugins/model-apps/scripts/tests/sdk-teardown.test.js b/plugins/model-apps/scripts/tests/sdk-teardown.test.jsindex a6456a7cd..f18a90e09 100644--- a/plugins/model-apps/scripts/tests/sdk-teardown.test.js+++ b/plugins/model-apps/scripts/tests/sdk-teardown.test.js@@ -770,6 +770,170 @@ test('forms without names are skipped (cannot be resolved)', () => {assert.strictEqual(formSteps[0].label, 'form "MyForm" (new_x)');});+function businessRuleTeardownSdk(rows, { refuseActivatedCopyOnce = false, refuseActivatedCopyAlways = false, staleGoneIds = [] } = {}) {+ const live = new Map(rows.map((r) => [String(r.workflowid), { ...r }]));+ const calls = [];+ const staleGone = new Set(staleGoneIds.map(String));+ const refused = new Set();+ return {+ calls,+ async resolveArtifact(kind) {+ calls.push({ method: 'resolveArtifact', kind });+ return [];+ },+ async queryRecords(entitySet, opts = {}) {+ calls.push({ method: 'queryRecords', entitySet, filter: String(opts.filter || '') });+ if (entitySet !== 'workflow') return [];+ const filter = String(opts.filter || '');+ const wantsType1 = /type eq 1/.test(filter);+ const wantsType2 = /type eq 2/.test(filter);+ return [...live.values()].filter((r) => {+ if (!/category eq 2/.test(filter) || !filter.includes(`name eq '${r.name}'`) || !filter.includes(`primaryentity eq '${r.primaryentity}'`)) return false;+ if (wantsType1 && wantsType2) return r.type === 1 || r.type === 2;+ if (wantsType1) return r.type === 1;+ if (wantsType2) return r.type === 2;+ return true;+ });+ },+ async updateRecord(entitySet, id, data) {+ calls.push({ method: 'updateRecord', entitySet, id, data });+ const row = live.get(String(id));+ // The real SDK routes updateRecord through `ensureSuccess`, so a PATCH against a row that no+ // longer exists THROWS 404. Silently no-op'ing here let a fallback that deactivated an+ // already-DELETED definition look like working defence-in-depth when it could never fire.+ if (!row) {+ const err = new Error(`workflow ${id} not found`);+ err.statusCode = 404;+ throw err;+ }+ Object.assign(row, data);+ },+ async deleteRecord(entitySet, id) {+ calls.push({ method: 'deleteRecord', entitySet, id });+ const row = live.get(String(id));+ if (staleGone.has(String(id)) && !row) {+ const err = new Error('workflow not found');+ err.statusCode = 404;+ throw err;+ }+ if ((refuseActivatedCopyAlways || refuseActivatedCopyOnce) && row && row.type === 2 && (refuseActivatedCopyAlways || !refused.has(String(id)))) {+ refused.add(String(id));+ const err = new Error('The requested action is not supported for activated business rules.');+ err.statusCode = 405;+ throw err;+ }+ if (!row) {+ const err = new Error('workflow not found');+ err.statusCode = 404;+ throw err;+ }+ live.delete(String(id));+ },+ async deleteTable(logical) {+ calls.push({ method: 'deleteTable', logical });+ const err = new Error('Could not find an entity with the specified logical name');+ err.statusCode = 404;+ throw err;+ },+ };+}++test('active business-rule teardown deletes the DEFINITION first, then the activated copy, then the table', async () => {+ const sdk = businessRuleTeardownSdk([+ { workflowid: 'def-1', name: 'Gate', primaryentity: 'new_ticket', category: 2, type: 1, statecode: 1 },+ { workflowid: 'active-1', name: 'Gate', primaryentity: 'new_ticket', category: 2, type: 2, statecode: 1, _parentworkflowid_value: 'def-1' },+ ]);+ const spec = {+ solution: { uniqueName: 'S', publisherPrefix: 'new' },+ entities: [{ schemaName: 'new_ticket', primaryAttribute: { schemaName: 'new_name' } }],+ businessRules: [{ entity: 'new_ticket', name: 'Gate' }],+ };+ const res = await runTeardown(spec, { apply: true }, { sdk, emit: () => {} });+ assert.strictEqual(res.ok, true, JSON.stringify(res.errors));+ assert.deepStrictEqual(res.deleted.businessRules, ['def-1', 'active-1'], 'both workflow rows are counted as this step\'s responsibility');+ const writes = sdk.calls.filter((c) => c.method === 'deleteRecord' || c.method === 'deleteTable');+ // Live-measured order. The definition holds a cascade-restrict reference to the activated copy via+ // `workflow_active_workflow`, so the copy CANNOT be deleted first:+ // 405 "Cascade Delete failed due to cascade restrict relation. Restricting entity Workflow has+ // Id: <type-1> and is collected by Relationship with name: workflow_active_workflow."+ // Deleting the definition releases it, and the now-orphaned copy deletes cleanly — but ONLY while+ // its table still exists. After the table drop it is undeletable forever (400 0x80041102), which+ // is why both rows must precede the tables phase.+ assert.deepStrictEqual(writes.map((c) => c.method === 'deleteRecord' ? `${c.entitySet}:${c.id}` : `table:${c.logical}`), [+ 'workflow:def-1',+ 'workflow:active-1',+ 'table:new_ticket',+ ]);+});++test('draft-only business-rule teardown keeps the existing definition-only behavior', async () => {+ const sdk = businessRuleTeardownSdk([+ { workflowid: 'def-1', name: 'Draft Gate', primaryentity: 'new_ticket', category: 2, type: 1, statecode: 0 },+ ]);+ const items = await KIND_HANDLERS.businessRules.resolve(sdk, { entity: 'new_ticket', name: 'Draft Gate' });+ assert.deepStrictEqual(items.map((i) => i.id), ['def-1']);+ await deleteStep(sdk, KIND_HANDLERS.businessRules, items);+ assert.deepStrictEqual(+ sdk.calls.filter((c) => c.method === 'updateRecord' || c.method === 'deleteRecord').map((c) => `${c.method}:${c.id}`),+ ['deleteRecord:def-1'],+ 'a never-activated Draft rule is still just deleted directly'+ );+});++test('business-rule teardown makes ONE attempt at the activated copy — no retry that cannot succeed', async () => {+ const sdk = businessRuleTeardownSdk([+ { workflowid: 'def-1', name: 'Gate', primaryentity: 'new_ticket', category: 2, type: 1, statecode: 1 },+ { workflowid: 'active-1', name: 'Gate', primaryentity: 'new_ticket', category: 2, type: 2, statecode: 1, _parentworkflowid_value: 'def-1' },+ ], { refuseActivatedCopyAlways: true });+ const spec = {+ solution: { uniqueName: 'S', publisherPrefix: 'new' },+ entities: [{ schemaName: 'new_ticket', primaryAttribute: { schemaName: 'new_name' } }],+ businessRules: [{ entity: 'new_ticket', name: 'Gate' }],+ };+ await runTeardown(spec, { apply: true }, { sdk, emit: () => {} });+ const writes = sdk.calls.filter((c) => c.method === 'deleteRecord' || c.method === 'updateRecord').map((c) => (+ c.method === 'updateRecord' ? `update:${c.id}` : `delete:${c.id}`+ ));+ // Definition first (deactivate -> delete), then exactly ONE attempt at the copy. An earlier+ // version deactivated `parentDefinitionId` and re-issued the same delete, which reads like+ // defence in depth but cannot work: the definition row is already gone by then, so the deactivate+ // 404s and the retry is byte-identical to the call that just failed. It only looked correct+ // because the mock silently no-op'd updateRecord on a missing row.+ assert.deepStrictEqual(writes, ['update:def-1', 'delete:def-1', 'delete:active-1'],+ `expected exactly one copy-delete attempt and no post-delete retry; got: ${writes.join(' | ')}`);+ assert.strictEqual(writes.filter((w) => w === 'delete:active-1').length, 1, 'the copy delete was retried');+});++test('business-rule teardown is idempotent when a resolved activated copy is already gone', async () => {+ const sdk = businessRuleTeardownSdk([+ { workflowid: 'def-1', name: 'Gate', primaryentity: 'new_ticket', category: 2, type: 1, statecode: 0 },+ { workflowid: 'active-1', name: 'Gate', primaryentity: 'new_ticket', category: 2, type: 2, statecode: 1, _parentworkflowid_value: 'def-1' },+ ]);+ const items = await KIND_HANDLERS.businessRules.resolve(sdk, { entity: 'new_ticket', name: 'Gate' });+ // Simulate a re-run race: the row existed at resolve time but another teardown already removed it.+ sdk.calls.length = 0;+ await sdk.deleteRecord('workflow', 'active-1');+ sdk.calls.length = 0;+ const r = await deleteStep(sdk, KIND_HANDLERS.businessRules, items);+ assert.deepStrictEqual(r.deletedIds, ['def-1', 'active-1'], 'already-gone rows count as removed rather than failing the run');+ assert.deepStrictEqual(r.skippedIds, []);+});++test('business-rule teardown reports a failure when the activated copy still cannot be removed', async () => {+ const sdk = businessRuleTeardownSdk([+ { workflowid: 'def-1', name: 'Gate', primaryentity: 'new_ticket', category: 2, type: 1, statecode: 1 },+ { workflowid: 'active-1', name: 'Gate', primaryentity: 'new_ticket', category: 2, type: 2, statecode: 1, _parentworkflowid_value: 'def-1' },+ ], { refuseActivatedCopyAlways: true });+ const spec = {+ solution: { uniqueName: 'S', publisherPrefix: 'new' },+ entities: [{ schemaName: 'new_ticket', primaryAttribute: { schemaName: 'new_name' } }],+ businessRules: [{ entity: 'new_ticket', name: 'Gate' }],+ };+ const res = await runTeardown(spec, { apply: true }, { sdk, emit: () => {} });+ assert.strictEqual(res.ok, false, 'an undeleted activated copy makes teardown report a failed step');+ assert.ok(res.errors.some((e) => /business rule "Gate"/.test(e.step) && /not supported/.test(e.message)), 'the failure names the business-rule step and platform reason');+});+// --- helpers ----------------------------------------------------------------------------test('odataStr doubles single quotes (OData literal escaping)', () => {@@ -889,7 +1053,7 @@ test('teardown still deletes a real (non-restricted) solution — regression', a// --- Security persona roles (Group N P1) ----------------------------------------------------test('planTeardown inserts persona role steps right after the app, before the data model', () => {+test('planTeardown orders persona roles AFTER forms and before the data model', () => {const spec = Object.assign(fullSpec(), { personas: [{ persona: 'Agent', jobs: [{ name: 'w', privileges: [{ entity: 'new_ticket', access: ['read'] }] }] },{ persona: 'Lead', jobs: [{ name: 'm', privileges: [{ entity: 'new_ticket', access: ['read', 'write'] }] }] },@@ -898,11 +1062,21 @@ test('planTeardown inserts persona role steps right after the app, before the daassert.strictEqual(kinds[0], 'app');// Generative pages are torn down immediately after the app (the SDK no longer cascades them).assert.strictEqual(kinds[1], 'genpage');- assert.strictEqual(kinds[2], 'role');- assert.strictEqual(kinds[3], 'role');- // Roles are torn down before any relationship/table delete (a role holding a table's privileges- // could otherwise block that table's delete).++ // Roles come AFTER forms. `forms[].securityRoles` writes the role id into the form's formxml as a+ // `<DisplayConditions>` entry, and the platform treats that as a real dependency.+ // MEASURED live: deleting the role first answered+ // HTTP 400 ... The Role(<id>) component cannot be deleted because it is referenced by 1 other+ // components+ // and the identical delete returned 204 with zero reported dependencies once the forms were gone.+ assert.ok(kinds.indexOf('role') > kinds.lastIndexOf('form'),+ `roles must be deleted after every form; order was ${JSON.stringify(kinds)}`);++ // And still BEFORE any relationship/table delete — the original reason they were early. A role+ // holding a table's privileges can block that table's delete, so this constraint has to survive+ // the move rather than be traded away for the one above.assert.ok(kinds.lastIndexOf('role') < kinds.indexOf('relationship'), 'roles before relationships/tables');+ assert.strictEqual(kinds.filter((k) => k === 'role').length, 2, 'both personas are still planned');});test('role handler resolves ONLY SDK-authored (marker) unmanaged roles — never a foreign same-name role', async () => {@@ -1232,3 +1406,137 @@ test('command teardown proceeds with the bar when the row listing fails', asyncconst items = await KIND_HANDLERS.commands.resolve(sdk, { entity: 'new_ticket', ownsTable: true });assert.deepStrictEqual(items.map((i) => i.id), ['bar-1']);});++test('a column visualization on a RETAINED table is cleared at teardown', () => {+ // A visualization is a controlconfiguration row bound to the attribute, so it goes with the table+ // when the table is deleted. A table flagged `existing: true` is deliberately KEPT, and its+ // columns would otherwise keep a renderer this spec applied — residue on somebody else's table.+ const spec = fullSpec();+ spec.entities.push({+ schemaName: 'account', displayName: 'Account', pluralName: 'Accounts', existing: true,+ primaryAttribute: { schemaName: 'name', displayName: 'Name' },+ columns: [{ schemaName: 'new_score', displayName: 'Score', type: 'Integer', visualization: 'StarRating' }],+ });+ const steps = planTeardown(spec, {});+ const viz = steps.filter((s) => s.kind === 'columnVisualization');+ assert.strictEqual(viz.length, 1, `expected one clear step, got ${JSON.stringify(viz.map((v) => v.label))}`);+ assert.strictEqual(viz[0].target.entityLogical, 'account');+ assert.strictEqual(viz[0].target.columnLogical, 'new_score');+ // Before the tables phase: a table we DO own takes its configurations with it, so ordering the+ // clear after the delete would just 404.+ const tableIdx = steps.findIndex((s) => s.kind === 'table');+ assert.ok(steps.indexOf(viz[0]) < tableIdx, 'the clear must precede the tables phase');+});++test('a clear candidate is planned for every declared visualization, ownership decided at resolve', () => {+ // Planning cannot know whether a table survives: `existing: true` is one reason, but a SYSTEM table+ // is retained by live detection the plan has no access to, and such a spec need not carry the flag.+ // So a candidate is planned for each declared visualization and the resolver establishes ownership+ // — it reads the current value and skips unless it still matches what this spec authored.+ const spec = fullSpec();+ spec.entities[0].columns = [{ schemaName: 'new_score', displayName: 'Score', type: 'Integer', visualization: 'StarRating' }];+ const steps = planTeardown(spec, {}).filter((s) => s.kind === 'columnVisualization');+ assert.strictEqual(steps.length, 1);+ assert.strictEqual(steps[0].target.authored, 'StarRating', 'the authored value is what makes the clear safe');+});++test('teardown does NOT clear a visualization somebody else changed', async () => {+ // The configuration row is shared by every app showing the column, and the build PATCHes an+ // existing row rather than creating a private one. Blindly writing 'None' would erase a renderer+ // another maker set after this spec built.+ const calls = [];+ const sdk = {+ getColumnVisualization: async () => 'HeatMap', // someone changed it+ setColumnVisualization: async (...a) => { calls.push(a); },+ };+ const res = await KIND_HANDLERS.columnVisualization.resolve(sdk, { entityLogical: 'account', columnLogical: 'new_score', authored: 'StarRating' });+ assert.deepStrictEqual(res.items, [], 'nothing to delete when the value is not ours');+ assert.match(res.skipReason, /someone else changed it/);+ assert.strictEqual(calls.length, 0, 'and nothing is written');+});++test('teardown clears a visualization that still matches what this spec authored', async () => {+ const sdk = { getColumnVisualization: async () => 'StarRating', setColumnVisualization: async () => {} };+ const items = await KIND_HANDLERS.columnVisualization.resolve(sdk, { entityLogical: 'account', columnLogical: 'new_score', authored: 'StarRating' });+ assert.strictEqual(items.length, 1);+});++test('teardown skips quietly where the visualization preview is not provisioned', async () => {+ const err = new Error("Resource not found for the segment 'controlconfigurations'.");+ err.statusCode = 404;+ const sdk = { getColumnVisualization: async () => { throw err; } };+ const res = await KIND_HANDLERS.columnVisualization.resolve(sdk, { entityLogical: 'account', columnLogical: 'new_score', authored: 'StarRating' });+ assert.deepStrictEqual(res.items, []);+ assert.match(res.skipReason, /not provisioned/);+});++test('an unreadable current value is left alone rather than cleared', async () => {+ // Fail closed: if ownership cannot be established, doing nothing is the safe outcome.+ const err = new Error('403 forbidden');+ err.statusCode = 403;+ const sdk = { getColumnVisualization: async () => { throw err; } };+ const res = await KIND_HANDLERS.columnVisualization.resolve(sdk, { entityLogical: 'account', columnLogical: 'new_score', authored: 'StarRating' });+ assert.deepStrictEqual(res.items, []);+ assert.match(res.skipReason, /could not read/);+});++test('clearing a visualization writes None through the SDK', async () => {+ const calls = [];+ const sdk = { setColumnVisualization: async (e, c, v) => { calls.push([e, c, v]); } };+ await KIND_HANDLERS.columnVisualization.del(sdk, { entityLogical: 'account', columnLogical: 'new_score' });+ assert.deepStrictEqual(calls, [['account', 'new_score', 'None']]);+});++// --- the teardown business-rule filter is built explicitly, not string-patched ------------------+//+// PR review: this filter used to be `businessRuleFilter(...).replace('type eq 1', '(type eq 1 or+// type eq 2)')`, which coupled teardown to the exact spelling of a function in another module. Any+// reordering or whitespace change there would silently stop the widening — the type-2 activated copy+// would survive the table delete, and #493's residue would return with every test still green.+//+// LIVE-VERIFIED that the widening matters: teardown of a genuinely activated rule reports+// "2 deleted" — the definition AND the platform's activated copy.++test('teardown resolves BOTH the definition and the activated copy (type 1 and type 2)', async () => {+ const queries = [];+ const sdk = {+ queryRecords: async (set, opts) => { queries.push({ set, opts }); return []; },+ updateRecord: async () => {},+ deleteRecord: async () => {},+ };+ await KIND_HANDLERS.businessRules.resolve(sdk, { name: "Lock O'Brien", entity: 'New_Ticket' });++ assert.strictEqual(queries.length, 1);+ const f = queries[0].opts.filter;+ assert.match(f, /\(type eq 1 or type eq 2\)/, 'both row types must be in scope for teardown');+ assert.match(f, /category eq 2/, 'business rules only — never a classic workflow');+ assert.match(f, /primaryentity eq 'new_ticket'/, 'the entity is lower-cased, and the rule is table-scoped');+ // An apostrophe must be OData-escaped by doubling, or the filter is malformed AND injectable.+ assert.match(f, /name eq 'Lock O''Brien'/, "a quote in the name must be escaped, not passed through");+});++test('the teardown filter does NOT depend on businessRuleFilter\'s spelling', async () => {+ // The specific brittleness that was reported. `businessRuleFilter` is the BUILD's definition-only+ // query; teardown must not derive from its text. Asserted on the source so a re-introduction of the+ // `.replace(...)` coupling fails here rather than silently in production.+ //+ // COMMENTS ARE STRIPPED FIRST. The fix's own comment quotes the old pattern verbatim to explain+ // what changed, and a naive source scan matched that prose — a test that fails on its own+ // documentation is worse than no test.+ const raw = fs.readFileSync(path.join(__dirname, '..', 'lib', 'sdk-teardown.js'), 'utf8');+ const code = raw+ .split(/\r?\n/)+ // No `$` anchor: this file is CRLF, and in JS `.` does not match `\r`, so `.*$` never reached the+ // end of a line that still carried one — the strip silently did nothing and this test failed on+ // its own documentation.+ .map((l) => l.replace(/^\s*\/\/.*/, ''))+ .join('\n')+ .replace(/\/\*[\s\S]*?\*\//g, ''); // block comments+ assert.doesNotMatch(code, /businessRuleFilter\([^)]*\)\s*\.replace\(/,+ 'teardown must not string-patch businessRuleFilter output');+ // And it must not import the symbol at all, so the coupling cannot creep back in another form.+ const importLine = code.split('\n').find((l) => l.includes("require('./sdk-build.js')")) || '';+ assert.ok(importLine, 'the sdk-build import line must still be findable for this check to mean anything');+ assert.strictEqual(importLine.includes('businessRuleFilter'), false,+ `teardown must not import businessRuleFilter; got: ${importLine.trim().slice(0, 160)}`);+});diff --git a/plugins/model-apps/scripts/tests/sdk-uptake-contract.test.js b/plugins/model-apps/scripts/tests/sdk-uptake-contract.test.jsindex 78b27b992..ee09c0db9 100644--- a/plugins/model-apps/scripts/tests/sdk-uptake-contract.test.js+++ b/plugins/model-apps/scripts/tests/sdk-uptake-contract.test.js@@ -142,10 +142,19 @@ test('REAL BUNDLE: a business rule goes through the SUPPORTED bound member firstassert.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.+test('REAL BUNDLE: a qualifying 400 no longer falls back — it throws, and writes nothing else', async () => {+ // This USED to be the point of the uptake: the bound member faulted with a server-side plugin error+ // on our tenants, and the SDK compiled the same typed rule to WWF XAML and wrote a plain+ // `workflows` row instead.+ //+ // That fallback has been DELETED upstream, deliberately. It covered 4 of the 7 action types, a+ // single clause and no else-if, so it silently narrowed a rule into something the platform accepted+ // but that did not say what the author wrote. A loud refusal is strictly better than a rule that+ // quietly means something else.+ //+ // Pinned here because the failure mode of losing this is invisible: a re-vendored bundle that+ // resurrected the fallback would make every one of these pushes "succeed" again, with narrowed+ // rules nobody asked for.const { sdk, calls } = sdkWith({post: (url) => (/WithWfomJson/i.test(url)? { status: 400, headers: {}, body: { error: { code: '0x80040216', message: 'System failure in WorkflowService' } } }@@ -153,23 +162,10 @@ test('REAL BUNDLE: 0x80040216 falls back to the classic XAML row, and the XAML n});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');+ await assert.rejects(() => sdk.pushArtifact('businessRule', art.id), 'the 400 must propagate, not be papered over');- 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');+ assert.strictEqual(calls.some((c) => c.verb === 'POST' && /\/workflows$/.test(String(c.url))), false,+ 'no classic XAML row may be written; calls: ' + JSON.stringify(calls.map((c) => `${c.verb} ${c.url}`)));});test('REAL BUNDLE: a NON-qualifying failure must NOT fall back (a second write could duplicate the rule)', async () => {@@ -212,32 +208,42 @@ test('REAL BUNDLE: a NON-qualifying failure must NOT fall back (a second write c'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.+test('REAL BUNDLE: a 404 on the bound member is refused with a STABLE, matchable code', async () => {+ // The plugin degrades gracefully on an environment that does not declare the member (it skips the+ // rules and builds the rest of the app rather than halting 90% of the way through). That branch is+ // selected by `err.code`, so the code is a contract, not an implementation detail.+ //+ // It must NOT be selected by `err.name`: the bundle is minified, so the class name is a+ // rebuild-unstable two-letter string that also happens to be the shared base error. Matching it+ // would silently disarm the branch on the next re-vendor.+ //+ // MEASURED live: `$metadata` on a real environment (16.5 MB) does not mention the member, and every+ // POST to it answers 404. The SDK's own message reports 18 of 20 environments in the same state.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');++ const err = await sdk.pushArtifact('businessRule', art.id).then(() => null, (e) => e);+ assert.ok(err, 'an undeclared member must be refused, not silently substituted');+ assert.strictEqual(err.code, 'BUSINESS_RULE_API_UNAVAILABLE',+ `the plugin branches on this exact code; got ${JSON.stringify(err.code)}`);+ assert.match(err.message, /does not expose/i, 'the message must name the cause for the operator');+ assert.strictEqual(calls.some((c) => c.verb === 'POST' && /\/workflows$/.test(String(c.url))), false,+ 'and nothing else may be written in its place');});-test('REAL BUNDLE: a wrongly-shaped condition compiles an EMPTY rule rather than erroring', async () => {+test('REAL BUNDLE: a wrongly-shaped condition produces 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.+ // is the natural guess at the shape; `updateElement` merges those keys onto the node, the+ // serializer ignores them, and the push SUCCEEDS with a workflow object model 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),- });+ // So a caller CANNOT rely on an error to tell them the shape is wrong. The plugin's App Spec+ // validation exists precisely because of this: it checks `conditions`/`actions` itself before+ // anything is pushed.+ const { sdk, calls } = sdkWith();const art = authorRule(sdk);await sdk.updateElement('businessRule', art.id, '/rootCondition', {operator: 'Equal',@@ -248,10 +254,11 @@ test('REAL BUNDLE: a wrongly-shaped condition compiles an EMPTY rule rather thanconst 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');+ const bound = calls.find((c) => c.verb === 'POST' && /CreateProcessWithWfomJson/i.test(String(c.url)));+ assert.ok(bound, 'a rule is still written');+ const wfom = String(bound.body.WfomJson);+ assert.doesNotMatch(wfom, /lvz_status/, 'the guessed shape contributes NO condition');+ assert.doesNotMatch(wfom, /lvz_notes/, 'and NO action');});// ---------------------------------------------------------------------------------------------@@ -267,14 +274,15 @@ test('REAL BUNDLE: a wrongly-shaped condition compiles an EMPTY rule rather than// 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;+ // The maps are emitted as, e.g.:+ // {formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",+ // formFillSmartPaste:"FormPredictSmartPasteEnabledOnByDefault",formFillFiles:"...",+ // nlSearch:"NLGridSearchSetting",nlChart:"...",m365:"..."}+ // The GATE map additionally carries `summaries` (the per-app map has none — row summaries are+ // configured through configureRowSummary, not a flag). Anchor on the `formFill` key rather than+ // the minified variable name, which changes every build, and accept any key set after it so a new+ // capability is caught by the deepEqual below rather than silently skipped by the regex.+ const m = /\{formFill:"[^"]+"(?:,[A-Za-z0-9_]+:"[^"]+")+\}/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}`);@@ -301,90 +309,72 @@ test('REAL BUNDLE: AI_APP_SETTING matches the SDK per-app setting map exactly',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: [] } }),- });-+// ---------------------------------------------------------------------------------------------+// 4. There is exactly ONE write path, so #482 cannot recur.+//+// #482 was a DOUBLE WRITE. The platform commits the workflow row and only then faults generating its+// UiData, raising a 400; the old bundle read that status as "nothing was written" and its XAML+// fallback wrote a SECOND copy. Measured live as 4 rows for 2 authored rules, both Active, both+// firing. The SDK then grew an orphan-probe-and-delete dance to compensate.+//+// The fallback — and with it the entire dance — has been deleted upstream. A business rule is now+// written through the bound member or not at all, which removes the second writer rather than+// coordinating it. That is a stronger guarantee, but only while it holds, so it is pinned here: any+// re-vendor that reintroduces ANY second write path fails these tests.+//+// https://github.com/microsoft/power-platform-skills/issues/482+test('REAL BUNDLE: the happy path writes the rule EXACTLY once', async () => {+ const { sdk, calls } = sdkWith();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');+ assert.strictEqual(res.saved, true);- // 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}`);- }+ const writes = calls.filter((c) => c.verb === 'POST' && /workflow/i.test(String(c.url)));+ assert.strictEqual(writes.length, 1, 'exactly one POST may create the rule; got ' + JSON.stringify(writes.map((c) => c.url)));+ assert.match(String(writes[0].url), /CreateProcessWithWfomJson/, 'and it must be the bound member');});-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).- {+test('REAL BUNDLE: no failure of the bound member produces a second write', async () => {+ // The qualifying 400 (0x80040216) and the 404 are the two statuses that USED to trigger the+ // fallback, so they are the two that would resurrect the duplicate. The rest are included because+ // "nothing else writes twice either" is the actual invariant, and a partial check would let a+ // narrower fallback back in unnoticed.+ const FAILURES = [+ [400, '0x80040216'], // committed-then-faulted: the exact #482 trigger+ [404, null], // member not declared on this environment+ [400, '0x80040265'], // an unrelated 400+ [401, null],+ [403, null],+ [429, null],+ [500, null],+ ];+ for (const [status, code] of FAILURES) {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' } } }),+ post: (url) => (/CreateProcessWithWfomJson/i.test(url)+ ? { status, headers: {}, body: code ? { error: { code, message: 'fault' } } : {} }+ : undefined),});- 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');- }+ await assert.rejects(() => authorDupGuard(sdk), `HTTP ${status} ${code || ''} must surface, not be absorbed`);- // 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');+ // The decisive assertion: no classic row, and no retry of the member either. Either one would be+ // a second rule on the table for a single authored rule.assert.strictEqual(calls.some((c) => c.verb === 'POST' && /\/workflows$/.test(String(c.url))), false,- 'and must not write a replacement either');+ `HTTP ${status} ${code || ''} must not write a classic row`);+ const memberPosts = calls.filter((c) => c.verb === 'POST' && /CreateProcessWithWfomJson/i.test(String(c.url)));+ assert.strictEqual(memberPosts.length, 1,+ `HTTP ${status} ${code || ''} must not retry the member; got ${memberPosts.length} posts`);}});++test('REAL BUNDLE: the deleted fallback leaves no trace in the bundle', async () => {+ // Deliberately NOT a grep for XAML fingerprints. That was tried and was wrong twice over:+ // `iscrmuiworkflow` is still in the bundle because it is part of the BOUND MEMBER's own create+ // payload, and the WWF activities namespace is still there because the BUSINESS PROCESS FLOW+ // compiler — an unrelated feature — emits it. A sentinel that fires on either would fail for a+ // reason that has nothing to do with business rules.+ //+ // The one string that WAS unique to the deleted compiler is its null-parameter emission, the exact+ // shape of the #481 fix. Its return would mean the compiler is back.+ const src = fs.readFileSync(BUNDLE, 'utf8');+ assert.ok(!src.includes('x:Null x:Key="Parameters"'),+ 'the business-rule XAML compiler\'s null-parameter emission is back — the fallback has been reintroduced');+});diff --git a/plugins/model-apps/scripts/tests/vendor/acorn.cjs b/plugins/model-apps/scripts/tests/vendor/acorn.cjsnew file mode 100644index 000000000..49702564b--- /dev/null+++ b/plugins/model-apps/scripts/tests/vendor/acorn.cjs@@ -0,0 +1,5805 @@+/* Vendored dev-only dependency: acorn 8.18.0 (MIT), bundled with esbuild for the async-surface+ * guard in sdk-async-surface.test.js. NOT shipped to users and not loaded by any plugin script —+ * the plugin itself keeps zero runtime dependencies, and the test CI job has no install step, which+ * is why this is a committed artifact rather than an npm dependency (see issue #475).+ *+ * Rebuild: npm install acorn --no-save && esbuild node_modules/acorn/dist/acorn.mjs \+ * --bundle --format=cjs --platform=node --outfile=scripts/tests/vendor/acorn.cjs+ *+ * Upstream: https://github.com/acornjs/acorn+ *+ * MIT License+ *+ * Copyright (C) 2012-2022 by various contributors (see AUTHORS)+ *+ * Permission is hereby granted, free of charge, to any person obtaining a copy+ * of this software and associated documentation files (the "Software"), to deal+ * in the Software without restriction, including without limitation the rights+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+ * copies of the Software, and to permit persons to whom the Software is+ * furnished to do so, subject to the following conditions:+ *+ * The above copyright notice and this permission notice shall be included in+ * all copies or substantial portions of the Software.+ *+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+ * THE SOFTWARE.+ *++ */+var __defProp = Object.defineProperty;+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;+var __getOwnPropNames = Object.getOwnPropertyNames;+var __hasOwnProp = Object.prototype.hasOwnProperty;+var __export = (target, all) => {+ for (var name in all)+ __defProp(target, name, { get: all[name], enumerable: true });+};+var __copyProps = (to, from, except, desc) => {+ if (from && typeof from === "object" || typeof from === "function") {+ for (let key of __getOwnPropNames(from))+ if (!__hasOwnProp.call(to, key) && key !== except)+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });+ }+ return to;+};+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);++// node_modules/acorn/dist/acorn.mjs+var acorn_exports = {};+__export(acorn_exports, {+ Node: () => Node,+ Parser: () => Parser,+ Position: () => Position,+ SourceLocation: () => SourceLocation,+ TokContext: () => TokContext,+ Token: () => Token,+ TokenType: () => TokenType,+ defaultOptions: () => defaultOptions,+ getLineInfo: () => getLineInfo,+ isIdentifierChar: () => isIdentifierChar,+ isIdentifierStart: () => isIdentifierStart,+ isNewLine: () => isNewLine,+ keywordTypes: () => keywords,+ lineBreak: () => lineBreak,+ lineBreakG: () => lineBreakG,+ nonASCIIwhitespace: () => nonASCIIwhitespace,+ parse: () => parse3,+ parseExpressionAt: () => parseExpressionAt2,+ tokContexts: () => types,+ tokTypes: () => types$1,+ tokenizer: () => tokenizer2,+ version: () => version+});+module.exports = __toCommonJS(acorn_exports);+var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 7, 9, 32, 4, 318, 1, 78, 5, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 199, 7, 137, 9, 54, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 55, 9, 266, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 245, 1, 2, 9, 233, 0, 3, 0, 8, 1, 6, 0, 475, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];+var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 4, 51, 13, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 7, 25, 39, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 39, 27, 10, 22, 251, 41, 7, 1, 17, 5, 57, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 200, 32, 32, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 24, 43, 261, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 33, 24, 3, 24, 45, 74, 6, 0, 67, 12, 65, 1, 2, 0, 15, 4, 10, 7381, 42, 31, 98, 114, 8702, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 229, 29, 3, 0, 208, 30, 2, 2, 2, 1, 2, 6, 3, 4, 10, 1, 225, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4381, 3, 5773, 3, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 8489];+var nonASCIIidentifierChars = "\u200C\u200D\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C04\u0C3C\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0CF3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u180F-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1ABF-\u1ADD\u1AE0-\u1AEB\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DFF\u200C\u200D\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\u30FB\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA8FF-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F\uFF65";+var nonASCIIidentifierStartChars = "\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088F\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5C\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDC-\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7DC\uA7F1-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC";+var reservedWords = {+ 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",+ 5: "class enum extends super const export import",+ 6: "enum",+ strict: "implements interface let package private protected public static yield",+ strictBind: "eval arguments"+};+var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";+var keywords$1 = {+ 5: ecma5AndLessKeywords,+ "5module": ecma5AndLessKeywords + " export import",+ 6: ecma5AndLessKeywords + " const class extends export import super"+};+var keywordRelationalOperator = /^in(stanceof)?$/;+var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");+var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");+function isInAstralSet(code, set) {+ var pos = 65536;+ for (var i2 = 0; i2 < set.length; i2 += 2) {+ pos += set[i2];+ if (pos > code) {+ return false;+ }+ pos += set[i2 + 1];+ if (pos >= code) {+ return true;+ }+ }+ return false;+}+function isIdentifierStart(code, astral) {+ if (code < 65) {+ return code === 36;+ }+ if (code < 91) {+ return true;+ }+ if (code < 97) {+ return code === 95;+ }+ if (code < 123) {+ return true;+ }+ if (code <= 65535) {+ return code >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code));+ }+ if (astral === false) {+ return false;+ }+ return isInAstralSet(code, astralIdentifierStartCodes);+}+function isIdentifierChar(code, astral) {+ if (code < 48) {+ return code === 36;+ }+ if (code < 58) {+ return true;+ }+ if (code < 65) {+ return false;+ }+ if (code < 91) {+ return true;+ }+ if (code < 97) {+ return code === 95;+ }+ if (code < 123) {+ return true;+ }+ if (code <= 65535) {+ return code >= 170 && nonASCIIidentifier.test(String.fromCharCode(code));+ }+ if (astral === false) {+ return false;+ }+ return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);+}+var TokenType = function TokenType2(label, conf) {+ if (conf === void 0) conf = {};+ this.label = label;+ this.keyword = conf.keyword;+ this.beforeExpr = !!conf.beforeExpr;+ this.startsExpr = !!conf.startsExpr;+ this.isLoop = !!conf.isLoop;+ this.isAssign = !!conf.isAssign;+ this.prefix = !!conf.prefix;+ this.postfix = !!conf.postfix;+ this.binop = conf.binop || null;+ this.updateContext = null;+};+function binop(name, prec) {+ return new TokenType(name, { beforeExpr: true, binop: prec });+}+var beforeExpr = { beforeExpr: true };+var startsExpr = { startsExpr: true };+var keywords = {};+function kw(name, options) {+ if (options === void 0) options = {};+ options.keyword = name;+ return keywords[name] = new TokenType(name, options);+}+var types$1 = {+ num: new TokenType("num", startsExpr),+ regexp: new TokenType("regexp", startsExpr),+ string: new TokenType("string", startsExpr),+ name: new TokenType("name", startsExpr),+ privateId: new TokenType("privateId", startsExpr),+ eof: new TokenType("eof"),+ // Punctuation token types.+ bracketL: new TokenType("[", { beforeExpr: true, startsExpr: true }),+ bracketR: new TokenType("]"),+ braceL: new TokenType("{", { beforeExpr: true, startsExpr: true }),+ braceR: new TokenType("}"),+ parenL: new TokenType("(", { beforeExpr: true, startsExpr: true }),+ parenR: new TokenType(")"),+ comma: new TokenType(",", beforeExpr),+ semi: new TokenType(";", beforeExpr),+ colon: new TokenType(":", beforeExpr),+ dot: new TokenType("."),+ question: new TokenType("?", beforeExpr),+ questionDot: new TokenType("?."),+ arrow: new TokenType("=>", beforeExpr),+ template: new TokenType("template"),+ invalidTemplate: new TokenType("invalidTemplate"),+ ellipsis: new TokenType("...", beforeExpr),+ backQuote: new TokenType("`", startsExpr),+ dollarBraceL: new TokenType("${", { beforeExpr: true, startsExpr: true }),+ // Operators. These carry several kinds of properties to help the+ // parser use them properly (the presence of these properties is+ // what categorizes them as operators).+ //+ // `binop`, when present, specifies that this operator is a binary+ // operator, and will refer to its precedence.+ //+ // `prefix` and `postfix` mark the operator as a prefix or postfix+ // unary operator.+ //+ // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as+ // binary operators with a very low precedence, that should result+ // in AssignmentExpression nodes.+ eq: new TokenType("=", { beforeExpr: true, isAssign: true }),+ assign: new TokenType("_=", { beforeExpr: true, isAssign: true }),+ incDec: new TokenType("++/--", { prefix: true, postfix: true, startsExpr: true }),+ prefix: new TokenType("!/~", { beforeExpr: true, prefix: true, startsExpr: true }),+ logicalOR: binop("||", 1),+ logicalAND: binop("&&", 2),+ bitwiseOR: binop("|", 3),+ bitwiseXOR: binop("^", 4),+ bitwiseAND: binop("&", 5),+ equality: binop("==/!=/===/!==", 6),+ relational: binop("</>/<=/>=", 7),+ bitShift: binop("<</>>/>>>", 8),+ plusMin: new TokenType("+/-", { beforeExpr: true, binop: 9, prefix: true, startsExpr: true }),+ modulo: binop("%", 10),+ star: binop("*", 10),+ slash: binop("/", 10),+ starstar: new TokenType("**", { beforeExpr: true }),+ coalesce: binop("??", 1),+ // Keyword token types.+ _break: kw("break"),+ _case: kw("case", beforeExpr),+ _catch: kw("catch"),+ _continue: kw("continue"),+ _debugger: kw("debugger"),+ _default: kw("default", beforeExpr),+ _do: kw("do", { isLoop: true, beforeExpr: true }),+ _else: kw("else", beforeExpr),+ _finally: kw("finally"),+ _for: kw("for", { isLoop: true }),+ _function: kw("function", startsExpr),+ _if: kw("if"),+ _return: kw("return", beforeExpr),+ _switch: kw("switch"),+ _throw: kw("throw", beforeExpr),+ _try: kw("try"),+ _var: kw("var"),+ _const: kw("const"),+ _while: kw("while", { isLoop: true }),+ _with: kw("with"),+ _new: kw("new", { beforeExpr: true, startsExpr: true }),+ _this: kw("this", startsExpr),+ _super: kw("super", startsExpr),+ _class: kw("class", startsExpr),+ _extends: kw("extends", beforeExpr),+ _export: kw("export"),+ _import: kw("import", startsExpr),+ _null: kw("null", startsExpr),+ _true: kw("true", startsExpr),+ _false: kw("false", startsExpr),+ _in: kw("in", { beforeExpr: true, binop: 7 }),+ _instanceof: kw("instanceof", { beforeExpr: true, binop: 7 }),+ _typeof: kw("typeof", { beforeExpr: true, prefix: true, startsExpr: true }),+ _void: kw("void", { beforeExpr: true, prefix: true, startsExpr: true }),+ _delete: kw("delete", { beforeExpr: true, prefix: true, startsExpr: true })+};+var lineBreak = /\r\n?|\n|\u2028|\u2029/;+var lineBreakG = new RegExp(lineBreak.source, "g");+function isNewLine(code) {+ return code === 10 || code === 13 || code === 8232 || code === 8233;+}+function nextLineBreak(code, from, end) {+ if (end === void 0) end = code.length;+ for (var i2 = from; i2 < end; i2++) {+ var next = code.charCodeAt(i2);+ if (isNewLine(next)) {+ return i2 < end - 1 && next === 13 && code.charCodeAt(i2 + 1) === 10 ? i2 + 2 : i2 + 1;+ }+ }+ return -1;+}+var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;+var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;+var ref = Object.prototype;+var hasOwnProperty = ref.hasOwnProperty;+var toString = ref.toString;+var hasOwn = Object.hasOwn || (function(obj, propName) {+ return hasOwnProperty.call(obj, propName);+});+var isArray = Array.isArray || (function(obj) {+ return toString.call(obj) === "[object Array]";+});+var regexpCache = /* @__PURE__ */ Object.create(null);+function wordsRegexp(words) {+ return regexpCache[words] || (regexpCache[words] = new RegExp("^(?:" + words.replace(/ /g, "|") + ")$"));+}+function codePointToString(code) {+ if (code <= 65535) {+ return String.fromCharCode(code);+ }+ code -= 65536;+ return String.fromCharCode((code >> 10) + 55296, (code & 1023) + 56320);+}+var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/;+var Position = function Position2(line, col) {+ this.line = line;+ this.column = col;+};+Position.prototype.offset = function offset(n) {+ return new Position(this.line, this.column + n);+};+var SourceLocation = function SourceLocation2(p, start, end) {+ this.start = start;+ this.end = end;+ if (p.sourceFile !== null) {+ this.source = p.sourceFile;+ }+};+function getLineInfo(input, offset2) {+ for (var line = 1, cur = 0; ; ) {+ var nextBreak = nextLineBreak(input, cur, offset2);+ if (nextBreak < 0) {+ return new Position(line, offset2 - cur);+ }+ ++line;+ cur = nextBreak;+ }+}+var defaultOptions = {+ // `ecmaVersion` indicates the ECMAScript version to parse. Must be+ // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10+ // (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"`+ // (the latest version the library supports). This influences+ // support for strict mode, the set of reserved words, and support+ // for new syntax features.+ ecmaVersion: null,+ // `sourceType` indicates the mode the code should be parsed in.+ // Can be either `"script"`, `"module"` or `"commonjs"`. This influences global+ // strict mode and parsing of `import` and `export` declarations.+ sourceType: "script",+ // When set to true, enable strict parsing mode even if `sourceType`+ // is `"script"`.+ strict: false,+ // `onInsertedSemicolon` can be a callback that will be called when+ // a semicolon is automatically inserted. It will be passed the+ // position of the inserted semicolon as an offset, and if+ // `locations` is enabled, it is given the location as a `{line,+ // column}` object as second argument.+ onInsertedSemicolon: null,+ // `onTrailingComma` is similar to `onInsertedSemicolon`, but for+ // trailing commas.+ onTrailingComma: null,+ // By default, reserved words are only enforced if ecmaVersion >= 5.+ // Set `allowReserved` to a boolean value to explicitly turn this on+ // an off. When this option has the value "never", reserved words+ // and keywords can also not be used as property names.+ allowReserved: null,+ // When enabled, a return at the top level is not considered an+ // error.+ allowReturnOutsideFunction: false,+ // When enabled, import/export statements are not constrained to+ // appearing at the top of the program, and an import.meta expression+ // in a script isn't considered an error.+ allowImportExportEverywhere: false,+ // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.+ // When enabled, await identifiers are allowed to appear at the top-level scope,+ // but they are still not allowed in non-async functions.+ allowAwaitOutsideFunction: null,+ // When enabled, super identifiers are not constrained to+ // appearing in methods and do not raise an error when they appear elsewhere.+ allowSuperOutsideMethod: null,+ // When enabled, hashbang directive in the beginning of file is+ // allowed and treated as a line comment. Enabled by default when+ // `ecmaVersion` >= 2023.+ allowHashBang: false,+ // By default, the parser will verify that private properties are+ // only used in places where they are valid and have been declared.+ // Set this to false to turn such checks off.+ checkPrivateFields: true,+ // When `locations` is on, `loc` properties holding objects with+ // `start` and `end` properties in `{line, column}` form (with+ // line being 1-based and column 0-based) will be attached to the+ // nodes.+ locations: false,+ // Pass an optional `{line, column}` object to use for the start of+ // the parse. This is mostly useful when using `parseExpressionAt`+ // with `locations: true`, to prevent the parser from having to+ // determine the line position at the start position.+ startLocation: null,+ // A function can be passed as `onToken` option, which will+ // cause Acorn to call that function with object in the same+ // format as tokens returned from `tokenizer().getToken()`. Note+ // that you are not allowed to call the parser from the+ // callback—that will corrupt its internal state.+ onToken: null,+ // A function can be passed as `onComment` option, which will+ // cause Acorn to call that function with `(block, text, start,+ // end)` parameters whenever a comment is skipped. `block` is a+ // boolean indicating whether this is a block (`/* */`) comment,+ // `text` is the content of the comment, and `start` and `end` are+ // character offsets that denote the start and end of the comment.+ // When the `locations` option is on, two more parameters are+ // passed, the full `{line, column}` locations of the start and+ // end of the comments. Note that you are not allowed to call the+ // parser from the callback—that will corrupt its internal state.+ // When this option has an array as value, objects representing the+ // comments are pushed to it.+ onComment: null,+ // Nodes have their start and end characters offsets recorded in+ // `start` and `end` properties (directly on the node, rather than+ // the `loc` object, which holds line/column data. To also add a+ // [semi-standardized][range] `range` property holding a `[start,+ // end]` array with the same numbers, set the `ranges` option to+ // `true`.+ //+ // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678+ ranges: false,+ // It is possible to parse multiple files into a single AST by+ // passing the tree produced by parsing the first file as+ // `program` option in subsequent parses. This will add the+ // toplevel forms of the parsed file to the `Program` (top) node+ // of an existing parse tree.+ program: null,+ // When `locations` is on, you can pass this to record the source+ // file in every node's `loc` object.+ sourceFile: null,+ // This value, if given, is stored in every node, whether+ // `locations` is on or off.+ directSourceFile: null,+ // When enabled, parenthesized expressions are represented by+ // (non-standard) ParenthesizedExpression nodes+ preserveParens: false+};+var warnedAboutEcmaVersion = false;+function getOptions(opts) {+ var options = {};+ for (var opt in defaultOptions) {+ options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt];+ }+ if (options.ecmaVersion === "latest") {+ options.ecmaVersion = 1e8;+ } else if (options.ecmaVersion == null) {+ if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {+ warnedAboutEcmaVersion = true;+ console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");+ }+ options.ecmaVersion = 11;+ } else if (options.ecmaVersion >= 2015) {+ options.ecmaVersion -= 2009;+ }+ if (options.allowReserved == null) {+ options.allowReserved = options.ecmaVersion < 5;+ }+ if (!opts || opts.allowHashBang == null) {+ options.allowHashBang = options.ecmaVersion >= 14;+ }+ if (isArray(options.onToken)) {+ var tokens = options.onToken;+ options.onToken = function(token) {+ return tokens.push(token);+ };+ }+ if (isArray(options.onComment)) {+ options.onComment = pushComment(options, options.onComment);+ }+ if (options.sourceType === "commonjs" && options.allowAwaitOutsideFunction) {+ throw new Error("Cannot use allowAwaitOutsideFunction with sourceType: commonjs");+ }+ return options;+}+function pushComment(options, array) {+ return function(block, text, start, end, startLoc, endLoc) {+ var comment = {+ type: block ? "Block" : "Line",+ value: text,+ start,+ end+ };+ if (options.locations) {+ comment.loc = new SourceLocation(this, startLoc, endLoc);+ }+ if (options.ranges) {+ comment.range = [start, end];+ }+ array.push(comment);+ };+}+var SCOPE_TOP = 1;+var SCOPE_FUNCTION = 2;+var SCOPE_ASYNC = 4;+var SCOPE_GENERATOR = 8;+var SCOPE_ARROW = 16;+var SCOPE_SIMPLE_CATCH = 32;+var SCOPE_SUPER = 64;+var SCOPE_DIRECT_SUPER = 128;+var SCOPE_CLASS_STATIC_BLOCK = 256;+var SCOPE_CLASS_FIELD_INIT = 512;+var SCOPE_SWITCH = 1024;+var SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK;+function functionFlags(async, generator) {+ return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0);+}+var BIND_NONE = 0;+var BIND_VAR = 1;+var BIND_LEXICAL = 2;+var BIND_FUNCTION = 3;+var BIND_SIMPLE_CATCH = 4;+var BIND_OUTSIDE = 5;+var Parser = function Parser2(options, input, startPos) {+ this.options = options = getOptions(options);+ this.sourceFile = options.sourceFile;+ this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);+ var reserved = "";+ if (options.allowReserved !== true) {+ reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];+ if (options.sourceType === "module") {+ reserved += " await";+ }+ }+ this.reservedWords = wordsRegexp(reserved);+ var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;+ this.reservedWordsStrict = wordsRegexp(reservedStrict);+ this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);+ this.input = String(input);+ this.containsEsc = false;+ this.pos = startPos || 0;+ this.curLine = 1;+ if (options.startLocation) {+ this.lineStart = this.pos - options.startLocation.column;+ this.curLine = options.startLocation.line;+ } else if (startPos) {+ this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;+ if (this.options.locations) {+ this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;+ }+ } else {+ this.lineStart = 0;+ }+ this.type = types$1.eof;+ this.value = null;+ this.start = this.end = this.pos;+ this.startLoc = this.endLoc = this.curPosition();+ this.lastTokEndLoc = this.lastTokStartLoc = null;+ this.lastTokStart = this.lastTokEnd = this.pos;+ this.context = this.initialContext();+ this.exprAllowed = true;+ this.inModule = options.sourceType === "module";+ this.strict = this.inModule || options.strict === true || this.strictDirective(this.pos);+ this.potentialArrowAt = -1;+ this.potentialArrowInForAwait = false;+ this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;+ this.labels = [];+ this.undefinedExports = /* @__PURE__ */ Object.create(null);+ if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") {+ this.skipLineComment(2);+ }+ this.scopeStack = [];+ this.enterScope(+ this.options.sourceType === "commonjs" ? SCOPE_FUNCTION : SCOPE_TOP+ );+ this.regexpState = null;+ this.privateNameStack = [];+};+var prototypeAccessors = { inFunction: { configurable: true }, inGenerator: { configurable: true }, inAsync: { configurable: true }, canAwait: { configurable: true }, allowReturn: { configurable: true }, allowSuper: { configurable: true }, allowDirectSuper: { configurable: true }, treatFunctionsAsVar: { configurable: true }, allowNewDotTarget: { configurable: true }, allowUsing: { configurable: true }, inClassStaticBlock: { configurable: true } };+Parser.prototype.parse = function parse() {+ var this$1$1 = this;+ var node = this.options.program || this.startNode();+ this.nextToken();+ return this.catchStackOverflow(function() {+ return this$1$1.parseTopLevel(node);+ });+};+prototypeAccessors.inFunction.get = function() {+ return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0;+};+prototypeAccessors.inGenerator.get = function() {+ return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0;+};+prototypeAccessors.inAsync.get = function() {+ return (this.currentVarScope().flags & SCOPE_ASYNC) > 0;+};+prototypeAccessors.canAwait.get = function() {+ for (var i2 = this.scopeStack.length - 1; i2 >= 0; i2--) {+ var ref2 = this.scopeStack[i2];+ var flags = ref2.flags;+ if (flags & (SCOPE_CLASS_STATIC_BLOCK | SCOPE_CLASS_FIELD_INIT)) {+ return false;+ }+ if (flags & SCOPE_FUNCTION) {+ return (flags & SCOPE_ASYNC) > 0;+ }+ }+ return this.inModule && this.options.ecmaVersion >= 13 || this.options.allowAwaitOutsideFunction;+};+prototypeAccessors.allowReturn.get = function() {+ if (this.inFunction) {+ return true;+ }+ if (this.options.allowReturnOutsideFunction && this.currentVarScope().flags & SCOPE_TOP) {+ return true;+ }+ return false;+};+prototypeAccessors.allowSuper.get = function() {+ var ref2 = this.currentThisScope();+ var flags = ref2.flags;+ return (flags & SCOPE_SUPER) > 0 || this.options.allowSuperOutsideMethod;+};+prototypeAccessors.allowDirectSuper.get = function() {+ return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0;+};+prototypeAccessors.treatFunctionsAsVar.get = function() {+ return this.treatFunctionsAsVarInScope(this.currentScope());+};+prototypeAccessors.allowNewDotTarget.get = function() {+ for (var i2 = this.scopeStack.length - 1; i2 >= 0; i2--) {+ var ref2 = this.scopeStack[i2];+ var flags = ref2.flags;+ if (flags & (SCOPE_CLASS_STATIC_BLOCK | SCOPE_CLASS_FIELD_INIT) || flags & SCOPE_FUNCTION && !(flags & SCOPE_ARROW)) {+ return true;+ }+ }+ return false;+};+prototypeAccessors.allowUsing.get = function() {+ var ref2 = this.currentScope();+ var flags = ref2.flags;+ if (flags & SCOPE_SWITCH) {+ return false;+ }+ if (!this.inModule && flags & SCOPE_TOP) {+ return false;+ }+ return true;+};+prototypeAccessors.inClassStaticBlock.get = function() {+ return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0;+};+Parser.extend = function extend() {+ var plugins = [], len = arguments.length;+ while (len--) plugins[len] = arguments[len];+ var cls = this;+ for (var i2 = 0; i2 < plugins.length; i2++) {+ cls = plugins[i2](cls);+ }+ return cls;+};+Parser.parse = function parse2(input, options) {+ return new this(options, input).parse();+};+Parser.parseExpressionAt = function parseExpressionAt(input, pos, options) {+ var parser = new this(options, input, pos);+ parser.nextToken();+ return parser.parseExpression();+};+Parser.tokenizer = function tokenizer(input, options) {+ return new this(options, input);+};+Object.defineProperties(Parser.prototype, prototypeAccessors);+var pp$9 = Parser.prototype;+var literal = /^(?:'((?:\\[^]|[^'\\])*?)'|"((?:\\[^]|[^"\\])*?)")/;+pp$9.strictDirective = function(start) {+ if (this.options.ecmaVersion < 5) {+ return false;+ }+ for (; ; ) {+ skipWhiteSpace.lastIndex = start;+ start += skipWhiteSpace.exec(this.input)[0].length;+ var match = literal.exec(this.input.slice(start));+ if (!match) {+ return false;+ }+ if ((match[1] || match[2]) === "use strict") {+ skipWhiteSpace.lastIndex = start + match[0].length;+ var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;+ var next = this.input.charAt(end);+ return next === ";" || next === "}" || lineBreak.test(spaceAfter[0]) && !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=");+ }+ start += match[0].length;+ skipWhiteSpace.lastIndex = start;+ start += skipWhiteSpace.exec(this.input)[0].length;+ if (this.input[start] === ";") {+ start++;+ }+ }+};+pp$9.eat = function(type) {+ if (this.type === type) {+ this.next();+ return true;+ } else {+ return false;+ }+};+pp$9.isContextual = function(name) {+ return this.type === types$1.name && this.value === name && !this.containsEsc;+};+pp$9.eatContextual = function(name) {+ if (!this.isContextual(name)) {+ return false;+ }+ this.next();+ return true;+};+pp$9.catchStackOverflow = function(f) {+ try {+ return f();+ } catch (e) {+ if (e instanceof Error && (/\bstack\b.*\b(exceeded|overflow)\b/i.test(e.message) || /\btoo much recursion\b/i.test(e.message))) {+ this.raise(this.start, "Not enough stack space to parse input");+ } else {+ throw e;+ }+ }+};+pp$9.expectContextual = function(name) {+ if (!this.eatContextual(name)) {+ this.unexpected();+ }+};+pp$9.canInsertSemicolon = function() {+ return this.type === types$1.eof || this.type === types$1.braceR || lineBreak.test(this.input.slice(this.lastTokEnd, this.start));+};+pp$9.insertSemicolon = function() {+ if (this.canInsertSemicolon()) {+ if (this.options.onInsertedSemicolon) {+ this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc);+ }+ return true;+ }+};+pp$9.semicolon = function() {+ if (!this.eat(types$1.semi) && !this.insertSemicolon()) {+ this.unexpected();+ }+};+pp$9.afterTrailingComma = function(tokType, notNext) {+ if (this.type === tokType) {+ if (this.options.onTrailingComma) {+ this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc);+ }+ if (!notNext) {+ this.next();+ }+ return true;+ }+};+pp$9.expect = function(type) {+ this.eat(type) || this.unexpected();+};+pp$9.unexpected = function(pos) {+ this.raise(pos != null ? pos : this.start, "Unexpected token");+};+var DestructuringErrors = function DestructuringErrors2() {+ this.shorthandAssign = this.trailingComma = this.parenthesizedAssign = this.parenthesizedBind = this.doubleProto = -1;+};+pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) {+ if (!refDestructuringErrors) {+ return;+ }+ if (refDestructuringErrors.trailingComma > -1) {+ this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element");+ }+ var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;+ if (parens > -1) {+ this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern");+ }+};+pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) {+ if (!refDestructuringErrors) {+ return false;+ }+ var shorthandAssign = refDestructuringErrors.shorthandAssign;+ var doubleProto = refDestructuringErrors.doubleProto;+ if (!andThrow) {+ return shorthandAssign >= 0 || doubleProto >= 0;+ }+ if (shorthandAssign >= 0) {+ this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns");+ }+ if (doubleProto >= 0) {+ this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property");+ }+};+pp$9.checkYieldAwaitInDefaultParams = function() {+ if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) {+ this.raise(this.yieldPos, "Yield expression cannot be a default value");+ }+ if (this.awaitPos) {+ this.raise(this.awaitPos, "Await expression cannot be a default value");+ }+};+pp$9.isSimpleAssignTarget = function(expr) {+ if (expr.type === "ParenthesizedExpression") {+ return this.isSimpleAssignTarget(expr.expression);+ }+ return expr.type === "Identifier" || expr.type === "MemberExpression";+};+var pp$8 = Parser.prototype;+pp$8.parseTopLevel = function(node) {+ var exports$1 = /* @__PURE__ */ Object.create(null);+ if (!node.body) {+ node.body = [];+ }+ while (this.type !== types$1.eof) {+ var stmt = this.parseStatement(null, true, exports$1);+ node.body.push(stmt);+ }+ if (this.inModule) {+ for (var i2 = 0, list2 = Object.keys(this.undefinedExports); i2 < list2.length; i2 += 1) {+ var name = list2[i2];+ this.raiseRecoverable(this.undefinedExports[name].start, "Export '" + name + "' is not defined");+ }+ }+ this.adaptDirectivePrologue(node.body);+ this.next();+ node.sourceType = this.options.sourceType === "commonjs" ? "script" : this.options.sourceType;+ return this.finishNode(node, "Program");+};+var loopLabel = { kind: "loop" };+var switchLabel = { kind: "switch" };+pp$8.isLet = function(context) {+ if (this.options.ecmaVersion < 6 || !this.isContextual("let")) {+ return false;+ }+ skipWhiteSpace.lastIndex = this.pos;+ var skip = skipWhiteSpace.exec(this.input);+ var next = this.pos + skip[0].length, nextCh = this.fullCharCodeAt(next);+ if (nextCh === 91 || nextCh === 92) {+ return true;+ }+ if (context) {+ return false;+ }+ if (nextCh === 123) {+ return true;+ }+ if (isIdentifierStart(nextCh)) {+ var start = next;+ do {+ next += nextCh <= 65535 ? 1 : 2;+ } while (isIdentifierChar(nextCh = this.fullCharCodeAt(next)));+ if (nextCh === 92) {+ return true;+ }+ var ident = this.input.slice(start, next);+ if (!keywordRelationalOperator.test(ident)) {+ return true;+ }+ }+ return false;+};+pp$8.isAsyncFunction = function() {+ if (this.options.ecmaVersion < 8 || !this.isContextual("async")) {+ return false;+ }+ skipWhiteSpace.lastIndex = this.pos;+ var skip = skipWhiteSpace.exec(this.input);+ var next = this.pos + skip[0].length, after;+ return !lineBreak.test(this.input.slice(this.pos, next)) && this.input.slice(next, next + 8) === "function" && (next + 8 === this.input.length || !(isIdentifierChar(after = this.fullCharCodeAt(next + 8)) || after === 92));+};+pp$8.isUsingKeyword = function(isAwaitUsing, isFor) {+ if (this.options.ecmaVersion < 17 || !this.isContextual(isAwaitUsing ? "await" : "using")) {+ return false;+ }+ skipWhiteSpace.lastIndex = this.pos;+ var skip = skipWhiteSpace.exec(this.input);+ var next = this.pos + skip[0].length;+ if (lineBreak.test(this.input.slice(this.pos, next))) {+ return false;+ }+ if (isAwaitUsing) {+ var usingEndPos = next + 5, after;+ if (this.input.slice(next, usingEndPos) !== "using" || usingEndPos === this.input.length || isIdentifierChar(after = this.fullCharCodeAt(usingEndPos)) || after === 92) {+ return false;+ }+ skipWhiteSpace.lastIndex = usingEndPos;+ var skipAfterUsing = skipWhiteSpace.exec(this.input);+ next = usingEndPos + skipAfterUsing[0].length;+ if (skipAfterUsing && lineBreak.test(this.input.slice(usingEndPos, next))) {+ return false;+ }+ }+ var ch = this.fullCharCodeAt(next);+ if (!isIdentifierStart(ch) && ch !== 92) {+ return false;+ }+ var idStart = next;+ do {+ next += ch <= 65535 ? 1 : 2;+ } while (isIdentifierChar(ch = this.fullCharCodeAt(next)));+ if (ch === 92) {+ return true;+ }+ var id = this.input.slice(idStart, next);+ if (keywordRelationalOperator.test(id)) {+ return false;+ }+ if (isFor && !isAwaitUsing && id === "of") {+ skipWhiteSpace.lastIndex = next;+ var skipAfterOf = skipWhiteSpace.exec(this.input);+ next = next + skipAfterOf[0].length;+ if (this.input.charCodeAt(next) !== 61 || // Check for ==, === and => operators+ (ch = this.input.charCodeAt(next + 1)) === 61 || ch === 62) {+ return false;+ }+ }+ return true;+};+pp$8.isAwaitUsing = function(isFor) {+ return this.isUsingKeyword(true, isFor);+};+pp$8.isUsing = function(isFor) {+ return this.isUsingKeyword(false, isFor);+};+pp$8.parseStatement = function(context, topLevel, exports$1) {+ var starttype = this.type, node = this.startNode(), kind;+ if (this.isLet(context)) {+ starttype = types$1._var;+ kind = "let";+ }+ switch (starttype) {+ case types$1._break:+ case types$1._continue:+ return this.parseBreakContinueStatement(node, starttype.keyword);+ case types$1._debugger:+ return this.parseDebuggerStatement(node);+ case types$1._do:+ return this.parseDoStatement(node);+ case types$1._for:+ return this.parseForStatement(node);+ case types$1._function:+ if (context && (this.strict || context !== "if" && context !== "label") && this.options.ecmaVersion >= 6) {+ this.unexpected();+ }+ return this.parseFunctionStatement(node, false, !context);+ case types$1._class:+ if (context) {+ this.unexpected();+ }+ return this.parseClass(node, true);+ case types$1._if:+ return this.parseIfStatement(node);+ case types$1._return:+ return this.parseReturnStatement(node);+ case types$1._switch:+ return this.parseSwitchStatement(node);+ case types$1._throw:+ return this.parseThrowStatement(node);+ case types$1._try:+ return this.parseTryStatement(node);+ case types$1._const:+ case types$1._var:+ kind = kind || this.value;+ if (context && kind !== "var") {+ this.unexpected();+ }+ return this.parseVarStatement(node, kind);+ case types$1._while:+ return this.parseWhileStatement(node);+ case types$1._with:+ return this.parseWithStatement(node);+ case types$1.braceL:+ return this.parseBlock(true, node);+ case types$1.semi:+ return this.parseEmptyStatement(node);+ case types$1._export:+ case types$1._import:+ if (this.options.ecmaVersion > 10 && starttype === types$1._import) {+ skipWhiteSpace.lastIndex = this.pos;+ var skip = skipWhiteSpace.exec(this.input);+ var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);+ if (nextCh === 40 || nextCh === 46) {+ return this.parseExpressionStatement(node, this.parseExpression());+ }+ }+ if (!this.options.allowImportExportEverywhere) {+ if (!topLevel) {+ this.raise(this.start, "'import' and 'export' may only appear at the top level");+ }+ if (!this.inModule) {+ this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'");+ }+ }+ return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports$1);+ // If the statement does not start with a statement keyword or a+ // brace, it's an ExpressionStatement or LabeledStatement. We+ // simply start parsing an expression, and afterwards, if the+ // next token is a colon and the expression was a simple+ // Identifier node, we switch to interpreting it as a label.+ default:+ if (this.isAsyncFunction()) {+ if (context) {+ this.unexpected();+ }+ this.next();+ return this.parseFunctionStatement(node, true, !context);+ }+ var usingKind = this.isAwaitUsing(false) ? "await using" : this.isUsing(false) ? "using" : null;+ if (usingKind) {+ if (!this.allowUsing) {+ this.raise(this.start, "Using declaration cannot appear in the top level when source type is `script` or in the bare case statement");+ }+ if (context) {+ this.raise(this.start, "Using declaration is not allowed in single-statement positions");+ }+ if (usingKind === "await using") {+ if (!this.canAwait) {+ this.raise(this.start, "Await using cannot appear outside of async function");+ }+ this.next();+ }+ this.next();+ this.parseVar(node, false, usingKind);+ this.semicolon();+ return this.finishNode(node, "VariableDeclaration");+ }+ var maybeName = this.value, expr = this.parseExpression();+ if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon)) {+ return this.parseLabeledStatement(node, maybeName, expr, context);+ } else {+ return this.parseExpressionStatement(node, expr);+ }+ }+};+pp$8.parseBreakContinueStatement = function(node, keyword) {+ var isBreak = keyword === "break";+ this.next();+ if (this.eat(types$1.semi) || this.insertSemicolon()) {+ node.label = null;+ } else if (this.type !== types$1.name) {+ this.unexpected();+ } else {+ node.label = this.parseIdent();+ this.semicolon();+ }+ var i2 = 0;+ for (; i2 < this.labels.length; ++i2) {+ var lab = this.labels[i2];+ if (node.label == null || lab.name === node.label.name) {+ if (lab.kind != null && (isBreak || lab.kind === "loop")) {+ break;+ }+ if (node.label && isBreak) {+ break;+ }+ }+ }+ if (i2 === this.labels.length) {+ this.raise(node.start, "Unsyntactic " + keyword);+ }+ return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");+};+pp$8.parseDebuggerStatement = function(node) {+ this.next();+ this.semicolon();+ return this.finishNode(node, "DebuggerStatement");+};+pp$8.parseDoStatement = function(node) {+ this.next();+ this.labels.push(loopLabel);+ node.body = this.parseStatement("do");+ this.labels.pop();+ this.expect(types$1._while);+ node.test = this.parseParenExpression();+ if (this.options.ecmaVersion >= 6) {+ this.eat(types$1.semi);+ } else {+ this.semicolon();+ }+ return this.finishNode(node, "DoWhileStatement");+};+pp$8.parseForStatement = function(node) {+ this.next();+ var awaitAt = this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await") ? this.lastTokStart : -1;+ this.labels.push(loopLabel);+ this.enterScope(0);+ this.expect(types$1.parenL);+ if (this.type === types$1.semi) {+ if (awaitAt > -1) {+ this.unexpected(awaitAt);+ }+ return this.parseFor(node, null);+ }+ var isLet = this.isLet();+ if (this.type === types$1._var || this.type === types$1._const || isLet) {+ var init$1 = this.startNode(), kind = isLet ? "let" : this.value;+ this.next();+ this.parseVar(init$1, true, kind);+ this.finishNode(init$1, "VariableDeclaration");+ return this.parseForAfterInit(node, init$1, awaitAt);+ }+ var startsWithLet = this.isContextual("let"), isForOf = false;+ var usingKind = this.isUsing(true) ? "using" : this.isAwaitUsing(true) ? "await using" : null;+ if (usingKind) {+ var init$2 = this.startNode();+ this.next();+ if (usingKind === "await using") {+ if (!this.canAwait) {+ this.raise(this.start, "Await using cannot appear outside of async function");+ }+ this.next();+ }+ this.parseVar(init$2, true, usingKind);+ this.finishNode(init$2, "VariableDeclaration");+ return this.parseForAfterInit(node, init$2, awaitAt);+ }+ var containsEsc = this.containsEsc;+ var refDestructuringErrors = new DestructuringErrors();+ var initPos = this.start;+ var init = awaitAt > -1 ? this.parseExprSubscripts(refDestructuringErrors, "await") : this.parseExpression(true, refDestructuringErrors);+ if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) {+ if (awaitAt > -1) {+ if (this.type === types$1._in) {+ this.unexpected(awaitAt);+ }+ node.await = true;+ } else if (isForOf && this.options.ecmaVersion >= 8) {+ if (init.start === initPos && !containsEsc && init.type === "Identifier" && init.name === "async") {+ this.unexpected();+ } else if (this.options.ecmaVersion >= 9) {+ node.await = false;+ }+ }+ if (startsWithLet && isForOf) {+ this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'.");+ }+ this.toAssignable(init, false, refDestructuringErrors);+ this.checkLValPattern(init);+ return this.parseForIn(node, init);+ } else {+ this.checkExpressionErrors(refDestructuringErrors, true);+ }+ if (awaitAt > -1) {+ this.unexpected(awaitAt);+ }+ return this.parseFor(node, init);+};+pp$8.parseForAfterInit = function(node, init, awaitAt) {+ if ((this.type === types$1._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) && init.declarations.length === 1) {+ if (this.type === types$1._in) {+ if ((init.kind === "using" || init.kind === "await using") && !init.declarations[0].init) {+ this.raise(this.start, "Using declaration is not allowed in for-in loops");+ }+ if (this.options.ecmaVersion >= 9 && awaitAt > -1) {+ this.unexpected(awaitAt);+ }+ } else if (this.options.ecmaVersion >= 9) {+ node.await = awaitAt > -1;+ }+ return this.parseForIn(node, init);+ }+ if (awaitAt > -1) {+ this.unexpected(awaitAt);+ }+ return this.parseFor(node, init);+};+pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) {+ this.next();+ return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync);+};+pp$8.parseIfStatement = function(node) {+ this.next();+ node.test = this.parseParenExpression();+ node.consequent = this.parseStatement("if");+ node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null;+ return this.finishNode(node, "IfStatement");+};+pp$8.parseReturnStatement = function(node) {+ if (!this.allowReturn) {+ this.raise(this.start, "'return' outside of function");+ }+ this.next();+ if (this.eat(types$1.semi) || this.insertSemicolon()) {+ node.argument = null;+ } else {+ node.argument = this.parseExpression();+ this.semicolon();+ }+ return this.finishNode(node, "ReturnStatement");+};+pp$8.parseSwitchStatement = function(node) {+ this.next();+ node.discriminant = this.parseParenExpression();+ node.cases = [];+ this.expect(types$1.braceL);+ this.labels.push(switchLabel);+ this.enterScope(SCOPE_SWITCH);+ var cur;+ for (var sawDefault = false; this.type !== types$1.braceR; ) {+ if (this.type === types$1._case || this.type === types$1._default) {+ var isCase = this.type === types$1._case;+ if (cur) {+ this.finishNode(cur, "SwitchCase");+ }+ node.cases.push(cur = this.startNode());+ cur.consequent = [];+ this.next();+ if (isCase) {+ cur.test = this.parseExpression();+ } else {+ if (sawDefault) {+ this.raiseRecoverable(this.lastTokStart, "Multiple default clauses");+ }+ sawDefault = true;+ cur.test = null;+ }+ this.expect(types$1.colon);+ } else {+ if (!cur) {+ this.unexpected();+ }+ cur.consequent.push(this.parseStatement(null));+ }+ }+ this.exitScope();+ if (cur) {+ this.finishNode(cur, "SwitchCase");+ }+ this.next();+ this.labels.pop();+ return this.finishNode(node, "SwitchStatement");+};+pp$8.parseThrowStatement = function(node) {+ this.next();+ if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) {+ this.raise(this.lastTokEnd, "Illegal newline after throw");+ }+ node.argument = this.parseExpression();+ this.semicolon();+ return this.finishNode(node, "ThrowStatement");+};+var empty$1 = [];+pp$8.parseCatchClauseParam = function() {+ var param = this.parseBindingAtom();+ var simple = param.type === "Identifier";+ this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);+ this.checkLValPattern(param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);+ this.expect(types$1.parenR);+ return param;+};+pp$8.parseTryStatement = function(node) {+ this.next();+ node.block = this.parseBlock();+ node.handler = null;+ if (this.type === types$1._catch) {+ var clause = this.startNode();+ this.next();+ if (this.eat(types$1.parenL)) {+ clause.param = this.parseCatchClauseParam();+ } else {+ if (this.options.ecmaVersion < 10) {+ this.unexpected();+ }+ clause.param = null;+ this.enterScope(0);+ }+ clause.body = this.parseBlock(false);+ this.exitScope();+ node.handler = this.finishNode(clause, "CatchClause");+ }+ node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null;+ if (!node.handler && !node.finalizer) {+ this.raise(node.start, "Missing catch or finally clause");+ }+ return this.finishNode(node, "TryStatement");+};+pp$8.parseVarStatement = function(node, kind, allowMissingInitializer) {+ this.next();+ this.parseVar(node, false, kind, allowMissingInitializer);+ this.semicolon();+ return this.finishNode(node, "VariableDeclaration");+};+pp$8.parseWhileStatement = function(node) {+ this.next();+ node.test = this.parseParenExpression();+ this.labels.push(loopLabel);+ node.body = this.parseStatement("while");+ this.labels.pop();+ return this.finishNode(node, "WhileStatement");+};+pp$8.parseWithStatement = function(node) {+ if (this.strict) {+ this.raise(this.start, "'with' in strict mode");+ }+ this.next();+ node.object = this.parseParenExpression();+ node.body = this.parseStatement("with");+ return this.finishNode(node, "WithStatement");+};+pp$8.parseEmptyStatement = function(node) {+ this.next();+ return this.finishNode(node, "EmptyStatement");+};+pp$8.parseLabeledStatement = function(node, maybeName, expr, context) {+ for (var i$1 = 0, list2 = this.labels; i$1 < list2.length; i$1 += 1) {+ var label = list2[i$1];+ if (label.name === maybeName) {+ this.raise(expr.start, "Label '" + maybeName + "' is already declared");+ }+ }+ var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null;+ for (var i2 = this.labels.length - 1; i2 >= 0; i2--) {+ var label$1 = this.labels[i2];+ if (label$1.statementStart === node.start) {+ label$1.statementStart = this.start;+ label$1.kind = kind;+ } else {+ break;+ }+ }+ this.labels.push({ name: maybeName, kind, statementStart: this.start });+ node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");+ this.labels.pop();+ node.label = expr;+ return this.finishNode(node, "LabeledStatement");+};+pp$8.parseExpressionStatement = function(node, expr) {+ node.expression = expr;+ this.semicolon();+ return this.finishNode(node, "ExpressionStatement");+};+pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) {+ if (createNewLexicalScope === void 0) createNewLexicalScope = true;+ if (node === void 0) node = this.startNode();+ node.body = [];+ this.expect(types$1.braceL);+ if (createNewLexicalScope) {+ this.enterScope(0);+ }+ while (this.type !== types$1.braceR) {+ var stmt = this.parseStatement(null);+ node.body.push(stmt);+ }+ if (exitStrict) {+ this.strict = false;+ }+ this.next();+ if (createNewLexicalScope) {+ this.exitScope();+ }+ return this.finishNode(node, "BlockStatement");+};+pp$8.parseFor = function(node, init) {+ node.init = init;+ this.expect(types$1.semi);+ node.test = this.type === types$1.semi ? null : this.parseExpression();+ this.expect(types$1.semi);+ node.update = this.type === types$1.parenR ? null : this.parseExpression();+ this.expect(types$1.parenR);+ node.body = this.parseStatement("for");+ this.exitScope();+ this.labels.pop();+ return this.finishNode(node, "ForStatement");+};+pp$8.parseForIn = function(node, init) {+ var isForIn = this.type === types$1._in;+ this.next();+ if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.options.ecmaVersion < 8 || this.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) {+ this.raise(+ init.start,+ (isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer"+ );+ }+ node.left = init;+ node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();+ this.expect(types$1.parenR);+ node.body = this.parseStatement("for");+ this.exitScope();+ this.labels.pop();+ return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");+};+pp$8.parseVar = function(node, isFor, kind, allowMissingInitializer) {+ node.declarations = [];+ node.kind = kind;+ for (; ; ) {+ var decl = this.startNode();+ this.parseVarId(decl, kind);+ if (this.eat(types$1.eq)) {+ decl.init = this.parseMaybeAssign(isFor);+ } else if (!allowMissingInitializer && kind === "const" && !(this.type === types$1._in || this.options.ecmaVersion >= 6 && this.isContextual("of"))) {+ this.unexpected();+ } else if (!allowMissingInitializer && (kind === "using" || kind === "await using") && this.options.ecmaVersion >= 17 && this.type !== types$1._in && !this.isContextual("of")) {+ this.raise(this.lastTokEnd, "Missing initializer in " + kind + " declaration");+ } else if (!allowMissingInitializer && decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) {+ this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");+ } else {+ decl.init = null;+ }+ node.declarations.push(this.finishNode(decl, "VariableDeclarator"));+ if (!this.eat(types$1.comma)) {+ break;+ }+ }+ return node;+};+pp$8.parseVarId = function(decl, kind) {+ decl.id = kind === "using" || kind === "await using" ? this.parseIdent() : this.parseBindingAtom();+ this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);+};+var FUNC_STATEMENT = 1;+var FUNC_HANGING_STATEMENT = 2;+var FUNC_NULLABLE_ID = 4;+pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) {+ this.initFunction(node);+ if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {+ if (this.type === types$1.star && statement & FUNC_HANGING_STATEMENT) {+ this.unexpected();+ }+ node.generator = this.eat(types$1.star);+ }+ if (this.options.ecmaVersion >= 8) {+ node.async = !!isAsync;+ }+ if (statement & FUNC_STATEMENT) {+ node.id = statement & FUNC_NULLABLE_ID && this.type !== types$1.name ? null : this.parseIdent();+ if (node.id && !(statement & FUNC_HANGING_STATEMENT)) {+ this.checkLValSimple(node.id, this.strict || node.generator || node.async ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION);+ }+ }+ var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;+ this.yieldPos = 0;+ this.awaitPos = 0;+ this.awaitIdentPos = 0;+ this.enterScope(functionFlags(node.async, node.generator));+ if (!(statement & FUNC_STATEMENT)) {+ node.id = this.type === types$1.name ? this.parseIdent() : null;+ }+ this.parseFunctionParams(node);+ this.parseFunctionBody(node, allowExpressionBody, false, forInit);+ this.yieldPos = oldYieldPos;+ this.awaitPos = oldAwaitPos;+ this.awaitIdentPos = oldAwaitIdentPos;+ return this.finishNode(node, statement & FUNC_STATEMENT ? "FunctionDeclaration" : "FunctionExpression");+};+pp$8.parseFunctionParams = function(node) {+ this.expect(types$1.parenL);+ node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);+ this.checkYieldAwaitInDefaultParams();+};+pp$8.parseClass = function(node, isStatement) {+ this.next();+ var oldStrict = this.strict;+ this.strict = true;+ this.parseClassId(node, isStatement);+ this.parseClassSuper(node);+ var privateNameMap = this.enterClassBody();+ var classBody = this.startNode();+ var hadConstructor = false;+ classBody.body = [];+ this.expect(types$1.braceL);+ while (this.type !== types$1.braceR) {+ var element = this.parseClassElement(node.superClass !== null);+ if (element) {+ classBody.body.push(element);+ if (element.type === "MethodDefinition" && element.kind === "constructor") {+ if (hadConstructor) {+ this.raiseRecoverable(element.start, "Duplicate constructor in the same class");+ }+ hadConstructor = true;+ } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {+ this.raiseRecoverable(element.key.start, "Identifier '#" + element.key.name + "' has already been declared");+ }+ }+ }+ this.strict = oldStrict;+ this.next();+ node.body = this.finishNode(classBody, "ClassBody");+ this.exitClassBody();+ return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");+};+pp$8.parseClassElement = function(constructorAllowsSuper) {+ if (this.eat(types$1.semi)) {+ return null;+ }+ var ecmaVersion2 = this.options.ecmaVersion;+ var node = this.startNode();+ var keyName = "";+ var isGenerator = false;+ var isAsync = false;+ var kind = "method";+ var isStatic = false;+ if (this.eatContextual("static")) {+ if (ecmaVersion2 >= 13 && this.eat(types$1.braceL)) {+ this.parseClassStaticBlock(node);+ return node;+ }+ if (this.isClassElementNameStart() || this.type === types$1.star) {+ isStatic = true;+ } else {+ keyName = "static";+ }+ }+ node.static = isStatic;+ if (!keyName && ecmaVersion2 >= 8 && this.eatContextual("async")) {+ if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) {+ isAsync = true;+ } else {+ keyName = "async";+ }+ }+ if (!keyName && (ecmaVersion2 >= 9 || !isAsync) && this.eat(types$1.star)) {+ isGenerator = true;+ }+ if (!keyName && !isAsync && !isGenerator) {+ var lastValue = this.value;+ if (this.eatContextual("get") || this.eatContextual("set")) {+ if (this.isClassElementNameStart()) {+ kind = lastValue;+ } else {+ keyName = lastValue;+ }+ }+ }+ if (keyName) {+ node.computed = false;+ node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);+ node.key.name = keyName;+ this.finishNode(node.key, "Identifier");+ } else {+ this.parseClassElementName(node);+ }+ if (ecmaVersion2 < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) {+ var isConstructor = !node.static && checkKeyName(node, "constructor");+ var allowsDirectSuper = isConstructor && constructorAllowsSuper;+ if (isConstructor && kind !== "method") {+ this.raise(node.key.start, "Constructor can't have get/set modifier");+ }+ node.kind = isConstructor ? "constructor" : kind;+ this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);+ } else {+ this.parseClassField(node);+ }+ return node;+};+pp$8.isClassElementNameStart = function() {+ return this.type === types$1.name || this.type === types$1.privateId || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword;+};+pp$8.parseClassElementName = function(element) {+ if (this.type === types$1.privateId) {+ if (this.value === "constructor") {+ this.raise(this.start, "Classes can't have an element named '#constructor'");+ }+ element.computed = false;+ element.key = this.parsePrivateIdent();+ } else {+ this.parsePropertyName(element);+ }+};+pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {+ var key = method.key;+ if (method.kind === "constructor") {+ if (isGenerator) {+ this.raise(key.start, "Constructor can't be a generator");+ }+ if (isAsync) {+ this.raise(key.start, "Constructor can't be an async method");+ }+ } else if (method.static && checkKeyName(method, "prototype")) {+ this.raise(key.start, "Classes may not have a static property named prototype");+ }+ var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);+ if (method.kind === "get" && value.params.length !== 0) {+ this.raiseRecoverable(value.start, "getter should have no params");+ }+ if (method.kind === "set" && value.params.length !== 1) {+ this.raiseRecoverable(value.start, "setter should have exactly one param");+ }+ if (method.kind === "set" && value.params[0].type === "RestElement") {+ this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params");+ }+ return this.finishNode(method, "MethodDefinition");+};+pp$8.parseClassField = function(field) {+ if (checkKeyName(field, "constructor")) {+ this.raise(field.key.start, "Classes can't have a field named 'constructor'");+ } else if (field.static && checkKeyName(field, "prototype")) {+ this.raise(field.key.start, "Classes can't have a static field named 'prototype'");+ }+ if (this.eat(types$1.eq)) {+ this.enterScope(SCOPE_CLASS_FIELD_INIT | SCOPE_SUPER);+ field.value = this.parseMaybeAssign();+ this.exitScope();+ } else {+ field.value = null;+ }+ this.semicolon();+ return this.finishNode(field, "PropertyDefinition");+};+pp$8.parseClassStaticBlock = function(node) {+ node.body = [];+ var oldLabels = this.labels;+ this.labels = [];+ this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER);+ while (this.type !== types$1.braceR) {+ var stmt = this.parseStatement(null);+ node.body.push(stmt);+ }+ this.next();+ this.exitScope();+ this.labels = oldLabels;+ return this.finishNode(node, "StaticBlock");+};+pp$8.parseClassId = function(node, isStatement) {+ if (this.type === types$1.name) {+ node.id = this.parseIdent();+ if (isStatement) {+ this.checkLValSimple(node.id, BIND_LEXICAL, false);+ }+ } else {+ if (isStatement === true) {+ this.unexpected();+ }+ node.id = null;+ }+};+pp$8.parseClassSuper = function(node) {+ node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(null, false) : null;+};+pp$8.enterClassBody = function() {+ var element = { declared: /* @__PURE__ */ Object.create(null), used: [] };+ this.privateNameStack.push(element);+ return element.declared;+};+pp$8.exitClassBody = function() {+ var ref2 = this.privateNameStack.pop();+ var declared = ref2.declared;+ var used = ref2.used;+ if (!this.options.checkPrivateFields) {+ return;+ }+ var len = this.privateNameStack.length;+ var parent = len === 0 ? null : this.privateNameStack[len - 1];+ for (var i2 = 0; i2 < used.length; ++i2) {+ var id = used[i2];+ if (!hasOwn(declared, id.name)) {+ if (parent) {+ parent.used.push(id);+ } else {+ this.raiseRecoverable(id.start, "Private field '#" + id.name + "' must be declared in an enclosing class");+ }+ }+ }+};+function isPrivateNameConflicted(privateNameMap, element) {+ var name = element.key.name;+ var curr = privateNameMap[name];+ var next = "true";+ if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {+ next = (element.static ? "s" : "i") + element.kind;+ }+ if (curr === "iget" && next === "iset" || curr === "iset" && next === "iget" || curr === "sget" && next === "sset" || curr === "sset" && next === "sget") {+ privateNameMap[name] = "true";+ return false;+ } else if (!curr) {+ privateNameMap[name] = next;+ return false;+ } else {+ return true;+ }+}+function checkKeyName(node, name) {+ var computed = node.computed;+ var key = node.key;+ return !computed && (key.type === "Identifier" && key.name === name || key.type === "Literal" && key.value === name);+}+pp$8.parseExportAllDeclaration = function(node, exports$1) {+ if (this.options.ecmaVersion >= 11) {+ if (this.eatContextual("as")) {+ node.exported = this.parseModuleExportName();+ this.checkExport(exports$1, node.exported, this.lastTokStart);+ } else {+ node.exported = null;+ }+ }+ this.expectContextual("from");+ if (this.type !== types$1.string) {+ this.unexpected();+ }+ node.source = this.parseExprAtom();+ if (this.options.ecmaVersion >= 16) {+ node.attributes = this.parseWithClause();+ }+ this.semicolon();+ return this.finishNode(node, "ExportAllDeclaration");+};+pp$8.parseExport = function(node, exports$1) {+ this.next();+ if (this.eat(types$1.star)) {+ return this.parseExportAllDeclaration(node, exports$1);+ }+ if (this.eat(types$1._default)) {+ this.checkExport(exports$1, "default", this.lastTokStart);+ node.declaration = this.parseExportDefaultDeclaration();+ return this.finishNode(node, "ExportDefaultDeclaration");+ }+ if (this.shouldParseExportStatement()) {+ node.declaration = this.parseExportDeclaration(node);+ if (node.declaration.type === "VariableDeclaration") {+ this.checkVariableExport(exports$1, node.declaration.declarations);+ } else {+ this.checkExport(exports$1, node.declaration.id, node.declaration.id.start);+ }+ node.specifiers = [];+ node.source = null;+ if (this.options.ecmaVersion >= 16) {+ node.attributes = [];+ }+ } else {+ node.declaration = null;+ node.specifiers = this.parseExportSpecifiers(exports$1);+ if (this.eatContextual("from")) {+ if (this.type !== types$1.string) {+ this.unexpected();+ }+ node.source = this.parseExprAtom();+ if (this.options.ecmaVersion >= 16) {+ node.attributes = this.parseWithClause();+ }+ } else {+ for (var i2 = 0, list2 = node.specifiers; i2 < list2.length; i2 += 1) {+ var spec = list2[i2];+ this.checkUnreserved(spec.local);+ this.checkLocalExport(spec.local);+ if (spec.local.type === "Literal") {+ this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`.");+ }+ }+ node.source = null;+ if (this.options.ecmaVersion >= 16) {+ node.attributes = [];+ }+ }+ this.semicolon();+ }+ return this.finishNode(node, "ExportNamedDeclaration");+};+pp$8.parseExportDeclaration = function(node) {+ return this.parseStatement(null);+};+pp$8.parseExportDefaultDeclaration = function() {+ var isAsync;+ if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) {+ var fNode = this.startNode();+ this.next();+ if (isAsync) {+ this.next();+ }+ return this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);+ } else if (this.type === types$1._class) {+ var cNode = this.startNode();+ return this.parseClass(cNode, "nullableID");+ } else {+ var declaration = this.parseMaybeAssign();+ this.semicolon();+ return declaration;+ }+};+pp$8.checkExport = function(exports$1, name, pos) {+ if (!exports$1) {+ return;+ }+ if (typeof name !== "string") {+ name = name.type === "Identifier" ? name.name : name.value;+ }+ if (hasOwn(exports$1, name)) {+ this.raiseRecoverable(pos, "Duplicate export '" + name + "'");+ }+ exports$1[name] = true;+};+pp$8.checkPatternExport = function(exports$1, pat) {+ var type = pat.type;+ if (type === "Identifier") {+ this.checkExport(exports$1, pat, pat.start);+ } else if (type === "ObjectPattern") {+ for (var i2 = 0, list2 = pat.properties; i2 < list2.length; i2 += 1) {+ var prop = list2[i2];+ this.checkPatternExport(exports$1, prop);+ }+ } else if (type === "ArrayPattern") {+ for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {+ var elt = list$1[i$1];+ if (elt) {+ this.checkPatternExport(exports$1, elt);+ }+ }+ } else if (type === "Property") {+ this.checkPatternExport(exports$1, pat.value);+ } else if (type === "AssignmentPattern") {+ this.checkPatternExport(exports$1, pat.left);+ } else if (type === "RestElement") {+ this.checkPatternExport(exports$1, pat.argument);+ }+};+pp$8.checkVariableExport = function(exports$1, decls) {+ if (!exports$1) {+ return;+ }+ for (var i2 = 0, list2 = decls; i2 < list2.length; i2 += 1) {+ var decl = list2[i2];+ this.checkPatternExport(exports$1, decl.id);+ }+};+pp$8.shouldParseExportStatement = function() {+ return this.type.keyword === "var" || this.type.keyword === "const" || this.type.keyword === "class" || this.type.keyword === "function" || this.isLet() || this.isAsyncFunction();+};+pp$8.parseExportSpecifier = function(exports$1) {+ var node = this.startNode();+ node.local = this.parseModuleExportName();+ node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local;+ this.checkExport(+ exports$1,+ node.exported,+ node.exported.start+ );+ return this.finishNode(node, "ExportSpecifier");+};+pp$8.parseExportSpecifiers = function(exports$1) {+ var nodes = [], first = true;+ this.expect(types$1.braceL);+ while (!this.eat(types$1.braceR)) {+ if (!first) {+ this.expect(types$1.comma);+ if (this.afterTrailingComma(types$1.braceR)) {+ break;+ }+ } else {+ first = false;+ }+ nodes.push(this.parseExportSpecifier(exports$1));+ }+ return nodes;+};+pp$8.parseImport = function(node) {+ this.next();+ if (this.type === types$1.string) {+ node.specifiers = empty$1;+ node.source = this.parseExprAtom();+ } else {+ node.specifiers = this.parseImportSpecifiers();+ this.expectContextual("from");+ node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected();+ }+ if (this.options.ecmaVersion >= 16) {+ node.attributes = this.parseWithClause();+ }+ this.semicolon();+ return this.finishNode(node, "ImportDeclaration");+};+pp$8.parseImportSpecifier = function() {+ var node = this.startNode();+ node.imported = this.parseModuleExportName();+ if (this.eatContextual("as")) {+ node.local = this.parseIdent();+ } else {+ this.checkUnreserved(node.imported);+ node.local = node.imported;+ }+ this.checkLValSimple(node.local, BIND_LEXICAL);+ return this.finishNode(node, "ImportSpecifier");+};+pp$8.parseImportDefaultSpecifier = function() {+ var node = this.startNode();+ node.local = this.parseIdent();+ this.checkLValSimple(node.local, BIND_LEXICAL);+ return this.finishNode(node, "ImportDefaultSpecifier");+};+pp$8.parseImportNamespaceSpecifier = function() {+ var node = this.startNode();+ this.next();+ this.expectContextual("as");+ node.local = this.parseIdent();+ this.checkLValSimple(node.local, BIND_LEXICAL);+ return this.finishNode(node, "ImportNamespaceSpecifier");+};+pp$8.parseImportSpecifiers = function() {+ var nodes = [], first = true;+ if (this.type === types$1.name) {+ nodes.push(this.parseImportDefaultSpecifier());+ if (!this.eat(types$1.comma)) {+ return nodes;+ }+ }+ if (this.type === types$1.star) {+ nodes.push(this.parseImportNamespaceSpecifier());+ return nodes;+ }+ this.expect(types$1.braceL);+ while (!this.eat(types$1.braceR)) {+ if (!first) {+ this.expect(types$1.comma);+ if (this.afterTrailingComma(types$1.braceR)) {+ break;+ }+ } else {+ first = false;+ }+ nodes.push(this.parseImportSpecifier());+ }+ return nodes;+};+pp$8.parseWithClause = function() {+ var nodes = [];+ if (!this.eat(types$1._with)) {+ return nodes;+ }+ this.expect(types$1.braceL);+ var attributeKeys = {};+ var first = true;+ while (!this.eat(types$1.braceR)) {+ if (!first) {+ this.expect(types$1.comma);+ if (this.afterTrailingComma(types$1.braceR)) {+ break;+ }+ } else {+ first = false;+ }+ var attr = this.parseImportAttribute();+ var keyName = attr.key.type === "Identifier" ? attr.key.name : attr.key.value;+ if (hasOwn(attributeKeys, keyName)) {+ this.raiseRecoverable(attr.key.start, "Duplicate attribute key '" + keyName + "'");+ }+ attributeKeys[keyName] = true;+ nodes.push(attr);+ }+ return nodes;+};+pp$8.parseImportAttribute = function() {+ var node = this.startNode();+ node.key = this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never");+ this.expect(types$1.colon);+ if (this.type !== types$1.string) {+ this.unexpected();+ }+ node.value = this.parseExprAtom();+ return this.finishNode(node, "ImportAttribute");+};+pp$8.parseModuleExportName = function() {+ if (this.options.ecmaVersion >= 13 && this.type === types$1.string) {+ var stringLiteral = this.parseLiteral(this.value);+ if (loneSurrogate.test(stringLiteral.value)) {+ this.raise(stringLiteral.start, "An export name cannot include a lone surrogate.");+ }+ return stringLiteral;+ }+ return this.parseIdent(true);+};+pp$8.adaptDirectivePrologue = function(statements) {+ for (var i2 = 0; i2 < statements.length && this.isDirectiveCandidate(statements[i2]); ++i2) {+ statements[i2].directive = statements[i2].expression.raw.slice(1, -1);+ }+};+pp$8.isDirectiveCandidate = function(statement) {+ return this.options.ecmaVersion >= 5 && statement.type === "ExpressionStatement" && statement.expression.type === "Literal" && typeof statement.expression.value === "string" && // Reject parenthesized strings.+ (this.input[statement.start] === '"' || this.input[statement.start] === "'");+};+var pp$7 = Parser.prototype;+pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) {+ if (this.options.ecmaVersion >= 6 && node) {+ switch (node.type) {+ case "Identifier":+ if (this.inAsync && node.name === "await") {+ this.raise(node.start, "Cannot use 'await' as identifier inside an async function");+ }+ break;+ case "ObjectPattern":+ case "ArrayPattern":+ case "AssignmentPattern":+ case "RestElement":+ break;+ case "ObjectExpression":+ node.type = "ObjectPattern";+ if (refDestructuringErrors) {+ this.checkPatternErrors(refDestructuringErrors, true);+ }+ for (var i2 = 0, list2 = node.properties; i2 < list2.length; i2 += 1) {+ var prop = list2[i2];+ this.toAssignable(prop, isBinding);+ if (prop.type === "RestElement" && (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")) {+ this.raise(prop.argument.start, "Unexpected token");+ }+ }+ break;+ case "Property":+ if (node.kind !== "init") {+ this.raise(node.key.start, "Object pattern can't contain getter or setter");+ }+ this.toAssignable(node.value, isBinding);+ break;+ case "ArrayExpression":+ node.type = "ArrayPattern";+ if (refDestructuringErrors) {+ this.checkPatternErrors(refDestructuringErrors, true);+ }+ this.toAssignableList(node.elements, isBinding);+ break;+ case "SpreadElement":+ node.type = "RestElement";+ this.toAssignable(node.argument, isBinding);+ if (node.argument.type === "AssignmentPattern") {+ this.raise(node.argument.start, "Rest elements cannot have a default value");+ }+ break;+ case "AssignmentExpression":+ if (node.operator !== "=") {+ this.raise(node.left.end, "Only '=' operator can be used for specifying default value.");+ }+ node.type = "AssignmentPattern";+ delete node.operator;+ this.toAssignable(node.left, isBinding);+ break;+ case "ParenthesizedExpression":+ this.toAssignable(node.expression, isBinding, refDestructuringErrors);+ break;+ case "ChainExpression":+ this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");+ break;+ case "MemberExpression":+ if (!isBinding) {+ break;+ }+ default:+ this.raise(node.start, "Assigning to rvalue");+ }+ } else if (refDestructuringErrors) {+ this.checkPatternErrors(refDestructuringErrors, true);+ }+ return node;+};+pp$7.toAssignableList = function(exprList, isBinding) {+ var end = exprList.length;+ for (var i2 = 0; i2 < end; i2++) {+ var elt = exprList[i2];+ if (elt) {+ this.toAssignable(elt, isBinding);+ }+ }+ if (end) {+ var last = exprList[end - 1];+ if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") {+ this.unexpected(last.argument.start);+ }+ }+ return exprList;+};+pp$7.parseSpread = function(refDestructuringErrors) {+ var node = this.startNode();+ this.next();+ node.argument = this.parseMaybeAssign(false, refDestructuringErrors);+ return this.finishNode(node, "SpreadElement");+};+pp$7.parseRestBinding = function() {+ var node = this.startNode();+ this.next();+ if (this.options.ecmaVersion === 6 && this.type !== types$1.name) {+ this.unexpected();+ }+ node.argument = this.parseBindingAtom();+ return this.finishNode(node, "RestElement");+};+pp$7.parseBindingAtom = function() {+ if (this.options.ecmaVersion >= 6) {+ switch (this.type) {+ case types$1.bracketL:+ var node = this.startNode();+ this.next();+ node.elements = this.parseBindingList(types$1.bracketR, true, true);+ return this.finishNode(node, "ArrayPattern");+ case types$1.braceL:+ return this.parseObj(true);+ }+ }+ return this.parseIdent();+};+pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowModifiers) {+ var elts = [], first = true;+ while (!this.eat(close)) {+ if (first) {+ first = false;+ } else {+ this.expect(types$1.comma);+ }+ if (allowEmpty && this.type === types$1.comma) {+ elts.push(null);+ } else if (allowTrailingComma && this.afterTrailingComma(close)) {+ break;+ } else if (this.type === types$1.ellipsis) {+ var rest = this.parseRestBinding();+ this.parseBindingListItem(rest);+ elts.push(rest);+ if (this.type === types$1.comma) {+ this.raiseRecoverable(this.start, "Comma is not permitted after the rest element");+ }+ this.expect(close);+ break;+ } else {+ elts.push(this.parseAssignableListItem(allowModifiers));+ }+ }+ return elts;+};+pp$7.parseAssignableListItem = function(allowModifiers) {+ var elem = this.parseMaybeDefault(this.start, this.startLoc);+ this.parseBindingListItem(elem);+ return elem;+};+pp$7.parseBindingListItem = function(param) {+ return param;+};+pp$7.parseMaybeDefault = function(startPos, startLoc, left) {+ left = left || this.parseBindingAtom();+ if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) {+ return left;+ }+ var node = this.startNodeAt(startPos, startLoc);+ node.left = left;+ node.right = this.parseMaybeAssign();+ return this.finishNode(node, "AssignmentPattern");+};+pp$7.checkLValSimple = function(expr, bindingType, checkClashes) {+ if (bindingType === void 0) bindingType = BIND_NONE;+ var isBind = bindingType !== BIND_NONE;+ switch (expr.type) {+ case "Identifier":+ if (this.strict && this.reservedWordsStrictBind.test(expr.name)) {+ this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode");+ }+ if (isBind) {+ if (bindingType === BIND_LEXICAL && expr.name === "let") {+ this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name");+ }+ if (checkClashes) {+ if (hasOwn(checkClashes, expr.name)) {+ this.raiseRecoverable(expr.start, "Argument name clash");+ }+ checkClashes[expr.name] = true;+ }+ if (bindingType !== BIND_OUTSIDE) {+ this.declareName(expr.name, bindingType, expr.start);+ }+ }+ break;+ case "ChainExpression":+ this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");+ break;+ case "MemberExpression":+ if (isBind) {+ this.raiseRecoverable(expr.start, "Binding member expression");+ }+ break;+ case "ParenthesizedExpression":+ if (isBind) {+ this.raiseRecoverable(expr.start, "Binding parenthesized expression");+ }+ return this.checkLValSimple(expr.expression, bindingType, checkClashes);+ default:+ this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");+ }+};+pp$7.checkLValPattern = function(expr, bindingType, checkClashes) {+ if (bindingType === void 0) bindingType = BIND_NONE;+ switch (expr.type) {+ case "ObjectPattern":+ for (var i2 = 0, list2 = expr.properties; i2 < list2.length; i2 += 1) {+ var prop = list2[i2];+ this.checkLValInnerPattern(prop, bindingType, checkClashes);+ }+ break;+ case "ArrayPattern":+ for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {+ var elem = list$1[i$1];+ if (elem) {+ this.checkLValInnerPattern(elem, bindingType, checkClashes);+ }+ }+ break;+ default:+ this.checkLValSimple(expr, bindingType, checkClashes);+ }+};+pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) {+ if (bindingType === void 0) bindingType = BIND_NONE;+ switch (expr.type) {+ case "Property":+ this.checkLValInnerPattern(expr.value, bindingType, checkClashes);+ break;+ case "AssignmentPattern":+ this.checkLValPattern(expr.left, bindingType, checkClashes);+ break;+ case "RestElement":+ this.checkLValPattern(expr.argument, bindingType, checkClashes);+ break;+ default:+ this.checkLValPattern(expr, bindingType, checkClashes);+ }+};+var TokContext = function TokContext2(token, isExpr, preserveSpace, override, generator) {+ this.token = token;+ this.isExpr = !!isExpr;+ this.preserveSpace = !!preserveSpace;+ this.override = override;+ this.generator = !!generator;+};+var types = {+ b_stat: new TokContext("{", false),+ b_expr: new TokContext("{", true),+ b_tmpl: new TokContext("${", false),+ p_stat: new TokContext("(", false),+ p_expr: new TokContext("(", true),+ q_tmpl: new TokContext("`", true, true, function(p) {+ return p.tryReadTemplateToken();+ }),+ f_stat: new TokContext("function", false),+ f_expr: new TokContext("function", true),+ f_expr_gen: new TokContext("function", true, false, null, true),+ f_gen: new TokContext("function", false, false, null, true)+};+var pp$6 = Parser.prototype;+pp$6.initialContext = function() {+ return [types.b_stat];+};+pp$6.curContext = function() {+ return this.context[this.context.length - 1];+};+pp$6.braceIsBlock = function(prevType) {+ var parent = this.curContext();+ if (parent === types.f_expr || parent === types.f_stat) {+ return true;+ }+ if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr)) {+ return !parent.isExpr;+ }+ if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed) {+ return lineBreak.test(this.input.slice(this.lastTokEnd, this.start));+ }+ if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow) {+ return true;+ }+ if (prevType === types$1.braceL) {+ return parent === types.b_stat;+ }+ if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name) {+ return false;+ }+ return !this.exprAllowed;+};+pp$6.inGeneratorContext = function() {+ for (var i2 = this.context.length - 1; i2 >= 1; i2--) {+ var context = this.context[i2];+ if (context.token === "function") {+ return context.generator;+ }+ }+ return false;+};+pp$6.updateContext = function(prevType) {+ var update, type = this.type;+ if (type.keyword && prevType === types$1.dot) {+ this.exprAllowed = false;+ } else if (update = type.updateContext) {+ update.call(this, prevType);+ } else {+ this.exprAllowed = type.beforeExpr;+ }+};+pp$6.overrideContext = function(tokenCtx) {+ if (this.curContext() !== tokenCtx) {+ this.context[this.context.length - 1] = tokenCtx;+ }+};+types$1.parenR.updateContext = types$1.braceR.updateContext = function() {+ if (this.context.length === 1) {+ this.exprAllowed = true;+ return;+ }+ var out = this.context.pop();+ if (out === types.b_stat && this.curContext().token === "function") {+ out = this.context.pop();+ }+ this.exprAllowed = !out.isExpr;+};+types$1.braceL.updateContext = function(prevType) {+ this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr);+ this.exprAllowed = true;+};+types$1.dollarBraceL.updateContext = function() {+ this.context.push(types.b_tmpl);+ this.exprAllowed = true;+};+types$1.parenL.updateContext = function(prevType) {+ var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while;+ this.context.push(statementParens ? types.p_stat : types.p_expr);+ this.exprAllowed = true;+};+types$1.incDec.updateContext = function() {+};+types$1._function.updateContext = types$1._class.updateContext = function(prevType) {+ if (prevType.beforeExpr && prevType !== types$1._else && !(prevType === types$1.semi && this.curContext() !== types.p_stat) && !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat)) {+ this.context.push(types.f_expr);+ } else {+ this.context.push(types.f_stat);+ }+ this.exprAllowed = false;+};+types$1.colon.updateContext = function() {+ if (this.curContext().token === "function") {+ this.context.pop();+ }+ this.exprAllowed = true;+};+types$1.backQuote.updateContext = function() {+ if (this.curContext() === types.q_tmpl) {+ this.context.pop();+ } else {+ this.context.push(types.q_tmpl);+ }+ this.exprAllowed = false;+};+types$1.star.updateContext = function(prevType) {+ if (prevType === types$1._function) {+ var index = this.context.length - 1;+ if (this.context[index] === types.f_expr) {+ this.context[index] = types.f_expr_gen;+ } else {+ this.context[index] = types.f_gen;+ }+ }+ this.exprAllowed = true;+};+types$1.name.updateContext = function(prevType) {+ var allowed = false;+ if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) {+ if (this.value === "of" && !this.exprAllowed || this.value === "yield" && this.inGeneratorContext()) {+ allowed = true;+ }+ }+ this.exprAllowed = allowed;+};+var pp$5 = Parser.prototype;+pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {+ if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") {+ return;+ }+ if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) {+ return;+ }+ var key = prop.key;+ var name;+ switch (key.type) {+ case "Identifier":+ name = key.name;+ break;+ case "Literal":+ name = String(key.value);+ break;+ default:+ return;+ }+ var kind = prop.kind;+ if (this.options.ecmaVersion >= 6) {+ if (name === "__proto__" && kind === "init") {+ if (propHash.proto) {+ if (refDestructuringErrors) {+ if (refDestructuringErrors.doubleProto < 0) {+ refDestructuringErrors.doubleProto = key.start;+ }+ } else {+ this.raiseRecoverable(key.start, "Redefinition of __proto__ property");+ }+ }+ propHash.proto = true;+ }+ return;+ }+ name = "$" + name;+ var other = propHash[name];+ if (other) {+ var redefinition;+ if (kind === "init") {+ redefinition = this.strict && other.init || other.get || other.set;+ } else {+ redefinition = other.init || other[kind];+ }+ if (redefinition) {+ this.raiseRecoverable(key.start, "Redefinition of property");+ }+ } else {+ other = propHash[name] = {+ init: false,+ get: false,+ set: false+ };+ }+ other[kind] = true;+};+pp$5.parseExpression = function(forInit, refDestructuringErrors) {+ var this$1$1 = this;+ return this.catchStackOverflow(function() {+ var startPos = this$1$1.start, startLoc = this$1$1.startLoc;+ var expr = this$1$1.parseMaybeAssign(forInit, refDestructuringErrors);+ if (this$1$1.type === types$1.comma) {+ var node = this$1$1.startNodeAt(startPos, startLoc);+ node.expressions = [expr];+ while (this$1$1.eat(types$1.comma)) {+ node.expressions.push(this$1$1.parseMaybeAssign(forInit, refDestructuringErrors));+ }+ return this$1$1.finishNode(node, "SequenceExpression");+ }+ return expr;+ });+};+pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {+ if (this.isContextual("yield")) {+ if (this.inGenerator) {+ return this.parseYield(forInit);+ } else {+ this.exprAllowed = false;+ }+ }+ var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1;+ if (refDestructuringErrors) {+ oldParenAssign = refDestructuringErrors.parenthesizedAssign;+ oldTrailingComma = refDestructuringErrors.trailingComma;+ oldDoubleProto = refDestructuringErrors.doubleProto;+ refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;+ } else {+ refDestructuringErrors = new DestructuringErrors();+ ownDestructuringErrors = true;+ }+ var startPos = this.start, startLoc = this.startLoc;+ if (this.type === types$1.parenL || this.type === types$1.name) {+ this.potentialArrowAt = this.start;+ this.potentialArrowInForAwait = forInit === "await";+ }+ var left = this.parseMaybeConditional(forInit, refDestructuringErrors);+ if (afterLeftParse) {+ left = afterLeftParse.call(this, left, startPos, startLoc);+ }+ if (this.type.isAssign) {+ var node = this.startNodeAt(startPos, startLoc);+ node.operator = this.value;+ if (this.type === types$1.eq) {+ left = this.toAssignable(left, false, refDestructuringErrors);+ }+ if (!ownDestructuringErrors) {+ refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;+ }+ if (refDestructuringErrors.shorthandAssign >= left.start) {+ refDestructuringErrors.shorthandAssign = -1;+ }+ if (this.type === types$1.eq) {+ this.checkLValPattern(left);+ } else {+ this.checkLValSimple(left);+ }+ node.left = left;+ this.next();+ node.right = this.parseMaybeAssign(forInit);+ if (oldDoubleProto > -1) {+ refDestructuringErrors.doubleProto = oldDoubleProto;+ }+ return this.finishNode(node, "AssignmentExpression");+ } else {+ if (ownDestructuringErrors) {+ this.checkExpressionErrors(refDestructuringErrors, true);+ }+ }+ if (oldParenAssign > -1) {+ refDestructuringErrors.parenthesizedAssign = oldParenAssign;+ }+ if (oldTrailingComma > -1) {+ refDestructuringErrors.trailingComma = oldTrailingComma;+ }+ return left;+};+pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) {+ var startPos = this.start, startLoc = this.startLoc;+ var expr = this.parseExprOps(forInit, refDestructuringErrors);+ if (this.checkExpressionErrors(refDestructuringErrors)) {+ return expr;+ }+ if (!(expr.type === "ArrowFunctionExpression" && expr.start === startPos) && this.eat(types$1.question)) {+ var node = this.startNodeAt(startPos, startLoc);+ node.test = expr;+ node.consequent = this.parseMaybeAssign();+ this.expect(types$1.colon);+ node.alternate = this.parseMaybeAssign(forInit);+ return this.finishNode(node, "ConditionalExpression");+ }+ return expr;+};+pp$5.parseExprOps = function(forInit, refDestructuringErrors) {+ var startPos = this.start, startLoc = this.startLoc;+ var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit);+ if (this.checkExpressionErrors(refDestructuringErrors)) {+ return expr;+ }+ return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit);+};+pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {+ var prec = this.type.binop;+ if (prec != null && (!forInit || this.type !== types$1._in)) {+ if (prec > minPrec) {+ var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND;+ var coalesce = this.type === types$1.coalesce;+ if (coalesce) {+ prec = types$1.logicalAND.binop;+ }+ var op = this.value;+ this.next();+ var startPos = this.start, startLoc = this.startLoc;+ var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit);+ var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);+ if (logical && this.type === types$1.coalesce || coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND)) {+ this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");+ }+ return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit);+ }+ }+ return left;+};+pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) {+ if (right.type === "PrivateIdentifier") {+ this.raise(right.start, "Private identifier can only be left side of binary expression");+ }+ var node = this.startNodeAt(startPos, startLoc);+ node.left = left;+ node.operator = op;+ node.right = right;+ return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression");+};+pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) {+ var startPos = this.start, startLoc = this.startLoc, expr;+ if (this.isContextual("await") && this.canAwait) {+ expr = this.parseAwait(forInit);+ sawUnary = true;+ } else if (this.type.prefix) {+ var node = this.startNode(), update = this.type === types$1.incDec;+ node.operator = this.value;+ node.prefix = true;+ this.next();+ node.argument = this.parseMaybeUnary(null, true, update, forInit);+ this.checkExpressionErrors(refDestructuringErrors, true);+ if (update) {+ this.checkLValSimple(node.argument);+ } else if (this.strict && node.operator === "delete" && isLocalVariableAccess(node.argument)) {+ this.raiseRecoverable(node.start, "Deleting local variable in strict mode");+ } else if (node.operator === "delete" && isPrivateFieldAccess(node.argument)) {+ this.raiseRecoverable(node.start, "Private fields can not be deleted");+ } else {+ sawUnary = true;+ }+ expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");+ } else if (!sawUnary && this.type === types$1.privateId) {+ if ((forInit || this.privateNameStack.length === 0) && this.options.checkPrivateFields) {+ this.unexpected();+ }+ expr = this.parsePrivateIdent();+ if (this.type !== types$1._in) {+ this.unexpected();+ }+ } else {+ expr = this.parseExprSubscripts(refDestructuringErrors, forInit);+ if (this.checkExpressionErrors(refDestructuringErrors)) {+ return expr;+ }+ while (this.type.postfix && !this.canInsertSemicolon()) {+ var node$1 = this.startNodeAt(startPos, startLoc);+ node$1.operator = this.value;+ node$1.prefix = false;+ node$1.argument = expr;+ this.checkLValSimple(expr);+ this.next();+ expr = this.finishNode(node$1, "UpdateExpression");+ }+ }+ if (!incDec && !(expr.type === "ArrowFunctionExpression" && expr.start === startPos) && this.eat(types$1.starstar)) {+ if (sawUnary) {+ this.unexpected(this.lastTokStart);+ } else {+ return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false);+ }+ } else {+ return expr;+ }+};+function isLocalVariableAccess(node) {+ return node.type === "Identifier" || node.type === "ParenthesizedExpression" && isLocalVariableAccess(node.expression);+}+function isPrivateFieldAccess(node) {+ return node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" || node.type === "ChainExpression" && isPrivateFieldAccess(node.expression) || node.type === "ParenthesizedExpression" && isPrivateFieldAccess(node.expression);+}+pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) {+ var startPos = this.start, startLoc = this.startLoc;+ var expr = this.parseExprAtom(refDestructuringErrors, forInit);+ if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") {+ return expr;+ }+ var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit);+ if (refDestructuringErrors && result.type === "MemberExpression") {+ if (refDestructuringErrors.parenthesizedAssign >= result.start) {+ refDestructuringErrors.parenthesizedAssign = -1;+ }+ if (refDestructuringErrors.parenthesizedBind >= result.start) {+ refDestructuringErrors.parenthesizedBind = -1;+ }+ if (refDestructuringErrors.trailingComma >= result.start) {+ refDestructuringErrors.trailingComma = -1;+ }+ }+ return result;+};+pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) {+ var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && this.potentialArrowAt === base.start;+ var optionalChained = false;+ while (true) {+ var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit);+ if (element.optional) {+ optionalChained = true;+ }+ if (element === base || element.type === "ArrowFunctionExpression") {+ if (optionalChained) {+ var chainNode = this.startNodeAt(startPos, startLoc);+ chainNode.expression = element;+ element = this.finishNode(chainNode, "ChainExpression");+ }+ return element;+ }+ base = element;+ }+};+pp$5.shouldParseAsyncArrow = function() {+ return !this.canInsertSemicolon() && this.eat(types$1.arrow);+};+pp$5.parseSubscriptAsyncArrow = function(startPos, startLoc, exprList, forInit) {+ return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit);+};+pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {+ var optionalSupported = this.options.ecmaVersion >= 11;+ var optional = optionalSupported && this.eat(types$1.questionDot);+ if (noCalls && optional) {+ this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions");+ }+ var computed = this.eat(types$1.bracketL);+ if (computed || optional && this.type !== types$1.parenL && this.type !== types$1.backQuote || this.eat(types$1.dot)) {+ var node = this.startNodeAt(startPos, startLoc);+ node.object = base;+ if (computed) {+ node.property = this.parseExpression();+ this.expect(types$1.bracketR);+ } else if (this.type === types$1.privateId && base.type !== "Super") {+ node.property = this.parsePrivateIdent();+ } else {+ node.property = this.parseIdent(this.options.allowReserved !== "never");+ }+ node.computed = !!computed;+ if (optionalSupported) {+ node.optional = optional;+ }+ base = this.finishNode(node, "MemberExpression");+ } else if (!noCalls && this.eat(types$1.parenL)) {+ var refDestructuringErrors = new DestructuringErrors(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;+ this.yieldPos = 0;+ this.awaitPos = 0;+ this.awaitIdentPos = 0;+ var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);+ if (maybeAsyncArrow && !optional && this.shouldParseAsyncArrow()) {+ this.checkPatternErrors(refDestructuringErrors, false);+ this.checkYieldAwaitInDefaultParams();+ if (this.awaitIdentPos > 0) {+ this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function");+ }+ this.yieldPos = oldYieldPos;+ this.awaitPos = oldAwaitPos;+ this.awaitIdentPos = oldAwaitIdentPos;+ return this.parseSubscriptAsyncArrow(startPos, startLoc, exprList, forInit);+ }+ this.checkExpressionErrors(refDestructuringErrors, true);+ this.yieldPos = oldYieldPos || this.yieldPos;+ this.awaitPos = oldAwaitPos || this.awaitPos;+ this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;+ var node$1 = this.startNodeAt(startPos, startLoc);+ node$1.callee = base;+ node$1.arguments = exprList;+ if (optionalSupported) {+ node$1.optional = optional;+ }+ base = this.finishNode(node$1, "CallExpression");+ } else if (this.type === types$1.backQuote) {+ if (optional || optionalChained) {+ this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");+ }+ var node$2 = this.startNodeAt(startPos, startLoc);+ node$2.tag = base;+ node$2.quasi = this.parseTemplate({ isTagged: true });+ base = this.finishNode(node$2, "TaggedTemplateExpression");+ }+ return base;+};+pp$5.parseExprAtom = function(refDestructuringErrors, forInit, forNew) {+ if (this.type === types$1.slash) {+ this.readRegexp();+ }+ var node, canBeArrow = this.potentialArrowAt === this.start;+ switch (this.type) {+ case types$1._super:+ if (!this.allowSuper) {+ this.raise(this.start, "'super' keyword outside a method");+ }+ node = this.startNode();+ this.next();+ if (this.type === types$1.parenL && !this.allowDirectSuper) {+ this.raise(node.start, "super() call outside constructor of a subclass");+ }+ if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL) {+ this.unexpected();+ }+ return this.finishNode(node, "Super");+ case types$1._this:+ node = this.startNode();+ this.next();+ return this.finishNode(node, "ThisExpression");+ case types$1.name:+ var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;+ var id = this.parseIdent(false);+ if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) {+ this.overrideContext(types.f_expr);+ return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit);+ }+ if (canBeArrow && !this.canInsertSemicolon()) {+ if (this.eat(types$1.arrow)) {+ return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit);+ }+ if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc && (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {+ id = this.parseIdent(false);+ if (this.canInsertSemicolon() || !this.eat(types$1.arrow)) {+ this.unexpected();+ }+ return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit);+ }+ }+ return id;+ case types$1.regexp:+ var value = this.value;+ node = this.parseLiteral(value.value);+ node.regex = { pattern: value.pattern, flags: value.flags };+ return node;+ case types$1.num:+ case types$1.string:+ return this.parseLiteral(this.value);+ case types$1._null:+ case types$1._true:+ case types$1._false:+ node = this.startNode();+ node.value = this.type === types$1._null ? null : this.type === types$1._true;+ node.raw = this.type.keyword;+ this.next();+ return this.finishNode(node, "Literal");+ case types$1.parenL:+ var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit);+ if (refDestructuringErrors) {+ if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) {+ refDestructuringErrors.parenthesizedAssign = start;+ }+ if (refDestructuringErrors.parenthesizedBind < 0) {+ refDestructuringErrors.parenthesizedBind = start;+ }+ }+ return expr;+ case types$1.bracketL:+ node = this.startNode();+ this.next();+ node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors);+ return this.finishNode(node, "ArrayExpression");+ case types$1.braceL:+ this.overrideContext(types.b_expr);+ return this.parseObj(false, refDestructuringErrors);+ case types$1._function:+ node = this.startNode();+ this.next();+ return this.parseFunction(node, 0);+ case types$1._class:+ return this.parseClass(this.startNode(), false);+ case types$1._new:+ return this.parseNew();+ case types$1.backQuote:+ return this.parseTemplate();+ case types$1._import:+ if (this.options.ecmaVersion >= 11) {+ return this.parseExprImport(forNew);+ } else {+ return this.unexpected();+ }+ default:+ return this.parseExprAtomDefault();+ }+};+pp$5.parseExprAtomDefault = function() {+ this.unexpected();+};+pp$5.parseExprImport = function(forNew) {+ var node = this.startNode();+ if (this.containsEsc) {+ this.raiseRecoverable(this.start, "Escape sequence in keyword import");+ }+ this.next();+ if (this.type === types$1.parenL && !forNew) {+ return this.parseDynamicImport(node);+ } else if (this.type === types$1.dot) {+ var meta = this.startNodeAt(node.start, node.loc && node.loc.start);+ meta.name = "import";+ node.meta = this.finishNode(meta, "Identifier");+ return this.parseImportMeta(node);+ } else {+ this.unexpected();+ }+};+pp$5.parseDynamicImport = function(node) {+ this.next();+ node.source = this.parseMaybeAssign();+ if (this.options.ecmaVersion >= 16) {+ if (!this.eat(types$1.parenR)) {+ this.expect(types$1.comma);+ if (!this.afterTrailingComma(types$1.parenR)) {+ node.options = this.parseMaybeAssign();+ if (!this.eat(types$1.parenR)) {+ this.expect(types$1.comma);+ if (!this.afterTrailingComma(types$1.parenR)) {+ this.unexpected();+ }+ }+ } else {+ node.options = null;+ }+ } else {+ node.options = null;+ }+ } else {+ if (!this.eat(types$1.parenR)) {+ var errorPos = this.start;+ if (this.eat(types$1.comma) && this.eat(types$1.parenR)) {+ this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");+ } else {+ this.unexpected(errorPos);+ }+ }+ }+ return this.finishNode(node, "ImportExpression");+};+pp$5.parseImportMeta = function(node) {+ this.next();+ var containsEsc = this.containsEsc;+ node.property = this.parseIdent(true);+ if (node.property.name !== "meta") {+ this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'");+ }+ if (containsEsc) {+ this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters");+ }+ if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) {+ this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module");+ }+ return this.finishNode(node, "MetaProperty");+};+pp$5.parseLiteral = function(value) {+ var node = this.startNode();+ node.value = value;+ node.raw = this.input.slice(this.start, this.end);+ if (node.raw.charCodeAt(node.raw.length - 1) === 110) {+ node.bigint = node.value != null ? node.value.toString() : node.raw.slice(0, -1).replace(/_/g, "");+ }+ this.next();+ return this.finishNode(node, "Literal");+};+pp$5.parseParenExpression = function() {+ this.expect(types$1.parenL);+ var val = this.parseExpression();+ this.expect(types$1.parenR);+ return val;+};+pp$5.shouldParseArrow = function(exprList) {+ return !this.canInsertSemicolon();+};+pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) {+ var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;+ if (this.options.ecmaVersion >= 6) {+ this.next();+ var innerStartPos = this.start, innerStartLoc = this.startLoc;+ var exprList = [], first = true, lastIsComma = false;+ var refDestructuringErrors = new DestructuringErrors(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;+ this.yieldPos = 0;+ this.awaitPos = 0;+ while (this.type !== types$1.parenR) {+ first ? first = false : this.expect(types$1.comma);+ if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) {+ lastIsComma = true;+ break;+ } else if (this.type === types$1.ellipsis) {+ spreadStart = this.start;+ exprList.push(this.parseParenItem(this.parseRestBinding()));+ if (this.type === types$1.comma) {+ this.raiseRecoverable(+ this.start,+ "Comma is not permitted after the rest element"+ );+ }+ break;+ } else {+ exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));+ }+ }+ var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc;+ this.expect(types$1.parenR);+ if (canBeArrow && this.shouldParseArrow(exprList) && this.eat(types$1.arrow)) {+ this.checkPatternErrors(refDestructuringErrors, false);+ this.checkYieldAwaitInDefaultParams();+ this.yieldPos = oldYieldPos;+ this.awaitPos = oldAwaitPos;+ return this.parseParenArrowList(startPos, startLoc, exprList, forInit);+ }+ if (!exprList.length || lastIsComma) {+ this.unexpected(this.lastTokStart);+ }+ if (spreadStart) {+ this.unexpected(spreadStart);+ }+ this.checkExpressionErrors(refDestructuringErrors, true);+ this.yieldPos = oldYieldPos || this.yieldPos;+ this.awaitPos = oldAwaitPos || this.awaitPos;+ if (exprList.length > 1) {+ val = this.startNodeAt(innerStartPos, innerStartLoc);+ val.expressions = exprList;+ this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);+ } else {+ val = exprList[0];+ }+ } else {+ val = this.parseParenExpression();+ }+ if (this.options.preserveParens) {+ var par = this.startNodeAt(startPos, startLoc);+ par.expression = val;+ return this.finishNode(par, "ParenthesizedExpression");+ } else {+ return val;+ }+};+pp$5.parseParenItem = function(item) {+ return item;+};+pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) {+ return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit);+};+var empty = [];+pp$5.parseNew = function() {+ if (this.containsEsc) {+ this.raiseRecoverable(this.start, "Escape sequence in keyword new");+ }+ var node = this.startNode();+ this.next();+ if (this.options.ecmaVersion >= 6 && this.type === types$1.dot) {+ var meta = this.startNodeAt(node.start, node.loc && node.loc.start);+ meta.name = "new";+ node.meta = this.finishNode(meta, "Identifier");+ this.next();+ var containsEsc = this.containsEsc;+ node.property = this.parseIdent(true);+ if (node.property.name !== "target") {+ this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'");+ }+ if (containsEsc) {+ this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters");+ }+ if (!this.allowNewDotTarget) {+ this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block");+ }+ return this.finishNode(node, "MetaProperty");+ }+ var startPos = this.start, startLoc = this.startLoc;+ node.callee = this.parseSubscripts(this.parseExprAtom(null, false, true), startPos, startLoc, true, false);+ if (node.callee.type === "Super") {+ this.raiseRecoverable(startPos, "Invalid use of 'super'");+ }+ if (this.eat(types$1.parenL)) {+ node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false);+ } else {+ node.arguments = empty;+ }+ return this.finishNode(node, "NewExpression");+};+pp$5.parseTemplateElement = function(ref2) {+ var isTagged = ref2.isTagged;+ var elem = this.startNode();+ if (this.type === types$1.invalidTemplate) {+ if (!isTagged) {+ this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");+ }+ elem.value = {+ raw: this.value.replace(/\r\n?/g, "\n"),+ cooked: null+ };+ } else {+ elem.value = {+ raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),+ cooked: this.value+ };+ }+ this.next();+ elem.tail = this.type === types$1.backQuote;+ return this.finishNode(elem, "TemplateElement");+};+pp$5.parseTemplate = function(ref2) {+ if (ref2 === void 0) ref2 = {};+ var isTagged = ref2.isTagged;+ if (isTagged === void 0) isTagged = false;+ var node = this.startNode();+ this.next();+ node.expressions = [];+ var curElt = this.parseTemplateElement({ isTagged });+ node.quasis = [curElt];+ while (!curElt.tail) {+ if (this.type === types$1.eof) {+ this.raise(this.pos, "Unterminated template literal");+ }+ this.expect(types$1.dollarBraceL);+ node.expressions.push(this.parseExpression());+ this.expect(types$1.braceR);+ node.quasis.push(curElt = this.parseTemplateElement({ isTagged }));+ }+ this.next();+ return this.finishNode(node, "TemplateLiteral");+};+pp$5.isAsyncProp = function(prop) {+ return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && (this.type === types$1.name || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword || this.options.ecmaVersion >= 9 && this.type === types$1.star) && !lineBreak.test(this.input.slice(this.lastTokEnd, this.start));+};+pp$5.parseObj = function(isPattern, refDestructuringErrors) {+ var node = this.startNode(), first = true, propHash = {};+ node.properties = [];+ this.next();+ while (!this.eat(types$1.braceR)) {+ if (!first) {+ this.expect(types$1.comma);+ if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) {+ break;+ }+ } else {+ first = false;+ }+ var prop = this.parseProperty(isPattern, refDestructuringErrors);+ if (!isPattern) {+ this.checkPropClash(prop, propHash, refDestructuringErrors);+ }+ node.properties.push(prop);+ }+ return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression");+};+pp$5.parseProperty = function(isPattern, refDestructuringErrors) {+ var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;+ if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) {+ if (isPattern) {+ prop.argument = this.parseIdent(false);+ if (this.type === types$1.comma) {+ this.raiseRecoverable(this.start, "Comma is not permitted after the rest element");+ }+ return this.finishNode(prop, "RestElement");+ }+ prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);+ if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {+ refDestructuringErrors.trailingComma = this.start;+ }+ return this.finishNode(prop, "SpreadElement");+ }+ if (this.options.ecmaVersion >= 6) {+ prop.method = false;+ prop.shorthand = false;+ if (isPattern || refDestructuringErrors) {+ startPos = this.start;+ startLoc = this.startLoc;+ }+ if (!isPattern) {+ isGenerator = this.eat(types$1.star);+ }+ }+ var containsEsc = this.containsEsc;+ this.parsePropertyName(prop);+ if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {+ isAsync = true;+ isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star);+ this.parsePropertyName(prop);+ } else {+ isAsync = false;+ }+ this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);+ return this.finishNode(prop, "Property");+};+pp$5.parseGetterSetter = function(prop) {+ var kind = prop.key.name;+ this.parsePropertyName(prop);+ prop.value = this.parseMethod(false);+ prop.kind = kind;+ var paramCount = prop.kind === "get" ? 0 : 1;+ if (prop.value.params.length !== paramCount) {+ var start = prop.value.start;+ if (prop.kind === "get") {+ this.raiseRecoverable(start, "getter should have no params");+ } else {+ this.raiseRecoverable(start, "setter should have exactly one param");+ }+ } else {+ if (prop.kind === "set" && prop.value.params[0].type === "RestElement") {+ this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params");+ }+ }+};+pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {+ if ((isGenerator || isAsync) && this.type === types$1.colon) {+ this.unexpected();+ }+ if (this.eat(types$1.colon)) {+ prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);+ prop.kind = "init";+ } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) {+ if (isPattern) {+ this.unexpected();+ }+ prop.method = true;+ prop.value = this.parseMethod(isGenerator, isAsync);+ prop.kind = "init";+ } else if (!isPattern && !containsEsc && this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) {+ if (isGenerator || isAsync) {+ this.unexpected();+ }+ this.parseGetterSetter(prop);+ } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {+ if (isGenerator || isAsync) {+ this.unexpected();+ }+ this.checkUnreserved(prop.key);+ if (prop.key.name === "await" && !this.awaitIdentPos) {+ this.awaitIdentPos = startPos;+ }+ if (isPattern) {+ prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));+ } else if (this.type === types$1.eq && refDestructuringErrors) {+ if (refDestructuringErrors.shorthandAssign < 0) {+ refDestructuringErrors.shorthandAssign = this.start;+ }+ prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));+ } else {+ prop.value = this.copyNode(prop.key);+ }+ prop.kind = "init";+ prop.shorthand = true;+ } else {+ this.unexpected();+ }+};+pp$5.parsePropertyName = function(prop) {+ if (this.options.ecmaVersion >= 6) {+ if (this.eat(types$1.bracketL)) {+ prop.computed = true;+ prop.key = this.parseMaybeAssign();+ this.expect(types$1.bracketR);+ return prop.key;+ } else {+ prop.computed = false;+ }+ }+ return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never");+};+pp$5.initFunction = function(node) {+ node.id = null;+ if (this.options.ecmaVersion >= 6) {+ node.generator = node.expression = false;+ }+ if (this.options.ecmaVersion >= 8) {+ node.async = false;+ }+};+pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {+ var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;+ this.initFunction(node);+ if (this.options.ecmaVersion >= 6) {+ node.generator = isGenerator;+ }+ if (this.options.ecmaVersion >= 8) {+ node.async = !!isAsync;+ }+ this.yieldPos = 0;+ this.awaitPos = 0;+ this.awaitIdentPos = 0;+ this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));+ this.expect(types$1.parenL);+ node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);+ this.checkYieldAwaitInDefaultParams();+ this.parseFunctionBody(node, false, true, false);+ this.yieldPos = oldYieldPos;+ this.awaitPos = oldAwaitPos;+ this.awaitIdentPos = oldAwaitIdentPos;+ return this.finishNode(node, "FunctionExpression");+};+pp$5.parseArrowExpression = function(node, params, isAsync, forInit) {+ var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;+ this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);+ this.initFunction(node);+ if (this.options.ecmaVersion >= 8) {+ node.async = !!isAsync;+ }+ this.yieldPos = 0;+ this.awaitPos = 0;+ this.awaitIdentPos = 0;+ node.params = this.toAssignableList(params, true);+ this.parseFunctionBody(node, true, false, forInit);+ this.yieldPos = oldYieldPos;+ this.awaitPos = oldAwaitPos;+ this.awaitIdentPos = oldAwaitIdentPos;+ return this.finishNode(node, "ArrowFunctionExpression");+};+pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) {+ var isExpression = isArrowFunction && this.type !== types$1.braceL;+ var oldStrict = this.strict, useStrict = false;+ if (isExpression) {+ node.body = this.parseMaybeAssign(forInit);+ node.expression = true;+ this.checkParams(node, false);+ } else {+ var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);+ if (!oldStrict || nonSimple) {+ useStrict = this.strictDirective(this.end);+ if (useStrict && nonSimple) {+ this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list");+ }+ }+ var oldLabels = this.labels;+ this.labels = [];+ if (useStrict) {+ this.strict = true;+ }+ this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));+ if (this.strict && node.id) {+ this.checkLValSimple(node.id, BIND_OUTSIDE);+ }+ node.body = this.parseBlock(false, void 0, useStrict && !oldStrict);+ node.expression = false;+ this.adaptDirectivePrologue(node.body.body);+ this.labels = oldLabels;+ }+ this.exitScope();+};+pp$5.isSimpleParamList = function(params) {+ for (var i2 = 0, list2 = params; i2 < list2.length; i2 += 1) {+ var param = list2[i2];+ if (param.type !== "Identifier") {+ return false;+ }+ }+ return true;+};+pp$5.checkParams = function(node, allowDuplicates) {+ var nameHash = /* @__PURE__ */ Object.create(null);+ for (var i2 = 0, list2 = node.params; i2 < list2.length; i2 += 1) {+ var param = list2[i2];+ this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);+ }+};+pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {+ var elts = [], first = true;+ while (!this.eat(close)) {+ if (!first) {+ this.expect(types$1.comma);+ if (allowTrailingComma && this.afterTrailingComma(close)) {+ break;+ }+ } else {+ first = false;+ }+ var elt = void 0;+ if (allowEmpty && this.type === types$1.comma) {+ elt = null;+ } else if (this.type === types$1.ellipsis) {+ elt = this.parseSpread(refDestructuringErrors);+ if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0) {+ refDestructuringErrors.trailingComma = this.start;+ }+ } else {+ elt = this.parseMaybeAssign(false, refDestructuringErrors);+ }+ elts.push(elt);+ }+ return elts;+};+pp$5.checkUnreserved = function(ref2) {+ var start = ref2.start;+ var end = ref2.end;+ var name = ref2.name;+ if (this.inGenerator && name === "yield") {+ this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator");+ }+ if (this.inAsync && name === "await") {+ this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function");+ }+ if (!(this.currentThisScope().flags & SCOPE_VAR) && name === "arguments") {+ this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer");+ }+ if (this.inClassStaticBlock && (name === "arguments" || name === "await")) {+ this.raise(start, "Cannot use " + name + " in class static initialization block");+ }+ if (this.keywords.test(name)) {+ this.raise(start, "Unexpected keyword '" + name + "'");+ }+ if (this.options.ecmaVersion < 6 && this.input.slice(start, end).indexOf("\\") !== -1) {+ return;+ }+ var re = this.strict ? this.reservedWordsStrict : this.reservedWords;+ if (re.test(name)) {+ if (!this.inAsync && name === "await") {+ this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function");+ }+ this.raiseRecoverable(start, "The keyword '" + name + "' is reserved");+ }+};+pp$5.parseIdent = function(liberal) {+ var node = this.parseIdentNode();+ this.next(!!liberal);+ this.finishNode(node, "Identifier");+ if (!liberal) {+ this.checkUnreserved(node);+ if (node.name === "await" && !this.awaitIdentPos) {+ this.awaitIdentPos = node.start;+ }+ }+ return node;+};+pp$5.parseIdentNode = function() {+ var node = this.startNode();+ if (this.type === types$1.name) {+ node.name = this.value;+ } else if (this.type.keyword) {+ node.name = this.type.keyword;+ if ((node.name === "class" || node.name === "function") && (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {+ this.context.pop();+ }+ this.type = types$1.name;+ } else {+ this.unexpected();+ }+ return node;+};+pp$5.parsePrivateIdent = function() {+ var node = this.startNode();+ if (this.type === types$1.privateId) {+ node.name = this.value;+ } else {+ this.unexpected();+ }+ this.next();+ this.finishNode(node, "PrivateIdentifier");+ if (this.options.checkPrivateFields) {+ if (this.privateNameStack.length === 0) {+ this.raise(node.start, "Private field '#" + node.name + "' must be declared in an enclosing class");+ } else {+ this.privateNameStack[this.privateNameStack.length - 1].used.push(node);+ }+ }+ return node;+};+pp$5.parseYield = function(forInit) {+ if (!this.yieldPos) {+ this.yieldPos = this.start;+ }+ var node = this.startNode();+ this.next();+ if (this.type === types$1.semi || this.canInsertSemicolon() || this.type !== types$1.star && !this.type.startsExpr) {+ node.delegate = false;+ node.argument = null;+ } else {+ node.delegate = this.eat(types$1.star);+ node.argument = this.parseMaybeAssign(forInit);+ }+ return this.finishNode(node, "YieldExpression");+};+pp$5.parseAwait = function(forInit) {+ if (!this.awaitPos) {+ this.awaitPos = this.start;+ }+ var node = this.startNode();+ this.next();+ node.argument = this.parseMaybeUnary(null, true, false, forInit);+ return this.finishNode(node, "AwaitExpression");+};+var pp$4 = Parser.prototype;+pp$4.raise = function(pos, message) {+ var loc = getLineInfo(this.input, pos);+ message += " (" + loc.line + ":" + loc.column + ")";+ if (this.sourceFile) {+ message += " in " + this.sourceFile;+ }+ var err = new SyntaxError(message);+ err.pos = pos;+ err.loc = loc;+ err.raisedAt = this.pos;+ throw err;+};+pp$4.raiseRecoverable = pp$4.raise;+pp$4.curPosition = function() {+ if (this.options.locations) {+ return new Position(this.curLine, this.pos - this.lineStart);+ }+};+var pp$3 = Parser.prototype;+var Scope = function Scope2(flags) {+ this.flags = flags;+ this.var = [];+ this.lexical = [];+ this.functions = [];+};+pp$3.enterScope = function(flags) {+ this.scopeStack.push(new Scope(flags));+};+pp$3.exitScope = function() {+ this.scopeStack.pop();+};+pp$3.treatFunctionsAsVarInScope = function(scope) {+ return scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_TOP;+};+pp$3.declareName = function(name, bindingType, pos) {+ var redeclared = false;+ if (bindingType === BIND_LEXICAL) {+ var scope = this.currentScope();+ redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;+ scope.lexical.push(name);+ if (this.inModule && scope.flags & SCOPE_TOP) {+ delete this.undefinedExports[name];+ }+ } else if (bindingType === BIND_SIMPLE_CATCH) {+ var scope$1 = this.currentScope();+ scope$1.lexical.push(name);+ } else if (bindingType === BIND_FUNCTION) {+ var scope$2 = this.currentScope();+ if (this.treatFunctionsAsVar) {+ redeclared = scope$2.lexical.indexOf(name) > -1;+ } else {+ redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1;+ }+ scope$2.functions.push(name);+ } else {+ for (var i2 = this.scopeStack.length - 1; i2 >= 0; --i2) {+ var scope$3 = this.scopeStack[i2];+ if (scope$3.lexical.indexOf(name) > -1 && !(scope$3.flags & SCOPE_SIMPLE_CATCH && scope$3.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {+ redeclared = true;+ break;+ }+ scope$3.var.push(name);+ if (this.inModule && scope$3.flags & SCOPE_TOP) {+ delete this.undefinedExports[name];+ }+ if (scope$3.flags & SCOPE_VAR) {+ break;+ }+ }+ }+ if (redeclared) {+ this.raiseRecoverable(pos, "Identifier '" + name + "' has already been declared");+ }+};+pp$3.checkLocalExport = function(id) {+ if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && this.scopeStack[0].var.indexOf(id.name) === -1) {+ this.undefinedExports[id.name] = id;+ }+};+pp$3.currentScope = function() {+ return this.scopeStack[this.scopeStack.length - 1];+};+pp$3.currentVarScope = function() {+ for (var i2 = this.scopeStack.length - 1; ; i2--) {+ var scope = this.scopeStack[i2];+ if (scope.flags & (SCOPE_VAR | SCOPE_CLASS_FIELD_INIT | SCOPE_CLASS_STATIC_BLOCK)) {+ return scope;+ }+ }+};+pp$3.currentThisScope = function() {+ for (var i2 = this.scopeStack.length - 1; ; i2--) {+ var scope = this.scopeStack[i2];+ if (scope.flags & (SCOPE_VAR | SCOPE_CLASS_FIELD_INIT | SCOPE_CLASS_STATIC_BLOCK) && !(scope.flags & SCOPE_ARROW)) {+ return scope;+ }+ }+};+var Node = function Node2(parser, pos, loc) {+ this.type = "";+ this.start = pos;+ this.end = 0;+ if (parser.options.locations) {+ this.loc = new SourceLocation(parser, loc);+ }+ if (parser.options.directSourceFile) {+ this.sourceFile = parser.options.directSourceFile;+ }+ if (parser.options.ranges) {+ this.range = [pos, 0];+ }+};+var pp$2 = Parser.prototype;+pp$2.startNode = function() {+ return new Node(this, this.start, this.startLoc);+};+pp$2.startNodeAt = function(pos, loc) {+ return new Node(this, pos, loc);+};+function finishNodeAt(node, type, pos, loc) {+ node.type = type;+ node.end = pos;+ if (this.options.locations) {+ node.loc.end = loc;+ }+ if (this.options.ranges) {+ node.range[1] = pos;+ }+ return node;+}+pp$2.finishNode = function(node, type) {+ return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc);+};+pp$2.finishNodeAt = function(node, type, pos, loc) {+ return finishNodeAt.call(this, node, type, pos, loc);+};+pp$2.copyNode = function(node) {+ var newNode = new Node(this, node.start, this.startLoc);+ for (var prop in node) {+ newNode[prop] = node[prop];+ }+ return newNode;+};+var scriptValuesAddedInUnicode = "Berf Beria_Erfe Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sidetic Sidt Sunu Sunuwar Tai_Yo Tayo Todhri Todr Tolong_Siki Tols Tulu_Tigalari Tutg Unknown Zzzz";+var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";+var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";+var ecma11BinaryProperties = ecma10BinaryProperties;+var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";+var ecma13BinaryProperties = ecma12BinaryProperties;+var ecma14BinaryProperties = ecma13BinaryProperties;+var unicodeBinaryProperties = {+ 9: ecma9BinaryProperties,+ 10: ecma10BinaryProperties,+ 11: ecma11BinaryProperties,+ 12: ecma12BinaryProperties,+ 13: ecma13BinaryProperties,+ 14: ecma14BinaryProperties+};+var ecma14BinaryPropertiesOfStrings = "Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji";+var unicodeBinaryPropertiesOfStrings = {+ 9: "",+ 10: "",+ 11: "",+ 12: "",+ 13: "",+ 14: ecma14BinaryPropertiesOfStrings+};+var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";+var ecma9ScriptValues = "Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";+var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";+var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";+var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";+var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith";+var ecma14ScriptValues = ecma13ScriptValues + " " + scriptValuesAddedInUnicode;+var unicodeScriptValues = {+ 9: ecma9ScriptValues,+ 10: ecma10ScriptValues,+ 11: ecma11ScriptValues,+ 12: ecma12ScriptValues,+ 13: ecma13ScriptValues,+ 14: ecma14ScriptValues+};+var data = {};+function buildUnicodeData(ecmaVersion2) {+ var d = data[ecmaVersion2] = {+ binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion2] + " " + unicodeGeneralCategoryValues),+ binaryOfStrings: wordsRegexp(unicodeBinaryPropertiesOfStrings[ecmaVersion2]),+ nonBinary: {+ General_Category: wordsRegexp(unicodeGeneralCategoryValues),+ Script: wordsRegexp(unicodeScriptValues[ecmaVersion2])+ }+ };+ d.nonBinary.Script_Extensions = d.nonBinary.Script;+ d.nonBinary.gc = d.nonBinary.General_Category;+ d.nonBinary.sc = d.nonBinary.Script;+ d.nonBinary.scx = d.nonBinary.Script_Extensions;+}+for (i = 0, list = [9, 10, 11, 12, 13, 14]; i < list.length; i += 1) {+ ecmaVersion = list[i];+ buildUnicodeData(ecmaVersion);+}+var ecmaVersion;+var i;+var list;+var pp$1 = Parser.prototype;+var BranchID = function BranchID2(parent, base) {+ this.parent = parent;+ this.base = base || this;+};+BranchID.prototype.separatedFrom = function separatedFrom(alt) {+ for (var self = this; self; self = self.parent) {+ for (var other = alt; other; other = other.parent) {+ if (self.base === other.base && self !== other) {+ return true;+ }+ }+ }+ return false;+};+BranchID.prototype.sibling = function sibling() {+ return new BranchID(this.parent, this.base);+};+var RegExpValidationState = function RegExpValidationState2(parser) {+ this.parser = parser;+ this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "") + (parser.options.ecmaVersion >= 15 ? "v" : "");+ this.unicodeProperties = data[parser.options.ecmaVersion >= 14 ? 14 : parser.options.ecmaVersion];+ this.source = "";+ this.flags = "";+ this.start = 0;+ this.switchU = false;+ this.switchV = false;+ this.switchN = false;+ this.pos = 0;+ this.lastIntValue = 0;+ this.lastStringValue = "";+ this.lastAssertionIsQuantifiable = false;+ this.numCapturingParens = 0;+ this.maxBackReference = 0;+ this.groupNames = /* @__PURE__ */ Object.create(null);+ this.backReferenceNames = [];+ this.branchID = null;+};+RegExpValidationState.prototype.reset = function reset(start, pattern, flags) {+ var unicodeSets = flags.indexOf("v") !== -1;+ var unicode = flags.indexOf("u") !== -1;+ this.start = start | 0;+ this.source = pattern + "";+ this.flags = flags;+ if (unicodeSets && this.parser.options.ecmaVersion >= 15) {+ this.switchU = true;+ this.switchV = true;+ this.switchN = true;+ } else {+ this.switchU = unicode && this.parser.options.ecmaVersion >= 6;+ this.switchV = false;+ this.switchN = unicode && this.parser.options.ecmaVersion >= 9;+ }+};+RegExpValidationState.prototype.raise = function raise(message) {+ this.parser.raiseRecoverable(this.start, "Invalid regular expression: /" + this.source + "/: " + message);+};+RegExpValidationState.prototype.at = function at(i2, forceU) {+ if (forceU === void 0) forceU = false;+ var s = this.source;+ var l = s.length;+ if (i2 >= l) {+ return -1;+ }+ var c = s.charCodeAt(i2);+ if (!(forceU || this.switchU) || c <= 55295 || c >= 57344 || i2 + 1 >= l) {+ return c;+ }+ var next = s.charCodeAt(i2 + 1);+ return next >= 56320 && next <= 57343 ? (c << 10) + next - 56613888 : c;+};+RegExpValidationState.prototype.nextIndex = function nextIndex(i2, forceU) {+ if (forceU === void 0) forceU = false;+ var s = this.source;+ var l = s.length;+ if (i2 >= l) {+ return l;+ }+ var c = s.charCodeAt(i2), next;+ if (!(forceU || this.switchU) || c <= 55295 || c >= 57344 || i2 + 1 >= l || (next = s.charCodeAt(i2 + 1)) < 56320 || next > 57343) {+ return i2 + 1;+ }+ return i2 + 2;+};+RegExpValidationState.prototype.current = function current(forceU) {+ if (forceU === void 0) forceU = false;+ return this.at(this.pos, forceU);+};+RegExpValidationState.prototype.lookahead = function lookahead(forceU) {+ if (forceU === void 0) forceU = false;+ return this.at(this.nextIndex(this.pos, forceU), forceU);+};+RegExpValidationState.prototype.advance = function advance(forceU) {+ if (forceU === void 0) forceU = false;+ this.pos = this.nextIndex(this.pos, forceU);+};+RegExpValidationState.prototype.eat = function eat(ch, forceU) {+ if (forceU === void 0) forceU = false;+ if (this.current(forceU) === ch) {+ this.advance(forceU);+ return true;+ }+ return false;+};+RegExpValidationState.prototype.eatChars = function eatChars(chs, forceU) {+ if (forceU === void 0) forceU = false;+ var pos = this.pos;+ for (var i2 = 0, list2 = chs; i2 < list2.length; i2 += 1) {+ var ch = list2[i2];+ var current2 = this.at(pos, forceU);+ if (current2 === -1 || current2 !== ch) {+ return false;+ }+ pos = this.nextIndex(pos, forceU);+ }+ this.pos = pos;+ return true;+};+pp$1.validateRegExpFlags = function(state) {+ var validFlags = state.validFlags;+ var flags = state.flags;+ var u = false;+ var v = false;+ for (var i2 = 0; i2 < flags.length; i2++) {+ var flag = flags.charAt(i2);+ if (validFlags.indexOf(flag) === -1) {+ this.raise(state.start, "Invalid regular expression flag");+ }+ if (flags.indexOf(flag, i2 + 1) > -1) {+ this.raise(state.start, "Duplicate regular expression flag");+ }+ if (flag === "u") {+ u = true;+ }+ if (flag === "v") {+ v = true;+ }+ }+ if (this.options.ecmaVersion >= 15 && u && v) {+ this.raise(state.start, "Invalid regular expression flag");+ }+};+function hasProp(obj) {+ for (var _ in obj) {+ return true;+ }+ return false;+}+pp$1.validateRegExpPattern = function(state) {+ this.regexp_pattern(state);+ if (!state.switchN && this.options.ecmaVersion >= 9 && hasProp(state.groupNames)) {+ state.switchN = true;+ this.regexp_pattern(state);+ }+};+pp$1.regexp_pattern = function(state) {+ state.pos = 0;+ state.lastIntValue = 0;+ state.lastStringValue = "";+ state.lastAssertionIsQuantifiable = false;+ state.numCapturingParens = 0;+ state.maxBackReference = 0;+ state.groupNames = /* @__PURE__ */ Object.create(null);+ state.backReferenceNames.length = 0;+ state.branchID = null;+ this.regexp_disjunction(state);+ if (state.pos !== state.source.length) {+ if (state.eat(+ 41+ /* ) */+ )) {+ state.raise("Unmatched ')'");+ }+ if (state.eat(+ 93+ /* ] */+ ) || state.eat(+ 125+ /* } */+ )) {+ state.raise("Lone quantifier brackets");+ }+ }+ if (state.maxBackReference > state.numCapturingParens) {+ state.raise("Invalid escape");+ }+ for (var i2 = 0, list2 = state.backReferenceNames; i2 < list2.length; i2 += 1) {+ var name = list2[i2];+ if (!state.groupNames[name]) {+ state.raise("Invalid named capture referenced");+ }+ }+};+pp$1.regexp_disjunction = function(state) {+ var trackDisjunction = this.options.ecmaVersion >= 16;+ if (trackDisjunction) {+ state.branchID = new BranchID(state.branchID, null);+ }+ this.regexp_alternative(state);+ while (state.eat(+ 124+ /* | */+ )) {+ if (trackDisjunction) {+ state.branchID = state.branchID.sibling();+ }+ this.regexp_alternative(state);+ }+ if (trackDisjunction) {+ state.branchID = state.branchID.parent;+ }+ if (this.regexp_eatQuantifier(state, true)) {+ state.raise("Nothing to repeat");+ }+ if (state.eat(+ 123+ /* { */+ )) {+ state.raise("Lone quantifier brackets");+ }+};+pp$1.regexp_alternative = function(state) {+ while (state.pos < state.source.length && this.regexp_eatTerm(state)) {+ }+};+pp$1.regexp_eatTerm = function(state) {+ if (this.regexp_eatAssertion(state)) {+ if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {+ if (state.switchU) {+ state.raise("Invalid quantifier");+ }+ }+ return true;+ }+ if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {+ this.regexp_eatQuantifier(state);+ return true;+ }+ return false;+};+pp$1.regexp_eatAssertion = function(state) {+ var start = state.pos;+ state.lastAssertionIsQuantifiable = false;+ if (state.eat(+ 94+ /* ^ */+ ) || state.eat(+ 36+ /* $ */+ )) {+ return true;+ }+ if (state.eat(+ 92+ /* \ */+ )) {+ if (state.eat(+ 66+ /* B */+ ) || state.eat(+ 98+ /* b */+ )) {+ return true;+ }+ state.pos = start;+ }+ if (state.eat(+ 40+ /* ( */+ ) && state.eat(+ 63+ /* ? */+ )) {+ var lookbehind = false;+ if (this.options.ecmaVersion >= 9) {+ lookbehind = state.eat(+ 60+ /* < */+ );+ }+ if (state.eat(+ 61+ /* = */+ ) || state.eat(+ 33+ /* ! */+ )) {+ this.regexp_disjunction(state);+ if (!state.eat(+ 41+ /* ) */+ )) {+ state.raise("Unterminated group");+ }+ state.lastAssertionIsQuantifiable = !lookbehind;+ return true;+ }+ }+ state.pos = start;+ return false;+};+pp$1.regexp_eatQuantifier = function(state, noError) {+ if (noError === void 0) noError = false;+ if (this.regexp_eatQuantifierPrefix(state, noError)) {+ state.eat(+ 63+ /* ? */+ );+ return true;+ }+ return false;+};+pp$1.regexp_eatQuantifierPrefix = function(state, noError) {+ return state.eat(+ 42+ /* * */+ ) || state.eat(+ 43+ /* + */+ ) || state.eat(+ 63+ /* ? */+ ) || this.regexp_eatBracedQuantifier(state, noError);+};+pp$1.regexp_eatBracedQuantifier = function(state, noError) {+ var start = state.pos;+ if (state.eat(+ 123+ /* { */+ )) {+ var min = 0, max = -1;+ if (this.regexp_eatDecimalDigits(state)) {+ min = state.lastIntValue;+ if (state.eat(+ 44+ /* , */+ ) && this.regexp_eatDecimalDigits(state)) {+ max = state.lastIntValue;+ }+ if (state.eat(+ 125+ /* } */+ )) {+ if (max !== -1 && max < min && !noError) {+ state.raise("numbers out of order in {} quantifier");+ }+ return true;+ }+ }+ if (state.switchU && !noError) {+ state.raise("Incomplete quantifier");+ }+ state.pos = start;+ }+ return false;+};+pp$1.regexp_eatAtom = function(state) {+ return this.regexp_eatPatternCharacters(state) || state.eat(+ 46+ /* . */+ ) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state);+};+pp$1.regexp_eatReverseSolidusAtomEscape = function(state) {+ var start = state.pos;+ if (state.eat(+ 92+ /* \ */+ )) {+ if (this.regexp_eatAtomEscape(state)) {+ return true;+ }+ state.pos = start;+ }+ return false;+};+pp$1.regexp_eatUncapturingGroup = function(state) {+ var start = state.pos;+ if (state.eat(+ 40+ /* ( */+ )) {+ if (state.eat(+ 63+ /* ? */+ )) {+ if (this.options.ecmaVersion >= 16) {+ var addModifiers = this.regexp_eatModifiers(state);+ var hasHyphen = state.eat(+ 45+ /* - */+ );+ if (addModifiers || hasHyphen) {+ for (var i2 = 0; i2 < addModifiers.length; i2++) {+ var modifier = addModifiers.charAt(i2);+ if (addModifiers.indexOf(modifier, i2 + 1) > -1) {+ state.raise("Duplicate regular expression modifiers");+ }+ }+ if (hasHyphen) {+ var removeModifiers = this.regexp_eatModifiers(state);+ if (!addModifiers && !removeModifiers && state.current() === 58) {+ state.raise("Invalid regular expression modifiers");+ }+ for (var i$1 = 0; i$1 < removeModifiers.length; i$1++) {+ var modifier$1 = removeModifiers.charAt(i$1);+ if (removeModifiers.indexOf(modifier$1, i$1 + 1) > -1 || addModifiers.indexOf(modifier$1) > -1) {+ state.raise("Duplicate regular expression modifiers");+ }+ }+ }+ }+ }+ if (state.eat(+ 58+ /* : */+ )) {+ this.regexp_disjunction(state);+ if (state.eat(+ 41+ /* ) */+ )) {+ return true;+ }+ state.raise("Unterminated group");+ }+ }+ state.pos = start;+ }+ return false;+};+pp$1.regexp_eatCapturingGroup = function(state) {+ if (state.eat(+ 40+ /* ( */+ )) {+ if (this.options.ecmaVersion >= 9) {+ this.regexp_groupSpecifier(state);+ } else if (state.current() === 63) {+ state.raise("Invalid group");+ }+ this.regexp_disjunction(state);+ if (state.eat(+ 41+ /* ) */+ )) {+ state.numCapturingParens += 1;+ return true;+ }+ state.raise("Unterminated group");+ }+ return false;+};+pp$1.regexp_eatModifiers = function(state) {+ var modifiers = "";+ var ch = 0;+ while ((ch = state.current()) !== -1 && isRegularExpressionModifier(ch)) {+ modifiers += codePointToString(ch);+ state.advance();+ }+ return modifiers;+};+function isRegularExpressionModifier(ch) {+ return ch === 105 || ch === 109 || ch === 115;+}+pp$1.regexp_eatExtendedAtom = function(state) {+ return state.eat(+ 46+ /* . */+ ) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state) || this.regexp_eatInvalidBracedQuantifier(state) || this.regexp_eatExtendedPatternCharacter(state);+};+pp$1.regexp_eatInvalidBracedQuantifier = function(state) {+ if (this.regexp_eatBracedQuantifier(state, true)) {+ state.raise("Nothing to repeat");+ }+ return false;+};+pp$1.regexp_eatSyntaxCharacter = function(state) {+ var ch = state.current();+ if (isSyntaxCharacter(ch)) {+ state.lastIntValue = ch;+ state.advance();+ return true;+ }+ return false;+};+function isSyntaxCharacter(ch) {+ return ch === 36 || ch >= 40 && ch <= 43 || ch === 46 || ch === 63 || ch >= 91 && ch <= 94 || ch >= 123 && ch <= 125;+}+pp$1.regexp_eatPatternCharacters = function(state) {+ var start = state.pos;+ var ch = 0;+ while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {+ state.advance();+ }+ return state.pos !== start;+};+pp$1.regexp_eatExtendedPatternCharacter = function(state) {+ var ch = state.current();+ if (ch !== -1 && ch !== 36 && !(ch >= 40 && ch <= 43) && ch !== 46 && ch !== 63 && ch !== 91 && ch !== 94 && ch !== 124) {+ state.advance();+ return true;+ }+ return false;+};+pp$1.regexp_groupSpecifier = function(state) {+ if (state.eat(+ 63+ /* ? */+ )) {+ if (!this.regexp_eatGroupName(state)) {+ state.raise("Invalid group");+ }+ var trackDisjunction = this.options.ecmaVersion >= 16;+ var known = state.groupNames[state.lastStringValue];+ if (known) {+ if (trackDisjunction) {+ for (var i2 = 0, list2 = known; i2 < list2.length; i2 += 1) {+ var altID = list2[i2];+ if (!altID.separatedFrom(state.branchID)) {+ state.raise("Duplicate capture group name");+ }+ }+ } else {+ state.raise("Duplicate capture group name");+ }+ }+ if (trackDisjunction) {+ (known || (state.groupNames[state.lastStringValue] = [])).push(state.branchID);+ } else {+ state.groupNames[state.lastStringValue] = true;+ }+ }+};+pp$1.regexp_eatGroupName = function(state) {+ state.lastStringValue = "";+ if (state.eat(+ 60+ /* < */+ )) {+ if (this.regexp_eatRegExpIdentifierName(state) && state.eat(+ 62+ /* > */+ )) {+ return true;+ }+ state.raise("Invalid capture group name");+ }+ return false;+};+pp$1.regexp_eatRegExpIdentifierName = function(state) {+ state.lastStringValue = "";+ if (this.regexp_eatRegExpIdentifierStart(state)) {+ state.lastStringValue += codePointToString(state.lastIntValue);+ while (this.regexp_eatRegExpIdentifierPart(state)) {+ state.lastStringValue += codePointToString(state.lastIntValue);+ }+ return true;+ }+ return false;+};+pp$1.regexp_eatRegExpIdentifierStart = function(state) {+ var start = state.pos;+ var forceU = this.options.ecmaVersion >= 11;+ var ch = state.current(forceU);+ state.advance(forceU);+ if (ch === 92 && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {+ ch = state.lastIntValue;+ }+ if (isRegExpIdentifierStart(ch)) {+ state.lastIntValue = ch;+ return true;+ }+ state.pos = start;+ return false;+};+function isRegExpIdentifierStart(ch) {+ return isIdentifierStart(ch, true) || ch === 36 || ch === 95;+}+pp$1.regexp_eatRegExpIdentifierPart = function(state) {+ var start = state.pos;+ var forceU = this.options.ecmaVersion >= 11;+ var ch = state.current(forceU);+ state.advance(forceU);+ if (ch === 92 && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {+ ch = state.lastIntValue;+ }+ if (isRegExpIdentifierPart(ch)) {+ state.lastIntValue = ch;+ return true;+ }+ state.pos = start;+ return false;+};+function isRegExpIdentifierPart(ch) {+ return isIdentifierChar(ch, true) || ch === 36 || ch === 95 || ch === 8204 || ch === 8205;+}+pp$1.regexp_eatAtomEscape = function(state) {+ if (this.regexp_eatBackReference(state) || this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) || state.switchN && this.regexp_eatKGroupName(state)) {+ return true;+ }+ if (state.switchU) {+ if (state.current() === 99) {+ state.raise("Invalid unicode escape");+ }+ state.raise("Invalid escape");+ }+ return false;+};+pp$1.regexp_eatBackReference = function(state) {+ var start = state.pos;+ if (this.regexp_eatDecimalEscape(state)) {+ var n = state.lastIntValue;+ if (state.switchU) {+ if (n > state.maxBackReference) {+ state.maxBackReference = n;+ }+ return true;+ }+ if (n <= state.numCapturingParens) {+ return true;+ }+ state.pos = start;+ }+ return false;+};+pp$1.regexp_eatKGroupName = function(state) {+ if (state.eat(+ 107+ /* k */+ )) {+ if (this.regexp_eatGroupName(state)) {+ state.backReferenceNames.push(state.lastStringValue);+ return true;+ }+ state.raise("Invalid named reference");+ }+ return false;+};+pp$1.regexp_eatCharacterEscape = function(state) {+ return this.regexp_eatControlEscape(state) || this.regexp_eatCControlLetter(state) || this.regexp_eatZero(state) || this.regexp_eatHexEscapeSequence(state) || this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || !state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state) || this.regexp_eatIdentityEscape(state);+};+pp$1.regexp_eatCControlLetter = function(state) {+ var start = state.pos;+ if (state.eat(+ 99+ /* c */+ )) {+ if (this.regexp_eatControlLetter(state)) {+ return true;+ }+ state.pos = start;+ }+ return false;+};+pp$1.regexp_eatZero = function(state) {+ if (state.current() === 48 && !isDecimalDigit(state.lookahead())) {+ state.lastIntValue = 0;+ state.advance();+ return true;+ }+ return false;+};+pp$1.regexp_eatControlEscape = function(state) {+ var ch = state.current();+ if (ch === 116) {+ state.lastIntValue = 9;+ state.advance();+ return true;+ }+ if (ch === 110) {+ state.lastIntValue = 10;+ state.advance();+ return true;+ }+ if (ch === 118) {+ state.lastIntValue = 11;+ state.advance();+ return true;+ }+ if (ch === 102) {+ state.lastIntValue = 12;+ state.advance();+ return true;+ }+ if (ch === 114) {+ state.lastIntValue = 13;+ state.advance();+ return true;+ }+ return false;+};+pp$1.regexp_eatControlLetter = function(state) {+ var ch = state.current();+ if (isControlLetter(ch)) {+ state.lastIntValue = ch % 32;+ state.advance();+ return true;+ }+ return false;+};+function isControlLetter(ch) {+ return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122;+}+pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {+ if (forceU === void 0) forceU = false;+ var start = state.pos;+ var switchU = forceU || state.switchU;+ if (state.eat(+ 117+ /* u */+ )) {+ if (this.regexp_eatFixedHexDigits(state, 4)) {+ var lead = state.lastIntValue;+ if (switchU && lead >= 55296 && lead <= 56319) {+ var leadSurrogateEnd = state.pos;+ if (state.eat(+ 92+ /* \ */+ ) && state.eat(+ 117+ /* u */+ ) && this.regexp_eatFixedHexDigits(state, 4)) {+ var trail = state.lastIntValue;+ if (trail >= 56320 && trail <= 57343) {+ state.lastIntValue = (lead - 55296) * 1024 + (trail - 56320) + 65536;+ return true;+ }+ }+ state.pos = leadSurrogateEnd;+ state.lastIntValue = lead;+ }+ return true;+ }+ if (switchU && state.eat(+ 123+ /* { */+ ) && this.regexp_eatHexDigits(state) && state.eat(+ 125+ /* } */+ ) && isValidUnicode(state.lastIntValue)) {+ return true;+ }+ if (switchU) {+ state.raise("Invalid unicode escape");+ }+ state.pos = start;+ }+ return false;+};+function isValidUnicode(ch) {+ return ch >= 0 && ch <= 1114111;+}+pp$1.regexp_eatIdentityEscape = function(state) {+ if (state.switchU) {+ if (this.regexp_eatSyntaxCharacter(state)) {+ return true;+ }+ if (state.eat(+ 47+ /* / */+ )) {+ state.lastIntValue = 47;+ return true;+ }+ return false;+ }+ var ch = state.current();+ if (ch !== 99 && (!state.switchN || ch !== 107)) {+ state.lastIntValue = ch;+ state.advance();+ return true;+ }+ return false;+};+pp$1.regexp_eatDecimalEscape = function(state) {+ state.lastIntValue = 0;+ var ch = state.current();+ if (ch >= 49 && ch <= 57) {+ do {+ state.lastIntValue = 10 * state.lastIntValue + (ch - 48);+ state.advance();+ } while ((ch = state.current()) >= 48 && ch <= 57);+ return true;+ }+ return false;+};+var CharSetNone = 0;+var CharSetOk = 1;+var CharSetString = 2;+pp$1.regexp_eatCharacterClassEscape = function(state) {+ var ch = state.current();+ if (isCharacterClassEscape(ch)) {+ state.lastIntValue = -1;+ state.advance();+ return CharSetOk;+ }+ var negate = false;+ if (state.switchU && this.options.ecmaVersion >= 9 && ((negate = ch === 80) || ch === 112)) {+ state.lastIntValue = -1;+ state.advance();+ var result;+ if (state.eat(+ 123+ /* { */+ ) && (result = this.regexp_eatUnicodePropertyValueExpression(state)) && state.eat(+ 125+ /* } */+ )) {+ if (negate && result === CharSetString) {+ state.raise("Invalid property name");+ }+ return result;+ }+ state.raise("Invalid property name");+ }+ return CharSetNone;+};+function isCharacterClassEscape(ch) {+ return ch === 100 || ch === 68 || ch === 115 || ch === 83 || ch === 119 || ch === 87;+}+pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {+ var start = state.pos;+ if (this.regexp_eatUnicodePropertyName(state) && state.eat(+ 61+ /* = */+ )) {+ var name = state.lastStringValue;+ if (this.regexp_eatUnicodePropertyValue(state)) {+ var value = state.lastStringValue;+ this.regexp_validateUnicodePropertyNameAndValue(state, name, value);+ return CharSetOk;+ }+ }+ state.pos = start;+ if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {+ var nameOrValue = state.lastStringValue;+ return this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);+ }+ return CharSetNone;+};+pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {+ if (!hasOwn(state.unicodeProperties.nonBinary, name)) {+ state.raise("Invalid property name");+ }+ if (!state.unicodeProperties.nonBinary[name].test(value)) {+ state.raise("Invalid property value");+ }+};+pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {+ if (state.unicodeProperties.binary.test(nameOrValue)) {+ return CharSetOk;+ }+ if (state.switchV && state.unicodeProperties.binaryOfStrings.test(nameOrValue)) {+ return CharSetString;+ }+ state.raise("Invalid property name");+};+pp$1.regexp_eatUnicodePropertyName = function(state) {+ var ch = 0;+ state.lastStringValue = "";+ while (isUnicodePropertyNameCharacter(ch = state.current())) {+ state.lastStringValue += codePointToString(ch);+ state.advance();+ }+ return state.lastStringValue !== "";+};+function isUnicodePropertyNameCharacter(ch) {+ return isControlLetter(ch) || ch === 95;+}+pp$1.regexp_eatUnicodePropertyValue = function(state) {+ var ch = 0;+ state.lastStringValue = "";+ while (isUnicodePropertyValueCharacter(ch = state.current())) {+ state.lastStringValue += codePointToString(ch);+ state.advance();+ }+ return state.lastStringValue !== "";+};+function isUnicodePropertyValueCharacter(ch) {+ return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch);+}+pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {+ return this.regexp_eatUnicodePropertyValue(state);+};+pp$1.regexp_eatCharacterClass = function(state) {+ if (state.eat(+ 91+ /* [ */+ )) {+ var negate = state.eat(+ 94+ /* ^ */+ );+ var result = this.regexp_classContents(state);+ if (!state.eat(+ 93+ /* ] */+ )) {+ state.raise("Unterminated character class");+ }+ if (negate && result === CharSetString) {+ state.raise("Negated character class may contain strings");+ }+ return true;+ }+ return false;+};+pp$1.regexp_classContents = function(state) {+ if (state.current() === 93) {+ return CharSetOk;+ }+ if (state.switchV) {+ return this.regexp_classSetExpression(state);+ }+ this.regexp_nonEmptyClassRanges(state);+ return CharSetOk;+};+pp$1.regexp_nonEmptyClassRanges = function(state) {+ while (this.regexp_eatClassAtom(state)) {+ var left = state.lastIntValue;+ if (state.eat(+ 45+ /* - */+ ) && this.regexp_eatClassAtom(state)) {+ var right = state.lastIntValue;+ if (state.switchU && (left === -1 || right === -1)) {+ state.raise("Invalid character class");+ }+ if (left !== -1 && right !== -1 && left > right) {+ state.raise("Range out of order in character class");+ }+ }+ }+};+pp$1.regexp_eatClassAtom = function(state) {+ var start = state.pos;+ if (state.eat(+ 92+ /* \ */+ )) {+ if (this.regexp_eatClassEscape(state)) {+ return true;+ }+ if (state.switchU) {+ var ch$1 = state.current();+ if (ch$1 === 99 || isOctalDigit(ch$1)) {+ state.raise("Invalid class escape");+ }+ state.raise("Invalid escape");+ }+ state.pos = start;+ }+ var ch = state.current();+ if (ch !== 93) {+ state.lastIntValue = ch;+ state.advance();+ return true;+ }+ return false;+};+pp$1.regexp_eatClassEscape = function(state) {+ var start = state.pos;+ if (state.eat(+ 98+ /* b */+ )) {+ state.lastIntValue = 8;+ return true;+ }+ if (state.switchU && state.eat(+ 45+ /* - */+ )) {+ state.lastIntValue = 45;+ return true;+ }+ if (!state.switchU && state.eat(+ 99+ /* c */+ )) {+ if (this.regexp_eatClassControlLetter(state)) {+ return true;+ }+ state.pos = start;+ }+ return this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state);+};+pp$1.regexp_classSetExpression = function(state) {+ var result = CharSetOk, subResult;+ if (this.regexp_eatClassSetRange(state)) ;+ else if (subResult = this.regexp_eatClassSetOperand(state)) {+ if (subResult === CharSetString) {+ result = CharSetString;+ }+ var start = state.pos;+ while (state.eatChars(+ [38, 38]+ /* && */+ )) {+ if (state.current() !== 38 && (subResult = this.regexp_eatClassSetOperand(state))) {+ if (subResult !== CharSetString) {+ result = CharSetOk;+ }+ continue;+ }+ state.raise("Invalid character in character class");+ }+ if (start !== state.pos) {+ return result;+ }+ while (state.eatChars(+ [45, 45]+ /* -- */+ )) {+ if (this.regexp_eatClassSetOperand(state)) {+ continue;+ }+ state.raise("Invalid character in character class");+ }+ if (start !== state.pos) {+ return result;+ }+ } else {+ state.raise("Invalid character in character class");+ }+ for (; ; ) {+ if (this.regexp_eatClassSetRange(state)) {+ continue;+ }+ subResult = this.regexp_eatClassSetOperand(state);+ if (!subResult) {+ return result;+ }+ if (subResult === CharSetString) {+ result = CharSetString;+ }+ }+};+pp$1.regexp_eatClassSetRange = function(state) {+ var start = state.pos;+ if (this.regexp_eatClassSetCharacter(state)) {+ var left = state.lastIntValue;+ if (state.eat(+ 45+ /* - */+ ) && this.regexp_eatClassSetCharacter(state)) {+ var right = state.lastIntValue;+ if (left !== -1 && right !== -1 && left > right) {+ state.raise("Range out of order in character class");+ }+ return true;+ }+ state.pos = start;+ }+ return false;+};+pp$1.regexp_eatClassSetOperand = function(state) {+ if (this.regexp_eatClassSetCharacter(state)) {+ return CharSetOk;+ }+ return this.regexp_eatClassStringDisjunction(state) || this.regexp_eatNestedClass(state);+};+pp$1.regexp_eatNestedClass = function(state) {+ var start = state.pos;+ if (state.eat(+ 91+ /* [ */+ )) {+ var negate = state.eat(+ 94+ /* ^ */+ );+ var result = this.regexp_classContents(state);+ if (state.eat(+ 93+ /* ] */+ )) {+ if (negate && result === CharSetString) {+ state.raise("Negated character class may contain strings");+ }+ return result;+ }+ state.pos = start;+ }+ if (state.eat(+ 92+ /* \ */+ )) {+ var result$1 = this.regexp_eatCharacterClassEscape(state);+ if (result$1) {+ return result$1;+ }+ state.pos = start;+ }+ return null;+};+pp$1.regexp_eatClassStringDisjunction = function(state) {+ var start = state.pos;+ if (state.eatChars(+ [92, 113]+ /* \q */+ )) {+ if (state.eat(+ 123+ /* { */+ )) {+ var result = this.regexp_classStringDisjunctionContents(state);+ if (state.eat(+ 125+ /* } */+ )) {+ return result;+ }+ } else {+ state.raise("Invalid escape");+ }+ state.pos = start;+ }+ return null;+};+pp$1.regexp_classStringDisjunctionContents = function(state) {+ var result = this.regexp_classString(state);+ while (state.eat(+ 124+ /* | */+ )) {+ if (this.regexp_classString(state) === CharSetString) {+ result = CharSetString;+ }+ }+ return result;+};+pp$1.regexp_classString = function(state) {+ var count = 0;+ while (this.regexp_eatClassSetCharacter(state)) {+ count++;+ }+ return count === 1 ? CharSetOk : CharSetString;+};+pp$1.regexp_eatClassSetCharacter = function(state) {+ var start = state.pos;+ if (state.eat(+ 92+ /* \ */+ )) {+ if (this.regexp_eatCharacterEscape(state) || this.regexp_eatClassSetReservedPunctuator(state)) {+ return true;+ }+ if (state.eat(+ 98+ /* b */+ )) {+ state.lastIntValue = 8;+ return true;+ }+ state.pos = start;+ return false;+ }+ var ch = state.current();+ if (ch < 0 || ch === state.lookahead() && isClassSetReservedDoublePunctuatorCharacter(ch)) {+ return false;+ }+ if (isClassSetSyntaxCharacter(ch)) {+ return false;+ }+ state.advance();+ state.lastIntValue = ch;+ return true;+};+function isClassSetReservedDoublePunctuatorCharacter(ch) {+ return ch === 33 || ch >= 35 && ch <= 38 || ch >= 42 && ch <= 44 || ch === 46 || ch >= 58 && ch <= 64 || ch === 94 || ch === 96 || ch === 126;+}+function isClassSetSyntaxCharacter(ch) {+ return ch === 40 || ch === 41 || ch === 45 || ch === 47 || ch >= 91 && ch <= 93 || ch >= 123 && ch <= 125;+}+pp$1.regexp_eatClassSetReservedPunctuator = function(state) {+ var ch = state.current();+ if (isClassSetReservedPunctuator(ch)) {+ state.lastIntValue = ch;+ state.advance();+ return true;+ }+ return false;+};+function isClassSetReservedPunctuator(ch) {+ return ch === 33 || ch === 35 || ch === 37 || ch === 38 || ch === 44 || ch === 45 || ch >= 58 && ch <= 62 || ch === 64 || ch === 96 || ch === 126;+}+pp$1.regexp_eatClassControlLetter = function(state) {+ var ch = state.current();+ if (isDecimalDigit(ch) || ch === 95) {+ state.lastIntValue = ch % 32;+ state.advance();+ return true;+ }+ return false;+};+pp$1.regexp_eatHexEscapeSequence = function(state) {+ var start = state.pos;+ if (state.eat(+ 120+ /* x */+ )) {+ if (this.regexp_eatFixedHexDigits(state, 2)) {+ return true;+ }+ if (state.switchU) {+ state.raise("Invalid escape");+ }+ state.pos = start;+ }+ return false;+};+pp$1.regexp_eatDecimalDigits = function(state) {+ var start = state.pos;+ var ch = 0;+ state.lastIntValue = 0;+ while (isDecimalDigit(ch = state.current())) {+ state.lastIntValue = 10 * state.lastIntValue + (ch - 48);+ state.advance();+ }+ return state.pos !== start;+};+function isDecimalDigit(ch) {+ return ch >= 48 && ch <= 57;+}+pp$1.regexp_eatHexDigits = function(state) {+ var start = state.pos;+ var ch = 0;+ state.lastIntValue = 0;+ while (isHexDigit(ch = state.current())) {+ state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);+ state.advance();+ }+ return state.pos !== start;+};+function isHexDigit(ch) {+ return ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102;+}+function hexToInt(ch) {+ if (ch >= 65 && ch <= 70) {+ return 10 + (ch - 65);+ }+ if (ch >= 97 && ch <= 102) {+ return 10 + (ch - 97);+ }+ return ch - 48;+}+pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) {+ if (this.regexp_eatOctalDigit(state)) {+ var n1 = state.lastIntValue;+ if (this.regexp_eatOctalDigit(state)) {+ var n2 = state.lastIntValue;+ if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {+ state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;+ } else {+ state.lastIntValue = n1 * 8 + n2;+ }+ } else {+ state.lastIntValue = n1;+ }+ return true;+ }+ return false;+};+pp$1.regexp_eatOctalDigit = function(state) {+ var ch = state.current();+ if (isOctalDigit(ch)) {+ state.lastIntValue = ch - 48;+ state.advance();+ return true;+ }+ state.lastIntValue = 0;+ return false;+};+function isOctalDigit(ch) {+ return ch >= 48 && ch <= 55;+}+pp$1.regexp_eatFixedHexDigits = function(state, length) {+ var start = state.pos;+ state.lastIntValue = 0;+ for (var i2 = 0; i2 < length; ++i2) {+ var ch = state.current();+ if (!isHexDigit(ch)) {+ state.pos = start;+ return false;+ }+ state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);+ state.advance();+ }+ return true;+};+var Token = function Token2(p) {+ this.type = p.type;+ this.value = p.value;+ this.start = p.start;+ this.end = p.end;+ if (p.options.locations) {+ this.loc = new SourceLocation(p, p.startLoc, p.endLoc);+ }+ if (p.options.ranges) {+ this.range = [p.start, p.end];+ }+};+var pp = Parser.prototype;+pp.next = function(ignoreEscapeSequenceInKeyword) {+ if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) {+ this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword);+ }+ if (this.options.onToken) {+ this.options.onToken(new Token(this));+ }+ this.lastTokEnd = this.end;+ this.lastTokStart = this.start;+ this.lastTokEndLoc = this.endLoc;+ this.lastTokStartLoc = this.startLoc;+ this.nextToken();+};+pp.getToken = function() {+ this.next();+ return new Token(this);+};+if (typeof Symbol !== "undefined") {+ pp[Symbol.iterator] = function() {+ var this$1$1 = this;+ return {+ next: function() {+ var token = this$1$1.getToken();+ return {+ done: token.type === types$1.eof,+ value: token+ };+ }+ };+ };+}+pp.nextToken = function() {+ var curContext = this.curContext();+ if (!curContext || !curContext.preserveSpace) {+ this.skipSpace();+ }+ this.start = this.pos;+ if (this.options.locations) {+ this.startLoc = this.curPosition();+ }+ if (this.pos >= this.input.length) {+ return this.finishToken(types$1.eof);+ }+ if (curContext.override) {+ return curContext.override(this);+ } else {+ this.readToken(this.fullCharCodeAtPos());+ }+};+pp.readToken = function(code) {+ if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92) {+ return this.readWord();+ }+ return this.getTokenFromCode(code);+};+pp.fullCharCodeAt = function(pos) {+ var code = this.input.charCodeAt(pos);+ if (code <= 55295 || code >= 56320) {+ return code;+ }+ var next = this.input.charCodeAt(pos + 1);+ return next <= 56319 || next >= 57344 ? code : (code << 10) + next - 56613888;+};+pp.fullCharCodeAtPos = function() {+ return this.fullCharCodeAt(this.pos);+};+pp.skipBlockComment = function() {+ var startLoc = this.options.onComment && this.curPosition();+ var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);+ if (end === -1) {+ this.raise(this.pos - 2, "Unterminated comment");+ }+ this.pos = end + 2;+ if (this.options.locations) {+ for (var nextBreak = void 0, pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1; ) {+ ++this.curLine;+ pos = this.lineStart = nextBreak;+ }+ }+ if (this.options.onComment) {+ this.options.onComment(+ true,+ this.input.slice(start + 2, end),+ start,+ this.pos,+ startLoc,+ this.curPosition()+ );+ }+};+pp.skipLineComment = function(startSkip) {+ var start = this.pos;+ var startLoc = this.options.onComment && this.curPosition();+ var ch = this.input.charCodeAt(this.pos += startSkip);+ while (this.pos < this.input.length && !isNewLine(ch)) {+ ch = this.input.charCodeAt(++this.pos);+ }+ if (this.options.onComment) {+ this.options.onComment(+ false,+ this.input.slice(start + startSkip, this.pos),+ start,+ this.pos,+ startLoc,+ this.curPosition()+ );+ }+};+pp.skipSpace = function() {+ loop: while (this.pos < this.input.length) {+ var ch = this.input.charCodeAt(this.pos);+ switch (ch) {+ case 32:+ case 160:+ ++this.pos;+ break;+ case 13:+ if (this.input.charCodeAt(this.pos + 1) === 10) {+ ++this.pos;+ }+ case 10:+ case 8232:+ case 8233:+ ++this.pos;+ if (this.options.locations) {+ ++this.curLine;+ this.lineStart = this.pos;+ }+ break;+ case 47:+ switch (this.input.charCodeAt(this.pos + 1)) {+ case 42:+ this.skipBlockComment();+ break;+ case 47:+ this.skipLineComment(2);+ break;+ default:+ break loop;+ }+ break;+ default:+ if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {+ ++this.pos;+ } else {+ break loop;+ }+ }+ }+};+pp.finishToken = function(type, val) {+ this.end = this.pos;+ if (this.options.locations) {+ this.endLoc = this.curPosition();+ }+ var prevType = this.type;+ this.type = type;+ this.value = val;+ this.updateContext(prevType);+};+pp.readToken_dot = function() {+ var next = this.input.charCodeAt(this.pos + 1);+ if (next >= 48 && next <= 57) {+ return this.readNumber(true);+ }+ var next2 = this.input.charCodeAt(this.pos + 2);+ if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) {+ this.pos += 3;+ return this.finishToken(types$1.ellipsis);+ } else {+ ++this.pos;+ return this.finishToken(types$1.dot);+ }+};+pp.readToken_slash = function() {+ var next = this.input.charCodeAt(this.pos + 1);+ if (this.exprAllowed) {+ ++this.pos;+ return this.readRegexp();+ }+ if (next === 61) {+ return this.finishOp(types$1.assign, 2);+ }+ return this.finishOp(types$1.slash, 1);+};+pp.readToken_mult_modulo_exp = function(code) {+ var next = this.input.charCodeAt(this.pos + 1);+ var size = 1;+ var tokentype = code === 42 ? types$1.star : types$1.modulo;+ if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {+ ++size;+ tokentype = types$1.starstar;+ next = this.input.charCodeAt(this.pos + 2);+ }+ if (next === 61) {+ return this.finishOp(types$1.assign, size + 1);+ }+ return this.finishOp(tokentype, size);+};+pp.readToken_pipe_amp = function(code) {+ var next = this.input.charCodeAt(this.pos + 1);+ if (next === code) {+ if (this.options.ecmaVersion >= 12) {+ var next2 = this.input.charCodeAt(this.pos + 2);+ if (next2 === 61) {+ return this.finishOp(types$1.assign, 3);+ }+ }+ return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2);+ }+ if (next === 61) {+ return this.finishOp(types$1.assign, 2);+ }+ return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1);+};+pp.readToken_caret = function() {+ var next = this.input.charCodeAt(this.pos + 1);+ if (next === 61) {+ return this.finishOp(types$1.assign, 2);+ }+ return this.finishOp(types$1.bitwiseXOR, 1);+};+pp.readToken_plus_min = function(code) {+ var next = this.input.charCodeAt(this.pos + 1);+ if (next === code) {+ if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {+ this.skipLineComment(3);+ this.skipSpace();+ return this.nextToken();+ }+ return this.finishOp(types$1.incDec, 2);+ }+ if (next === 61) {+ return this.finishOp(types$1.assign, 2);+ }+ return this.finishOp(types$1.plusMin, 1);+};+pp.readToken_lt_gt = function(code) {+ var next = this.input.charCodeAt(this.pos + 1);+ var size = 1;+ if (next === code) {+ size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;+ if (this.input.charCodeAt(this.pos + size) === 61) {+ return this.finishOp(types$1.assign, size + 1);+ }+ return this.finishOp(types$1.bitShift, size);+ }+ if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && this.input.charCodeAt(this.pos + 3) === 45) {+ this.skipLineComment(4);+ this.skipSpace();+ return this.nextToken();+ }+ if (next === 61) {+ size = 2;+ }+ return this.finishOp(types$1.relational, size);+};+pp.readToken_eq_excl = function(code) {+ var next = this.input.charCodeAt(this.pos + 1);+ if (next === 61) {+ return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2);+ }+ if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) {+ this.pos += 2;+ return this.finishToken(types$1.arrow);+ }+ return this.finishOp(code === 61 ? types$1.eq : types$1.prefix, 1);+};+pp.readToken_question = function() {+ var ecmaVersion2 = this.options.ecmaVersion;+ if (ecmaVersion2 >= 11) {+ var next = this.input.charCodeAt(this.pos + 1);+ if (next === 46) {+ var next2 = this.input.charCodeAt(this.pos + 2);+ if (next2 < 48 || next2 > 57) {+ return this.finishOp(types$1.questionDot, 2);+ }+ }+ if (next === 63) {+ if (ecmaVersion2 >= 12) {+ var next2$1 = this.input.charCodeAt(this.pos + 2);+ if (next2$1 === 61) {+ return this.finishOp(types$1.assign, 3);+ }+ }+ return this.finishOp(types$1.coalesce, 2);+ }+ }+ return this.finishOp(types$1.question, 1);+};+pp.readToken_numberSign = function() {+ var ecmaVersion2 = this.options.ecmaVersion;+ var code = 35;+ if (ecmaVersion2 >= 13) {+ ++this.pos;+ code = this.fullCharCodeAtPos();+ if (isIdentifierStart(code, true) || code === 92) {+ return this.finishToken(types$1.privateId, this.readWord1());+ }+ }+ this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");+};+pp.getTokenFromCode = function(code) {+ switch (code) {+ // The interpretation of a dot depends on whether it is followed+ // by a digit or another two dots.+ case 46:+ return this.readToken_dot();+ // Punctuation tokens.+ case 40:+ ++this.pos;+ return this.finishToken(types$1.parenL);+ case 41:+ ++this.pos;+ return this.finishToken(types$1.parenR);+ case 59:+ ++this.pos;+ return this.finishToken(types$1.semi);+ case 44:+ ++this.pos;+ return this.finishToken(types$1.comma);+ case 91:+ ++this.pos;+ return this.finishToken(types$1.bracketL);+ case 93:+ ++this.pos;+ return this.finishToken(types$1.bracketR);+ case 123:+ ++this.pos;+ return this.finishToken(types$1.braceL);+ case 125:+ ++this.pos;+ return this.finishToken(types$1.braceR);+ case 58:+ ++this.pos;+ return this.finishToken(types$1.colon);+ case 96:+ if (this.options.ecmaVersion < 6) {+ break;+ }+ ++this.pos;+ return this.finishToken(types$1.backQuote);+ case 48:+ var next = this.input.charCodeAt(this.pos + 1);+ if (next === 120 || next === 88) {+ return this.readRadixNumber(16);+ }+ if (this.options.ecmaVersion >= 6) {+ if (next === 111 || next === 79) {+ return this.readRadixNumber(8);+ }+ if (next === 98 || next === 66) {+ return this.readRadixNumber(2);+ }+ }+ // Anything else beginning with a digit is an integer, octal+ // number, or float.+ case 49:+ case 50:+ case 51:+ case 52:+ case 53:+ case 54:+ case 55:+ case 56:+ case 57:+ return this.readNumber(false);+ // Quotes produce strings.+ case 34:+ case 39:+ return this.readString(code);+ // Operators are parsed inline in tiny state machines. '=' (61) is+ // often referred to. `finishOp` simply skips the amount of+ // characters it is given as second argument, and returns a token+ // of the type given by its first argument.+ case 47:+ return this.readToken_slash();+ case 37:+ case 42:+ return this.readToken_mult_modulo_exp(code);+ case 124:+ case 38:+ return this.readToken_pipe_amp(code);+ case 94:+ return this.readToken_caret();+ case 43:+ case 45:+ return this.readToken_plus_min(code);+ case 60:+ case 62:+ return this.readToken_lt_gt(code);+ case 61:+ case 33:+ return this.readToken_eq_excl(code);+ case 63:+ return this.readToken_question();+ case 126:+ return this.finishOp(types$1.prefix, 1);+ case 35:+ return this.readToken_numberSign();+ }+ this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");+};+pp.finishOp = function(type, size) {+ var str = this.input.slice(this.pos, this.pos + size);+ this.pos += size;+ return this.finishToken(type, str);+};+pp.readRegexp = function() {+ var escaped, inClass, start = this.pos;+ for (; ; ) {+ if (this.pos >= this.input.length) {+ this.raise(start, "Unterminated regular expression");+ }+ var ch = this.input.charAt(this.pos);+ if (lineBreak.test(ch)) {+ this.raise(start, "Unterminated regular expression");+ }+ if (!escaped) {+ if (ch === "[") {+ inClass = true;+ } else if (ch === "]" && inClass) {+ inClass = false;+ } else if (ch === "/" && !inClass) {+ break;+ }+ escaped = ch === "\\";+ } else {+ escaped = false;+ }+ ++this.pos;+ }+ var pattern = this.input.slice(start, this.pos);+ ++this.pos;+ var flagsStart = this.pos;+ var flags = this.readWord1();+ if (this.containsEsc) {+ this.unexpected(flagsStart);+ }+ var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));+ state.reset(start, pattern, flags);+ this.validateRegExpFlags(state);+ this.validateRegExpPattern(state);+ var value = null;+ try {+ value = new RegExp(pattern, flags);+ } catch (e) {+ }+ return this.finishToken(types$1.regexp, { pattern, flags, value });+};+pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {+ var allowSeparators = this.options.ecmaVersion >= 12 && len === void 0;+ var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;+ var start = this.pos, total = 0, lastCode = 0;+ for (var i2 = 0, e = len == null ? Infinity : len; i2 < e; ++i2, ++this.pos) {+ var code = this.input.charCodeAt(this.pos), val = void 0;+ if (allowSeparators && code === 95) {+ if (isLegacyOctalNumericLiteral) {+ this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals");+ }+ if (lastCode === 95) {+ this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore");+ }+ if (i2 === 0) {+ this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits");+ }+ lastCode = code;+ continue;+ }+ if (code >= 97) {+ val = code - 97 + 10;+ } else if (code >= 65) {+ val = code - 65 + 10;+ } else if (code >= 48 && code <= 57) {+ val = code - 48;+ } else {+ val = Infinity;+ }+ if (val >= radix) {+ break;+ }+ lastCode = code;+ total = total * radix + val;+ }+ if (allowSeparators && lastCode === 95) {+ this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits");+ }+ if (this.pos === start || len != null && this.pos - start !== len) {+ return null;+ }+ return total;+};+function stringToNumber(str, isLegacyOctalNumericLiteral) {+ if (isLegacyOctalNumericLiteral) {+ return parseInt(str, 8);+ }+ return parseFloat(str.replace(/_/g, ""));+}+function stringToBigInt(str) {+ if (typeof BigInt !== "function") {+ return null;+ }+ return BigInt(str.replace(/_/g, ""));+}+pp.readRadixNumber = function(radix) {+ var start = this.pos;+ this.pos += 2;+ var val = this.readInt(radix);+ if (val == null) {+ this.raise(this.start + 2, "Expected number in radix " + radix);+ }+ if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {+ val = stringToBigInt(this.input.slice(start, this.pos));+ ++this.pos;+ } else if (isIdentifierStart(this.fullCharCodeAtPos())) {+ this.raise(this.pos, "Identifier directly after number");+ }+ return this.finishToken(types$1.num, val);+};+pp.readNumber = function(startsWithDot) {+ var start = this.pos;+ if (!startsWithDot && this.readInt(10, void 0, true) === null) {+ this.raise(start, "Invalid number");+ }+ var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;+ if (octal && this.strict) {+ this.raise(start, "Invalid number");+ }+ var next = this.input.charCodeAt(this.pos);+ if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {+ var val$1 = stringToBigInt(this.input.slice(start, this.pos));+ ++this.pos;+ if (isIdentifierStart(this.fullCharCodeAtPos())) {+ this.raise(this.pos, "Identifier directly after number");+ }+ return this.finishToken(types$1.num, val$1);+ }+ if (octal && /[89]/.test(this.input.slice(start, this.pos))) {+ octal = false;+ }+ if (next === 46 && !octal) {+ ++this.pos;+ this.readInt(10);+ next = this.input.charCodeAt(this.pos);+ }+ if ((next === 69 || next === 101) && !octal) {+ next = this.input.charCodeAt(++this.pos);+ if (next === 43 || next === 45) {+ ++this.pos;+ }+ if (this.readInt(10) === null) {+ this.raise(start, "Invalid number");+ }+ }+ if (isIdentifierStart(this.fullCharCodeAtPos())) {+ this.raise(this.pos, "Identifier directly after number");+ }+ var val = stringToNumber(this.input.slice(start, this.pos), octal);+ return this.finishToken(types$1.num, val);+};+pp.readCodePoint = function() {+ var ch = this.input.charCodeAt(this.pos), code;+ if (ch === 123) {+ if (this.options.ecmaVersion < 6) {+ this.unexpected();+ }+ var codePos = ++this.pos;+ code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);+ ++this.pos;+ if (code > 1114111) {+ this.invalidStringToken(codePos, "Code point out of bounds");+ }+ } else {+ code = this.readHexChar(4);+ }+ return code;+};+pp.readString = function(quote) {+ var out = "", chunkStart = ++this.pos;+ for (; ; ) {+ if (this.pos >= this.input.length) {+ this.raise(this.start, "Unterminated string constant");+ }+ var ch = this.input.charCodeAt(this.pos);+ if (ch === quote) {+ break;+ }+ if (ch === 92) {+ out += this.input.slice(chunkStart, this.pos);+ out += this.readEscapedChar(false);+ chunkStart = this.pos;+ } else if (ch === 8232 || ch === 8233) {+ if (this.options.ecmaVersion < 10) {+ this.raise(this.start, "Unterminated string constant");+ }+ ++this.pos;+ if (this.options.locations) {+ this.curLine++;+ this.lineStart = this.pos;+ }+ } else {+ if (isNewLine(ch)) {+ this.raise(this.start, "Unterminated string constant");+ }+ ++this.pos;+ }+ }+ out += this.input.slice(chunkStart, this.pos++);+ return this.finishToken(types$1.string, out);+};+var INVALID_TEMPLATE_ESCAPE_ERROR = {};+pp.tryReadTemplateToken = function() {+ this.inTemplateElement = true;+ try {+ this.readTmplToken();+ } catch (err) {+ if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {+ this.readInvalidTemplateToken();+ } else {+ throw err;+ }+ }+ this.inTemplateElement = false;+};+pp.invalidStringToken = function(position, message) {+ if (this.inTemplateElement && this.options.ecmaVersion >= 9) {+ throw INVALID_TEMPLATE_ESCAPE_ERROR;+ } else {+ this.raise(position, message);+ }+};+pp.readTmplToken = function() {+ var out = "", chunkStart = this.pos;+ for (; ; ) {+ if (this.pos >= this.input.length) {+ this.raise(this.start, "Unterminated template");+ }+ var ch = this.input.charCodeAt(this.pos);+ if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) {+ if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) {+ if (ch === 36) {+ this.pos += 2;+ return this.finishToken(types$1.dollarBraceL);+ } else {+ ++this.pos;+ return this.finishToken(types$1.backQuote);+ }+ }+ out += this.input.slice(chunkStart, this.pos);+ return this.finishToken(types$1.template, out);+ }+ if (ch === 92) {+ out += this.input.slice(chunkStart, this.pos);+ out += this.readEscapedChar(true);+ chunkStart = this.pos;+ } else if (isNewLine(ch)) {+ out += this.input.slice(chunkStart, this.pos);+ ++this.pos;+ switch (ch) {+ case 13:+ if (this.input.charCodeAt(this.pos) === 10) {+ ++this.pos;+ }+ case 10:+ out += "\n";+ break;+ default:+ out += String.fromCharCode(ch);+ break;+ }+ if (this.options.locations) {+ ++this.curLine;+ this.lineStart = this.pos;+ }+ chunkStart = this.pos;+ } else {+ ++this.pos;+ }+ }+};+pp.readInvalidTemplateToken = function() {+ for (; this.pos < this.input.length; this.pos++) {+ switch (this.input[this.pos]) {+ case "\\":+ ++this.pos;+ break;+ case "$":+ if (this.input[this.pos + 1] !== "{") {+ break;+ }+ // fall through+ case "`":+ return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos));+ case "\r":+ if (this.input[this.pos + 1] === "\n") {+ ++this.pos;+ }+ // fall through+ case "\n":+ case "\u2028":+ case "\u2029":+ ++this.curLine;+ this.lineStart = this.pos + 1;+ break;+ }+ }+ this.raise(this.start, "Unterminated template");+};+pp.readEscapedChar = function(inTemplate) {+ var ch = this.input.charCodeAt(++this.pos);+ ++this.pos;+ switch (ch) {+ case 110:+ return "\n";+ // 'n' -> '\n'+ case 114:+ return "\r";+ // 'r' -> '\r'+ case 120:+ return String.fromCharCode(this.readHexChar(2));+ // 'x'+ case 117:+ return codePointToString(this.readCodePoint());+ // 'u'+ case 116:+ return " ";+ // 't' -> '\t'+ case 98:+ return "\b";+ // 'b' -> '\b'+ case 118:+ return "\v";+ // 'v' -> '\u000b'+ case 102:+ return "\f";+ // 'f' -> '\f'+ case 13:+ if (this.input.charCodeAt(this.pos) === 10) {+ ++this.pos;+ }+ // '\r\n'+ case 10:+ if (this.options.locations) {+ this.lineStart = this.pos;+ ++this.curLine;+ }+ return "";+ case 56:+ case 57:+ if (this.strict) {+ this.invalidStringToken(+ this.pos - 1,+ "Invalid escape sequence"+ );+ }+ if (inTemplate) {+ var codePos = this.pos - 1;+ this.invalidStringToken(+ codePos,+ "Invalid escape sequence in template string"+ );+ }+ default:+ if (ch >= 48 && ch <= 55) {+ var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];+ var octal = parseInt(octalStr, 8);+ if (octal > 255) {+ octalStr = octalStr.slice(0, -1);+ octal = parseInt(octalStr, 8);+ }+ this.pos += octalStr.length - 1;+ ch = this.input.charCodeAt(this.pos);+ if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {+ this.invalidStringToken(+ this.pos - 1 - octalStr.length,+ inTemplate ? "Octal literal in template string" : "Octal literal in strict mode"+ );+ }+ return String.fromCharCode(octal);+ }+ if (isNewLine(ch)) {+ if (this.options.locations) {+ this.lineStart = this.pos;+ ++this.curLine;+ }+ return "";+ }+ return String.fromCharCode(ch);+ }+};+pp.readHexChar = function(len) {+ var codePos = this.pos;+ var n = this.readInt(16, len);+ if (n === null) {+ this.invalidStringToken(codePos, "Bad character escape sequence");+ }+ return n;+};+pp.readWord1 = function() {+ this.containsEsc = false;+ var word = "", first = true, chunkStart = this.pos;+ var astral = this.options.ecmaVersion >= 6;+ while (this.pos < this.input.length) {+ var ch = this.fullCharCodeAtPos();+ if (isIdentifierChar(ch, astral)) {+ this.pos += ch <= 65535 ? 1 : 2;+ } else if (ch === 92) {+ this.containsEsc = true;+ word += this.input.slice(chunkStart, this.pos);+ var escStart = this.pos;+ if (this.input.charCodeAt(++this.pos) !== 117) {+ this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX");+ }+ ++this.pos;+ var esc = this.readCodePoint();+ if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral)) {+ this.invalidStringToken(escStart, "Invalid Unicode escape");+ }+ word += codePointToString(esc);+ chunkStart = this.pos;+ } else {+ break;+ }+ first = false;+ }+ return word + this.input.slice(chunkStart, this.pos);+};+pp.readWord = function() {+ var word = this.readWord1();+ var type = types$1.name;+ if (this.keywords.test(word)) {+ type = keywords[word];+ }+ return this.finishToken(type, word);+};+var version = "8.18.0";+Parser.acorn = {+ Parser,+ version,+ defaultOptions,+ Position,+ SourceLocation,+ getLineInfo,+ Node,+ TokenType,+ tokTypes: types$1,+ keywordTypes: keywords,+ TokContext,+ tokContexts: types,+ isIdentifierChar,+ isIdentifierStart,+ Token,+ isNewLine,+ lineBreak,+ lineBreakG,+ nonASCIIwhitespace+};+function parse3(input, options) {+ return Parser.parse(input, options);+}+function parseExpressionAt2(input, pos, options) {+ return Parser.parseExpressionAt(input, pos, options);+}+function tokenizer2(input, options) {+ return Parser.tokenizer(input, options);+}+// Annotate the CommonJS export names for ESM import in node:+0 && (module.exports = {+ Node,+ Parser,+ Position,+ SourceLocation,+ TokContext,+ Token,+ TokenType,+ defaultOptions,+ getLineInfo,+ isIdentifierChar,+ isIdentifierStart,+ isNewLine,+ keywordTypes,+ lineBreak,+ lineBreakG,+ nonASCIIwhitespace,+ parse,+ parseExpressionAt,+ tokContexts,+ tokTypes,+ tokenizer,+ version+});diff --git a/plugins/model-apps/scripts/tests/verify-spec.test.js b/plugins/model-apps/scripts/tests/verify-spec.test.jsindex fee4202cc..abc2cf950 100644--- a/plugins/model-apps/scripts/tests/verify-spec.test.js+++ b/plugins/model-apps/scripts/tests/verify-spec.test.js@@ -1,799 +1,809 @@-'use strict';-const { test } = require('node:test');-const assert = require('node:assert');-const { verifySpec, hasElement } = require('../lib/verify-spec.js');-const { sitemapXmlFor } = require('../verify-model-app.js');-const { SDK_ROLE_MARKER } = require('../lib/app-spec.js');--const idFor = (set) => ({ savedquery: 'savedqueryid', savedqueryvisualization: 'savedqueryvisualizationid', systemform: 'formid' }[set] || 'id');--test('verifySpec: everything present -> ok', async () => {- const spec = {- entities: [{ schemaName: 'new_o', columns: [{ schemaName: 'new_s' }] }],- views: [{ entity: 'new_o', name: 'V' }],- charts: [{ entity: 'new_o', name: 'C' }],- forms: [{ entity: 'new_o', name: 'F' }],- appShell: { areas: [{ label: 'Main', icon: 'a.png', groups: [{ subAreas: [{ entity: 'new_o', title: 'O', icon: 'ic.png' }] }] }] },- };- const read = {- findTable: async () => ({ logicalName: 'new_o' }),- findColumns: async () => [{ logicalName: 'new_s' }],- queryRecords: async (set) => [{ [idFor(set)]: 'id-1' }],- sitemapXml: async () => '<SiteMap><Area Icon="a.png"><SubArea Entity="new_o" Icon="ic.png"/></Area></SiteMap>',- };- const r = await verifySpec(spec, read);- assert.strictEqual(r.ok, true, JSON.stringify(r.missing));- assert.ok(r.checks.some((c) => c.kind === 'subarea-icon' && c.present));-});--test('verifySpec: flags a missing column, view, and subarea icon', async () => {- const spec = {- entities: [{ schemaName: 'new_o', columns: [{ schemaName: 'new_s' }] }],- views: [{ entity: 'new_o', name: 'V' }],- forms: [],- charts: [],- appShell: { areas: [{ groups: [{ subAreas: [{ entity: 'new_o', title: 'O', icon: 'ic.png' }] }] }] },- };- const read = {- findTable: async () => ({ logicalName: 'new_o' }),- findColumns: async () => [], // column missing- queryRecords: async () => [], // view missing- sitemapXml: async () => '<SiteMap><SubArea Entity="new_o"/></SiteMap>', // icon missing (subarea present)- };- const r = await verifySpec(spec, read);- assert.strictEqual(r.ok, false);- assert.ok(r.missing.some((m) => m.kind === 'column'));- assert.ok(r.missing.some((m) => m.kind === 'view'));- assert.ok(r.missing.some((m) => m.kind === 'subarea-icon'));- assert.ok(r.checks.some((c) => c.kind === 'subarea' && c.present), 'the subarea itself is present');-});--test('verifySpec: a missing entity skips its column checks', async () => {- const spec = { entities: [{ schemaName: 'new_o', columns: [{ schemaName: 'new_s' }] }], appShell: { areas: [] } };- const read = { findTable: async () => null, findColumns: async () => [], queryRecords: async () => [], sitemapXml: async () => '' };- const r = await verifySpec(spec, read);- assert.ok(r.missing.some((m) => m.kind === 'entity'));- assert.ok(!r.checks.some((c) => c.kind === 'column'), 'no column checks when the entity is absent');-});--test('verifySpec reports missing entities without propagating dependent Dataverse read errors', async () => {- const spec = {- entities: [{ schemaName: 'new_missing', columns: [] }],- views: [{ entity: 'new_missing', name: 'Missing View' }],- appShell: { areas: [] },- };- const read = {- findTable: async () => null,- findColumns: async () => [],- queryRecords: async () => {- throw new Error('HTTP 400 metadata cache: entity was not found');- },- sitemapXml: async () => '',- };-- const r = await verifySpec(spec, read);-- assert.equal(r.ok, false);- assert.ok(r.missing.some((m) => m.kind === 'entity'));- assert.ok(r.missing.some((m) => m.kind === 'view'));-});--test('verifySpec: a Main form check is type-scoped — a same-named Quick View sibling does NOT satisfy it', async () => {- const spec = { entities: [], views: [], charts: [], forms: [{ entity: 'zava_javavendor', name: 'Information', formType: 'Main' }], appShell: { areas: [] } };- let captured;- const read = {- findTable: async () => null, findColumns: async () => [],- // Only a same-named Quick View exists; the type-scoped Main (type 2) query must find nothing.- queryRecords: async (set, opts) => { if (set === 'systemform') { captured = opts.filter; return /type eq 2/.test(opts.filter) ? [] : [{ formid: 'qv-1' }]; } return []; },- sitemapXml: async () => '',- };- const r = await verifySpec(spec, read);- assert.match(captured, /objecttypecode eq 'zava_javavendor' and name eq 'Information' and type eq 2/, 'verify scopes the Main form query by type');- assert.ok(r.missing.some((m) => m.kind === 'form'), 'the Main form is correctly reported MISSING — a same-named Quick View does not count (no false pass)');-});--test('verifySpec: an icon present only on a different element does not satisfy the check (scoped)', async () => {- const spec = {- entities: [], views: [], charts: [], forms: [],- appShell: { areas: [{ label: 'Main', icon: 'shared.png', groups: [{ subAreas: [{ entity: 'new_o', title: 'O', icon: 'shared.png' }] }] }] },- };- const read = {- findTable: async () => null,- findColumns: async () => [],- queryRecords: async () => [],- // 'shared.png' appears ONLY on the SubArea, never on the Area.- sitemapXml: async () => '<SiteMap><Area Icon="area-only.png"><SubArea Entity="new_o" Icon="shared.png"/></Area></SiteMap>',- };- const r = await verifySpec(spec, read);- assert.ok(r.missing.some((m) => m.kind === 'area-icon'), 'area icon missing even though the same icon exists on a subarea');- assert.ok(r.checks.some((c) => c.kind === 'subarea-icon' && c.present), 'subarea icon correctly matched on its own SubArea');-});--test('hasElement scopes attribute matching to the named element start-tag', () => {- const xml = '<SiteMap><Area Icon="a.png"><SubArea Entity="new_o" Icon="ic.png"/></Area></SiteMap>';- assert.strictEqual(hasElement(xml, 'Area', { Icon: 'a.png' }), true);- assert.strictEqual(hasElement(xml, 'Area', { Icon: 'ic.png' }), false, 'a SubArea icon must not match an Area check');- assert.strictEqual(hasElement(xml, 'SubArea', { Entity: 'new_o', Icon: 'ic.png' }), true, 'both attrs on the same SubArea');- assert.strictEqual(hasElement(xml, 'SubArea', { Entity: 'new_o', Icon: 'a.png' }), false, 'icon lives on the Area, not this SubArea');-});--test('verifySpec: dashboard subarea resolves the dashboard id and matches the sitemap DefaultDashboard', async () => {- const DASH = 'AAaa1111-2222-3333-4444-555566667777';- const spec = {- entities: [], views: [], charts: [], forms: [],- appShell: { areas: [{ groups: [{ subAreas: [{ dashboard: 'Ops', title: 'Ops' }] }] }] },- };- const present = {- findTable: async () => null, findColumns: async () => [],- queryRecords: async (set, opts) => (set === 'systemform' && /name eq 'Ops'/.test(opts.filter) ? [{ formid: DASH }] : []),- // Sitemap points a SubArea at the resolved dashboard id (Dataverse upper-cases + brace-wraps it).- sitemapXml: async () => `<SiteMap><Area><SubArea Id="s" DefaultDashboard="{${DASH.toUpperCase()}}"/></Area></SiteMap>`,- };- const ok = await verifySpec(spec, present);- assert.ok(ok.checks.some((c) => c.kind === 'subarea' && c.present), 'dashboard subarea matched by resolved id (brace/case-insensitive)');-- // A different dashboard id in the sitemap must NOT satisfy the check.- const wrong = { ...present, sitemapXml: async () => '<SiteMap><Area><SubArea Id="s" DefaultDashboard="99999999-0000-0000-0000-000000000000"/></Area></SiteMap>' };- const bad = await verifySpec(spec, wrong);- assert.ok(bad.missing.some((m) => m.kind === 'subarea'), 'a different dashboard id does not satisfy the check');-});--test('sitemapXmlFor resolves appmodule -> component 62 -> sitemap', async () => {- const sdk = {- queryRecords: async (set) => {- if (set === 'appmodule') return [{ appmoduleid: 'a', appmoduleidunique: 'u-1' }];- if (set === 'appmodulecomponent') return [{ objectid: 'sm-1', componenttype: 62 }];- if (set === 'sitemap') return [{ sitemapxml: '<SiteMap/>' }];- return [];- },- };- assert.strictEqual(await sitemapXmlFor(sdk, 'new_app'), '<SiteMap/>');-});--test('sitemapXmlFor returns empty when the app is not found', async () => {- const sdk = { queryRecords: async () => [] };- assert.strictEqual(await sitemapXmlFor(sdk, 'new_missing'), '');-});--// ----------------------------------------------------------------------------// Page branch tests — Task 7: three-authority (IDENTITY+EXISTENCE+MEMBERSHIP)-// ----------------------------------------------------------------------------// Plan 5 GUIDs (Imp9): real 36-char GUIDs in every mock.-const GP_OVERVIEW = '13ecbc57-a3a4-4132-b0a2-a6c6b12691e8';-const GP_DETAIL = '5c0a4889-45fd-46ea-91a8-ff876914d644';-const GP_EXTRA = '9f2b1a3c-77de-4a10-8b6e-2c4d5e6f7a8b';--// Reader mock: supplies all three authorities (sitemapPageIds/existenceIds/manifest) + pageCode.-// Tests set each authority independently to exercise specific check paths.-function pageRead({ sitemapIds, existenceIds, manifest, code, sitemap }) {- return {- findTable: async () => ({ logicalName: 'contoso_item' }),- findColumns: async () => [],- queryRecords: async () => [],- sitemapXml: async () => sitemap || '',- sitemapPageIds: async () => sitemapIds || [],- existenceIds: async () => existenceIds || [],- manifest: async () => manifest || null,- pageCode: async (id) => (code && code[String(id).toLowerCase()]) || '',- };-}--function pageSpec(navTargets = [{ targetKey: 'detail' }]) {- return {- entities: [{ schemaName: 'contoso_item', primaryAttribute: { schemaName: 'contoso_name' }, columns: [] }],- schemaVersion: 2,- pages: [- { key: 'overview', name: 'Overview', navigatesTo: navTargets, source: { kind: 'tsx', codeFile: 'overview.tsx' } },- { key: 'detail', name: 'Detail', source: { kind: 'tsx', codeFile: 'detail.tsx' } },- ],- appShell: { areas: [{ label: 'M', groups: [{ label: 'G', subAreas: [{ page: 'overview', title: 'Overview' }, { page: 'detail', title: 'Detail' }] }] }] },- };-}--// Sitemap XML binding both pages by real GUIDs in the GenPageId attribute.-const SITEMAP_OK = `<SiteMap><Area><Group><SubArea Id="s1" GenPageId="${GP_OVERVIEW}"/><SubArea Id="s2" GenPageId="${GP_DETAIL}"/></Group></Area></SiteMap>`;-const NAV_TO = (id) => `Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "${id}", data: {} });`;-// Standard manifest with both pages having real GUIDs.-const BOTH_MANIFEST = { schemaVersion: 1, pages: [{ key: 'overview', name: 'Overview', pageId: GP_OVERVIEW }, { key: 'detail', name: 'Detail', pageId: GP_DETAIL }] };--test('verifySpec pages: present + GenPageId-bound + nav edge resolves to the actual target id → ok', async () => {- const read = pageRead({- sitemapIds: [GP_OVERVIEW, GP_DETAIL],- existenceIds: [GP_OVERVIEW, GP_DETAIL],- manifest: BOTH_MANIFEST,- sitemap: SITEMAP_OK,- code: { [GP_OVERVIEW]: NAV_TO(GP_DETAIL) },- });- const r = await verifySpec(pageSpec(), read);- assert.ok(r.checks.some((c) => c.kind === 'page' && c.name === 'Overview' && c.present));- assert.ok(r.checks.some((c) => c.kind === 'page-subarea' && c.name === 'Overview' && c.present));- assert.ok(r.checks.some((c) => c.kind === 'page-nav' && c.name === 'Overview -> detail' && c.present));- assert.ok(r.checks.filter((c) => c.kind.startsWith('page')).every((c) => c.present), 'all page checks present');-});--test('verifySpec pages: a WRONG deployed GUID in the nav literal FAILS the nav check (C1 wrong-GUID)', async () => {- const read = pageRead({- sitemapIds: [GP_OVERVIEW, GP_DETAIL],- existenceIds: [GP_OVERVIEW, GP_DETAIL],- manifest: BOTH_MANIFEST,- sitemap: SITEMAP_OK,- code: { [GP_OVERVIEW]: NAV_TO('00000000-dead-beef-0000-000000000000') },- });- const r = await verifySpec(pageSpec(), read);- assert.ok(r.checks.some((c) => c.kind === 'page-nav' && c.name === 'Overview -> detail' && !c.present), 'nav edge must resolve to the ACTUAL target id');- assert.strictEqual(r.ok, false);-});--test('verifySpec pages: the correct target id only in a COMMENT (not a nav call site) FAILS the edge (C1 structural oracle)', async () => {- const read = pageRead({- sitemapIds: [GP_OVERVIEW, GP_DETAIL],- existenceIds: [GP_OVERVIEW, GP_DETAIL],- manifest: BOTH_MANIFEST,- sitemap: SITEMAP_OK,- // GP_DETAIL appears in a comment, the actual nav call has a wrong id → edge fails.- code: { [GP_OVERVIEW]: `// go to ${GP_DETAIL}\n${NAV_TO('00000000-0000-4000-8000-000000000000')}` },- });- const r = await verifySpec(pageSpec(), read);- assert.ok(r.checks.some((c) => c.kind === 'page-nav' && !c.present), 'a decoy id in a comment does not satisfy the edge');- assert.strictEqual(r.ok, false);-});--test('verifySpec pages: a residual PAGEREF_ in deployed nav code FAILS the no-pageref check', async () => {- const read = pageRead({- sitemapIds: [GP_OVERVIEW, GP_DETAIL],- existenceIds: [GP_OVERVIEW, GP_DETAIL],- manifest: BOTH_MANIFEST,- sitemap: SITEMAP_OK,- code: { [GP_OVERVIEW]: NAV_TO('PAGEREF_detail') },- });- const r = await verifySpec(pageSpec(), read);- assert.ok(r.checks.some((c) => c.kind === 'page-no-pageref' && !c.present));- assert.strictEqual(r.ok, false);-});--test('verifySpec pages: a page missing from existence FAILS the page check', async () => {- const read = pageRead({- sitemapIds: [GP_DETAIL], // GP_OVERVIEW not in sitemap- existenceIds: [GP_DETAIL], // GP_OVERVIEW not in existence- manifest: BOTH_MANIFEST,- sitemap: `<SiteMap><Area><Group><SubArea GenPageId="${GP_DETAIL}"/></Group></Area></SiteMap>`,- code: {},- });- const r = await verifySpec(pageSpec([]), read); // no nav to keep test focused- assert.ok(r.checks.some((c) => c.kind === 'page' && c.name === 'Overview' && !c.present));- assert.strictEqual(r.ok, false);-});--test('verifySpec pages: the sitemap subarea check matches the GenPageId attribute ONLY (a decoy attr does not satisfy it)', async () => {- // GP_OVERVIEW is in sitemapIds (membership says it is placed) but the raw XML has it only in a- // DECOY Url attribute, not a GenPageId attribute — subareaHasGenPage(xml, GP_OVERVIEW) fails.- const sitemap = `<SiteMap><Area><Group><SubArea Id="s1" Url="${GP_OVERVIEW}"/><SubArea Id="s2" GenPageId="${GP_DETAIL}"/></Group></Area></SiteMap>`;- const read = pageRead({- sitemapIds: [GP_OVERVIEW, GP_DETAIL],- existenceIds: [GP_OVERVIEW, GP_DETAIL],- manifest: BOTH_MANIFEST,- sitemap,- code: { [GP_OVERVIEW]: NAV_TO(GP_DETAIL) },- });- const r = await verifySpec(pageSpec(), read);- assert.ok(r.checks.some((c) => c.kind === 'page-subarea' && c.name === 'Overview' && !c.present), 'only a GenPageId="…" binding counts');-});--test('verifySpec pages: FAIL-CLOSED + unableToRun when the reader lacks page-authority methods (C6/Imp7)', async () => {- // A reader without sitemapPageIds/existenceIds/manifest means the verifier is unable to run — this- // must yield r.unableToRun===true (distinct from a reader that has authorities but finds a page missing).- const read = {- findTable: async () => ({ logicalName: 'contoso_item' }),- findColumns: async () => [],- queryRecords: async () => [],- sitemapXml: async () => '',- }; // NO sitemapPageIds, existenceIds, manifest- const r = await verifySpec(pageSpec(), read);- assert.ok(r.checks.some((c) => c.kind === 'page-verify' && !c.present), 'a page-bearing spec with no page reader must fail, not silently pass');- assert.strictEqual(r.ok, false);- assert.strictEqual(r.unableToRun, true, 'unableToRun must be true for reader-incapacity (distinct from ordinary miss)');-});--test('verifySpec pages: ordinary miss (reader has authorities but page absent from existence) has unableToRun falsy', async () => {- // Distinct from reader-incapacity: the reader CAN supply all three authorities but the pages are absent.- // ok:false but unableToRun is NOT set (it is an ordinary failed check, not a capacity gap).- const read = pageRead({- sitemapIds: [],- existenceIds: [], // pages not in existence- manifest: BOTH_MANIFEST,- sitemap: '',- code: {},- });- const r = await verifySpec(pageSpec([]), read);- assert.strictEqual(r.ok, false);- assert.ok(!r.unableToRun, 'ordinary miss (authorities available but pages absent) must NOT set unableToRun');-});--// ----------------------------------------------------------------------------// NEW Task 7 tests: name≠title match, page-not-in-existence, page-not-in-sitemap,-// empty manifest → unableToRun, page-extra set-equality, caching (Imp7).-// -----------------------------------------------------------------------------test('verifySpec pages: name≠title page matched by id (spec name does not need to match sitemap title)', async () => {- // The spec names the page "My Orders Overview" but the sitemap title is "Overview Title Differs".- // With three-authority id matching this is irrelevant — the manifest maps key→id and we match by id.- const spec = {- entities: [],- schemaVersion: 2,- pages: [{ key: 'overview', name: 'My Orders Overview', source: { kind: 'tsx', codeFile: 'o.tsx' } }],- appShell: { areas: [{ label: 'M', groups: [{ label: 'G', subAreas: [{ page: 'overview', title: 'Overview Title Differs' }] }] }] },- };- const xml = `<SiteMap><Area><Group><SubArea GenPageId="${GP_OVERVIEW}" Title="Overview Title Differs"/></Group></Area></SiteMap>`;- const read = pageRead({- sitemapIds: [GP_OVERVIEW],- existenceIds: [GP_OVERVIEW],- manifest: { schemaVersion: 1, pages: [{ key: 'overview', name: 'My Orders Overview', pageId: GP_OVERVIEW }] },- sitemap: xml,- code: { [GP_OVERVIEW]: 'export default 1;' },- });- const r = await verifySpec(spec, read);- assert.ok(r.checks.find((c) => c.kind === 'page' && c.name === 'My Orders Overview' && c.present), 'page present by id despite spec name != sitemap title');- assert.ok(r.checks.find((c) => c.kind === 'page-subarea' && c.name === 'My Orders Overview' && c.present), 'placement verified by id in GenPageId attr');- assert.strictEqual(r.ok, true);-});--test('verifySpec pages: a page whose manifest id is NOT in existence → missing', async () => {- // GP_OVERVIEW is in the manifest and sitemapIds but NOT in existenceIds (e.g. page was deleted env-wide).- const read = pageRead({- sitemapIds: [GP_OVERVIEW, GP_DETAIL],- existenceIds: [GP_DETAIL], // GP_OVERVIEW missing from env-wide existence- manifest: BOTH_MANIFEST,- sitemap: SITEMAP_OK,- code: {},- });- const r = await verifySpec(pageSpec([]), read);- assert.ok(r.checks.some((c) => c.kind === 'page' && c.name === 'Overview' && !c.present), 'page absent from existence → missing');- assert.strictEqual(r.ok, false);-});--test('verifySpec pages: a page not in the sitemap → missing (placement check, id-based)', async () => {- // GP_OVERVIEW exists env-wide (in existenceIds) but is NOT in sitemapIds (not placed in this app).- const read = pageRead({- sitemapIds: [GP_DETAIL], // GP_OVERVIEW not placed- existenceIds: [GP_OVERVIEW, GP_DETAIL],- manifest: BOTH_MANIFEST,- sitemap: `<SiteMap><Area><Group><SubArea GenPageId="${GP_DETAIL}"/></Group></Area></SiteMap>`,- code: {},- });- const r = await verifySpec(pageSpec([]), read);- assert.ok(r.checks.some((c) => c.kind === 'page' && c.name === 'Overview' && !c.present), 'page not in sitemap → page check fails (not placed)');- assert.strictEqual(r.ok, false);-});--test('verifySpec pages: empty/absent manifest on a page-bearing spec → unableToRun (Imp7, NOT all-missing)', async () => {- // Absent manifest (null) → cannot correlate any spec page to a deployed id → unableToRun.- const readNull = pageRead({- sitemapIds: [GP_OVERVIEW, GP_DETAIL],- existenceIds: [GP_OVERVIEW, GP_DETAIL],- manifest: null, // absent- sitemap: SITEMAP_OK,- code: {},- });- const r = await verifySpec(pageSpec([]), readNull);- assert.strictEqual(r.unableToRun, true, 'null manifest → unableToRun (page-identity)');- assert.ok(!r.checks.some((c) => c.kind === 'page' && c.present === false), 'no false "page missing" checks when manifest absent');-- // Empty manifest (pages:[]) → no key→id mappings → same result.- const readEmpty = pageRead({- sitemapIds: [GP_OVERVIEW, GP_DETAIL],- existenceIds: [GP_OVERVIEW, GP_DETAIL],- manifest: { schemaVersion: 1, pages: [] }, // present but no entries- sitemap: SITEMAP_OK,- code: {},- });- const r2 = await verifySpec(pageSpec([]), readEmpty);- assert.strictEqual(r2.unableToRun, true, 'empty manifest → unableToRun (page-identity)');-});--test('verifySpec pages: an extra live sitemap page not in the spec → page-extra (set-equality, Imp7)', async () => {- // sitemapIds includes GP_EXTRA which is not referenced by any spec page → page-extra.- const read = pageRead({- sitemapIds: [GP_OVERVIEW, GP_DETAIL, GP_EXTRA],- existenceIds: [GP_OVERVIEW, GP_DETAIL, GP_EXTRA],- manifest: BOTH_MANIFEST, // only overview and detail in spec/manifest- sitemap: `<SiteMap><Area><Group><SubArea GenPageId="${GP_OVERVIEW}"/><SubArea GenPageId="${GP_DETAIL}"/><SubArea GenPageId="${GP_EXTRA}"/></Group></Area></SiteMap>`,- code: {},- });- const r = await verifySpec(pageSpec([]), read); // no nav to focus on page-extra- assert.ok(r.checks.some((c) => c.kind === 'page-extra' && !c.present), 'the unmatched live page GP_EXTRA is reported');- assert.ok(r.checks.some((c) => c.kind === 'page-extra' && !c.present && c.name === GP_EXTRA), 'extra page reported by id');- assert.strictEqual(r.ok, false);-});--test('verifySpec pages: each reader method called exactly once (caching, Imp7)', async () => {- let sitemapCalls = 0;- let existenceCalls = 0;- let manifestCalls = 0;- const read = {- findTable: async () => ({ logicalName: 'contoso_item' }),- findColumns: async () => [],- queryRecords: async () => [],- sitemapXml: async () => SITEMAP_OK,- sitemapPageIds: async () => { sitemapCalls++; return [GP_OVERVIEW, GP_DETAIL]; },- existenceIds: async () => { existenceCalls++; return [GP_OVERVIEW, GP_DETAIL]; },- manifest: async () => { manifestCalls++; return BOTH_MANIFEST; },- pageCode: async () => '',- };- // Two pages, no nav — verifySpec should call each authority method exactly once.- await verifySpec(pageSpec([]), read);- assert.strictEqual(sitemapCalls, 1, 'sitemapPageIds called exactly once');- assert.strictEqual(existenceCalls, 1, 'existenceIds called exactly once');- assert.strictEqual(manifestCalls, 1, 'manifest called exactly once');-});--// ── Content-level verify (F5 scoped): catch a build that reports success while the deployed artifact-// DIFFERS from the spec (edits silently not applied). All best-effort + ADDITIVE — a check only fires-// when the reader supplies the data, so existing existence-only readers are unaffected. ────────────--test('verifySpec: view-columns — a spec view column missing from the deployed layoutxml FAILS (F5)', async () => {- const spec = { entities: [], charts: [], forms: [],- views: [{ entity: 'new_o', name: 'V', columns: ['new_name', 'new_status'] }], appShell: { areas: [] } };- const read = {- findTable: async () => null, findColumns: async () => [], sitemapXml: async () => '',- // Deployed view exists but its layoutxml is MISSING new_status (an unapplied column edit).- queryRecords: async (set) => (set === 'savedquery'- ? [{ savedqueryid: 'v1', layoutxml: '<grid><row><cell name="new_name"/></row></grid>' }]- : []),- };- const r = await verifySpec(spec, read);- assert.ok(r.checks.some((c) => c.kind === 'view' && c.present), 'the view exists (existence check still passes)');- const vc = r.checks.find((c) => c.kind === 'view-columns');- assert.ok(vc && !vc.present, 'view-columns FAILS because new_status is not in the deployed layoutxml');- assert.strictEqual(r.ok, false);-});--test('verifySpec: view-columns — passes when every spec column is in the layoutxml (extra deployed cols OK)', async () => {- const spec = { entities: [], charts: [], forms: [],- views: [{ entity: 'new_o', name: 'V', columns: ['new_name'] }], appShell: { areas: [] } };- const read = {- findTable: async () => null, findColumns: async () => [], sitemapXml: async () => '',- queryRecords: async (set) => (set === 'savedquery'- ? [{ savedqueryid: 'v1', layoutxml: '<grid><row><cell name="new_name"/><cell name="createdon"/></row></grid>' }]- : []),- };- const r = await verifySpec(spec, read);- const vc = r.checks.find((c) => c.kind === 'view-columns');- assert.ok(vc && vc.present, 'all spec columns present -> view-columns passes (a deployed extra column is fine — additive)');-});--test('verifySpec: view-columns check is SKIPPED when the reader gives no layoutxml (existence-only readers unaffected)', async () => {- const spec = { entities: [], charts: [], forms: [],- views: [{ entity: 'new_o', name: 'V', columns: ['new_name'] }], appShell: { areas: [] } };- const read = { findTable: async () => null, findColumns: async () => [], sitemapXml: async () => '',- queryRecords: async (set) => (set === 'savedquery' ? [{ savedqueryid: 'v1' }] : []) };- const r = await verifySpec(spec, read);- assert.ok(r.checks.some((c) => c.kind === 'view' && c.present));- assert.ok(!r.checks.some((c) => c.kind === 'view-columns'), 'no layoutxml -> no view-columns check (best-effort)');-});--test('verifySpec: relationship existence — a declared relationship absent from the child metadata FAILS (F5)', async () => {- const spec = { entities: [{ schemaName: 'new_o' }], views: [], charts: [], forms: [], appShell: { areas: [] },- relationships: [{ type: 'OneToMany', referenced: 'new_customer', referencing: 'new_o', lookup: { schemaName: 'new_CustomerId' } }] };- const read = {- findTable: async () => ({ logicalName: 'new_o' }), findColumns: async () => [], queryRecords: async () => [], sitemapXml: async () => '',- // Child entity metadata has NO relationships -> the declared relationship silently didn't build.- entityRelationships: async () => [],- };- const r = await verifySpec(spec, read);- const rc = r.checks.find((c) => c.kind === 'relationship');- assert.ok(rc && !rc.present, 'relationship existence FAILS when absent from child metadata');- assert.strictEqual(r.ok, false);-});--test('verifySpec: relationship check is SKIPPED when the reader cannot list relationships (best-effort)', async () => {- const spec = { entities: [], views: [], charts: [], forms: [], appShell: { areas: [] },- relationships: [{ type: 'OneToMany', referenced: 'new_customer', referencing: 'new_o', lookup: { schemaName: 'new_CustomerId' } }] };- const read = { findTable: async () => null, findColumns: async () => [], queryRecords: async () => [], sitemapXml: async () => '' };- const r = await verifySpec(spec, read);- assert.ok(!r.checks.some((c) => c.kind === 'relationship'), 'no entityRelationships reader -> no relationship check');-});--test('verifySpec: command existence — a declared command bar with no deployed appaction FAILS (F5)', async () => {- const spec = { entities: [{ schemaName: 'new_o' }], views: [], charts: [], forms: [], appShell: { areas: [] },- commands: [{ entity: 'new_o', label: 'Escalate', library: 'new_o.js', function: 'X.y' }] };- const read = {- findTable: async () => ({ logicalName: 'new_o' }), findColumns: async () => [], queryRecords: async () => [], sitemapXml: async () => '',- commandBar: async () => false, // no command bar deployed for the entity- };- const r = await verifySpec(spec, read);- const cc = r.checks.find((c) => c.kind === 'command');- assert.ok(cc && !cc.present, 'command existence FAILS when no appaction bar exists for the entity');- assert.strictEqual(r.ok, false);-});--test('verifySpec: command check is SKIPPED when the reader cannot resolve a command bar (best-effort)', async () => {- const spec = { entities: [], views: [], charts: [], forms: [], appShell: { areas: [] },- commands: [{ entity: 'new_o', label: 'Escalate', library: 'new_o.js', function: 'X.y' }] };- const read = { findTable: async () => null, findColumns: async () => [], queryRecords: async () => [], sitemapXml: async () => '' };- const r = await verifySpec(spec, read);- assert.ok(!r.checks.some((c) => c.kind === 'command'), 'no commandBar reader -> no command check');-});--// --- Security persona roles (Group N P1) -----------------------------------------------------test('verifySpec: an SDK-authored persona role present -> ok', async () => {- const spec = { entities: [{ schemaName: 'new_o', columns: [] }], personas: [{ persona: 'Agent', jobs: [{ name: 'w', privileges: [{ entity: 'new_o', access: ['read'] }] }] }] };- const read = {- findTable: async () => ({ logicalName: 'new_o' }),- findColumns: async () => [],- queryRecords: async (set) => (set === 'role' ? [{ roleid: 'r1', description: SDK_ROLE_MARKER, ismanaged: false }] : set === 'businessunit' ? [{ businessunitid: '00000000-0000-0000-0000-000000000001' }] : []),- sitemapXml: async () => '',- };- const r = await verifySpec(spec, read);- assert.strictEqual(r.ok, true, JSON.stringify(r.missing));- assert.ok(r.checks.some((c) => c.kind === 'role' && c.name === 'Agent' && c.present));-});--test('verifySpec: a missing persona role (or a foreign same-name role) is a loud fail', async () => {- const spec = { entities: [{ schemaName: 'new_o', columns: [] }], personas: [{ persona: 'Agent', jobs: [{ name: 'w', privileges: [{ entity: 'new_o', access: ['read'] }] }] }] };- const read = {- findTable: async () => ({ logicalName: 'new_o' }),- findColumns: async () => [],- // A same-name role NOT authored by the SDK must not satisfy the check (it is not the role we built).- queryRecords: async (set) => (set === 'businessunit' ? [{ businessunitid: '00000000-0000-0000-0000-000000000001' }] : [{ roleid: 'r2', description: 'hand-built by an admin', ismanaged: false }]),- sitemapXml: async () => '',- };- const r = await verifySpec(spec, read);- assert.strictEqual(r.ok, false);- assert.ok(r.missing.some((m) => m.kind === 'role' && m.name === 'Agent'));-});---// ── AI app features (ADO 6603383 / 6560699) ────────────────────────────────────────────────────-// verifySpec had NO awareness of spec.ai, so a build whose every requested AI feature was skipped-// (admin gate off) or silently not persisted still reported a clean PASS.-//-// The oracle is the APP-SCOPE OVERRIDE ROW in `appsettings`, NOT the effective value:-// `RetrieveSetting(name, { appUniqueName })` falls back to the ENVIRONMENT value when the app has no-// override, so an effective-value compare passes whenever the environment happens to already hold the-// requested value — a false PASS for an app that was never configured. This mirrors the oracle the-// SDK's own `setAppAiFeatures` uses to populate its `applied` bucket.--const AI_BASE = {- solution: { uniqueName: 'S', publisherPrefix: 'co' },- app: { name: 'A', uniqueName: 'co_a' },- entities: [], views: [], charts: [], forms: [], appShell: { areas: [] },-};-// `overrides` maps the PER-APP setting name -> the value held by its APP-SCOPE override row (present-// key == a row exists). `effective` maps setting name -> what RetrieveSetting reports for the app,-// which includes environment fallback; it defaults to `overrides` and is context only. Note these are-// the app settings, NOT the org readiness gates: nlSearch's gate is the boolean `EnableNLGridSearch`-// but its per-app setting is the numeric `NLGridSearchSetting` — conflating them is what made NL grid-// search silently no-op.-const aiRead = (overrides, effective, opts = {}) => {- const eff = effective || overrides;- return {- findTable: async () => null,- findColumns: async () => [],- sitemapXml: async () => '',- queryRecords: async (set, o) => {- const filter = (o && o.filter) || '';- if (set === 'appmodule') return opts.noApp ? [] : [{ appmoduleid: 'APPID' }];- if (set === 'settingdefinition') {- if (opts.noDef) return [];- const m = /uniquename eq '([^']+)'/.exec(filter);- return [{ settingdefinitionid: `DEF-${m && m[1]}` }];- }- if (set === 'appsetting') {- if (opts.proofThrows) throw new Error('403 forbidden');- const m = /_settingdefinitionid_value eq DEF-(.+)$/.exec(filter);- const name = m && m[1];- return Object.prototype.hasOwnProperty.call(overrides, name) ? [{ value: overrides[name] }] : [];- }- return [];- },- retrieveSetting: async (name) => ({ value: eff[name], dataType: opts.dataType }),- };-};-const ALL_ON = { formFill: true, nlSearch: true, nlChart: true, m365: true };-const ALL_SETTINGS_ON = {- FormFillBarUXEnabled: '1',- NLGridSearchSetting: '1',- NLChartDataVisualizationSetting: '1',- m365copilotmodelappenabled: '1',-};-// The overrides a DEFAULT build writes: `resolveAiFlags` seeds formFill/nlSearch/nlChart on and-// m365 off for any spec carrying `ai`, and verify reconciles that whole set — so a test focusing on-// ONE feature must still satisfy the other three or it is asserting on unrelated misses.-const DEFAULT_SETTINGS = {- FormFillBarUXEnabled: '1',- NLGridSearchSetting: '1',- NLChartDataVisualizationSetting: '1',- m365copilotmodelappenabled: '0',-};-const aiMissing = (r, feature) => r.missing.find((m) => m.kind === 'ai-feature' && m.name === feature);-// The override proof retries the ABSENT case with real backoff; these tests drive that path-// constantly, so they opt out of the delay. Retry BEHAVIOUR has its own dedicated test below.-const verifyAi = (spec, read) => verifySpec(spec, read, { proofDelayMs: 0 });--test('verifySpec: requested AI features that are NOT in effect fail verify (no more false PASS)', async () => {- const r = await verifyAi({ ...AI_BASE, ai: { appFeatures: ALL_ON } }, aiRead({}));- assert.strictEqual(r.ok, false);- assert.strictEqual(r.missing.filter((m) => m.kind === 'ai-feature').length, 4);-});--test('verifySpec: AI features in effect verify clean', async () => {- const r = await verifyAi({ ...AI_BASE, ai: { appFeatures: ALL_ON } }, aiRead(ALL_SETTINGS_ON));- assert.strictEqual(r.ok, true, JSON.stringify(r.missing));- assert.strictEqual(r.checks.filter((c) => c.kind === 'ai-feature' && c.present).length, 4);-});--test('verifySpec: an ENV-fallback value that matches the request is NOT a pass (no app override)', async () => {- // The regression this oracle exists for: RetrieveSetting at app scope returns the ENVIRONMENT value- // when the app has no override. Every requested feature reads back exactly as requested, yet the app- // itself was never configured — an effective-value compare reported PASS for a build the SDK itself- // classified as notPersisted/skipped.- const r = await verifyAi({ ...AI_BASE, ai: { appFeatures: ALL_ON } }, aiRead({}, ALL_SETTINGS_ON));- assert.strictEqual(r.ok, false, 'env fallback must not satisfy an app-scope request');- assert.strictEqual(r.missing.filter((m) => m.kind === 'ai-feature').length, 4);- assert.match(r.missing.find((m) => m.kind === 'ai-feature').detail, /NO app-scope override/);- // The effective value is still reported, as context for the maker.- assert.match(r.missing.find((m) => m.kind === 'ai-feature').detail, /environment fallback/);-});--test('verifySpec: reads the PER-APP setting, not the org readiness gate, for nlSearch', async () => {- // Only the ORG gate is on; the per-app setting has no override. Verify must NOT pass.- const r = await verifyAi({ ...AI_BASE, ai: { appFeatures: { nlSearch: true } } }, aiRead({ ...DEFAULT_SETTINGS, NLGridSearchSetting: undefined, EnableNLGridSearch: 'true' }));- assert.strictEqual(r.ok, false);- assert.match(aiMissing(r, 'nlSearch').detail, /NLGridSearchSetting/);-});--test('verifySpec: an explicit numeric AI value (2 = on for everyone) is compared verbatim', async () => {- const want2 = { ...AI_BASE, ai: { appFeatures: { formFill: 2 } } };- const mismatch = await verifyAi(want2, aiRead({ ...DEFAULT_SETTINGS, FormFillBarUXEnabled: '1' }));- assert.strictEqual(mismatch.ok, false, 'requested 2 but the override holds 1 must fail');- assert.match(aiMissing(mismatch, 'formFill').detail, /requested '2'/);- const match = await verifyAi(want2, aiRead({ ...DEFAULT_SETTINGS, FormFillBarUXEnabled: '2' }));- assert.strictEqual(match.ok, true, JSON.stringify(match.missing));-});--test('verifySpec: an explicit OFF request is verified against 0, not treated as dont-care', async () => {- const r = await verifyAi({ ...AI_BASE, ai: { appFeatures: { formFill: false } } }, aiRead({ ...DEFAULT_SETTINGS, FormFillBarUXEnabled: '1' }));- assert.strictEqual(r.ok, false);- // An explicit disable is still WRITTEN (disabling is never gated), so the override must hold '0'.- const ok = await verifyAi({ ...AI_BASE, ai: { appFeatures: { formFill: false } } }, aiRead({ ...DEFAULT_SETTINGS, FormFillBarUXEnabled: '0' }));- assert.strictEqual(ok.ok, true, JSON.stringify(ok.missing));-});--test('verifySpec: an unreadable override row fails CLOSED (cannot prove => not present)', async () => {- // We could look and looking failed, so we must not claim PASS on the strength of an effective value- // that may simply be the environment default — even though it matches the request here.- const read = aiRead({ FormFillBarUXEnabled: '1' }, { FormFillBarUXEnabled: '1' }, { proofThrows: true });- const r = await verifyAi({ ...AI_BASE, ai: { appFeatures: { formFill: true } } }, read);- assert.strictEqual(r.ok, false);- assert.match(r.missing.find((m) => m.kind === 'ai-feature').detail, /could not prove/);- assert.match(r.missing.find((m) => m.kind === 'ai-feature').detail, /403 forbidden/);-});--test('verifySpec: an unresolvable app module fails CLOSED rather than proving against the wrong app', async () => {- const read = aiRead(ALL_SETTINGS_ON, ALL_SETTINGS_ON, { noApp: true });- const r = await verifyAi({ ...AI_BASE, ai: { appFeatures: { formFill: true } } }, read);- assert.strictEqual(r.ok, false);- assert.match(r.missing.find((m) => m.kind === 'ai-feature').detail, /no app module with unique name 'co_a'/);-});--test('verifySpec: a spec with ai but NO appFeatures still verifies every feature the build writes', async () => {- // DR-P1-SK-001 / DR-P1-AR-001: the build seeds a default for EVERY feature whenever `spec.ai`- // exists, but verify used to iterate `spec.ai.appFeatures` — so `{ ai: { summaries: {...} } }`- // had three features written and ZERO verified, and `--verify` reported a clean PASS for features- // the platform may never have stored. That is ADO 6603383 surviving in the shipped artifact.- const spec = { ...AI_BASE, ai: { summaries: { default: 'auto' } } };- const none = await verifyAi(spec, aiRead({}));- assert.strictEqual(none.checks.filter((c) => c.kind === 'ai-feature').length, 4, 'all four defaults are reconciled');- assert.strictEqual(none.ok, false, 'unwritten defaults must fail verify');- // ...and the same spec passes once the defaults really are in place (m365 defaults OFF).- const ok = await verifyAi(spec, aiRead(DEFAULT_SETTINGS));- assert.strictEqual(ok.ok, true, JSON.stringify(ok.missing));-});--test('verifySpec: an undeclared feature is still checked when the spec declares only one', async () => {- // The partial-declaration half of the same hole: `{ appFeatures: { m365: true } }` still causes- // the build to write formFill/nlSearch/nlChart.- const spec = { ...AI_BASE, ai: { appFeatures: { m365: true } } };- const r = await verifyAi(spec, aiRead({ m365copilotmodelappenabled: '1' }));- assert.strictEqual(r.checks.filter((c) => c.kind === 'ai-feature').length, 4);- assert.ok(aiMissing(r, 'formFill'), 'the undeclared formFill default is reconciled');- assert.strictEqual(r.ok, false);-});--test('verifySpec: an override row that appears late is retried, not reported as a false FAIL', async () => {- // Observed live: an override row can lag briefly behind the write that created it (the SDK- // reported a feature not persisted on first apply and clean on a re-run, with the value correct- // all along). Verify gates the build's exit code, so a single read would turn that lag into a- // false FAIL. Only the ABSENT case is retried — a read ERROR is a different condition.- let attempts = 0;- const base = aiRead(DEFAULT_SETTINGS);- const read = {- ...base,- queryRecords: async (set, o) => {- if (set === 'appsetting') { attempts += 1; if (attempts < 2) return []; }- return base.queryRecords(set, o);- },- };- const r = await verifyAi({ ...AI_BASE, ai: { appFeatures: { formFill: true } } }, read);- assert.ok(attempts > 1, 'the absent read must be retried');- assert.strictEqual(r.ok, true, JSON.stringify(r.missing));-});--test('verifySpec: the AI check is reader-gated and absent-spec-safe (existing callers unaffected)', async () => {- // No ai block at all -> no ai checks.- const noAi = await verifyAi(AI_BASE, aiRead(ALL_SETTINGS_ON));- assert.strictEqual(noAi.checks.filter((c) => c.kind === 'ai-feature').length, 0);- // ai requested but the reader cannot read settings -> skipped, not a false failure.- const noSupport = { findTable: async () => null, findColumns: async () => [], queryRecords: async () => [], sitemapXml: async () => '' };- const r = await verifyAi({ ...AI_BASE, ai: { appFeatures: ALL_ON } }, noSupport);- assert.strictEqual(r.ok, true, JSON.stringify(r.missing));- assert.strictEqual(r.checks.filter((c) => c.kind === 'ai-feature').length, 0);- // ...and equally when it can read settings but cannot run the override PROOF: the check needs both- // capabilities, and degrading to the unsound effective-value compare is exactly the false PASS.- const noQuery = { findTable: async () => null, findColumns: async () => [], sitemapXml: async () => '', retrieveSetting: async () => ({ value: '1' }) };- const r2 = await verifyAi({ ...AI_BASE, ai: { appFeatures: ALL_ON } }, noQuery);- assert.strictEqual(r2.checks.filter((c) => c.kind === 'ai-feature').length, 0);-});--test('verifySpec: AI settings are read at the APP scope the BUILD wrote under, not the env scope', () => {- // Regression guard for a false PASS: when a spec carries no explicit app.uniqueName (neither shipped- // sample does), reading `spec.app.uniqueName` yields undefined, the SDK then omits the AppUniqueName- // path segment, and RetrieveSetting returns the ENVIRONMENT value. Comparing that against the request- // can pass while the app itself has the feature off. The identity must be `appUniqueName(spec)`.- const seen = [];- const appFilters = [];- const spec = {- solution: { uniqueName: 'S', publisherPrefix: 'new' },- app: { name: 'Project Tracker' }, // <- no uniqueName, like the real samples- entities: [], views: [], charts: [], forms: [], appShell: { areas: [] },- ai: { appFeatures: { formFill: true } },- };- const base = aiRead(DEFAULT_SETTINGS);- const read = {- ...base,- queryRecords: async (set, o) => {- if (set === 'appmodule') appFilters.push(o.filter);- return base.queryRecords(set, o);- },- retrieveSetting: async (name, opts) => { seen.push({ name, opts }); return { value: '1' }; },- };- return verifyAi(spec, read).then((r) => {- assert.strictEqual(r.ok, true, JSON.stringify(r.missing));- // Every feature the BUILD writes is reconciled, not only the one the spec named — the build- // seeds defaults for all four, so checking fewer would leave the rest silently unverified.- assert.strictEqual(seen.length, 4);- for (const s of seen) {- // Same derivation the build uses for setAppAiFeatures: `<publisherPrefix>_<app.name>` sanitized.- assert.strictEqual(s.opts.appUniqueName, 'new_projecttracker');- }- // ...and the override proof must resolve THE SAME app, or it would prove against another app.- assert.ok(appFilters.length >= 1);- for (const f of appFilters) assert.strictEqual(f, "uniquename eq 'new_projecttracker'");- });-});--test('verifySpec: a Boolean-spelled override value compares as on/off, independent of any dataType read', () => {- // Dataverse dataType 2 == Boolean, whose value is the string 'true'/'false'. An exact '1' compare- // would report a genuinely-enabled feature as not-in-effect (a false FAIL on a correct build).- // The normalization is deliberately UNCONDITIONAL: branching on a `dataType` read made the- // authoritative comparison depend on a second request that can fail independently, so a transport- // error on that read silently flipped a correctly-applied feature to FAIL.- const spec = { ...AI_BASE, ai: { appFeatures: { formFill: true } } };- return verifyAi(spec, aiRead({ ...DEFAULT_SETTINGS, FormFillBarUXEnabled: 'true' })).then(async (on) => {- assert.strictEqual(on.ok, true, JSON.stringify(on.missing));- const off = await verifyAi(spec, aiRead({ ...DEFAULT_SETTINGS, FormFillBarUXEnabled: 'false' }));- assert.strictEqual(off.ok, false, 'a Boolean-spelled setting reading false must still fail');- });-});--test('verifySpec: a failing context read cannot flip a proven feature to FAIL', () => {- // Regression guard: `retrieveSetting` is context only. When the override row proves the feature,- // a throwing context read must not change the verdict (it previously supplied `dataType`, which- // silently decided the comparison).- const spec = { ...AI_BASE, ai: { appFeatures: { formFill: true } } };- const read = { ...aiRead({ ...DEFAULT_SETTINGS, FormFillBarUXEnabled: 'true' }), retrieveSetting: async () => { throw new Error('429 too many requests'); } };- return verifyAi(spec, read).then((r) => {- assert.strictEqual(r.ok, true, JSON.stringify(r.missing));- });-});+'use strict';+const { test } = require('node:test');+const assert = require('node:assert');+const { verifySpec, hasElement } = require('../lib/verify-spec.js');+const { sitemapXmlFor } = require('../verify-model-app.js');+const { SDK_ROLE_MARKER } = require('../lib/app-spec.js');++const idFor = (set) => ({ savedquery: 'savedqueryid', savedqueryvisualization: 'savedqueryvisualizationid', systemform: 'formid' }[set] || 'id');++test('verifySpec: everything present -> ok', async () => {+ const spec = {+ entities: [{ schemaName: 'new_o', columns: [{ schemaName: 'new_s' }] }],+ views: [{ entity: 'new_o', name: 'V' }],+ charts: [{ entity: 'new_o', name: 'C' }],+ forms: [{ entity: 'new_o', name: 'F' }],+ appShell: { areas: [{ label: 'Main', icon: 'a.png', groups: [{ subAreas: [{ entity: 'new_o', title: 'O', icon: 'ic.png' }] }] }] },+ };+ const read = {+ findTable: async () => ({ logicalName: 'new_o' }),+ findColumns: async () => [{ logicalName: 'new_s' }],+ queryRecords: async (set) => [{ [idFor(set)]: 'id-1' }],+ sitemapXml: async () => '<SiteMap><Area Icon="a.png"><SubArea Entity="new_o" Icon="ic.png"/></Area></SiteMap>',+ };+ const r = await verifySpec(spec, read);+ assert.strictEqual(r.ok, true, JSON.stringify(r.missing));+ assert.ok(r.checks.some((c) => c.kind === 'subarea-icon' && c.present));+});++test('verifySpec: flags a missing column, view, and subarea icon', async () => {+ const spec = {+ entities: [{ schemaName: 'new_o', columns: [{ schemaName: 'new_s' }] }],+ views: [{ entity: 'new_o', name: 'V' }],+ forms: [],+ charts: [],+ appShell: { areas: [{ groups: [{ subAreas: [{ entity: 'new_o', title: 'O', icon: 'ic.png' }] }] }] },+ };+ const read = {+ findTable: async () => ({ logicalName: 'new_o' }),+ findColumns: async () => [], // column missing+ queryRecords: async () => [], // view missing+ sitemapXml: async () => '<SiteMap><SubArea Entity="new_o"/></SiteMap>', // icon missing (subarea present)+ };+ const r = await verifySpec(spec, read);+ assert.strictEqual(r.ok, false);+ assert.ok(r.missing.some((m) => m.kind === 'column'));+ assert.ok(r.missing.some((m) => m.kind === 'view'));+ assert.ok(r.missing.some((m) => m.kind === 'subarea-icon'));+ assert.ok(r.checks.some((c) => c.kind === 'subarea' && c.present), 'the subarea itself is present');+});++test('verifySpec: a missing entity skips its column checks', async () => {+ const spec = { entities: [{ schemaName: 'new_o', columns: [{ schemaName: 'new_s' }] }], appShell: { areas: [] } };+ const read = { findTable: async () => null, findColumns: async () => [], queryRecords: async () => [], sitemapXml: async () => '' };+ const r = await verifySpec(spec, read);+ assert.ok(r.missing.some((m) => m.kind === 'entity'));+ assert.ok(!r.checks.some((c) => c.kind === 'column'), 'no column checks when the entity is absent');+});++test('verifySpec reports missing entities without propagating dependent Dataverse read errors', async () => {+ const spec = {+ entities: [{ schemaName: 'new_missing', columns: [] }],+ views: [{ entity: 'new_missing', name: 'Missing View' }],+ appShell: { areas: [] },+ };+ const read = {+ findTable: async () => null,+ findColumns: async () => [],+ queryRecords: async () => {+ throw new Error('HTTP 400 metadata cache: entity was not found');+ },+ sitemapXml: async () => '',+ };++ const r = await verifySpec(spec, read);++ assert.equal(r.ok, false);+ assert.ok(r.missing.some((m) => m.kind === 'entity'));+ assert.ok(r.missing.some((m) => m.kind === 'view'));+});++test('verifySpec: a Main form check is type-scoped — a same-named Quick View sibling does NOT satisfy it', async () => {+ const spec = { entities: [], views: [], charts: [], forms: [{ entity: 'zava_javavendor', name: 'Information', formType: 'Main' }], appShell: { areas: [] } };+ let captured;+ const read = {+ findTable: async () => null, findColumns: async () => [],+ // Only a same-named Quick View exists; the type-scoped Main (type 2) query must find nothing.+ queryRecords: async (set, opts) => { if (set === 'systemform') { captured = opts.filter; return /type eq 2/.test(opts.filter) ? [] : [{ formid: 'qv-1' }]; } return []; },+ sitemapXml: async () => '',+ };+ const r = await verifySpec(spec, read);+ assert.match(captured, /objecttypecode eq 'zava_javavendor' and name eq 'Information' and type eq 2/, 'verify scopes the Main form query by type');+ assert.ok(r.missing.some((m) => m.kind === 'form'), 'the Main form is correctly reported MISSING — a same-named Quick View does not count (no false pass)');+});++test('verifySpec: an icon present only on a different element does not satisfy the check (scoped)', async () => {+ const spec = {+ entities: [], views: [], charts: [], forms: [],+ appShell: { areas: [{ label: 'Main', icon: 'shared.png', groups: [{ subAreas: [{ entity: 'new_o', title: 'O', icon: 'shared.png' }] }] }] },+ };+ const read = {+ findTable: async () => null,+ findColumns: async () => [],+ queryRecords: async () => [],+ // 'shared.png' appears ONLY on the SubArea, never on the Area.+ sitemapXml: async () => '<SiteMap><Area Icon="area-only.png"><SubArea Entity="new_o" Icon="shared.png"/></Area></SiteMap>',+ };+ const r = await verifySpec(spec, read);+ assert.ok(r.missing.some((m) => m.kind === 'area-icon'), 'area icon missing even though the same icon exists on a subarea');+ assert.ok(r.checks.some((c) => c.kind === 'subarea-icon' && c.present), 'subarea icon correctly matched on its own SubArea');+});++test('hasElement scopes attribute matching to the named element start-tag', () => {+ const xml = '<SiteMap><Area Icon="a.png"><SubArea Entity="new_o" Icon="ic.png"/></Area></SiteMap>';+ assert.strictEqual(hasElement(xml, 'Area', { Icon: 'a.png' }), true);+ assert.strictEqual(hasElement(xml, 'Area', { Icon: 'ic.png' }), false, 'a SubArea icon must not match an Area check');+ assert.strictEqual(hasElement(xml, 'SubArea', { Entity: 'new_o', Icon: 'ic.png' }), true, 'both attrs on the same SubArea');+ assert.strictEqual(hasElement(xml, 'SubArea', { Entity: 'new_o', Icon: 'a.png' }), false, 'icon lives on the Area, not this SubArea');+});++test('verifySpec: dashboard subarea resolves the dashboard id and matches the sitemap DefaultDashboard', async () => {+ const DASH = 'AAaa1111-2222-3333-4444-555566667777';+ const spec = {+ entities: [], views: [], charts: [], forms: [],+ appShell: { areas: [{ groups: [{ subAreas: [{ dashboard: 'Ops', title: 'Ops' }] }] }] },+ };+ const present = {+ findTable: async () => null, findColumns: async () => [],+ queryRecords: async (set, opts) => (set === 'systemform' && /name eq 'Ops'/.test(opts.filter) ? [{ formid: DASH }] : []),+ // Sitemap points a SubArea at the resolved dashboard id (Dataverse upper-cases + brace-wraps it).+ sitemapXml: async () => `<SiteMap><Area><SubArea Id="s" DefaultDashboard="{${DASH.toUpperCase()}}"/></Area></SiteMap>`,+ };+ const ok = await verifySpec(spec, present);+ assert.ok(ok.checks.some((c) => c.kind === 'subarea' && c.present), 'dashboard subarea matched by resolved id (brace/case-insensitive)');++ // A different dashboard id in the sitemap must NOT satisfy the check.+ const wrong = { ...present, sitemapXml: async () => '<SiteMap><Area><SubArea Id="s" DefaultDashboard="99999999-0000-0000-0000-000000000000"/></Area></SiteMap>' };+ const bad = await verifySpec(spec, wrong);+ assert.ok(bad.missing.some((m) => m.kind === 'subarea'), 'a different dashboard id does not satisfy the check');+});++test('sitemapXmlFor resolves appmodule -> component 62 -> sitemap', async () => {+ const sdk = {+ queryRecords: async (set) => {+ if (set === 'appmodule') return [{ appmoduleid: 'a', appmoduleidunique: 'u-1' }];+ if (set === 'appmodulecomponent') return [{ objectid: 'sm-1', componenttype: 62 }];+ if (set === 'sitemap') return [{ sitemapxml: '<SiteMap/>' }];+ return [];+ },+ };+ assert.strictEqual(await sitemapXmlFor(sdk, 'new_app'), '<SiteMap/>');+});++test('sitemapXmlFor returns empty when the app is not found', async () => {+ const sdk = { queryRecords: async () => [] };+ assert.strictEqual(await sitemapXmlFor(sdk, 'new_missing'), '');+});++// ---------------------------------------------------------------------------+// Page branch tests — Task 7: three-authority (IDENTITY+EXISTENCE+MEMBERSHIP)+// ---------------------------------------------------------------------------+// Plan 5 GUIDs (Imp9): real 36-char GUIDs in every mock.+const GP_OVERVIEW = '13ecbc57-a3a4-4132-b0a2-a6c6b12691e8';+const GP_DETAIL = '5c0a4889-45fd-46ea-91a8-ff876914d644';+const GP_EXTRA = '9f2b1a3c-77de-4a10-8b6e-2c4d5e6f7a8b';++// Reader mock: supplies all three authorities (sitemapPageIds/existenceIds/manifest) + pageCode.+// Tests set each authority independently to exercise specific check paths.+function pageRead({ sitemapIds, existenceIds, manifest, code, sitemap }) {+ return {+ findTable: async () => ({ logicalName: 'contoso_item' }),+ findColumns: async () => [],+ queryRecords: async () => [],+ sitemapXml: async () => sitemap || '',+ sitemapPageIds: async () => sitemapIds || [],+ existenceIds: async () => existenceIds || [],+ manifest: async () => manifest || null,+ pageCode: async (id) => (code && code[String(id).toLowerCase()]) || '',+ };+}++function pageSpec(navTargets = [{ targetKey: 'detail' }]) {+ return {+ entities: [{ schemaName: 'contoso_item', primaryAttribute: { schemaName: 'contoso_name' }, columns: [] }],+ schemaVersion: 2,+ pages: [+ { key: 'overview', name: 'Overview', navigatesTo: navTargets, source: { kind: 'tsx', codeFile: 'overview.tsx' } },+ { key: 'detail', name: 'Detail', source: { kind: 'tsx', codeFile: 'detail.tsx' } },+ ],+ appShell: { areas: [{ label: 'M', groups: [{ label: 'G', subAreas: [{ page: 'overview', title: 'Overview' }, { page: 'detail', title: 'Detail' }] }] }] },+ };+}++// Sitemap XML binding both pages by real GUIDs in the GenPageId attribute.+const SITEMAP_OK = `<SiteMap><Area><Group><SubArea Id="s1" GenPageId="${GP_OVERVIEW}"/><SubArea Id="s2" GenPageId="${GP_DETAIL}"/></Group></Area></SiteMap>`;+const NAV_TO = (id) => `Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "${id}", data: {} });`;+// Standard manifest with both pages having real GUIDs.+const BOTH_MANIFEST = { schemaVersion: 1, pages: [{ key: 'overview', name: 'Overview', pageId: GP_OVERVIEW }, { key: 'detail', name: 'Detail', pageId: GP_DETAIL }] };++test('verifySpec pages: present + GenPageId-bound + nav edge resolves to the actual target id → ok', async () => {+ const read = pageRead({+ sitemapIds: [GP_OVERVIEW, GP_DETAIL],+ existenceIds: [GP_OVERVIEW, GP_DETAIL],+ manifest: BOTH_MANIFEST,+ sitemap: SITEMAP_OK,+ code: { [GP_OVERVIEW]: NAV_TO(GP_DETAIL) },+ });+ const r = await verifySpec(pageSpec(), read);+ assert.ok(r.checks.some((c) => c.kind === 'page' && c.name === 'Overview' && c.present));+ assert.ok(r.checks.some((c) => c.kind === 'page-subarea' && c.name === 'Overview' && c.present));+ assert.ok(r.checks.some((c) => c.kind === 'page-nav' && c.name === 'Overview -> detail' && c.present));+ assert.ok(r.checks.filter((c) => c.kind.startsWith('page')).every((c) => c.present), 'all page checks present');+});++test('verifySpec pages: a WRONG deployed GUID in the nav literal FAILS the nav check (C1 wrong-GUID)', async () => {+ const read = pageRead({+ sitemapIds: [GP_OVERVIEW, GP_DETAIL],+ existenceIds: [GP_OVERVIEW, GP_DETAIL],+ manifest: BOTH_MANIFEST,+ sitemap: SITEMAP_OK,+ code: { [GP_OVERVIEW]: NAV_TO('00000000-dead-beef-0000-000000000000') },+ });+ const r = await verifySpec(pageSpec(), read);+ assert.ok(r.checks.some((c) => c.kind === 'page-nav' && c.name === 'Overview -> detail' && !c.present), 'nav edge must resolve to the ACTUAL target id');+ assert.strictEqual(r.ok, false);+});++test('verifySpec pages: the correct target id only in a COMMENT (not a nav call site) FAILS the edge (C1 structural oracle)', async () => {+ const read = pageRead({+ sitemapIds: [GP_OVERVIEW, GP_DETAIL],+ existenceIds: [GP_OVERVIEW, GP_DETAIL],+ manifest: BOTH_MANIFEST,+ sitemap: SITEMAP_OK,+ // GP_DETAIL appears in a comment, the actual nav call has a wrong id → edge fails.+ code: { [GP_OVERVIEW]: `// go to ${GP_DETAIL}\n${NAV_TO('00000000-0000-4000-8000-000000000000')}` },+ });+ const r = await verifySpec(pageSpec(), read);+ assert.ok(r.checks.some((c) => c.kind === 'page-nav' && !c.present), 'a decoy id in a comment does not satisfy the edge');+ assert.strictEqual(r.ok, false);+});++test('verifySpec pages: a residual PAGEREF_ in deployed nav code FAILS the no-pageref check', async () => {+ const read = pageRead({+ sitemapIds: [GP_OVERVIEW, GP_DETAIL],+ existenceIds: [GP_OVERVIEW, GP_DETAIL],+ manifest: BOTH_MANIFEST,+ sitemap: SITEMAP_OK,+ code: { [GP_OVERVIEW]: NAV_TO('PAGEREF_detail') },+ });+ const r = await verifySpec(pageSpec(), read);+ assert.ok(r.checks.some((c) => c.kind === 'page-no-pageref' && !c.present));+ assert.strictEqual(r.ok, false);+});++test('verifySpec pages: a page missing from existence FAILS the page check', async () => {+ const read = pageRead({+ sitemapIds: [GP_DETAIL], // GP_OVERVIEW not in sitemap+ existenceIds: [GP_DETAIL], // GP_OVERVIEW not in existence+ manifest: BOTH_MANIFEST,+ sitemap: `<SiteMap><Area><Group><SubArea GenPageId="${GP_DETAIL}"/></Group></Area></SiteMap>`,+ code: {},+ });+ const r = await verifySpec(pageSpec([]), read); // no nav to keep test focused+ assert.ok(r.checks.some((c) => c.kind === 'page' && c.name === 'Overview' && !c.present));+ assert.strictEqual(r.ok, false);+});++test('verifySpec pages: the sitemap subarea check matches the GenPageId attribute ONLY (a decoy attr does not satisfy it)', async () => {+ // GP_OVERVIEW is in sitemapIds (membership says it is placed) but the raw XML has it only in a+ // DECOY Url attribute, not a GenPageId attribute — subareaHasGenPage(xml, GP_OVERVIEW) fails.+ const sitemap = `<SiteMap><Area><Group><SubArea Id="s1" Url="${GP_OVERVIEW}"/><SubArea Id="s2" GenPageId="${GP_DETAIL}"/></Group></Area></SiteMap>`;+ const read = pageRead({+ sitemapIds: [GP_OVERVIEW, GP_DETAIL],+ existenceIds: [GP_OVERVIEW, GP_DETAIL],+ manifest: BOTH_MANIFEST,+ sitemap,+ code: { [GP_OVERVIEW]: NAV_TO(GP_DETAIL) },+ });+ const r = await verifySpec(pageSpec(), read);+ assert.ok(r.checks.some((c) => c.kind === 'page-subarea' && c.name === 'Overview' && !c.present), 'only a GenPageId="…" binding counts');+});++test('verifySpec pages: FAIL-CLOSED + unableToRun when the reader lacks page-authority methods (C6/Imp7)', async () => {+ // A reader without sitemapPageIds/existenceIds/manifest means the verifier is unable to run — this+ // must yield r.unableToRun===true (distinct from a reader that has authorities but finds a page missing).+ const read = {+ findTable: async () => ({ logicalName: 'contoso_item' }),+ findColumns: async () => [],+ queryRecords: async () => [],+ sitemapXml: async () => '',+ }; // NO sitemapPageIds, existenceIds, manifest+ const r = await verifySpec(pageSpec(), read);+ assert.ok(r.checks.some((c) => c.kind === 'page-verify' && !c.present), 'a page-bearing spec with no page reader must fail, not silently pass');+ assert.strictEqual(r.ok, false);+ assert.strictEqual(r.unableToRun, true, 'unableToRun must be true for reader-incapacity (distinct from ordinary miss)');+});++test('verifySpec pages: ordinary miss (reader has authorities but page absent from existence) has unableToRun falsy', async () => {+ // Distinct from reader-incapacity: the reader CAN supply all three authorities but the pages are absent.+ // ok:false but unableToRun is NOT set (it is an ordinary failed check, not a capacity gap).+ const read = pageRead({+ sitemapIds: [],+ existenceIds: [], // pages not in existence+ manifest: BOTH_MANIFEST,+ sitemap: '',+ code: {},+ });+ const r = await verifySpec(pageSpec([]), read);+ assert.strictEqual(r.ok, false);+ assert.ok(!r.unableToRun, 'ordinary miss (authorities available but pages absent) must NOT set unableToRun');+});++// ---------------------------------------------------------------------------+// NEW Task 7 tests: name≠title match, page-not-in-existence, page-not-in-sitemap,+// empty manifest → unableToRun, page-extra set-equality, caching (Imp7).+// ---------------------------------------------------------------------------++test('verifySpec pages: name≠title page matched by id (spec name does not need to match sitemap title)', async () => {+ // The spec names the page "My Orders Overview" but the sitemap title is "Overview Title Differs".+ // With three-authority id matching this is irrelevant — the manifest maps key→id and we match by id.+ const spec = {+ entities: [],+ schemaVersion: 2,+ pages: [{ key: 'overview', name: 'My Orders Overview', source: { kind: 'tsx', codeFile: 'o.tsx' } }],+ appShell: { areas: [{ label: 'M', groups: [{ label: 'G', subAreas: [{ page: 'overview', title: 'Overview Title Differs' }] }] }] },+ };+ const xml = `<SiteMap><Area><Group><SubArea GenPageId="${GP_OVERVIEW}" Title="Overview Title Differs"/></Group></Area></SiteMap>`;+ const read = pageRead({+ sitemapIds: [GP_OVERVIEW],+ existenceIds: [GP_OVERVIEW],+ manifest: { schemaVersion: 1, pages: [{ key: 'overview', name: 'My Orders Overview', pageId: GP_OVERVIEW }] },+ sitemap: xml,+ code: { [GP_OVERVIEW]: 'export default 1;' },+ });+ const r = await verifySpec(spec, read);+ assert.ok(r.checks.find((c) => c.kind === 'page' && c.name === 'My Orders Overview' && c.present), 'page present by id despite spec name != sitemap title');+ assert.ok(r.checks.find((c) => c.kind === 'page-subarea' && c.name === 'My Orders Overview' && c.present), 'placement verified by id in GenPageId attr');+ assert.strictEqual(r.ok, true);+});++test('verifySpec pages: a page whose manifest id is NOT in existence → missing', async () => {+ // GP_OVERVIEW is in the manifest and sitemapIds but NOT in existenceIds (e.g. page was deleted env-wide).+ const read = pageRead({+ sitemapIds: [GP_OVERVIEW, GP_DETAIL],+ existenceIds: [GP_DETAIL], // GP_OVERVIEW missing from env-wide existence+ manifest: BOTH_MANIFEST,+ sitemap: SITEMAP_OK,+ code: {},+ });+ const r = await verifySpec(pageSpec([]), read);+ assert.ok(r.checks.some((c) => c.kind === 'page' && c.name === 'Overview' && !c.present), 'page absent from existence → missing');+ assert.strictEqual(r.ok, false);+});++test('verifySpec pages: a page not in the sitemap → missing (placement check, id-based)', async () => {+ // GP_OVERVIEW exists env-wide (in existenceIds) but is NOT in sitemapIds (not placed in this app).+ const read = pageRead({+ sitemapIds: [GP_DETAIL], // GP_OVERVIEW not placed+ existenceIds: [GP_OVERVIEW, GP_DETAIL],+ manifest: BOTH_MANIFEST,+ sitemap: `<SiteMap><Area><Group><SubArea GenPageId="${GP_DETAIL}"/></Group></Area></SiteMap>`,+ code: {},+ });+ const r = await verifySpec(pageSpec([]), read);+ assert.ok(r.checks.some((c) => c.kind === 'page' && c.name === 'Overview' && !c.present), 'page not in sitemap → page check fails (not placed)');+ assert.strictEqual(r.ok, false);+});++test('verifySpec pages: empty/absent manifest on a page-bearing spec → unableToRun (Imp7, NOT all-missing)', async () => {+ // Absent manifest (null) → cannot correlate any spec page to a deployed id → unableToRun.+ const readNull = pageRead({+ sitemapIds: [GP_OVERVIEW, GP_DETAIL],+ existenceIds: [GP_OVERVIEW, GP_DETAIL],+ manifest: null, // absent+ sitemap: SITEMAP_OK,+ code: {},+ });+ const r = await verifySpec(pageSpec([]), readNull);+ assert.strictEqual(r.unableToRun, true, 'null manifest → unableToRun (page-identity)');+ assert.ok(!r.checks.some((c) => c.kind === 'page' && c.present === false), 'no false "page missing" checks when manifest absent');++ // Empty manifest (pages:[]) → no key→id mappings → same result.+ const readEmpty = pageRead({+ sitemapIds: [GP_OVERVIEW, GP_DETAIL],+ existenceIds: [GP_OVERVIEW, GP_DETAIL],+ manifest: { schemaVersion: 1, pages: [] }, // present but no entries+ sitemap: SITEMAP_OK,+ code: {},+ });+ const r2 = await verifySpec(pageSpec([]), readEmpty);+ assert.strictEqual(r2.unableToRun, true, 'empty manifest → unableToRun (page-identity)');+});++test('verifySpec pages: an extra live sitemap page not in the spec → page-extra (set-equality, Imp7)', async () => {+ // sitemapIds includes GP_EXTRA which is not referenced by any spec page → page-extra.+ const read = pageRead({+ sitemapIds: [GP_OVERVIEW, GP_DETAIL, GP_EXTRA],+ existenceIds: [GP_OVERVIEW, GP_DETAIL, GP_EXTRA],+ manifest: BOTH_MANIFEST, // only overview and detail in spec/manifest+ sitemap: `<SiteMap><Area><Group><SubArea GenPageId="${GP_OVERVIEW}"/><SubArea GenPageId="${GP_DETAIL}"/><SubArea GenPageId="${GP_EXTRA}"/></Group></Area></SiteMap>`,+ code: {},+ });+ const r = await verifySpec(pageSpec([]), read); // no nav to focus on page-extra+ assert.ok(r.checks.some((c) => c.kind === 'page-extra' && !c.present), 'the unmatched live page GP_EXTRA is reported');+ assert.ok(r.checks.some((c) => c.kind === 'page-extra' && !c.present && c.name === GP_EXTRA), 'extra page reported by id');+ assert.strictEqual(r.ok, false);+});++test('verifySpec pages: each reader method called exactly once (caching, Imp7)', async () => {+ let sitemapCalls = 0;+ let existenceCalls = 0;+ let manifestCalls = 0;+ const read = {+ findTable: async () => ({ logicalName: 'contoso_item' }),+ findColumns: async () => [],+ queryRecords: async () => [],+ sitemapXml: async () => SITEMAP_OK,+ sitemapPageIds: async () => { sitemapCalls++; return [GP_OVERVIEW, GP_DETAIL]; },+ existenceIds: async () => { existenceCalls++; return [GP_OVERVIEW, GP_DETAIL]; },+ manifest: async () => { manifestCalls++; return BOTH_MANIFEST; },+ pageCode: async () => '',+ };+ // Two pages, no nav — verifySpec should call each authority method exactly once.+ await verifySpec(pageSpec([]), read);+ assert.strictEqual(sitemapCalls, 1, 'sitemapPageIds called exactly once');+ assert.strictEqual(existenceCalls, 1, 'existenceIds called exactly once');+ assert.strictEqual(manifestCalls, 1, 'manifest called exactly once');+});++// ── Content-level verify (F5 scoped): catch a build that reports success while the deployed artifact+// DIFFERS from the spec (edits silently not applied). All best-effort + ADDITIVE — a check only fires+// when the reader supplies the data, so existing existence-only readers are unaffected. ────────────++test('verifySpec: view-columns — a spec view column missing from the deployed layoutxml FAILS (F5)', async () => {+ const spec = { entities: [], charts: [], forms: [],+ views: [{ entity: 'new_o', name: 'V', columns: ['new_name', 'new_status'] }], appShell: { areas: [] } };+ const read = {+ findTable: async () => null, findColumns: async () => [], sitemapXml: async () => '',+ // Deployed view exists but its layoutxml is MISSING new_status (an unapplied column edit).+ queryRecords: async (set) => (set === 'savedquery'+ ? [{ savedqueryid: 'v1', layoutxml: '<grid><row><cell name="new_name"/></row></grid>' }]+ : []),+ };+ const r = await verifySpec(spec, read);+ assert.ok(r.checks.some((c) => c.kind === 'view' && c.present), 'the view exists (existence check still passes)');+ const vc = r.checks.find((c) => c.kind === 'view-columns');+ assert.ok(vc && !vc.present, 'view-columns FAILS because new_status is not in the deployed layoutxml');+ assert.strictEqual(r.ok, false);+});++test('verifySpec: view-columns — passes when every spec column is in the layoutxml (extra deployed cols OK)', async () => {+ const spec = { entities: [], charts: [], forms: [],+ views: [{ entity: 'new_o', name: 'V', columns: ['new_name'] }], appShell: { areas: [] } };+ const read = {+ findTable: async () => null, findColumns: async () => [], sitemapXml: async () => '',+ queryRecords: async (set) => (set === 'savedquery'+ ? [{ savedqueryid: 'v1', layoutxml: '<grid><row><cell name="new_name"/><cell name="createdon"/></row></grid>' }]+ : []),+ };+ const r = await verifySpec(spec, read);+ const vc = r.checks.find((c) => c.kind === 'view-columns');+ assert.ok(vc && vc.present, 'all spec columns present -> view-columns passes (a deployed extra column is fine — additive)');+});++test('verifySpec: view-columns check is SKIPPED when the reader gives no layoutxml (existence-only readers unaffected)', async () => {+ const spec = { entities: [], charts: [], forms: [],+ views: [{ entity: 'new_o', name: 'V', columns: ['new_name'] }], appShell: { areas: [] } };+ const read = { findTable: async () => null, findColumns: async () => [], sitemapXml: async () => '',+ queryRecords: async (set) => (set === 'savedquery' ? [{ savedqueryid: 'v1' }] : []) };+ const r = await verifySpec(spec, read);+ assert.ok(r.checks.some((c) => c.kind === 'view' && c.present));+ assert.ok(!r.checks.some((c) => c.kind === 'view-columns'), 'no layoutxml -> no view-columns check (best-effort)');+});++test('verifySpec: relationship existence — a declared relationship absent from the child metadata FAILS (F5)', async () => {+ const spec = { entities: [{ schemaName: 'new_o' }], views: [], charts: [], forms: [], appShell: { areas: [] },+ relationships: [{ type: 'OneToMany', referenced: 'new_customer', referencing: 'new_o', lookup: { schemaName: 'new_CustomerId' } }] };+ const read = {+ findTable: async () => ({ logicalName: 'new_o' }), findColumns: async () => [], queryRecords: async () => [], sitemapXml: async () => '',+ // Child entity metadata has NO relationships -> the declared relationship silently didn't build.+ entityRelationships: async () => [],+ };+ const r = await verifySpec(spec, read);+ const rc = r.checks.find((c) => c.kind === 'relationship');+ assert.ok(rc && !rc.present, 'relationship existence FAILS when absent from child metadata');+ assert.strictEqual(r.ok, false);+});++test('verifySpec: relationship check is SKIPPED when the reader cannot list relationships (best-effort)', async () => {+ const spec = { entities: [], views: [], charts: [], forms: [], appShell: { areas: [] },+ relationships: [{ type: 'OneToMany', referenced: 'new_customer', referencing: 'new_o', lookup: { schemaName: 'new_CustomerId' } }] };+ const read = { findTable: async () => null, findColumns: async () => [], queryRecords: async () => [], sitemapXml: async () => '' };+ const r = await verifySpec(spec, read);+ assert.ok(!r.checks.some((c) => c.kind === 'relationship'), 'no entityRelationships reader -> no relationship check');+});++test('verifySpec: command existence — a declared command bar with no deployed appaction FAILS (F5)', async () => {+ const spec = { entities: [{ schemaName: 'new_o' }], views: [], charts: [], forms: [], appShell: { areas: [] },+ commands: [{ entity: 'new_o', label: 'Escalate', library: 'new_o.js', function: 'X.y' }] };+ const read = {+ findTable: async () => ({ logicalName: 'new_o' }), findColumns: async () => [], queryRecords: async () => [], sitemapXml: async () => '',+ commandBar: async () => false, // no command bar deployed for the entity+ };+ const r = await verifySpec(spec, read);+ const cc = r.checks.find((c) => c.kind === 'command');+ assert.ok(cc && !cc.present, 'command existence FAILS when no appaction bar exists for the entity');+ assert.strictEqual(r.ok, false);+});++test('verifySpec: command check is SKIPPED when the reader cannot resolve a command bar (best-effort)', async () => {+ const spec = { entities: [], views: [], charts: [], forms: [], appShell: { areas: [] },+ commands: [{ entity: 'new_o', label: 'Escalate', library: 'new_o.js', function: 'X.y' }] };+ const read = { findTable: async () => null, findColumns: async () => [], queryRecords: async () => [], sitemapXml: async () => '' };+ const r = await verifySpec(spec, read);+ assert.ok(!r.checks.some((c) => c.kind === 'command'), 'no commandBar reader -> no command check');+});++// --- Security persona roles (Group N P1) ---------------------------------------------------++test('verifySpec: an SDK-authored persona role present -> ok', async () => {+ const spec = { entities: [{ schemaName: 'new_o', columns: [] }], personas: [{ persona: 'Agent', jobs: [{ name: 'w', privileges: [{ entity: 'new_o', access: ['read'] }] }] }] };+ const read = {+ findTable: async () => ({ logicalName: 'new_o' }),+ findColumns: async () => [],+ queryRecords: async (set) => (set === 'role' ? [{ roleid: 'r1', description: SDK_ROLE_MARKER, ismanaged: false }] : set === 'businessunit' ? [{ businessunitid: '00000000-0000-0000-0000-000000000001' }] : []),+ sitemapXml: async () => '',+ };+ const r = await verifySpec(spec, read);+ assert.strictEqual(r.ok, true, JSON.stringify(r.missing));+ assert.ok(r.checks.some((c) => c.kind === 'role' && c.name === 'Agent' && c.present));+});++test('verifySpec: a missing persona role (or a foreign same-name role) is a loud fail', async () => {+ const spec = { entities: [{ schemaName: 'new_o', columns: [] }], personas: [{ persona: 'Agent', jobs: [{ name: 'w', privileges: [{ entity: 'new_o', access: ['read'] }] }] }] };+ const read = {+ findTable: async () => ({ logicalName: 'new_o' }),+ findColumns: async () => [],+ // A same-name role NOT authored by the SDK must not satisfy the check (it is not the role we built).+ queryRecords: async (set) => (set === 'businessunit' ? [{ businessunitid: '00000000-0000-0000-0000-000000000001' }] : [{ roleid: 'r2', description: 'hand-built by an admin', ismanaged: false }]),+ sitemapXml: async () => '',+ };+ const r = await verifySpec(spec, read);+ assert.strictEqual(r.ok, false);+ assert.ok(r.missing.some((m) => m.kind === 'role' && m.name === 'Agent'));+});+++// ── AI app features (ADO 6603383 / 6560699) ────────────────────────────────────────────────────+// verifySpec had NO awareness of spec.ai, so a build whose every requested AI feature was skipped+// (admin gate off) or silently not persisted still reported a clean PASS.+//+// The oracle is the APP-SCOPE OVERRIDE ROW in `appsettings`, NOT the effective value:+// `RetrieveSetting(name, { appUniqueName })` falls back to the ENVIRONMENT value when the app has no+// override, so an effective-value compare passes whenever the environment happens to already hold the+// requested value — a false PASS for an app that was never configured. This mirrors the oracle the+// SDK's own `setAppAiFeatures` uses to populate its `applied` bucket.++const AI_BASE = {+ solution: { uniqueName: 'S', publisherPrefix: 'co' },+ app: { name: 'A', uniqueName: 'co_a' },+ entities: [], views: [], charts: [], forms: [], appShell: { areas: [] },+};+// `overrides` maps the PER-APP setting name -> the value held by its APP-SCOPE override row (present+// key == a row exists). `effective` maps setting name -> what RetrieveSetting reports for the app,+// which includes environment fallback; it defaults to `overrides` and is context only. Note these are+// the app settings, NOT the org readiness gates: nlSearch's gate is the boolean `EnableNLGridSearch`+// but its per-app setting is the numeric `NLGridSearchSetting` — conflating them is what made NL grid+// search silently no-op.+const aiRead = (overrides, effective, opts = {}) => {+ const eff = effective || overrides;+ return {+ findTable: async () => null,+ findColumns: async () => [],+ sitemapXml: async () => '',+ queryRecords: async (set, o) => {+ const filter = (o && o.filter) || '';+ if (set === 'appmodule') return opts.noApp ? [] : [{ appmoduleid: 'APPID' }];+ if (set === 'settingdefinition') {+ if (opts.noDef) return [];+ const m = /uniquename eq '([^']+)'/.exec(filter);+ return [{ settingdefinitionid: `DEF-${m && m[1]}` }];+ }+ if (set === 'appsetting') {+ if (opts.proofThrows) throw new Error('403 forbidden');+ const m = /_settingdefinitionid_value eq DEF-(.+)$/.exec(filter);+ const name = m && m[1];+ return Object.prototype.hasOwnProperty.call(overrides, name) ? [{ value: overrides[name] }] : [];+ }+ return [];+ },+ retrieveSetting: async (name) => ({ value: eff[name], dataType: opts.dataType }),+ };+};+const ALL_ON = { formFill: true, nlSearch: true, nlChart: true, m365: true };+// The AI form-fill family does not use 1/0: 0 = platform default, 1 = DISABLED, 2 = ENABLED+// (SDK SETTING_CODEC, mirroring the admin UI). An ENABLED override therefore holds '2'.+const ALL_SETTINGS_ON = {+ FormFillBarUXEnabled: '2',+ NLGridSearchSetting: '1',+ NLChartDataVisualizationSetting: '1',+ m365copilotmodelappenabled: '1',+};+// The overrides a DEFAULT build writes: `resolveAiFlags` seeds formFill/nlSearch/nlChart on and+// m365 off for any spec carrying `ai`, and verify reconciles that whole set — so a test focusing on+// ONE feature must still satisfy the other three or it is asserting on unrelated misses.+const DEFAULT_SETTINGS = {+ FormFillBarUXEnabled: '2',+ NLGridSearchSetting: '1',+ NLChartDataVisualizationSetting: '1',+ m365copilotmodelappenabled: '0',+};+const aiMissing = (r, feature) => r.missing.find((m) => m.kind === 'ai-feature' && m.name === feature);+// The override proof retries the ABSENT case with real backoff; these tests drive that path+// constantly, so they opt out of the delay. Retry BEHAVIOUR has its own dedicated test below.+const verifyAi = (spec, read) => verifySpec(spec, read, { proofDelayMs: 0 });++test('verifySpec: requested AI features that are NOT in effect fail verify (no more false PASS)', async () => {+ const r = await verifyAi({ ...AI_BASE, ai: { appFeatures: ALL_ON } }, aiRead({}));+ assert.strictEqual(r.ok, false);+ assert.strictEqual(r.missing.filter((m) => m.kind === 'ai-feature').length, 4);+});++test('verifySpec: AI features in effect verify clean', async () => {+ const r = await verifyAi({ ...AI_BASE, ai: { appFeatures: ALL_ON } }, aiRead(ALL_SETTINGS_ON));+ assert.strictEqual(r.ok, true, JSON.stringify(r.missing));+ assert.strictEqual(r.checks.filter((c) => c.kind === 'ai-feature' && c.present).length, 4);+});++test('verifySpec: an ENV-fallback value that matches the request is NOT a pass (no app override)', async () => {+ // The regression this oracle exists for: RetrieveSetting at app scope returns the ENVIRONMENT value+ // when the app has no override. Every requested feature reads back exactly as requested, yet the app+ // itself was never configured — an effective-value compare reported PASS for a build the SDK itself+ // classified as notPersisted/skipped.+ const r = await verifyAi({ ...AI_BASE, ai: { appFeatures: ALL_ON } }, aiRead({}, ALL_SETTINGS_ON));+ assert.strictEqual(r.ok, false, 'env fallback must not satisfy an app-scope request');+ assert.strictEqual(r.missing.filter((m) => m.kind === 'ai-feature').length, 4);+ assert.match(r.missing.find((m) => m.kind === 'ai-feature').detail, /NO app-scope override/);+ // The effective value is still reported, as context for the maker.+ assert.match(r.missing.find((m) => m.kind === 'ai-feature').detail, /environment fallback/);+});++test('verifySpec: reads the PER-APP setting, not the org readiness gate, for nlSearch', async () => {+ // Only the ORG gate is on; the per-app setting has no override. Verify must NOT pass.+ const r = await verifyAi({ ...AI_BASE, ai: { appFeatures: { nlSearch: true } } }, aiRead({ ...DEFAULT_SETTINGS, NLGridSearchSetting: undefined, EnableNLGridSearch: 'true' }));+ assert.strictEqual(r.ok, false);+ assert.match(aiMissing(r, 'nlSearch').detail, /NLGridSearchSetting/);+});++test('verifySpec: an explicit numeric AI value (2 = on for everyone) is compared verbatim', async () => {+ const want2 = { ...AI_BASE, ai: { appFeatures: { formFill: 2 } } };+ const mismatch = await verifyAi(want2, aiRead({ ...DEFAULT_SETTINGS, FormFillBarUXEnabled: '1' }));+ assert.strictEqual(mismatch.ok, false, 'requested 2 but the override holds 1 must fail');+ assert.match(aiMissing(mismatch, 'formFill').detail, /requested '2'/);+ const match = await verifyAi(want2, aiRead({ ...DEFAULT_SETTINGS, FormFillBarUXEnabled: '2' }));+ assert.strictEqual(match.ok, true, JSON.stringify(match.missing));+});++test('verifySpec: an explicit OFF request is verified against 0, not treated as dont-care', async () => {+ const r = await verifyAi({ ...AI_BASE, ai: { appFeatures: { formFill: false } } }, aiRead({ ...DEFAULT_SETTINGS, FormFillBarUXEnabled: '2' }));+ assert.strictEqual(r.ok, false);+ // An explicit disable is still WRITTEN (disabling is never gated), so the override must hold '0'.+ // OFF for this family is '1' (DISABLED). '0' would be the platform default — deliberately NOT+ // accepted as off, because it defers to flighting rather than turning the feature off.+ const ok = await verifyAi({ ...AI_BASE, ai: { appFeatures: { formFill: false } } }, aiRead({ ...DEFAULT_SETTINGS, FormFillBarUXEnabled: '1' }));+ assert.strictEqual(ok.ok, true, JSON.stringify(ok.missing));+});++test('verifySpec: an unreadable override row fails CLOSED (cannot prove => not present)', async () => {+ // We could look and looking failed, so we must not claim PASS on the strength of an effective value+ // that may simply be the environment default — even though it matches the request here.+ const read = aiRead({ FormFillBarUXEnabled: '1' }, { FormFillBarUXEnabled: '1' }, { proofThrows: true });+ const r = await verifyAi({ ...AI_BASE, ai: { appFeatures: { formFill: true } } }, read);+ assert.strictEqual(r.ok, false);+ assert.match(r.missing.find((m) => m.kind === 'ai-feature').detail, /could not prove/);+ assert.match(r.missing.find((m) => m.kind === 'ai-feature').detail, /403 forbidden/);+});++test('verifySpec: an unresolvable app module fails CLOSED rather than proving against the wrong app', async () => {+ const read = aiRead(ALL_SETTINGS_ON, ALL_SETTINGS_ON, { noApp: true });+ const r = await verifyAi({ ...AI_BASE, ai: { appFeatures: { formFill: true } } }, read);+ assert.strictEqual(r.ok, false);+ assert.match(r.missing.find((m) => m.kind === 'ai-feature').detail, /no app module with unique name 'co_a'/);+});++test('verifySpec: a spec with ai but NO appFeatures still verifies every feature the build writes', async () => {+ // DR-P1-SK-001 / DR-P1-AR-001: the build seeds a default for EVERY feature whenever `spec.ai`+ // exists, but verify used to iterate `spec.ai.appFeatures` — so `{ ai: { summaries: {...} } }`+ // had three features written and ZERO verified, and `--verify` reported a clean PASS for features+ // the platform may never have stored. That is ADO 6603383 surviving in the shipped artifact.+ const spec = { ...AI_BASE, ai: { summaries: { default: 'auto' } } };+ const none = await verifyAi(spec, aiRead({}));+ assert.strictEqual(none.checks.filter((c) => c.kind === 'ai-feature').length, 4, 'all four defaults are reconciled');+ assert.strictEqual(none.ok, false, 'unwritten defaults must fail verify');+ // ...and the same spec passes once the defaults really are in place (m365 defaults OFF).+ const ok = await verifyAi(spec, aiRead(DEFAULT_SETTINGS));+ assert.strictEqual(ok.ok, true, JSON.stringify(ok.missing));+});++test('verifySpec: an undeclared feature is still checked when the spec declares only one', async () => {+ // The partial-declaration half of the same hole: `{ appFeatures: { m365: true } }` still causes+ // the build to write formFill/nlSearch/nlChart.+ const spec = { ...AI_BASE, ai: { appFeatures: { m365: true } } };+ const r = await verifyAi(spec, aiRead({ m365copilotmodelappenabled: '1' }));+ assert.strictEqual(r.checks.filter((c) => c.kind === 'ai-feature').length, 4);+ assert.ok(aiMissing(r, 'formFill'), 'the undeclared formFill default is reconciled');+ assert.strictEqual(r.ok, false);+});++test('verifySpec: an override row that appears late is retried, not reported as a false FAIL', async () => {+ // Observed live: an override row can lag briefly behind the write that created it (the SDK+ // reported a feature not persisted on first apply and clean on a re-run, with the value correct+ // all along). Verify gates the build's exit code, so a single read would turn that lag into a+ // false FAIL. Only the ABSENT case is retried — a read ERROR is a different condition.+ let attempts = 0;+ const base = aiRead(DEFAULT_SETTINGS);+ const read = {+ ...base,+ queryRecords: async (set, o) => {+ if (set === 'appsetting') { attempts += 1; if (attempts < 2) return []; }+ return base.queryRecords(set, o);+ },+ };+ const r = await verifyAi({ ...AI_BASE, ai: { appFeatures: { formFill: true } } }, read);+ assert.ok(attempts > 1, 'the absent read must be retried');+ assert.strictEqual(r.ok, true, JSON.stringify(r.missing));+});++test('verifySpec: the AI check is reader-gated and absent-spec-safe (existing callers unaffected)', async () => {+ // No ai block at all -> no ai checks.+ const noAi = await verifyAi(AI_BASE, aiRead(ALL_SETTINGS_ON));+ assert.strictEqual(noAi.checks.filter((c) => c.kind === 'ai-feature').length, 0);+ // ai requested but the reader cannot read settings -> skipped, not a false failure.+ const noSupport = { findTable: async () => null, findColumns: async () => [], queryRecords: async () => [], sitemapXml: async () => '' };+ const r = await verifyAi({ ...AI_BASE, ai: { appFeatures: ALL_ON } }, noSupport);+ assert.strictEqual(r.ok, true, JSON.stringify(r.missing));+ assert.strictEqual(r.checks.filter((c) => c.kind === 'ai-feature').length, 0);+ // ...and equally when it can read settings but cannot run the override PROOF: the check needs both+ // capabilities, and degrading to the unsound effective-value compare is exactly the false PASS.+ const noQuery = { findTable: async () => null, findColumns: async () => [], sitemapXml: async () => '', retrieveSetting: async () => ({ value: '1' }) };+ const r2 = await verifyAi({ ...AI_BASE, ai: { appFeatures: ALL_ON } }, noQuery);+ assert.strictEqual(r2.checks.filter((c) => c.kind === 'ai-feature').length, 0);+});++test('verifySpec: AI settings are read at the APP scope the BUILD wrote under, not the env scope', () => {+ // Regression guard for a false PASS: when a spec carries no explicit app.uniqueName (neither shipped+ // sample does), reading `spec.app.uniqueName` yields undefined, the SDK then omits the AppUniqueName+ // path segment, and RetrieveSetting returns the ENVIRONMENT value. Comparing that against the request+ // can pass while the app itself has the feature off. The identity must be `appUniqueName(spec)`.+ const seen = [];+ const appFilters = [];+ const spec = {+ solution: { uniqueName: 'S', publisherPrefix: 'new' },+ app: { name: 'Project Tracker' }, // <- no uniqueName, like the real samples+ entities: [], views: [], charts: [], forms: [], appShell: { areas: [] },+ ai: { appFeatures: { formFill: true } },+ };+ const base = aiRead(DEFAULT_SETTINGS);+ const read = {+ ...base,+ queryRecords: async (set, o) => {+ if (set === 'appmodule') appFilters.push(o.filter);+ return base.queryRecords(set, o);+ },+ retrieveSetting: async (name, opts) => { seen.push({ name, opts }); return { value: '1' }; },+ };+ return verifyAi(spec, read).then((r) => {+ assert.strictEqual(r.ok, true, JSON.stringify(r.missing));+ // Every feature the BUILD writes is reconciled, not only the one the spec named — the build+ // seeds defaults for all four, so checking fewer would leave the rest silently unverified.+ assert.strictEqual(seen.length, 4);+ for (const s of seen) {+ // Same derivation the build uses for setAppAiFeatures: `<publisherPrefix>_<app.name>` sanitized.+ assert.strictEqual(s.opts.appUniqueName, 'new_projecttracker');+ }+ // ...and the override proof must resolve THE SAME app, or it would prove against another app.+ assert.ok(appFilters.length >= 1);+ for (const f of appFilters) assert.strictEqual(f, "uniquename eq 'new_projecttracker'");+ });+});++test('verifySpec: a Boolean-spelled override value compares as on/off, independent of any dataType read', () => {+ // Dataverse dataType 2 == Boolean, whose value is the string 'true'/'false'. An exact '1' compare+ // would report a genuinely-enabled feature as not-in-effect (a false FAIL on a correct build).+ // The normalization is deliberately UNCONDITIONAL: branching on a `dataType` read made the+ // authoritative comparison depend on a second request that can fail independently, so a transport+ // error on that read silently flipped a correctly-applied feature to FAIL.+ // Requested on nlSearch, not formFill: this asserts that a Boolean SPELLING of the stored value is+ // reconciled with the requested one, and that only makes sense for a setting whose on/off really+ // is 1/0. The form-fill family is a 0/1/2 enum (0 = platform default, 1 = disabled, 2 = enabled)+ // and never stores 'true'/'false', so pointing this at formFill would assert a shape the platform+ // cannot produce — and, with the request and the stub naming different settings, it could pass or+ // fail for reasons unrelated to the normalisation under test.+ const spec = { ...AI_BASE, ai: { appFeatures: { nlSearch: true } } };+ return verifyAi(spec, aiRead({ ...DEFAULT_SETTINGS, NLGridSearchSetting: 'true' })).then(async (on) => {+ assert.strictEqual(on.ok, true, JSON.stringify(on.missing));+ const off = await verifyAi(spec, aiRead({ ...DEFAULT_SETTINGS, NLGridSearchSetting: 'false' }));+ assert.strictEqual(off.ok, false, 'a Boolean-spelled setting reading false must still fail');+ });+});++test('verifySpec: a failing context read cannot flip a proven feature to FAIL', () => {+ // Regression guard: `retrieveSetting` is context only. When the override row proves the feature,+ // a throwing context read must not change the verdict (it previously supplied `dataType`, which+ // silently decided the comparison).+ const spec = { ...AI_BASE, ai: { appFeatures: { formFill: true } } };+ const read = { ...aiRead({ ...DEFAULT_SETTINGS }), retrieveSetting: async () => { throw new Error('429 too many requests'); } };+ return verifyAi(spec, read).then((r) => {+ assert.strictEqual(r.ok, true, JSON.stringify(r.missing));+ });+});diff --git a/plugins/model-apps/scripts/vendor/PROVENANCE.json b/plugins/model-apps/scripts/vendor/PROVENANCE.jsonindex f6fe8a5f5..2533bb9dc 100644--- a/plugins/model-apps/scripts/vendor/PROVENANCE.json+++ b/plugins/model-apps/scripts/vendor/PROVENANCE.json@@ -1,14 +1,14 @@{- "commit": "b17bd3da66121a620c8cb1b198a7aaab6b6a0eed",- "subject": "feat(cds-maker-sdk): Business Process Flow (BPF) authoring - all phases (create/activate/edit/structure/flow/security)",+ "commit": "5dcb83986fb7b396b2c033089ab89a199665a830",+ "subject": "loc(copilot-studio): add catalogues for 12 new locales (additions-only)","dirtySdkPackage": 0,- "libBuiltAt": "2026-08-28T16:33:04.842Z",- "newestSrcAt": "2026-08-28T16:28:40.376Z",+ "libBuiltAt": "2026-08-31T21:41:17.872Z",+ "newestSrcAt": "2026-08-31T21:40:14.316Z","libIsStale": false,"nostub": false,"esbuildVersion": "0.28.1","nodeVersion": "v22.13.1",- "builtAt": "2026-08-28T16:34:11.012Z",- "bundleSha256": "0168206487969d69f01f843c1cfa3b751c018271b320d64017f880a17c466b86",- "bundleBytes": 687133+ "builtAt": "2026-08-31T21:41:40.924Z",+ "bundleSha256": "2d459dec4bad316c468a05ce9d21f13eef48984a483b0aaa29d3f627213db0f5",+ "bundleBytes": 682531}diff --git a/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs b/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjsindex d7a94e799..11210ca9d 100644--- a/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs+++ b/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs@@ -25,37 +25,37 @@}globalThis.document=globalThis.document||globalThis.window.document;})();-"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}:+"use strict";var T1=Object.create;var ns=Object.defineProperty;var O1=Object.getOwnPropertyDescriptor;var R1=Object.getOwnPropertyNames;var x1=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}},ar=(e,t)=>{for(var r in t)ns(e,r,{get:t[r],enumerable:!0})},Um=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of R1(t))!F1.call(e,i)&&i!==r&&ns(e,i,{get:()=>t[i],enumerable:!(n=O1(t,i))||n.enumerable});return e};var le=(e,t,r)=>(r=e!=null?T1(x1(e)):{},Um(t||!e||!e.__esModule?ns(r,"default",{value:e,enumerable:!0}):r,e)),or=e=>Um(ns({},"__esModule",{value:!0}),e);var ne=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 Xe=class extends Error{constructor(t,r){super(r),this.code=t,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}};K.SdkError=Xe;var Bm=Symbol.for("cds-maker-sdk.partialWriteTokens");function L1(e,t){return typeof e=="object"&&e!==null&&(e[Bm]=t),e}K.withPartialTokens=L1;function k1(e){let t=e;for(let r=0;t&&typeof t=="object"&&r<8;r++){let n=t[Bm];if(n&&typeof n=="object")return n;t=t.cause}}K.readPartialTokens=k1;var Ju=class extends Xe{constructor(t,r){super("ARTIFACT_NOT_FOUND",`Artifact ${t}/${r} not found in workspace`),this.type=t,this.id=r}};K.ArtifactNotFoundError=Ju;var Xu=class extends Xe{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=Xu;var Ku=class extends Xe{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"}};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+`)),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=Ku;var Yu=class extends Xe{constructor(t){super("INVALID_ARGUMENT",t)}};K.InvalidArgumentError=Yu;var Zu=class extends Xe{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=Zu;var ec=class extends Xe{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=ec;var tc=class extends Xe{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=tc;var rc=class extends Xe{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=rc;var nc=class extends Xe{constructor(t){super("WORKSPACE_NOT_INITIALIZED",`Workspace not initialized at ${t}. Call initWorkspace() first.`),this.workspacePath=t}};K.WorkspaceNotInitializedError=nc;var ic=class extends Xe{constructor(t,r){super("NOT_IMPLEMENTED",`Operation '${t}' is not implemented yet${r?`: ${r}`:""}.`),this.operation=t}};K.NotImplementedError=ic;var ac=class extends Xe{constructor(t,r){super("INVALID_JSON_POINTER",`Invalid JSON Pointer '${t}': ${r}`),this.pointer=t}};K.JsonPointerError=ac;var oc=class extends Xe{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=oc;var sc=class extends Xe{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=sc;var lc=class extends Xe{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=lc});var os=g(as=>{"use strict";Object.defineProperty(as,"__esModule",{value:!0});as.JsonPointer=void 0;var _t=ne(),is=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)}};as.JsonPointer=is;is.RESERVED_TOKENS=new Set(["__proto__","prototype","constructor"])});var qm=g(ss=>{"use strict";Object.defineProperty(ss,"__esModule",{value:!0});ss.findElements=void 0;var $m=os();function M1(e,t){let r=[];return uc(e,"",t,r),r}ss.findElements=M1;function uc(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)=>{uc(i,$m.JsonPointer.append(t,a),r,n)});else for(let i of Object.keys(e))uc(e[i],$m.JsonPointer.append(t,i),r,n)}});var zm=g(Ke=>{"use strict";var U1=Ke&&Ke.__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]})),B1=Ke&&Ke.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Gm=Ke&&Ke.__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)&&U1(t,e,r);return B1(t,e),t};Object.defineProperty(Ke,"__esModule",{value:!0});Ke.canonicalArtifactId=Ke.WorkspaceManager=Ke.WORKSPACE_SCHEMA_VERSION=void 0;var De=Gm(require("fs")),Pe=Gm(require("path")),li=ne();Ke.WORKSPACE_SCHEMA_VERSION=1;var ls={form:"forms",view:"views",businessRule:"business-rules",app:"apps",command:"commands",chart:"charts",dashboard:"dashboards",genPage:"gen-pages",bpf:"business-process-flows"},$1="manifest.json",us=".metadata",Vm="entities",cc=class{constructor(t,r){this.workspacePath=t,this.instanceUrl=r}getRoot(){return this.workspacePath}getArtifactDir(t){return Pe.join(this.workspacePath,ls[t])}getArtifactFilePath(t,r){return this.assertSafeId(r),this.assertWithinRoot(Pe.join(this.getArtifactDir(t),`${Ia(r)}.json`))}getMetaFilePath(t,r){return this.assertSafeId(r),this.assertWithinRoot(Pe.join(this.workspacePath,us,ls[t],`${Ia(r)}.meta.json`))}getEntityMetaFilePath(t){return this.assertSafeId(t),this.assertWithinRoot(Pe.join(this.workspacePath,us,Vm,`${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("..")||Pe.basename(t)!==t)throw new li.PathTraversalError(String(t),this.workspacePath)}assertWithinRoot(t){let r=Pe.resolve(this.workspacePath),n=Pe.resolve(t);if(n!==r&&!n.startsWith(r+Pe.sep))throw new li.PathTraversalError(t,this.workspacePath);let i=De.existsSync(r)?De.realpathSync(r):r,a=n,o=[];for(;!De.existsSync(a);){o.unshift(Pe.basename(a));let l=Pe.dirname(a);if(l===a)break;a=l}let s=Pe.resolve(De.realpathSync(a),...o);if(s!==i&&!s.startsWith(i+Pe.sep))throw new li.PathTraversalError(t,this.workspacePath);return n}get manifestPath(){return Pe.join(this.workspacePath,$1)}init(){for(let t of Object.keys(ls))De.mkdirSync(this.getArtifactDir(t),{recursive:!0}),De.mkdirSync(Pe.dirname(this.getMetaFilePath(t,"x")),{recursive:!0});if(De.mkdirSync(Pe.join(this.workspacePath,us,Vm),{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 li.WorkspaceNotInitializedError(this.workspacePath)}clean(){for(let r of Object.keys(ls))dc(this.getArtifactDir(r));dc(Pe.join(this.workspacePath,us));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=Ia(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 li.WorkspaceNotInitializedError(this.workspacePath);if(t.schemaVersion!==void 0&&t.schemaVersion>Ke.WORKSPACE_SCHEMA_VERSION)throw new li.IncompatibleWorkspaceError(t.schemaVersion,Ke.WORKSPACE_SCHEMA_VERSION);return t}writeManifest(t){this.writeJson(this.manifestPath,{...t,schemaVersion:Ke.WORKSPACE_SCHEMA_VERSION})}updateManifest(t){let r=this.getManifest();this.writeManifest({...r,...t})}upsertManifestEntry(t,r,n){let i=this.getManifest(),a=Ia(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(De.readFileSync(t,"utf8")):null}writeJson(t,r){let n=Pe.dirname(t);De.mkdirSync(n,{recursive:!0});let i=Pe.join(n,`.${Pe.basename(t)}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);try{De.writeFileSync(i,`${JSON.stringify(r,null,2)}+`,"utf8"),De.renameSync(i,t)}catch(a){try{De.existsSync(i)&&De.unlinkSync(i)}catch{}throw a}}removeFile(t){this.exists(t)&&De.unlinkSync(t)}exists(t){return De.existsSync(t)}};Ke.WorkspaceManager=cc;function Ia(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()}Ke.canonicalArtifactId=Ia;function dc(e){let t;try{t=De.lstatSync(e)}catch{return}if(t.isSymbolicLink()){try{De.unlinkSync(e)}catch{De.rmdirSync(e)}return}if(!t.isDirectory()){De.unlinkSync(e);return}for(let r of De.readdirSync(e))dc(Pe.join(e,r));De.rmdirSync(e)}});var pc=g(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});ui.deepEqual=ui.deepDiff=void 0;var q1=os();function V1(e,t){let r=[];return jm(e,t,"",r,0),r}ui.deepDiff=V1;var cs=Symbol("missing"),ds=512;function jm(e,t,r,n,i){if(e===t)return;if(i>ds)throw new RangeError(`deepDiff exceeded the maximum supported depth of ${ds}`);let a=ps(e),o=ps(t);if(a&&o&&Array.isArray(e)===Array.isArray(t)){let s=G1(e,t);for(let l of s){let u=Wm(e,l),c=Wm(t,l),d=q1.JsonPointer.append(r,l);u===cs?n.push({pointer:d,type:"added",newValue:c}):c===cs?n.push({pointer:d,type:"removed",oldValue:u}):jm(u,c,d,n,i+1)}return}Hm(e,t)||n.push({pointer:r,type:"modified",oldValue:e,newValue:t})}function ps(e){return e!==null&&typeof e=="object"}function G1(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 Wm(e,t){if(Array.isArray(e)){let r=Number(t);return r<e.length?e[r]:cs}return t in e?e[t]:cs}function Hm(e,t){return Qm(e,t,0)}ui.deepEqual=Hm;function Qm(e,t,r){if(e===t)return!0;if(r>ds)throw new RangeError(`deepEqual exceeded the maximum supported depth of ${ds}`);if(!ps(e)||!ps(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&&Qm(e[a],t[a],r+1))}});var Xm=g(fs=>{"use strict";Object.defineProperty(fs,"__esModule",{value:!0});fs.VersionManager=void 0;var Jm=pc(),fc=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,Jm.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,Jm.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}};fs.VersionManager=fc});var Ym=g((mc,Km)=>{(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof mc=="object"?Km.exports=t():e.compareVersions=t()})(mc,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 m=l[l.length-1],h=u[u.length-1];if(m&&h){var w=m.split(".").map(n),y=h.split(".").map(n);for(c=0;c<Math.max(w.length,y.length);c++){if(w[c]===void 0||typeof y[c]=="string"&&typeof w[c]=="number")return-1;if(y[c]===void 0||typeof w[c]=="string"&&typeof y[c]=="number"||w[c]>y[c])return 1;if(y[c]>w[c])return-1}}else if(m||h)return m?-1:1;return 0}})});var nh=g(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.EnvironmentFlowHostingType=Ce.EnvironmentDisableReasonCode=Ce.EnvironmentMigrationConstants=Ce.EnvironmentProvisioningStates=Ce.EnvironmentLocations=Ce.EnvironmentCreationTypeConstants=Ce.EnvironmentType=Ce.EnvironmentSkuConstants=Ce.environmentPermissions=Ce.DatabaseType=void 0;var Zm;(function(e){e.CommonDataService="CommonDataService",e.None="None"})(Zm||(Ce.DatabaseType=Zm={}));Ce.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"};Ce.EnvironmentSkuConstants={NotSpecified:"NotSpecified",Standard:"Standard",Premium:"Premium",Developer:"Developer",Basic:"Basic",Production:"Production",Sandbox:"Sandbox",Trial:"Trial",Default:"Default",Teams:"Teams",Platform:"Platform"};var eh;(function(e){e[e.CDS2=0]="CDS2",e[e.CDS1=1]="CDS1",e[e.Empty=2]="Empty"})(eh||(Ce.EnvironmentType=eh={}));Ce.EnvironmentCreationTypeConstants={NotSpecified:"NotSpecified",Legacy:"Legacy",DefaultTenant:"DefaultTenant",User:"User",CommonDataModelLegacy:"CommonDataModelLegacy"};Ce.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"};Ce.EnvironmentProvisioningStates={NotSpecified:"NotSpecified",Succeeded:"Succeeded",Deleting:"Deleting",Deleted:"Deleted",FailedDeleting:"FailedDeleting",LinkedDatabaseProvisioning:"LinkedDatabaseProvisioning",LinkedDatabaseFailedProvisioning:"LinkedDatabaseFailedProvisioning",LinkedDatabaseFailedConfiguring:"LinkedDatabaseFailedConfiguring",LinkedDatabaseUnavailable:"LinkedDatabaseUnavailable",Creating:"Creating"};Ce.EnvironmentMigrationConstants={phases:{completed:"Completed"}};var th;(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"})(th||(Ce.EnvironmentDisableReasonCode=th={}));var rh;(function(e){e.LogicApps="LogicApps",e.SelfHostSingleTenant="SelfHostSingleTenant",e.SelfHostMultiTenant="SelfHostMultiTenant"})(rh||(Ce.EnvironmentFlowHostingType=rh={}))});var dh=g(A=>{"use strict";var z1=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 W1=z1(Ym()),oe=nh(),_a=gc();function j1(e){let t=Or(e);return t&&t.version}A.getCrmVersion=j1;function Or(e){return e&&e.properties&&e.properties.linkedEnvironmentMetadata}A.getLinkedEnvironmentMetadata=Or;function Tr(e,t){return e?!!e[t]:!1}A.doesUserHavePermission=Tr;A.crmBapSolutionId="00000001-0000-0000-0001-00000000009b";A.DEFAULT_SOLUTION_ID="fd140aaf-4df4-11dd-bd17-0019b9312238";A.DEFAULT_SOLUTION_UNIQUE_NAME="Default";function Rn(e){return!!Or(e)&&ih(e)}A.environmentHasCds2Database=Rn;function H1(e){if(e&&Rn(e)){let t=en(e);return(0,_a.getCrmAdminSecurityRolesUrl)(t)}return""}A.getSecurityUsersUrl=H1;function Q1(e){if(e&&Rn(e)){let t=en(e);return(0,_a.getCrmAdminSecurityUsersUrl)(t)}return""}A.getSecurityRolesUrl=Q1;function J1(e){if(e&&Rn(e)){let t=en(e);(0,_a.getCrmAllSolutionsUrl)(t)}return""}A.getAllSolutionsUrl=J1;function X1(e){if(e&&Rn(e)){let t=en(e);return(0,_a.getCrmAllPublishersUrl)(t)}return""}A.getAllPublishersUrl=X1;function K1(e){return e&&Rn(e)?en(e):""}A.getAllThemesUrl=K1;function ih(e){return!!e&&e.properties&&!!e.properties.provisioningState&&e.properties.provisioningState.toUpperCase()===oe.EnvironmentProvisioningStates.Succeeded.toUpperCase()}A.isEnvironmentInSuccessfulState=ih;function Y1(e){if(e&&Rn(e)){let t=en(e);return(0,_a.getCrmDevResourcesUrl)(t)}return""}A.getDevResourcesUrl=Y1;function Z1(e){return`${e}designer/app/{${A.crmBapSolutionId}}/CreateNewApp}}`}A.getCrmAppDesignerUrl=Z1;function en(e){let t=Or(e);if(t){let r=t.instanceUrl;return r?r.endsWith("/")?r:r+"/":""}return""}A.getCrmInstanceUrl=en;function eP(e){let t=Or(e);return t?t.uniqueName:""}A.getCrmInstanceName=eP;function tP(e){return Or(e)?oe.EnvironmentType.CDS2:e&&e.properties&&e.properties.namespace?oe.EnvironmentType.CDS1:oe.EnvironmentType.Empty}A.getEnvironmentType=tP;function rP(e){return e&&e.properties&&e.properties.environmentSku===oe.EnvironmentSkuConstants.Developer}A.isDevEnvironment=rP;function nP(e){return e&&e.properties&&e.properties.environmentSku===oe.EnvironmentSkuConstants.Production}A.isProdEnvironment=nP;function iP(e){return e&&e.properties&&e.properties.environmentSku===oe.EnvironmentSkuConstants.Sandbox}A.isSandboxEnvironment=iP;function Pa(e){return e&&e.properties&&e.properties.environmentSku===oe.EnvironmentSkuConstants.Teams}A.isTeamsEnvironment=Pa;function aP(e){return e&&e.properties&&e.properties.environmentSku===oe.EnvironmentSkuConstants.Platform}A.isPlatformEnvironment=aP;var oP=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.environmentSku)===oe.EnvironmentSkuConstants.Trial};A.isTrialEnvironment=oP;function sP(e){return e&&e.properties&&(e.properties.isDefault||e.properties.creationType===oe.EnvironmentCreationTypeConstants.DefaultTenant)}A.isDefaultEnvironment=sP;function lP(e){return e&&e.properties&&!!e.properties.states&&!!e.properties.states.runtime&&e.properties.states.runtime.id==="Disabled"}A.isDisabledEnvironment=lP;function uP(e){return e&&e.properties&&Tr(e.properties.permissions,oe.environmentPermissions.CreateDatabase)}A.canUserCreateDatabase=uP;function cP(e){return!!(e&&e.properties&&e.properties.provisioningState&&ch(e.properties.provisioningState,oe.EnvironmentProvisioningStates.LinkedDatabaseProvisioning))}A.isDatabaseInProvisioningState=cP;function dP(e){return!!e&&!!e.properties&&e.properties.provisioningState===oe.EnvironmentProvisioningStates.Creating}A.isEnvironmentInCreatingState=dP;function pP(e){return e&&e.properties&&(e.properties.provisioningState===oe.EnvironmentProvisioningStates.Deleted||e.properties.provisioningState===oe.EnvironmentProvisioningStates.Deleting||e.properties.provisioningState===oe.EnvironmentProvisioningStates.FailedDeleting)}A.isEnvironmentInDeletedState=pP;function fP(e){return!!e&&!!e.properties&&!!e.properties.expirationTime&&Date.parse(e.properties.expirationTime)<Date.now()}A.isEnvironmentExpired=fP;function mP(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=mP;function hP(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Test"}A.isEnvironmentInTestCluster=hP;function gP(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Preprod"}A.isEnvironmentInPreprodCluster=gP;function vP(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="FirstRelease"}A.isEnvironmentInFirstReleaseCluster=vP;function bP(e){return e&&e.name||""}A.getEnvironmentName=bP;function yP(e){return e&&e.properties&&e.properties.displayName||""}A.getEnvironmentDisplayName=yP;var ah="9.1.0.8202";A.cdsVersionSupportingOSColorEdit="9.1.0000.20708";function wP(e){return lh(e,ah)}A.doesCds2EnvironmentSupportApiVersion9_1=wP;function AP(e){return hc(e,ah)}A.doesCds2VersionSupportApiVersion9_1=AP;function oh(e){let t=Or(e);if(t)return t.securityGroupId}function sh(e){return e&&e.properties&&e.properties.connectedGroups}function CP(e,t){let r=sh(e);return!!r&&!!r.find(n=>n.id===t)||oh(e)===t}A.hasSecurityGroupId=CP;function SP(e){let t=sh(e);return t&&t.length>0&&t[0].id?t[0].id:oh(e)}A.getSecurityOrConnectedGroupId=SP;function lh(e,t){let r=e.version;return r?hc(r,t):!1}A.isCds2EnvironmentVersionAtLeast=lh;function hc(e,t){return t?e?(0,W1.default)(e,t)>=0:!1:!0}A.checkVersions=hc;function NP(e){return e&&e.properties&&e.properties.updateCadence&&e.properties.updateCadence.id||"NotSpecified"}A.getEnvironmentUpdateCadence=NP;function EP(e){let t=Or(e);return t?Number(t.baseLanguage):0}A.getEnvironmentLanguageCode=EP;function uh(e){let t=Or(e);return t?t.instanceApiUrl:void 0}A.getEnvironmentInstanceApiUrl=uh;function DP(e){let t=uh(e);return t?t+"/api/data/v9.2":""}A.getEnvironmentWebApiUrl=DP;function IP(e){let t=en(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=IP;var _P=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.databaseType)===oe.DatabaseType.CommonDataService};A.hasCommonDataServiceDatabase=_P;var PP=e=>{var t;return Tr((t=e.properties)===null||t===void 0?void 0:t.permissions,oe.environmentPermissions.AdminReadEnvironment)};A.doesUserHaveAdminPermission=PP;var TP=e=>{var t;return Tr((t=e.properties)===null||t===void 0?void 0:t.permissions,oe.environmentPermissions.CreatePowerApp)};A.doesUserHaveCreateAppPermission=TP;var OP=e=>(0,A.doesUserHaveAdminPermission)(e)&&(0,A.hasCommonDataServiceDatabase)(e)?!0:(0,A.doesUserHaveCreateAppPermission)(e)?Pa(e)||(0,A.doesUserHaveDatabaseTablePermissions)(e):!1;A.isUserMakerWithDataAccess=OP;var RP=e=>(0,A.doesUserHaveCreateAppPermission)(e)&&!Pa(e)&&!(0,A.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,A.doesUserHaveAdminPermission)(e)||!(0,A.hasCommonDataServiceDatabase)(e));A.isUserMakerWithoutDataAccess=RP;var xP=e=>[oe.environmentPermissions.CreateDatabaseEntities,oe.environmentPermissions.ListDatabaseEntities,oe.environmentPermissions.UpdateDatabaseEntities,oe.environmentPermissions.DeleteDatabaseEntities].every(t=>{var r;return Tr((r=e.properties)===null||r===void 0?void 0:r.permissions,t)});A.doesUserHaveDatabaseTablePermissions=xP;var FP=e=>{var t;return Tr((t=e.properties)===null||t===void 0?void 0:t.permissions,oe.environmentPermissions.CreateDatabase)};A.doesUserHaveCreateDatabasePermission=FP;function ch(e,t){return!e&&!t?!0:!e||!t?!1:e.toUpperCase()===t.toUpperCase()}A.equalsIgnoreCase=ch;var LP=e=>{var t;return Tr((t=e.properties)===null||t===void 0?void 0:t.permissions,oe.environmentPermissions.CreateFlow)};A.doesUserHaveCreateFlowPermission=LP;var kP=e=>(0,A.doesUserHaveAdminPermission)(e)&&(0,A.hasCommonDataServiceDatabase)(e)?!0:(0,A.doesUserHaveCreateFlowPermission)(e)?Pa(e)||(0,A.doesUserHaveDatabaseTablePermissions)(e):!1;A.isUserPautoMakerWithDataAccess=kP;var MP=e=>(0,A.doesUserHaveCreateFlowPermission)(e)&&!Pa(e)&&!(0,A.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,A.doesUserHaveAdminPermission)(e)||!(0,A.hasCommonDataServiceDatabase)(e));A.isUserPautoMakerWithoutDataAccess=MP;var UP=e=>{var t,r;return!Tr((t=e.properties)===null||t===void 0?void 0:t.permissions,oe.environmentPermissions.CreateFlow)&&Tr((r=e.properties)===null||r===void 0?void 0:r.permissions,oe.environmentPermissions.ReadEnvironment)};A.doesUserHaveFlowRunOnlyPermission=UP});var gc=g(b=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});b.getRequiredComponentsQueryUrl=b.solutionComponentCountSummariesQueryUrl=b.solutionComponentSummariesQueryUrl=b.solutionComponentConfigurationsQueryUrl=b.chartsQueryUrl=b.workflowsQueryUrl=b.entityDefinitionsQueryUrl=b.solutionComponentDefinitionsQueryUrl=b.getCreateNewArticleTemplateUrl=b.getCreateNewPublisherUrl=b.getEnableSecurityRolesUrl=b.getArticleTemplateUrl=b.getFieldSecurityProfileDesignerUrl=b.getSecurityRoleDesignerUrl=b.getMailMergeTemplateDesignerUrl=b.getEmailTemplateDesignerUrl=b.getConnectionRoleDesignerUrl=b.getSiteMapDesignerUrl=b.getWebResourceFileUrl=b.getWebResourceDesignerUrl=b.getReportDesignerUrl=b.getBusinessProcessFlowDesignerUrl=b.getProcessShareUrl=b.getProcessDesignerUrl=b.getChartDesignerUrl=b.getOpenModernEntityDashboardUrl=b.getNewModernEntityDashboardUrl=b.getNewModernDashboardUrl=b.getOpenModernDashboardUrl=b.getDashboardDesignerUrl=b.getAppModuleDesignerUrl=b.privilegesQueryUrls=b.xrmApiUrl=b.getPlayAppModuleUrl=b.getCrmAdminSecurityUsersUrl=b.getCrmAdminSecurityRolesUrl=b.getCrmMyAppsUrl=b.getCrmAppDesignerUrl=b.getCrmDevResourcesUrl=b.getCrmAllPublishersUrl=b.getCrmAllSolutionsUrl=b.getSolutionPublisherUrl=b.getExportTranslationFileName=b.getExportSolutionTranslationUrl=b.getImportSolutionTranslationUrl=b.getShowSolutionDependenciesUrl=b.getShowComponentDependenciesUrl=b.cdsServiceUrl=b.ODATA_NEXT_LINK=b.ODATA_MAX_PAGE_SIZE=void 0;b.retrieveOrganizationResources=b.getUCIEntityRecordEditUrl=b.getUCIEntityRecordBaseUrl=b.getBusinessRuleDesignerUri=b.retrieveUnpublishedSuffix=b.getSavePowerSettingUri=b.getPowerSettingUri=b.getPowerSettingsUri=b.RetrievePlatform=b.getAppSettingOverrideUri=b.AppSettingOverrideName=b.getOrgSettingOverrideUri=b.OrgSettingOverrideName=b.getSettingDefinitionsUri=b.retrieveFeatureControlSettingsByNamespaceUrl=b.retrieveDeploymentPipelineConfigAppUrl=b.SPNPrincipalIdUrl=b.retrieveDeploymentEnvironmentInfoUrl=b.devSolutionInfoUrl=b.deployOperationStatusUrl=b.getAIGeneratedDeploymentNotesUrl=b.deploymentStageRunUrl=b.validatePackageAsyncUrl=b.deployPackageAsyncUrl=b.updateDeploymentStageRunUrl=b.createDeploymentStageRunUrl=b.retrieveDeploymentStagesUrl=b.retrievePipelinesUrl=b.retrieveDeploymentPipelineInfoUrl=b.getDeploymentStageRunsUrl=b.appDeploymentUrls=b.getProvisionLanguageUrl=b.getSolutionQueryUrl=b.getSolutionsByUniqueNameQueryUrl=b.solutionsQueryUrl=b.getDependentComponentsWithMetadataQueryUrl=void 0;var ph=dh();b.ODATA_MAX_PAGE_SIZE="odata.maxpagesize";b.ODATA_NEXT_LINK="@odata.nextLink";b.cdsServiceUrl="https://cds-org/";var Oa;(function(e){e.AllSolutions="11",e.AllPublishers="10",e.DevResources="05"})(Oa||(Oa={}));function BP(e,t,r,n){return`${e}tools/dependency/dependencyviewdialog.aspx?appSolutionId=%7b${t}%7d&dType=1&objectid=%7b${r}%7d&objecttype=${n}&operationtype=showdependency`}b.getShowComponentDependenciesUrl=BP;function $P(e,t){let r=`dType=1&isproactivecheck=true&objecttype=7100&operationtype=dependenciesforuninstall&objectid=${t}`;return`${e}tools/dependency/dependencyviewdialog.aspx?${r}`}b.getShowSolutionDependenciesUrl=$P;function qP(e,t){return`${e}tools/muiProvisioning/Dialogs/LangTranslationsImport.aspx?dType=1&appSolutionId=${t}`}b.getImportSolutionTranslationUrl=qP;function VP(e,t){return`${e}_grid/cmds/dlg_exportsolution.aspx?command=exporttranslation&appSolutionId=${t}`}b.getExportSolutionTranslationUrl=VP;function GP(e,t){return e!==void 0&&t!==void 0&&`CrmTranslations_${e}_${t.replace(/[.]/g,"_")}.zip`||""}b.getExportTranslationFileName=GP;function zP(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`}b.getSolutionPublisherUrl=zP;function vc(e,t){return`${e}tools/systemcustomization/systemCustomization.aspx?pid=${t}`}function WP(e){return vc(e,Oa.AllSolutions)}b.getCrmAllSolutionsUrl=WP;function jP(e){return vc(e,Oa.AllPublishers)}b.getCrmAllPublishersUrl=jP;function HP(e){return vc(e,Oa.DevResources)}b.getCrmDevResourcesUrl=HP;function QP(e,t=ph.crmBapSolutionId){return`${e}designer/app/${t}#/CreateNewApp`}b.getCrmAppDesignerUrl=QP;function JP(e){return`${e}apps`}b.getCrmMyAppsUrl=JP;function XP(e){return fh(e,"role")+"&forceUCI=0"}b.getCrmAdminSecurityRolesUrl=XP;function KP(e){return`${fh(e,"systemuser")}&forceclassic=1`}b.getCrmAdminSecurityUsersUrl=KP;function fh(e,t){return`${e}main.aspx?pagetype=entitylist&etn=${t}`}function YP(e,t){return`${e}main.aspx?appid=${t}`}b.getPlayAppModuleUrl=YP;b.xrmApiUrl="api/data/v9.0";b.privilegesQueryUrls={systemUserInfo:e=>`${e}${b.xrmApiUrl}/WhoAmI`,userPrivileges:(e,t)=>`${e}${b.xrmApiUrl}/systemusers(${t})/Microsoft.Dynamics.CRM.RetrieveUserPrivileges`,systemPrivileges:e=>`${e}${b.xrmApiUrl}/privileges/Microsoft.Dynamics.CRM.RetrievePrivilegeSet`};function ZP(e,t,r=ph.crmBapSolutionId){return`${e}designer/app/${r}/${t}/AppDesignerCanvas/${t}`}b.getAppModuleDesignerUrl=ZP;function eT(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${r}%7d&extraqs=%26formId%3d%7b${t}%7d%26dashboardType%3d1030&pagetype=${`${n?"ic":""}dashboardeditor`}`}b.getDashboardDesignerUrl=eT;function tT(e,t,r){return`/e/${e}/s/${t}/dashboard/${r}`}b.getOpenModernDashboardUrl=tT;function rT(e,t,r){let n=r!==void 0?r.toString():void 0;return`/e/${e}/s/${t}/dashboard/new${n?`/${n}`:""}`}b.getNewModernDashboardUrl=rT;function nT(e,t,r,n){let i=n!==void 0?n.toString():void 0;return`/e/${e}/s/${t}/n/${r}/dashboard/new${i?`/${i}`:""}`}b.getNewModernEntityDashboardUrl=nT;function iT(e,t,r,n){return`/e/${e}/s/${t}/n/${r}/dashboard/${n}`}b.getOpenModernEntityDashboardUrl=iT;function aT(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${t}%7d&extraqs=etc=${r||""}`+(n?`%26id=${n}`:"")+"&pagetype=vizdesigner"}b.getChartDesignerUrl=aT;function oT(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}b.getProcessDesignerUrl=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`}b.getProcessShareUrl=sT;function lT(e,t){return`${e}Tools/ProcessControl/UnifiedProcessDesigner.aspx?id=${t}`}b.getBusinessProcessFlowDesignerUrl=lT;function uT(e,t,r){return`${e}CRMReports/reportproperty.aspx?appSolutionId=%7b${r}%7d&disablePersonal=true&id=%7b${t}%7d`}b.getReportDesignerUrl=uT;function cT(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`}b.getWebResourceDesignerUrl=cT;function dT(e,t){return`${e}WebResources/${t}`}b.getWebResourceFileUrl=dT;function pT(e,t,r){return`${e}designer/sitemap/${r}/${t}/SiteMapHome/${t}`}b.getSiteMapDesignerUrl=pT;function fT(e,t,r){return`${e}connections/connectionroles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}b.getConnectionRoleDesignerUrl=fT;function mT(e,t,r){return`${e}tools/emailtemplateeditor/emailtemplateeditor.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}b.getEmailTemplateDesignerUrl=mT;function hT(e,t,r){return`${e}tools/mailmerge/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}b.getMailMergeTemplateDesignerUrl=hT;function gT(e,t,r){return`${e}biz/roles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}b.getSecurityRoleDesignerUrl=gT;function vT(e,t,r){return`${e}biz/fieldsecurityprofiles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}b.getFieldSecurityProfileDesignerUrl=vT;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`}b.getArticleTemplateUrl=bT;function yT(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}`}b.getEnableSecurityRolesUrl=yT;function wT(e){return`${e}tools/publisher/edit.aspx`}b.getCreateNewPublisherUrl=wT;function AT(e,t){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?appSolutionId=${t}`}b.getCreateNewArticleTemplateUrl=AT;b.solutionComponentDefinitionsQueryUrl="api/data/v9.0/solutioncomponentdefinitions";b.entityDefinitionsQueryUrl="api/data/v9.0/EntityDefinitions?$select=EntitySetName,DisplayName,LogicalName&$filter=";b.workflowsQueryUrl="api/data/v9.0/workflows";b.chartsQueryUrl="/api/data/v9.0/savedqueryvisualizations";b.solutionComponentConfigurationsQueryUrl="/api/data/v9.1/solutioncomponentconfigurations?$filter=isdisplayable eq true&$select=name";b.solutionComponentSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentsummaries";b.solutionComponentCountSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentcountsummaries";function CT(e,t){return`${b.xrmApiUrl}/RetrieveRequiredComponents(ObjectId=${e},ComponentType=${t})`}b.getRequiredComponentsQueryUrl=CT;function ST(e,t){return`${b.cdsServiceUrl}${b.xrmApiUrl}/RetrieveDependentComponentsWithMetadata(ObjectId=${e},ComponentType=${t})`}b.getDependentComponentsWithMetadataQueryUrl=ST;b.solutionsQueryUrl="/api/data/v9.0/solutions?$expand=publisherid&$filter=(isvisible eq true)";function NT(e){return`/api/data/v9.0/solutions?$expand=publisherid&$filter=(uniquename eq '${e}')`}b.getSolutionsByUniqueNameQueryUrl=NT;function ET(e){return`/api/data/v9.0/solutions(${e})?$expand=publisherid`}b.getSolutionQueryUrl=ET;function DT(e){return`${e}api/data/v9.1/ProvisionLanguageForUser`}b.getProvisionLanguageUrl=DT;b.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 IT(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`}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+ &$orderby=starttime desc`}b.getDeploymentStageRunsUrl=IT;function _T(e,t,r){return`/api/data/v9.1/RetrieveDeploymentPipelineInfo(DeploymentPipelineId=${e},SourceEnvironmentId='${t}',ArtifactName='${r}')`}b.retrieveDeploymentPipelineInfoUrl=_T;function PT(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}')`}y.retrievePipelinesUrl=TT;function OT(e){return`/api/data/v9.0/deploymentstages+ &$filter=(environmentid eq '${e}')`}b.retrievePipelinesUrl=PT;function TT(e){return`/api/data/v9.0/deploymentstages?$filter=(_deploymentpipelineid_value eq ${e})&$select=name,description,deploymentstageid,_previousdeploymentstageid_value- &$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+ &$expand=targetdeploymentenvironmentid($select=deploymentenvironmentid,environmentid,name)`}b.retrieveDeploymentStagesUrl=TT;function OT(){return"/api/data/v9.0/deploymentstageruns?$select=deploymentstagerunid"}b.createDeploymentStageRunUrl=OT;function RT(e){return`/api/data/v9.0/deploymentstageruns(${e})`}b.updateDeploymentStageRunUrl=RT;function xT(){return"/api/data/v9.0/DeployPackageAsync"}b.deployPackageAsyncUrl=xT;function FT(){return"/api/data/v9.0/ValidatePackageAsync"}b.validatePackageAsyncUrl=FT;function LT(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)":""}`}b.deploymentStageRunUrl=LT;function kT(e){return`/api/data/v9.0/deploymentstageruns(${e})+ ?$select=aigenerateddeploymentnotes,deploymentstagerunid`}b.getAIGeneratedDeploymentNotesUrl=kT;function MT(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`}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=_deploymentstageid_value,deploymentstagerunid,stagerunstatus,operation,operationstatus,suboperation,artifactname`}b.deployOperationStatusUrl=MT;function UT(e){return`/api/data/v9.0/solutions(${e})+ ?$select=solutionid,uniquename,version`}b.devSolutionInfoUrl=UT;function BT(e){return`/api/data/v9.0/deploymentenvironments?$select=deploymentenvironmentid,environmentid,environmenttype,name- &$filter=(environmentid eq '${e}')`}y.retrieveDeploymentEnvironmentInfoUrl=$T;var qT=e=>`/api/data/v9.0/systemusers+ &$filter=(environmentid eq '${e}')`}b.retrieveDeploymentEnvironmentInfoUrl=BT;var $T=e=>`/api/data/v9.0/systemusers?$select=azureactivedirectoryobjectid- &$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+ &$filter=(applicationid eq '${e}')`;b.SPNPrincipalIdUrl=$T;function qT(){return"/api/data/v9.0/appmodules?$filter=(uniquename eq 'AppDeploymentConfiguration')"}b.retrieveDeploymentPipelineConfigAppUrl=qT;b.retrieveFeatureControlSettingsByNamespaceUrl="/api/data/v9.1/RetrieveFeatureControlSettingsByNamespace";function VT(e){return`/api/data/v9.0/settingdefinitions${e}`}b.getSettingDefinitionsUri=VT;b.OrgSettingOverrideName="organizationsettings";function GT(e,t=!1){let r=`/api/data/v9.0/${b.OrgSettingOverrideName}${e}`;return t?`${b.cdsServiceUrl}${r}`:r}b.getOrgSettingOverrideUri=GT;b.AppSettingOverrideName="appsettings";function zT(e,t=!1){let r=`/api/data/v9.0/${b.AppSettingOverrideName}${e}`;return t?`${b.cdsServiceUrl.replace("/$","")}${r}`:r}b.getAppSettingOverrideUri=zT;var Ta;(function(e){e[e.All=0]="All",e[e.IsPlatformOnly=1]="IsPlatformOnly",e[e.NotPlatformOnly=2]="NotPlatformOnly"})(Ta||(b.RetrievePlatform=Ta={}));function WT(e,t,r,n=Ta.All,i=!1){let a=[];e&&a.push(`AppUniqueName='${e}'`),t!=null&&a.push(`ReleaseLevel=${t}`),r&&a.push(`RetrieveHiddenSettings=${r}`),n!==Ta.All&&a.push(`RetrievePlatformSettings=${n===Ta.IsPlatformOnly?1:0}`);let o="/api/data/v9.0/RetrieveUnpublishedOverridableSettingsInfo";return a.length&&(o=`${o}(${a.join(",")})`),i?`${b.cdsServiceUrl}${o}`:o}b.getPowerSettingsUri=WT;function jT(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?`${b.cdsServiceUrl}${a}`:a}b.getPowerSettingUri=jT;function HT(e=!1){let t="/api/data/v9.0/SaveSettingValue()";return e?`${b.cdsServiceUrl}${t}`:t}b.getSavePowerSettingUri=HT;b.retrieveUnpublishedSuffix="Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()";function QT(e){return`tools/systemcustomization/businessrules/businessRulesDesigner.aspx?BRlaunchpoint=BRGrid&appSolutionId={${e}}`}b.getBusinessRuleDesignerUri=QT;function mh({environmentInstanceUrl:e,entityLogicalName:t}){return e&&t?`${e}main.aspx?cmdbar=true&forceUCI=1&navbar=off&newWindow=true&pageType=entityRecord&etn=${t}`:void 0}b.getUCIEntityRecordBaseUrl=mh;function JT({baseUrl:e,environmentInstanceUrl:t,entityLogicalName:r,recordId:n}){let i=e||mh({environmentInstanceUrl:t,entityLogicalName:r});return i&&n?`${i}&id=${n}`:void 0}b.getUCIEntityRecordEditUrl=JT;b.retrieveOrganizationResources=`${b.cdsServiceUrl}api/data/v9.0/RetrieveOrganizationResources`});var hh=g(ms=>{"use strict";Object.defineProperty(ms,"__esModule",{value:!0});ms.DataverseClient=void 0;var XT=gc(),xn=ne(),bc=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}/${XT.xrmApiUrl}${n}`}async send(t,r){try{return await r()}catch(n){throw n instanceof xn.SdkError?n:new xn.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 xn.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${t}'`)}if(r.protocol!==n.protocol||r.host!==n.host)throw new xn.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 xn.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 xn.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 xn.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)))}};ms.DataverseClient=bc});var Z=g(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.odataQuery=Te.normalizeGuid=Te.createSafeXmlElement=Te.assertNoControlChars=Te.assertODataName=Te.assertXmlName=Te.xmlText=Te.odataPathLiteral=Te.odataLiteral=void 0;var hs=ne();function gh(e){return String(e??"").replace(/'/g,"''")}Te.odataLiteral=gh;function KT(e){return encodeURIComponent(gh(e))}Te.odataPathLiteral=KT;function YT(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}Te.xmlText=YT;function vh(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 hs.InvalidArgumentError(`${t} must be a valid XML element name (got '${e}')`);return e}Te.assertXmlName=vh;function ZT(e,t){let r=String(e??"");if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new hs.InvalidArgumentError(`${t} must be a valid OData identifier (letters, digits, underscore): got '${e}'`);return e}Te.assertODataName=ZT;function eO(e,t){if(/[\u0000-\u001F\u007F]/.test(String(e??"")))throw new hs.InvalidArgumentError(`${t} must not contain control characters (including CR/LF): they would inject additional lines into the request`);return e}Te.assertNoControlChars=eO;function tO(e,t,r){return e.createElement(vh(t,r))}Te.createSafeXmlElement=tO;var rO=/^[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 nO(e,t){let r=String(e??""),n=r.length===38&&r.startsWith("{")&&r.endsWith("}")?r.slice(1,-1):r;if(!rO.test(n))throw new hs.InvalidArgumentError(`${t} must be a valid GUID (got '${e}')`);return n.toLowerCase()}Te.normalizeGuid=nO;function iO(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=iO});var ge=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 ci=ne(),Ra=Z();ee.VERSION_CONFLICT_CODE="VERSION_CONFLICT";ee.UPDATE_NO_ETAG_CODE="ARTIFACT_UPDATE_NO_ETAG";function aO(e,t){return{query:`?$select=${encodeURIComponent(e)}`,options:{headers:{...t??{},Prefer:"return=representation"}}}}ee.echoWrite=aO;function oO(e,t,r){if(!e)throw new ci.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=oO;function sO(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=sO;function yc(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=yc;function lO(e,t,r){return r?{...e,[t]:(0,Ra.normalizeGuid)(r,t)}:e}ee.withClientMintedId=lO;function uO(e,t,r){let n=yc(e,t);if(!n)throw new ci.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`);return n}ee.requireCreatedId=uO;function cO(e,t,r,n){let i=yc(e,t);if(i)return i;if(n)return(0,Ra.normalizeGuid)(n,t);throw new ci.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`)}ee.resolveCreatedId=cO;function bh(e,t){if(e.status===412)throw new ci.SdkError(ee.VERSION_CONFLICT_CODE,`Version conflict (412) from ${t}`);if(e.status<200||e.status>=300)throw new ci.ConnectionError(t,e.status,dO(e.body),e.body);return e}ee.ensureSuccess=bh;function dO(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 pO(e,t,r,n){let i=(0,Ra.normalizeGuid)(r,"id"),a=`/${t}(${i})`;bh(await e.delete(a,n?{headers:{"If-Match":n}}:void 0),e.apiUrl(a))}ee.deleteRecord=pO;function fO(e){return e instanceof ci.ConnectionError&&e.statusCode===404}ee.isAlreadyDeleted=fO;function mO(){return new Date().toISOString()}ee.nowIso=mO});var yh=g(rn=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});rn.findColumns=rn.findTables=rn.fetchEntityMetadataFromApi=void 0;var wc=ge(),sr=Z();function xa(e){var t,r;return(r=(t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)!==null&&r!==void 0?r:""}async function di(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 tn(e){return`/EntityDefinitions(LogicalName='${(0,sr.odataLiteral)(e)}')`}async function hO(e,t,r){let n=await di(e,`${tn(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata${(0,sr.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 gO(e,t,r){var n;let i=await di(e,`${tn(t)}/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata${(0,sr.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:xa(s.Label)}}))}}async function vO(e,t,r){let n=await di(e,`${tn(t)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata${(0,sr.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 di(e,`${tn(t)}/OneToManyRelationships${(0,sr.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 di(e,`${tn(t)}/ManyToOneRelationships${(0,sr.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 di(e,`${tn(t)}/ManyToManyRelationships${(0,sr.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 yO(e,t){var r,n,i,a,o;let s=`${tn(t)}`+(0,sr.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,EntitySetName,IsCustomEntity,PrimaryNameAttribute,PrimaryIdAttribute"],["$expand","Attributes($select=LogicalName,DisplayName,AttributeType,IsCustomAttribute)"]]),u=(0,wc.ensureSuccess)(await e.get(s),e.apiUrl(s)).body,c=((r=u.Attributes)!==null&&r!==void 0?r:[]).map(m=>{var h;return{logicalName:m.LogicalName,displayName:xa(m.DisplayName),attributeType:(h=m.AttributeType)!==null&&h!==void 0?h:"Unknown",isCustomAttribute:!!m.IsCustomAttribute}}),d=new Map(c.map(m=>[m.logicalName,m])),[,,,p]=await Promise.all([hO(e,t,d),gO(e,t,d),vO(e,t,d),bO(e,t)]);return{logicalName:u.LogicalName,schemaName:(n=u.SchemaName)!==null&&n!==void 0?n:u.LogicalName,displayName:xa(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}}rn.fetchEntityMetadataFromApi=yO;async function wO(e,t,r){var n,i;let a=`/EntityDefinitions${(0,sr.odataQuery)([["$select","LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity"]])}`,s=(i=(n=(0,wc.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:xa(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}rn.findTables=wO;async function AO(e,t,r,n){var i,a;let o=`${tn(t)}/Attributes`+(0,sr.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute"]]),l=(a=(i=(0,wc.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,m;return{logicalName:d.LogicalName,schemaName:(p=d.SchemaName)!==null&&p!==void 0?p:d.LogicalName,displayName:xa(d.DisplayName),attributeType:(m=d.AttributeType)!==null&&m!==void 0?m:"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}rn.findColumns=AO});var pi=g(gs=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});gs.DEFAULT_LCID=void 0;gs.DEFAULT_LCID=1033});var wh=g(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});Ac.default="ffffffff-ffff-ffff-ffff-ffffffffffff"});var Ah=g(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});Cc.default="00000000-0000-0000-0000-000000000000"});var Ch=g(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});Sc.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(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});var CO=Ch();function SO(e){return typeof e=="string"&&CO.default.test(e)}Nc.default=SO});var La=g(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var NO=Fa();function EO(e){if(!(0,NO.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)}Ec.default=EO});var Rr=g(ka=>{"use strict";Object.defineProperty(ka,"__esModule",{value:!0});ka.unsafeStringify=void 0;var DO=Fa(),Ye=[];for(let e=0;e<256;++e)Ye.push((e+256).toString(16).slice(1));function Sh(e,t=0){return(Ye[e[t+0]]+Ye[e[t+1]]+Ye[e[t+2]]+Ye[e[t+3]]+"-"+Ye[e[t+4]]+Ye[e[t+5]]+"-"+Ye[e[t+6]]+Ye[e[t+7]]+"-"+Ye[e[t+8]]+Ye[e[t+9]]+"-"+Ye[e[t+10]]+Ye[e[t+11]]+Ye[e[t+12]]+Ye[e[t+13]]+Ye[e[t+14]]+Ye[e[t+15]]).toLowerCase()}ka.unsafeStringify=Sh;function IO(e,t=0){let r=Sh(e,t);if(!(0,DO.default)(r))throw TypeError("Stringified UUID is invalid");return r}ka.default=IO});var ys=g(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});var _O=require("crypto"),bs=new Uint8Array(256),vs=bs.length;function PO(){return vs>bs.length-16&&((0,_O.randomFillSync)(bs),vs=0),bs.slice(vs,vs+=16)}Dc.default=PO});var Ic=g(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.updateV1State=void 0;var Nh=ys(),TO=Rr(),Ma={};function OO(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=Eh(e.random??e.rng?.()??(0,Nh.default)(),e.msecs,e.nsecs,e.clockseq,e.node,t,r);else{let a=Date.now(),o=(0,Nh.default)();Dh(Ma,a,o),n=Eh(o,Ma.msecs,Ma.nsecs,i?void 0:Ma.clockseq,i?void 0:Ma.node,t,r)}return t??(0,TO.unsafeStringify)(n)}function Dh(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}Ua.updateV1State=Dh;function Eh(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}Ua.default=OO});var Pc=g(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var RO=La(),xO=Rr();function FO(e){let t=typeof e=="string"?(0,RO.default)(e):e,r=LO(t);return typeof e=="string"?(0,xO.unsafeStringify)(r):r}_c.default=FO;function LO(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 Ih=g(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});var kO=require("crypto");function MO(e){return Array.isArray(e)?e=Buffer.from(e):typeof e=="string"&&(e=Buffer.from(e,"utf8")),(0,kO.createHash)("md5").update(e).digest()}Tc.default=MO});var Ba=g(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.URL=xr.DNS=xr.stringToBytes=void 0;var _h=La(),UO=Rr();function Ph(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}xr.stringToBytes=Ph;xr.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8";xr.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function BO(e,t,r,n,i,a){let o=typeof r=="string"?Ph(r):r,s=typeof n=="string"?(0,_h.default)(n):n;if(typeof n=="string"&&(n=(0,_h.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,UO.unsafeStringify)(l)}xr.default=BO});var Oh=g(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.URL=Fn.DNS=void 0;var $O=Ih(),Oc=Ba(),Th=Ba();Object.defineProperty(Fn,"DNS",{enumerable:!0,get:function(){return Th.DNS}});Object.defineProperty(Fn,"URL",{enumerable:!0,get:function(){return Th.URL}});function Rc(e,t,r,n){return(0,Oc.default)(48,$O.default,e,t,r,n)}Rc.DNS=Oc.DNS;Rc.URL=Oc.URL;Fn.default=Rc});var Rh=g(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});var qO=require("crypto");xc.default={randomUUID:qO.randomUUID}});var Fh=g(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});var xh=Rh(),VO=ys(),GO=Rr();function zO(e,t,r){if(xh.default.randomUUID&&!t&&!e)return xh.default.randomUUID();e=e||{};let n=e.random??e.rng?.()??(0,VO.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,GO.unsafeStringify)(n)}Fc.default=zO});var Lh=g(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});var WO=require("crypto");function jO(e){return Array.isArray(e)?e=Buffer.from(e):typeof e=="string"&&(e=Buffer.from(e,"utf8")),(0,WO.createHash)("sha1").update(e).digest()}Lc.default=jO});var Mh=g(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.URL=Ln.DNS=void 0;var HO=Lh(),kc=Ba(),kh=Ba();Object.defineProperty(Ln,"DNS",{enumerable:!0,get:function(){return kh.DNS}});Object.defineProperty(Ln,"URL",{enumerable:!0,get:function(){return kh.URL}});function Mc(e,t,r,n){return(0,kc.default)(80,HO.default,e,t,r,n)}Mc.DNS=kc.DNS;Mc.URL=kc.URL;Ln.default=Mc});var Uh=g(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});var QO=Rr(),JO=Ic(),XO=Pc();function KO(e,t,r){e??={},r??=0;let n=(0,JO.default)({...e,_v6:!0},new Uint8Array(16));if(n=(0,XO.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,QO.unsafeStringify)(n)}Uc.default=KO});var Bh=g(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});var YO=La(),ZO=Rr();function eR(e){let t=typeof e=="string"?(0,YO.default)(e):e,r=tR(t);return typeof e=="string"?(0,ZO.unsafeStringify)(r):r}Bc.default=eR;function tR(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 Gh=g($a=>{"use strict";Object.defineProperty($a,"__esModule",{value:!0});$a.updateV7State=void 0;var $h=ys(),rR=Rr(),$c={};function nR(e,t,r){let n;if(e)n=qh(e.random??e.rng?.()??(0,$h.default)(),e.msecs,e.seq,t,r);else{let i=Date.now(),a=(0,$h.default)();Vh($c,i,a),n=qh(a,$c.msecs,$c.seq,t,r)}return t??(0,rR.unsafeStringify)(n)}function Vh(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}$a.updateV7State=Vh;function qh(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}$a.default=nR});var zh=g(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var iR=Fa();function aR(e){if(!(0,iR.default)(e))throw TypeError("Invalid UUID");return parseInt(e.slice(14,15),16)}qc.default=aR});var ws=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 oR=wh();Object.defineProperty(te,"MAX",{enumerable:!0,get:function(){return oR.default}});var sR=Ah();Object.defineProperty(te,"NIL",{enumerable:!0,get:function(){return sR.default}});var lR=La();Object.defineProperty(te,"parse",{enumerable:!0,get:function(){return lR.default}});var uR=Rr();Object.defineProperty(te,"stringify",{enumerable:!0,get:function(){return uR.default}});var cR=Ic();Object.defineProperty(te,"v1",{enumerable:!0,get:function(){return cR.default}});var dR=Pc();Object.defineProperty(te,"v1ToV6",{enumerable:!0,get:function(){return dR.default}});var pR=Oh();Object.defineProperty(te,"v3",{enumerable:!0,get:function(){return pR.default}});var fR=Fh();Object.defineProperty(te,"v4",{enumerable:!0,get:function(){return fR.default}});var mR=Mh();Object.defineProperty(te,"v5",{enumerable:!0,get:function(){return mR.default}});var hR=Uh();Object.defineProperty(te,"v6",{enumerable:!0,get:function(){return hR.default}});var gR=Bh();Object.defineProperty(te,"v6ToV1",{enumerable:!0,get:function(){return gR.default}});var vR=Gh();Object.defineProperty(te,"v7",{enumerable:!0,get:function(){return vR.default}});var bR=Fa();Object.defineProperty(te,"validate",{enumerable:!0,get:function(){return bR.default}});var yR=zh();Object.defineProperty(te,"version",{enumerable:!0,get:function(){return yR.default}})});var ht=g(fi=>{"use strict";Object.defineProperty(fi,"__esModule",{value:!0});fi.assignMissingIds=fi.newId=void 0;var wR=ws();function Wh(){return(0,wR.v4)()}fi.newId=Wh;function AR(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var CR=new Set(["parameters","bag","expression","rawExpression","lookupValue","stepLabels"]);function SR(e){return Vc(e),e}fi.assignMissingIds=SR;function Vc(e){if(Array.isArray(e)){e.forEach(t=>Vc(t));return}if(AR(e)){(typeof e.id!="string"||e.id.length===0)&&(e.id=Wh());for(let t of Object.keys(e))t==="id"||CR.has(t)||Vc(e[t])}}});var Gc=g(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});nn.postChangeSet=nn.parseChangeSetStatuses=nn.renderChangeSet=void 0;var As=ne(),NR=ge(),jh=ht(),Hh=Z();function Qh(e,t){let r=`batch_${(0,jh.newId)()}`,n=`changeset_${(0,jh.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,Hh.assertNoControlChars)(s.path,"batch operation path"),s.etag&&(0,Hh.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+`),batchId:r,contentIds:i}}nn.renderChangeSet=Qh;function Jh(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 m=p.indexOf(`\r\r-`);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+`);if(m===-1)return;let h=p.slice(0,m),w=p.slice(m+4);if(!/^Content-Type:\s*application\/http\b/im.test(h))return;let y=/^HTTP\/1\.[01] (\d{3})\b/.exec(w);if(!y||((i=w.match(/^HTTP\/1\.[01] \d{3}\b/gm))!==null&&i!==void 0?i:[]).length!==1)return;let N=(a=/^Content-ID:\s*(\S+)/im.exec(h))===null||a===void 0?void 0:a[1];if(N===void 0||d.has(N)||!u.has(N))return;d.add(N),c.push(Number(y[1]))}return c.length===0?void 0:c}nn.parseChangeSetStatuses=Jh;async function ER(e,t,r){if(t.length===0)return;let{body:n,batchId:i,contentIds:a}=Qh(e,t),o=await e.postBatch(n,i),s=e.apiUrl("/$batch");if((0,NR.ensureSuccess)(o,s),typeof o.body!="string"||o.body.length===0)throw new As.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=Jh(o.body,a);if(l===void 0)throw new As.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 As.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 As.ConnectionError(s,u,`atomic write of ${r} was rolled back: the change set reported HTTP ${u}`)}nn.postChangeSet=ER});var Cs=g(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.createColumns=J.setColumnVisualization=J.getColumnVisualization=J.createColumn=J.createTable=J.resolveEntitySetName=void 0;var re=ge(),H=Z(),lr=pi(),Oe=ne(),DR=Gc(),IR={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 Ie(e,t){return{"@odata.type":"Microsoft.Dynamics.CRM.Label",LocalizedLabels:[{"@odata.type":"Microsoft.Dynamics.CRM.LocalizedLabel",Label:e,LanguageCode:t}]}}function qa(e){return{Value:e,CanBeChanged:!0,ManagedPropertyLogicalName:"canmodifyrequirementlevelsettings"}}function jc(e){let t=e.indexOf("_");return t>0?e.slice(0,t):e}function Xh(e,t,r){let n=e[t];n&&typeof n=="object"?n.Value=r:e[t]={Value:r}}function Va(e){let t=(0,re.readCreatedId)(e,"MetadataId");if(!t)throw new Oe.InvalidArgumentError("Dataverse did not return a MetadataId for the created metadata component");return t}function _R(e,t,r){var n,i,a,o,s,l,u,c,d,p,m,h,w,y,N,D,x,F,q,G,M,U,B,W;if(t.defaultValue!==void 0&&e!=="boolean")throw new Oe.InvalidArgumentError(`createColumn: 'defaultValue' applies to boolean columns, but '${t.schemaName}' is of type '${e}'.`);if(t.integerFormat!==void 0&&e!=="integer")throw new Oe.InvalidArgumentError(`createColumn: 'integerFormat' applies to integer columns, but '${t.schemaName}' is of type '${e}'.`);switch(e){case"string":return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},MaxLength:(n=t.maxLength)!==null&&n!==void 0?n:100,FormatName:{Value:(i=t.stringFormat)!==null&&i!==void 0?i:"Text"}};case"memo":return{"@odata.type":"Microsoft.Dynamics.CRM.MemoAttributeMetadata",AttributeType:"Memo",AttributeTypeName:{Value:"MemoType"},MaxLength:(a=t.maxLength)!==null&&a!==void 0?a:2e3,Format:"TextArea"};case"integer":return{"@odata.type":"Microsoft.Dynamics.CRM.IntegerAttributeMetadata",AttributeType:"Integer",AttributeTypeName:{Value:"IntegerType"},Format:(o=t.integerFormat)!==null&&o!==void 0?o:"None",MinValue:(s=t.minValue)!==null&&s!==void 0?s:-2147483648,MaxValue:(l=t.maxValue)!==null&&l!==void 0?l:2147483647};case"bigint":return{"@odata.type":"Microsoft.Dynamics.CRM.BigIntAttributeMetadata",AttributeType:"BigInt",AttributeTypeName:{Value:"BigIntType"}};case"double":return{"@odata.type":"Microsoft.Dynamics.CRM.DoubleAttributeMetadata",AttributeType:"Double",AttributeTypeName:{Value:"DoubleType"},Precision:(u=t.precision)!==null&&u!==void 0?u:2,MinValue:(c=t.minValue)!==null&&c!==void 0?c:-1e11,MaxValue:(d=t.maxValue)!==null&&d!==void 0?d:1e11};case"decimal":return{"@odata.type":"Microsoft.Dynamics.CRM.DecimalAttributeMetadata",AttributeType:"Decimal",AttributeTypeName:{Value:"DecimalType"},Precision:(p=t.precision)!==null&&p!==void 0?p:2,MinValue:(m=t.minValue)!==null&&m!==void 0?m:-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:(w=t.precision)!==null&&w!==void 0?w:2,PrecisionSource:2,MinValue:(y=t.minValue)!==null&&y!==void 0?y: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:(D=t.defaultValue)!==null&&D!==void 0?D:!1,OptionSet:{"@odata.type":"Microsoft.Dynamics.CRM.BooleanOptionSetMetadata",TrueOption:{Value:1,Label:Ie((x=t.trueLabel)!==null&&x!==void 0?x:"Yes",r)},FalseOption:{Value:0,Label:Ie((F=t.falseLabel)!==null&&F!==void 0?F:"No",r)}}};case"dateTime":return{"@odata.type":"Microsoft.Dynamics.CRM.DateTimeAttributeMetadata",AttributeType:"DateTime",AttributeTypeName:{Value:"DateTimeType"},Format:(q=t.dateFormat)!==null&&q!==void 0?q:"DateAndTime"};case"choice":return Kh(t,r,!1);case"multiChoice":return Kh(t,r,!0);case"file":return{"@odata.type":"Microsoft.Dynamics.CRM.FileAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"FileType"},MaxSizeInKB:(G=t.maxSizeKb)!==null&&G!==void 0?G:10240};case"image":return{"@odata.type":"Microsoft.Dynamics.CRM.ImageAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"ImageType"},IsPrimaryImage:(M=t.isPrimaryImage)!==null&&M!==void 0?M:!1,MaxSizeInKB:(U=t.maxSizeKb)!==null&&U!==void 0?U:10240};case"autonumber":return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},FormatName:{Value:"Text"},MaxLength:(B=t.maxLength)!==null&&B!==void 0?B:100,AutoNumberFormat:(W=t.autoNumberFormat)!==null&&W!==void 0?W:""};default:throw new Oe.InvalidArgumentError(`unsupported column type '${String(e)}'`)}}function Kh(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,H.normalizeGuid)(e.globalChoiceMetadataId,"globalChoiceMetadataId")})`,i;if(!e.options||e.options.length===0)throw new Oe.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:Ie(a.label,t)}))},i}var zc=new WeakMap;async function PR(e,t){var r,n;let i=(r=zc.get(e))===null||r===void 0?void 0:r.get(t);if(i)return i;let a=`/EntityDefinitions(LogicalName='${(0,H.odataLiteral)(t)}')${(0,H.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 Oe.InvalidArgumentError(`could not resolve EntitySetName for '${t}'`);(0,H.assertODataName)(s,`server-derived EntitySetName for '${t}'`);let l=zc.get(e);return l||(l=new Map,zc.set(e,l)),l.set(t,s),s}J.resolveEntitySetName=PR;async function TR(e,t){var r,n,i,a,o,s,l,u,c,d,p,m,h,w,y;let N=(r=t.languageCode)!==null&&r!==void 0?r:lr.DEFAULT_LCID,D=jc(t.schemaName),x=(n=t.primaryColumnSchemaName)!==null&&n!==void 0?n:`${D}_Name`,F={"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},SchemaName:x,RequiredLevel:qa("None"),MaxLength:(i=t.primaryColumnMaxLength)!==null&&i!==void 0?i:100,FormatName:{Value:"Text"},DisplayName:Ie((a=t.primaryColumnDisplayName)!==null&&a!==void 0?a:"Name",N),IsPrimaryName:!0};t.primaryColumnAutoNumberFormat&&(F.AutoNumberFormat=t.primaryColumnAutoNumberFormat),t.columns&&tg(t.columns,"createTable");let q={"@odata.type":"Microsoft.Dynamics.CRM.EntityMetadata",SchemaName:t.schemaName,DisplayName:Ie(t.displayName,N),DisplayCollectionName:Ie((o=t.pluralName)!==null&&o!==void 0?o:`${t.displayName}s`,N),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:[F,...((c=t.columns)!==null&&c!==void 0?c:[]).map($e=>Hc($e,N))]};t.description&&(q.Description=Ie(t.description,N));let G="/EntityDefinitions",M=(0,re.ensureSuccess)(await e.post(G,q),e.apiUrl(G)),U=Va(M),B=`/EntityDefinitions(${U})`+(0,H.odataQuery)([["$select","LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute"]]),W=Math.max(1,Math.trunc((d=t.readBackAttempts)!==null&&d!==void 0?d:6)),$=Math.max(0,(p=t.readBackDelayMs)!==null&&p!==void 0?p:1e3),Ae;for(let $e=1;$e<=W;$e+=1){let Je=await e.get(B);if(Je.status>=200&&Je.status<300){Ae=Je;break}Je.status!==404&&(0,re.ensureSuccess)(Je,e.apiUrl(B)),$e<W&&$>0&&await new Promise(ce=>setTimeout(ce,$))}if(!Ae)throw new Oe.SdkError("TABLE_METADATA_NOT_VISIBLE",`Table '${t.schemaName}' WAS CREATED (MetadataId ${U}) but its metadata was still not readable after ${W} attempt(s). Do NOT re-run the create \u2014 it will collide on the schema name. Re-read /EntityDefinitions(${U}) once the environment catches up, or raise 'readBackAttempts'.`);let he=Ae.body;return{logicalName:(m=he.LogicalName)!==null&&m!==void 0?m:t.schemaName.toLowerCase(),metadataId:U,entitySetName:(h=he.EntitySetName)!==null&&h!==void 0?h:"",primaryIdAttribute:(w=he.PrimaryIdAttribute)!==null&&w!==void 0?w:`${t.schemaName.toLowerCase()}id`,primaryNameAttribute:(y=he.PrimaryNameAttribute)!==null&&y!==void 0?y:x.toLowerCase()}}J.createTable=TR;function Hc(e,t){var r,n;let i=(r=e.languageCode)!==null&&r!==void 0?r:t,a={..._R(e.type,e,i),SchemaName:e.schemaName,RequiredLevel:qa((n=e.required)!==null&&n!==void 0?n:"None"),DisplayName:Ie(e.displayName,i)};return e.description&&(a.Description=Ie(e.description,i)),e.sourceType&&e.sourceType!=="Simple"&&(a.SourceType=e.sourceType==="Rollup"?2:1,e.formulaDefinition&&(a.FormulaDefinition=e.formulaDefinition)),Zh(a,e),a}function Zh(e,t){t.isValidForCreate!==void 0&&(e.IsValidForCreate=t.isValidForCreate),t.isValidForUpdate!==void 0&&(e.IsValidForUpdate=t.isValidForUpdate),t.isValidForRead!==void 0&&(e.IsValidForRead=t.isValidForRead)}async function OR(e,t,r){var n;let i=Hc(r,(n=r.languageCode)!==null&&n!==void 0?n:lr.DEFAULT_LCID),a=`/EntityDefinitions(LogicalName='${(0,H.odataLiteral)(t)}')/Attributes`,o=(0,re.ensureSuccess)(await e.post(a,i),e.apiUrl(a)),s={logicalName:r.schemaName.toLowerCase(),metadataId:Va(o)};if(r.visualization&&r.visualization!=="None")try{await ig(e,t,s.logicalName,s.metadataId,r.visualization)}catch(l){let u=new Oe.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}J.createColumn=OR;var mi="/controlconfigurations",eg="CustomRenderersConfiguration",Wc={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 tg(e,t){let r=e.find(n=>n.visualization&&n.visualization!=="None");if(r)throw new Oe.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 rg(e){return JSON.stringify({type:Wc[e]})}function RR(e){if(!e)return"None";let t;try{t=JSON.parse(e)}catch{return"None"}let r=t?.type,n=Object.keys(Wc).find(i=>Wc[i]===r);return n??"None"}async function ng(e,t,r){var n,i;let a=`entitylogicalname eq '${(0,H.odataLiteral)(t)}' and Attribute/logicalname eq '${(0,H.odataLiteral)(r)}'`,o=`${mi}${(0,H.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 xR(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,H.odataLiteral)(t)}')/Attributes(LogicalName='${(0,H.odataLiteral)(r)}')${(0,H.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 Oe.InvalidArgumentError(`cannot resolve column '${r}' on '${t}' to set its visualization`);return(0,H.normalizeGuid)(o,"MetadataId")}async function ig(e,t,r,n,i){let a={name:eg,uniquename:`msdyn_${t}_${r}_customrenderers`,metadatajson:rg(i),"[email protected]":`/attributes(${(0,H.normalizeGuid)(n,"MetadataId")})`,entitylogicalname:t};(0,re.ensureSuccess)(await e.post(mi,a),e.apiUrl(mi))}async function FR(e,t,r){var n;let i=await ng(e,t,r);return RR((n=i[0])===null||n===void 0?void 0:n.metadatajson)}J.getColumnVisualization=FR;async function LR(e,t,r,n){let a=(await ng(e,t,r)).map(u=>u.controlconfigurationid).filter(u=>!!u);if(n==="None"){for(let u of a){let c=`${mi}(${(0,H.normalizeGuid)(u,"controlconfigurationid")})`;(0,re.ensureSuccess)(await e.delete(c),e.apiUrl(c))}return}let[o,...s]=a,l=await xR(e,t,r);if(o){let u=`${mi}(${(0,H.normalizeGuid)(o,"controlconfigurationid")})`,c={name:eg,metadatajson:rg(n),"[email protected]":`/attributes(${l})`,entitylogicalname:t};(0,re.ensureSuccess)(await e.patch(u,c),e.apiUrl(u))}else await ig(e,t,r,l,n);for(let u of s){let c=`${mi}(${(0,H.normalizeGuid)(u,"controlconfigurationid")})`;(0,re.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}J.setColumnVisualization=LR;async function kR(e,t,r){if(r.length===0)return;if(tg(r,"createColumns"),!e.supportsAtomicBatch)throw new Oe.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,H.odataLiteral)(t)}')/Attributes`;await(0,DR.postChangeSet)(e,r.map(i=>{var a;return{method:"POST",path:n,body:Hc(i,(a=i.languageCode)!==null&&a!==void 0?a:lr.DEFAULT_LCID)}}),`${r.length} column(s) on '${t}'`)}J.createColumns=kR;async function MR(e,t,r){var n,i,a,o;let s=(n=r.languageCode)!==null&&n!==void 0?n:lr.DEFAULT_LCID,l=jc(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:Ie(r.displayName,s),RequiredLevel:qa((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:""}}J.createCustomerColumn=MR;async function UR(e,t,r){var n,i,a,o,s;let l=(n=r.languageCode)!==null&&n!==void 0?n:lr.DEFAULT_LCID,u={EntityLogicalName:t,AttributeLogicalName:"statuscode",Label:Ie(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)}J.insertStatusValue=UR;async function BR(e,t){var r,n,i,a,o;let s=(r=t.languageCode)!==null&&r!==void 0?r:lr.DEFAULT_LCID,l,u;if(t.type==="OneToMany"){if(!t.referencedEntity||!t.referencingEntity)throw new Oe.InvalidArgumentError("OneToMany relationship requires referencedEntity and referencingEntity");let p=(n=t.lookupSchemaName)!==null&&n!==void 0?n:`${jc(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:qa((i=t.lookupRequired)!==null&&i!==void 0?i:"None"),DisplayName:Ie((a=t.lookupDisplayName)!==null&&a!==void 0?a:t.referencedEntity,s)}}}else{if(!t.entity1||!t.entity2)throw new Oe.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:Va(d),lookupLogicalName:u}}J.createRelationship=BR;async function $R(e,t){let r=`/EntityDefinitions(LogicalName='${(0,H.odataLiteral)(t)}')`;(0,re.ensureSuccess)(await e.delete(r),e.apiUrl(r))}J.deleteTable=$R;async function qR(e,t,r,n){var i,a;let o=(i=n.languageCode)!==null&&i!==void 0?i:lr.DEFAULT_LCID,s=`/EntityDefinitions(LogicalName='${(0,H.odataLiteral)(t)}')/Attributes`,l=`${s}(LogicalName='${(0,H.odataLiteral)(r)}')${(0,H.odataQuery)([["$select","MetadataId,AttributeType"]])}`,c=(0,re.ensureSuccess)(await e.get(l),e.apiUrl(l)).body,d=IR[(a=c.AttributeType)!==null&&a!==void 0?a:""];if(!c.MetadataId||!d)throw new Oe.InvalidArgumentError(`cannot update column '${r}' on '${t}' (type '${c.AttributeType}' not supported)`);let p=(0,H.normalizeGuid)(c.MetadataId,"MetadataId"),m=`${s}(${p})/${d}`,h=(0,re.ensureSuccess)(await e.get(m),e.apiUrl(m)).body;for(let y of Object.keys(h))y.startsWith("@odata.")&&delete h[y];if(h["@odata.type"]=d,n.displayName!==void 0&&(h.DisplayName=Ie(n.displayName,o)),n.description!==void 0&&(h.Description=Ie(n.description,o)),n.required!==void 0&&(h.RequiredLevel=qa(n.required)),n.maxLength!==void 0&&(h.MaxLength=n.maxLength),n.autoNumberFormat!==void 0&&(h.AutoNumberFormat=n.autoNumberFormat),n.defaultValue!==void 0&&c.AttributeType!=="Boolean")throw new Oe.InvalidArgumentError(`updateColumn: 'defaultValue' applies to Boolean columns, but '${r}' on '${t}' is of type '${c.AttributeType}'.`);if(n.integerFormat!==void 0&&c.AttributeType!=="Integer")throw new Oe.InvalidArgumentError(`updateColumn: 'integerFormat' applies to Integer columns, but '${r}' on '${t}' is of type '${c.AttributeType}'.`);n.defaultValue!==void 0&&(h.DefaultValue=n.defaultValue),n.integerFormat!==void 0&&(h.Format=n.integerFormat),Zh(h,n);let w=`${s}(${p})`;(0,re.ensureSuccess)(await e.put(w,h,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(w))}J.updateColumn=qR;async function VR(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,H.odataLiteral)(t)}')/Attributes`,a=`${i}(LogicalName='${(0,H.odataLiteral)(r)}')${(0,H.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 Oe.InvalidArgumentError(`column '${r}' not found on '${t}'`);let l=`${i}(${(0,H.normalizeGuid)(s,"MetadataId")})`;(0,re.ensureSuccess)(await e.delete(l),e.apiUrl(l))}J.deleteColumn=VR;async function GR(e,t){var r,n,i;let a=`/RelationshipDefinitions${(0,H.odataQuery)([["$filter",`SchemaName eq '${(0,H.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 Oe.InvalidArgumentError(`relationship '${t}' not found`);let l=`/RelationshipDefinitions(${(0,H.normalizeGuid)(s,"MetadataId")})`;(0,re.ensureSuccess)(await e.delete(l),e.apiUrl(l))}J.deleteRelationship=GR;async function Yh(e,t){var r;let n=`/GlobalOptionSetDefinitions(Name='${(0,H.odataPathLiteral)(t)}')${(0,H.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,H.normalizeGuid)(o,"MetadataId"):void 0}async function zR(e,t){var r;let n=t.name.toLowerCase(),i=await Yh(e,n);if(i)return{name:n,metadataId:i};let a=(r=t.languageCode)!==null&&r!==void 0?r:lr.DEFAULT_LCID,o={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",Name:n,DisplayName:Ie(t.displayName,a),IsGlobal:!0,OptionSetType:"Picklist",Options:t.options.map(l=>({Value:l.value,Label:Ie(l.label,a)}))};t.description&&(o.Description=Ie(t.description,a));let s="/GlobalOptionSetDefinitions";try{let l=(0,re.ensureSuccess)(await e.post(s,o),e.apiUrl(s));return{name:n,metadataId:Va(l)}}catch(l){let u;try{u=await Yh(e,n)}catch{u=void 0}if(u)return{name:n,metadataId:u};throw l}}J.createGlobalOptionSet=zR;async function WR(e,t){let r=`/GlobalOptionSetDefinitions(Name='${(0,H.odataLiteral)(t.toLowerCase())}')`;(0,re.ensureSuccess)(await e.delete(r),e.apiUrl(r))}J.deleteGlobalOptionSet=WR;async function jR(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:lr.DEFAULT_LCID,a={"@odata.type":"Microsoft.Dynamics.CRM.EntityKeyMetadata",SchemaName:r.schemaName,DisplayName:Ie(r.displayName,i),KeyAttributes:r.keyAttributes},o=`/EntityDefinitions(LogicalName='${(0,H.odataLiteral)(t)}')/Keys`,s=(0,re.ensureSuccess)(await e.post(o,a),e.apiUrl(o));return{logicalName:r.schemaName.toLowerCase(),metadataId:Va(s)}}J.createAlternateKey=jR;async function HR(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,H.odataLiteral)(t)}')/Keys`,a=`${i}(LogicalName='${(0,H.odataLiteral)(r.toLowerCase())}')${(0,H.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 Oe.InvalidArgumentError(`alternate key '${r}' not found on '${t}'`);let l=`${i}(${(0,H.normalizeGuid)(s,"MetadataId")})`;(0,re.ensureSuccess)(await e.delete(l),e.apiUrl(l))}J.deleteAlternateKey=HR;async function QR(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:lr.DEFAULT_LCID,a=`/EntityDefinitions(LogicalName='${(0,H.odataLiteral)(t)}')`,s=(0,re.ensureSuccess)(await e.get(a),e.apiUrl(a)).body,l=s.MetadataId;if(!l)throw new Oe.InvalidArgumentError(`table '${t}' not found`);let u=(0,H.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=Ie(r.displayName,i)),r.pluralName!==void 0&&(s.DisplayCollectionName=Ie(r.pluralName,i)),r.description!==void 0&&(s.Description=Ie(r.description,i)),r.auditEnabled!==void 0&&Xh(s,"IsAuditEnabled",r.auditEnabled),r.duplicateDetectionEnabled!==void 0&&Xh(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))}J.updateTable=QR});var Jt=g(hi=>{"use strict";Object.defineProperty(hi,"__esModule",{value:!0});hi.describeMalformedValue=hi.collectPages=void 0;var ag=ge(),Qc=ne();async function JR(e,t,r){let n=[],i=new Set,a=e.apiUrl(t),o=(0,ag.ensureSuccess)(await e.get(t),a);for(;;){let s=o.body,l=s?.value;if(!Array.isArray(l))throw new Qc.ConnectionError(a,o.status,`${r}: paginated read returned a malformed page \u2014 expected an OData 'value' array but got ${Jc(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 Qc.ConnectionError(a,o.status,`${r}: paginated read returned a malformed @odata.nextLink (${Jc(u)}); cannot follow it, and refusing to return partial results.`);if(i.has(u))throw new Qc.InvalidArgumentError(`${r}: aborting pagination \u2014 the server returned a repeated @odata.nextLink ('${u}'), which would loop indefinitely.`);i.add(u),a=u,o=(0,ag.ensureSuccess)(await e.getAbsolute(u),u)}return n}hi.collectPages=JR;function Jc(e){return e===null?"null":e===void 0?"undefined (missing)":`a ${typeof e}`}hi.describeMalformedValue=Jc});var on=g(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.rebuildRaw=gt.assembleChildren=gt.spliceChildren=gt.mergeAttrs=gt.rawFromNode=gt.emptyBag=void 0;var an=ne(),og=1e6,Ns=512;function XR(){return{a:[],c:[]}}gt.emptyBag=XR;function sg(e,t=0){if(t>Ns)throw new an.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${Ns}`);return{n:e.getNodeName(),a:e.getAllProperties().map(r=>[r.key,r.value]),c:e.getAllChildren().map(r=>sg(r,t+1))}}gt.rawFromNode=sg;function KR(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}gt.mergeAttrs=KR;function Ss(e,t){let r=new Set;for(let s of e){let l=s.i;if(!Number.isInteger(l)||l<0||l>og)throw new an.InvalidArgumentError(`Bag child index must be an integer in [0, ${og}] (got ${String(l)})`);if(r.has(l))throw new an.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}gt.spliceChildren=Ss;function YR(e,t){if(e.w){let r={n:e.w.n,a:e.w.a.map(n=>[n[0],n[1]]),c:Ss(e.w.c,t)};return Ss(e.c,[r])}return Ss(e.c,t)}gt.assembleChildren=YR;function lg(e,t,r,n=0){if(n>Ns)throw new an.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${Ns}`);ZR(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,lg(a,t,i,n+1));return i}gt.rebuildRaw=lg;function ZR(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new an.InvalidArgumentError(`Malformed hybrid node at depth ${t}: expected a JSON object`);let r=e;if(typeof r.n!="string")throw new an.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 an.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 an.InvalidArgumentError(`Malformed hybrid node '${r.n}': each attribute must be a [string, string] pair`)}});var kn=g(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.projectElementBag=_e.serializeNode=_e.domEngine=_e.nodeLikeFromDom=_e.parseXmlRoot=_e.EMPTY_FORM_SENTINEL=_e.TEXT_SENTINEL=void 0;var ex=on(),Ga=ne();_e.TEXT_SENTINEL="#text";_e.EMPTY_FORM_SENTINEL="#empty";var Ds=new WeakSet;function tx(e,t){let r=e&&e.trim()!==""?e:t,i=new DOMParser().parseFromString(r,"text/xml").documentElement;if(!i)throw new Ga.InvalidArgumentError("XML source has no root element (empty or malformed input)");return nx(i),ix(i),sx(i,r),i}_e.parseXmlRoot=tx;var rx=new Set([1,3]);function nx(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(!rx.has(a.nodeType))throw new Ga.InvalidArgumentError(`Unsupported XML node type ${a.nodeType} (CDATA / comment / processing-instruction) is outside the hybrid projection's lossless grammar and cannot be round-tripped`);a.nodeType===1&&t.push(a)}}}function ix(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 Ga.InvalidArgumentError(`Unsupported document-level XML node (type ${o.nodeType}: declaration / comment / processing-instruction outside the root element) cannot be round-tripped`)}}function ax(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 ox(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 cg(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 sx(e,t){let r=ax(t),n=ox(e),i=Math.min(r.length,n.length);for(let a=0;a<i;a+=1){if(r[a])continue;let o=n[a];cg(o)||Ds.add(o)}}function Xc(e){let t=e.nodeType===3;return{getNodeName:()=>t?_e.TEXT_SENTINEL:e.tagName,getAllProperties:()=>{var r;if(t)return[{key:_e.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 Ds.has(e)&&!cg(e)&&i.push({key:_e.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(Xc(a))}return r}}}_e.nodeLikeFromDom=Xc;function lx(e){return{make:t=>t===_e.TEXT_SENTINEL?e.createTextNode(""):e.createElement(t),setProp:(t,r,n)=>{t.nodeType===3?t.nodeValue=n:r===_e.EMPTY_FORM_SENTINEL?Ds.add(t):t.setAttribute(r,n)},addChild:(t,r)=>{t.appendChild(r)}}}_e.domEngine=lx;function dg(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 Es(r);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))throw Es(r);t+=1;continue}if(r>=56320&&r<=57343)throw Es(r)}}function Es(e){let t=e.toString(16).toUpperCase().padStart(4,"0");return new Ga.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 ux(e){return dg(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/\r/g,"
").replace(/\n/g,"
").replace(/\t/g,"	")}function cx(e){return dg(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function dx(e){return pg(e,0)}_e.serializeNode=dx;var ug=512;function pg(e,t){var r;if(t>ug)throw new Ga.InvalidArgumentError(`XML nesting exceeds the maximum supported depth of ${ug}`);if(e.nodeType===3)return cx((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+'="'+ux(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 Ds.has(n)?i+"></"+n.tagName+">":i+" />";i+=">";for(let l of o)i+=pg(l,t+1);return i+"</"+n.tagName+">"}function px(e){let t=Xc(e);return{a:t.getAllProperties().map(r=>[r.key,r.value]),c:t.getAllChildren().map((r,n)=>({i:n,node:(0,ex.rawFromNode)(r)}))}}_e.projectElementBag=px});var Zc=g(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.getFormSecurityRoles=sn.setFormSecurityRoles=sn.formApi=void 0;var fx=Jt(),de=ge(),Rt=Z(),gi=ne(),Kc=kn(),mx="formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber",hx="formid,name,type,objecttypecode",gx=2;sn.formApi={async get(e,t){let n=`/systemforms(${(0,Rt.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Rt.odataQuery)([["$select",mx]]),i=(0,de.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,de.readEtag)(i)}},async list(e,t){let r=[`type eq ${gx}`];t?.entityLogicalName&&r.push(`objecttypecode eq '${(0,Rt.odataLiteral)(t.entityLogicalName)}'`);let n=`/systemforms${(0,Rt.odataQuery)([["$select",hx],["$filter",r.join(" and ")]])}`;return(await(0,fx.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,de.echoWrite)("formid"),i=`/systemforms${n.query}`,a=(0,de.ensureSuccess)(await e.post(i,(0,de.withClientMintedId)(t,"formid",r),n.options),e.apiUrl(i));return{id:(0,de.resolveCreatedId)(a,"formid","form",r),etag:(0,de.readEtag)(a)}},async update(e,t,r,n){let i=(0,Rt.normalizeGuid)(t,"id");await hg(e,i,mg(i),n);let a=await fg(e,i),o=(0,de.echoWrite)("formid",{"If-Match":(0,de.requireEtag)(a,"form",i)}),s=`/systemforms(${i})${o.query}`;return(0,de.ensureSuccess)(await e.patch(s,r,o.options),e.apiUrl(s)),{id:i,etag:await bx(e,i)}},delete(e,t){return(0,de.deleteRecord)(e,"systemforms",t)}};var Yc="DisplayConditions";async function vx(e,t,r){var n,i,a,o,s;if(r.everyone&&r.roleIds&&r.roleIds.length>0)throw new gi.InvalidArgumentError("setFormSecurityRoles: `everyone` and `roleIds` are mutually exclusive \u2014 the platform models <Everyone /> as a replacement for the <Role> list, not an addition to it.");let l=(0,Rt.normalizeGuid)(t,"formId"),u=`/systemforms(${l})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Rt.odataQuery)([["$select","formid,formxml"]]),c=(0,de.ensureSuccess)(await e.get(u),e.apiUrl(u)),d=(0,de.readEtag)(c),p=c.body,m=p?.formxml;if(!m)throw new gi.InvalidArgumentError(`form '${l}' returned no formxml, so its roles cannot be set`);let h=(0,Kc.parseXmlRoot)(m,"<form/>"),w=h.ownerDocument;if(!w)throw new gi.InvalidArgumentError(`form '${l}' produced no owner document`);let y=gg(h,Yc),N=(n=y?.getAttribute("Order"))!==null&&n!==void 0?n:void 0,D=(i=y?.getAttribute("FallbackForm"))!==null&&i!==void 0?i:void 0;y&&h.removeChild(y);let x=!!r.everyone||((o=(a=r.roleIds)===null||a===void 0?void 0:a.length)!==null&&o!==void 0?o:0)>0;if(!x&&(r.order!==void 0||r.fallbackForm!==void 0)){if(!y)throw new gi.InvalidArgumentError("setFormSecurityRoles: `order`/`fallbackForm` were supplied without `roleIds` or `everyone`, but this form has no <DisplayConditions> to attach them to. Pass the roles as well.");r.order!==void 0&&y.setAttribute("Order",String(r.order)),r.fallbackForm!==void 0&&y.setAttribute("FallbackForm",String(r.fallbackForm)),h.appendChild(y)}else if(x){let U=w.createElement(Yc),B=r.order!==void 0?String(r.order):N;B!==void 0&&U.setAttribute("Order",B);let W=r.fallbackForm!==void 0?String(r.fallbackForm):D??"false";if(U.setAttribute("FallbackForm",W),r.everyone)U.appendChild(w.createElement("Everyone"));else for(let $ of(s=r.roleIds)!==null&&s!==void 0?s:[]){let Ae=w.createElement("Role");Ae.setAttribute("Id",`{${(0,Rt.normalizeGuid)($,"roleId")}}`),U.appendChild(Ae)}h.appendChild(U)}let q=(0,Kc.serializeNode)(h);await hg(e,l,u,d);let G=await fg(e,l),M=`/systemforms(${l})`;(0,de.ensureSuccess)(await e.patch(M,{formxml:q},{headers:{"Content-Type":"application/json","If-Match":(0,de.requireEtag)(G,"form",l)}}),e.apiUrl(M))}sn.setFormSecurityRoles=vx;async function fg(e,t){let r=`/systemforms(${t})${(0,Rt.odataQuery)([["$select","formid"]])}`;return(0,de.readEtag)((0,de.ensureSuccess)(await e.get(r),e.apiUrl(r)))}function mg(e){return`/systemforms(${e})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Rt.odataQuery)([["$select","formid"]])}async function bx(e,t){let r=mg(t);return(0,de.readEtag)((0,de.ensureSuccess)(await e.get(r),e.apiUrl(r)))}async function hg(e,t,r,n){(0,de.requireEtag)(n,"form",t);let i=(0,de.readEtag)((0,de.ensureSuccess)(await e.get(r),e.apiUrl(r)));if(i===null)throw new gi.SdkError(de.VERSION_CONFLICT_CODE,`Refusing to write form '${t}': its current version could not be read, so the write could not be verified as conditional and would risk silently overwriting a concurrent edit.`);if(i!==n)throw new gi.SdkError(de.VERSION_CONFLICT_CODE,`Version conflict writing form '${t}': its formxml changed on the server since it was read (held ${n}, server ${i}). Re-fetch the form and re-apply the change.`)}function gg(e,t){let r=e.childNodes;for(let n=0;n<r.length;n+=1){let i=r[n];if(i.nodeType===1&&i.tagName===t)return i}}async function yx(e,t){var r,n;let a=`/systemforms(${(0,Rt.normalizeGuid)(t,"formId")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Rt.odataQuery)([["$select","formid,formxml"]]),s=(r=(0,de.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||r===void 0?void 0:r.formxml;if(!s)return;let l=(0,Kc.parseXmlRoot)(s,"<form/>"),u=gg(l,Yc);if(!u)return;let c=[],d=!1,p=u.childNodes;for(let h=0;h<p.length;h+=1){let w=p[h];if(w.nodeType!==1)continue;let y=w;if(y.tagName==="Everyone")d=!0;else if(y.tagName==="Role"){let N=(n=y.getAttribute("Id"))!==null&&n!==void 0?n:"";N&&c.push(N.replace(/[{}]/g,"").toLowerCase())}}let m=u.getAttribute("Order");return{...d?{everyone:!0}:{},...c.length>0?{roleIds:c}:{},fallbackForm:u.getAttribute("FallbackForm")==="true",...m!==null&&m!==""?{order:Number(m)}:{}}}sn.getFormSecurityRoles=yx});var Ps=g(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.disassociateRecords=Se.associateRecords=Se.createRecordsBulk=Se.upsertRecord=Se.queryAllRecords=Se.queryRecords=Se.getRecord=Se.deleteRecord=Se.updateRecord=Se.createRecord=void 0;var wx=Jt(),Xt=ge(),tt=Z(),Is=ne(),ur=Cs();function _s(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 Ax(e,t,r){let i=`/${await(0,ur.resolveEntitySetName)(e,t)}`,a=(0,Xt.ensureSuccess)(await e.post(i,_s(r)),e.apiUrl(i)),o=(0,Xt.readCreatedId)(a,`${t}id`);if(!o)throw new Is.InvalidArgumentError(`Dataverse did not return an id for the created '${t}' row`);return{id:o,entityType:t}}Se.createRecord=Ax;async function Cx(e,t,r,n){let i=(0,tt.normalizeGuid)(r,"id"),o=`/${await(0,ur.resolveEntitySetName)(e,t)}(${i})`;(0,Xt.ensureSuccess)(await e.patch(o,_s(n)),e.apiUrl(o))}Se.updateRecord=Cx;async function Sx(e,t,r){let n=(0,tt.normalizeGuid)(r,"id"),a=`/${await(0,ur.resolveEntitySetName)(e,t)}(${n})`;(0,Xt.ensureSuccess)(await e.delete(a),e.apiUrl(a))}Se.deleteRecord=Sx;async function Nx(e,t,r,n){var i;let a=(0,tt.normalizeGuid)(r,"id"),o=await(0,ur.resolveEntitySetName)(e,t),s=(0,tt.odataQuery)([["$select",n&&n.length>0?n.join(","):void 0]]),l=`/${o}(${a})${s}`;return(i=(0,Xt.ensureSuccess)(await e.get(l),e.apiUrl(l)).body)!==null&&i!==void 0?i:{}}Se.getRecord=Nx;function Ex(e){return e?.fetchXml?(0,tt.odataQuery)([["fetchXml",e.fetchXml]]):(0,tt.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 vg(e,t,r){var n,i;if(r?.paginate){if(r.top!==void 0)throw new Is.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 Is.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,ur.resolveEntitySetName)(e,t)}${Ex(r)}`;return r?.paginate?(0,wx.collectPages)(e,o,"queryRecords"):(i=(n=(0,Xt.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]}Se.queryRecords=vg;async function Dx(e,t,r){return vg(e,t,{...r,paginate:!0})}Se.queryAllRecords=Dx;function Ix(e){if("id"in e)return`(${(0,tt.normalizeGuid)(e.id,"id")})`;let t=typeof e.value=="string"?`'${(0,tt.odataPathLiteral)(e.value)}'`:e.value;return`(${(0,tt.assertODataName)(e.key,"alternate key name")}=${t})`}async function _x(e,t,r,n){let i=Ix(r),o=`/${await(0,ur.resolveEntitySetName)(e,t)}${i}`,s=(0,Xt.ensureSuccess)(await e.patch(o,_s(n)),e.apiUrl(o)),l=s.status===201,u=(0,Xt.readCreatedId)(s,`${t}id`);return{id:u??("id"in r?(0,tt.normalizeGuid)(r.id,"id"):""),created:l}}Se.upsertRecord=_x;async function Px(e,t,r){var n,i;if(r.length===0)return[];let a=await(0,ur.resolveEntitySetName)(e,t),o=r.map(c=>({"@odata.type":`Microsoft.Dynamics.CRM.${t}`,..._s(c)})),s=`/${a}/Microsoft.Dynamics.CRM.CreateMultiple`,u=(i=(n=(0,Xt.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 Is.InvalidArgumentError(`CreateMultiple on '${t}' returned ${u.length} id(s) for ${r.length} row(s)`);return u}Se.createRecordsBulk=Px;async function Tx(e,t,r,n){let i=(0,tt.normalizeGuid)(r,"id"),a=(0,tt.normalizeGuid)(n.targetId,"targetId"),o=await(0,ur.resolveEntitySetName)(e,t),s=await(0,ur.resolveEntitySetName)(e,n.targetEntity),l=(0,tt.assertODataName)(n.relationshipName,"relationshipName"),u=`/${o}(${i})/${l}/$ref`,c={"@odata.id":e.apiUrl(`/${s}(${a})`)};(0,Xt.ensureSuccess)(await e.post(u,c),e.apiUrl(u))}Se.associateRecords=Tx;async function Ox(e,t,r,n,i){let a=(0,tt.normalizeGuid)(r,"id"),o=(0,tt.normalizeGuid)(i,"targetId"),s=await(0,ur.resolveEntitySetName)(e,t),l=(0,tt.assertODataName)(n,"relationshipName"),u=`/${s}(${a})/${l}(${o})/$ref`;(0,Xt.ensureSuccess)(await e.delete(u),e.apiUrl(u))}Se.disassociateRecords=Ox});var Kt=g(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.publishBoundEntity=qe.boundEntityPublishScope=qe.publishGenPageById=qe.publishDashboardById=qe.publishWebResourceById=qe.publishEntity=qe.publishAppModule=qe.publishXml=void 0;var Rx=ge(),za=Z(),bg="/PublishXml";async function vi(e,t){(0,Rx.ensureSuccess)(await e.post(bg,{ParameterXml:t}),e.apiUrl(bg))}qe.publishXml=vi;function xx(e,t){return vi(e,`<importexportxml><appmodules><appmodule>${(0,za.xmlText)(t)}</appmodule></appmodules></importexportxml>`)}qe.publishAppModule=xx;function yg(e,t){return vi(e,`<importexportxml><entities><entity>${(0,za.xmlText)(t)}</entity></entities></importexportxml>`)}qe.publishEntity=yg;function Fx(e,t){return vi(e,`<importexportxml><webresources><webresource>${(0,za.xmlText)(t)}</webresource></webresources></importexportxml>`)}qe.publishWebResourceById=Fx;function Lx(e,t){return vi(e,`<importexportxml><dashboards><dashboard>${(0,za.xmlText)(t)}</dashboard></dashboards></importexportxml>`)}qe.publishDashboardById=Lx;function kx(e,t){return vi(e,`<importexportxml><uxagentprojects><uxagentproject>${(0,za.xmlText)(t)}</uxagentproject></uxagentprojects></importexportxml>`)}qe.publishGenPageById=kx;function Mx(e){let t=e?.entityLogicalName;return t?{envelope:"entity",entityLogicalName:t,blastRadiusWarning:"ENTITY_ENVELOPE_ALSO_SHIPS_UNRELATED_UNPUBLISHED_CHANGES"}:{envelope:"entity"}}qe.boundEntityPublishScope=Mx;function Ux(e,t){let r=t?.entityLogicalName;return r?yg(e,r):Promise.resolve()}qe.publishBoundEntity=Ux});var Cg=g(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.deleteWebResource=cr.getWebResource=cr.updateWebResource=cr.createWebResource=void 0;var Bx=Kt(),Wa=ge(),Ts=Z(),ed=ne(),$x={html:1,css:2,js:3,xml:4,png:5,jpg:6,gif:7,xsl:9,ico:10,svg:11,resx:12};function qx(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 wg(e){if(e.contentBase64!==void 0)return e.contentBase64;if(e.content!==void 0)return qx(e.content)}async function Ag(e,t){return(0,Bx.publishWebResourceById)(e,t)}async function Vx(e,t){var r;let n=wg(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:$x[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 Ag(e,o),{id:o,name:t.name}}cr.createWebResource=Vx;async function Gx(e,t,r){let n=(0,Ts.normalizeGuid)(t,"id"),i={},a=wg(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 Ag(e,n)}cr.updateWebResource=Gx;async function zx(e,t){var r;let i=`/webresourceset(${(0,Ts.normalizeGuid)(t,"id")})${(0,Ts.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:{}}cr.getWebResource=zx;async function Wx(e,t){let n=`/webresourceset(${(0,Ts.normalizeGuid)(t,"id")})`;(0,Wa.ensureSuccess)(await e.delete(n),e.apiUrl(n))}cr.deleteWebResource=Wx});var Os=g(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.applyAppSettings=Ve.setAppSetting=Ve.readAppSettings=Ve.resolveSettingDefinitions=Ve.APP_SETTING_UNSET=Ve.APP_SETTING_OFF=Ve.APP_SETTING_ON=Ve.HEADER_AND_NAVIGATION_REFRESH=void 0;var bi=ge(),Fr=Z();Ve.HEADER_AND_NAVIGATION_REFRESH="HeaderAndNavigationRefresh";Ve.APP_SETTING_ON="2";Ve.APP_SETTING_OFF="1";Ve.APP_SETTING_UNSET="0";function Eg(e,t){return"/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Fr.odataQuery)([["$select",e],["$filter",t]])}async function Dg(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,Fr.odataLiteral)(c)}'`).join(" or "),s=`/settingdefinitions${(0,Fr.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",o]])}`,u=((n=(r=(0,bi.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}Ve.resolveSettingDefinitions=Dg;async function jx(e,t){var r,n,i,a;let o=(0,Fr.normalizeGuid)(t,"App id"),s=Eg("appsettingid,value,_settingdefinitionid_value",`_parentappmoduleid_value eq ${o}`),u=((n=(r=(0,bi.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(w=>`settingdefinitionid eq ${(0,Fr.normalizeGuid)(w,"Setting definition id")}`).join(" or "),m=`/settingdefinitions${(0,Fr.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",p]])}`,h=(0,bi.ensureSuccess)(await e.get(m),e.apiUrl(m));for(let w of((a=(i=h.body)===null||i===void 0?void 0:i.value)!==null&&a!==void 0?a:[]).filter(Boolean))w.settingdefinitionid&&d.set(w.settingdefinitionid.toLowerCase(),w)}return u.map(p=>{var m,h,w,y,N;let D=d.get(((m=p._settingdefinitionid_value)!==null&&m!==void 0?m:"").toLowerCase());return{id:(h=p.appsettingid)!==null&&h!==void 0?h:"",name:(y=(w=D?.uniquename)!==null&&w!==void 0?w:p._settingdefinitionid_value)!==null&&y!==void 0?y:"",value:(N=p.value)!==null&&N!==void 0?N:"",...D?.displayname?{displayName:D.displayname}:{}}})}Ve.readAppSettings=jx;async function Sg(e,t,r){var n,i,a;let o=Eg("appsettingid,value",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${r}`),l=((i=(n=(0,bi.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 Ig(e,t,r,n){let i=(0,Fr.normalizeGuid)(t,"App id"),o=(await Dg(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,Fr.normalizeGuid)(s,"Setting definition id"),u=await Sg(e,i,l);if(u)return Ng(e,u,n);let c="/appsettings",d={"[email protected]":`/appmodules(${i})`,"[email protected]":`/settingdefinitions(${l})`,value:n},p,m;try{if(p=await e.post(c,d),p.status>=200&&p.status<300)return"created"}catch(w){m=w}let h;try{h=await Sg(e,i,l)}catch{h=void 0}if(h)return Ng(e,h,n);throw p&&(0,bi.ensureSuccess)(p,e.apiUrl(c)),m}Ve.setAppSetting=Ig;async function Ng(e,t,r){if(t.value===r)return"unchanged";let n=`/appsettings(${(0,Fr.normalizeGuid)(t.id,"App setting id")})`;return(0,bi.ensureSuccess)(await e.patch(n,{value:r}),e.apiUrl(n)),"updated"}async function Hx(e,t,r){var n;let i=[];for(let[a,o]of Object.entries(r??{}))try{await Ig(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}Ve.applyAppSettings=Hx});var xs=g(Rs=>{"use strict";Object.defineProperty(Rs,"__esModule",{value:!0});Rs.HEADER_NAV_BOOLEAN_RULE=void 0;Rs.HEADER_NAV_BOOLEAN_RULE="headerAndNavigationRefresh-must-be-boolean"});var Pg=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 _g=Jt(),Yt=ge(),vt=Z(),Mn=ne();Y.SolutionComponentType={SavedQuery:26,Workflow:29,SavedQueryVisualization:59,SystemForm:60,AppModule:80,UxAgentProject:10372};var Qx=[Y.SolutionComponentType.SavedQuery,Y.SolutionComponentType.Workflow,Y.SolutionComponentType.SavedQueryVisualization,Y.SolutionComponentType.SystemForm,Y.SolutionComponentType.AppModule,Y.SolutionComponentType.UxAgentProject];async function Jx(e,t){let r=(0,vt.normalizeGuid)(t,"solutionId"),n=Qx.map(s=>`msdyn_componenttype eq ${s}`).join(" or "),i=`/msdyn_solutioncomponentsummaries${(0,vt.odataQuery)([["$select","msdyn_objectid,msdyn_componenttype,msdyn_workflowcategory,msdyn_displayname,msdyn_name"],["$filter",`msdyn_solutionid eq ${r} and (${n})`]])}`,o=(await(0,_g.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 Xx(e,r,o)]}Y.fetchSolutionComponents=Jx;async function Xx(e,t,r){let n=new Set(r.map(s=>s.objectId.toLowerCase())),i=`/solutioncomponents${(0,vt.odataQuery)([["$select","objectid,componenttype"],["$filter",`_solutionid_value eq ${t} and componenttype eq ${Y.SolutionComponentType.UxAgentProject}`]])}`,a=await(0,_g.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 Kx(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 Yx(e,t){var r,n,i,a,o,s,l,u,c,d;let p=String(t??"").trim();if(!p)throw new Mn.InvalidArgumentError("getSolution: a solution unique name or id is required.");let m=Kx(p)?`solutionid eq ${(0,vt.normalizeGuid)(p,"solutionId")}`:`uniquename eq '${(0,vt.odataLiteral)(p)}'`,h=`/solutions${(0,vt.odataQuery)([["$select","solutionid,uniquename,friendlyname,version,ismanaged"],["$expand","publisherid($select=publisherid,uniquename,customizationprefix,customizationoptionvalueprefix)"],["$filter",m]])}`,N=((n=(r=(0,Yt.ensureSuccess)(await e.get(h),e.apiUrl(h)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0];if(!N?.solutionid)throw new Mn.InvalidArgumentError(`No solution found for '${t}'.`);let D=N.publisherid;if(!D?.publisherid)throw new Mn.InvalidArgumentError(`Solution '${(i=N.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 Mn.InvalidArgumentError(`Solution '${(a=N.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,vt.normalizeGuid)(N.solutionid,"solutionId"),uniqueName:(o=N.uniquename)!==null&&o!==void 0?o:"",friendlyName:(s=N.friendlyname)!==null&&s!==void 0?s:"",version:(l=N.version)!==null&&l!==void 0?l:"",isManaged:!!N.ismanaged,publisherId:(0,vt.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=Yx;async function Zx(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,Yt.ensureSuccess)(await e.post("/publishers",n),e.apiUrl("/publishers")),a=(0,Yt.readCreatedId)(i,"publisherid");if(!a)throw new Mn.InvalidArgumentError(`Dataverse did not return an id for publisher '${t.uniqueName}'`);return{id:a,uniqueName:t.uniqueName}}Y.createPublisher=Zx;async function eF(e,t){var r;let n=(0,vt.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,Yt.ensureSuccess)(await e.post("/solutions",i),e.apiUrl("/solutions")),o=(0,Yt.readCreatedId)(a,"solutionid");if(!o)throw new Mn.InvalidArgumentError(`Dataverse did not return an id for solution '${t.uniqueName}'`);return{id:o,uniqueName:t.uniqueName}}Y.createSolution=eF;async function tF(e,t,r){let i=`/solutions(${(0,vt.normalizeGuid)(t,"solutionId")})`;(0,Yt.ensureSuccess)(await e.patch(i,{version:r}),e.apiUrl(i))}Y.setSolutionVersion=tF;async function rF(e,t){var r;let i={ComponentId:(0,vt.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,Yt.ensureSuccess)(await e.post("/AddSolutionComponent",i),e.apiUrl("/AddSolutionComponent"))}Y.addSolutionComponent=rF;async function nF(e,t,r,n){let a={SolutionComponent:{"@odata.type":"Microsoft.Dynamics.CRM.solutioncomponent",solutioncomponentid:(0,vt.normalizeGuid)(t,"componentId")},ComponentType:r,SolutionUniqueName:n};(0,Yt.ensureSuccess)(await e.post("/RemoveSolutionComponent",a),e.apiUrl("/RemoveSolutionComponent"))}Y.removeSolutionComponent=nF;async function iF(e,t){var r,n;let i={SolutionName:t.solutionName,Managed:(r=t.managed)!==null&&r!==void 0?r:!1},o=(n=(0,Yt.ensureSuccess)(await e.post("/ExportSolution",i),e.apiUrl("/ExportSolution")).body)===null||n===void 0?void 0:n.ExportSolutionFile;if(!o)throw new Mn.InvalidArgumentError(`ExportSolution returned no file for '${t.solutionName}'`);return{base64:o}}Y.exportSolution=iF;async function aF(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,vt.normalizeGuid)(t.importJobId,"importJobId")),(0,Yt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution"))}Y.importSolution=aF;async function oF(e,t){let n=`/solutions(${(0,vt.normalizeGuid)(t,"solutionId")})`;(0,Yt.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Y.deleteSolution=oF});var ks=g(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.appApi=ln.deleteAppResolvingOnce=ln.unpublishedAppModulesQuery=void 0;var od=Jt(),sF=ld(),Tg=Kt(),lF=Os(),be=ge(),ie=Z(),ad=ht(),uF=Gc(),pe=ne(),cF=(0,ie.odataQuery)([["$select","appmoduleid,name,uniquename,description"]]),td="appmoduleid,name,uniquename,description";function Mg(e,t,r){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,ie.odataQuery)([["$select",e],["$filter",t],["$top",r]])}ln.unpublishedAppModulesQuery=Mg;function rd(e,t){return Mg(e,t?`appmoduleid eq ${t}`:void 0,t?1:void 0)}function Ls(e,t){return"/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,ie.odataQuery)([["$select",t],["$filter",`sitemapid eq ${e}`],["$top",1]])}function yi(e){var t;let r=(t=e.body)===null||t===void 0?void 0:t.value;if(Array.isArray(r))return r[0]}function Fs(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 dF(e){return`cdsapp_${(e||"").replace(/[^a-zA-Z0-9]/g,"")||"app"}`}async function Ug(e,t){var r,n;let i=u=>{throw new pe.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 pF(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="(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 fF(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=(0,be.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,be.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 mF(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,ie.odataQuery)([["$select","formid"],["$filter",`objecttypecode eq '${(0,ie.odataLiteral)(t)}' and type eq 2 and formactivationstate eq 1`]])}`,"formid","forms"),n(`/savedqueries${(0,ie.odataQuery)([["$select","savedqueryid"],["$filter",`returnedtypecode eq '${(0,ie.odataLiteral)(t)}' and querytype eq 0 and statecode eq 0`]])}`,"savedqueryid","views"),n(`/savedqueryvisualizations${(0,ie.odataQuery)([["$select","savedqueryvisualizationid"],["$filter",`primaryentitytypecode eq '${(0,ie.odataLiteral)(t)}'`]])}`,"savedqueryvisualizationid","charts")]);return{forms:i,views:a,charts:o,warnings:r}}var Og=new WeakMap;async function hF(e,t){let r=Og.get(e);r||(r=new Map,Og.set(e,r));let n=r.get(t);if(n!==void 0)return n;let i=await gF(e,t);return i&&r.set(t,i),i}async function Rg(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 gF(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 xg(e,t){let r=[],n=ja(t.entities),i=4,a=await Rg(n,i,m=>hF(e,m)),o=n.filter((m,h)=>!a[h]);if(o.length>0)throw new pe.SdkError("APP_ENTITY_COMPONENT_UNRESOLVED",`Refusing to build app components: table(s) ${o.map(m=>`'${m}'`).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(m=>!!m);for(let m of s)r.push({"@odata.id":`${m.entitySetName}(${m.metadataId})`});for(let m of ja(t.components.forms))r.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:m});for(let m of ja(t.components.views))r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:m});for(let m of ja(t.components.charts))r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:m});for(let m of ja(t.components.dashboards))r.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:m});let l=new Set(t.components.forms),u=new Set(t.components.views),c=new Set(t.components.charts),d=await Rg(n,i,m=>mF(e,m)),p=d.flatMap(m=>m.warnings);for(let m of d){for(let h of m.forms)l.has(h)||(l.add(h),r.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:h}));for(let h of m.views)u.has(h)||(u.add(h),r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:h}));for(let h of m.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 Fg(e,t,r){if(r.length===0)return;let n="/AddAppComponents";(0,be.ensureSuccess)(await e.post(n,{AppId:t,Components:r}),e.apiUrl(n))}function vF(e){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,ie.odataQuery)([["$select","appmoduleid,appmoduleidunique"],["$filter",`appmoduleid eq ${e}`],["$top",1]])}async function Lg(e,t,r){var n;if(r.length===0)return;let i=vF(t),a=await e.get(i);if(a.status<200||a.status>=300)throw new pe.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=yi(a),s=o?.appmoduleidunique;if(typeof s!="string"||!s)throw new pe.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 pe.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 pe.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(m=>m.objectid).filter(m=>typeof m=="string").map(m=>m.toLowerCase())),p=r.filter(m=>!d.has(m.metadataId.toLowerCase()));if(p.length>0)throw new pe.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(m=>`'${m.logicalName}' (expected objectid ${m.metadataId})`).join(", ")}. The app's navigation would reference content the app does not contain.`)}async function bF(e,t,r){let n=`/appmodules(${t})`,i=`/sitemaps(${r.sitemapId})`;try{if(!await yF(e,r.sitemapId)){r.serverRefusedSitemap&&(0,be.ensureSuccess)(await e.delete(n),e.apiUrl(n));return}e.supportsAtomicBatch&&await $g(e,[{path:n,etag:r.appEtag},{path:i,etag:r.sitemapEtag}])}catch{}}async function yF(e,t){var r;let n=Ls(t,"sitemapid"),i=await e.get(n);if(i.status<200||i.status>=300)throw new pe.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 pe.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 Bg(e,t){var r;let n=(0,ie.normalizeGuid)(t,"id"),i=h=>{throw new pe.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})${cF}`,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 Ug(e,s);if(!l)return{uniquename:s,appEtag:(0,be.readEtag)(o)};let u=(0,ie.normalizeGuid)(l,"sitemapId"),c=Ls(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=yi(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 m=p.sitemapxml;return typeof m!="string"?i(`sitemap '${u}' returned no sitemapxml.`):{sitemapId:u,uniquename:s,sitemapXml:m,appEtag:(0,be.readEtag)(o),sitemapEtag:Fs(p)}}async function wF(e,t,r){let n=(0,ie.normalizeGuid)(t,"id"),i=await Bg(e,n);await r?.(i.sitemapXml),await qg(e,n,i)}ln.deleteAppResolvingOnce=wF;async function $g(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,`+`),o=await e.postBatch(a,r),s=e.apiUrl("/$batch");(0,be.ensureSuccess)(o,s);let l=`app '${t[0].path}'`;if(typeof o.body!="string"||o.body.length===0)throw new pe.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,uF.parseChangeSetStatuses)(o.body,i.map((d,p)=>String(p+1)));if(u===void 0)throw new pe.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 pe.ConnectionError(s,c,`atomic delete of ${l} was rolled back: the change set reported HTTP ${c}`);if(u.length!==i.length)throw new pe.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=Ls(t,"sitemapid"),n=await e.get(r);return n.status<200||n.status>=300?null:Fs(yi(n))}catch{return null}}function AF(e){return e>=400&&e<500&&e!==408&&e!==429}function id(e,t,r){if(!e)throw new pe.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 qg(e,t,r){let n=`/appmodules(${t})`;if(!r.sitemapId){await CF(e,n,id(r.appEtag,t,"app"));return}if(!e.supportsAtomicBatch)throw new pe.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 $g(e,[{path:n,etag:id(r.appEtag,t,"app")},{path:`/sitemaps(${r.sitemapId})`,etag:id(r.sitemapEtag,t,"sitemap")}])}async function CF(e,t,r){(0,be.ensureSuccess)(await e.delete(t,{headers:{"If-Match":r}}),e.apiUrl(t))}async function kg(e,t){if(!/GenPageId/i.test(t))return;let r;try{r=[...new Set((0,sF.collectGenPageIds)(t))]}catch(o){throw new pe.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,ie.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,ie.normalizeGuid)(d,"uxagentprojectid"))}}let a=r.filter(o=>!n.has(o));if(a.length>0)throw new pe.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 SF(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,ie.normalizeGuid)(t,"id"),i=rd(td,n),a=(0,be.ensureSuccess)(await e.get(i),e.apiUrl(i)),o=(r=yi(a))!==null&&r!==void 0?r:{};if(!o.appmoduleid)throw new pe.SdkError("APP_NOT_FOUND",`App '${n}' was not found (checked the unpublished-aware projection, which includes drafts).`);let s=await Ug(e,o.uniquename),l=s?(0,ie.normalizeGuid)(s,"sitemapId"):void 0,u=null;if(l){let d=Ls(l,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"),p=(0,be.ensureSuccess)(await e.get(d),e.apiUrl(d)),m=yi(p);if(m&&m.sitemapnameunique!==o.uniquename)throw new pe.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${n}': sitemap '${l}' now carries sitemapnameunique '${String(m.sitemapnameunique)}', not '${String(o.uniquename)}', so it is no longer this app's sitemap. Retry.`);o.$sitemap=m??{},u=Fs(m)}let c=Fs(o);return{raw:o,etag:u,...o.appmoduleid?{siblingEtags:{[(0,ie.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 kg(e,n.sitemapxml);let i=n.iconWebResourceId?void 0:await pF(e),a=n.iconWebResourceId||i?.id;if(!a)throw new pe.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||dF(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,be.ensureSuccess)(await e.post(u,(0,be.withClientMintedId)(l,"appmoduleid",r)),e.apiUrl(u)),d=(0,be.resolveCreatedId)(c,"appmoduleid","app module",r),p=null,m=[];o&&m.push(o);let h={kind:"notRequested"},w=(0,ad.newId)(),y=!1;try{let D="/sitemaps",x=await e.post(D,{sitemapid:w,sitemapnameunique:s,sitemapname:n.sitemapname,sitemapxml:n.sitemapxml});y=AF(x.status);let F=(0,be.ensureSuccess)(x,e.apiUrl(D));p=(0,be.readEtag)(F),p||(p=await nd(e,w));let q=await xg(e,n);m.push(...q.warnings);let G=q.components;G.unshift({"@odata.type":"Microsoft.Dynamics.CRM.sitemap",sitemapid:w}),await Fg(e,d,G),await Lg(e,d,q.tables);let M=await fF(e,d);M&&m.push(M),n.appSettings&&Object.keys(n.appSettings).length>0&&m.push(...await(0,lF.applyAppSettings)(e,d,n.appSettings)),n.published!==!1&&(await(0,Tg.publishAppModule)(e,d),h={kind:"submitted"})}catch(D){throw await bF(e,d,{sitemapId:w,serverRefusedSitemap:y,appEtag:(0,be.readEtag)(c),sitemapEtag:p}),D}let N=null;if(h.kind==="submitted")try{let D=await e.get(`/appmodules(${d})?$select=appmoduleid`);D.status>=200&&D.status<300&&(N=(0,be.readEtag)(D))}catch{}return{id:d,etag:p,serverIdentity:{sitemapId:w},siblingEtags:{[d]:N},publish:h,...m.length>0?{warnings:m}:{}}},async update(e,t,r,n,i,a){var o,s,l,u,c,d,p;let m=r,h=(0,ie.normalizeGuid)(t,"id");if(await kg(e,m.sitemapxml),!m.sitemapId)throw new pe.ValidationError("app",h,"/sitemapId","missing sitemap identity \u2014 re-fetch the app before pushing edits");let w=(0,ie.normalizeGuid)(m.sitemapId,"sitemapId");if(!n)throw new pe.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 y=await xg(e,m),N=`/appmodules(${h})`,D=(o=a?.[h])!==null&&o!==void 0?o:null,x=!0,F=!1;try{let he=rd(td,h),$e=await e.get(he);if($e.status>=200&&$e.status<300){let Je=(s=yi($e))!==null&&s!==void 0?s:{};F=!0,x=String((l=Je.name)!==null&&l!==void 0?l:"")!==String((u=m.appModuleName)!==null&&u!==void 0?u:"")||String((c=Je.description)!==null&&c!==void 0?c:"")!==String((d=m.appModuleDescription)!==null&&d!==void 0?d:"")}}catch{}let q=D;if(x){let he=F?D:null,$e=he?(0,be.echoWrite)("appmoduleid",{"If-Match":he}):{query:"",options:void 0},Je=await e.patch(`${N}${$e.query}`,{name:m.appModuleName,description:m.appModuleDescription},$e.options);if(SF(Je))throw new pe.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,be.ensureSuccess)(Je,e.apiUrl(N)),q=(0,be.readEtag)(Je)}let G={"If-Match":n},M=`/sitemaps(${w})`,U;try{U=(0,be.ensureSuccess)(await e.patch(M,{sitemapxml:m.sitemapxml,sitemapname:m.sitemapname},G?{headers:G}:void 0),e.apiUrl(M))}catch(he){throw(0,pe.withPartialTokens)(he,{siblingEtags:{[h]:q}})}let B=[...y.warnings];try{await Fg(e,h,y.components),await Lg(e,h,y.tables)}catch(he){B.push(`App '${h}': one or more components were not pinned (${he.message}). Navigation may reference content not included in the app; re-push to retry.`)}let W={kind:"notRequested"},$=q,Ae=(0,be.readEtag)(U);if(m.published===!0){try{await(0,Tg.publishAppModule)(e,h),W={kind:"submitted"}}catch(he){W={kind:"failed",error:he},B.push(`App '${h}': saved, but publishing failed (${he.message}). The app remains unpublished; re-push to retry.`)}if(W.kind==="submitted"){$=null;try{let he=await e.get(`/appmodules(${h})?$select=appmoduleid`);he.status>=200&&he.status<300&&($=(0,be.readEtag)(he)),Ae=(p=await nd(e,w))!==null&&p!==void 0?p:Ae}catch{}}}return{id:h,etag:Ae??await nd(e,w),siblingEtags:{[h]:$},publish:W,...B.length>0?{warnings:B}:{}}},async delete(e,t){let r=(0,ie.normalizeGuid)(t,"id");await qg(e,r,await Bg(e,r))}}});var Ha=g(wi=>{"use strict";function NF(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 EF(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 Vg=ud({HTML:"text/html",isHTML:function(e){return e===Vg.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),Gg=ud({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(e){return e===Gg.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=EF;wi.find=NF;wi.freeze=ud;wi.MIME_TYPE=Vg;wi.NAMESPACE=Gg});var Ad=g(Ur=>{var Kg=Ha(),dr=Kg.find,Qa=Kg.NAMESPACE;function DF(e){return e!==""}function IF(e){return e?e.split(/[\t\n\f\r ]+/).filter(DF):[]}function _F(e,t){return e.hasOwnProperty(t)||(e[t]=!0),e}function zg(e){if(!e)return[];var t=IF(e);return Object.keys(t.reduce(_F,{}))}function PF(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 yt(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 wt={},xt=wt.ELEMENT_NODE=1,Ci=wt.ATTRIBUTE_NODE=2,Us=wt.TEXT_NODE=3,Yg=wt.CDATA_SECTION_NODE=4,Zg=wt.ENTITY_REFERENCE_NODE=5,TF=wt.ENTITY_NODE=6,cd=wt.PROCESSING_INSTRUCTION_NODE=7,dd=wt.COMMENT_NODE=8,e0=wt.DOCUMENT_NODE=9,t0=wt.DOCUMENT_TYPE_NODE=10,Lr=wt.DOCUMENT_FRAGMENT_NODE=11,OF=wt.NOTATION_NODE=12,rt={},ze={},Qz=rt.INDEX_SIZE_ERR=(ze[1]="Index size error",1),Jz=rt.DOMSTRING_SIZE_ERR=(ze[2]="DOMString size error",2),bt=rt.HIERARCHY_REQUEST_ERR=(ze[3]="Hierarchy request error",3),Xz=rt.WRONG_DOCUMENT_ERR=(ze[4]="Wrong document",4),RF=rt.INVALID_CHARACTER_ERR=(ze[5]="Invalid character",5),Kz=rt.NO_DATA_ALLOWED_ERR=(ze[6]="No data allowed",6),Yz=rt.NO_MODIFICATION_ALLOWED_ERR=(ze[7]="No modification allowed",7),r0=rt.NOT_FOUND_ERR=(ze[8]="Not found",8),Zz=rt.NOT_SUPPORTED_ERR=(ze[9]="Not supported",9),Wg=rt.INUSE_ATTRIBUTE_ERR=(ze[10]="Attribute in use",10),Ai=rt.INVALID_STATE_ERR=(ze[11]="Invalid state",11),eW=rt.SYNTAX_ERR=(ze[12]="Syntax error",12),tW=rt.INVALID_MODIFICATION_ERR=(ze[13]="Invalid modification",13),rW=rt.NAMESPACE_ERR=(ze[14]="Invalid namespace",14),nW=rt.INVALID_ACCESS_ERR=(ze[15]="Invalid access",15);function se(e,t){if(t instanceof Error)var r=t;else r=this,Error.call(this,ze[e]),this.message=ze[e],Error.captureStackTrace&&Error.captureStackTrace(this,se);return r.code=e,t&&(this.message=this.message+": "+t),r}se.prototype=Error.prototype;Xa(rt,se);function kr(){}kr.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(m0(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};yt(Si,kr);function Bs(){}function n0(e,t){for(var r=e.length;r--;)if(e[r]===t)return r}function jg(e,t,r,n){if(n?t[n0(t,n)]=r:t[t.length++]=r,e){r.ownerElement=e;var i=e.ownerDocument;i&&(n&&o0(i,e,n),xF(i,e,r))}}function Hg(e,t,r){var n=n0(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&&(o0(a,e,r),r.ownerElement=null)}}else throw new se(r0,new Error(e.tagName+"@"+r))}Bs.prototype={length:0,item:kr.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 se(Wg);var r=this.getNamedItem(e.nodeName);return jg(this._ownerElement,this,e,r),r},setNamedItemNS:function(e){var t=e.ownerElement,r;if(t&&t!=this._ownerElement)throw new se(Wg);return r=this.getNamedItemNS(e.namespaceURI,e.localName),jg(this._ownerElement,this,e,r),r},removeNamedItem:function(e){var t=this.getNamedItem(e);return Hg(this._ownerElement,this,t),t},removeNamedItemNS:function(e,t){var r=this.getNamedItemNS(e,t);return Hg(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 i0(){}i0.prototype={hasFeature:function(e,t){return!0},createDocument:function(e,t,r){var n=new Ka;if(n.implementation=this,n.childNodes=new kr,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 Gs;return n.name=e,n.nodeName=e,n.publicId=t||"",n.systemId=r||"",n}};function ae(){}ae.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 qs(this,e,t)},replaceChild:function(e,t){qs(this,e,t,l0),t&&this.removeChild(t)},removeChild:function(e){return s0(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return f0(this.ownerDocument||this,this,e)},normalize:function(){Ge(this,null,{enter:function(e){for(var t=e.firstChild;t;){var r=t.nextSibling;r!==null&&r.nodeType===Us&&t.nodeType===Us?(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 a0(e){return e=="<"&&"<"||e==">"&&">"||e=="&"&&"&"||e=='"'&&"""||"&#"+e.charCodeAt()+";"}Xa(wt,ae);Xa(wt,ae.prototype);function $s(e,t){return Ge(e,null,{enter:function(r){return t(r)?Ge.STOP:!0}})===Ge.STOP}function Ge(e,t,r){for(var n=[{node:e,context:t,phase:Ge.ENTER}];n.length>0;){var i=n.pop();if(i.phase===Ge.ENTER){var a=r.enter(i.node,i.context);if(a===Ge.STOP)return Ge.STOP;if(n.push({node:i.node,context:a,phase:Ge.EXIT}),a==null)continue;for(var o=i.node.lastChild;o;)n.push({node:o,context:a,phase:Ge.ENTER}),o=o.previousSibling}else r.exit&&r.exit(i.node,i.context)}}Ge.STOP=Symbol("walkDOM.STOP");Ge.ENTER=0;Ge.EXIT=1;function Ka(){this.ownerDocument=this}function xF(e,t,r){e&&e._inc++;var n=r.namespaceURI;n===Qa.XMLNS&&(t._nsMap[r.prefix?r.localName:""]=r.value)}function o0(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 s0(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 FF(e){return e&&(e.nodeType===ae.DOCUMENT_NODE||e.nodeType===ae.DOCUMENT_FRAGMENT_NODE||e.nodeType===ae.ELEMENT_NODE)}function LF(e){return e&&(pr(e)||md(e)||Mr(e)||e.nodeType===ae.DOCUMENT_FRAGMENT_NODE||e.nodeType===ae.COMMENT_NODE||e.nodeType===ae.PROCESSING_INSTRUCTION_NODE)}function Mr(e){return e&&e.nodeType===ae.DOCUMENT_TYPE_NODE}function pr(e){return e&&e.nodeType===ae.ELEMENT_NODE}function md(e){return e&&e.nodeType===ae.TEXT_NODE}function Qg(e,t){var r=e.childNodes||[];if(dr(r,pr)||Mr(t))return!1;var n=dr(r,Mr);return!(t&&n&&r.indexOf(n)>r.indexOf(t))}function Jg(e,t){var r=e.childNodes||[];function n(a){return pr(a)&&a!==t}if(dr(r,n))return!1;var i=dr(r,Mr);return!(t&&i&&r.indexOf(i)>r.indexOf(t))}function kF(e,t,r){if(!FF(e))throw new se(bt,"Unexpected parent node type "+e.nodeType);if(r&&r.parentNode!==e)throw new se(r0,"child not in parent");if(!LF(t)||Mr(t)&&e.nodeType!==ae.DOCUMENT_NODE)throw new se(bt,"Unexpected node type "+t.nodeType+" for parent node type "+e.nodeType)}function MF(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===ae.DOCUMENT_FRAGMENT_NODE){var a=i.filter(pr);if(a.length>1||dr(i,md))throw new se(bt,"More than one element or text in fragment");if(a.length===1&&!Qg(e,r))throw new se(bt,"Element in fragment can not be inserted before doctype")}if(pr(t)&&!Qg(e,r))throw new se(bt,"Only one element can be added and only after doctype");if(Mr(t)){if(dr(n,Mr))throw new se(bt,"Only one doctype is allowed");var o=dr(n,pr);if(r&&n.indexOf(o)<n.indexOf(r))throw new se(bt,"Doctype can only be inserted before an element");if(!r&&o)throw new se(bt,"Doctype can not be appended since element is present")}}function l0(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===ae.DOCUMENT_FRAGMENT_NODE){var a=i.filter(pr);if(a.length>1||dr(i,md))throw new se(bt,"More than one element or text in fragment");if(a.length===1&&!Jg(e,r))throw new se(bt,"Element in fragment can not be inserted before doctype")}if(pr(t)&&!Jg(e,r))throw new se(bt,"Only one element can be added and only after doctype");if(Mr(t)){let l=function(u){return Mr(u)&&u!==r};var s=l;if(dr(n,l))throw new se(bt,"Only one doctype is allowed");var o=dr(n,pr);if(r&&n.indexOf(o)<n.indexOf(r))throw new se(bt,"Doctype can only be inserted before an element")}}function qs(e,t,r,n){kF(e,t,r),e.nodeType===ae.DOCUMENT_NODE&&(n||MF)(e,t,r);var i=t.parentNode;if(i&&i.removeChild(t),t.nodeType===Lr){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==Lr&&(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 UF(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:e0,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==Lr){for(var r=e.firstChild;r;){var n=r.nextSibling;this.insertBefore(r,t),r=n}return e}return qs(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),s0(this,e)},replaceChild:function(e,t){qs(this,e,t,l0),Ja(e,this),t&&this.removeChild(t),pr(e)&&(this.documentElement=e)},importNode:function(e,t){return BF(this,e,t)},getElementById:function(e){var t=null;return $s(this.documentElement,function(r){if(r.nodeType==xt&&r.getAttribute("id")==e)return t=r,!0}),t},getElementsByClassName:function(e){var t=zg(e);return new Si(this,function(r){var n=[];return t.length>0&&$s(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=zg(a);o=t.every(PF(s))}o&&n.push(i)}}}),n})},createElement:function(e){var t=new Un;t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.localName=e,t.childNodes=new kr;var r=t.attributes=new Bs;return r._ownerElement=t,t},createDocumentFragment:function(){var e=new zs;return e.ownerDocument=this,e.childNodes=new kr,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 se(RF,'data contains "]]>"');var t=new vd;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var r=new yd;return r.ownerDocument=this,r.tagName=r.nodeName=r.target=e,r.nodeValue=r.data=t,r},createAttribute:function(e){var t=new Vs;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){var t=new bd;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var r=new Un,n=t.split(":"),i=r.attributes=new Bs;return r.childNodes=new kr,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 Vs,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}};yt(Ka,ae);function Un(){this._nsMap={}}Un.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===Lr?this.insertBefore(e,null):UF(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 $s(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 $s(r,function(i){i!==r&&i.nodeType===xt&&(e==="*"||i.namespaceURI===e)&&(t==="*"||i.localName==t)&&n.push(i)}),n})}};Ka.prototype.getElementsByTagName=Un.prototype.getElementsByTagName;Ka.prototype.getElementsByTagNameNS=Un.prototype.getElementsByTagNameNS;yt(Un,ae);function Vs(){}Vs.prototype.nodeType=Ci;yt(Vs,ae);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(ze[bt])},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}};yt(Ya,ae);function hd(){}hd.prototype={nodeName:"#text",nodeType:Us,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}};yt(hd,Ya);function gd(){}gd.prototype={nodeName:"#comment",nodeType:dd};yt(gd,Ya);function vd(){}vd.prototype={nodeName:"#cdata-section",nodeType:Yg};yt(vd,Ya);function Gs(){}Gs.prototype.nodeType=t0;yt(Gs,ae);function u0(){}u0.prototype.nodeType=OF;yt(u0,ae);function c0(){}c0.prototype.nodeType=TF;yt(c0,ae);function bd(){}bd.prototype.nodeType=Zg;yt(bd,ae);function zs(){}zs.prototype.nodeName="#document-fragment";zs.prototype.nodeType=Lr;yt(zs,ae);function yd(){}yd.prototype.nodeType=cd;yt(yd,ae);function d0(){}d0.prototype.serializeToString=function(e,t,r,n){return p0.call(e,t,r,n)};ae.prototype.toString=p0;function p0(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 Xg(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 Ms(e,t,r){e.push(" ",t,'="',r.replace(/[<>&"\t\n\r]/g,a0),'"')}function wd(e,t,r,n,i,a){i||(i=[]),Ge(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 m=p;if(!u&&!o.prefix&&o.namespaceURI){for(var h,w=0;w<c.length;w++)if(c.item(w).name==="xmlns"){h=c.item(w).value;break}if(!h)for(var y=l.length-1;y>=0;y--){var N=l[y];if(N.prefix===""&&N.namespace===o.namespaceURI){h=N.namespace;break}}if(h!==o.namespaceURI)for(var y=l.length-1;y>=0;y--){var N=l[y];if(N.namespace===o.namespaceURI){N.prefix&&(m=N.prefix+":"+p);break}}}t.push("<",m);for(var D=l.slice(),x=0;x<d;x++){var F=c.item(x);F.prefix=="xmlns"?D.push({prefix:F.localName,namespace:F.value}):F.nodeName=="xmlns"&&D.push({prefix:"",namespace:F.value})}for(var x=0;x<d;x++){var F=c.item(x);if(Xg(F,u,D)){var q=F.prefix||"",G=F.namespaceURI;Ms(t,q?"xmlns:"+q:"xmlns",G),D.push({prefix:q,namespace:G})}var M=n?n(F):F;M&&(typeof M=="string"?t.push(M):Ms(t,M.name,M.value))}if(p===m&&Xg(o,u,D)){var U=o.prefix||"",G=o.namespaceURI;Ms(t,U?"xmlns:"+U:"xmlns",G),D.push({prefix:U,namespace:G})}var B=o.firstChild;if(B||u&&!/^(?:meta|link|img|br|hr|input)$/i.test(p)){if(t.push(">"),u&&/^script$/i.test(p)){for(;B;)B.data?t.push(B.data):wd(B,t,u,n,D.slice(),a),B=B.nextSibling;return t.push("</",p,">"),null}return{ns:D,isHTML:u,tag:m}}else return t.push("/>"),null;case e0:case Lr:return{ns:l.slice(),isHTML:u,tag:null};case Ci:return Ms(t,o.name,o.value),null;case Us:return t.push(o.data.replace(/[<&>]/g,a0)),null;case Yg:if(a&&o.data.indexOf("]]>")!==-1)throw new se(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 se(Ai,'The comment node data contains "-->"');return t.push("<!--",o.data,"-->"),null;case t0:if(a){if(o.publicId&&!/^("[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%']*"|'[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%'"]*')$/.test(o.publicId))throw new se(Ai,"DocumentType publicId is not a valid PubidLiteral");if(o.systemId&&!/^("[^"]*"|'[^']*')$/.test(o.systemId))throw new se(Ai,"DocumentType systemId is not a valid SystemLiteral");if(o.internalSubset&&o.internalSubset.indexOf("]>")!==-1)throw new se(Ai,'DocumentType internalSubset contains "]>"')}var W=o.publicId,$=o.systemId;if(t.push("<!DOCTYPE ",o.name),W)t.push(" PUBLIC ",W),$&&$!="."&&t.push(" ",$),t.push(">");else if($&&$!=".")t.push(" SYSTEM ",$,">");else{var Ae=o.internalSubset;Ae&&t.push(" [",Ae,"]"),t.push(">")}return null;case cd:if(a&&o.data.indexOf("?>")!==-1)throw new se(Ai,'The ProcessingInstruction data contains "?>"');return t.push("<?",o.target," ",o.data,"?>"),null;case Zg: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 BF(e,t,r){var n;return Ge(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 f0(e,t,r){var n;return Ge(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 kr),o.ownerDocument=e;var u=r;switch(o.nodeType){case xt:var c=i.attributes,d=o.attributes=new Bs,p=c.length;d._ownerElement=o;for(var m=0;m<p;m++)o.setAttributeNode(f0(e,c.item(m),!0));break;case Ci:u=!0}return a!==null?a.appendChild(o):n=o,u?o:null}}),n}function m0(e,t,r){e[t]=r}try{Object.defineProperty&&(Object.defineProperty(Si.prototype,"length",{get:function(){return pd(this),this.$$length}}),Object.defineProperty(ae.prototype,"textContent",{get:function(){if(this.nodeType===xt||this.nodeType===Lr){var e=[];return Ge(this,null,{enter:function(t){if(t.nodeType===xt||t.nodeType===Lr)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 Lr: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}}}),m0=function(e,t,r){e["$$"+t]=r})}catch{}Ur.DocumentType=Gs;Ur.DOMException=se;Ur.DOMImplementation=i0;Ur.Element=Un;Ur.Node=ae;Ur.NodeList=kr;Ur.walkDOM=Ge;Ur.XMLSerializer=d0});var g0=g(Za=>{"use strict";var h0=Ha().freeze;Za.XML_ENTITIES=h0({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});Za.HTML_ENTITIES=h0({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 N0=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]/,v0=new RegExp("[\\-\\.0-9"+Cd.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),b0=new RegExp("^"+Cd.source+v0.source+"*(?::"+Cd.source+v0.source+"*)?$"),eo=0,un=1,Ni=2,to=3,Ei=4,Di=5,ro=6,Ws=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 A0(){}A0.prototype={parse:function(e,t,r){var n=this.domBuilder;n.startDocument(),C0(t,t={}),$F(e,t,r,n,this.errorHandler),n.endDocument()}};function $F(e,t,r,n,i){function a(ce){if(ce>65535){ce-=65536;var mt=55296+(ce>>10),Qu=56320+(ce&1023);return String.fromCharCode(mt,Qu)}else return String.fromCharCode(ce)}function o(ce){var mt=ce.slice(1,-1);return Object.hasOwnProperty.call(r,mt)?r[mt]:mt.charAt(0)==="#"?a(parseInt(mt.substr(1).replace("x","0x"))):(i.error("entity not found:"+ce),ce)}function s(ce){if(ce>w){var mt=e.substring(w,ce).replace(/&#?\w+;/g,o);p&&l(w),n.characters(mt,0,ce-w),w=ce}}function l(ce,mt){for(;ce>=c&&(mt=d.exec(e));)u=mt.index,c=u+mt[0].length,p.lineNumber++;p.columnNumber=ce-u+1}for(var u=0,c=0,d=/.*(?:\r\n?|\n)|.*$/g,p=n.locator,m=[{currentNSMap:t}],h={},w=0;;){try{var y=e.indexOf("<",w);if(y<0){if(!e.substr(w).match(/^\s*$/)){var N=n.doc,D=N.createTextNode(e.substr(w));N.appendChild(D),n.currentElement=D}return}switch(y>w&&s(y),e.charAt(y+1)){case"/":var $=e.indexOf(">",y+3),x=e.substring(y+2,$).replace(/[ \t\n\r]+$/g,""),F=m.pop();$<0?(x=e.substring(y+2).replace(/[\s<].*/,""),i.error("end tag name: "+x+" is not complete:"+F.tagName),$=y+1+x.length):x.match(/\s</)&&(x=x.replace(/[\s<].*/,""),i.error("end tag name: "+x+" maybe not complete"),$=y+1+x.length);var q=F.localNSMap,G=F.tagName==x,M=G||F.tagName&&F.tagName.toLowerCase()==x.toLowerCase();if(M){if(n.endElement(F.uri,F.localName,x),q)for(var U in q)Object.prototype.hasOwnProperty.call(q,U)&&n.endPrefixMapping(U);G||i.fatalError("end tag name: "+x+" is not match the current start tagName:"+F.tagName)}else m.push(F);$++;break;case"?":p&&l(y),$=WF(e,y,n);break;case"!":p&&l(y),$=zF(e,y,n,i);break;default:p&&l(y);var B=new S0,W=m[m.length-1].currentNSMap,$=qF(e,y,B,W,o,i),Ae=B.length;if(!B.closed&&GF(e,$,B.tagName,h)&&(B.closed=!0,r.nbsp||i.warning("unclosed xml attribute")),p&&Ae){for(var he=y0(p,{}),$e=0;$e<Ae;$e++){var Je=B[$e];l(Je.offset),Je.locator=y0(p,{})}n.locator=he,w0(B,n,W)&&m.push(B),n.locator=p}else w0(B,n,W)&&m.push(B);no.isHTML(B.uri)&&!B.closed?$=VF(e,$,B.tagName,o,n):$++}}catch(ce){if(ce instanceof Ii)throw ce;i.error("element parse error: "+ce),$=-1}$>w?w=$:s(Math.max(y,w)+1)}}function y0(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function qF(e,t,r,n,i,a){function o(m,h,w){r.attributeNames.hasOwnProperty(m)&&a.fatalError("Attribute "+m+" redefined"),r.addValue(m,h.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,i),w)}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 Ws:c=Ws,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 Ws: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 Ws:throw new Error("elements closed character '/' and '>' must be connected to")}}u++}}function w0(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={},C0(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 m=e.uri=r[l||""];if(t.startElement(m,u,n,e),e.closed){if(t.endElement(m,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 VF(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 GF(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 C0(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function zF(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=jF(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 WF(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 S0(){this.attributeNames={}}S0.prototype={setTagName:function(e){if(!b0.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},addValue:function(e,t,r){if(!b0.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 jF(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=A0;Sd.ParseError=Ii});var O0=g(Hs=>{var HF=Ha(),QF=Ad(),E0=g0(),_0=N0(),JF=QF.DOMImplementation,D0=HF.NAMESPACE,XF=_0.ParseError,KF=_0.XMLReader;function P0(e){return e.replace(/\r[\n\u0085]/g,``).replace(/[\r\u0085\u2028]/g,`-`)}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);+`)}function T0(e){this.options=e||{locator:{}}}T0.prototype.parseFromString=function(e,t){var r=this.options,n=new KF,i=r.domBuilder||new io,a=r.errorHandler,o=r.locator,s=r.xmlns||{},l=/\/x?html?$/.test(t),u=l?E0.HTML_ENTITIES:E0.XML_ENTITIES;o&&i.setDocumentLocator(o),n.errorHandler=YF(a,i,o),n.domBuilder=r.domBuilder||i,l&&(s[""]=D0.HTML),s.xml=s.xml||D0.XML;var c=r.normalizeLineEndings||P0;return e&&typeof e=="string"?n.parse(c(e),s,u):n.errorHandler.error("invalid doc source"),i.doc};function YF(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 JF().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;js(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),js(this,r)},ignorableWhitespace:function(e,t,r){},characters:function(e,t,r){if(e=I0.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=I0.apply(this,arguments);var n=this.doc.createComment(e);this.locator&&_i(this.locator,n),js(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),js(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 XF(e,this.locator)}};function Nd(e){if(e)return`+@`+(e.systemId||"")+"#[line:"+e.lineNumber+",col:"+e.columnNumber+"]"}function I0(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 js(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}Hs.__DOMHandler=io;Hs.normalizeLineEndings=P0;Hs.DOMParser=T0});var Js=g(Qs=>{var R0=Ad();Qs.DOMImplementation=R0.DOMImplementation;Qs.XMLSerializer=R0.XMLSerializer;Qs.DOMParser=O0().DOMParser});var ld=g(Pi=>{"use strict";Object.defineProperty(Pi,"__esModule",{value:!0});Pi.deleteAppCascade=Pi.collectGenPageIds=void 0;var ZF=ks(),eL=ne(),Ed=Z(),tL=Js();function x0(e){let t=[],r=s=>l=>t.push(`${s}: ${l}`),i=new tL.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml").documentElement;if(!i||t.length>0)throw new eL.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=x0;async function rL(e,t,r){let n=(0,Ed.normalizeGuid)(t,"appModuleId");(0,Ed.normalizeGuid)(r,"appModuleIdUnique");let i=[],a=[],o=[];await(0,ZF.deleteAppResolvingOnce)(e,n,l=>{l!==void 0&&o.push(...x0(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 F0={};ar(F0,{Guid:()=>P});var P,Le=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,nt=I(()=>{"use strict";Re();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(!E.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 E.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 L0={};ar(L0,{ScriptUtilities:()=>E});var E,Re=I(()=>{"use strict";Le();nt();E=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 Xs,Ks,Bn,Ys,Dd,Zs,Id=I(()=>{"use strict";(function(e){e[e.FormElementNodeChange=0]="FormElementNodeChange",e[e.FormElementAttributeChange=1]="FormElementAttributeChange"})(Xs||(Xs={}));Ks=class{type;targetNode;constructor(t,r){this.type=t,this.targetNode=r}},Bn=class extends Ks{key;oldValue;newValue;constructor(t,r,n,i){super(Xs.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)}},Ys=class extends Ks{property;oldValue;newValue;constructor(t,r,n,i){super(Xs.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()})}},Zs=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 k0={};ar(k0,{ChartGridMode:()=>Ft,ColumnLayoutWidths:()=>sL,ComponentCategory:()=>tl,ComponentType:()=>_d,ControlLayoutTypes:()=>Ld,DisplayConditionsInfo:()=>aL,ElementNames:()=>v,ElementProperties:()=>f,ElementType:()=>Td,EntityAttributeProperty:()=>Od,EventType:()=>ao,FormActivationState:()=>Fd,FormCanvasServiceScope:()=>yL,FormDesignerSideBarTab:()=>Pd,FormPresentation:()=>Rd,FormState:()=>el,FormType:()=>ke,HeaderDensityType:()=>cn,LookUpTable:()=>fr,MORE_TAB_PREFIX:()=>uL,NavBarChildElementType:()=>xd,PREVIEW_ID_HEADER_FLYOUT:()=>fL,PREVIEW_ID_HEADER_OVERFLOW_BUTTON:()=>hL,PREVIEW_ID_NAVIGATION_AREA:()=>dL,PREVIEW_ID_QUICKCREATE_ROOT:()=>vL,PREVIEW_ID_TAB:()=>gL,PREVIEW_ID_TAB_LIST:()=>mL,PREVIEW_ID_TAB_PANEL:()=>pL,PropertyModelKeys:()=>Ud,PropertyModelSectionKeys:()=>lL,RELATED_TAB_ID:()=>Bd,RELATED_TAB_PREFIX:()=>cL,SectionDefaultProperties:()=>oL,SectionLayoutTypes:()=>we,TabContentType:()=>kd,TabDefaultProperties:()=>dn,TabLayoutTypes:()=>ye,TelemetryPropertyNames:()=>bL,UnboundControlPropertyKeys:()=>Md,compositeAddressFields:()=>iL,compositeFieldNames:()=>Pt,compositeFields:()=>nL});var ke,_d,Pd,v,f,Td,Pt,nL,iL,Od,fr,el,cn,Rd,aL,xd,Fd,ye,oL,dn,we,Ld,kd,sL,Md,Ud,lL,ao,Ft,Bd,uL,cL,dL,pL,fL,mL,hL,gL,vL,bL,tl,yL,X=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"})(ke||(ke={}));(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={}));f={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"},nL=[Pt.fullname,Pt.yomifullname,Pt.address1_composite,Pt.address2_composite,Pt.address3_composite,Pt.billto,Pt.shipto],iL=[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"})(fr||(fr={}));(function(e){e[e.Published=0]="Published",e[e.Draft=1]="Draft",e[e.New=2]="New",e[e.SaveAs=3]="SaveAs"})(el||(el={}));(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"})(Rd||(Rd={}));aL={TopOrderFormId:"topOrderFormId",NextDisplayOrder:"nextDisplayOrder"};(function(e){e[e.NavBarRelationShipItem=0]="NavBarRelationShipItem",e[e.NavBarItem=1]="NavBarItem"})(xd||(xd={}));(function(e){e[e.InActive=0]="InActive",e[e.Active=1]="Active"})(Fd||(Fd={}));(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={}));oL={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"})(we||(we={}));(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"})(Ld||(Ld={}));(function(e){e.cardSections="cardSections",e.singleComponent="singleComponent",e.default="default",e.expandAvailableSpace="expandAvailableSpace"})(kd||(kd={}));sL={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={}));lL={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"})(Ft||(Ft={}));Bd="tab_related3b554255-7717-4d17-bb7f-9936fb1e75ca",uL="more_tab_",cL="related_tab_",dL="preview_id_navigation_area",pL="tab-section",fL="headerFieldsFlyout",mL="tablist",hL="header_overflowButton",gL="tab",vL="quickCreateRoot",bL={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"})(tl||(tl={}));yL="CellCanvasServiceScope"});var M0={};ar(M0,{Attribute:()=>rl,FormElementNode:()=>j});var rl,j,We=I(()=>{"use strict";Re();nt();Id();X();Le();rl=class{key;value;constructor(t,r){this.key=t,this.value=r}},j=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 rl(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 Bn(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 Bn(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 Bn(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 Ys(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 Bn(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){E.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(E.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=E.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 U0={};ar(U0,{ControlClassId:()=>S,ControlNamePrefixes:()=>nl,getControlDisplayNames:()=>wL});function wL(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,nl,$n=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={}));nl={[S.WebResourceHTMLControl]:"WebResource",[S.WebResourceImageControl]:"WebResource",[S.IframeControl]:"IFRAME",[S.SearchWidgetControl]:"Search widget",[S.SubgridControl]:"Subgrid",[S.TimelineControl]:"Timeline",[S.QuickViewControl]:"QuickviewControl"}});var qn=g((wW,$0)=>{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{}}}),B0=function(){return oo};Object.setPrototypeOf(B0,oo);$0.exports=B0});var lt,Br,q0,V0,Ti=I(()=>{"use strict";lt="cds-designer-models",Br="FormCustomControl",q0="FormCell",V0="Form"});var Oi,ut,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}},ut=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 Vn,$d=I(()=>{"use strict";so();X();Vn=class e{static lockedFieldCount=new ut;static dependencyFieldCount=new ut;static getNecessaryLookUpTable(t){switch(t){case fr.DependencyFieldTable:return e.dependencyFieldCount;case fr.LockedFieldTable:return e.lockedFieldCount}}static initCanvasLockedFieldLookUp(t){switch(t){case fr.DependencyFieldTable:e.dependencyFieldCount=new ut;case fr.LockedFieldTable:e.lockedFieldCount=new ut}}}});var il,G0=I(()=>{"use strict";Le();Re();X();We();il=class extends j{constructor(t){super(v.controlDescription,t)}get forControl(){let t=this.getProperty(f.ForControl);return E.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(f.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(!E.IsNullOrUndefined(t.id))return t.id;return null}get DefaultCustomControl(){for(let t of this.customControls)if(!E.IsNullOrUndefined(t.id))return t;return null}get DefaultCustomControls(){let t=[];for(let r of this.customControls)E.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 W0,j0,ct,_,z0,pn,Gn,Ri,qd,Vd,xi=I(()=>{"use strict";W0={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"},j0={GroupDefinition:"GroupDefinition"},ct={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"})(z0||(z0={}));(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"})(Gn||(Gn={}));(function(e){e[e.Bound=0]="Bound",e[e.Input=1]="Input",e[e.Output=2]="Output"})(Ri||(Ri={}));qd=[_.LookupCustomer,_.LookupOwner,_.LookupPartyList,_.LookupRegarding,_.LookupSimple],Vd=[_.WholeNone,_.WholeDuration,_.WholeLanguage,_.WholeTimeZone,_.FP,_.Decimal]});function $r(){return mr||(mr=window._makerConfig,mr&&window?.location?.search?.indexOf("useProductionConfig")>-1&&(mr={...mr,region:"prod",graphQLEndpoint:"https://graph.make.powerapps.com/"}),mr?.region==="prod"&&(mr={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/"}}},...mr}),mr||{aadClientId:"a8f7a65c-f5ba-4859-b2d6-df772c264e9d",location:"cus",region:"test",publicPath:"/",graphQLEndpoint:"https://graph.make.test.powerapps.com/"})}var mr,al=I(()=>{"use strict";});function H0(e,t,r){if(!e)return ol.has(e)||(window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoIsEmpty"}),ol.add("")),!1;if(e){if(e=e.toLowerCase(),ol.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}}),ol.add(e),!1}return!0}function AL(e){return H0(e,Gd,"Location dictionary")?Gd[e.toLowerCase()]:"us"}function CL(){let e=$r().location.toLowerCase();return H0(e,Gd,"Current location dictionary")?e:"us"}var ol,Gd,LW,Q0=I(()=>{"use strict";al();ol=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"};LW=AL(CL())});var L,MW,J0=I(()=>{"use strict";L={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"},MW={[L.USWest]:{geoName:"us",regionShortName:"wus"},[L.USCentral]:{geoName:"us",regionShortName:"cus"},[L.USEast]:{geoName:"us",regionShortName:"eus"},[L.USEast2]:{geoName:"us",regionShortName:"eus2"},[L.USWestCentral]:{geoName:"us",regionShortName:"wcus"},[L.USWest2]:{geoName:"us",regionShortName:"wus2"},[L.USSouthCentral]:{geoName:"br",regionShortName:"scus"},[L.BrazilSouth]:{geoName:"br",regionShortName:"sbr"},[L.UKSouth]:{geoName:"uk",regionShortName:"suk"},[L.UKWest]:{geoName:"uk",regionShortName:"wuk"},[L.JapanEast]:{geoName:"jp",regionShortName:"ejp"},[L.JapanWest]:{geoName:"jp",regionShortName:"wjp"},[L.IndiaCentral]:{geoName:"in",regionShortName:"cin"},[L.IndiaSouth]:{geoName:"in",regionShortName:"sin"},[L.ItalyNorth]:{geoName:"it",regionShortName:"nit"},[L.GermanyWestCentral]:{geoName:"de",regionShortName:"wcde"},[L.GermanyNorth]:{geoName:"de",regionShortName:"nde"},[L.EuropeNorth]:{geoName:"eu",regionShortName:"neu"},[L.EuropeWest]:{geoName:"eu",regionShortName:"weu"},[L.AustraliaEast]:{geoName:"au",regionShortName:"eau"},[L.AustraliaSouthEast]:{geoName:"au",regionShortName:"seau"},[L.AsiaSouthEast]:{geoName:"as",regionShortName:"seas"},[L.AsiaEast]:{geoName:"as",regionShortName:"eas"},[L.CanadaCentral]:{geoName:"ca",regionShortName:"cca"},[L.CanadaEast]:{geoName:"ca",regionShortName:"eca"},[L.SouthAfricaNorth]:{geoName:"za",regionShortName:"nza"},[L.SouthAfricaWest]:{geoName:"za",regionShortName:"wza"},[L.FranceCentral]:{geoName:"fr",regionShortName:"cfr"},[L.FranceSouth]:{geoName:"fr",regionShortName:"sfr"},[L.UAENorth]:{geoName:"ae",regionShortName:"nae"},[L.UAECentral]:{geoName:"ae",regionShortName:"cae"},[L.SwedenCentral]:{geoName:"se",regionShortName:"cse"},[L.SwitzerlandNorth]:{geoName:"ch",regionShortName:"nch"},[L.SwitzerlandWest]:{geoName:"ch",regionShortName:"wch"},[L.NorwayEast]:{geoName:"no",regionShortName:"eno"},[L.NorwayWest]:{geoName:"no",regionShortName:"wno"},[L.KoreaCentral]:{geoName:"kr",regionShortName:"ckr"},[L.KoreaSouth]:{geoName:"kr",regionShortName:"skr"},[L.SingaporeSouthEast]:{geoName:"sg",regionShortName:"seas"},[L.PolandCentral]:{geoName:"pl",regionShortName:"cpl"},[L.QatarCentral]:{geoName:"qa",regionShortName:"cqa"},[L.NewZealandNorth]:{geoName:"nz",regionShortName:"nnz"},[L.GovernmentUSTexas]:{geoName:"us",regionShortName:"ugtx"},[L.GovernmentUSVirginia]:{geoName:"us",regionShortName:"ugva"},[L.GovernmentUSDodCentral]:{regionShortName:"udc"},[L.GovernmentUSDodEast]:{regionShortName:"ude"},[L.ChinaEast]:{regionShortName:"cne"},[L.ChinaEast2]:{regionShortName:"cne2"},[L.ChinaEast3]:{regionShortName:"cne3"},[L.ChinaNorth]:{regionShortName:"cnn"},[L.ChinaNorth2]:{regionShortName:"cnn2"},[L.ChinaNorth3]:{regionShortName:"cnn3"},[L.UssecEast]:{geoName:"us",regionShortName:"erx"},[L.UssecWest]:{geoName:"us",regionShortName:"wrx"},[L.UsnatEast]:{geoName:"us",regionShortName:"eex"},[L.UsnatWest]:{geoName:"us",regionShortName:"wex"}}});var X0=I(()=>{"use strict";al();});var lo=I(()=>{"use strict";al();Q0();J0();X0();});function uo(e,t){return K0?K0.isOverridden(e,t):{overridden:!1}}var K0,co=I(()=>{"use strict";});var zd=I(()=>{"use strict";lo();co();});function SL(e,t){let{region:r}=$r();return()=>{let n=e.settings[t];if(n.allowOverrides){let s=uo(e.packageName,t);if(s.overridden)return typeof s.value=="string"?NL(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 NL(e){return isNaN(Number(e))?e==="true"?!0:e==="false"?!1:e:Number(e)}function EL(e){let t=e.packageName;if(sl.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=>!ul(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){EL(e);let t={};return Object.keys(e.settings).forEach(r=>{t[r]={enumerable:!0,get:SL(e,r)}}),sl.set(e.packageName,e),Object.defineProperties({},t)}function Wd(e,t){return sl.has(e)?!!sl.get(e).settings[t]:!1}var sl,ll=I(()=>{"use strict";lo();co();Hd();fo();sl=new Map});function Y0(e,t){let{region:r}=$r();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 DL(e){let t=e.packageName;if(cl.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=>!ul(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){DL(e);let t={};Object.keys(e.features).forEach(i=>{t[i]={enumerable:!0,configurable:!0,get:Y0(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:Y0(e,a.toString())}}),Object.defineProperties(r,i),n.clear()}},cl.set(e.packageName,e),Object.defineProperties(r,t)}function jd(e,t){return cl.has(e)?!!cl.get(e).features[t]:!1}var cl,Hd=I(()=>{"use strict";lo();fo();co();ll();cl=new Map});var ev=g((lj,Z0)=>{"use strict";Z0.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 nv=g(Jd=>{"use strict";var IL=Object.prototype.hasOwnProperty,_L;function tv(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch{return null}}function rv(e){try{return encodeURIComponent(e)}catch{return null}}function PL(e){for(var t=/([^=?#&]+)=?([^&]*)/g,r={},n;n=t.exec(e);){var i=tv(n[1]),a=tv(n[2]);i===null||a===null||i in r||(r[i]=a)}return r}function TL(e,t){t=t||"";var r=[],n,i;typeof t!="string"&&(t="?");for(i in e)if(IL.call(e,i)){if(n=e[i],!n&&(n===null||n===_L||isNaN(n))&&(n=""),i=rv(i),n=rv(n),i===null||n===null)continue;r.push(i+"="+n)}return r.length?t+r.join("&"):""}Jd.stringify=TL;Jd.parse=PL});var Yd=g((cj,uv)=>{"use strict";var av=ev(),dl=nv(),ov=/[\n\r\t]/g,OL=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,RL=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,xL=/^[a-zA-Z]:/,FL=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;function Kd(e){return(e||"").toString().replace(FL,"")}var Xd=[["#","hash"],["?","query"],function(t,r){return hr(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]],iv={hash:1,query:1};function sv(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 gr(unescape(e.pathname),{});else if(i==="string"){n=new gr(e,{});for(a in iv)delete n[a]}else if(i==="object"){for(a in e)a in iv||(n[a]=e[a]);n.slashes===void 0&&(n.slashes=OL.test(e.href))}return n}function hr(e){return e==="file:"||e==="ftp:"||e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function lv(e,t){e=Kd(e),e=e.replace(ov,""),t=t||{};var r=RL.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)):hr(n)?s=r[4]:n?i&&(s=s.slice(2)):o>=2&&hr(t.protocol)&&(s=r[4]),{protocol:n,slashes:i||hr(n),slashesCount:o,rest:s}}function LL(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 gr(e,t,r){if(e=Kd(e),e=e.replace(ov,""),!(this instanceof gr))return new gr(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=dl.parse),t=sv(t),i=lv(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||xL.test(e))||!i.slashes&&(i.protocol||i.slashesCount<2||!hr(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=LL(d.pathname,t.pathname)),d.pathname.charAt(0)!=="/"&&hr(d.protocol)&&(d.pathname="/"+d.pathname),av(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:"&&hr(d.protocol)&&d.host?d.protocol+"//"+d.host:"null",d.href=d.toString()}function kL(e,t,r){var n=this;switch(e){case"query":typeof t=="string"&&t.length&&(t=(r||dl.parse)(t)),n[e]=t;break;case"port":n[e]=t,av(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:"&&hr(n.protocol)&&n.host?n.protocol+"//"+n.host:"null",n.href=n.toString(),n}function ML(e){(!e||typeof e!="function")&&(e=dl.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||hr(r.protocol)?"//":"");return r.username?(a+=r.username,r.password&&(a+=":"+r.password),a+="@"):r.password?(a+=":"+r.password,a+="@"):r.protocol!=="file:"&&hr(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}gr.prototype={set:kL,toString:ML};gr.extractProtocol=lv;gr.location=sv;gr.trimLeft=Kd;gr.qs=dl;uv.exports=gr});var UL,cv=I(()=>{"use strict";UL=le(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 pl=I(()=>{"use strict";});var ep,tp,rp=I(()=>{"use strict";pl();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 ul(e){return BL.has(e)}var BL,fo=I(()=>{"use strict";zd();Hd();ll();co();zd();cv();rp();pl();np();BL=new Set(["tie","test","prod","preview","preprod","gov","high","dod","mooncake","ex","rx"])});var $L,dv=I(()=>{"use strict";fo();$L=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 fl,O,k,zn,Fi,ml,pv,fv,ip,mo=I(()=>{"use strict";so();fl=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={}));zn=class extends fl{constructor(t){super(t)}static get None(){return"None"}static get SystemRequired(){return"SystemRequired"}static get ApplicationRequired(){return"ApplicationRequired"}static get Recommended(){return"Recommended"}},Fi=class e extends fl{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?ml.Persistent:parseInt(ml[this.name])}};(function(e){e[e.Persistent=0]="Persistent",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup"})(ml||(ml={}));(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"})(pv||(pv={}));(function(e){e[e.Attribute=0]="Attribute",e[e.Organization=1]="Organization",e[e.Currency=2]="Currency"})(fv||(fv={}));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(Fi.Persistent,"SystemCustomization.String.Source.persistent"),t.add(Fi.Calculated,"SystemCustomization.String.Source.calculated"),t.add(Fi.Rollup,"SystemCustomization.String.Source.rollup"),t.add(Fi.None,"SystemCustomization.String.Source.none"),t}static getDisplayNameResourceKey(t){return e.resourceKeyMap.getValue(t)}}});var vv,op,Li,Wn,ap,hl,ki,qr,ve,mv,hv,gv,Zt=I(()=>{"use strict";vv={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"})(Li||(Li={}));(function(e){e.Left="Left",e.Right="Right",e.Center="Center"})(Wn||(Wn={}));(function(e){e[e.Mobile=0]="Mobile",e[e.Tablet=1]="Tablet",e[e.Web=2]="Web"})(ap||(ap={}));hl=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={}));qr=class{static StartTag="<"},ve={ShowLabel:"true",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_",labelAlignment:Wn.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"})(mv||(mv={}));(function(e){e.TabWithLockedFieldRemoval="TabWithLockedFieldRemoval",e.SectionWithLockedFieldRemoval="SectionWithLockedFieldRemoval",e.LockedSectionRemoval="LockedSectionRemoval",e.LockedFieldRemoval="LockedFieldRemoval",e.RequiredFieldRemoval="RequiredFieldRemoval",e.LastRemainingTab="LastRemainingTab",e.UnknownRemoval="UnknownRemoval"})(hv||(hv={}));(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"})(gv||(gv={}))});var jn=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 bv;(function(e){e.None="None",e.UserOwned="UserOwned",e.TeamOwned="TeamOwned",e.BusinessOwned="BusinessOwned",e.OrganizationOwned="OrganizationOwned",e.BusinessParented="BusinessParented",e.Filtered="Filtered"})(bv||(C.OwnershipTypes=bv={}));var yv;(function(e){e.User="Microsoft.Dynamics.CRM.systemuser",e.Team="Microsoft.Dynamics.CRM.team"})(yv||(C.PrincipalType=yv={}));var wv;(function(e){e[e.DoNotDisplayInActivityMenus=0]="DoNotDisplayInActivityMenus",e[e.DisplayInActivityMenus=1]="DisplayInActivityMenus"})(wv||(C.ActivityTypeMask=wv={}));var Av;(function(e){e.Activity="Activity",e.Virtual="Virtual",e.Standard="Standard",e.Elastic="Elastic"})(Av||(C.TableTypes=Av={}));var Cv;(function(e){e.Standard="Standard",e.Virtual="Virtual",e.Elastic="Elastic"})(Cv||(C.TableTypeCode=Cv={}));var Sv;(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"})(Sv||(C.FormType=Sv={}));var Nv;(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(Nv||(C.FormPresentation=Nv={}));var Ev;(function(e){e[e.Inactive=0]="Inactive",e[e.Active=1]="Active"})(Ev||(C.ActivationState=Ev={}));var Dv;(function(e){e[e.String=0]="String",e[e.Number=1]="Number",e[e.Picklist=2]="Picklist"})(Dv||(C.AttributeType=Dv={}));var Iv;(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"})(Iv||(C.ViewType=Iv={}));var _v;(function(e){e[e.ASPChart=0]="ASPChart",e[e.PowerBI=1]="PowerBI"})(_v||(C.ChartsType=_v={}));var Pv;(function(e){e[e.DataAndInteractionCentric=0]="DataAndInteractionCentric",e[e.InteractionCentric=1]="InteractionCentric"})(Pv||(C.ChartType=Pv={}));var Tv;(function(e){e[e.Published=0]="Published",e[e.Unpublished=1]="Unpublished",e[e.Deleted=2]="Deleted",e[e.DeletedUnpublished=3]="DeletedUnpublished"})(Tv||(C.ComponentState=Tv={}));var Ov;(function(e){e[e.None=1]="None",e[e.Sandbox=2]="Sandbox",e[e.External=3]="External"})(Ov||(C.PluginIsolationMode=Ov={}));var Rv;(function(e){e[e.BasicAuth=0]="BasicAuth"})(Rv||(C.AuthType=Rv={}));var xv;(function(e){e[e.Database=0]="Database",e[e.Disk=1]="Disk",e[e.Normal=2]="Normal",e[e.AzureWebApp=3]="AzureWebApp"})(xv||(C.PluginSourceType=xv={}));var Fv;(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"})(Fv||(C.AttributeTypeCode=Fv={}));var Lv;(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"})(Lv||(C.AttributeTypeName=Lv={}));var kv;(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"})(kv||(C.AttributeFormatCode=kv={}));var Mv;(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"})(Mv||(C.AttributeFormatName=Mv={}));var Uv;(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"})(Uv||(C.AttributeTypeCodeNum=Uv={}));var Bv;(function(e){e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean"})(Bv||(C.OptionSetType=Bv={}));var $v;(function(e){e[e.Draft=0]="Draft",e[e.Activated=1]="Activated"})($v||(C.StateCode=$v={}));var qv;(function(e){e[e.Draft=1]="Draft",e[e.Activated=2]="Activated"})(qv||(C.StatusCode=qv={}));var Vv;(function(e){e[e.Enabled=0]="Enabled",e[e.Disabled=1]="Disabled"})(Vv||(C.StateCodeEnabledDisabled=Vv={}));var Gv;(function(e){e[e.Enabled=1]="Enabled",e[e.Disabled=2]="Disabled"})(Gv||(C.StatusCodeEnabledDisabled=Gv={}));var zv;(function(e){e[e.Definition=1]="Definition",e[e.Activation=2]="Activation",e[e.Template=3]="Template"})(zv||(C.WorkflowTypeCode=zv={}));var Wv;(function(e){e[e.User=1]="User",e[e.BusinessUnit=2]="BusinessUnit",e[e.ParentChildBusinessUnit=3]="ParentChildBusinessUnit",e[e.Organization=4]="Organization"})(Wv||(C.WorkflowScope=Wv={}));var jv;(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"})(jv||(C.WorkflowCategory=jv={}));var Hv;(function(e){e[e.None=-1]="None",e[e.BusinessFlow=0]="BusinessFlow",e[e.TaskFlow=1]="TaskFlow"})(Hv||(C.BusinessProcessType=Hv={}));var Qv;(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"})(Qv||(C.AppSubType=Qv={}));var Jv;(function(e){e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(Jv||(C.RelationshipType=Jv={}));var Xv;(function(e){e.ManyToOneRelationship="ManyToOneRelationship",e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(Xv||(C.RelationshipTypeExt=Xv={}));var Kv;(function(e){e.NoCascade="NoCascade",e.Cascade="Cascade",e.Active="Active",e.UserOwned="UserOwned",e.RemoveLink="RemoveLink",e.Restrict="Restrict"})(Kv||(C.CascadeType=Kv={}));var Yv;(function(e){e.None="None",e.Append="Append",e.ParentChild="ParentChild",e.Pointer="Pointer",e.Inheritance="Inheritance"})(Yv||(C.RelationshipSecurityTypes=Yv={}));var Zv;(function(e){e[e.Active=1]="Active",e[e.Inactive=2]="Inactive"})(Zv||(C.ViewStatusCode=Zv={}));var eb;(function(e){e[e.Active=0]="Active",e[e.Inactive=1]="Inactive"})(eb||(C.ViewStateCode=eb={}));var tb;(function(e){e.Active="Active",e.Failed="Failed",e.InProgress="InProgress",e.Pending="Pending"})(tb||(C.EntityKeyIndexStatus=tb={}));var rb;(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"})(rb||(C.SolutionComponentTypeCode=rb={}));var nb;(function(e){e[e.IncludeSubcomponents=0]="IncludeSubcomponents",e[e.DoNotIncludeSubcomponents=1]="DoNotIncludeSubcomponents",e[e.IncludeAsShellOnly=2]="IncludeAsShellOnly"})(nb||(C.RootComponentBehavior=nb={}));var gl;(function(e){e[e.Entity=1]="Entity",e[e.Attribute=2]="Attribute",e[e.OptionSet=9]="OptionSet",e[e.EntityRelationship=10]="EntityRelationship",e[e.EntityKey=14]="EntityKey",e[e.Role=20]="Role",e[e.DisplayString=22]="DisplayString",e[e.SavedQuery=26]="SavedQuery",e[e.Workflow=29]="Workflow",e[e.Report=31]="Report",e[e.Template=36]="Template",e[e.ContractTemplate=37]="ContractTemplate",e[e.KbArticleTemplate=38]="KbArticleTemplate",e[e.MailMergeTemplate=39]="MailMergeTemplate",e[e.RibbonCustomization=50]="RibbonCustomization",e[e.SavedQueryVisualization=59]="SavedQueryVisualization",e[e.SystemForm=60]="SystemForm",e[e.WebResource=61]="WebResource",e[e.SiteMap=62]="SiteMap",e[e.ConnectionRole=63]="ConnectionRole",e[e.HierarchyRule=65]="HierarchyRule",e[e.CustomControl=66]="CustomControl",e[e.FieldSecurityProfile=70]="FieldSecurityProfile",e[e.AppModule=80]="AppModule",e[e.PluginAssembly=91]="PluginAssembly",e[e.SdkMessageProcessingStep=92]="SdkMessageProcessingStep",e[e.ServiceEndpoint=95]="ServiceEndpoint",e[e.RoutingRule=150]="RoutingRule",e[e.SLA=152]="SLA",e[e.ConvertRule=154]="ConvertRule",e[e.MobileOfflineProfile=161]="MobileOfflineProfile",e[e.EntityDataProvider=181]="EntityDataProvider",e[e.EntityDataSource=183]="EntityDataSource",e[e.SdkMessage=201]="SdkMessage",e[e.CanvasApp=300]="CanvasApp",e[e.Connector=372]="Connector",e[e.EnvironmentVariableDefinition=380]="EnvironmentVariableDefinition",e[e.EnvironmentVariableValue=381]="EnvironmentVariableValue",e[e.AIModel=401]="AIModel",e[e.Dataflow=418]="Dataflow",e[e.DataflowEntities=419]="DataflowEntities",e[e.DualWriteEntityMap=500]="DualWriteEntityMap",e[e.DataIntegrationConnection=501]="DataIntegrationConnection",e[e.ExportToDataLakeConfig=510]="ExportToDataLakeConfig",e[e.DataWorkspace=10282]="DataWorkspace",e[e.Dashboard=100001]="Dashboard",e[e.InteractionCentricDashboard=100002]="InteractionCentricDashboard",e[e.Dialog=100003]="Dialog",e[e.PowerBIDashboard=100004]="PowerBIDashboard",e[e.BusinessRule=100021]="BusinessRule",e[e.ProcessFlow=100024]="ProcessFlow",e[e.Flow=100025]="Flow",e[e.UIFlow=100026]="UIFlow",e[e.ProcessNoFlow=100031]="ProcessNoFlow",e[e.AllDashboards=100032]="AllDashboards",e[e.FormsOnly=100033]="FormsOnly",e[e.ComponentLibrary=100034]="ComponentLibrary",e[e.CanvasAppsOnly=100035]="CanvasAppsOnly",e[e.CustomCanvasPage=100038]="CustomCanvasPage",e[e.CodeApp=100039]="CodeApp",e[e.MobileApp=100046]="MobileApp",e[e.ProcessNoFlowNoUIFlowNoBusinessRule=100036]="ProcessNoFlowNoUIFlowNoBusinessRule",e[e.ActionDefinition=100040]="ActionDefinition",e[e.ActionTemplate=100041]="ActionTemplate",e[e.DialogDefinition=100042]="DialogDefinition",e[e.DialogTemplate=100043]="DialogTemplate",e[e.WorkflowDefinition=100044]="WorkflowDefinition",e[e.WorkflowTemplate=100045]="WorkflowTemplate"})(gl||(C.SolutionComponentTypeCodeExt=gl={}));var vl;(function(e){e[e.Entity=9801]="Entity",e[e.Attribute=9802]="Attribute",e[e.OptionSet=9804]="OptionSet",e[e.EntityRelationship=9805]="EntityRelationship",e[e.EntityKey=9812]="EntityKey",e[e.Role=1036]="Role",e[e.DisplayString=4102]="DisplayString",e[e.SavedQuery=1039]="SavedQuery",e[e.Workflow=4703]="Workflow",e[e.Report=9100]="Report",e[e.Template=2010]="Template",e[e.ContractTemplate=2011]="ContractTemplate",e[e.KbArticleTemplate=1016]="KbArticleTemplate",e[e.MailMergeTemplate=9106]="MailMergeTemplate",e[e.SavedQueryVisualization=1111]="SavedQueryVisualization",e[e.SystemForm=1030]="SystemForm",e[e.WebResource=9333]="WebResource",e[e.SiteMap=4709]="SiteMap",e[e.ConnectionRole=3231]="ConnectionRole",e[e.HierarchyRule=8840]="HierarchyRule",e[e.CustomControl=9753]="CustomControl",e[e.FieldSecurityProfile=1200]="FieldSecurityProfile",e[e.AppModule=9006]="AppModule",e[e.PluginAssembly=4605]="PluginAssembly",e[e.SdkMessageProcessingStep=4608]="SdkMessageProcessingStep",e[e.ServiceEndpoint=4618]="ServiceEndpoint",e[e.RoutingRule=8181]="RoutingRule",e[e.SLA=9750]="SLA",e[e.ConvertRule=9300]="ConvertRule",e[e.MobileOfflineProfile=9866]="MobileOfflineProfile",e[e.EntityDataSource=85]="EntityDataSource",e[e.SdkMessage=4606]="SdkMessage",e[e.RibbonCustomization=1120]="RibbonCustomization",e[e.EntityDataProvider=181]="EntityDataProvider",e[e.CanvasApp=300]="CanvasApp",e[e.Connector=372]="Connector",e[e.MaskingRule=373]="MaskingRule",e[e.AttributeMaskingRule=374]="AttributeMaskingRule",e[e.EnvironmentVariableDefinition=380]="EnvironmentVariableDefinition",e[e.EnvironmentVariableValue=381]="EnvironmentVariableValue",e[e.AIModel=401]="AIModel",e[e.Plan=10283]="Plan",e[e.Dataflow=418]="Dataflow",e[e.DataflowEntities=419]="DataflowEntities",e[e.DualWriteEntityMap=500]="DualWriteEntityMap",e[e.DataIntegrationConnection=501]="DataIntegrationConnection",e[e.ExportToDataLakeConfig=510]="ExportToDataLakeConfig",e[e.TeamTemplate=511]="TeamTemplate",e[e.DataWorkspace=10282]="DataWorkspace",e[e.Dashboard=1030]="Dashboard",e[e.InteractionCentricDashboard=1032]="InteractionCentricDashboard",e[e.PowerBIDashboard=1034]="PowerBIDashboard",e[e.Dialog=1030]="Dialog",e[e.WebResourceImage=9333]="WebResourceImage",e[e.WebResourceSilverlight=9333]="WebResourceSilverlight",e[e.WebResourceCode=9333]="WebResourceCode",e[e.WebResourceData=9333]="WebResourceData",e[e.BusinessRule=4703]="BusinessRule",e[e.ActionDefinition=4703]="ActionDefinition",e[e.ActionTemplate=4703]="ActionTemplate",e[e.DialogDefinition=4703]="DialogDefinition",e[e.DialogTemplate=4703]="DialogTemplate",e[e.WorkflowDefinition=4703]="WorkflowDefinition",e[e.WorkflowTemplate=4703]="WorkflowTemplate",e[e.ProcessFlow=4703]="ProcessFlow",e[e.Flow=4703]="Flow",e[e.UIFlow=4703]="UIFlow",e[e.ProcessNoFlow=4703]="ProcessNoFlow",e[e.ProcessNoFlowNoUIFlowNoBusinessRule=4703]="ProcessNoFlowNoUIFlowNoBusinessRule",e[e.AllDashboards=1030]="AllDashboards",e[e.FormsOnly=1030]="FormsOnly",e[e.ComponentLibrary=300]="ComponentLibrary",e[e.CanvasAppsOnly=300]="CanvasAppsOnly",e[e.CustomCanvasPage=300]="CustomCanvasPage",e[e.CodeApp=300]="CodeApp",e[e.MobileApp=300]="MobileApp",e[e.Chatbot=10030]="Chatbot",e[e.Card=10276]="Card"})(vl||(C.EntityTypeCode=vl={}));var ib;(function(e){e.MultiSelectPicklist="MultiSelectPicklist",e.File="File",e.Image="Image"})(ib||(C.SolutionComponentVirtualAttributeSubtype=ib={}));function qL(e){let t=gl[e];return vl[t]}C.SolutionComponentTypeCodeToEntityTypeCodeExt=qL;function VL(e){let t=vl[e];return gl[t]}C.SolutionEntityTypeCodeExtToComponentTypeCode=VL;var ab;(function(e){e.Active="Active",e.Auto="Auto",e.Disabled="Disabled",e.Inactive="Inactive"})(ab||(C.ImeMode=ab={}));var ob;(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"})(ob||(C.SourceType=ob={}));var sb;(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"})(sb||(C.StringFormatName=sb={}));var lb;(function(e){e[e.PrecisionProperty=0]="PrecisionProperty",e[e.Organization=1]="Organization",e[e.TransactionCurrency=2]="TransactionCurrency"})(lb||(C.PrecisionSource=lb={}));var ub;(function(e){e.UserLocal="UserLocal",e.DateOnly="DateOnly",e.TimeZoneIndependent="TimeZoneIndependent"})(ub||(C.DateTimeBehavior=ub={}));var cb;(function(e){e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(cb||(C.DateTimeFormat=cb={}));var db;(function(e){e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(db||(C.IntegerFormat=db={}));var pb;(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"})(pb||(C.WebResourceTypeCode=pb={}));var fb;(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"})(fb||(C.SdkMessageProcessingStage=fb={}));var mb;(function(e){e[e.ServerOnly=0]="ServerOnly",e[e.OutlookClientOnly=1]="OutlookClientOnly",e[e.Both=2]="Both"})(mb||(C.SupportedDeployment=mb={}));var hb;(function(e){e[e.Synchronous=0]="Synchronous",e[e.Asynchronous=1]="Asynchronous"})(hb||(C.SdkMessageProcessingMode=hb={}));var gb;(function(e){e[e.ReportingServicesReport=1]="ReportingServicesReport",e[e.OtherReport=2]="OtherReport",e[e.LinkedReport=3]="LinkedReport"})(gb||(C.ReportTypeCode=gb={}));var vb;(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"})(vb||(C.ConnectionRoleCategory=vb={}));var bb;(function(e){e[e.Name=1]="Name",e[e.Address=2]="Address"})(bb||(C.ServiceNamespaceFormat=bb={}));var yb;(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"})(yb||(C.ServiceEndpointContract=yb={}));var wb;(function(e){e[e.Normal=1]="Normal",e[e.Federated=2]="Federated"})(wb||(C.ServiceEndpointConnectionMode=wb={}));var Ab;(function(e){e.CannotDeleteInUseComponent="0x8004f01f",e.CannotDeleteInUseAttribute="0x80048418",e.CannotDeleteInUseOptionSet="0x80048417",e.CannotDeleteInUseEntity="0x80048420",e.CannotUninstallWithDependencies="0x8004F01D"})(Ab||(C.DeleteDependencyErrorCode=Ab={}));var Cb;(function(e){e.SystemAdministrator="627090FF-40A3-4053-8790-584EDC5BE201",e.SystemCustomizer="119F245C-3CC8-4B62-B31C-D1A046CED15D"})(Cb||(C.DefaultRoleTemplates=Cb={}));var Sb;(function(e){e[e.DefaultTeamPrivilege=0]="DefaultTeamPrivilege",e[e.DirectUserAndTeamPrivilege=1]="DirectUserAndTeamPrivilege"})(Sb||(C.RoleInheritance=Sb={}));var Nb;(function(e){e[e.NotSpecified=0]="NotSpecified",e[e.CustomConnector=1]="CustomConnector"})(Nb||(C.ConnectorTypeEnum=Nb={}));var Eb;(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"})(Eb||(C.EnvironmentVariableDefinitionTypeEnum=Eb={}));var Db;(function(e){e[e.Owner=0]="Owner",e[e.Access=1]="Access",e[e.AADSecurityGroup=2]="AADSecurityGroup",e[e.AADOfficeGroup=3]="AADOfficeGroup"})(Db||(C.TeamTypeEnum=Db={}));var Ib;(function(e){e.Bots="bots"})(Ib||(C.KnownCustomSolutionComponentEntitySetName=Ib={}));var _b;(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"})(_b||(C.QueryType=_b={}))});var sp,Pb=I(()=>{"use strict";(function(e){e.DefaultValue="defaultValue",e.Loaded="loaded"})(sp||(sp={}))});var Rb,GL,Tb,uH,cH,ho,Ob,dH,pH,xb=I(()=>{"use strict";Rb=le(qn());Re();Ti();dv();mo();Zt();xi();X();GL=le(jn());Pb();(function(e){e.Model="Model",e.Canvas="Canvas",e.CustomPages="CustomPages"})(Tb||(Tb={}));uH={Read:Gn.Read,Edit:Gn.Edit,Both:Gn.Both,Container:Gn.Container},cH={input:Ri.Input,bound:Ri.Bound,output:Ri.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"})(Ob||(Ob={}));dH=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]),pH={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 er,bl,Fb=I(()=>{"use strict";er=le(qn());Le();Re();nt();Ti();xi();xb();mo();X();We();Zt();bl=class extends j{constructor(t){super(v.customControl,t)}customControlId;get id(){let t=this.getProperty(f.id);return E.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(ct.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===ct.name)?.value}getParameterChildrenValues(t,r,n){if(this.isDataSet(t)){let i=r.find(u=>u.key===ct.name)?.value,a={Name:i,Type:_.Grid,Columns:[]},l=this.getParameters().get(ct.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===f.static&&a.value==="true"){r=!0;break}}return r}get name(){return this.getProperty(f.Name)}get formFactor(){return this.getProperty(f.formFactor)}set formFactor(t){this.setProperty(f.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(qr.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:j0.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(ct.dataset)?.some(m=>this.getDatasetName(m)===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,er.trackInfoTrace)(lt,{eventName:`${Br}/parametersToJSON`,eventData:{message:`Configuration metadata for custom control parameter ${o} is not available for custom control : ${this.name}.`}}),r=[];break}}}else(0,er.trackErrorTrace)(lt,{eventName:`${Br}/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,er.trackErrorTrace)(lt,{eventName:`${Br}/parametersToJSON`,eventData:{message:"Custom Control Manifest not found"}},new Error(`No custom control manifest found for ${this.name}`))}catch(n){(0,er.trackErrorTrace)(lt,{eventName:`${Br}/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===ct.name)?.value;if(a)return this.getParameterChildrenValues(t,r);{let s=new Error(`No dataset manifest info for ${o}`);(0,er.trackErrorTrace)(lt,{eventName:`${Br}/parameterJSON`,eventData:{message:"Missing custom control manifest dataset info"}},s)}}else{let a=n,o=r&&r.find(l=>l.key===f.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(f.bindAttribute),p=await i.formModelService.loadLookupModel(d),m=p.lookupColumn,h=this.getLookupDataTypeFromAttributeMetadata(m);return{Name:t,Type:h,Usage:l,Static:u,Primary:c,EntityName:p.primaryTableName,Value:d,ViewId:this.getFormComponentValueByParameterName(W0.DefaultViewId),TargetEntityType:m.targets[0],FilterRelationshipName:this.getFormComponentValueByParameterName(f.FilterRelationshipName),AvailableViewIds:this.getFormComponentValueByParameterName(f.AvailableViewIds),DependentAttributeName:this.getFormComponentValueByParameterName(f.DependentAttributeName),DependentAttributeType:this.getFormComponentValueByParameterName(f.DependentAttributeType),AllowFilterOff:T.IsStrictTrue(this.getFormComponentValueByParameterName(f.AllowFilterOff)),DisableQuickFind:T.IsStrictTrue(this.getFormComponentValueByParameterName(f.DisableQuickFind)),EnableViewPicker:!T.IsStrictTrue(this.getFormComponentValueByParameterName(f.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,er.trackErrorTrace)(lt,{eventName:`${Br}/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 m=o.value;return{Type:m,Static:u,Usage:l,Value:this.isNumberTypeProperty(a,m)&&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,er.trackErrorTrace)(lt,{eventName:`${Br}/parameterJSON`,eventData:{message:"Missing property type info"}},p)}else{let l=new Error(`No property manifest info for ${t}`);(0,er.trackWarningTrace)(lt,{eventName:`${Br}/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 ct.dataset===t}isGroups(t){return!!t[0].getAllProperties().find(n=>n.key==="isGroup"&&n.value==="true")}}});var V,lp=I(()=>{"use strict";V=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 R,Mi,Me,yl=I(()=>{"use strict";Le();so();Re();nt();mo();$n();lp();Zt();R=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"}},Me=class e{static FieldControlIds=e.initializeFieldControls();static UnboundControlIds=e.initializeUnboundControls();static ControlsAllowedForReferencePanel=e.initializeReferencePanelControls();static ControlsAllowedForFooter=e.initializeFooterControls();static CustomControlIdMap=new ut;static initializeFieldControls(){let t=new ut,r=e.getControlName(O.SingleLineofText,k.Phone);t.add(r,new P(R.PhoneNumberControl));let n=e.getControlName(O.SingleLineofText,k.TextArea);t.add(n,new P(R.TextAreaControl));let i=e.getControlName(O.SingleLineofText,k.Text);t.add(i,new P(R.TextBoxControl));let a=e.getControlName(O.SingleLineofText,k.Email);t.add(a,new P(R.EmailAddressControl));let o=e.getControlName(O.SingleLineofText,k.Url);t.add(o,new P(R.UrlControl));let s=e.getControlName(O.SingleLineofText,k.TickerSymbol);t.add(s,new P(R.TickerControl));let l=e.getControlName(O.SingleLineofText,k.PhoneticGuide);t.add(l,new P(R.TextBoxControl));let u=e.getControlName(O.WholeNumber,k.Duration);t.add(u,new P(R.DurationControl));let c=e.getControlName(O.WholeNumber,k.Language);t.add(c,new P(R.LanguagePickerControl));let d=e.getControlName(O.WholeNumber,k.TimeZone);t.add(d,new P(R.TimeZonePicklistControl));let p=e.getControlName(O.WholeNumber,k.None);t.add(p,new P(R.IntegerControl));let m=e.getControlName(O.DateTime,k.DateOnly);t.add(m,new P(R.DateTimeControl));let h=e.getControlName(O.DateTime,k.DateAndTime);t.add(h,new P(R.DateTimeControl));let w=e.getControlName(O.LookupType,k.None);t.add(w,new P(R.LookupControl));let y=e.getControlName(O.CustomerType,k.None);t.add(y,new P(R.LookupControl));let N=e.getControlName(O.FloatingPointNumber,k.None);t.add(N,new P(R.FloatControl));let D=e.getControlName(O.DecimalNumber,k.None);t.add(D,new P(R.DecimalControl));let x=e.getControlName(O.Currency,k.None);t.add(x,new P(R.MoneyControl));let F=e.getControlName(O.MultipleLineofText,k.None);t.add(F,new P(R.TextAreaControl));let q=e.getControlName(O.MultipleLineofText,k.Text);t.add(q,new P(R.TextAreaControl));let G=e.getControlName(O.MultipleLineofText,k.TextArea);t.add(G,new P(R.TextAreaControl));let M=e.getControlName(O.MultipleLineofText,k.Email);t.add(M,new P(R.EmailBodyControl));let U=e.getControlName(O.OptionSet,k.None);t.add(U,new P(R.PicklistControl));let B=e.getControlName(O.TwoOptions,k.None);t.add(B,new P(R.RadioControl));let W=e.getControlName(O.Image,k.None);t.add(W,new P(R.WebResourceImageControl));let $=e.getControlName(O.Image,k.None);t.add($,new P(R.WebResourceHtmlControl));let Ae=e.getControlName(O.TwoOptions,"Radio");t.add(Ae,new P(R.RadioControl));let he=e.getControlName(O.TwoOptions,"CheckBox");t.add(he,new P(R.CheckBoxControl));let $e=e.getControlName(O.TwoOptions,"List");t.add($e,new P(R.PicklistControl));let Je=e.getControlName(O.State,k.None);t.add(Je,new P(R.PicklistControl));let ce=e.getControlName(O.Status,k.None);t.add(ce,new P(R.PicklistStatusControl));let mt=e.getControlName(O.OwnerType,k.None);t.add(mt,new P(R.LookupControl));let Qu=e.getControlName(O.PartyListType,k.None);t.add(Qu,new P(R.PartyListControl));let _1=e.getControlName(O.LookupType,k.Regarding);t.add(_1,new P(R.RegardingControl));let P1=e.getControlName(O.MultiSelectOptionSet,k.None);return t.add(P1,new P(R.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(!E.IsNullOrEmptyGuid(t)){let r=e.getTypeAndFormatByControlOrUniqueId(t.guidString.toLowerCase());return r=E.IsNullOrUndefined(r)?e.getUnboundControlNameFromIdentifier(t):r.substring(0,r.indexOf("_")),r}return null}static isCustomControl(t){return E.IsNullOrUndefined(t.control)||E.IsNullOrUndefined(t.control.ClassId)||t.control.ClassId.guidString===R.CustomControl}static initializeUnboundControls(){let t=new ut;return t.add(R.ACIControl,V.ACIControl),t.add(R.IframeControl,V.IframeControl),t.add(R.SearchWidgetControl,V.SearchWidgetControl),t.add(R.MapsControl,V.MapsControl),t.add(R.QuickFormCollectionControl,V.QuickFormCollectionControl),t.add(R.GridControl,V.SubGridControl),t.add(R.WebResourceImageControl,V.WebResourceImageControl),t.add(R.WebResourceHtmlControl,V.WebResourceHtmlControl),t.add(R.ReferencePanelSearchWidget,V.SearchWidgetControl),t.add(R.ReferencePanelQuickFormCollectionControl,V.QuickFormCollectionControl),t.add(R.ReferencePanelSubgridControl,V.SubGridControl),t.add(R.TimerControl,V.TimerControl),t.add(R.TimeLineControl,V.NotesControl),t.add(R.TimeLineControlUC,V.NotesControl),t.add(R.SocialInsightControl,V.SocialInsightControl),t.add(Mi.RelationshipAssistant,V.CustomControl),t}static initializeReferencePanelControls(){let t=new ut;return t.add(R.IframeControl,V.IframeControl),t.add(R.ReferencePanelSearchWidget,V.SearchWidgetControl),t.add(R.ReferencePanelQuickFormCollectionControl,V.QuickFormCollectionControl),t.add(R.ReferencePanelSubgridControl,V.SubGridControl),t.add(R.WebResourceHtmlControl,V.WebResourceHtmlControl),t.add(R.WebResourceImageControl,V.WebResourceHtmlControl),t}static initializeFooterControls(){let t=new Oi;return t.add(Li.IFRAME,!0),t.add(Li.SPACER,!0),t.add(Li.WEB_RESOURCE_HTML,!0),t}static isUnboundFormControl(t){if(E.IsNullOrUndefined(t)||E.IsNullOrUndefined(t.control)||E.IsNullOrUndefined(t.control.ClassId))return!1;let r=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.containsKey(r.guidString)}static isReferencePanelSection(t){return!E.IsNullOrUndefined(t)&&!E.IsNullOrUndefined(t.Name)&&t.Name.indexOf(ve.referencePanelNamePrefix)===0}static isUnboundFormControlByIdentifier(t){return E.IsNullOrUndefined(t)||E.IsNullOrUndefined(t.guidString)?!1:e.UnboundControlIds.containsKey(t.guidString)}static getUnboundFormControlName(t){let r=T.EmptyString;if(E.IsNullOrUndefined(t)||E.IsNullOrUndefined(t.control)||E.IsNullOrUndefined(t.control.ClassId))return r;let n=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.getValue(n.guidString).toString()}static getUnboundControlNameFromIdentifier(t){return E.IsNullOrUndefined(t)||E.IsNullOrUndefined(t.guidString)?T.EmptyString:e.UnboundControlIds.getValue(t.guidString).toString()}static isSpacerControl(t){return t===R.SpacerControl}static GetRowSpan(t){let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===R.CustomControl&&!E.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}switch(e.UnboundControlIds.getValue(r.guidString)){case V.IframeControl:case V.ACIControl:case V.SocialInsightControl:return 6;case V.SubGridControl:case V.CustomControl:return 4;case V.WebResourceImageControl:return 15;case V.WebResourceHtmlControl:return 15;case V.MapsControl:return 8;case V.SearchWidgetControl:return 10;case V.NotesControl:case V.TimeLineControl:return 15;case V.TimerControl:return 2;default:}}static isLookUpControl(t){return!E.IsNullOrUndefined(t)&&t.ClassId.guidString===R.LookupControl}static isRelationshipAssistantOrLeadScoringControl(t){return!E.IsNullOrUndefined(t)&&e.isRelationshipAssistantOrLeadScoring(t.UniqueId)}static isRelationshipAssistantOrLeadScoring(t){return!E.IsNullOrUndefined(t)&&(t.guidString===Mi.RelationshipAssistant||t.guidString===Mi.PredictiveLeadScoring)}static isRelationshipAssistantControl(t){return!E.IsNullOrUndefined(t)&&e.isRelationshipAssistant(t.UniqueId)}static isRelationshipAssistant(t){return!E.IsNullOrUndefined(t)&&t.guidString===Mi.RelationshipAssistant}static getUniqueIdentifierForControl(t){if(E.IsNullOrUndefined(t))return null;let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===R.CustomControl&&!E.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}return r}}});var wl,Lb=I(()=>{"use strict";wl=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,kb,Mb,fn,Ub,Bb,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"})(kb||(kb={}));(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"})(Mb||(Mb={}));(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"})(fn||(fn={}));(function(e){e[e.None=0]="None",e[e.SystemRequired=1]="SystemRequired",e[e.ApplicationRequired=2]="ApplicationRequired",e[e.Recommended=3]="Recommended"})(Ub||(Ub={}));(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"})(Bb||(Bb={}))});var Bi,$b=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 qb(e){return{...e,extractConfig:t=>zL(t,Object.keys(e.fallback))}}function zL(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(($H,Gb)=>{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{}}}),Vb=function(){return go};Object.setPrototypeOf(Vb,go);Gb.exports=Vb});var jb=g((qH,Wb)=>{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{}}}),zb=function(){return vo};Object.setPrototypeOf(zb,vo);Wb.exports=zb});var pp=g((VH,Qb)=>{var bo=new Proxy(function(){return bo},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:bo},apply:function(){return bo},construct:function(){return{}}}),Hb=function(){return bo};Object.setPrototypeOf(Hb,bo);Qb.exports=Hb});var Xb=g((GH,Jb)=>{function WL(){this.__data__=[],this.size=0}Jb.exports=WL});var $i=g((zH,Kb)=>{function jL(e,t){return e===t||e!==e&&t!==t}Kb.exports=jL});var yo=g((WH,Yb)=>{var HL=$i();function QL(e,t){for(var r=e.length;r--;)if(HL(e[r][0],t))return r;return-1}Yb.exports=QL});var ey=g((jH,Zb)=>{var JL=yo(),XL=Array.prototype,KL=XL.splice;function YL(e){var t=this.__data__,r=JL(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():KL.call(t,r,1),--this.size,!0}Zb.exports=YL});var ry=g((HH,ty)=>{var ZL=yo();function ek(e){var t=this.__data__,r=ZL(t,e);return r<0?void 0:t[r][1]}ty.exports=ek});var iy=g((QH,ny)=>{var tk=yo();function rk(e){return tk(this.__data__,e)>-1}ny.exports=rk});var oy=g((JH,ay)=>{var nk=yo();function ik(e,t){var r=this.__data__,n=nk(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}ay.exports=ik});var wo=g((XH,sy)=>{var ak=Xb(),ok=ey(),sk=ry(),lk=iy(),uk=oy();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=ak;qi.prototype.delete=ok;qi.prototype.get=sk;qi.prototype.has=lk;qi.prototype.set=uk;sy.exports=qi});var uy=g((KH,ly)=>{var ck=wo();function dk(){this.__data__=new ck,this.size=0}ly.exports=dk});var dy=g((YH,cy)=>{function pk(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}cy.exports=pk});var fy=g((ZH,py)=>{function fk(e){return this.__data__.get(e)}py.exports=fk});var hy=g((eQ,my)=>{function mk(e){return this.__data__.has(e)}my.exports=mk});var fp=g((tQ,gy)=>{var hk=typeof global=="object"&&global&&global.Object===Object&&global;gy.exports=hk});var tr=g((rQ,vy)=>{var gk=fp(),vk=typeof self=="object"&&self&&self.Object===Object&&self,bk=gk||vk||Function("return this")();vy.exports=bk});var Ao=g((nQ,by)=>{var yk=tr(),wk=yk.Symbol;by.exports=wk});var Cy=g((iQ,Ay)=>{var yy=Ao(),wy=Object.prototype,Ak=wy.hasOwnProperty,Ck=wy.toString,Co=yy?yy.toStringTag:void 0;function Sk(e){var t=Ak.call(e,Co),r=e[Co];try{e[Co]=void 0;var n=!0}catch{}var i=Ck.call(e);return n&&(t?e[Co]=r:delete e[Co]),i}Ay.exports=Sk});var Ny=g((aQ,Sy)=>{var Nk=Object.prototype,Ek=Nk.toString;function Dk(e){return Ek.call(e)}Sy.exports=Dk});var Qn=g((oQ,Iy)=>{var Ey=Ao(),Ik=Cy(),_k=Ny(),Pk="[object Null]",Tk="[object Undefined]",Dy=Ey?Ey.toStringTag:void 0;function Ok(e){return e==null?e===void 0?Tk:Pk:Dy&&Dy in Object(e)?Ik(e):_k(e)}Iy.exports=Ok});var Vr=g((sQ,_y)=>{function Rk(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}_y.exports=Rk});var Al=g((lQ,Py)=>{var xk=Qn(),Fk=Vr(),Lk="[object AsyncFunction]",kk="[object Function]",Mk="[object GeneratorFunction]",Uk="[object Proxy]";function Bk(e){if(!Fk(e))return!1;var t=xk(e);return t==kk||t==Mk||t==Lk||t==Uk}Py.exports=Bk});var Oy=g((uQ,Ty)=>{var $k=tr(),qk=$k["__core-js_shared__"];Ty.exports=qk});var Fy=g((cQ,xy)=>{var mp=Oy(),Ry=(function(){var e=/[^.]+$/.exec(mp&&mp.keys&&mp.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function Vk(e){return!!Ry&&Ry in e}xy.exports=Vk});var hp=g((dQ,Ly)=>{var Gk=Function.prototype,zk=Gk.toString;function Wk(e){if(e!=null){try{return zk.call(e)}catch{}try{return e+""}catch{}}return""}Ly.exports=Wk});var My=g((pQ,ky)=>{var jk=Al(),Hk=Fy(),Qk=Vr(),Jk=hp(),Xk=/[\\^$.*+?()[\]{}|]/g,Kk=/^\[object .+?Constructor\]$/,Yk=Function.prototype,Zk=Object.prototype,eM=Yk.toString,tM=Zk.hasOwnProperty,rM=RegExp("^"+eM.call(tM).replace(Xk,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function nM(e){if(!Qk(e)||Hk(e))return!1;var t=jk(e)?rM:Kk;return t.test(Jk(e))}ky.exports=nM});var By=g((fQ,Uy)=>{function iM(e,t){return e?.[t]}Uy.exports=iM});var mn=g((mQ,$y)=>{var aM=My(),oM=By();function sM(e,t){var r=oM(e,t);return aM(r)?r:void 0}$y.exports=sM});var Cl=g((hQ,qy)=>{var lM=mn(),uM=tr(),cM=lM(uM,"Map");qy.exports=cM});var So=g((gQ,Vy)=>{var dM=mn(),pM=dM(Object,"create");Vy.exports=pM});var Wy=g((vQ,zy)=>{var Gy=So();function fM(){this.__data__=Gy?Gy(null):{},this.size=0}zy.exports=fM});var Hy=g((bQ,jy)=>{function mM(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}jy.exports=mM});var Jy=g((yQ,Qy)=>{var hM=So(),gM="__lodash_hash_undefined__",vM=Object.prototype,bM=vM.hasOwnProperty;function yM(e){var t=this.__data__;if(hM){var r=t[e];return r===gM?void 0:r}return bM.call(t,e)?t[e]:void 0}Qy.exports=yM});var Ky=g((wQ,Xy)=>{var wM=So(),AM=Object.prototype,CM=AM.hasOwnProperty;function SM(e){var t=this.__data__;return wM?t[e]!==void 0:CM.call(t,e)}Xy.exports=SM});var Zy=g((AQ,Yy)=>{var NM=So(),EM="__lodash_hash_undefined__";function DM(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=NM&&t===void 0?EM:t,this}Yy.exports=DM});var tw=g((CQ,ew)=>{var IM=Wy(),_M=Hy(),PM=Jy(),TM=Ky(),OM=Zy();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=_M;Vi.prototype.get=PM;Vi.prototype.has=TM;Vi.prototype.set=OM;ew.exports=Vi});var iw=g((SQ,nw)=>{var rw=tw(),RM=wo(),xM=Cl();function FM(){this.size=0,this.__data__={hash:new rw,map:new(xM||RM),string:new rw}}nw.exports=FM});var ow=g((NQ,aw)=>{function LM(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}aw.exports=LM});var No=g((EQ,sw)=>{var kM=ow();function MM(e,t){var r=e.__data__;return kM(t)?r[typeof t=="string"?"string":"hash"]:r.map}sw.exports=MM});var uw=g((DQ,lw)=>{var UM=No();function BM(e){var t=UM(this,e).delete(e);return this.size-=t?1:0,t}lw.exports=BM});var dw=g((IQ,cw)=>{var $M=No();function qM(e){return $M(this,e).get(e)}cw.exports=qM});var fw=g((_Q,pw)=>{var VM=No();function GM(e){return VM(this,e).has(e)}pw.exports=GM});var hw=g((PQ,mw)=>{var zM=No();function WM(e,t){var r=zM(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}mw.exports=WM});var Sl=g((TQ,gw)=>{var jM=iw(),HM=uw(),QM=dw(),JM=fw(),XM=hw();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=jM;Gi.prototype.delete=HM;Gi.prototype.get=QM;Gi.prototype.has=JM;Gi.prototype.set=XM;gw.exports=Gi});var bw=g((OQ,vw)=>{var KM=wo(),YM=Cl(),ZM=Sl(),eU=200;function tU(e,t){var r=this.__data__;if(r instanceof KM){var n=r.__data__;if(!YM||n.length<eU-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new ZM(n)}return r.set(e,t),this.size=r.size,this}vw.exports=tU});var gp=g((RQ,yw)=>{var rU=wo(),nU=uy(),iU=dy(),aU=fy(),oU=hy(),sU=bw();function zi(e){var t=this.__data__=new rU(e);this.size=t.size}zi.prototype.clear=nU;zi.prototype.delete=iU;zi.prototype.get=aU;zi.prototype.has=oU;zi.prototype.set=sU;yw.exports=zi});var Aw=g((xQ,ww)=>{var lU="__lodash_hash_undefined__";function uU(e){return this.__data__.set(e,lU),this}ww.exports=uU});var Sw=g((FQ,Cw)=>{function cU(e){return this.__data__.has(e)}Cw.exports=cU});var Ew=g((LQ,Nw)=>{var dU=Sl(),pU=Aw(),fU=Sw();function Nl(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new dU;++t<r;)this.add(e[t])}Nl.prototype.add=Nl.prototype.push=pU;Nl.prototype.has=fU;Nw.exports=Nl});var Iw=g((kQ,Dw)=>{function mU(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}Dw.exports=mU});var Pw=g((MQ,_w)=>{function hU(e,t){return e.has(t)}_w.exports=hU});var vp=g((UQ,Tw)=>{var gU=Ew(),vU=Iw(),bU=Pw(),yU=1,wU=2;function AU(e,t,r,n,i,a){var o=r&yU,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,m=r&wU?new gU:void 0;for(a.set(e,t),a.set(t,e);++d<s;){var h=e[d],w=t[d];if(n)var y=o?n(w,h,d,t,e,a):n(h,w,d,e,t,a);if(y!==void 0){if(y)continue;p=!1;break}if(m){if(!vU(t,function(N,D){if(!bU(m,D)&&(h===N||i(h,N,r,n,a)))return m.push(D)})){p=!1;break}}else if(!(h===w||i(h,w,r,n,a))){p=!1;break}}return a.delete(e),a.delete(t),p}Tw.exports=AU});var bp=g((BQ,Ow)=>{var CU=tr(),SU=CU.Uint8Array;Ow.exports=SU});var xw=g(($Q,Rw)=>{function NU(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}Rw.exports=NU});var Lw=g((qQ,Fw)=>{function EU(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}Fw.exports=EU});var $w=g((VQ,Bw)=>{var kw=Ao(),Mw=bp(),DU=$i(),IU=vp(),_U=xw(),PU=Lw(),TU=1,OU=2,RU="[object Boolean]",xU="[object Date]",FU="[object Error]",LU="[object Map]",kU="[object Number]",MU="[object RegExp]",UU="[object Set]",BU="[object String]",$U="[object Symbol]",qU="[object ArrayBuffer]",VU="[object DataView]",Uw=kw?kw.prototype:void 0,yp=Uw?Uw.valueOf:void 0;function GU(e,t,r,n,i,a,o){switch(r){case VU:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case qU:return!(e.byteLength!=t.byteLength||!a(new Mw(e),new Mw(t)));case RU:case xU:case kU:return DU(+e,+t);case FU:return e.name==t.name&&e.message==t.message;case MU:case BU:return e==t+"";case LU:var s=_U;case UU:var l=n&TU;if(s||(s=PU),e.size!=t.size&&!l)return!1;var u=o.get(e);if(u)return u==t;n|=OU,o.set(e,t);var c=IU(s(e),s(t),n,i,a,o);return o.delete(e),c;case $U:if(yp)return yp.call(e)==yp.call(t)}return!1}Bw.exports=GU});var Vw=g((GQ,qw)=>{function zU(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}qw.exports=zU});var hn=g((zQ,Gw)=>{var WU=Array.isArray;Gw.exports=WU});var Ww=g((WQ,zw)=>{var jU=Vw(),HU=hn();function QU(e,t,r){var n=t(e);return HU(e)?n:jU(n,r(e))}zw.exports=QU});var Hw=g((jQ,jw)=>{function JU(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}jw.exports=JU});var Jw=g((HQ,Qw)=>{function XU(){return[]}Qw.exports=XU});var Yw=g((QQ,Kw)=>{var KU=Hw(),YU=Jw(),ZU=Object.prototype,eB=ZU.propertyIsEnumerable,Xw=Object.getOwnPropertySymbols,tB=Xw?function(e){return e==null?[]:(e=Object(e),KU(Xw(e),function(t){return eB.call(e,t)}))}:YU;Kw.exports=tB});var eA=g((JQ,Zw)=>{function rB(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}Zw.exports=rB});var gn=g((XQ,tA)=>{function nB(e){return e!=null&&typeof e=="object"}tA.exports=nB});var nA=g((KQ,rA)=>{var iB=Qn(),aB=gn(),oB="[object Arguments]";function sB(e){return aB(e)&&iB(e)==oB}rA.exports=sB});var wp=g((YQ,oA)=>{var iA=nA(),lB=gn(),aA=Object.prototype,uB=aA.hasOwnProperty,cB=aA.propertyIsEnumerable,dB=iA((function(){return arguments})())?iA:function(e){return lB(e)&&uB.call(e,"callee")&&!cB.call(e,"callee")};oA.exports=dB});var lA=g((ZQ,sA)=>{function pB(){return!1}sA.exports=pB});var El=g((Eo,Wi)=>{var fB=tr(),mB=lA(),dA=typeof Eo=="object"&&Eo&&!Eo.nodeType&&Eo,uA=dA&&typeof Wi=="object"&&Wi&&!Wi.nodeType&&Wi,hB=uA&&uA.exports===dA,cA=hB?fB.Buffer:void 0,gB=cA?cA.isBuffer:void 0,vB=gB||mB;Wi.exports=vB});var Dl=g((eJ,pA)=>{var bB=9007199254740991,yB=/^(?:0|[1-9]\d*)$/;function wB(e,t){var r=typeof e;return t=t??bB,!!t&&(r=="number"||r!="symbol"&&yB.test(e))&&e>-1&&e%1==0&&e<t}pA.exports=wB});var Ap=g((tJ,fA)=>{var AB=9007199254740991;function CB(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=AB}fA.exports=CB});var hA=g((rJ,mA)=>{var SB=Qn(),NB=Ap(),EB=gn(),DB="[object Arguments]",IB="[object Array]",_B="[object Boolean]",PB="[object Date]",TB="[object Error]",OB="[object Function]",RB="[object Map]",xB="[object Number]",FB="[object Object]",LB="[object RegExp]",kB="[object Set]",MB="[object String]",UB="[object WeakMap]",BB="[object ArrayBuffer]",$B="[object DataView]",qB="[object Float32Array]",VB="[object Float64Array]",GB="[object Int8Array]",zB="[object Int16Array]",WB="[object Int32Array]",jB="[object Uint8Array]",HB="[object Uint8ClampedArray]",QB="[object Uint16Array]",JB="[object Uint32Array]",fe={};fe[qB]=fe[VB]=fe[GB]=fe[zB]=fe[WB]=fe[jB]=fe[HB]=fe[QB]=fe[JB]=!0;fe[DB]=fe[IB]=fe[BB]=fe[_B]=fe[$B]=fe[PB]=fe[TB]=fe[OB]=fe[RB]=fe[xB]=fe[FB]=fe[LB]=fe[kB]=fe[MB]=fe[UB]=!1;function XB(e){return EB(e)&&NB(e.length)&&!!fe[SB(e)]}mA.exports=XB});var vA=g((nJ,gA)=>{function KB(e){return function(t){return e(t)}}gA.exports=KB});var yA=g((Do,ji)=>{var YB=fp(),bA=typeof Do=="object"&&Do&&!Do.nodeType&&Do,Io=bA&&typeof ji=="object"&&ji&&!ji.nodeType&&ji,ZB=Io&&Io.exports===bA,Cp=ZB&&YB.process,e$=(function(){try{var e=Io&&Io.require&&Io.require("util").types;return e||Cp&&Cp.binding&&Cp.binding("util")}catch{}})();ji.exports=e$});var Il=g((iJ,CA)=>{var t$=hA(),r$=vA(),wA=yA(),AA=wA&&wA.isTypedArray,n$=AA?r$(AA):t$;CA.exports=n$});var Sp=g((aJ,SA)=>{var i$=eA(),a$=wp(),o$=hn(),s$=El(),l$=Dl(),u$=Il(),c$=Object.prototype,d$=c$.hasOwnProperty;function p$(e,t){var r=o$(e),n=!r&&a$(e),i=!r&&!n&&s$(e),a=!r&&!n&&!i&&u$(e),o=r||n||i||a,s=o?i$(e.length,String):[],l=s.length;for(var u in e)(t||d$.call(e,u))&&!(o&&(u=="length"||i&&(u=="offset"||u=="parent")||a&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||l$(u,l)))&&s.push(u);return s}SA.exports=p$});var _l=g((oJ,NA)=>{var f$=Object.prototype;function m$(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||f$;return e===r}NA.exports=m$});var Np=g((sJ,EA)=>{function h$(e,t){return function(r){return e(t(r))}}EA.exports=h$});var IA=g((lJ,DA)=>{var g$=Np(),v$=g$(Object.keys,Object);DA.exports=v$});var PA=g((uJ,_A)=>{var b$=_l(),y$=IA(),w$=Object.prototype,A$=w$.hasOwnProperty;function C$(e){if(!b$(e))return y$(e);var t=[];for(var r in Object(e))A$.call(e,r)&&r!="constructor"&&t.push(r);return t}_A.exports=C$});var _o=g((cJ,TA)=>{var S$=Al(),N$=Ap();function E$(e){return e!=null&&N$(e.length)&&!S$(e)}TA.exports=E$});var RA=g((dJ,OA)=>{var D$=Sp(),I$=PA(),_$=_o();function P$(e){return _$(e)?D$(e):I$(e)}OA.exports=P$});var FA=g((pJ,xA)=>{var T$=Ww(),O$=Yw(),R$=RA();function x$(e){return T$(e,R$,O$)}xA.exports=x$});var MA=g((fJ,kA)=>{var LA=FA(),F$=1,L$=Object.prototype,k$=L$.hasOwnProperty;function M$(e,t,r,n,i,a){var o=r&F$,s=LA(e),l=s.length,u=LA(t),c=u.length;if(l!=c&&!o)return!1;for(var d=l;d--;){var p=s[d];if(!(o?p in t:k$.call(t,p)))return!1}var m=a.get(e),h=a.get(t);if(m&&h)return m==t&&h==e;var w=!0;a.set(e,t),a.set(t,e);for(var y=o;++d<l;){p=s[d];var N=e[p],D=t[p];if(n)var x=o?n(D,N,p,t,e,a):n(N,D,p,e,t,a);if(!(x===void 0?N===D||i(N,D,r,n,a):x)){w=!1;break}y||(y=p=="constructor")}if(w&&!y){var F=e.constructor,q=t.constructor;F!=q&&"constructor"in e&&"constructor"in t&&!(typeof F=="function"&&F instanceof F&&typeof q=="function"&&q instanceof q)&&(w=!1)}return a.delete(e),a.delete(t),w}kA.exports=M$});var BA=g((mJ,UA)=>{var U$=mn(),B$=tr(),$$=U$(B$,"DataView");UA.exports=$$});var qA=g((hJ,$A)=>{var q$=mn(),V$=tr(),G$=q$(V$,"Promise");$A.exports=G$});var GA=g((gJ,VA)=>{var z$=mn(),W$=tr(),j$=z$(W$,"Set");VA.exports=j$});var WA=g((vJ,zA)=>{var H$=mn(),Q$=tr(),J$=H$(Q$,"WeakMap");zA.exports=J$});var ZA=g((bJ,YA)=>{var Ep=BA(),Dp=Cl(),Ip=qA(),_p=GA(),Pp=WA(),KA=Qn(),Hi=hp(),jA="[object Map]",X$="[object Object]",HA="[object Promise]",QA="[object Set]",JA="[object WeakMap]",XA="[object DataView]",K$=Hi(Ep),Y$=Hi(Dp),Z$=Hi(Ip),eq=Hi(_p),tq=Hi(Pp),Jn=KA;(Ep&&Jn(new Ep(new ArrayBuffer(1)))!=XA||Dp&&Jn(new Dp)!=jA||Ip&&Jn(Ip.resolve())!=HA||_p&&Jn(new _p)!=QA||Pp&&Jn(new Pp)!=JA)&&(Jn=function(e){var t=KA(e),r=t==X$?e.constructor:void 0,n=r?Hi(r):"";if(n)switch(n){case K$:return XA;case Y$:return jA;case Z$:return HA;case eq:return QA;case tq:return JA}return t});YA.exports=Jn});var sC=g((yJ,oC)=>{var Tp=gp(),rq=vp(),nq=$w(),iq=MA(),eC=ZA(),tC=hn(),rC=El(),aq=Il(),oq=1,nC="[object Arguments]",iC="[object Array]",Pl="[object Object]",sq=Object.prototype,aC=sq.hasOwnProperty;function lq(e,t,r,n,i,a){var o=tC(e),s=tC(t),l=o?iC:eC(e),u=s?iC:eC(t);l=l==nC?Pl:l,u=u==nC?Pl:u;var c=l==Pl,d=u==Pl,p=l==u;if(p&&rC(e)){if(!rC(t))return!1;o=!0,c=!1}if(p&&!c)return a||(a=new Tp),o||aq(e)?rq(e,t,r,n,i,a):nq(e,t,l,r,n,i,a);if(!(r&oq)){var m=c&&aC.call(e,"__wrapped__"),h=d&&aC.call(t,"__wrapped__");if(m||h){var w=m?e.value():e,y=h?t.value():t;return a||(a=new Tp),i(w,y,r,n,a)}}return p?(a||(a=new Tp),iq(e,t,r,n,i,a)):!1}oC.exports=lq});var dC=g((wJ,cC)=>{var uq=sC(),lC=gn();function uC(e,t,r,n,i){return e===t?!0:e==null||t==null||!lC(e)&&!lC(t)?e!==e&&t!==t:uq(e,t,r,n,uC,i)}cC.exports=uC});var fC=g((AJ,pC)=>{var cq=dC();function dq(e,t){return cq(e,t)}pC.exports=dq});var Op=g((CJ,mC)=>{var pq=mn(),fq=(function(){try{var e=pq(Object,"defineProperty");return e({},"",{}),e}catch{}})();mC.exports=fq});var Tl=g((SJ,gC)=>{var hC=Op();function mq(e,t,r){t=="__proto__"&&hC?hC(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}gC.exports=mq});var Rp=g((NJ,vC)=>{var hq=Tl(),gq=$i();function vq(e,t,r){(r!==void 0&&!gq(e[t],r)||r===void 0&&!(t in e))&&hq(e,t,r)}vC.exports=vq});var yC=g((EJ,bC)=>{function bq(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}}bC.exports=bq});var AC=g((DJ,wC)=>{var yq=yC(),wq=yq();wC.exports=wq});var DC=g((Po,Qi)=>{var Aq=tr(),EC=typeof Po=="object"&&Po&&!Po.nodeType&&Po,CC=EC&&typeof Qi=="object"&&Qi&&!Qi.nodeType&&Qi,Cq=CC&&CC.exports===EC,SC=Cq?Aq.Buffer:void 0,NC=SC?SC.allocUnsafe:void 0;function Sq(e,t){if(t)return e.slice();var r=e.length,n=NC?NC(r):new e.constructor(r);return e.copy(n),n}Qi.exports=Sq});var PC=g((IJ,_C)=>{var IC=bp();function Nq(e){var t=new e.constructor(e.byteLength);return new IC(t).set(new IC(e)),t}_C.exports=Nq});var OC=g((_J,TC)=>{var Eq=PC();function Dq(e,t){var r=t?Eq(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}TC.exports=Dq});var xC=g((PJ,RC)=>{function Iq(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}RC.exports=Iq});var kC=g((TJ,LC)=>{var _q=Vr(),FC=Object.create,Pq=(function(){function e(){}return function(t){if(!_q(t))return{};if(FC)return FC(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})();LC.exports=Pq});var xp=g((OJ,MC)=>{var Tq=Np(),Oq=Tq(Object.getPrototypeOf,Object);MC.exports=Oq});var BC=g((RJ,UC)=>{var Rq=kC(),xq=xp(),Fq=_l();function Lq(e){return typeof e.constructor=="function"&&!Fq(e)?Rq(xq(e)):{}}UC.exports=Lq});var qC=g((xJ,$C)=>{var kq=_o(),Mq=gn();function Uq(e){return Mq(e)&&kq(e)}$C.exports=Uq});var zC=g((FJ,GC)=>{var Bq=Qn(),$q=xp(),qq=gn(),Vq="[object Object]",Gq=Function.prototype,zq=Object.prototype,VC=Gq.toString,Wq=zq.hasOwnProperty,jq=VC.call(Object);function Hq(e){if(!qq(e)||Bq(e)!=Vq)return!1;var t=$q(e);if(t===null)return!0;var r=Wq.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&VC.call(r)==jq}GC.exports=Hq});var Fp=g((LJ,WC)=>{function Qq(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}WC.exports=Qq});var Lp=g((kJ,jC)=>{var Jq=Tl(),Xq=$i(),Kq=Object.prototype,Yq=Kq.hasOwnProperty;function Zq(e,t,r){var n=e[t];(!(Yq.call(e,t)&&Xq(n,r))||r===void 0&&!(t in e))&&Jq(e,t,r)}jC.exports=Zq});var QC=g((MJ,HC)=>{var e3=Lp(),t3=Tl();function r3(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?t3(r,s,l):e3(r,s,l)}return r}HC.exports=r3});var XC=g((UJ,JC)=>{function n3(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}JC.exports=n3});var YC=g((BJ,KC)=>{var i3=Vr(),a3=_l(),o3=XC(),s3=Object.prototype,l3=s3.hasOwnProperty;function u3(e){if(!i3(e))return o3(e);var t=a3(e),r=[];for(var n in e)n=="constructor"&&(t||!l3.call(e,n))||r.push(n);return r}KC.exports=u3});var kp=g(($J,ZC)=>{var c3=Sp(),d3=YC(),p3=_o();function f3(e){return p3(e)?c3(e,!0):d3(e)}ZC.exports=f3});var tS=g((qJ,eS)=>{var m3=QC(),h3=kp();function g3(e){return m3(e,h3(e))}eS.exports=g3});var sS=g((VJ,oS)=>{var rS=Rp(),v3=DC(),b3=OC(),y3=xC(),w3=BC(),nS=wp(),iS=hn(),A3=qC(),C3=El(),S3=Al(),N3=Vr(),E3=zC(),D3=Il(),aS=Fp(),I3=tS();function _3(e,t,r,n,i,a,o){var s=aS(e,r),l=aS(t,r),u=o.get(l);if(u){rS(e,r,u);return}var c=a?a(s,l,r+"",e,t,o):void 0,d=c===void 0;if(d){var p=iS(l),m=!p&&C3(l),h=!p&&!m&&D3(l);c=l,p||m||h?iS(s)?c=s:A3(s)?c=y3(s):m?(d=!1,c=v3(l,!0)):h?(d=!1,c=b3(l,!0)):c=[]:E3(l)||nS(l)?(c=s,nS(s)?c=I3(s):(!N3(s)||S3(s))&&(c=w3(l))):d=!1}d&&(o.set(l,c),i(c,l,n,a,o),o.delete(l)),rS(e,r,c)}oS.exports=_3});var Mp=g((GJ,uS)=>{var P3=gp(),T3=Rp(),O3=AC(),R3=sS(),x3=Vr(),F3=kp(),L3=Fp();function lS(e,t,r,n,i){e!==t&&O3(t,function(a,o){if(i||(i=new P3),x3(a))R3(e,t,o,r,lS,n,i);else{var s=n?n(L3(e,o),a,o+"",e,t,i):void 0;s===void 0&&(s=a),T3(e,o,s)}},F3)}uS.exports=lS});var Up=g((zJ,cS)=>{function k3(e){return e}cS.exports=k3});var pS=g((WJ,dS)=>{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)}dS.exports=M3});var hS=g((jJ,mS)=>{var U3=pS(),fS=Math.max;function B3(e,t,r){return t=fS(t===void 0?e.length-1:t,0),function(){for(var n=arguments,i=-1,a=fS(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),U3(e,this,s)}}mS.exports=B3});var vS=g((HJ,gS)=>{function $3(e){return function(){return e}}gS.exports=$3});var wS=g((QJ,yS)=>{var q3=vS(),bS=Op(),V3=Up(),G3=bS?function(e,t){return bS(e,"toString",{configurable:!0,enumerable:!1,value:q3(t),writable:!0})}:V3;yS.exports=G3});var CS=g((JJ,AS)=>{var z3=800,W3=16,j3=Date.now;function H3(e){var t=0,r=0;return function(){var n=j3(),i=W3-(n-r);if(r=n,i>0){if(++t>=z3)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}AS.exports=H3});var NS=g((XJ,SS)=>{var Q3=wS(),J3=CS(),X3=J3(Q3);SS.exports=X3});var DS=g((KJ,ES)=>{var K3=Up(),Y3=hS(),Z3=NS();function e4(e,t){return Z3(Y3(e,t,K3),e+"")}ES.exports=e4});var _S=g((YJ,IS)=>{var t4=$i(),r4=_o(),n4=Dl(),i4=Vr();function a4(e,t,r){if(!i4(r))return!1;var n=typeof t;return(n=="number"?r4(r)&&n4(t,r.length):n=="string"&&t in r)?t4(r[t],e):!1}IS.exports=a4});var Bp=g((ZJ,PS)=>{var o4=DS(),s4=_S();function l4(e){return o4(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&&s4(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})}PS.exports=l4});var OS=g((eX,TS)=>{var u4=Mp(),c4=Bp(),d4=c4(function(e,t,r,n){u4(e,t,r,n)});TS.exports=d4});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 xS(e,t,r="PROD"){let n=i=>`ShellSettings_ECS_ClientCache_${e}_${RS.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 RS,p4,FS=I(()=>{"use strict";RS=le(pp()),p4=le(dp());});var $p,LS=I(()=>{"use strict";ll();$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 MS,US,BS,$S,qp,f4,Ol,kS,Vp=I(()=>{"use strict";MS=le(dp()),US=le(jb()),BS=le(pp()),$S=le(fC()),qp=le(OS());To();FS();LS();f4=60*1e3,Ol=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 US.default;init=async({clientVersion:t,getFilters:r,cacheStorage:n=MS.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:[BS.EcsConfigType.Default],hosts:[this.ecsEndpoint],initialAppActiveState:!0,getEcsParameters:o,databaseInterface:xS(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*f4)};getConfig=t=>{let r=this.getMergedClientConfigByTeamName(t.teamName),n=r?t.extractConfig(r):{};return(0,qp.default)({},t.fallback,n,t.override,kS)};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,$S.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,kS);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})}},kS=(e,t)=>{if(Array.isArray(t))return t}});var VS=g((uX,qS)=>{"use strict";var m4=()=>{let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e};qS.exports=m4});var Gp=g((cX,zS)=>{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{}}}),GS=function(){return Oo};Object.setPrototypeOf(GS,Oo);zS.exports=GS});var HS=g((dX,jS)=>{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{}}}),WS=function(){return Ro};Object.setPrototypeOf(WS,Ro);jS.exports=WS});var eN=g((pX,ZS)=>{"use strict";var zp=HS(),h4={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},g4={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},v4={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},KS={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},Wp={};Wp[zp.ForwardRef]=v4;Wp[zp.Memo]=KS;function QS(e){return zp.isMemo(e)?KS:Wp[e.$$typeof]||h4}var b4=Object.defineProperty,y4=Object.getOwnPropertyNames,JS=Object.getOwnPropertySymbols,w4=Object.getOwnPropertyDescriptor,A4=Object.getPrototypeOf,XS=Object.prototype;function YS(e,t,r){if(typeof t!="string"){if(XS){var n=A4(t);n&&n!==XS&&YS(e,n,r)}var i=y4(t);JS&&(i=i.concat(JS(t)));for(var a=QS(e),o=QS(t),s=0;s<i.length;++s){var l=i[s];if(!g4[l]&&!(r&&r[l])&&!(o&&o[l])&&!(a&&a[l])){var u=w4(t,l);try{b4(e,l,u)}catch{}}}}return e}ZS.exports=YS});function rN(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 nN(e){return function(t,r){return rN(e,t,r)}}function iN(e,t,r,n){let i=a=>{let o=rN(e,t,n),s={...a,...o};return Ji.default.createElement(r,{...s})};return(0,tN.default)(i,r),i.displayName=`WithFeature(${r.name})`,i}function aN(e,t,r,n){return t.reduce((i,a)=>iN(e,a,i,n),r)}function oN(e){return function(t,r,n){return iN(e,t,r,n)}}var tN,Ji,jp=I(()=>{"use strict";tN=le(eN()),Ji=le(Gp());To();});var lN=g((hX,sN)=>{var C4=Mp(),S4=Bp(),N4=S4(function(e,t,r){C4(e,t,r)});sN.exports=N4});var Rl=g((gX,uN)=>{var E4=Qn(),D4=gn(),I4="[object Symbol]";function _4(e){return typeof e=="symbol"||D4(e)&&E4(e)==I4}uN.exports=_4});var dN=g((vX,cN)=>{var P4=hn(),T4=Rl(),O4=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,R4=/^\w*$/;function x4(e,t){if(P4(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||T4(e)?!0:R4.test(e)||!O4.test(e)||t!=null&&e in Object(t)}cN.exports=x4});var mN=g((bX,fN)=>{var pN=Sl(),F4="Expected a function";function Hp(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(F4);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||pN),r}Hp.Cache=pN;fN.exports=Hp});var gN=g((yX,hN)=>{var L4=mN(),k4=500;function M4(e){var t=L4(e,function(n){return r.size===k4&&r.clear(),n}),r=t.cache;return t}hN.exports=M4});var bN=g((wX,vN)=>{var U4=gN(),B4=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,$4=/\\(\\)?/g,q4=U4(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(B4,function(r,n,i,a){t.push(i?a.replace($4,"$1"):n||r)}),t});vN.exports=q4});var wN=g((AX,yN)=>{function V4(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}yN.exports=V4});var DN=g((CX,EN)=>{var AN=Ao(),G4=wN(),z4=hn(),W4=Rl(),j4=1/0,CN=AN?AN.prototype:void 0,SN=CN?CN.toString:void 0;function NN(e){if(typeof e=="string")return e;if(z4(e))return G4(e,NN)+"";if(W4(e))return SN?SN.call(e):"";var t=e+"";return t=="0"&&1/e==-j4?"-0":t}EN.exports=NN});var _N=g((SX,IN)=>{var H4=DN();function Q4(e){return e==null?"":H4(e)}IN.exports=Q4});var TN=g((NX,PN)=>{var J4=hn(),X4=dN(),K4=bN(),Y4=_N();function Z4(e,t){return J4(e)?e:X4(e,t)?[e]:K4(Y4(e))}PN.exports=Z4});var RN=g((EX,ON)=>{var e5=Rl(),t5=1/0;function r5(e){if(typeof e=="string"||e5(e))return e;var t=e+"";return t=="0"&&1/e==-t5?"-0":t}ON.exports=r5});var LN=g((DX,FN)=>{var n5=Lp(),i5=TN(),a5=Dl(),xN=Vr(),o5=RN();function s5(e,t,r,n){if(!xN(e))return e;t=i5(t,e);for(var i=-1,a=t.length,o=a-1,s=e;s!=null&&++i<a;){var l=o5(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=xN(c)?c:a5(t[i+1])?[]:{})}n5(s,l,u),s=s[l]}return e}FN.exports=s5});var MN=g((IX,kN)=>{var l5=LN();function u5(e,t,r){return e==null?e:l5(e,t,r)}kN.exports=u5});function qN(e){let{query:t}=(0,$N.default)(window.location.href,!0);return d5(e,t),e}function d5(e,t){let r=c5+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+VN,u={};if(a===r)u=s;else if(a.startsWith(l)){let c=a.substring(l.length);(0,BN.default)(u,c,s)}(0,UN.default)(i,u)}catch{}}),Object.keys(i).length>0&&e.overrideClientConfig(i)}var UN,BN,$N,VN,c5,GN=I(()=>{"use strict";UN=le(lN()),BN=le(MN()),$N=le(Yd());VN=".",c5="ecs"+VN});function Fl(e,t,r){let n=qN(new Ol(e,t,r));function i(a){(0,xl.useEffect)(()=>{n.init(a)},[])}return{featuresClient:n,createFeature:f5(n),useFeaturesClientInitParams:i,withFeatures:(a,o,s)=>aN(n,a,o,s)}}function f5(e){let t=nN(e),r=oN(e);return function(i){let a=qb(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 p5,xl,Qp=I(()=>{"use strict";p5=le(VS()),xl=le(Gp());cp();Vp();To();jp();GN();rp();});var zN=I(()=>{"use strict";cp();Vp();Qp();To();jp();pl();np();});function Ll(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=le(qn());});var HX,QX,JX,WN=I(()=>{"use strict";zN();Jp();({featuresClient:HX,createFeature:QX,useFeaturesClientInitParams:JX}=Fl("PowerApps-Shell-Test",Ll("shell-features")))});var QN=g((KX,HN)=>{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{}}}),jN=function(){return xo};Object.setPrototypeOf(jN,xo);HN.exports=jN});var m5,h5,JN=I(()=>{"use strict";lo();m5=le(QN()),h5=le(qn());});var XN=I(()=>{"use strict";WN();Jp();JN();});var oK,Ki,sK,KN=I(()=>{"use strict";XN();Qp();({featuresClient:oK,createFeature:Ki,useFeaturesClientInitParams:sK}=Fl("PowerApps-MakerPortal",Ll("powerapps-features")))});var YN,ZN,dK,pK,fK,mK,Xp=I(()=>{"use strict";$b();KN();({feature:YN}=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:ZN}=Ki({teamName:"MakerPortal",owners:["aansu"],description:"Enable the one grid events for form designer",createdOn:"08/21/2024",fallback:{enableOneGridEventsForFormDesigner:Bi.enableOneGridEvents}}),{feature:dK}=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:pK}=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:fK,useFeature:mK}=Ki({teamName:"MakerPortal",owners:["aansu"],description:"Enables delayed localization of custom control",createdOn:"06/08/2025",fallback:{enableDelayedLocalizationForCustomControls:Bi.enableDelayedLocalizationForCustomControls}})});var rE=g((gK,tE)=>{var Fo=new Proxy(function(){return Fo},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Fo},apply:function(){return Fo},construct:function(){return{}}}),eE=function(){return Fo};Object.setPrototypeOf(eE,Fo);tE.exports=eE});var it,vn=I(()=>{"use strict";Le();Re();nt();yl();X();We();it=class extends j{static HighestUsedIndexByClass=new Map;get colspan(){let t=this.getProperty(f.colspan);return E.IsNullOrUndefined(t)?null:parseInt(t,10)}set colspan(t){E.IsNullOrUndefined(t)||this.setProperty(f.colspan,String(t))}constructor(t,r){super(t,r)}get id(){let t=this.getProperty(f.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(f.id,`{${t.ToString()}}`)}set labelId(t){this.setProperty(f.labelId,`{${t.ToString()}}`)}get labelId(){let t=this.getProperty(f.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(f.Name)}set Name(t){this.setProperty(f.Name,t)}setDisplayName(t,r){for(let i of this.getAllLabels())if(+i.getProperty(f.languagecode)===r){i.setProperty(f.description,t);return}let n=new j(v.formLabel,null);n.setProperty(f.description,t),n.setProperty(f.languagecode,String(r)),this.addGrandChild("labels",n)}getDisplayName(t){for(let r of this.getAllLabels())if(+r.getProperty(f.languagecode)===t)return r.getProperty(f.description)}getAllLabels(){let t=this.getChildren("labels");return t.length!==1?[]:t[0].getChildren("label")}get isLocked(){return+this.getProperty(f.locklevel)==1}set isLocked(t){!this.IsUnboundControl&&this.setProperty(f.locklevel,t?"1":"0")}get availableforphone(){return this.getProcessedValue(f.availableforphone)}set availableforphone(t){E.IsNullOrUndefined(t)||!this.IsAllowedUBCForAvailableOnPhone()||this.setProperty(f.availableforphone,String(t))}get visible(){return this.getProcessedValue(f.visible)}set visible(t){E.IsNullOrUndefined(t)||!this.IsAllowedUBCForVisibleByDefault()||this.setProperty(f.visible,String(t))}isLockLevelSettable(){return!this.IsUnboundControl}get showlabel(){return this.getProcessedValue(f.showlabel)}set showlabel(t){E.IsNullOrUndefined(t)||this.setProperty(f.showlabel,String(t))}isAvailableForPhoneSettable(){return this.IsAllowedUBCForAvailableOnPhone()}isVisibleSettable(){return this.IsAllowedUBCForVisibleByDefault()}getProcessedValue(t){let r=this.getProperty(t);return E.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(f.AllowFilterOff)==="true"}set allowfilteroff(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(f.AllowFilterOff,t)}get autoresolve(){let t=this.getFirstChild(v.formControl);if(t)return t.getParam(f.AutoResolve)==="true"}set autoresolve(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(f.AutoResolve,t)}get defaultviewid(){let t=this.getFirstChild(v.formControl);return t?t.getParam(f.DefaultViewId):T.EmptyString}set defaultviewid(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(f.DefaultViewId,t)}get dependentattributename(){let t=this.getFirstChild(v.formControl);return t?t.getParam(f.DependentAttributeName):T.EmptyString}set dependentattributename(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(f.DependentAttributeName,t)}get dependentattributetype(){let t=this.getFirstChild(v.formControl);return t?t.getParam(f.DependentAttributeType):T.EmptyString}set dependentattributetype(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(f.DependentAttributeType,t)}get disablequickfind(){let t=this.getFirstChild(v.formControl);if(t)return t.getParam(f.DisableQuickFind)==="true"}set disablequickfind(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(f.DisableQuickFind,t)}get disableviewpicker(){let t=this.getFirstChild(v.formControl);if(t)return t.getParam(f.DisableViewPicker)==="true"}set disableviewpicker(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(f.DisableViewPicker,t)}get filterrelationshipname(){let t=this.getFirstChild(v.formControl);return t?t.getParam(f.FilterRelationshipName):T.EmptyString}set filterrelationshipname(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(f.FilterRelationshipName,t)}get availableviewids(){let t=this.getFirstChild(v.formControl);return t?t.getParam(f.AvailableViewIds):T.EmptyString}set availableviewids(t){let r=this.getFirstChild(v.formControl);r&&!this.IsUnboundControl&&r.setParameter(f.AvailableViewIds,t)}get IsUnboundControl(){let t=this.getFirstChild(v.formControl);if(t&&t.ClassId){let r=Me.getUniqueIdentifierForControl(t);return!E.IsNullOrUndefined(r)&&Me.isUnboundFormControlByIdentifier(r)}else return!1}IsAllowedUBCForAvailableOnPhone(){let t=this.getFirstChild(v.formControl);if(t){let n=Me.getUniqueIdentifierForControl(t).guidString,i=n===R.GridControl||n===R.TimeLineControl||n===R.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=Me.getUniqueIdentifierForControl(t).guidString,i=n===R.MapsControl||n===R.WebResourceHtmlControl||n===R.WebResourceImageControl||n===R.IframeControl||n===R.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";nt();X();We();Yi=class extends j{constructor(t,r){super(v.dependency,t),T.IsNullOrEmpty(r)||this.setDefaultProperties(r)}set id(t){this.setProperty(f.id,t)}get id(){return this.getProperty(f.id)}setDefaultProperties(t){this.id=t}}});var nE,Zi,Yp=I(()=>{"use strict";Re();Kp();X();We();vn();(function(e){e[e.Form=0]="Form",e[e.Cell=1]="Cell",e[e.Tab=2]="Tab",e[e.Control=3]="Control"})(nE||(nE={}));Zi=class extends it{constructor(t,r){super(v.formEvent,t),r&&(this.eventName=r,this.application="false",this.active="false")}set eventName(t){this.setProperty(f.Name,t)}get eventName(){return this.getProperty(f.Name)}set application(t){this.setProperty(f.application,t)}get application(){return this.getProperty(f.application)}set attribute(t){this.setProperty(f.EventAttribute,t)}get attribute(){return this.getProperty(f.EventAttribute)}set relationship(t){this.setProperty(f.Relationship,t)}get relationship(){return this.getProperty(f.Relationship)}set control(t){this.setProperty(f.Control,t)}get control(){return this.getProperty(f.Control)}set active(t){this.setProperty(f.EventActive,t)}get active(){return this.getProperty(f.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(E.IsNullOrUndefined(r)){if(t.length===0)return;this.addChild(new j(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 rr,Lo=I(()=>{"use strict";Le();so();Re();$n();X();We();Zt();rr=class extends j{previewVersion;constructor(t){super(v.formControl,t)}updatePreview(){this.previewVersion=Date.now()}get ClassId(){let t=this.getProperty(f.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(f.classid,`{${t.ToString()}}`)}get dataFieldName(){return this.getProperty(f.datafieldname)}set dataFieldName(t){this.setProperty(f.datafieldname,t)}set id(t){this.setProperty(f.id,t)}get id(){return this.getProperty(f.id)}get UniqueId(){let t=this.getProperty(f.uniqueid);return E.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(f.uniqueid,`{${t.ToString()}}`)}get isRequired(){return this.getProperty(f.isRequired)==="true"}set isRequired(t){E.IsNullOrUndefined(t)||this.setProperty(f.isRequired,String(t))}get disableMru(){return this.getParam(f.DisableMru)==="true"}set disableMru(t){E.IsNullOrUndefined(t)||this.setParameter(f.DisableMru,t)}get useMFDForCreate(){return this.getParam(f.UseMFDForCreate)==="true"}set useMFDForCreate(t){E.IsNullOrUndefined(t)||this.setParameter(f.UseMFDForCreate,t)}get useMFDForEdit(){return this.getParam(f.UseMFDForEdit)==="true"}set useMFDForEdit(t){E.IsNullOrUndefined(t)||this.setParameter(f.UseMFDForEdit,t)}get disabled(){return this.getProperty(f.disabled)==="true"}set disabled(t){E.IsNullOrUndefined(t)||this.setProperty(f.disabled,String(t))}get indicationOfSubgrid(){return this.getProperty(f.indicationOfSubgrid)==="true"}set indicationOfSubgrid(t){this.setProperty(f.indicationOfSubgrid,String(t))}getAllParameters(){let t=new ut,r=this.getFirstChild(f.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=(qr.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 j(i,o))}else n||(o=new j(t,a),o.addChild(new j(i,o)),a.addChild(o))}else if(!n){a=new j("parameters",this);let o=new j(t,a);o.addChild(new j(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)===qr.StartTag?a.substring(1):a}}}return null}get parametersNode(){let t=this.getChildren(f.parameters);return t.length===0?null:t[0]}async serializeParameters(t,r){let n=new ut;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(f.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()===ke.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";nt();xi();Lo();X();We();ea=class extends rr{constructor(t){super(t)}get targetEntityType(){return this.getParam(f.targetEntityType)||T.EmptyString}set targetEntityType(t){this.setParameter(f.targetEntityType,t)}get viewId(){return T.StripBraces(this.getParam(f.viewId))||T.EmptyString}set viewId(t){this.setParameter(f.viewId,T.AddBraces(t))}get viewIds(){return this.getParam(f.viewIds)||T.EmptyString}set viewIds(t){this.setParameter(f.viewIds,t)}get relationshipName(){return this.getParam(f.RelationshipName)||T.EmptyString}set relationshipName(t){this.setParameter(f.RelationshipName,t)}get isUserView(){return T.IsStrictTrue(this.getParam(f.isUserView))}set isUserView(t){this.setParameter(f.isUserView,t.toString())}get enableViewPicker(){return T.IsStrictTrue(this.getParam(f.enableViewPicker))}set enableViewPicker(t){this.setParameter(f.enableViewPicker,t)}get autoExpand(){return this.getParent().autoexpand&&this.getParam(f.autoExpand)===f.Auto}set autoExpand(t){let r=this.getParent();this.setParameter(f.autoExpand,t?f.Auto:f.Fixed),r.autoexpand=t}get recordsPerPage(){return this.getParam(f.recordsPerPage)?Number(this.getParam(f.recordsPerPage)):Number(f.RecordsPerPageRAControlDefault)}set recordsPerPage(t){this.setParameter(f.recordsPerPage,String(t))}get enableQuickFind(){return T.IsStrictTrue(this.getParam(f.enableQuickFind))}set enableQuickFind(t){this.setParameter(f.enableQuickFind,t)}get teamTemplateId(){return T.StripBraces(this.getParam(f.teamTemplateId))||T.EmptyString}set teamTemplateId(t){this.setParameter(f.teamTemplateId,T.AddBraces(t))}get chartId(){return this.getParam(f.visualizationId)||T.EmptyString}set chartId(t){this.setParameter(f.visualizationId,t)}get enableChartPicker(){return T.IsStrictTrue(this.getParam(f.enableChartPicker))}set enableChartPicker(t){this.setParameter(f.enableChartPicker,t)}get chartGridMode(){switch(this.getParam(f.chartGridMode)){case Ft.Chart:return Ft.Chart;case Ft.Grid:return Ft.Grid;default:return Ft.All}}set chartGridMode(t){this.setParameter(f.chartGridMode,t)}updateChartGridMode(t){t?this.chartGridMode=Ft.Chart:this.chartGridMode=this.enableChartPicker?Ft.All:Ft.Grid}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case f.targetEntityType:n.getAllChildren()[0].setNodeName("<"+r.targetEntityType);break;case f.viewId:n.getAllChildren()[0].setNodeName("<"+T.AddBraces(r.viewId));break;case f.isUserView:n.getAllChildren()[0].setNodeName("<"+r.isUserView);break;case f.enableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.enableViewPicker);break;case f.RelationshipName:let i=n.getAllChildren(),a="<"+r.relationshipName;i.length?n.getAllChildren()[0].setNodeName(a):n.addChild(new j(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(ct.dataset)?n[i].getParameters().get(ct.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";nt();xi();Lo();X();ta=class extends rr{constructor(t){super(t)}get defaultViewId(){return T.StripBraces(this.getParam(f.DefaultViewId))||T.EmptyString}set defaultViewId(t){this.setParameter(f.DefaultViewId,T.AddBraces(t))}get autoResolve(){return T.IsStrictTrue(this.getParam(f.AutoResolve))}set autoResolve(t){this.setParameter(f.AutoResolve,t)}get disableQuickFind(){return T.IsStrictTrue(this.getParam(f.DisableQuickFind))}set disableQuickFind(t){this.setParameter(f.DisableQuickFind,t)}get disableViewPicker(){return T.IsStrictTrue(this.getParam(f.DisableViewPicker))}set disableViewPicker(t){this.setParameter(f.DisableViewPicker,t)}get allowFilterOff(){return T.IsStrictTrue(this.getParam(f.AllowFilterOff))}set allowFilterOff(t){this.setParameter(f.AllowFilterOff,t)}get disableMru(){return T.IsStrictTrue(this.getParam(f.DisableMru))}set disableMru(t){this.setParameter(f.DisableMru,t)}get dependentAttributeName(){return this.getParam(f.DependentAttributeName)||T.EmptyString}set dependentAttributeName(t){this.setParameter(f.DependentAttributeName,t)}get dependentAttributeType(){return this.getParam(f.DependentAttributeType)||T.EmptyString}set dependentAttributeType(t){this.setParameter(f.DependentAttributeType,t)}get filterRelationshipName(){return this.getParam(f.FilterRelationshipName)||T.EmptyString}set filterRelationshipName(t){this.setParameter(f.FilterRelationshipName,t)}get availableViewIds(){return this.getParam(f.AvailableViewIds)||T.EmptyString}set availableViewIds(t){this.setParameter(f.AvailableViewIds,t)}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case f.datafieldname:case f.bindAttribute:n.getAllChildren()[0].setNodeName("<"+r.dataFieldName);break;case f.DefaultViewId:n.getAllChildren()[0].setNodeName("<"+T.AddBraces(r.defaultViewId));break;case f.AllowFilterOff:n.getAllChildren()[0].setNodeName("<"+r.allowFilterOff);break;case f.DisableQuickFind:n.getAllChildren()[0].setNodeName("<"+r.disableQuickFind);break;case f.DisableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.disableViewPicker);break;case f.FilterRelationshipName:n.getAllChildren()[0].setNodeName("<"+r.filterRelationshipName);break;case f.DependentAttributeName:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeName);break;case f.DependentAttributeType:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeType);break;case f.AvailableViewIds:n.getAllChildren()[0].setNodeName("<"+r.availableViewIds);break;case f.DisableMru:n.getAllChildren()[0].setNodeName("<"+r.disableMru);break;case f.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(ct.value)?n[i].getParameters().get(ct.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 iE,tf,At,ko=I(()=>{"use strict";iE=le(rE());vn();X();Re();Le();Yp();Lo();yl();lp();$d();Zt();$n();Ti();Zp();ef();rf();mo();tf="_",At=class e extends it{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,E.IsNullOrUndefined(this.getProperty(f.id))&&(this.id=new P(P.NewGuid()))}addControl(t,r,n,i,a,o,s){n instanceof rr?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(!E.IsNullOrUndefined(this.control))return E.IsNullOrUndefined(this.control.dataFieldName)?E.IsNullOrUndefined(this.control.id)?!0:!Vn.dependencyFieldCount.containsKey(this.control.id):!Vn.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&&nl[i])a=nl[i].replace(/ /g,tf)+tf;else{a="Control_";let u=new Error("Control class id does not exist or is undefined");(0,iE.trackErrorTrace)(lt,{eventName:`${q0}/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,f.isUnbound,"true"),e.prototype.setProperty.call(t,f.isRequired,"false")}getControlWithControlSpecificProperties(t,r,n,i,a,o,s){let l;a===kt.Grid?(l=new ea(this),l.indicationOfSubgrid=!0):a===kt.Lookup?l=new ta(this):l=new rr(this);let u=n.guidString,c=o||this.getNextAvailableControlName(t,i,this.getUsedNodeNameSet(t),u);if(e.prototype.setProperty.call(l,f.id,c),l.ClassId=n,!E.IsNullOrUndefined(s)&&(l.UniqueId=s),!o&&r)this.getUnboundControlProperties(l);else{let d=Me.getUniqueIdentifierForControl(l);E.IsNullOrUndefined(d)||(Me.getControlDataTypeByControlOrUniqueId(d)===V.QuickFormCollectionControl||!Me.isUnboundFormControlByIdentifier(d)?a!==kt.Grid&&o&&u!==S.IframeControl&&u!==S.SubgridControl&&u!==S.ReferencePanelSubgridControl&&(l.dataFieldName=o,e.prototype.setProperty.call(l,f.disabled,"false")):(this.rowspan=Me.GetRowSpan(l),(Me.getControlDataTypeByControlOrUniqueId(d)===V.NotesControl||Me.getControlDataTypeByControlOrUniqueId(d)===V.TimeLineControl)&&(e.prototype.setProperty.call(l,f.disabled,"false"),l.id=V.NotesControl)),(Me.getUnboundControlNameFromIdentifier(n)===V.SubGridControl||Me.getUnboundControlNameFromIdentifier(n)===V.NotesControl||Me.getUnboundControlNameFromIdentifier(n)===V.TimeLineControl)&&(this.availableforphone=!0))}return l}buildDependencyList(t,r){if(E.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(f.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(f.rowspan,String(t))}get rowspan(){let t=this.getProperty(f.rowspan);return E.IsNullOrUndefined(t)?1:parseInt(t,10)}set autoexpand(t){this.setProperty(f.auto,String(t))}get autoexpand(){return this.getProperty(f.auto)==="true"}set colspan(t){let r=Number(op.ONE_COLUMN),n=Number(op.FOUR_COLUMN);E.IsNullOrUndefined(t)||t>n||t<r||this.setProperty(f.colspan,String(t))}get colspan(){let t=this.getProperty(f.colspan);return E.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!E.IsNullOrUndefined(t)}isInFooter(){let t=this.getAncestor(v.formFooter);return!E.IsNullOrUndefined(t)}isEmpty(){return E.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(f.userspacer);return E.IsNullOrUndefined(t)?!1:t==="true"}SetUserSpacer(){this.setProperty(f.userspacer,"true")}ClearUserSpacer(){this.setProperty(f.userspacer,"false")}get columns(){let t=this.getProperty(f.columnName);return E.IsNullOrUndefined(t)?null:parseInt(t,10)}getColumnLayoutValue(t){let r;switch(t){case we.TWO_COLUMN:r="11";break;case we.THREE_COLUMN:r="111";break;case we.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(!E.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();E.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===zn.ApplicationRequired||o===zn.SystemRequired)&&!a||this.isCellLockedByExternal(t)&&!a)return!0}}return!1}getRequiredLevel(t){return!this.control?.dataFieldName||!this.control?.id||this.IsNewField||!this.control?.ClassId?zn.None:t.getEntityAttributeByName(this.control.dataFieldName)?.requiredLevel?.toString()??zn.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";nt();X();We();ra=class extends j{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(f.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(f.libraryUniqueId,t)}get name(){return this.getProperty(f.libraryName)}set name(t){this.setProperty(f.libraryName,t)}get displayName(){return this.getProperty(f.displayName)}set displayName(t){this.setProperty(f.displayName,t)}get description(){return this.getProperty(f.description)}set description(t){this.setProperty(f.description,t)}}});var Xn,af=I(()=>{"use strict";Re();ko();X();We();Xn=class extends j{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 E.IsNullOrUndefined(t)?!1:this.deleteChild(t)>=0}insertCellAtIndex(t,r){return E.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 At(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 g5(e){switch(e){case Wn.Left:return Hn.Left;case Wn.Right:return Hn.Right;case Wn.Center:return Hn.Center;default:return Hn.Left}}function v5(e){switch(e){case ki.Left:return Ui.Left;case ki.Top:return Ui.Top;default:return Ui.Left}}function aE(e){switch(e){case 1:return 1;case 2:return 11;case 3:return 111;case 4:return 1111;default:return 1}}var b5,vr,Mo=I(()=>{"use strict";up();Le();Re();nt();Xp();ko();X();Zt();vn();af();b5=115,vr=class e extends it{colSpan=1;constructor(t,r){super(t,r)}getSectionType(){let t;switch(this.columns){case 1:t=we.ONE_COLUMN;break;case 11:t=we.TWO_COLUMN;break;case 111:t=we.THREE_COLUMN;break;case 1111:t=we.FOUR_COLUMN;break;default:t=this.colSpan-1}return t}setUniqueName(){let t=this.getParentTab(),r=ve.namePrefix;if(t){let n=t.Name,i=t.TotalSectionsCount+1;r=n+ve.namePrefix+i.toString()}else r+=Math.floor(Math.random()*1e3);this.setProperty(f.Name,r)}initializeDefaultProperties(t,r,n){if(n===we.REFERENCE_PANEL){this.addProperty(f.rowheight,"25");let i=`${ve.referencePanelNamePrefix}${P.NewGuid()}${ve.namePrefix}`;this.addProperty(f.Name,i)}else this.setUniqueName();if(this.addProperty(f.id,new P(P.NewGuid()).guidString),this.addProperty(f.IsUserDefined,ve.IsUserDefined),this.addProperty(f.locklevel,ve.LockLevel),this.addProperty(f.showlabel,ve.ShowLabel),this.addProperty(f.showbar,ve.ShowBar),this.addProperty(f.layout,ve.Layout),this.addProperty(f.Fieldlabelalignment,ve.labelAlignment),this.addProperty(f.Fieldlabelposition,ve.labelPosition),E.IsNullOrUndefined(n))this.addProperty(f.columnName,ve.columns);else{let i=this.getColumnLayoutValue(n);this.addProperty(f.columnName,i)}this.addProperty(f.LabelWidth,ve.LabelWidth),this.setDisplayName(r,t)}getColumnLayoutValue(t){let r;switch(t){case we.TWO_COLUMN:r="11";break;case we.THREE_COLUMN:r="111";break;case we.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 E.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),YN.getConfig().enableAutoInsertionOfCellInRow)for(let n=0;n<t;n++){let i=new At(r);i.setDefaultProperties(!1),r.addCell(i)}}}initialize(t,r,n){this.initializeDefaultProperties(t,r,n),n===we.REFERENCE_PANEL&&(n=we.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(f.columnName),r=E.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 aE(n)}return r}set columns(t){E.IsNullOrUndefined(t)||this.setProperty(f.columnName,String(t))}get rowHeight(){let t=this.getProperty(f.rowheight);return E.IsNullOrUndefined(t)?null:parseInt(t,10)}set rowHeight(t){this.setProperty(f.rowheight,String(t))}set autoexpand(t){this.setProperty(f.autoExpand.toLowerCase(),String(t))}get autoexpand(){return this.getProperty(f.autoExpand.toLowerCase())==="true"}get isUserDefined(){return+this.getProperty(f.IsUserDefined)!=0}set isUserDefined(t){t?this.setProperty(f.IsUserDefined,"1"):this.setProperty(f.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(f.showlabel)==="true"}set showlabel(t){E.IsNullOrUndefined(t)||this.setProperty(f.showlabel,String(t))}get fieldLabelAlignment(){let t=ve.labelAlignment,r=this.getProperty(f.Fieldlabelalignment);return E.IsNullOrUndefined(r)?t:r}set fieldLabelAlignment(t){E.IsNullOrUndefined(t)||this.setProperty(f.Fieldlabelalignment,t)}get fieldLabelPosition(){let t=this.getProperty(f.Fieldlabelposition);return E.IsNullOrUndefined(t)?ve.labelPosition:t}set fieldLabelPosition(t){E.IsNullOrUndefined(t)||this.setProperty(f.Fieldlabelposition,String(t))}get showbar(){return this.getProperty(f.showbar)==="true"}set showbar(t){E.IsNullOrUndefined(t)||this.setProperty(f.showbar,String(t))}get labelwidth(){let t=+this.getProperty(f.LabelWidth);return t===0?b5:t}set labelwidth(t){E.IsNullOrUndefined(t)||t>283&&t<57||this.setProperty(f.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:g5(this.fieldLabelAlignment),Position:v5(this.fieldLabelPosition)},Columns:aE(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!E.IsNullOrUndefined(this)&&!E.IsNullOrUndefined(this.Name)&&this.Name.indexOf(ve.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,kl=I(()=>{"use strict";X();We();Mo();bn=class e extends j{constructor(t){super(v.formColumn,t)}initializeDefaultProperties(t){this.addProperty(f.width,t.toString()+"%")}insertSectionAtIndex(t,r){this.addGrandChildAtIndex(v.formSections,t,r)}static createAndInitNewSection(t,r,n){let i=new vr(v.formSection,null);return i.initialize(t,r,n),i}addSectionAtIndex(t,r){this.addGrandChildAtIndex(v.formSections,t,r)}initialize(t,r,n,i=we.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(f.width)}set width(t){this.setProperty(f.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(f.Name),Id:this.getProperty(f.id),Label:null,ShowLabel:!1,Visible:!0,LabelId:null,PreviewId:this.getProperty(f.id),Sections:await this.getSectionsJSON(t),Width:this.width}}}});var Ml,oE=I(()=>{"use strict";Le();X();Zt();Mo();Ml=class extends vr{initializeNavArea(t,r,n){this.initializeNavAreaProps(t,r,n)}get AreaName(){return this.Name}initializeNavAreaProps(t,r,n){this.addProperty(f.Name,n),this.addProperty(f.id,new P(P.NewGuid()).guidString),this.addProperty(f.columnName,ve.columns),this.setDisplayName(r,t)}}});var Ul,sE=I(()=>{"use strict";kl();X();oE();Ul=class extends bn{addAndIntializeNavBarSection(t,r,n,i){let a=new Ml(v.formSection,null);return a.initializeNavArea(t,r,i),this.addGrandChildAtIndex(v.formSections,a,n),a}}});var Gr,Bl=I(()=>{"use strict";Le();Re();nt();kl();X();We();vn();Gr=class extends it{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(f.Name,dn.namePrefix+t.toString()),this.addProperty(f.id,new P(P.NewGuid()).guidString),this.addProperty(f.IsUserDefined,dn.IsUserDefined),this.addProperty(f.locklevel,dn.LockLevel),this.addProperty(f.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=we.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=we.ONE_COLUMN,s=!0,l){this.addChild(new j(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(f.expanded)}set expanded(t){E.IsNullOrUndefined(t)||this.setProperty(f.expanded,String(t))}get groupName(){return this.getProperty(f.groupName)}get contentType(){return this.getProperty(f.contentType)}set contentType(t){this.setProperty(f.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";Le();X();We();Zt();sE();Bl();Kn=class extends Gr{constructor(t,r,n){super(t,ye.THREE_COLUMN_EQUAL),this.setDisplayName(r,n),this.id=new P(P.NewGuid())}initializeDefaultProps(){this.addChild(new j(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<hl.FIVE_COLUMN;t++){let r=new Ul(this.getChildren(v.formColumns)[0]);r.initializeDefaultProperties(vv.FiveEqColumn),this.addGrandChild(v.formColumns,r)}}}});function w5(e){switch(e){case ke.Main:return fn.Main;case ke.QuickCreate:return fn.QuickCreate;case ke.QuickViewForm:return fn.Quick;case ke.Dialog:return fn.Dialog;default:return fn.None}}function A5(e,t){if(t===ke.Main){if(e)switch(e.toLowerCase()){case"low":return cn.Low;case"highreadonlyvalues":return cn.HighReadOnlyValues;default:return cn.HighWithControls}return cn.Low}}var ql,y5,$l,lE=I(()=>{"use strict";Lb();ql=le(qn());up();Re();nt();Ti();Xp();X();xi();Id();$n();ko();X();vn();nf();of();Bl();y5="1920";$l=class e extends it{_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 Zs,this._metadataChangeEvent=new wl}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 At).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 At){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,ql.trackErrorTrace)(V0,{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(f.ShowImage))?!0:this.getProperty(f.ShowImage)!=="false"}set ShowImagecheck(t){t?this.setProperty(f.ShowImage,String(t)):this.setProperty(f.ShowImage,"false")}get ShowNavigation(){return T.IsNullOrEmpty(this.getProperty(f.ShowNavigationbar))?!0:this.getProperty(f.ShowNavigationbar)!=="false"}set ShowNavigation(t){t?this.setProperty(f.ShowNavigationbar,String(t)):this.setProperty(f.ShowNavigationbar,"false")}get MaxWidth(){return T.IsNullOrEmpty(this.getProperty(f.MaxWidth))?y5:this.getProperty(f.MaxWidth)}set MaxWidth(t){this.setProperty(f.MaxWidth,t)}get headerDensityType(){return this.getProperty(f.HeaderDensityType)}set headerDensityType(t){t&&this.formType===ke.Main?this.setProperty(f.HeaderDensityType,t):this.formType!==ke.Main&&this.headerDensityType&&this.removeProperty(f.HeaderDensityType)}IsMainOrQuickCreateForm(){return this.formType===ke.Main||this.formType===ke.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){E.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 E.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){E.IsNullOrUndefined(t)||(this.deleteChild(this.footer),this.addChild(t))}createAndInitNewTab(t,r,n){let i=new Gr(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 Gr(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(!E.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);E.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 At))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 At&&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)||ZN.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,ql.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===ke.Main?{HeaderDensity:A5(this.headerDensityType,this.formType)}:{},InlineEditGridRow:[],InlineQuickForms:[],QuickFormEntities:[],EventHandlers:[],LinkControlSections:[],FormType:w5(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 Vl,sf,uE=I(()=>{"use strict";Le();Re();X();We();vn();Vl=class extends it{constructor(t){super(v.formDisplayConditions,t)}get Order(){let t=this.getProperty(f.Order);return E.IsNullOrUndefined(t)?null:parseInt(t,10)}set Order(t){this.setProperty(f.Order,t.toString())}get FallbackForm(){return this.getProperty(f.FallbackForm)==="true"}set FallbackForm(t){this.setProperty(f.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 j{constructor(t){super(v.formEveryOne,t)}}});var Gl,cE=I(()=>{"use strict";X();We();Gl=class extends j{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(f.HandlerUniqueId)}set HandlerUniqueID(t){this.setProperty(f.HandlerUniqueId,t)}get FunctionName(){return this.getProperty(f.functionName)}set FunctionName(t){this.setProperty(f.functionName,t)}get LibraryName(){return this.getProperty(f.libraryNameEventHandler)}set LibraryName(t){this.setProperty(f.libraryNameEventHandler,t)}get Enabled(){return this.getProperty(f.enabledForField)}set Enabled(t){this.setProperty(f.enabledForField,t)}get PassExecutionContext(){return this.getProperty(f.passExecutionContext)}set PassExecutionContext(t){this.setProperty(f.passExecutionContext,t)}get Parameters(){return this.getProperty(f.parameters)}set Parameters(t){this.setProperty(f.parameters,t)}}});var na,lf=I(()=>{"use strict";X();Mo();na=class extends vr{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,dE=I(()=>{"use strict";X();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,pE=I(()=>{"use strict";X();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(f.showCommandBar)}set showCommandBar(t){t!=null&&this.setProperty(f.showCommandBar,String(t))}get showBody(){return this.getProcessedValue(f.showBody)}set showBody(t){t!=null&&this.setProperty(f.showBody,String(t))}get showTabNavigator(){return this.getProcessedValue(f.showTabNavigator)}set showTabNavigator(t){t!=null&&this.setProperty(f.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 Ct,Yn=I(()=>{"use strict";Le();nt();X();vn();Ct=class e extends it{constructor(t,r){super(t,r)}getTitle(t){for(let r of this.getAllTitles())if(+r.getProperty(f.LCID)===t)return r.getProperty(f.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(f.LCID)===r){i.setProperty(f.text,t);return}let n=new e(v.Title,null);n.setProperty(f.text,t),n.setProperty(f.LCID,String(r)),this.addGrandChild(v.Titles,n)}get Sequence(){return+this.getProperty(f.Sequence)}set Sequence(t){this.setProperty(f.Sequence,t.toString())}get Area(){return this.getProperty(f.Area)}set Area(t){this.setProperty(f.Area,t)}set Id(t){this.setProperty(f.Id,t)}get Id(){return this.getProperty(f.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(f.icon)}set Icon(t){t=t||T.EmptyString,this.setProperty(f.icon,t)}updateCommonProperties(t,r){this.Area=t.Area,this.Sequence=t.Sequence,this.setTitle(t.getDisplayName(r),r)}}});var $o,fE=I(()=>{"use strict";(function(e){e[e.NavLinkNotAvailable=-1]="NavLinkNotAvailable",e[e.NavLinkIdConflict=-2]="NavLinkIdConflict",e[e.NavBarNotAvailable=-3]="NavBarNotAvailable"})($o||($o={}))});var zl,mE=I(()=>{"use strict";Re();X();Yn();fE();zl=class extends Ct{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 E.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 me,C5,hE,aee,ia,uf=I(()=>{"use strict";Le();X();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"})(me||(me={}));C5=new Map([[me.Info,"Info"],[me.Sales,"Sales"],[me.Service,"Service"],[me.Marketing,"Marketing"],[me.ProcessCenter,"ProcessCenter"]]),hE=new Map([["Info",me.Info],["Sales",me.Sales],["Service",me.Service],["Marketing",me.Marketing],["ProcessCenter",me.ProcessCenter]]),aee=new Map([[me.Info,9e3],[me.Sales,9200],[me.Service,9400],[me.Marketing,9600],[me.ProcessCenter,9800],[me.InternetMarketing,1e4],[me.Async,10200]]),ia=class extends Ct{constructor(t,r){super(v.formNavBarArea,r)}setDefaultPropertiesByType(t,r,n){this.AreaId=C5.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(f.Id)}set AreaId(t){this.setProperty(f.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";X();Yn();aa=class extends Ct{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 Wl,gE=I(()=>{"use strict";Re();X();Yn();Wl=class extends Ct{RelationshipNameUCIRuntime;constructor(t){super(v.formNavBarByRelationshipItem,t)}get RelationshipName(){return this.getProperty(f.RelationshipName)}set RelationshipName(t){this.setProperty(f.RelationshipName,t)}set Show(t){this.setProperty(f.Show,String(t))}get Show(){let t=this.getProperty(f.Show);return E.IsNullOrUndefined(t)||t==="true"}get TitleResourceId(){return this.getProperty(f.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 jl,vE=I(()=>{"use strict";X();Yn();jl=class extends Ct{constructor(t){super(v.formNavBarItem,t)}get Url(){return this.getProperty(f.url)}set Url(t){this.setProperty(f.url,t)}}});var Hl,bE=I(()=>{"use strict";Le();X();uf();cf();Yn();Hl=class extends Ct{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=[me.Info,me.Sales,me.Service,me.Marketing,me.ProcessCenter];if(this.navBarAreas){let i=this.navBarAreas?.AllNavBarAreaItems;if(i&&i.length>0){let a=new Set(i.map(o=>hE.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 yE={};ar(yE,{ControlType:()=>kt,DeserializationService:()=>ff,DeserializationServiceScope:()=>pf,DeserializedFormElementNode:()=>St});var df,St,pf,kt,ff,rf=I(()=>{"use strict";df=le(qn());Le();Re();nt();Ti();$d();$n();G0();Fb();yl();lE();ko();kl();Lo();Kp();X();X();uE();We();Zt();Yp();cE();dE();Zp();ef();pE();nf();af();Mo();Bl();mE();uf();cf();gE();vE();bE();St=class extends j{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"})(kt||(kt={}));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 m="";throw d.length===0?m="FormXml has no form node.":m="FormXml has multiple form nodes.",(0,df.trackErrorTrace)(lt,{eventName:pf,eventData:{error:m}}),new Error(m)}let p=this.createFormModel(d.item(0),r,n,i,a,o,s,l,u,c);return E.IsNullOrUndefined(p.displayCondition)&&s!==ke.Dialog&&this.appendDefaultDisplayCondition(p),p}upsertFieldCount(t,r){let n=Vn.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(!E.IsNullOrUndefined(t)){let n=E.ParseXml(r);n!==null&&this.populateElementChildren(t,n.childNodes)}}createFormModel(t,r,n,i,a,o,s,l,u,c){let d=new $l(r,n,i,a,o,s,l,u,c);return this.populateElementProperties(d,t.attributes),this.populateElementChildren(d,t.childNodes),s===ke.Main&&(this.insertHeaderFooterElementProperties(v.formHeader,d,d.header),this.insertHeaderFooterElementProperties(v.formFooter,d,d.footer)),d}insertHeaderFooterElementProperties(t,r,n){if(E.IsNullOrUndefined(n)){let i=t===v.formHeader?new Bo(r,!0):new Uo(r,!0);St.prototype.insertProperty.call(i,f.id,"{"+P.NewGuid()+"}"),St.prototype.insertProperty.call(i,f.Fieldlabelposition,"Top"),St.prototype.insertProperty.call(i,f.columnName,ve.MarginalControlColumns),St.prototype.insertProperty.call(i,f.LabelWidth,ve.LabelWidth),St.prototype.insertProperty.call(i,f.Fieldlabelalignment,"Left");let a=null,o=new Xn(a);for(let s=0;s<i.maxColumns;s++){let l=new At(o);St.prototype.insertProperty.call(l,f.id,"{"+P.NewGuid()+"}"),l.setDisplayName(T.EmptyString,this.lcid),St.prototype.insertProperty.call(l,f.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 St(`<${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)(lt,{eventName:pf,eventData:{error:n}}),new Error(n)}for(let n=0;n<r.length;n++){let i=r.item(n);i&&(St.prototype.insertProperty.call(t,i.name,i.value),t.getNodeName()===v.formCell&&i.name===f.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&&St.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 Gr(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 vr(v.formSection,r);case v.formRow:return new Xn(r);case v.formCell:return new At(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===f.indicationOfSubgrid&&l.value==="true"||l.name===f.classid&&(l.value?.toLocaleUpperCase()===`{${S.SubgridControl}}`||l.value?.toLocaleUpperCase()===`{${S.ReferencePanelSubgridControl}}`))a=kt.Grid;else if(l.name===f.classid&&l.value?.toLocaleUpperCase()===`{${S.LookupControl}}`)a=kt.Lookup;else if(l.name===f.classid&&l.value?.toLocaleUpperCase()===`{${S.CustomControl}}`)for(let u=0;u<i?.length;u++)i[u].nodeName===f.DefaultViewId&&(a=kt.Lookup)}return a===kt.Grid?new ea(r):a===kt.Lookup?new ta(r):new rr(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 Gl(o,r);case v.formNavigation:return new Hl(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 zl(r);case v.formNavBarByRelationshipItem:return new Wl(r);case v.formNavBarItem:return new jl(r);case v.formDisplayConditions:return new Vl(r);case v.library:return new ra(r,T.EmptyString,T.EmptyString);case v.controlDescription:return new il(r);case v.customControl:return this.populateCustomControlConfigurationId(t),new bl(r);default:return new St(t.nodeName,r)}}populateDependencyTable(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);i.name===f.id&&this.upsertFieldCount(i.value,fr.DependencyFieldTable)}}populateCustomControlConfigurationId(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);if(i.name===f.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===f.ForControl){let l=s.value.substr(1,i.value.length-2);Me.CustomControlIdMap.upsert(l,a);break}}break}}}}});var wE={};ar(wE,{SerializationService:()=>mf,SerializationServiceScope:()=>S5,SerializedFormElementNode:()=>oa});var S5,oa,mf,AE=I(()=>{"use strict";nt();We();Zt();of();S5="SerializationService",oa=class extends j{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)===qr.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 br=g(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.childObjects=Nt.optionalGuidId=Nt.optionalEnum=Nt.eachObject=Nt.issue=Nt.isJsonObject=void 0;function CE(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}Nt.isJsonObject=CE;function qo(e,t,r,n){return n?{pointer:e,rule:t,message:r,fatal:n}:{pointer:e,rule:t,message:r}}Nt.issue=qo;function SE(e,t,r,n){if(!Array.isArray(e))return[];let i=[];return e.forEach((a,o)=>{CE(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}Nt.eachObject=SE;function N5(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)}`))}Nt.optionalEnum=N5;var E5=/^(?:\{[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 D5(e,t,r,n,i){let a=e[t];typeof a=="string"&&a!==""&&!E5.test(a)&&i.push(qo(`${r}/${t}`,n,`${t} must be a GUID or empty, got '${a}'`))}Nt.optionalGuidId=D5;function I5(e,t,r,n,i){let a=e[t],o=`${r}/${t}`;return a===void 0?[]:Array.isArray(a)?SE(a,o,n,i):(i.push(qo(o,`${n}-list-must-be-array`,`${t} must be an array when present, got ${typeof a}`)),[])}Nt.childObjects=I5});var yn=g(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});Ql.installDomShim=void 0;var NE=Js(),EE=!1,_5={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 P5(){if(EE)return;let e=globalThis;typeof e.DOMParser>"u"&&(e.DOMParser=NE.DOMParser),typeof e.XMLSerializer>"u"&&(e.XMLSerializer=NE.XMLSerializer),typeof e.Node>"u"&&(e.Node=_5),EE=!0}Ql.installDomShim=P5});var VE=g(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.classIdForAttributeType=Et.QUICK_VIEW_CLASS_ID=Et.NOTES_CLASS_ID=Et.SUBGRID_CLASS_ID=Et.formRegistration=Et.FormAdapter=void 0;var Mt=(Le(),or(F0)),T5=(Re(),or(L0)),O5=(We(),or(M0)),at=(X(),or(k0)),xe=($n(),or(U0)),R5=(rf(),or(yE)),x5=(AE(),or(wE)),Ue=on(),DE=Kt(),Zn=br(),F5=Zc(),OE=ht(),bf=Z(),RE=yn(),xE=pi(),L5={[at.FormType.Main]:"Main",[at.FormType.QuickCreate]:"QuickCreate",[at.FormType.QuickViewForm]:"QuickView",[at.FormType.Card]:"Card"},hf={Main:at.FormType.Main,QuickCreate:at.FormType.QuickCreate,QuickView:at.FormType.QuickViewForm,Card:at.FormType.Card},k5=new Map(Object.entries(xe.ControlClassId).map(([e,t])=>[String(t).toUpperCase(),e]));function FE(e){var t;return e&&(t=k5.get(e.toUpperCase()))!==null&&t!==void 0?t:"Unknown"}function Vo(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 LE(e,t){return e.getAllChildren().find(r=>r.getNodeName()===t)}function yf(e,t){var r,n;let i=LE(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 M5(e){let t=LE(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 kE(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 Go(e){return String(e??"").replace(/[{}]/g,"")}function vf(e){return`{${Go(e)}}`}function IE(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,Ue.rawFromNode)(u)})}),i<0)return{modeled:[],bag:{a:Vo(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,Ue.rawFromNode)(u)})}),{modeled:s,bag:{a:Vo(e),c:a,w:{n:o.getNodeName(),a:Vo(o),c:l}}}}function ME(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,Ue.rawFromNode)(a)})}),{modeled:n,bag:{a:Vo(e),c:i}}}function U5(e,t){let{modeled:r,bag:n}=Xl(e,"tabs","tab");return{tabs:r.map(i=>B5(i,t)),bag:n}}function B5(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:yf(e,t),expanded:i.get("expanded")==="true",visible:i.has("visible")?i.get("visible")==="true":!0,columns:a.map(s=>$5(s,t)),bag:o}}function $5(e,t){let r=ei(e),{modeled:n,bag:i}=Xl(e,"sections","section");return{width:r.get("width"),sections:n.map(a=>q5(a,t)),bag:i}}function q5(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:yf(e,t),visible:a.has("visible")?a.get("visible")==="true":!0,showLabel:a.get("showlabel")==="true",columns:kE((i=a.get("columns"))!==null&&i!==void 0?i:"1"),rows:o.map(l=>V5(l,t)),bag:s}}function V5(e,t){let{modeled:r,bag:n}=ME(e,"cell",!1);return{cells:r.map(i=>G5(i,t)),bag:n}}function G5(e,t){var r;let n=ei(e),{modeled:i,bag:a}=ME(e,"control",!0),o=yf(e,t),s=n.get("showlabel")==="true",l=i[0]?z5(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:IE(n.get("colspan"),1),rowspan:IE(n.get("rowspan"),1),control:l,bag:a}}function z5(e,t,r){var n,i;let a=ei(e),o=Go((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:FE(o),isRequired:a.get("isrequired")==="true",isReadOnly:a.get("disabled")==="true",label:t,showLabel:r,parameters:M5(e),bag:{a:Vo(e),c:e.getAllChildren().map((l,u)=>({i:u,node:(0,Ue.rawFromNode)(l)}))}}}function sa(e){return e.a.length===0&&e.c.length===0&&!e.w}function UE(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function ti(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=UE(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,Ue.mergeAttrs)(e.a,a)}var wn=(e,t)=>({key:e,matches:r=>r===t,render:()=>t,absentDefault:""}),An=(e,t,r=!1)=>({key:e,matches:n=>n==="true"===t,render:()=>String(t),absentDefault:String(r)}),_E=(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 BE(e){return{n:"parameters",a:[],c:Object.keys(e).map(t=>({n:(0,bf.assertXmlName)(t,"Form control parameter name"),a:[],c:[{n:`<${e[t]}`,a:[],c:[]}]}))}}function W5(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 j5(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||W5(e.c[n].node,r)===t)return e;let i=j5(e.c[n].node,t,r);return{...e,c:e.c.map((a,o)=>o===n?{...a,node:i}:a)}}function H5(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 Q5(e,t){let r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every(i=>e[i]===t[i])}function J5(e,t){return e.a.some(r=>r[0]===t)?{...e,a:e.a.filter(r=>r[0]!==t)}:e}function X5(e,t){let r=e.c.findIndex(i=>i.node.n==="parameters");if(r<0||Q5(H5(e.c[r].node),t))return e;let n=BE(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,Ue.spliceChildren)(e.w.c,r)};return(0,Ue.spliceChildren)(e.c,[o])}let i=n(),a={n:t,a:[],c:r};return e.c.length===0?[...i,a]:(0,Ue.spliceChildren)(e.c,[...i,a])}function K5(e,t){let r=e.tabs.map(n=>Y5(n,t));return{n:"form",a:ti(e.bag,[]),c:e.tabs.length===0&&sa(e.bag)?[]:Kl(e.bag,"tabs",r,()=>[])}}function Y5(e,t){let r=[wn("id",e.id),wn("name",e.name),An("expanded",e.expanded),An("visible",e.visible,!0)],n=e.columns.map(a=>Z5(a,t)),i=Af(e.bag,e.label,t);return{n:"tab",a:ti(i,r),c:Kl(i,"columns",n,()=>e.label?[wf(e.label,t)]:[])}}function Z5(e,t){let r=e.width!==void 0?[wn("width",e.width)]:[],n=e.sections.map(i=>e9(i,t));return{n:"column",a:ti(e.bag,r),c:Kl(e.bag,"sections",n,()=>[])}}function e9(e,t){let r=[wn("id",e.id),wn("name",e.name),An("showlabel",e.showLabel),An("visible",e.visible,!0),{key:"columns",matches:a=>kE(a)===e.columns,render:()=>gf(e.columns),absentDefault:gf(1)}],n=e.rows.map(a=>t9(a,t)),i=Af(e.bag,e.label,t);return{n:"section",a:ti(i,r),c:Kl(i,"rows",n,()=>e.label?[wf(e.label,t)]:[])}}function t9(e,t){let r=e.cells.map(n=>r9(n,t));return{n:"row",a:ti(e.bag,[]),c:sa(e.bag)?r:(0,Ue.assembleChildren)(e.bag,r)}}function r9(e,t){let r=e.control?e.control.showLabel:UE(e.bag,"showlabel")==="true",n=[wn("id",e.id),An("showlabel",r),An("visible",e.visible,!0),_E("colspan",e.colspan),_E("rowspan",e.rowspan)],i=e.control?[n9(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,Ue.assembleChildren)(o,i)}return{n:"cell",a:ti(e.bag,n),c:a}}function n9(e){let t=[wn("id",e.id),{key:"classid",matches:i=>Go(i)===e.classId,render:()=>vf(e.classId),absentDefault:""}];e.fieldName!==null&&t.push(wn("datafieldname",e.fieldName)),t.push(An("disabled",e.isReadOnly)),t.push(An("isrequired",e.isRequired));let r=e.fieldName===null?J5(e.bag,"datafieldname"):e.bag,n;return sa(r)?n=Object.keys(e.parameters).length>0?[BE(e.parameters)]:[]:n=(0,Ue.assembleChildren)(X5(r,e.parameters),[]),{n:"control",a:ti(r,t),c:n}}var i9={make:(e,t)=>new O5.FormElementNode(e,t),setProp:(e,t,r)=>e.setProperty(t,r),addChild:(e,t)=>e.addChild(t)};function PE(e,t,r){(0,RE.installDomShim)();let n=o9(e,r),i=(0,Ue.rebuildRaw)(K5(n,t),i9,null);return new x5.SerializationService(t).serializeFormXmlNode(i)}function a9(e){return JSON.parse(JSON.stringify(e))}function o9(e,t){var r;let n=a9(e);n.bag||(n.bag=(0,Ue.emptyBag)()),m9(n.bag),t&&s9(n,t);for(let i of(r=n.tabs)!==null&&r!==void 0?r:[])l9(i);return n}function s9(e,t){var r;let n=(r=e.entityLogicalName)!==null&&r!==void 0?r:"";$E(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=qE(s.attributeType)))})}function $E(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 l9(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)u9(t);e.bag||(e.bag=(0,Ue.emptyBag)())}function u9(e){e.sections||(e.sections=[]);for(let t of e.sections)c9(t);e.bag||(e.bag=(0,Ue.emptyBag)()),e.width===void 0&&sa(e.bag)&&(e.width="100%")}function c9(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)d9(t);e.bag||(e.bag=(0,Ue.emptyBag)())}function d9(e){e.cells||(e.cells=[]);for(let t of e.cells)p9(t);e.bag||(e.bag=(0,Ue.emptyBag)())}function p9(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&&f9(e.control),e.bag||(e.bag=(0,Ue.emptyBag)())}function f9(e){var t;e.id||(e.id=Mt.Guid.NewGuid()),e.classId===void 0&&(e.classId=String(xe.ControlClassId.TextboxControl)),e.fieldName===void 0&&(e.fieldName=null),e.type===void 0&&(e.type=e.fieldName?"Field":FE(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,bf.assertXmlName)(r,"Form control parameter name");e.bag||(e.bag=(0,Ue.emptyBag)())}function m9(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"&&!TE(a,"handlerUniqueId")&&a.a.push(["handlerUniqueId",vf(Mt.Guid.NewGuid())])}}else if(r.n==="formLibraries")for(let n of r.c)n.n==="Library"&&!TE(n,"libraryUniqueId")&&n.a.push(["libraryUniqueId",vf(Mt.Guid.NewGuid())])}}var Jl=class{constructor(t=xE.DEFAULT_LCID){this.lcid=t}toArtifact(t,r){var n,i,a;let{tabs:o,bag:s}=U5(t,this.lcid);return{id:t.formId?t.formId.guidString:"",name:(n=t.formName)!==null&&n!==void 0?n:"",entityLogicalName:(i=t.entityName)!==null&&i!==void 0?i:"",formType:(a=L5[t.formType])!==null&&a!==void 0?a:"Main",status:this.readActivationStatus(t),...r!==void 0&&r!==""?{description:r}:{},tabs:o,bag:s}}fromArtifact(t){var r;return this.deserialize({formxml:PE(t,this.lcid),formid:t.id||Mt.Guid.NewGuid(),objecttypecode:t.entityLogicalName,type:hf[t.formType],name:t.name,uniquename:t.name,description:(r=t.description)!==null&&r!==void 0?r:"",formpresentation:at.FormPresentation.AirForm,formactivationstate:t.status==="Active"?at.FormActivationState.Active:at.FormActivationState.InActive})}fromApiResponse(t){var r,n,i,a,o,s,l;let u=t,c=this.deserialize({formxml:(r=u.formxml)!==null&&r!==void 0?r:"",formid:(n=u.formid)!==null&&n!==void 0?n:Mt.Guid.NewGuid(),objecttypecode:(i=u.objecttypecode)!==null&&i!==void 0?i:"",type:u.type,name:(a=u.name)!==null&&a!==void 0?a:"",uniquename:(o=u.uniquename)!==null&&o!==void 0?o:"",description:(s=u.description)!==null&&s!==void 0?s:"",formpresentation:u.formpresentation,formactivationstate:u.formactivationstate});return this.toArtifact(c,(l=u.description)!==null&&l!==void 0?l:void 0)}toApiPayload(t,r,n){return{formxml:PE(t,this.lcid,n),name:t.name,type:hf[t.formType],objecttypecode:t.entityLogicalName,...t.description!==void 0?{description:t.description}:{}}}metadataNeeds(t){let r=t.entityLogicalName;if(!r)return[];let n=new Set,i=[];return $E(t,a=>{let o=a.fieldName,s=a;!o||s.label!==void 0&&s.classId!==void 0||n.has(o)||(n.add(o),i.push({entityLogicalName:r,fieldName:o}))}),i}createDefault(t){var r,n,i,a,o,s,l,u,c,d,p;let m=t.tabs&&t.tabs.length>0?void 0:S9(this.lcid),h=m!==void 0?m:t.tabs.map(N=>h9(N,this.lcid)).join(""),w=this.deserialize({formxml:`<form><tabs>${h}</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:(o=t.description)!==null&&o!==void 0?o:"",formpresentation:at.FormPresentation.AirForm,formactivationstate:((s=t.status)!==null&&s!==void 0?s:"Active")==="Active"?at.FormActivationState.Active:at.FormActivationState.InActive}),y=this.toArtifact(w,t.description);return{id:(l=t.id)!==null&&l!==void 0?l:y.id,name:(u=t.name)!==null&&u!==void 0?u:"New Form",entityLogicalName:(c=t.entityLogicalName)!==null&&c!==void 0?c:"",formType:(d=t.formType)!==null&&d!==void 0?d:"Main",status:(p=t.status)!==null&&p!==void 0?p:"Active",...t.description!==void 0?{description:t.description}:{},tabs:y.tabs,bag:y.bag}}assignMissingIds(t){return(0,OE.assignMissingIds)(t)}validate(t){return E9(t)}deserialize(t){(0,RE.installDomShim)();let r=T5.ScriptUtilities.ParseXml(t.formxml),n=new R5.DeserializationService(this.lcid).deSerializeFormXml(r,new Mt.Guid(t.formid),t.objecttypecode,at.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===at.FormActivationState.InActive?"Inactive":"Active"}};Et.FormAdapter=Jl;function nr(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Cf(e,t){return e?`<labels><label description="${nr(e)}" languagecode="${t}" /></labels>`:""}function Sf(e){return e&&e.length>0?Go(e):(0,OE.newId)()}function h9(e,t){var r,n,i,a;let o=(r=e.columns)!==null&&r!==void 0?r:[],s=(o.length>0?o:[C9()]).map(l=>g9(l,t)).join("");return`<tab id="{${nr(Sf(e.id))}}" name="${nr((n=e.name)!==null&&n!==void 0?n:"")}" expanded="${(i=e.expanded)!==null&&i!==void 0?i:!0}" visible="${(a=e.visible)!==null&&a!==void 0?a:!0}">${Cf(e.label,t)}<columns>${s}</columns></tab>`}function g9(e,t){var r,n;let i=((r=e.sections)!==null&&r!==void 0?r:[]).map(a=>v9(a,t)).join("");return`<column width="${nr((n=e.width)!==null&&n!==void 0?n:"100%")}"><sections>${i}</sections></column>`}function v9(e,t){var r,n,i,a,o;let s=((r=e.rows)!==null&&r!==void 0?r:[]).map(l=>b9(l,t)).join("");return`<section id="{${nr(Sf(e.id))}}" name="${nr((n=e.name)!==null&&n!==void 0?n:"")}" showlabel="${(i=e.showLabel)!==null&&i!==void 0?i:!1}" visible="${(a=e.visible)!==null&&a!==void 0?a:!0}" columns="${gf((o=e.columns)!==null&&o!==void 0?o:1)}">${Cf(e.label,t)}<rows>${s}</rows></section>`}function b9(e,t){var r;return`<row>${((r=e.cells)!==null&&r!==void 0?r:[]).map(n=>y9(n,t)).join("")}</row>`}function y9(e,t){var r,n,i,a,o,s;let l=e.control,u=l?Cf((n=(r=l.label)!==null&&r!==void 0?r:l.fieldName)!==null&&n!==void 0?n:"",t):"",c=l?w9(l):"";return`<cell id="{${nr(Sf(e.id))}}" showlabel="${l?(i=l.showLabel)!==null&&i!==void 0?i:!0:!1}" visible="${(a=e.visible)!==null&&a!==void 0?a:!0}" colspan="${(o=e.colspan)!==null&&o!==void 0?o:1}" rowspan="${(s=e.rowspan)!==null&&s!==void 0?s:1}">${u}${c}</cell>`}function w9(e){var t,r,n;let i=e.fieldName?` datafieldname="${nr(e.fieldName)}"`:"",a=A9(e.parameters),o=e.classId?Go(e.classId):String(xe.ControlClassId.TextboxControl);return`<control id="${nr((t=e.id)!==null&&t!==void 0?t:"")}" classid="{${nr(o)}}"${i} disabled="${(r=e.isReadOnly)!==null&&r!==void 0?r:!1}" isrequired="${(n=e.isRequired)!==null&&n!==void 0?n:!1}">${a}</control>`}function A9(e){let t=Object.keys(e??{});return t.length===0?"":(t.forEach(n=>(0,bf.assertXmlName)(n,"Form control parameter name")),`<parameters>${t.map(n=>`<${n}>${nr(e[n])}</${n}>`).join("")}</parameters>`)}function C9(){return{width:"100%",sections:[],bag:{a:[],c:[]}}}function S9(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 N9(e=xE.DEFAULT_LCID){return{adapter:new Jl(e),api:F5.formApi,languageSensitive:!0,publish:(t,r,n)=>(0,DE.publishBoundEntity)(t,n),publishScope:(t,r)=>(0,DE.boundEntityPublishScope)(r)}}Et.formRegistration=N9;function E9(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:w})=>{let y=`${p}/rows/${w}`;(0,Zn.childObjects)(h,"cells",y,"cell",t).forEach(({node:D,index:x})=>{let F=D.control;F!=null&&!(0,Zn.isJsonObject)(F)&&t.push((0,Zn.issue)(`${y}/cells/${x}/control`,"control-must-be-object-or-null",`a cell control must be a JSON object or null, got ${typeof F}`))})})})})}),t}Et.SUBGRID_CLASS_ID=xe.ControlClassId.SubgridControl;Et.NOTES_CLASS_ID=xe.ControlClassId.TimelineControl;Et.QUICK_VIEW_CLASS_ID=xe.ControlClassId.QuickViewControl;var D9={Lookup:String(xe.ControlClassId.LookupControl),Customer:String(xe.ControlClassId.LookupControl),Owner:String(xe.ControlClassId.LookupControl),PartyList:String(xe.ControlClassId.PartyListControl),Boolean:String(xe.ControlClassId.BooleanControl),DateTime:String(xe.ControlClassId.DateTimeControl),Decimal:String(xe.ControlClassId.DecimalControl),Double:String(xe.ControlClassId.FloatingNumberControl),Money:String(xe.ControlClassId.CurrencyControl),Integer:String(xe.ControlClassId.IntegerControl),BigInt:String(xe.ControlClassId.IntegerControl),Memo:String(xe.ControlClassId.TextAreaControl),String:String(xe.ControlClassId.TextboxControl)},I9="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE";function qE(e){return e==="Picklist"||e==="State"||e==="Status"?I9:e&&D9[e]||String(xe.ControlClassId.TextboxControl)}Et.classIdForAttributeType=qE;function TE(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}});var Nf=g(la=>{"use strict";Object.defineProperty(la,"__esModule",{value:!0});la.viewApi=la.findDefaultViews=void 0;var zE=Jt(),Ut=ge(),zr=Z(),_9="savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault",P9="savedqueryid,name,returnedtypecode,querytype,isdefault";async function T9(e,t,r={}){var n;let i=new Set(((n=r.excludeViewIds)!==null&&n!==void 0?n:[]).filter(Boolean)),a=`returnedtypecode eq '${(0,zr.odataLiteral)(t)}' and querytype eq 0`,o=`/savedqueries${(0,zr.odataQuery)([["$select","savedqueryid,name,isdefault"],["$filter",a]])}`;return(await(0,zE.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:"")}})}la.findDefaultViews=T9;async function O9(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,zr.odataLiteral)(t)}')${(0,zr.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 GE(e,t,r){if(!r||!/<grid\b/.test(t)||/<grid[^>]*\bobject=/.test(t))return t;let n=await O9(e,r);return n===void 0?t:t.replace(/<grid\b/,`<grid object="${n}"`)}la.viewApi={async get(e,t){let n=`/savedqueries(${(0,zr.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,zr.odataQuery)([["$select",_9]]),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,zr.odataQuery)([["$select",P9],["$filter",t?.entityLogicalName?`returnedtypecode eq '${(0,zr.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,zE.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 GE(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,zr.normalizeGuid)(t,"id"),o=(0,Ut.echoWrite)("savedqueryid",{"If-Match":(0,Ut.requireEtag)(n,"view",a)}),s=`/savedqueries(${a})${o.query}`,l=await GE(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 nD=g(ca=>{"use strict";Object.defineProperty(ca,"__esModule",{value:!0});ca.viewRegistration=ca.ViewAdapter=void 0;var ua=br(),Ef=on(),ri=kn(),WE=Kt(),R9=Nf(),Df=yn(),x9=ht(),JE=100,Yl=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,ri.parseXmlRoot)(c,"<fetch/>"),m=(0,ri.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:F9(p),queryType:(l=t.querytype)!==null&&l!==void 0?l:0,isDefault:(u=t.isdefault)!==null&&u!==void 0?u:!1,columns:KE(m,p),filters:eD(p),sort:ZE(p),fetchBag:c?(0,ri.projectElementBag)(p):void 0,layoutBag:d?(0,ri.projectElementBag)(m):void 0}}fromArtifact(t){(0,Df.installDomShim)();let{fetchxml:r,layoutxml:n}=jE(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}=jE(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,ua.childObjects)(n,"columns","","column",r),(0,ua.childObjects)(n,"sort","","sort",r);let i=n.filters;return i!=null&&((0,ua.isJsonObject)(i)?XE(i,"/filters",r):r.push((0,ua.issue)("/filters","filters-must-be-object",`filters must be a JSON object, got ${typeof i}`))),r}};ca.ViewAdapter=Yl;function XE(e,t,r){(0,ua.childObjects)(e,"conditions",t,"condition",r),(0,ua.childObjects)(e,"groups",t,"filterGroup",r).forEach(({node:i,index:a})=>XE(i,`${t}/groups/${a}`,r))}function F9(e){var t;let r=e.getElementsByTagName("entity")[0];return(t=r?.getAttribute("name"))!==null&&t!==void 0?t:""}function KE(e,t){var r;let n=YE(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 YE(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 ZE(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 eD(e){let t=e.getElementsByTagName("entity")[0],r={type:"and",conditions:[],groups:[]};if(!t)return r;let n=Bt(t,"filter").filter(i=>!tD(i)).map(rD);return n.length===0?r:n.length===1?n[0]:{type:"and",conditions:[],groups:n}}function tD(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 rD(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(rD(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 jE(e){let t=L9(e.columns);if(!HE(e.fetchBag)||!HE(e.layoutBag))return{fetchxml:W9({...e,columns:t}),layoutxml:j9({...e,columns:t},`${e.entityLogicalName}id`)};let r=new DOMParser().parseFromString("<root/>","text/xml"),n=QE(e.fetchBag,"fetch",r),i=QE(e.layoutBag,"grid",r),a=KE(i,n),o=!If(t,a),s=!If(e.sort,ZE(n)),l=!If(e.filters,eD(n));return o&&(k9(r,n,t,a),$9(r,i,t)),s&&G9(r,n,e.sort),l&&z9(r,n,e.filters),{fetchxml:(0,ri.serializeNode)(n),layoutxml:(0,ri.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 HE(e){return!!e&&(e.c.length>0||e.a.length>0)}function QE(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,ri.domEngine)(r),null)}function k9(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}`)||M9(a,u);let s=YE(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=U9(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),B9(a,c),l.add(u.name)}}function M9(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 U9(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 B9(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 $9(e,t,r){let n=t.getElementsByTagName("row")[0];if(!n)return;let i=[...r].sort((s,l)=>s.order-l.order),a=q9(n);if(V9(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 q9(e){return Bt(e,"cell").filter(t=>!!t.getAttribute("name")&&t.getAttribute("ishidden")!=="1")}function V9(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 G9(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 z9(e,t,r){let n=t.getElementsByTagName("entity")[0];if(n){for(let i of Bt(n,"filter"))tD(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 W9(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 j9(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 H9(){return{adapter:new Yl,api:R9.viewApi,publish:(e,t,r)=>(0,WE.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,WE.boundEntityPublishScope)(t)}}ca.viewRegistration=H9});function iD(e,t=0){return(Ze[e[t+0]]+Ze[e[t+1]]+Ze[e[t+2]]+Ze[e[t+3]]+"-"+Ze[e[t+4]]+Ze[e[t+5]]+"-"+Ze[e[t+6]]+Ze[e[t+7]]+"-"+Ze[e[t+8]]+Ze[e[t+9]]+"-"+Ze[e[t+10]]+Ze[e[t+11]]+Ze[e[t+12]]+Ze[e[t+13]]+Ze[e[t+14]]+Ze[e[t+15]]).toLowerCase()}var Ze,aD=I(()=>{Ze=[];for(let e=0;e<256;++e)Ze.push((e+256).toString(16).slice(1))});function Pf(){return Zl>eu.length-16&&((0,oD.randomFillSync)(eu),Zl=0),eu.slice(Zl,Zl+=16)}var oD,eu,Zl,sD=I(()=>{oD=require("crypto"),eu=new Uint8Array(256),Zl=eu.length});var lD,Tf,uD=I(()=>{lD=require("crypto"),Tf={randomUUID:lD.randomUUID}});function Q9(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 iD(n)}var dt,cD=I(()=>{uD();sD();aD();dt=Q9});var Of=I(()=>{cD()});var dD=I(()=>{"use strict";});var Rf=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 AD(e){return e&&e!==yr.WorkflowAttributeType.String?e:void 0}function K9(e){return{__class:wD,parameterName:"primaryEntity",entityName:e}}function pD(e){return{__class:Ff,type:xf,typeSet:!1,behavior:yr.AttributeDateTimeBehavior.None,method:hD,parameters:[e]}}function fD(e,t,r=yr.WorkflowAttributeType.String){return{__class:vD,type:r,behavior:yr.AttributeDateTimeBehavior.None,typeSet:!1,entity:K9(t),attributeName:e}}function Y9(e,t=yr.WorkflowAttributeType.String){return{__class:bD,type:t,behavior:yr.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function Z9(e){return{__class:yD,type:xf,typeSet:!1,behavior:yr.AttributeDateTimeBehavior.None,days:e,hours:"0",minutes:"0",months:"0",years:"0"}}function CD(e,t){let r=J9[e.operator],n=pD(fD(e.leftField,t,e.leftWorkflowType)),i;e.dateArithmetic?i=Z9(e.right.value??"0"):e.right.kind==="field"?i=fD(e.right.field??"",t,e.right.workflowType):i=Y9(e.right.value??"",e.right.workflowType??e.leftWorkflowType);let a=pD(i);return{__class:Ff,type:xf,typeSet:!1,behavior:yr.AttributeDateTimeBehavior.None,method:gD,parameters:[r,n,a]}}function SD(e){return typeof e=="object"&&e.__class===Ff}function e8(e){return typeof e=="object"&&e.__class===yD}function tu(e){return SD(e)&&e.method===hD&&e.parameters.length>0?tu(e.parameters[0]):e}function mD(e){if(typeof e!="object"||e.__class!==vD)return null;let t=e.entity;if(t&&t.__class&&t.__class!==wD)return null;let r=e.attributeName;return r?{field:r,workflowType:AD(e.type)}:null}function ND(e){if(!e)return null;let t=tu(e);if(!SD(t)||t.method!==gD||t.parameters.length!==3)return null;let r=t.parameters[0],n=X9[String(r)];if(!n)return null;let i=mD(tu(t.parameters[1]));if(!i)return null;let a=tu(t.parameters[2]);if(e8(a))return n!=="+"&&n!=="-"?null:{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:String(a.days??"")},dateArithmetic:!0};let o=mD(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===bD){let s=a.primitiveValue;return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:s!=null?String(s):"",workflowType:AD(a.type)}}}return null}function ru(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 yr,hD,gD,xf,vD,bD,Ff,yD,wD,J9,X9,Lf=I(()=>{"use strict";yr=le(Rf());hD="0",gD="3",xf="0",vD="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",bD="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",Ff="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",yD="TimeSpanExpression:#Microsoft.Crm.Workflow.Expressions",wD="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions";J9={"+":0,"-":1,"*":2,"/":3},X9={0:"+",1:"-",2:"*",3:"/"}});var LD={};ar(LD,{DEFAULT_DESERIALIZE_LABELS:()=>FD,WorkflowJsonMapper:()=>jo,deserializeWorkflowJson:()=>o8,serializeToWorkflowJson:()=>a8});function ED(e){return e.__class==="BinaryExpression:#Microsoft.Crm.Workflow.Expressions"}function t8(e){return e.__class==="ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel"}function zo(){return{list:[]}}function DD(e,t,r){return e&&e.list.length>0?{list:[{...e.list[0],description:t},...e.list.slice(1)]}:{list:[{labelId:dt(),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 Wo(e,t){return{__class:"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",type:t,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function xD(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:Wo(e.id.replace(/[{}]/g,""),z.WorkflowAttributeType.UniqueIdentifier)}}function ID(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=[xD(e.lookupValue)]}else e.valueType==="Clear"?a=[Wo(null,r)]:e.valueType==="Expression"?a=[iu(e.valueType,e.value,e.valueField,t,e.expression,e.rawExpression)]:a=[Wo(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 r8(e,t,r){if(e.length===0)return null;if(e.length===1)return ID(e[0],r);let n=t==="AND"?z.WorkflowConditionOperator.LogicalAnd:z.WorkflowConditionOperator.LogicalOr,[i,...a]=e.map(o=>ID(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 nu(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=ND(e);return t?{valueType:"Expression",expression:t}:{valueType:"Expression",rawExpression:e}}return{valueType:"Value",value:""}}function kf(e){let t=RD[e.conditionOperatoroperator]??"Equals",r=e.left.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"?e.left.attributeName:"",i=t==="ContainsData"||t==="DoesNotContainData"?{valueType:"Value"}:nu(e.right[0]);return{id:dt(),field:r,fieldDisplayName:r,operator:t,...i}}function _D(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:[...ED(e.left)?[kf(e.left)]:[],...e.right.filter(ED).map(kf)],logic:r}}return{clauses:[kf(e)],logic:"AND"}}function iu(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 CD(i,n);if(a!=null)return a}return e==="Lookup"&&o?xD(o):e==="Clear"?Wo(null,s??z.WorkflowAttributeType.String):Wo(t??"",z.WorkflowAttributeType.String)}function Mf(e,t){return{propertyName:e,propertyValueExpr:t}}function da(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 PD(e,t,r){return e&&!r.used.has(e)?(r.used.add(e),e):qt(t,r)}function n8(e){return e===OD.StateCode.Activated?"Active":"Draft"}function i8(e,t){let r=e.processtriggerscope,n=e.processtriggerformid;return r===1&&n?n:r===2?"Entity":t??"Entity"}function a8(e,t=1033){return new jo({languageCode:t}).serialize(e)}function o8(e){return new jo().deserialize(e)}var OD,z,Uf,RD,FD,jo,kD=I(()=>{"use strict";Of();OD=le(jn());dD();Lf();z=le(Rf());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},RD={};for(let e of Object.keys(Uf))RD[Uf[e]]=e;FD={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"};jo=class{resolveLabel;languageCode;entityName="";stepCounter={value:0};idCounter={counts:{},used:new Set};constructor(t={}){this.resolveLabel=t.resolveLabel??(r=>FD[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??dt(),name:r?.name??"Step_0",description:r!==void 0?r.description:t.description||null,stepLabels:zo(),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??da(this.stepCounter),stepLabels:{list:[]},specification:Mf(t.field,iu(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=DD(o,a,this.languageCode);return{__class:"ActionStep:#Microsoft.Crm.Workflow.ObjectModel",id:PD(n?.id,"ActionStep",this.idCounter),name:n?.name??da(this.stepCounter),description:n?.description??"Action step",stepLabels:s,steps:{list:i},actionId:null,actionType:n?.actionType??"4",processId:n?.processId??dt(),uniqueName:n?.uniqueName??`id_${dt().replace(/-/g,"")}ActionStep`}}serializeAction(t){let r=Bf(this.entityName),n=t.stepName??da(this.stepCounter),i=t.stepLabels??zo(),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,iu(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,iu(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:dt(),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=DD(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??da(this.stepCounter),n=qt("ConditionStep",this.idCounter),i=[],a=t,o=!0;for(;a;){let s=r8(a.clauses,a.logic,this.entityName),l=o?a.branchName??da(this.stepCounter):da(this.stepCounter),c={__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:o?PD(a.branchId,"ConditionBranchStep",this.idCounter):qt("ConditionBranchStep",this.idCounter),name:l,description:a.displayName,stepLabels:zo(),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:zo(),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:zo(),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??dt():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:i8(r,i?.formId),status:n8(t.statecode),rootCondition:n,wfomRoot:i}}deserializeConditionStep(t){let r=(t.steps?.list??[]).filter(t8);return this.buildConditionNodeFromBranches(r,t,!0)}buildConditionNodeFromBranches(t,r,n){let[i,...a]=t,{clauses:o,logic:s}=_D(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)??dt(),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}=_D(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||dt(),field:u?.propertyName??"",stepName:l.name??void 0,displayName:l.description??void 0,...nu(u?.propertyValueExpr)}}),meta:i,acceptanceText:o}}deserializeAction(t){switch(t.__class){case"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=nu(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=nu(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 MD(e,t){return e==="SetFieldValue"&&t!==void 0&&s8.has(t.attributeType)&&(t.requiredLevel==="None"||t.requiredLevel==="Recommended")}var s8,UD=I(()=>{"use strict";s8=new Set(["Integer","Double","Decimal","Money","String","Memo","DateTime","Picklist","Lookup"])});function pa(e){return!l8.has(e)}function BD(e){return u8.has(e)?"string":e==="Money"?"money":e==="Integer"||e==="BigInt"?"integer":e==="Decimal"||e==="Double"?"decimal":c8.has(e)?"date":d8.has(e)?"boolean":"other"}function $D(e,t){let r=BD(e),n=BD(t);return r==="other"||n==="other"?e===t:r===n}var l8,u8,c8,d8,qD=I(()=>{"use strict";l8=new Set(["ContainsData","DoesNotContainData"]);u8=new Set(["String","Memo","EntityName"]),c8=new Set(["DateTime"]),d8=new Set(["Boolean"])});var KD={};ar(KD,{addElseIfInTree:()=>g8,appendToBranch:()=>m8,buildBreadcrumb:()=>S8,collectUsedFields:()=>A8,createEmptyAction:()=>w8,createEmptyCondition:()=>QD,findNode:()=>WD,findParent:()=>fa,getBranchPosition:()=>y8,hasAnyTriggerGeneratingAction:()=>zf,isTriggerGeneratingAction:()=>zD,moveBranchItemInTree:()=>b8,removeElseIfInTree:()=>v8,removeNodeFromTree:()=>jD,updateActionInTree:()=>Vf,updateConditionInTree:()=>ni,validateTree:()=>C8});function zD(e){return p8.has(e.type)}function qf(e,t,r,n,i,a){let o=i.get(r);o&&f8.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 VD(e,t,r,n,i,a,o){if(i!=="Clear")return;let s=a.get(n);MD(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(zD(t))return!0}else if(zf(t))return!0;return!1}function WD(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=WD(r,t);if(n)return n}}return null}function fa(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=fa(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=fa(n,t);if(i)return i}}return null}function jD(e,t){return{...e,trueBranch:GD(e.trueBranch,t),falseBranch:GD(e.falseBranch,t)}}function GD(e,t){return e.filter(r=>r.id!==t).map(r=>r.kind==="condition"?jD(r,t):r)}function ni(e,t,r){return e.id===t?r(e):{...e,trueBranch:e.trueBranch.map(n=>n.kind==="condition"?ni(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="condition"?ni(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 m8(e,t,r,n){return ni(e,t,i=>({...i,trueBranch:r==="true"?[...i.trueBranch,n]:i.trueBranch,falseBranch:r==="false"?[...i.falseBranch,n]:i.falseBranch}))}function h8(e){return e.length===1&&e[0].kind==="condition"}function g8(e,t,r){return ni(e,t,n=>HD(n,r))}function HD(e,t){if(h8(e.falseBranch))return{...e,falseBranch:[HD(e.falseBranch[0],t)]};let r=QD(t);return r.falseBranch=e.falseBranch,{...e,falseBranch:[r]}}function v8(e,t){let r=fa(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 ni(e,r.node.id,a=>({...a,falseBranch:i}))}function b8(e,t,r){let n=fa(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 ni(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=fa(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 QD(e){return{kind:"condition",id:dt(),displayName:e??"New Condition",clauses:[],logic:"AND",trueBranch:[],falseBranch:[],isCollapsed:!1}}function w8(e,t){let r={kind:"action",id:dt(),type:e,displayName:t??`New ${e}`};switch(e){case"Recommendation":return{...r,type:"Recommendation",field:"",recommendationTitle:"",messageText:"",applyActions:[{id:dt(),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 A8(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 C8(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 XD(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 XD(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(pa(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(pa(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 pa(n.operator)&&n.valueType==="Expression"&&!n.rawExpression&&!ru(n.expression)&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please complete the formula for this clause."});pa(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."}),pa(n.operator)&&qf(e.id,"Condition",n.field,n.valueType,r,t)}),[...e.trueBranch,...e.falseBranch].forEach(n=>{if(n.kind==="condition")XD(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&&!$D(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&&!ru(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),VD(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&&!ru(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),VD(n.id,"Recommendation","SetFieldValue",a.field,a.valueType,r,t))})}}})}function S8(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 p8,f8,YD=I(()=>{"use strict";Of();UD();qD();Lf();p8=new Set(["LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]);f8=new Set(["Lookup","Customer","Owner"])});var Wf=g(au=>{"use strict";Object.defineProperty(au,"__esModule",{value:!0});au.cloneJson=void 0;function N8(e){return JSON.parse(JSON.stringify(e))}au.cloneJson=N8});var t2=g(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.businessRuleApi=ii.WFOM_API_UNAVAILABLE_CODE=void 0;var Wr=jn(),E8=Jt(),ot=ge(),Cn=Z(),jf=ne();ii.WFOM_API_UNAVAILABLE_CODE="BUSINESS_RULE_API_UNAVAILABLE";async function ZD(e,t,r,n){let i=`/workflows(${_8})/Microsoft.Dynamics.CRM.${t}`;try{return(0,ot.ensureSuccess)(await e.post(i,{Entity:r.Entity,WfomJson:r.WfomJson},{headers:n}),e.apiUrl(i))}catch(a){throw a?.statusCode!==404?a:new jf.SdkError(ii.WFOM_API_UNAVAILABLE_CODE,`This environment does not expose 'Microsoft.Dynamics.CRM.${t}', so business rules cannot be authored here. That member is how the modern business-rule designer reads and writes rules; environments without it (18 of 20 measured 2026-08-28) have no supported authoring path. The SDK does NOT fall back to generating workflow XAML: that covered only 4 of the 7 action types and would silently save a rule different from the one you wrote.`)}}async function D8(e,t){let r=`/workflows(${t})${(0,Cn.odataQuery)([["$select","workflowid,statecode,statuscode"]])}`;try{let n=await e.get(r);if(n.status<200||n.status>=300)return null;let i=n.body;return{etag:(0,ot.readEtag)(n),statecode:typeof i?.statecode=="number"?i.statecode:null,statuscode:typeof i?.statuscode=="number"?i.statuscode:null}}catch{return null}}async function I8(e,t,r){let n=await D8(e,t);if(n===null||n.etag===null)throw new jf.SdkError(ot.VERSION_CONFLICT_CODE,`Refusing to update business rule '${t}': its current version could not be read, so the write could not be verified as conditional. The supported update api does not enforce If-Match, so proceeding would risk silently overwriting a concurrent edit. Re-fetch the rule and try again.`);if(n.etag!==r)throw new jf.SdkError(ot.VERSION_CONFLICT_CODE,`Version conflict updating business rule '${t}': it changed on the server since it was fetched (held ${r}, server ${n.etag}). Re-fetch the rule and re-apply the change.`);return{statecode:n.statecode,statuscode:n.statuscode}}var _8="00000000-0000-0000-0000-000000000000",ou={"Content-Type":"application/json",Accept:"application/json","OData-Version":"4.0","OData-MaxVersion":"4.0"},P8="workflowid,name,description,primaryentity,statecode,category,type",T8="category eq 2 and type eq 1";async function e2(e,t,r){var n;if(r==="Draft")return null;let i=(0,Cn.normalizeGuid)(t,"workflowid"),a=r==="Active",o={statecode:a?Wr.StateCode.Activated:Wr.StateCode.Draft,statuscode:a?Wr.StatusCode.Activated:Wr.StatusCode.Draft},s=`/workflows(${i})`,l=(0,ot.ensureSuccess)(await e.patch(s,o,{headers:ou}),e.apiUrl(s));return(n=(0,ot.readEtag)(l))!==null&&n!==void 0?n:await Ho(e,i)}async function Ho(e,t){let r=`/workflows(${t})${(0,Cn.odataQuery)([["$select","workflowid"]])}`;try{let n=await e.get(r);return n.status>=200&&n.status<300?(0,ot.readEtag)(n):null}catch{return null}}async function O8(e,t,r){let n=await Ho(e,t),i=await r(),a=(0,ot.readEtag)(i);if(a)return{response:i,etag:a};let o=await Ho(e,t);return{response:i,etag:n!==null&&n===o?o:null}}ii.businessRuleApi={async get(e,t){let r=(0,Cn.normalizeGuid)(t,"id"),n=`/workflows(${r})/Microsoft.Dynamics.CRM.RetrieveProcessWithWfomJson`,{response:i,etag:a}=await O8(e,r,async()=>(0,ot.ensureSuccess)(await e.get(n),e.apiUrl(n)));return{raw:i.body,etag:a}},async list(e,t){let r=[T8];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,Cn.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,Cn.odataQuery)([["$select",P8],["$filter",r.join(" and ")]])}`;return(await(0,E8.collectPages)(e,n,"listArtifacts('businessRule')")).map(a=>{var o,s;return{type:"businessRule",id:(o=a.workflowid)!==null&&o!==void 0?o:"",name:(s=a.name)!==null&&s!==void 0?s:"",entityLogicalName:a.primaryentity,isDirty:!1}})},async create(e,t){var r;let n=t,i=(0,Cn.normalizeGuid)(n.Entity.workflowid,"workflowid"),a=await ZD(e,"CreateProcessWithWfomJson",n,ou),o=(0,ot.resolveCreatedId)(a,"workflowid","business rule",i),s=null;try{s=await e2(e,o,n.status)}catch(l){try{await(0,ot.deleteRecord)(e,"workflows",o)}catch{}throw l}return{id:o,etag:(r=s??(0,ot.readEtag)(a))!==null&&r!==void 0?r:await Ho(e,o)}},async update(e,t,r,n){var i,a;let o=r,s=(0,Cn.normalizeGuid)(t,"id"),l=`/workflows(${s})`,u={...ou,"If-Match":(0,ot.requireEtag)(n,"business rule",s)},c=await I8(e,s,u["If-Match"]),d=c.statecode===Wr.StateCode.Activated;d&&(0,ot.ensureSuccess)(await e.patch(l,{statecode:Wr.StateCode.Draft,statuscode:Wr.StatusCode.Draft},{headers:u}),e.apiUrl(l));let p;try{p=await ZD(e,"UpdateProcessWithWfomJson",o,u)}catch(h){if(d)try{await e.patch(l,{statecode:Wr.StateCode.Activated,statuscode:(i=c.statuscode)!==null&&i!==void 0?i:Wr.StatusCode.Activated},{headers:ou})}catch{}throw h}let m=await e2(e,s,o.status);return{id:s,etag:(a=m??(0,ot.readEtag)(p))!==null&&a!==void 0?a:await Ho(e,s)}},delete(e,t){return(0,ot.deleteRecord)(e,"workflows",t)}}});var u2=g(Nn=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});Nn.BUSINESS_RULE_NULL_GUID=Nn.businessRuleRegistration=Nn.BusinessRuleAdapter=void 0;var r2=ws(),Hf=jn(),n2=(kD(),or(LD)),R8=(YD(),or(KD)),i2=Kt(),a2=ne(),x8=Wf(),Sn=br(),F8=t2(),L8=ht();function k8(e){return s2((0,x8.cloneJson)(e))}function s2(e){var t,r;let n=i=>(i??[]).map(a=>M8(a)?s2(a):a);return{...e,logic:(t=e.logic)!==null&&t!==void 0?t:"AND",clauses:(r=e.clauses)!==null&&r!==void 0?r:[],trueBranch:n(e.trueBranch),falseBranch:n(e.falseBranch)}}function M8(e){return Object.prototype.hasOwnProperty.call(e,"type")?!1:Object.prototype.hasOwnProperty.call(e,"clauses")||Object.prototype.hasOwnProperty.call(e,"trueBranch")||Object.prototype.hasOwnProperty.call(e,"falseBranch")||Object.prototype.hasOwnProperty.call(e,"logic")}function U8(e){var t;if(e===null||typeof e!="object"||Array.isArray(e))throw new a2.ValidationError("businessRule","(new)","/rootCondition",`rootCondition must be a condition object or null, got ${Array.isArray(e)?"array":typeof e}`);if(Object.prototype.hasOwnProperty.call(e,"type"))throw new a2.ValidationError("businessRule",(t=e.id)!==null&&t!==void 0?t:"(new)","/rootCondition","rootCondition looks like an ACTION (it carries 'type'), but it must be a condition. Wrap the action in a condition's trueBranch instead \u2014 a bare action would compile to an empty rule that saves successfully and does nothing.");return e}var B8="00000000-0000-0000-0000-000000000000";Nn.BUSINESS_RULE_NULL_GUID=B8;var $8=new Set(["Recommendation","LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]),q8=["ruleId","name","description","entityLogicalName","scope","status","rootCondition"],V8=["kind","id","displayName","logic","clauses","trueBranch","falseBranch"],G8=["id","field","fieldDisplayName","operator","valueType","value","valueField","lookupValue","expression","rawExpression","valueWorkflowType"];function o2(e){var t;return(0,Sn.isJsonObject)(e)?{...e,label:(t=e.label)!==null&&t!==void 0?t:""}:e}function z8(e){return{...e,...e.lookupValue!==void 0?{lookupValue:o2(e.lookupValue)}:{},...Array.isArray(e.applyActions)?{applyActions:e.applyActions.map(t=>(0,Sn.isJsonObject)(t)&&t.lookupValue!==void 0?{...t,lookupValue:o2(t.lookupValue)}:t)}:{}}}var su=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,n2.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,n2.serializeToWorkflowJson)(n),a=(r=n.ruleId)!==null&&r!==void 0?r:(0,r2.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:t.rootCondition===void 0?(0,R8.createEmptyCondition)():t.rootCondition===null?null:this.conditionFromJson(k8(U8(t.rootCondition)))},u=this.toArtifact(l);return u.id||(u.id=(0,r2.v4)()),u}assignMissingIds(t){return(0,L8.assignMissingIds)(t)}validate(t){let r=[],n=t.rootCondition;return n==null?r:(0,Sn.isJsonObject)(n)?(l2(n,"/rootCondition",r),r):(r.push((0,Sn.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:Hf.WorkflowCategory.BusinessRule,type:Hf.WorkflowTypeCode.Definition,mode:1,scope:Hf.WorkflowScope.Organization,primaryentity:t.entityLogicalName,iscrmuiworkflow:!0,processtriggerscope:n?1:2,...n?{processtriggerformid:t.scope}:{}}}conditionToJson(t){let r=this.residualBag(t,V8),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,G8),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(!$8.has(t.type))throw new Error(`Unsupported business-rule action type: ${t.type}`);return j8(t),{...z8(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")}};Nn.BusinessRuleAdapter=su;function l2(e,t,r){(0,Sn.optionalEnum)(e,"logic",["AND","OR"],t,"condition-logic-invalid",r),(0,Sn.childObjects)(e,"clauses",t,"clause",r);for(let n of["trueBranch","falseBranch"])(0,Sn.childObjects)(e,n,t,"branchItem",r).forEach(({node:a,index:o})=>{"clauses"in a||"trueBranch"in a||"falseBranch"in a?l2(a,`${t}/${n}/${o}`,r):W8(a,`${t}/${n}/${o}`,r)})}function W8(e,t,r){e.type==="SetDefaultValue"&&e.valueType==="Clear"&&r.push((0,Sn.issue)(`${t}/valueType`,"clear-only-set-field-value","Clear is only supported for SetFieldValue actions."))}function j8(e){if(e.type==="SetDefaultValue"&&e.valueType==="Clear")throw new Error("Clear is only supported for SetFieldValue actions.")}function H8(){return{adapter:new su,api:F8.businessRuleApi,publish:(e,t,r)=>(0,i2.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,i2.boundEntityPublishScope)(t)}}Nn.businessRuleRegistration=H8});var w2=g(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});En.appRegistration=En.AppAdapter=En.HEADER_NAV_BOOLEAN_RULE=void 0;var jr=br(),je=on(),Jo=kn(),Q8=Kt(),J8=ks(),Qf=Os(),Jf=yn(),X8=ht(),K8=Z(),h2=pi(),Y8=ne(),g2=xs();Object.defineProperty(En,"HEADER_NAV_BOOLEAN_RULE",{enumerable:!0,get:function(){return g2.HEADER_NAV_BOOLEAN_RULE}});var cu="7.0.0.0",c2=`<SiteMap IntroducedVersion="${cu}"></SiteMap>`,Z8="/_imgs/imagestrips/transparent_spacer.gif",eV="/_imgs/TableIconsFluentV9/document_one_page_sparkle.svg",tV=["Entity","Url","DefaultDashboard","Page","GenPageId"],Qo="sitemapId",d2="sitemapName",rV="sitemapNameUnique";function p2(e,t,r){if(e===void 0)return r;if(typeof e!="boolean")throw new Y8.ValidationError("app",t,[v2(e)]);return e}function v2(e){return(0,jr.issue)("/headerAndNavigationRefresh",g2.HEADER_NAV_BOOLEAN_RULE,`headerAndNavigationRefresh must be a boolean, got ${typeof e}`)}function nV(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,K8.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 du=class{constructor(t=h2.DEFAULT_LCID){this.lcid=t}toArtifact(t){let{bag:r,modeledEls:n}=lu(t,"Area");return{id:"",name:"",uniqueName:"",description:"",siteMap:{areas:n.map(i=>this.areaToJson(i)),bag:r},bag:(0,je.emptyBag)()}}fromArtifact(t){(0,Jf.installDomShim)();let r=this.assignMissingIds(JSON.parse(JSON.stringify(t))),n=new DOMParser().parseFromString("<root/>","text/xml"),i=this.rootToRaw(r);return(0,je.rebuildRaw)(i,(0,Jo.domEngine)(n),null)}fromApiResponse(t){var r,n,i,a,o,s,l,u,c,d;(0,Jf.installDomShim)();let p=t??{},m=(r=p.$sitemap)!==null&&r!==void 0?r:p,h=(0,Jo.parseXmlRoot)((n=m.sitemapxml)!==null&&n!==void 0?n:c2,c2),w=this.toArtifact(h);return w.id=(i=p.appmoduleid)!==null&&i!==void 0?i:"",w.name=(a=p.name)!==null&&a!==void 0?a:"",w.uniqueName=(o=p.uniquename)!==null&&o!==void 0?o:"",w.description=(s=p.description)!==null&&s!==void 0?s:"",w.bag={a:[[Qo,(u=(l=m.sitemapid)!==null&&l!==void 0?l:p._sitemapid_value)!==null&&u!==void 0?u:""],[d2,(c=m.sitemapname)!==null&&c!==void 0?c:""],[rV,(d=m.sitemapnameunique)!==null&&d!==void 0?d:""]],c:[]},w}toApiPayload(t){var r,n,i,a,o,s,l,u,c,d,p,m,h,w,y;(0,Jf.installDomShim)();let N=(0,Jo.serializeNode)(this.fromArtifact(t)),D=[],x=[];for(let q of(n=(r=t.siteMap)===null||r===void 0?void 0:r.areas)!==null&&n!==void 0?n:[])for(let G of(i=q.groups)!==null&&i!==void 0?i:[])for(let M of(a=G.subAreas)!==null&&a!==void 0?a:[])M.type==="Entity"&&M.entity?D.push(M.entity):M.type==="DashBoard"&&M.dashboardId&&x.push(M.dashboardId);let F=(o=t.bag)!==null&&o!==void 0?o:(0,je.emptyBag)();return{sitemapId:(s=m2(F,Qo))!==null&&s!==void 0?s:"",sitemapxml:N,sitemapname:m2(F,d2)||t.name,appModuleId:t.id,appModuleName:t.name,appModuleDescription:t.description,appModuleUniqueName:t.uniqueName,...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},...t.headerAndNavigationRefresh===void 0?{}:{appSettings:{[Qf.HEADER_AND_NAVIGATION_REFRESH]:p2(t.headerAndNavigationRefresh,(l=t.id)!==null&&l!==void 0?l:"(unknown)",!0)?Qf.APP_SETTING_ON:Qf.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=(m=t.components)===null||m===void 0?void 0:m.charts)!==null&&h!==void 0?h:[],dashboards:[...(y=(w=t.components)===null||w===void 0?void 0:w.dashboards)!==null&&y!==void 0?y:[],...x]}}}createDefault(t){var r,n,i,a,o,s;let l=!((r=t.siteMap)===null||r===void 0)&&r.areas&&t.siteMap.areas.length>0?t.siteMap.areas:[{id:"",title:"Area",groups:[{id:"",title:"Group",subAreas:[]}]}];return{id:(n=t.id)!==null&&n!==void 0?n:(0,X8.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New App",uniqueName:(a=t.uniqueName)!==null&&a!==void 0?a:"",description:(o=t.description)!==null&&o!==void 0?o:"",siteMap:{areas:l},...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},headerAndNavigationRefresh:p2(t.headerAndNavigationRefresh,(s=t.id)!==null&&s!==void 0?s:"(new)",!0),...typeof t.published=="boolean"?{published:t.published}:{},...t.components?{components:t.components}:{}}}assignMissingIds(t){let r=t;if(!r||typeof r!="object")return t;let n=r.siteMap;return n&&Array.isArray(n.areas)?n.areas.forEach(Yf):Array.isArray(r.areas)?r.areas.forEach(Yf):Array.isArray(r.groups)?Yf(r):Array.isArray(r.subAreas)?y2(r):"type"in r&&pu(r,"subarea"),t}validate(t){let r=[],n=t.published;n!==void 0&&typeof n!="boolean"&&r.push((0,jr.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(v2(a)),i==null)return r;if(!(0,jr.isJsonObject)(i))return r.push((0,jr.issue)("/siteMap","sitemap-must-be-object",`siteMap must be a JSON object, got ${typeof i}`)),r;let o=(0,jr.childObjects)(i,"areas","/siteMap","area",r),s=new Map;return o.forEach(({node:l,index:u})=>{let c=`/siteMap/areas/${u}`;(0,jr.childObjects)(l,"groups",c,"group",r).forEach(({node:p,index:m})=>{let h=`${c}/groups/${m}`;(0,jr.childObjects)(p,"subAreas",h,"subArea",r).forEach(({node:y,index:N})=>{let D=`${h}/subAreas/${N}`;(0,jr.optionalEnum)(y,"type",["Entity","URL","DashBoard","CustomPage","GenPage"],D,"subarea-type-invalid",r);let x=nV(y);if(!x)return;let F=s.get(x);if(F===void 0){s.set(x,D);return}r.push((0,jr.issue)(D,"subarea-duplicate-target",`the sitemap already navigates to this target at ${F}; a duplicate SubArea would pin it twice and a single removeElement would leave one behind`))})})}),r}applyServerIdentity(t,r){let n=r[Qo];if(!n)return;t.bag||(t.bag=(0,je.emptyBag)());let i=t.bag.a.find(a=>a[0]===Qo);i?i[1]=n:t.bag.a.push([Qo,n])}areaToJson(t){var r;let{bag:n,modeledEls:i}=lu(t,"Group"),a={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:Xf(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}=lu(t,"SubArea");return{id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:Xf(t,this.lcid),subAreas:i.map(a=>this.subAreaToJson(a)),bag:n}}subAreaToJson(t){var r;let{bag:n}=lu(t,null),i=iV(t),a={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",type:i,title:Xf(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!==Z8&&(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,je.emptyBag)(),l=uu(o)?[["IntroducedVersion",cu]]:[],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,je.mergeAttrs)(o.a,l),c:(0,je.spliceChildren)(o.c,u)}}areaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,je.emptyBag)(),i=uu(n),a=[];t.id&&a.push(["Id",t.id]),i&&a.push(["ShowGroups","true"],["ResourceId","SitemapDesigner.NewTitle"],["DescriptionResourceId","SitemapDesigner.NewTitle"],["IntroducedVersion",cu]),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=Kf((0,je.spliceChildren)(n.c,o),t.title,i,this.lcid);return{n:"Area",a:(0,je.mergeAttrs)(n.a,a),c:s}}groupToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,je.emptyBag)(),i=uu(n),a=[];t.id&&a.push(["Id",t.id]),i&&a.push(["ResourceId","SitemapDesigner.NewGroup"],["DescriptionResourceId","SitemapDesigner.NewGroup"],["ToolTipResourseId","SitemapDesigner.Unknown"],["IntroducedVersion",cu],["IsProfile","false"]);let o=t.subAreas.map(l=>this.subAreaToRaw(l)),s=Kf((0,je.spliceChildren)(n.c,o),t.title,i,this.lcid);return{n:"Group",a:(0,je.mergeAttrs)(n.a,a),c:s}}subAreaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,je.emptyBag)(),i=uu(n),a=oV(n.a,t.type),o=[];t.id&&o.push(["Id",t.id]),lV(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"&&!aV(a,"VectorIcon")&&o.push(["VectorIcon",eV]);let s=Kf((0,je.spliceChildren)(n.c,[]),t.title,i,this.lcid);return{n:"SubArea",a:(0,je.mergeAttrs)(a,o),c:s}}};En.AppAdapter=du;function lu(e,t){let r=(0,Jo.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,je.rawFromNode)((0,Jo.nodeLikeFromDom)(l))}),o+=1)}return{bag:{a:r,c:n},modeledEls:i}}function f2(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 Xf(e,t){var r;let n=f2(e,"Titles")[0];if(!n)return"";let a=f2(n,"Title").find(o=>o.getAttribute("LCID")===String(t));return a&&(r=a.getAttribute("Title"))!==null&&r!==void 0?r:""}function iV(e){return e.getAttribute("GenPageId")?"GenPage":e.getAttribute("Entity")?"Entity":e.getAttribute("Page")?"CustomPage":e.getAttribute("DefaultDashboard")?"DashBoard":"URL"}function uu(e){return e.a.length===0&&e.c.length===0}function aV(e,t){return e.some(([r])=>r===t)}function m2(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function oV(e,t){let r=sV(t);return e.filter(([n])=>!tV.includes(n)||r.has(n)).map(n=>[n[0],n[1]])}function sV(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 lV(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 Kf(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]=uV(e[i],t,n),a}return r?[cV(t,n),...e]:e}function uV(e,t,r){let n=!1,i=e.c.map(a=>!n&&a.n==="Title"&&dV(a,"LCID")===String(r)?(n=!0,{n:a.n,a:(0,je.mergeAttrs)(a.a,[["Title",t]]),c:a.c}):a);return n||i.unshift(b2(t,r)),{n:e.n,a:e.a.map(a=>[a[0],a[1]]),c:i}}function cV(e,t){return{n:"Titles",a:[],c:[b2(e,t)]}}function b2(e,t){return{n:"Title",a:[["LCID",String(t)],["Title",e]],c:[]}}function dV(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function pV(e){let t="0123456789abcdef",r="";for(let n=0;n<e;n+=1)r+=t[Math.floor(Math.random()*t.length)];return r}function pu(e,t){e&&(typeof e.id!="string"||e.id.length===0)&&(e.id=`${t}_${pV(8)}`)}function Yf(e){var t;pu(e,"area");for(let r of(t=e.groups)!==null&&t!==void 0?t:[])y2(r)}function y2(e){var t;pu(e,"group");for(let r of(t=e.subAreas)!==null&&t!==void 0?t:[])pu(r,"subarea")}function fV(e=h2.DEFAULT_LCID){return{adapter:new du(e),api:J8.appApi,languageSensitive:!0,publish:(t,r)=>(0,Q8.publishAppModule)(t,r),publishScope:t=>({envelope:"appmodule",targetIds:[t]})}}En.appRegistration=fV});var A2={};ar(A2,{ActionType:()=>em,AppActionOrigin:()=>lm,AppActionVisibilityType:()=>sm,ButtonType:()=>rm,CannotUpdateAppActionColumns:()=>mV,Context:()=>im,IconType:()=>tm,Location:()=>nm,OnClickEventType:()=>om,Scope:()=>am,VisibilityType:()=>Zf});var Zf,em,tm,rm,nm,im,am,om,sm,lm,mV,C2=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"})(Zf||(Zf={}));(function(e){e[e.NotSupported=0]="NotSupported",e[e.None=1]="None",e[e.JavaScript=2]="JavaScript",e[e.Expression=3]="Expression"})(em||(em={}));(function(e){e[e.NoIcon=0]="NoIcon",e[e.UseIcon=1]="UseIcon",e[e.UseWebResource=2]="UseWebResource"})(tm||(tm={}));(function(e){e[e.Standard=0]="Standard",e[e.Dropdown=1]="Dropdown",e[e.Split=2]="Split",e[e.Group=3]="Group"})(rm||(rm={}));(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"})(nm||(nm={}));(function(e){e[e.All=0]="All",e[e.Entity=1]="Entity"})(im||(im={}));(function(e){e[e.App=0]="App",e[e.Entity=1]="Entity",e[e.Global=2]="Global"})(am||(am={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.JavaScript=2]="JavaScript"})(om||(om={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.ClassicRules=2]="ClassicRules"})(sm||(sm={}));(function(e){e[e.Default=0]="Default",e[e.Migrated=1]="Migrated",e[e.MigratedClone=2]="MigratedClone"})(lm||(lm={}));mV=["appactionid","appmoduleid","context","contextvalue","location","name","type","uniquename","isdisabled","origin"]});var N2=g(fu=>{"use strict";Object.defineProperty(fu,"__esModule",{value:!0});fu.commandApi=void 0;var Tt=ge(),hV=ne(),Vt=Z(),gV="OnClickEventJavaScriptWebResourceId($select=name,webresourceid),IconWebResourceId($select=name,webresourceid)";async function um(e,t){let r=`/EntityDefinitions(LogicalName='${(0,Vt.odataLiteral)(t)}')${(0,Vt.odataQuery)([["$select","MetadataId"]])}`,i=(0,Tt.ensureSuccess)(await e.get(r),e.apiUrl(r)).body,a=i?.MetadataId;return a?(0,Vt.normalizeGuid)(a,"entityMetadataId"):""}fu.commandApi={async get(e,t){var r;let n=t,i=await um(e,n),a=i?`_contextentity_value eq ${i}`:`contextvalue eq '${(0,Vt.odataLiteral)(n)}'`,o=`/appactions${(0,Vt.odataQuery)([["$expand",gV],["$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 m=typeof p.appactionid=="string"?p.appactionid:void 0;if(m){let h=p["@odata.etag"];d[(0,Vt.normalizeGuid)(m,"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 um(e,r.entityLogicalName);return S2(e,{...r,entityMetadataId:n},!1)},async update(e,t,r,n,i){return S2(e,r,!0,i)},async delete(e,t){var r,n;let i=await um(e,t),a=i?`_contextentity_value eq ${i}`:`contextvalue eq '${(0,Vt.odataLiteral)(t)}'`,o=`/appactions${(0,Vt.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 S2(e,t,r,n){let i=t.entityMetadataId?(0,Vt.normalizeGuid)(t.entityMetadataId,"entityMetadataId"):"",a=bV(t.rows),o={};try{await vV(e,t,a,i,r,n,o)}catch(s){throw(0,hV.withPartialTokens)(s,{memberEtags:o})}return{id:t.entityLogicalName,etag:null,memberEtags:o}}async function vV(e,t,r,n,i,a,o){var s,l,u;for(let c of r)if(i&&c.exists){let d=(0,Vt.normalizeGuid)(c.appactionid,"id"),p=(s=a?.[d])!==null&&s!==void 0?s:c.etag,m=(0,Tt.echoWrite)("appactionid",p?{"If-Match":p}:void 0),h=`/appactions(${d})${m.query}`,w=(0,Tt.ensureSuccess)(await e.patch(h,c.body,m.options),e.apiUrl(h));o[d]=(0,Tt.readEtag)(w)}else{let d=(0,Tt.echoWrite)("appactionid"),p=`/appactions${d.query}`,m={...c.body};n&&m["[email protected]"]===void 0&&(m["[email protected]"]=`/entities(${n})`);let h=(0,Tt.ensureSuccess)(await e.post(p,m,d.options),e.apiUrl(p)),w=(0,Tt.readCreatedId)(h,"appactionid");w&&(o[(0,Vt.normalizeGuid)(w,"appactionid")]=(0,Tt.readEtag)(h))}for(let c of[...(l=t.deletedRowIds)!==null&&l!==void 0?l:[]].reverse()){let d=(0,Vt.normalizeGuid)(c,"id");await(0,Tt.deleteRecord)(e,"appactions",d,(u=a?.[d])!==null&&u!==void 0?u:void 0),delete o[d]}}function bV(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 B2=g(ma=>{"use strict";Object.defineProperty(ma,"__esModule",{value:!0});ma.commandRegistration=ma.CommandAdapter=void 0;var Be=(C2(),or(A2)),E2=Kt(),Gt=br(),yV=N2(),I2=ht(),ha=Z(),dm="$ClientSvg:",pm=".svg",wV=2,AV=1,CV=1,_2="entityMetadataId",SV=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"]),mu=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 m of l){let h=typeof m._parentappactionid_value=="string"&&m._parentappactionid_value?m._parentappactionid_value:"",w=(i=c.get(h))!==null&&i!==void 0?i:[];w.push(m),c.set(h,w)}let d=new Map;for(let m of(a=c.get(""))!==null&&a!==void 0?a:[]){let h=_V(m.location),w=(o=d.get(h))!==null&&o!==void 0?o:[];w.push(m),d.set(h,w)}let p=[];for(let[m,h]of d)p.push({location:m,groups:EV(h,c,x2(m),u)});return{id:u,entityLogicalName:u,commandBars:IV(p),bag:{a:[[_2,(s=t.entityMetadataId)!==null&&s!==void 0?s:""]]}}}fromArtifact(t){return{entityLogicalName:t.entityLogicalName,entityMetadataId:mm(t),appActions:cm(t).map(r=>r.row)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t,r){let n=new Set(r?cm(r).map(l=>l.appactionid):[]),i=cm(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?$V(l.row):U2(l.row)}}),s=[...n].filter(l=>!a.has(l));return{entityLogicalName:t.entityLogicalName,entityMetadataId:mm(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,I2.assignMissingIds)(t)}validate(t){let r=[];return(0,Gt.childObjects)(t,"commandBars","","commandBar",r).forEach(({node:i,index:a})=>{let o=`/commandBars/${a}`;(0,Gt.optionalEnum)(i,"location",["MainTab","ContextualTab","HomeTab"],o,"bar-location-invalid",r),(0,Gt.childObjects)(i,"groups",o,"group",r).forEach(({node:l,index:u})=>{let c=`${o}/groups/${u}`;(0,Gt.optionalGuidId)(l,"id",c,"group-id-invalid",r),P2((0,Gt.childObjects)(l,"controls",c,"control",r),`${c}/controls`,r)})}),r}};ma.CommandAdapter=mu;function P2(e,t,r){e.forEach(({node:n,index:i})=>{let a=`${t}/${i}`;(0,Gt.optionalGuidId)(n,"id",a,"control-id-invalid",r),(0,Gt.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,Gt.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,Gt.isJsonObject)(n.action)?(0,Gt.optionalEnum)(n.action,"type",["javascript"],`${a}/action`,"action-type-invalid",r):r.push((0,Gt.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,Gt.childObjects)(n,"children",a,"control",r);s.length>0&&P2(s,`${a}/children`,r)})}function T2(e){return{a:Object.entries(e)}}function NV(e){return Object.fromEntries(e.a)}function fm(e,t){if(e){for(let[r,n]of e.a)if(r===t)return n}}function mm(e){let t=fm(e.bag,_2);return typeof t=="string"?t:""}function EV(e,t,r,n){var i,a;let o=[],s=[];for(let l of gu(e))l.type===Be.ButtonType.Group?o.push({id:R2(l.name,n),title:typeof l.grouptitle=="string"?l.grouptitle:"",controls:gu((a=t.get((i=l.appactionid)!==null&&i!==void 0?i:""))!==null&&a!==void 0?a:[]).map(u=>hu(u,t,r,n)),bag:T2(l)}):s.push(hu(l,t,r,n));return s.length>0&&o.unshift({id:(0,I2.newId)(),title:"",controls:s}),o}function hu(e,t,r,n){var i,a,o,s;let l=R2(e.name,n),u={id:l,type:PV(e.type),label:typeof e.buttonlabeltext=="string"?e.buttonlabeltext:"",command:typeof e.appactionid=="string"?e.appactionid:l,bag:T2(e)},c=O2(e);c&&(u.icon=c);let d=DV(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 m=[];for(let h of gu(p))if(h.type===Be.ButtonType.Group){u.flyoutGroupId=(a=h.appactionid)!==null&&a!==void 0?a:void 0;for(let w of gu((s=t.get((o=h.appactionid)!==null&&o!==void 0?o:""))!==null&&s!==void 0?s:[]))m.push(hu(w,t,r,n))}else m.push(hu(h,t,r,n));u.children=m}return u}function O2(e){var t;if(!((t=e.IconWebResourceId)===null||t===void 0)&&t.name)return e.IconWebResourceId.name;if(e.fonticon)return e.fonticon.startsWith(dm)?e.fonticon.slice(dm.length)+pm:e.fonticon}function DV(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 D2(e){return typeof e.sequence=="number"?e.sequence:typeof e.buttonsequencepriority=="number"?e.buttonsequencepriority:0}function gu(e){return[...e].sort((t,r)=>D2(t)-D2(r))}function IV(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 R2(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 _V(e){switch(e){case Be.Location.Form:case Be.Location.QuickForm:return"MainTab";case Be.Location.HomePageGrid:case Be.Location.Dashboard:return"HomeTab";default:return"ContextualTab"}}function x2(e){switch(e){case"MainTab":return Be.Location.Form;case"HomeTab":return Be.Location.HomePageGrid;default:return Be.Location.SubGridStandard}}function PV(e){switch(e){case Be.ButtonType.Dropdown:return"FlyoutAnchor";case Be.ButtonType.Split:return"SplitButton";default:return"Button"}}function TV(e){switch(e){case"FlyoutAnchor":return Be.ButtonType.Dropdown;case"SplitButton":return Be.ButtonType.Split;default:return Be.ButtonType.Standard}}function OV(e){var t;return e.bag&&e.bag.a.length>0?!0:((t=e.title)!==null&&t!==void 0?t:"").length>0}function F2(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 cm(e,t=new Set){var r,n,i,a;let o=[],s=mm(e);for(let l of(r=e.commandBars)!==null&&r!==void 0?r:[]){let u=x2(l.location),c=((n=l.groups)!==null&&n!==void 0?n:[]).flatMap(m=>{var h;return(h=m.controls)!==null&&h!==void 0?h:[]}),d=c.length>0&&c.every(m=>!F2(m,t)),p=0;for(let m of(i=l.groups)!==null&&i!==void 0?i:[]){let h;if(OV(m)){let w=xV(m,u,void 0,e,s);o.push(w),h=w.appactionid}for(let w of(a=m.controls)!==null&&a!==void 0?a:[])L2(w,u,h,e,s,o,d?p:void 0,t),p+=1}}return o}function L2(e,t,r,n,i,a,o,s=new Set){var l;let u=RV(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||BV(u.appactionid);a.push(FV(d,t,u.appactionid,n,i));let p=c.every(m=>!F2(m,s));for(let[m,h]of c.entries())L2(h,t,d,n,i,a,p?m:void 0,s)}function RV(e,t,r,n,i,a){let o=k2(e,t,r,n,i),s=o.row;a!==void 0&&typeof s.sequence!="number"&&(s.sequence=a);let l=O2(s);return e.location!==void 0&&(s.location=e.location),s.type=TV(e.type),s.buttonlabeltext=e.label,LV(s,e.icon,l),MV(s,e.action),kV(s),e.hidden!==void 0&&(s.hidden=e.hidden),e.disabled!==void 0&&(s.isdisabled=e.disabled),{...o,row:s}}function xV(e,t,r,n,i){let a=k2(e,t,r,n,i);return a.row.type=Be.ButtonType.Group,a.row.grouptitle=e.title,a}function FV(e,t,r,n,i){let a=M2(e,t,n,i);return a["[email protected]"]=`/appactions(${(0,ha.normalizeGuid)(r,"Command flyout group id")})`,a.type=Be.ButtonType.Group,a.grouptitle===void 0&&(a.grouptitle=""),a.isgrouptitlehidden=!0,{appactionid:e,exists:!1,etag:null,row:a}}function k2(e,t,r,n,i){let a,o,s,l;if(e.bag&&e.bag.a.length>0){a=NV(e.bag),o=!0;let u=fm(e.bag,"@odata.etag");s=typeof u=="string"?u:null;let c=fm(e.bag,"appactionid");l=typeof c=="string"&&c?c:e.id}else l=e.id,a=M2(l,t,n,i),o=!1,s=null;return r&&(a["[email protected]"]=`/appactions(${(0,ha.normalizeGuid)(r,"Command parent appaction id")})`),{appactionid:l,exists:o,etag:s,row:a}}function M2(e,t,r,n){let i={appactionid:e,name:`${e}!${e.replace(/-/g,"").slice(0,32)}`,uniquename:"",location:t,context:Be.Context.Entity,contextvalue:r.entityLogicalName,scope:Be.Scope.Entity};return n&&(i["[email protected]"]=`/entities(${(0,ha.normalizeGuid)(n,"Command context entity metadata id")})`),i}function LV(e,t,r){if(t===r){let n=e._iconwebresourceid_value;typeof n=="string"&&n&&!e.fonticon&&(e["[email protected]"]=`/webresourceset(${(0,ha.normalizeGuid)(n,"Command icon web resource id")})`);return}if(t===void 0){e.fonticon="",e.IconWebResourceId=null;return}e.fonticon=t.toLowerCase().endsWith(pm)?dm+t.slice(0,t.length-pm.length):t,e.IconWebResourceId=null}function kV(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,ha.normalizeGuid)(a,`Command ${i}`);e[`${i}@odata.bind`]=`/canvasapps(${o})`};e.onclickeventtype===AV&&t("_onclickeventformulacomponentlibraryid_value","OnClickEventFormulaComponentLibraryId");let r=e.visibilitytype;(!r||r===CV)&&t("_visibilityformulacomponentlibraryid_value","VisibilityFormulaComponentLibraryId")}function MV(e,t){if(!(!t||t.type!=="javascript")){if(e.onclickeventtype=wV,t.webResourceId){let r=(0,ha.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 UV(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 BV(e){let t="";for(let r=0;r<4;r+=1)t+=UV(`${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 U2(e){let t={...e};for(let r of SV)delete t[r];return t}function $V(e){let t=U2(e);for(let r of Be.CannotUpdateAppActionColumns)delete t[r];return t}function qV(){return{adapter:new mu,api:yV.commandApi,publish:(e,t,r)=>(0,E2.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,E2.boundEntityPublishScope)(t)}}ma.commandRegistration=qV});var $2=g(vu=>{"use strict";Object.defineProperty(vu,"__esModule",{value:!0});vu.chartApi=void 0;var VV=Jt(),zt=ge(),Xo=Z(),GV="savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault",zV="savedqueryvisualizationid,name,primaryentitytypecode,charttype,isdefault";vu.chartApi={async get(e,t){let n=`/savedqueryvisualizations(${(0,Xo.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Xo.odataQuery)([["$select",GV]]),i=(0,zt.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,zt.readEtag)(i)}},async list(e,t){let r=`/savedqueryvisualizations${(0,Xo.odataQuery)([["$select",zV],["$filter",t?.entityLogicalName?`primaryentitytypecode eq '${(0,Xo.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,VV.collectPages)(e,r,"listArtifacts('chart')")).map(i=>{var a,o;return{type:"chart",id:(a=i.savedqueryvisualizationid)!==null&&a!==void 0?a:"",name:(o=i.name)!==null&&o!==void 0?o:"",entityLogicalName:i.primaryentitytypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,zt.echoWrite)("savedqueryvisualizationid"),a=`/savedqueryvisualizations${i.query}`,o=(0,zt.ensureSuccess)(await e.post(a,(0,zt.withClientMintedId)({name:n.name,description:n.description,datadescription:n.datadescription,presentationdescription:n.presentationdescription,primaryentitytypecode:n.primaryentitytypecode,charttype:n.charttype,isdefault:n.isdefault},"savedqueryvisualizationid",r),i.options),e.apiUrl(a));return{id:(0,zt.resolveCreatedId)(o,"savedqueryvisualizationid","chart",r),etag:(0,zt.readEtag)(o)}},async update(e,t,r,n){let i=r,a=(0,Xo.normalizeGuid)(t,"id"),o=(0,zt.echoWrite)("savedqueryvisualizationid",{"If-Match":(0,zt.requireEtag)(n,"chart",a)}),s=`/savedqueryvisualizations(${a})${o.query}`,l=(0,zt.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,datadescription:i.datadescription,presentationdescription:i.presentationdescription},o.options),e.apiUrl(s));return{id:a,etag:(0,zt.readEtag)(l)}},delete(e,t){return(0,zt.deleteRecord)(e,"savedqueryvisualizations",t)}}});var rI=g(ga=>{"use strict";Object.defineProperty(ga,"__esModule",{value:!0});ga.chartRegistration=ga.ChartAdapter=void 0;var hm=on(),q2=br(),Hr=kn(),V2=Kt(),WV=$2(),gm=yn(),jV=ht(),HV=["Column","StackedColumn","StackedColumn100","Bar","StackedBar","StackedBar100","Area","StackedArea","StackedArea100","Line","Pie","Doughnut","Funnel","Tag"],QV=new Map(HV.map(e=>[e.toLowerCase(),e]));function j2(e){var t;return e&&(t=QV.get(e.toLowerCase()))!==null&&t!==void 0?t:"Column"}function JV(){return'<Chart Palette="BrightPastel"><Series><Series ChartType="Column" ChartArea="Default" /></Series><ChartAreas><ChartArea Name="Default" /></ChartAreas><Legends><Legend Name="Default" /></Legends></Chart>'}function XV(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="${Ko(u.series.attribute)}" aggregate="${Ko(u.series.aggregate)}" />`).join("")+a.map(u=>`<attribute alias="${u.alias}" name="${Ko(u.category.attribute)}" groupby="true"${u.category.dateGrouping?` dategrouping="${Ko(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="${Ko(n)}">${o}</entity></fetch></fetchcollection><categorycollection><category alias="${l}"><measurecollection>${s}</measurecollection></category></categorycollection></datadefinition>`}var bu=class{toArtifact(t){var r,n,i,a,o,s,l;(0,gm.installDomShim)();let u=(r=t.datadescription)!==null&&r!==void 0?r:"",c=(n=t.presentationdescription)!==null&&n!==void 0?n:"",d=(0,Hr.parseXmlRoot)(u,"<datadefinition/>"),p=(0,Hr.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:H2(p),isDefault:(l=t.isdefault)!==null&&l!==void 0?l:!1,series:X2(d),categories:K2(d),presentation:Q2(p),dataBag:u?(0,Hr.projectElementBag)(d):void 0,presentationBag:c?(0,Hr.projectElementBag)(p):void 0,rowBag:KV(t.charttype,t.type)}}fromArtifact(t){(0,gm.installDomShim)();let{datadescription:r,presentationdescription:n}=YV(t);return{savedqueryvisualizationid:t.id,name:t.name,description:t.description,primaryentitytypecode:t.entityLogicalName,datadescription:r,presentationdescription:n,charttype:G2(t.rowBag,"charttype"),type:G2(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,gm.installDomShim)();let u=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,jV.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,q2.childObjects)(n,"series","","series",r),(0,q2.childObjects)(n,"categories","","category",r),r}};ga.ChartAdapter=bu;function KV(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 G2(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 H2(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 Q2(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 yu(e){return e.getElementsByTagName("fetch")[0]}function J2(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 X2(e){let t=yu(e);if(!t)return[];let r=J2(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,m=r.get(p);m&&(u.relatedEntity=m),i.push(u)}return i}function K2(e){var t;let r=yu(e);if(!r)return[];let n=J2(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,m=n.get(p);m&&(u.relatedEntity=m),a.push(u)}return a}function YV(e){if(!z2(e.dataBag)||!z2(e.presentationBag))return{datadescription:XV(e),presentationdescription:b6(e)};let t=new DOMParser().parseFromString("<root/>","text/xml"),r=W2(e.dataBag,"datadefinition",t),n=W2(e.presentationBag,"Chart",t);return vm(e.series,X2(r))||(e6(t,r,e.series),ZV(t,n,e.series.length,e.chartType)),vm(e.categories,K2(r))||t6(t,r,e.categories),e.chartType!==H2(n)&&eI(n,e.chartType),vm(e.presentation,Q2(n))||tI(n,e.presentation),{datadescription:(0,Hr.serializeNode)(r),presentationdescription:(0,Hr.serializeNode)(n)}}function z2(e){return!!e&&(e.c.length>0||e.a.length>0)}function ZV(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 W2(e,t,r){let n={n:t,a:(0,hm.mergeAttrs)(e.a,[]),c:(0,hm.spliceChildren)(e.c,[])};return(0,hm.rebuildRaw)(n,(0,Hr.domEngine)(r),null)}function e6(e,t,r){let n=yu(t),i=n?.getElementsByTagName("entity")[0];!n||!i||Y2(e,t,i,l6(n),r,c6,{aliasPrefix:"aggregate_column",addRef:i6,removeRef:s6})}function t6(e,t,r){let n=yu(t),i=n?.getElementsByTagName("entity")[0];!n||!i||Y2(e,t,i,u6(n),r,d6,{aliasPrefix:"groupby_column",addRef:a6,removeRef:o6})}function Y2(e,t,r,n,i,a,o){let s=new Map;for(let p of n){let m=p.getAttribute("alias");m&&s.set(m,p)}let l=new Set,u=[];for(let p of i){let m=p.alias?s.get(p.alias):void 0;m&&!l.has(m)?(a(m,p),l.add(m)):u.push(p)}let c=n.filter(p=>!l.has(p)),d=0;for(let p of u)if(d<c.length){let m=c[d];a(m,p),l.add(m),d+=1}else{let m=e.createElement("attribute"),h=p.alias||n6(t,o.aliasPrefix);m.setAttribute("alias",h),a(m,p),p6(e,r,m,p.relatedEntity),o.addRef(e,t,h)}for(let p of n)if(!l.has(p)){let m=p.getAttribute("alias");m&&o.removeRef(t,m),m6(p)}}function r6(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 n6(e,t){let r=r6(e);if(!r.has(t))return t;for(let n=2;;n+=1){let i=`${t}_${n}`;if(!r.has(i))return i}}function Z2(e,t){let r=t.getElementsByTagName("categorycollection")[0];if(r)return r;let n=e.createElement("categorycollection");return t.appendChild(n),n}function i6(e,t,r){let n=Z2(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 a6(e,t,r){let n=Z2(e,t),i=e.createElement("category");i.setAttribute("alias",r),n.appendChild(i)}function o6(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 s6(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"&&!g6(o)&&((r=o.parentNode)===null||r===void 0||r.removeChild(o))}}function l6(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 u6(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 c6(e,t){e.setAttribute("name",t.attribute),e.setAttribute("aggregate",t.aggregate),t.seriesType&&e.setAttribute("charttype",t.seriesType)}function d6(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 p6(e,t,r,n){n?f6(e,t,n).appendChild(r):t.appendChild(r)}function f6(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 m6(e){let t=e.parentNode;if(t&&(t.removeChild(e),t.tagName==="link-entity"&&!h6(t))){let r=t.parentNode;r&&r.removeChild(t)}}function h6(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 g6(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1)if(t[r].nodeType===1)return!0;return!1}function eI(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(!v6(r[i])){r[i].setAttribute("ChartType",t);return}}}function v6(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 tI(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 b6(e){let t=(0,Hr.parseXmlRoot)(JV(),"<Chart/>");return eI(t,e.chartType),tI(t,e.presentation),(0,Hr.serializeNode)(t)}function vm(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Ko(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function y6(){return{adapter:new bu,api:WV.chartApi,publish:(e,t,r)=>(0,V2.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,V2.boundEntityPublishScope)(t)}}ga.chartRegistration=y6});var nI=g(wu=>{"use strict";Object.defineProperty(wu,"__esModule",{value:!0});wu.dashboardApi=void 0;var w6=Jt(),Wt=ge(),Yo=Z(),A6="formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber",C6="formid,name,type,objecttypecode",S6=0,N6=10;wu.dashboardApi={async get(e,t){let n=`/systemforms(${(0,Yo.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Yo.odataQuery)([["$select",A6]]),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=[`(type eq ${S6} or type eq ${N6})`];t?.entityLogicalName&&r.push(`objecttypecode eq '${(0,Yo.odataLiteral)(t.entityLogicalName)}'`);let n=`/systemforms${(0,Yo.odataQuery)([["$select",C6],["$filter",r.join(" and ")]])}`;return(await(0,w6.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,Wt.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,Wt.ensureSuccess)(await e.post(a,(0,Wt.withClientMintedId)(o,"formid",r),i.options),e.apiUrl(a));return{id:(0,Wt.resolveCreatedId)(s,"formid","dashboard",r),etag:(0,Wt.readEtag)(s)}},async update(e,t,r,n){let i=r,a=(0,Yo.normalizeGuid)(t,"id"),o=(0,Wt.echoWrite)("formid",{"If-Match":(0,Wt.requireEtag)(n,"dashboard",a)}),s=`/systemforms(${a})${o.query}`,l=(0,Wt.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,Wt.readEtag)(l)}},delete(e,t){return(0,Wt.deleteRecord)(e,"systemforms",t)}}});var hI=g(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.dashboardRegistration=wr.TILE_CLASS_ID=wr.DashboardAdapter=void 0;var es=on(),jt=kn(),bm=Kt(),Zo=br(),E6=nI(),ym=yn(),ai=ht(),uI=Z(),cI=pi(),iI="0",wm="10",D6=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"]]),I6="{3FF9A528-DD50-4ACA-8F10-2E5ED73513AD}",Cu=class{constructor(t=cI.DEFAULT_LCID){this.lcid=t}toArtifact(t){var r,n,i,a;(0,ym.installDomShim)();let o=(r=t.formxml)!==null&&r!==void 0?r:"",s=(0,jt.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:_6(t.type),entityLogicalName:t.objecttypecode?t.objecttypecode:null,enabledForMobile:!!t.istabletenabled,layoutType:P6(s),components:aI(s,this.lcid),bag:(0,jt.projectElementBag)(s)}}fromArtifact(t){var r;return(0,ym.installDomShim)(),{formid:t.id,name:t.name,description:t.description,type:t.dashboardType==="Interactive"?wm:iI,objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",istabletenabled:t.enabledForMobile,formxml:oI(t,this.lcid)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){return{name:t.name,description:t.description,formxml:oI(t,this.lcid),istabletenabled:t.enabledForMobile,type:t.dashboardType==="Interactive"?wm:iI,objecttypecode:t.entityLogicalName}}createDefault(t){var r,n,i,a,o,s,l,u;(0,ym.installDomShim)();let c=(0,jt.parseXmlRoot)(V6(),"<form/>");return{id:(r=t.id)!==null&&r!==void 0?r:(0,ai.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:aI(c,this.lcid),bag:(0,jt.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,ai.newId)())}return t}validate(t){let r=[],n=(0,Zo.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,Zo.isJsonObject)(u)&&r.push((0,Zo.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,Zo.isJsonObject)(a.position)){let l=ts(a.position);i.has(l)?r.push((0,Zo.issue)(`${s}/position`,"component-position-collision",`two components occupy the same dashboard position (${l}); move one to a free cell`)):i.add(l)}}),r}};wr.DashboardAdapter=Cu;function _6(e){return String(e??"")===wm?"Interactive":"Standard"}function P6(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 Q(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 aI(e,t){let r=[];return Q(e,"tabs").flatMap(i=>Q(i,"tab")).forEach((i,a)=>{Q(i,"columns").flatMap(s=>Q(s,"column")).forEach((s,l)=>{Q(s,"sections").flatMap(c=>Q(c,"section")).forEach((c,d)=>{T6(c,{tabIndex:a,columnIndex:l,sectionIndex:d},r,t)})})}),r}function T6(e,t,r,n){Q(e,"rows").flatMap(a=>Q(a,"row")).forEach((a,o)=>{Q(a,"cell").forEach((s,l)=>{let u=O6(s,{...t,rowIndex:o,cellIndex:l},n);u&&r.push(u)})})}function O6(e,t,r){var n,i,a;let o=fI((n=e.getAttribute("id"))!==null&&n!==void 0?n:"");if(o.toLowerCase().startsWith("spacer"))return null;let s=Q(e,"control")[0];if(!s)return null;let l=(i=s.getAttribute("classid"))!==null&&i!==void 0?i:"",u=F6(s),c=L6(l,u,s),d=R6(s);return{id:(a=s.getAttribute("id"))!==null&&a!==void 0?a:o,type:c,name:pI(e,r),classId:l,position:t,colspan:Am(e,"colspan",1),rowspan:Am(e,"rowspan",1),parameters:u,bag:(0,jt.projectElementBag)(e),...d?{icProperties:d}:{}}}function dI(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 R6(e){let t=dI(e);return t?(0,jt.serializeNode)(t):void 0}function x6(e,t,r){let n=dI(t);if(!r){n&&t.removeChild(n);return}let i=new DOMParser().parseFromString(r,"text/xml").documentElement,a=(0,es.rebuildRaw)((0,es.rawFromNode)((0,jt.nodeLikeFromDom)(i)),(0,jt.domEngine)(e),null);n&&(0,jt.serializeNode)(n)===(0,jt.serializeNode)(a)||(n?t.replaceChild(a,n):t.appendChild(a))}function pI(e,t){var r,n;let i=Q(e,"labels")[0];if(!i)return"";let a=Q(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 F6(e){var t;let r={},n=Q(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 L6(e,t,r){var n;let i=D6.get(e.toUpperCase());return i?i==="chart"?t.ChartGridMode==="Chart"?"chart":"list":i==="assistant"&&((n=r.getAttribute("uniqueid"))!==null&&n!==void 0?n:"").toUpperCase()===I6?"assistant":i:"unknown"}function Am(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 fI(e){return e.replace(/^\{/,"").replace(/\}$/,"")}function k6(e,t){let r={n:"form",a:(0,es.mergeAttrs)(e.bag.a,[]),c:(0,es.spliceChildren)(e.bag.c,[])};return(0,es.rebuildRaw)(r,(0,jt.domEngine)(t),null)}function oI(e,t){let r=new DOMParser().parseFromString("<root/>","text/xml"),n=k6(e,r);return B6(r,n,e.components,t),M6(r,n,e.components,t),(0,jt.serializeNode)(n)}function M6(e,t,r,n){let i=mI(t);for(let a of r)i.has(ts(a.position))||U6(e,t,a,n)}function U6(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=G6(t,e,l);for(let W of Q(u,"row"))Q(W,"cell").some($=>Q($,"control").length>0)||u.removeChild(W);let c=r.classId||wr.TILE_CLASS_ID[r.type]||wr.TILE_CLASS_ID.iframe,d=r.rowspan&&r.rowspan>0?r.rowspan:4,p=r.bag&&sI(r.bag,"id")?String(sI(r.bag,"id")):Au((0,ai.newId)()),m=r.id?Au(r.id):Au((0,ai.newId)()),h=u.parentNode,w=Math.max(1,parseInt(h&&h.getAttribute&&h.getAttribute("columns")||"1",10)||1),y=Math.min(Math.max(1,r.colspan&&r.colspan>0?r.colspan:1),w),N=Q(u,"row"),D=N[N.length-1],x=D?Q(D,"cell").reduce((W,$)=>W+Am($,"colspan",1),0):0;(!D||x+y>w)&&(D=e.createElement("row"),u.appendChild(D));let F=e.createElement("cell");F.setAttribute("id",p),F.setAttribute("colspan",String(y)),F.setAttribute("rowspan",String(d)),F.setAttribute("showlabel","true");let q=e.createElement("labels"),G=e.createElement("label");G.setAttribute("description",(o=r.name)!==null&&o!==void 0?o:""),G.setAttribute("languagecode",String(n)),q.appendChild(G),F.appendChild(q);let M=e.createElement("control");M.setAttribute("id",m),M.setAttribute("classid",Au(c));let U=e.createElement("parameters"),B=(s=r.parameters)!==null&&s!==void 0?s:{};for(let W of Object.keys(B)){let $=(0,uI.createSafeXmlElement)(e,W,"dashboard tile parameter");$.textContent=B[W],U.appendChild($)}M.appendChild(U),F.appendChild(M),D.appendChild(F)}function sI(e,t){if(!e)return;let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function B6(e,t,r,n){var i;let a=mI(t),o=new Set(r.map(s=>ts(s.position)));for(let s of r){let l=a.get(ts(s.position));if(!l)continue;let u=Q(l,"control")[0];u&&($6(e,l,s.name,n),q6(e,u,s.parameters),lI(l,"colspan",s.colspan),lI(l,"rowspan",s.rowspan),s.icProperties!==void 0&&x6(e,u,s.icProperties))}for(let[s,l]of a)o.has(s)||(i=l.parentNode)===null||i===void 0||i.removeChild(l)}function mI(e){let t=new Map;return Q(e,"tabs").flatMap(n=>Q(n,"tab")).forEach((n,i)=>{Q(n,"columns").flatMap(o=>Q(o,"column")).forEach((o,s)=>{Q(o,"sections").flatMap(u=>Q(u,"section")).forEach((u,c)=>{Q(u,"rows").flatMap(p=>Q(p,"row")).forEach((p,m)=>{Q(p,"cell").forEach((h,w)=>{var y;fI((y=h.getAttribute("id"))!==null&&y!==void 0?y:"").toLowerCase().startsWith("spacer")||Q(h,"control")[0]&&t.set(ts({tabIndex:i,columnIndex:s,sectionIndex:c,rowIndex:m,cellIndex:w}),h)})})})})}),t}function ts(e){let t=e??{};return`${t.tabIndex}.${t.columnIndex}.${t.sectionIndex}.${t.rowIndex}.${t.cellIndex}`}function $6(e,t,r,n){if(r===pI(t,n))return;let i=Q(t,"labels")[0];i||(i=e.createElement("labels"),t.appendChild(i));let a=Q(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=Q(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,uI.createSafeXmlElement)(e,l,"dashboard component parameter");d.textContent=u,a.appendChild(d)}}}function lI(e,t,r){var n;((n=e.getAttribute(t))!==null&&n!==void 0?n:"")!==String(r)&&e.setAttribute(t,String(r))}function V6(e=2){let t=`{${(0,ai.newId)()}}`,r=`{${(0,ai.newId)()}}`,n=`{${(0,ai.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>`}wr.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 Au(e){return`{${e.replace(/[{}]/g,"")}}`}function G6(e,t,r){var n;let i=Q(e,"tabs").flatMap(u=>Q(u,"tab"))[0];if(!i)throw new Error("addDashboardTile: dashboard formxml has no <tab>");let a=Q(i,"columns").flatMap(u=>Q(u,"column"))[0];if(!a)throw new Error("addDashboardTile: dashboard formxml has no <column>");let o=Q(a,"sections").flatMap(u=>Q(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=Q(s,"rows")[0];return l||(l=t.createElement("rows"),s.appendChild(l)),l}function z6(e=cI.DEFAULT_LCID){return{adapter:new Cu(e),api:E6.dashboardApi,languageSensitive:!0,publish:(t,r,n)=>n?.entityLogicalName?(0,bm.publishBoundEntity)(t,n):(0,bm.publishDashboardById)(t,r),publishScope:(t,r)=>r?.entityLogicalName?(0,bm.boundEntityPublishScope)(r):{envelope:"dashboard",targetIds:[t]}}}wr.dashboardRegistration=z6});var AI=g(Nu=>{"use strict";Object.defineProperty(Nu,"__esModule",{value:!0});Nu.genPageApi=void 0;var wI=Jt(),Ne=ge(),Dt=Z(),Ar=ne(),Dn="uxagentprojects",ba="uxagentprojectfiles",va="uxagentprojectid",Cr="uxagentprojectfileid",Su=`${va},name`,W6=`${Cr},filename,filetype`;async function Cm(e,t,r,n){var i;let a=`/${t}(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Dt.odataQuery)([["$select",n]]),o=(0,Ne.ensureSuccess)(await e.get(a),e.apiUrl(a));return{row:(i=o.body)!==null&&i!==void 0?i:{},etag:(0,Ne.readEtag)(o)}}async function j6(e,t){let r=`/${ba}(${t})/filecontent/$value`,n=await e.get(r);if(n.status===404)return{status:"unavailable",reason:"unpublished"};(0,Ne.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 Ar.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 H6(e,t,r,n){if(!e.supportsBinaryPatch)throw new Ar.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,Ne.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 Sm(e,t){let r=`/${ba}/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()`+(0,Dt.odataQuery)([["$select",W6],["$filter",`_${va}_value eq ${t}`]]);return(await(0,wI.collectPages)(e,r,"fetchArtifact('genPage')")).map(i=>({row:i,etag:typeof i["@odata.etag"]=="string"?i["@odata.etag"]:null}))}async function gI(e,t,r){var n;let{etag:i}=await Cm(e,Dn,t,Su),a={};for(let{row:l,etag:u}of await Sm(e,t))a[(0,Dt.normalizeGuid)(String((n=l[Cr])!==null&&n!==void 0?n:""),Cr)]=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 vI(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}}Nu.genPageApi={async get(e,t){var r;let n=(0,Dt.normalizeGuid)(t,"id"),{row:i,etag:a}=await Cm(e,Dn,n,Su),o=await Sm(e,n),s={},l=[];for(let{row:u,etag:c}of o){let d=(0,Dt.normalizeGuid)(String((r=u[Cr])!==null&&r!==void 0?r:""),Cr);s[d]=c;let p=await j6(e,d);l.push({...u,content:p})}return{raw:{project:i,files:l},etag:a,memberEtags:s}},async list(e,t){let r=`/${Dn}/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()`+(0,Dt.odataQuery)([["$select",Su]]);return(await(0,wI.collectPages)(e,r,"listArtifacts('genPage')")).map(i=>{var a,o;return{type:"genPage",id:String((a=i[va])!==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;bI(e,n);let i=`/${Dn}`,a=(0,Ne.ensureSuccess)(await e.post(i,(0,Ne.withClientMintedId)({name:n.name},va,r)),e.apiUrl(i)),o=(0,Ne.resolveCreatedId)(a,va,"generative page",r),s=new Set;for(let l of n.files){let u=await yI(e,o,l,!0);s.add((0,Dt.normalizeGuid)(u.id,"file id"))}try{return{id:o,...vI(o,await gI(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");bI(e,a);let s=await Sm(e,o),{etag:l}=await Cm(e,Dn,o,Su);if(n&&l&&n!==l)throw new Ar.SdkError(Ne.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 Ar.SdkError(Ne.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:m})=>{var h;return(0,Dt.normalizeGuid)(String((h=m[Cr])!==null&&h!==void 0?h:""),Cr)})),c=new Set(a.files.map(m=>(0,Dt.normalizeGuid)(m.id,"file id")));if(!i)throw new Ar.SdkError(Ne.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(m=>m.toLowerCase()));{for(let h of c)if(!u.has(h)&&d.has(h))throw new Ar.SdkError(Ne.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 Ar.SdkError(Ne.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 m=new Map(s.map(({row:h,etag:w})=>{var y;return[(0,Dt.normalizeGuid)(String((y=h[Cr])!==null&&y!==void 0?y:""),Cr),w]}));for(let[h,w]of Object.entries(i??{})){let y=h.toLowerCase();if(!u.has(y))continue;let N=m.get(y);if(!w||!N)throw new Ar.SdkError(Ne.VERSION_CONFLICT_CODE,`Cannot verify generative-page file '${y}' before writing: ${w?"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(w!==N)throw new Ar.SdkError(Ne.VERSION_CONFLICT_CODE,`Generative-page file '${y}' changed on the server after this page was fetched (baseline ${w}, server ${N}) \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=`/${Dn}(${o})`;(0,Ne.ensureSuccess)(await e.patch(p,{name:a.name},{headers:{"If-Match":"*"}}),e.apiUrl(p));for(let m of a.files){let h=(0,Dt.normalizeGuid)(m.id,"file id");await yI(e,o,m,!u.has(h))}for(let m of u)c.has(m)||await(0,Ne.deleteRecord)(e,ba,m);try{return{id:o,...vI(o,await gI(e,o,c))}}catch(m){return{id:o,etag:null,memberEtags:{},warnings:[`The generative page was written, but re-reading its concurrency tokens failed (${m instanceof Error?m.message:String(m)}). 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,Ne.deleteRecord)(e,Dn,t)}};function bI(e,t){var r;if(((r=t.files)!==null&&r!==void 0?r:[]).some(i=>i.content.status==="available")&&!e.supportsBinaryPatch)throw new Ar.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 yI(e,t,r,n){let i=(0,Dt.normalizeGuid)(r.id,"file id"),a;if(n){let o=`/${ba}`,s=(0,Ne.ensureSuccess)(await e.post(o,(0,Ne.withClientMintedId)({filename:r.name,filetype:r.fileType,[`${va}@odata.bind`]:`/${Dn}(${t})`},Cr,i)),e.apiUrl(o));a=(0,Ne.readEtag)(s)}else{let o=`/${ba}(${i})`,s=(0,Ne.ensureSuccess)(await e.patch(o,{filename:r.name,filetype:r.fileType},{headers:{"If-Match":"*"}}),e.apiUrl(o));a=(0,Ne.readEtag)(s)}return r.content.status==="available"&&await H6(e,i,r.name,r.content.data),{id:i,etag:a}}});var EI=g(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.genPageRegistration=wa.GenPageAdapter=void 0;var Q6=AI(),J6=Kt(),In=br(),NI=ht(),CI=2e8;function SI(e){return typeof e=="string"&&e.trim()!==""?e:(0,NI.newId)()}function ya(e){return(0,In.isJsonObject)(e)?e:{}}function X6(e){let t=ya(e);return t.status==="available"&&typeof t.data=="string"?{status:"available",data:t.data}:{status:"unavailable",reason:"unpublished"}}var Eu=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var r,n;let i=t,a=ya(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=ya(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:CI),content:X6(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:SI(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:SI(i.id),name:(a=i.name)!==null&&a!==void 0?a:"index.tsx",fileType:(o=i.fileType)!==null&&o!==void 0?o:CI,content:(s=i.content)!==null&&s!==void 0?s:{status:"available",data:""}}})}}assignMissingIds(t){let r=ya(t);return(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,NI.newId)()),r}validate(t){let r=[],n=t.files;if(n!==void 0&&!Array.isArray(n))return r.push((0,In.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=ya(a),u=typeof l.id=="string"?l.id.trim().toLowerCase():"";if(u==="")r.push((0,In.issue)(s,"file-id-required","a generative-page file needs an id"));else{let m=i.get(u);m!==void 0?r.push((0,In.issue)(s,"file-id-duplicate",`two files share the id '${l.id}' (also at /files/${m}); 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,In.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,In.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=ya(d);p.status==="available"?typeof p.data!="string"&&r.push((0,In.issue)(s+"/content/data","file-content-data-invalid","available content needs base64 `data`")):p.status!=="unavailable"&&r.push((0,In.issue)(s+"/content/status","file-content-status-invalid",`content.status must be 'available' or 'unavailable', got ${String(p.status)}`))}),r}};wa.GenPageAdapter=Eu;function K6(){return{adapter:new Eu,api:Q6.genPageApi,publish:(e,t)=>(0,J6.publishGenPageById)(e,t),publishScope:e=>({envelope:"uxagentproject",targetIds:[e]})}}wa.genPageRegistration=K6});var II=g(Iu=>{"use strict";Object.defineProperty(Iu,"__esModule",{value:!0});Iu.reconcileBpfSecurityRoles=void 0;var Du=ge(),Nm=Z(),Y6="Global",DI={create:"Create",read:"Read",write:"Write",delete:"Delete"};async function Z6(e,t){var r,n;let i=`/EntityDefinitions(LogicalName='${t}')?$select=LogicalName,Privileges`,o=(n=(r=(0,Du.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(DI).forEach(u=>{let c=o.find(d=>d.PrivilegeType===DI[u]);if(c){let d=(0,Nm.normalizeGuid)(c.PrivilegeId,"PrivilegeId");s[u]=d,l.add(d)}}),{byAccess:s,all:l}}async function eG(e,t){var r,n;let i=`/RetrieveRolePrivilegesRole(RoleId=${t})`,o=(n=(r=(0,Du.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,Nm.normalizeGuid)(s.PrivilegeId,"PrivilegeId")))}async function tG(e,t,r){if(r.length===0)return;let n={Privileges:r.map(a=>({Depth:Y6,PrivilegeId:a}))},i=`/roles(${t})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;(0,Du.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function rG(e,t,r){let n={Privilege:{"@odata.type":"Microsoft.Dynamics.CRM.privilege",privilegeid:r}},i=`/roles(${t})/Microsoft.Dynamics.CRM.RemovePrivilegeRole`;(0,Du.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function nG(e,t,r){var n;if(!r||r.length===0)return;let i=await Z6(e,t.toLowerCase());for(let a of r){let o=(0,Nm.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 eG(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 tG(e,o,c);for(let p of d)await rG(e,o,p)}}Iu.reconcileBpfSecurityRoles=nG});var RI=g(Pu=>{"use strict";Object.defineProperty(Pu,"__esModule",{value:!0});Pu.bpfApi=void 0;var _n=jn(),iG=Jt(),Ht=ge(),Sr=Z(),aG=II(),_u={"Content-Type":"application/json",Accept:"application/json"},oG=`category eq ${_n.WorkflowCategory.BusinessProcessFlow} and type eq ${_n.WorkflowTypeCode.Definition} and businessprocesstype eq ${_n.BusinessProcessType.BusinessFlow}`,sG="workflowid,name,description,primaryentity,statecode,category,type,businessprocesstype,processorder",lG="workflowid,name,uniquename,description,primaryentity,statecode,statuscode,category,type,businessprocesstype,processorder,xaml,clientdata",uG=["xaml","name","description","processorder"];async function _I(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,aG.reconcileBpfSecurityRoles)(e,n,t.securityRoles)}async function Em(e,t,r){var n;if(r==="Draft")return null;let i=(0,Sr.normalizeGuid)(t,"workflowid"),a={statecode:_n.StateCode.Activated,statuscode:_n.StatusCode.Activated},o=`/workflows(${i})`,s=(0,Ht.ensureSuccess)(await e.patch(o,a,{headers:_u}),e.apiUrl(o));return(n=(0,Ht.readEtag)(s))!==null&&n!==void 0?n:await OI(e,i)}async function OI(e,t){let r=`/workflows(${t})${(0,Sr.odataQuery)([["$select","workflowid"]])}`,n=await e.get(r);return n.status>=200&&n.status<300?(0,Ht.readEtag)(n):null}async function cG(e,t){var r;let n=`/workflows(${t})${(0,Sr.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 PI(e,t,r){if(await cG(e,t)!==_n.StateCode.Activated)return!1;let n={statecode:_n.StateCode.Draft,statuscode:_n.StatusCode.Draft},i=`/workflows(${t})`,a={..._u};return r&&(a["If-Match"]=r),(0,Ht.ensureSuccess)(await e.patch(i,n,{headers:a}),e.apiUrl(i)),!0}async function TI(e,t){try{await Em(e,t,"Active")}catch{}}function dG(e){let t={};for(let r of uG)e[r]!==void 0&&(t[r]=e[r]);return t}Pu.bpfApi={async get(e,t){let n=`/workflows(${(0,Sr.normalizeGuid)(t,"id")})${(0,Sr.odataQuery)([["$select",lG]])}`,i=(0,Ht.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,Ht.readEtag)(i)}},async list(e,t){let r=[oG];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,Sr.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,Sr.odataQuery)([["$select",sG],["$filter",r.join(" and ")]])}`;return(await(0,iG.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,Sr.normalizeGuid)(r.record.workflowid,"workflowid"),i="/workflows",a=(0,Ht.ensureSuccess)(await e.post(i,r.record,{headers:_u}),e.apiUrl(i)),o=null;try{o=await Em(e,n,r.status),await _I(e,r)}catch(s){try{await(0,Ht.deleteRecord)(e,"workflows",n)}catch{}throw s}return{id:n,etag:o??(0,Ht.readEtag)(a)}},async update(e,t,r,n){var i;let a=r,o=(0,Sr.normalizeGuid)(t,"id"),s=await PI(e,o,n);try{let l=`/workflows(${o})`,u={..._u};n&&!s&&(u["If-Match"]=n);let c=(0,Ht.ensureSuccess)(await e.patch(l,dG(a.record),{headers:u}),e.apiUrl(l)),d=await Em(e,o,a.status);return await _I(e,a),{id:o,etag:(i=d??(0,Ht.readEtag)(c))!==null&&i!==void 0?i:await OI(e,o)}}catch(l){throw s&&await TI(e,o),l}},async delete(e,t){let r=(0,Sr.normalizeGuid)(t,"id"),n=await PI(e,r,null);try{await(0,Ht.deleteRecord)(e,"workflows",r)}catch(i){throw n&&await TI(e,r),i}}}});var h_=g(Sa=>{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});Sa.bpfRegistration=Sa.BpfAdapter=void 0;var Aa=ws(),pG=Js(),Tu=jn(),fG=RI(),Dm=on(),oi=kn(),WI=yn(),Ot=br(),Pn=ht(),Nr=ne(),mG=100,_m='<?xml version="1.0" encoding="utf-16"?>',xI=1033,jI="mxswa:Workflow",hG="mxswa:ActivityReference.Properties",gG="mcwo:StepLabel",vG="mcwb:Control",FI="mcwb:Control.ControlDisplayName",HI="mcwb:Control.DataFieldName",QI="DataFieldName",LI="ControlDisplayName",JI="Literal",Ou="x:Null",kI="x:String",Pm="x:Key",Tm="DisplayName",xu="Activities",bG="StepLabels",XI="StageId",KI="StageCategory",YI="NextStageId",ZI="ProcessStepId",Om="IsProcessRequired",e_="EntityComposite",t_="StageComposite",r_="StepComposite";function Im(e){return(0,Ot.isJsonObject)(e)?e:{}}function Er(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 si(e,t){var r;return(r=Er(e).find(n=>n.tagName===t))!==null&&r!==void 0?r:null}function Dr(e){return si(e,hG)}function pt(e,t){var r;return(r=Er(e).find(n=>n.getAttribute(Pm)===t))!==null&&r!==void 0?r:null}function Ca(e,t){var r;return((r=e.getAttribute("AssemblyQualifiedName"))!==null&&r!==void 0?r:"").includes(t)}function Jr(e){var t;return!e||!e.firstChild?"":(t=e.firstChild.nodeValue)!==null&&t!==void 0?t:""}function n_(e,t,r){e.firstChild?e.firstChild.nodeValue=r:e.appendChild(t.createTextNode(r))}function rs(e){var t;let r=(t=e.getAttribute(Tm))!==null&&t!==void 0?t:"",n=r.indexOf(": ");return n>=0?r.slice(n+2):r}function i_(e,t){var r;let n=(r=e.getAttribute(Tm))!==null&&r!==void 0?r:"",i=n.indexOf(": ");e.setAttribute(Tm,i>=0?n.slice(0,i+2)+t:t)}function a_(e,t){let r=pt(e,bG),n=si(r,gG);n&&n.setAttribute("Description",t)}function yG(e){let t=pt(e,KI);if(!t||t.tagName===Ou)return;let r=Jr(t).trim();return r===""?void 0:Number(r)}function wG(e){let t=pt(e,YI);if(!t||t.tagName===Ou)return;let r=Jr(t).trim();return r===""?void 0:r}function o_(e){let t=s_(e);if(!t)return;let r=u_(t,QI,HI);return r===""?void 0:r}function Rm(e,t){let r=Er(e);for(;r.length>0;){let n=r.pop();if(n.tagName===t)return n;for(let i of Er(n))r.push(i)}return null}function s_(e){let t=pt(Dr(e),xu);return t?Rm(t,vG):null}function l_(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 u_(e,t,r){var n;return l_(e,t)?(n=e.getAttribute(t))!==null&&n!==void 0?n:"":EG(e,r)}function MI(e,t,r,n){if(l_(e,t)){e.setAttribute(t,n);return}if(si(e,r)){AG(e,r,n);return}throw new Nr.InvalidArgumentError(`BPF step control exposes neither a '${t}' attribute nor a <${r}> wrapper to bind a column`)}function AG(e,t,r){let n=si(e,t),i=n?Rm(n,JI):null;i&&i.setAttribute("Value",r)}function c_(e){return rs(e)}function Fu(e){let t=si(e,jI),r=[];for(let n of Er(t).filter(i=>Ca(i,e_))){let i=pt(Dr(n),xu);for(let a of Er(i).filter(o=>Ca(o,t_)))r.push({el:a,entity:c_(n)})}return r}function xm(e){let t=pt(Dr(e),xu);return Er(t).filter(r=>Ca(r,r_))}function CG(e){let t=Dr(e),r=Jr(pt(t,Om)).trim().toLowerCase(),n=o_(e),i={id:Jr(pt(t,ZI)),name:rs(e)};return n!==void 0&&(i.fieldName=n),r==="true"&&(i.required=!0),i}function SG(e,t){let r=Dr(e),n=yG(r),i=wG(r),a={id:Jr(pt(r,XI)),name:rs(e),entityLogicalName:t,steps:xm(e).map(CG)};return n!==void 0&&(a.category=n),i!==void 0&&(a.nextStageId=i),a}function NG(e){return Fu(e).map(({el:t,entity:r})=>SG(t,r))}function Qr(e){return new Nr.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 EG(e,t){var r;let n=si(e,t),i=n?Rm(n,JI):null;return(r=i?.getAttribute("Value"))!==null&&r!==void 0?r:""}function Fm(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(Fm(e,s)):s.nodeType===3&&n.appendChild(e.createTextNode((r=s.nodeValue)!==null&&r!==void 0?r:""))}return n}function d_(e){return pt(Dr(e),xu)}function DG(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,Pn.newId)(),{body:o}=Lu(Lm(i,(0,Aa.v4)(),t.id,a));return Fm(e,Fu((0,oi.parseXmlRoot)(o,"<Activity/>"))[0].el)}function IG(e,t){let{body:r}=Lu(Lm("account",(0,Aa.v4)(),(0,Aa.v4)(),t.id));return Fm(e,xm(Fu((0,oi.parseXmlRoot)(r,"<Activity/>"))[0].el)[0])}function p_(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);for(let r of t)e.appendChild(r)}function f_(e,t,r,n){let i=pt(e,r);if(!i||!i.parentNode){if(n!==void 0&&n!=="")throw Qr(`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!==Ou){let s=t.createElement(Ou);s.setAttribute(Pm,r),a.replaceChild(s,i)}return}if(i.tagName===kI){Jr(i)!==n&&n_(i,t,n);return}let o=t.createElement(kI);o.setAttribute(Pm,r),o.appendChild(t.createTextNode(n)),a.replaceChild(o,i)}function _G(e,t,r){f_(e,t,KI,r===void 0?void 0:String(r))}function PG(e,t,r){f_(e,t,YI,r)}function m_(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 UI(e){return Jr(pt(Dr(e),XI))}function BI(e){return Jr(pt(Dr(e),ZI))}function $I(e,t,r){var n,i,a,o;let s=Dr(e);r.name!==rs(e)&&(i_(e,r.name),a_(s,r.name));let l=Jr(pt(s,Om)).trim().toLowerCase()==="true";if(((n=r.required)!==null&&n!==void 0?n:!1)!==l){let u=pt(s,Om);u&&n_(u,t,r.required?"True":"False")}if(((i=r.fieldName)!==null&&i!==void 0?i:"")!==((a=o_(e))!==null&&a!==void 0?a:"")){let u=s_(e);if(!u)throw new Nr.InvalidArgumentError("BPF step has no <mcwb:Control> element to bind a column to");let c=(o=r.fieldName)!==null&&o!==void 0?o:"";MI(u,QI,HI,c),c!==""&&u_(u,LI,FI)===""&&MI(u,LI,FI,c)}}function qI(e,t,r,n){var i;let a=Dr(e);if(!a)throw new Nr.InvalidArgumentError("BPF stage composite has no <\u2026ActivityReference.Properties>");if(r.name!==rs(e)&&(i_(e,r.name),a_(a,r.name)),_G(a,t,r.category),PG(a,t,n),r.relationshipName&&r.relationshipName.trim()!=="")throw Qr("a stage relationship / table change (multi-table authoring)");if(r.actions&&r.actions.length>0||r.branch)throw Qr("stage actions or conditional branching");let o=d_(e);if(!o)throw new Nr.InvalidArgumentError("BPF stage has no [Activities] collection");let s=(i=r.steps)!==null&&i!==void 0?i:[];if(s.length===0)throw new Nr.InvalidArgumentError(`BPF stage '${r.name}' must have at least one step`);let l=xm(e);if(m_(l,s.map(d=>d.id),BI)){l.forEach((d,p)=>$I(d,t,s[p]));return}let u=new Map(l.map(d=>[BI(d),d]));if(Er(o).some(d=>!Ca(d,r_)))throw Qr("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:IG(t,d)});p_(o,c),c.forEach((d,p)=>$I(d,t,s[p]))}function TG(e,t,r){let n=si(e,jI);if(!n)throw new Nr.InvalidArgumentError("BPF xaml has no <mxswa:Workflow> root activity");if(r.globalActions&&r.globalActions.length>0)throw Qr("global (process-completed/abandoned) actions");if(!r.stages||r.stages.length===0)throw new Nr.InvalidArgumentError("a BPF must have at least one stage");let i=Fu(e),a=i.map(p=>p.el);if(m_(a,r.stages.map(p=>p.id),UI)){i.forEach(({el:p,entity:m},h)=>{let w=r.stages[h];if(w.entityLogicalName&&w.entityLogicalName.trim()!==""&&w.entityLogicalName!==m)throw Qr(`changing a stage's table ('${w.entityLogicalName}' vs the process's '${m}')`);qI(p,t,w,w.nextStageId)});return}let o=Er(n).filter(p=>Ca(p,e_));if(o.length!==1)throw Qr("adding, removing or reordering stages on a multi-table process");let s=o[0],l=c_(s),u=d_(s);if(!u)throw new Nr.InvalidArgumentError("BPF primary entity composite has no [Activities] collection");if(Er(u).some(p=>!Ca(p,t_)))throw Qr("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 Qr(`a stage on a different table ('${p.entityLogicalName}') than the process primary ('${l}')`);let c=new Map(a.map(p=>[UI(p),p])),d=r.stages.map(p=>{var m;return(m=c.get(p.id))!==null&&m!==void 0?m:DG(t,p,l)});p_(u,d),d.forEach((p,m)=>{let h=m<d.length-1?r.stages[m+1].id:void 0;qI(p,t,r.stages[m],h)})}function Lu(e){let t=e.match(/^<\?xml[^>]*\?>\s*/),r=t?t[0]:"";return{prolog:r,body:e.slice(r.length)}}function OG(e){var t,r,n,i,a,o;(0,WI.installDomShim)();let s=(t=e.bag)===null||t===void 0?void 0:t.xaml;if(s){let p=new pG.DOMParser().parseFromString("<root/>","text/xml"),m={n:"Activity",a:(0,Dm.mergeAttrs)(s.a,[]),c:(0,Dm.spliceChildren)(s.c,[])};return{root:(0,Dm.rebuildRaw)(m,(0,oi.domEngine)(p),null),prolog:(n=(r=e.bag)===null||r===void 0?void 0:r.xamlProlog)!==null&&n!==void 0?n:_m,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=Lm(e.entityLogicalName,(0,Aa.v4)(),l?.id&&l.id.trim()!==""?l.id:(0,Aa.v4)(),u?.id&&u.id.trim()!==""?u.id:(0,Aa.v4)()),{body:d}=Lu(c);return{root:(0,oi.parseXmlRoot)(d,"<Activity/>"),prolog:_m,eol:"lf"}}function RG(e){let{root:t,prolog:r,eol:n}=OG(e);TG(t,t.ownerDocument,e);let i=(0,oi.serializeNode)(t);return n==="crlf"&&(i=i.replace(/\n/g,`\r+`)),r+i}function xG(e){return e.uniqueName&&e.uniqueName.trim()!==""?e.uniqueName:`new_${(e.name||"businessprocessflow").toLowerCase().replace(/[^a-z0-9]/g,"")||"businessprocessflow"}`}var Ru=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var r,n;(0,WI.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}=Lu(a),u=(0,oi.parseXmlRoot)(l,"<Activity/>");o.stages=NG(u),o.bag={xaml:(0,oi.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,Pn.newId)(),name:t.name,uniquename:xG(t),primaryentity:t.entityLogicalName,xaml:RG(t),category:Tu.WorkflowCategory.BusinessProcessFlow,type:Tu.WorkflowTypeCode.Definition,businessprocesstype:Tu.BusinessProcessType.BusinessFlow,scope:Tu.WorkflowScope.Organization,processorder:(r=t.order)!==null&&r!==void 0?r:mG};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 Nr.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(GI):[GI({id:(0,Pn.newId)(),name:"New Stage",steps:[]})],o={id:t.id&&t.id.trim()!==""?t.id:(0,Pn.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=Im(t);(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,Pn.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=Im(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 m=Array.isArray(l.steps)?l.steps:[];m.length===0&&r.push((0,Ot.issue)(`${c}/steps`,"stage-needs-step","a BPF stage must have at least one step")),m.length>30&&r.push((0,Ot.issue)(`${c}/steps`,"too-many-steps",`a stage allows at most 30 steps, got ${m.length}`));let h=new Map;m.forEach((w,y)=>{let N=`${c}/steps/${y}`,D=typeof Im(w).id=="string"?w.id.trim():"";D===""?r.push((0,Ot.issue)(`${N}/id`,"step-id-required","a step needs an id")):h.has(D.toLowerCase())?r.push((0,Ot.issue)(`${N}/id`,"step-id-duplicate",`two steps in this stage share the id '${w.id}'`)):h.set(D.toLowerCase(),y)}),l.branch&&!VI(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!==""&&!VI(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=FG(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}};Sa.BpfAdapter=Ru;function FG(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 VI(e,t){return e.some(r=>r.id===t)}function GI(e){var t,r;let n=e.steps&&e.steps.length>0?e.steps.map(zI):[zI({id:(0,Pn.newId)(),name:"New Step"})],i={id:e.id&&e.id.trim()!==""?e.id:(0,Pn.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 zI(e){var t;let r={id:e.id&&e.id.trim()!==""?e.id:(0,Pn.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 Lm(e,t,r,n){return`${_m}<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="${xI}" /></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="${xI}" /></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 LG(){return{adapter:new Ru,api:fG.bpfApi,languageSensitive:!0}}Sa.bpfRegistration=LG});var g_=g(ku=>{"use strict";Object.defineProperty(ku,"__esModule",{value:!0});ku.buildRegistrations=void 0;var kG=VE(),MG=nD(),UG=u2(),BG=w2(),$G=B2(),qG=rI(),VG=hI(),GG=EI(),zG=h_();function WG(e){let t=new Map;return t.set("form",(0,kG.formRegistration)(e)),t.set("view",(0,MG.viewRegistration)()),t.set("businessRule",(0,UG.businessRuleRegistration)()),t.set("app",(0,BG.appRegistration)(e)),t.set("command",(0,$G.commandRegistration)()),t.set("chart",(0,qG.chartRegistration)()),t.set("dashboard",(0,VG.dashboardRegistration)(e)),t.set("genPage",(0,GG.genPageRegistration)()),t.set("bpf",(0,zG.bpfRegistration)()),t}ku.buildRegistrations=WG});var E_=g(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.removeRowSummary=Fe.configureRowSummary=Fe.buildGptDynamicPrompt=Fe.setAppAiFeatures=Fe.getAiReadiness=Fe.saveSettingValue=Fe.retrieveSetting=Fe.AI_GATE=void 0;var ir=ge(),He=Z(),v_=ht(),Xr=ne();Fe.AI_GATE={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabled",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"EnableNLGridSearch",nlChart:"NLChartVisualizationSetting",summaries:"EnableFormInsights",m365:"m365copilotmodelappenabled"};var jG={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabledOnByDefault",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"NLGridSearchSetting",nlChart:"NLChartDataVisualizationSetting",m365:"m365copilotmodelappenabled"},HG={formFill:{enabled:"2",disabled:"1"},formFillSuggestions:{enabled:"2",disabled:"1"},formFillSmartPaste:{enabled:"2",disabled:"1"},formFillFiles:{enabled:"2",disabled:"1"}};function A_(e){return HG[e]}var Mu=1e6;function QG(e,t){let r=A_(t),n=()=>{throw new Xr.InvalidArgumentError(`setAppAiFeatures: '${t}' must be a boolean or an integer between 0 and ${Mu} (e.g. 0, 1, 2); got '${String(e)}'.`)},i=a=>r?a?r.enabled:r.disabled:a?"1":"0";if(typeof e=="boolean")return i(e);if(typeof e=="number")return!Number.isSafeInteger(e)||e<0||e>Mu?n():String(e);if(typeof e=="string"){let a=e.trim(),o=a.toLowerCase();if(o==="true")return i(!0);if(o==="false")return i(!1);if(/^[0-9]+$/.test(a)){let s=a.replace(/^0+(?=[0-9])/,"");return s.length>String(Mu).length||Number(s)>Mu?n():s}}return n()}function JG(e,t){let r=A_(t);return r?e===r.enabled:e!=="0"}async function XG(e,t){var r,n,i;let a=`/appmodules${(0,He.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,He.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 KG(e,t){var r,n;let i=`/appmodules${(0,He.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,He.odataLiteral)(t)}'`]])}`,a;try{a=await e.get(i)}catch(l){throw new Xr.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 Xr.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 Xr.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 Xr.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a row with no appmoduleid.`);return s}var b_=new WeakMap;async function YG(e,t){var r,n,i;let a=b_.get(e);if(a||(a=new Map,b_.set(e,a)),a.has(t))return a.get(t);let o=`/settingdefinitions${(0,He.odataQuery)([["$select","settingdefinitionid"],["$filter",`uniquename eq '${(0,He.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 ZG(e,t,r){var n,i;let a=await YG(e,r);if(!t||!a)return;let o=`/appsettings${(0,He.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 e7=4,t7=500,y_=20,w_=3e4;function r7(e){if(e===void 0)return e7;if(!Number.isFinite(e))throw new Xr.InvalidArgumentError(`setAppAiFeatures: verifyAttempts must be a finite integer between 1 and ${y_}; got ${e}.`);return Math.min(y_,Math.max(1,Math.floor(e)))}function n7(e){if(e===void 0)return t7;if(!Number.isFinite(e))throw new Xr.InvalidArgumentError(`setAppAiFeatures: verifyDelayMs must be a finite number between 0 and ${w_}; got ${e}.`);return Math.min(w_,Math.max(0,Math.floor(e)))}function i7(e){return e>0?new Promise(t=>setTimeout(t,e)):Promise.resolve()}async function a7(e,t,r,n,i,a,o){let s,l,u,c=!1;for(let d=0;d<a;d+=1){d>0&&await i7(o*d);let p;try{let m=await t();m?(p=await ZG(e,m,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(m){p=void 0,u=m.message}c=p!==void 0,l=p?.exists;try{s=(await Uu(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 C_(e,t){return t===2?String(e).toLowerCase()==="true":e!=null&&e!=="0"&&e!==""}async function Uu(e,t,r={}){var n,i;let a=[`SettingName='${(0,He.odataPathLiteral)(t)}'`];r.appUniqueName&&a.push(`AppUniqueName='${(0,He.odataPathLiteral)(r.appUniqueName)}'`);let o=`/RetrieveSetting(${a.join(",")})`,l=(i=(n=(0,ir.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}}Fe.retrieveSetting=Uu;async function S_(e,t,r,n={}){let i={SettingName:t,Value:r};n.appUniqueName&&(i.AppUniqueName=n.appUniqueName),n.solutionUniqueName&&(i.SolutionUniqueName=n.solutionUniqueName),(0,ir.ensureSuccess)(await e.post("/SaveSettingValue",i),e.apiUrl("/SaveSettingValue"))}Fe.saveSettingValue=S_;async function o7(e,t={}){let r={};for(let[n,i]of Object.entries(Fe.AI_GATE)){let{value:a,dataType:o}=await Uu(e,i,t);r[n]={enabled:C_(a,o),setting:i,value:a}}return r}Fe.getAiReadiness=o7;async function s7(e,t,r,n={}){var i,a,o;if(!t||!t.trim())throw new Xr.InvalidArgumentError("setAppAiFeatures: a non-empty appUniqueName is required (an empty value would write the setting at organization scope, affecting every app).");let s=r7(n.verifyAttempts),l=n7(n.verifyDelayMs),u=[];for(let[y,N]of Object.entries(r)){if(N===void 0)continue;let D=jG[y];D&&u.push({feature:y,setting:D,requestedValue:QG(N,y)})}let c=[],d=n.appModuleId?(0,He.normalizeGuid)(n.appModuleId,"appModuleId"):void 0;if(d){let y=await KG(e,t);if(y&&(0,He.normalizeGuid)(y,"appModuleId")!==d)throw new Xr.InvalidArgumentError(`setAppAiFeatures: appModuleId '${d}' does not belong to app '${t}' (which resolves to '${y}'). Settings are written by unique name, so verifying against a different app would report success for a write that never landed.`)}let p,m=async()=>d||(p||(p=await XG(e,t)),p),h=new Map,w=async y=>{let N=Fe.AI_GATE[y];if(N){if(!h.has(N)){let{value:D,dataType:x}=await Uu(e,N);h.set(N,{enabled:C_(D,x),setting:N,value:D})}return h.get(N)}};for(let{feature:y,setting:N,requestedValue:D}of u)try{if(JG(D,y)){let q=await w(y);if(!q?.enabled){c.push({feature:y,setting:N,requestedValue:D,status:"skipped",reason:`the org readiness gate '${(i=q?.setting)!==null&&i!==void 0?i:y}' is off, so the feature cannot be enabled for this app`});continue}}await S_(e,N,D,{appUniqueName:t,solutionUniqueName:n.solutionUniqueName});let x=await a7(e,m,t,N,D,s,l),F={feature:y,setting:N,requestedValue:D,effectiveValue:x.effectiveValue,appOverrideExists:x.appOverrideExists};x.result==="proven"?c.push({...F,status:"applied"}):x.result==="absent"?c.push({...F,status:"notPersisted",reason:`the write reported success but no app-scope override holding '${D}' was observed for '${N}' after ${s} attempt(s) \u2014 it reads '${(a=x.effectiveValue)!==null&&a!==void 0?a:""}' for this app (Dataverse can accept an app-scope write without storing it)`}):c.push({...F,status:"unverified",reason:`the write was issued but could not be confirmed: ${(o=x.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(x){c.push({feature:y,setting:N,requestedValue:D,status:"failed",reason:x.message})}return{applied:c.filter(y=>y.status==="applied").map(y=>y.feature),skipped:c.filter(y=>y.status==="skipped").map(y=>y.feature),notPersisted:c.filter(y=>y.status==="notPersisted").map(y=>y.feature),unverified:c.filter(y=>y.status==="unverified").map(y=>y.feature),failed:c.filter(y=>y.status==="failed").map(y=>y.feature),outcomes:c}}Fe.setAppAiFeatures=s7;var l7="GptPowerPrompt",u7='{ "consumptionSource": "Api", "partnerSource": "AIBuilder", "consumptionSourceVersion": "GptApiClient"}';function N_(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:""}}Fe.buildGptDynamicPrompt=N_;async function c7(e,t){var r,n;let i=`/EntityDefinitions(LogicalName='${(0,He.odataPathLiteral)(t)}')${(0,He.odataQuery)([["$select","MetadataId"]])}`;return(n=(r=(0,ir.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.MetadataId)!==null&&n!==void 0?n:""}async function d7(e,t,r={}){var n,i,a,o,s;let l=`ais_RowSummary_${t.entityLogicalName}`,u=`/aiskillconfigs${(0,He.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,He.odataLiteral)(l)}'`],["$top",1]])}`,c=((i=(n=(0,ir.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,He.odataQuery)([["$select","msdyn_aitemplateid"],["$filter",`msdyn_uniquename eq '${l7}'`],["$top",1]])}`,p=((s=(o=(a=(0,ir.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,m=(0,v_.newId)(),h=(0,v_.newId)(),w=JSON.stringify(N_(t)),y={ModelId:m,RunConfigurationId:h,ModelName:`${t.entityLogicalName} row summary`,TemplateId:p,CustomConfiguration:w,Source:u7,RunConfiguration:""};(0,ir.ensureSuccess)(await e.post("/AIModelPublish",y),e.apiUrl("/AIModelPublish"));try{let N=await c7(e,t.entityLogicalName),D={uniquename:l,description:`${t.entityLogicalName} row summary`,"[email protected]":`/entities(${N})`,"[email protected]":`/msdyn_aimodels(${m})`,aiskill:"RowSummary"},x=(0,ir.ensureSuccess)(await e.post("/aiskillconfigs",D),e.apiUrl("/aiskillconfigs")),F=(0,ir.requireCreatedId)(x,"aiskillconfigid","row-summary skill");return{modelId:m,aiSkillConfigId:F}}catch(N){try{await e.delete(`/msdyn_aimodels(${m})`)}catch{}throw N}}Fe.configureRowSummary=d7;async function p7(e,t){var r,n;let i=`ais_RowSummary_${t.entityLogicalName}`,a=`/aiskillconfigs${(0,He.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,He.odataLiteral)(i)}'`],["$top",1]])}`,o=((n=(r=(0,ir.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,ir.ensureSuccess)(await e.delete(s),e.apiUrl(s)),o._aimodel_value){let l=`/msdyn_aimodels(${o._aimodel_value})`;(0,ir.ensureSuccess)(await e.delete(l),e.apiUrl(l))}}Fe.removeRowSummary=p7});var D_=g(Na=>{"use strict";Object.defineProperty(Na,"__esModule",{value:!0});Na.findArtifact=Na.resolveArtifact=void 0;var ft=Z(),Kr=Ps(),f7=ks(),m7=ge(),h7=ne();async function g7(e,t,r){var n,i,a,o,s,l,u,c,d,p,m,h;switch(t){case"app":{let w=(0,f7.unpublishedAppModulesQuery)("appmoduleid,name,appmoduleidunique",`uniquename eq '${(0,ft.odataLiteral)((n=r.uniqueName)!==null&&n!==void 0?n:"")}'`,1),N=(i=(0,m7.ensureSuccess)(await e.get(w),e.apiUrl(w)).body)===null||i===void 0?void 0:i.value,D=N&&N[0];return D?[{id:String(D.appmoduleid),name:String(D.name),appModuleIdUnique:String(D.appmoduleidunique)}]:[]}case"dashboard":return(await(0,Kr.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,ft.odataLiteral)((a=r.name)!==null&&a!==void 0?a:"")}' and type eq 0`,top:10})||[]).map(y=>({id:String(y.formid),name:String(y.name)}));case"command":{let w=await(0,Kr.queryRecords)(e,"appaction",{select:["appactionid","buttonlabeltext"],filter:`contextvalue eq '${(0,ft.odataLiteral)((o=r.entity)!==null&&o!==void 0?o:"")}'`,top:1});return w&&w.length?[{id:String(r.entity),entity:String(r.entity)}]:[]}case"form":return(await(0,Kr.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,ft.odataLiteral)((s=r.name)!==null&&s!==void 0?s:"")}' and objecttypecode eq '${(0,ft.odataLiteral)((l=r.entity)!==null&&l!==void 0?l:"")}'`,top:10})||[]).map(y=>({id:String(y.formid),name:String(y.name)}));case"chart":return(await(0,Kr.queryRecords)(e,"savedqueryvisualization",{select:["savedqueryvisualizationid","name"],filter:`name eq '${(0,ft.odataLiteral)((u=r.name)!==null&&u!==void 0?u:"")}' and primaryentitytypecode eq '${(0,ft.odataLiteral)((c=r.entity)!==null&&c!==void 0?c:"")}'`,top:10})||[]).map(y=>({id:String(y.savedqueryvisualizationid),name:String(y.name)}));case"view":return(await(0,Kr.queryRecords)(e,"savedquery",{select:["savedqueryid","name"],filter:`name eq '${(0,ft.odataLiteral)((d=r.name)!==null&&d!==void 0?d:"")}' and returnedtypecode eq '${(0,ft.odataLiteral)((p=r.entity)!==null&&p!==void 0?p:"")}'`,top:10})||[]).map(y=>({id:String(y.savedqueryid),name:String(y.name)}));case"webResource":return(await(0,Kr.queryRecords)(e,"webresource",{select:["webresourceid","name"],filter:`name eq '${(0,ft.odataLiteral)((m=r.name)!==null&&m!==void 0?m:"")}'`,top:1})||[]).map(y=>({id:String(y.webresourceid),name:String(y.name)}));case"solution":return(await(0,Kr.queryRecords)(e,"solution",{select:["solutionid","uniquename"],filter:`uniquename eq '${(0,ft.odataLiteral)((h=r.uniqueName)!==null&&h!==void 0?h:"")}'`,top:1})||[]).map(y=>({id:String(y.solutionid),name:String(y.uniquename)}));default:return[]}}Na.resolveArtifact=g7;async function v7(e,t,r){var n,i,a,o,s;let l=(0,ft.odataLiteral)((n=r.name)!==null&&n!==void 0?n:""),u=(0,ft.odataLiteral)((i=r.entity)!==null&&i!==void 0?i:"");if(t==="command"){let h=await(0,Kr.queryRecords)(e,"appaction",{select:["appactionid"],filter:`contextvalue eq '${(0,ft.odataLiteral)((a=r.entity)!==null&&a!==void 0?a:"")}'`,top:1});return h&&h.length?String(r.entity):null}let c=b7(t,l,u,r),d=t!=="app",p=await(0,Kr.queryRecords)(e,c.set,{select:[c.idField],filter:c.filter,top:d?2:1});if(d&&p&&p.length>1)throw new h7.AmbiguousArtifactError(t,(s=(o=r.name)!==null&&o!==void 0?o:r.uniqueName)!==null&&s!==void 0?s:"",p.length);let m=p&&p[0]&&p[0][c.idField];return m!=null?String(m):null}Na.findArtifact=v7;function b7(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,ft.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 __=g($u=>{"use strict";Object.defineProperty($u,"__esModule",{value:!0});$u.seedRecordGraph=void 0;var I_=Ps(),y7=Cs(),Bu=Z(),w7=ne();async function A7(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,y7.resolveEntitySetName)(e,p)),c={},d=p=>{var m;return(m=c[p])!==null&&m!==void 0?m:l[p]};for(let p of t){let m=p.entityLogical.toLowerCase(),h=(a=p.matchOn)===null||a===void 0?void 0:a.toLowerCase(),w=[];for(let G of p.records){let M={...G.body};for(let U of(o=G.binds)!==null&&o!==void 0?o:[]){let B=U.parentEntity.toLowerCase(),W=(s=d(B))===null||s===void 0?void 0:s[U.parentIndex];if(!W)throw new w7.InvalidArgumentError(`Cannot resolve bind '${U.navProperty}' on a '${m}' record: parent '${U.parentEntity}'[${U.parentIndex}] has no created id. Seed the parent group before the child, or supply it via options.createdIds.`);let $=(0,Bu.assertODataName)(await u(B),`entity set for parent '${U.parentEntity}'`),Ae=(0,Bu.normalizeGuid)(W,`parent id for bind '${U.navProperty}'`);M[`${U.navProperty}@odata.bind`]=`/${$}(${Ae})`}w.push(M)}let y=h?w.map(G=>{let M=G[h];return M!=null&&M!==""?String(M):null}):w.map(()=>null),N=new Map;if(h){let G=(0,Bu.assertODataName)(h,"RecordGraph matchOn key"),M=[...new Set(y.filter(U=>U!==null))];if(M.length){let U=M.map(W=>`${G} eq '${(0,Bu.odataLiteral)(W)}'`).join(" or "),B=await(0,I_.queryRecords)(e,m,{select:[G,`${m}id`],filter:U,top:5e3});for(let W of B??[]){let $=W[G];$!=null&&N.set(String($).toLowerCase(),String(W[`${m}id`]))}}}let D=[],x=new Map,F=w.map((G,M)=>{let U=y[M];if(U&&N.has(U.toLowerCase()))return null;if(U){let B=U.toLowerCase(),W=x.get(B);if(W!==void 0)return W;let $=D.push(G)-1;return x.set(B,$),$}return D.push(G)-1}),q=D.length?await(0,I_.createRecordsBulk)(e,m,D):[];c[m]=w.map((G,M)=>{let U=y[M];return U&&N.has(U.toLowerCase())?N.get(U.toLowerCase()):q[F[M]]})}return{createdIds:c}}$u.seedRecordGraph=A7});var M_=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 Ir=ge(),et=Z(),Qt=ne(),qu={read:"Read",create:"Create",write:"Write",delete:"Delete",append:"Append",appendTo:"AppendTo",assign:"Assign",share:"Share"},F_={user:"Basic",businessUnit:"Local",parentChild:"Deep",organization:"Global"},P_={user:1,businessUnit:2,parentChild:3,organization:4},km={user:"CanBeBasic",businessUnit:"CanBeLocal",parentChild:"CanBeDeep",organization:"CanBeGlobal"};It.SDK_ROLE_MARKER="Authored by @maker-studio/cds-maker-sdk (persona/security role).";function C7(e){return Object.prototype.hasOwnProperty.call(qu,e)?qu[e]:void 0}function S7(e){return Object.prototype.hasOwnProperty.call(F_,e)}var T_=new WeakMap,O_=new WeakMap;async function L_(e,t){var r,n;(0,et.assertODataName)(t,"entity logical name");let i=T_.get(e);i||(i=new Map,T_.set(e,i));let a=i.get(t);if(a)return a;let o=`/EntityDefinitions(LogicalName='${(0,et.odataPathLiteral)(t)}')${(0,et.odataQuery)([["$select","LogicalName,Privileges"]])}`,l=(n=(r=(0,Ir.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 Qt.InvalidArgumentError(`Entity '${t}' exposes no privileges (unknown or non-securable entity).`);return i.set(t,l),l}async function N7(e){var t,r,n;let i=O_.get(e);if(i)return i;let a=`/businessunits${(0,et.odataQuery)([["$select","businessunitid"],["$filter","_parentbusinessunitid_value eq null"],["$top",1]])}`,l=(n=((r=(t=(0,Ir.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 Qt.InvalidArgumentError("Could not resolve the root business unit.");let u=(0,et.normalizeGuid)(l,"businessUnitId");return O_.set(e,u),u}async function E7(e,t){var r;let n=new Map;for(let i of t){if(!i.access||i.access.length===0)throw new Qt.InvalidArgumentError(`Entity '${i.entity}' privilege request has no access levels.`);let a=(r=i.scope)!==null&&r!==void 0?r:"user";if(!S7(a))throw new Qt.InvalidArgumentError(`Unknown privilege scope '${a}' for entity '${i.entity}'.`);let o=await L_(e,i.entity);for(let s of i.access){let l=C7(s);if(!l)throw new Qt.InvalidArgumentError(`Unknown access level '${s}' for entity '${i.entity}'.`);let u=o.find(h=>h.PrivilegeType===l);if(!u)throw new Qt.InvalidArgumentError(`Entity '${i.entity}' does not support '${s}' access.`);let c=km[a];if(u[c]===!1)throw new Qt.InvalidArgumentError(`Privilege '${u.Name}' on '${i.entity}' does not support the '${a}' scope.`);let d=(0,et.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 Qt.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=P_[a]>P_[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 D7(e,t,r,n){if(r.length===0&&!n)return;let i={Privileges:r.map(o=>({Depth:F_[o.scope],PrivilegeId:o.privilegeId}))},a=`/roles(${t})/Microsoft.Dynamics.CRM.ReplacePrivilegesRole`;(0,Ir.ensureSuccess)(await e.post(a,i),e.apiUrl(a))}async function R_(e,t,r,n,i){var a,o;let s=`/${t}(${r})/${n}${(0,et.odataQuery)([["$select","roleid"],["$filter",`roleid eq ${i}`]])}`;return((o=(a=(0,Ir.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 I7(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,et.normalizeGuid)(l,"teamId");if(!await R_(e,"teams",u,"teamroles_association",t)){let c=`/teams(${u})/teamroles_association/$ref`;(0,Ir.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,et.normalizeGuid)(l,"userId");if(!await R_(e,"systemusers",u,"systemuserroles_association",t)){let c=`/systemusers(${u})/systemuserroles_association/$ref`;(0,Ir.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}o.push(u)}return{teams:a,users:o}}async function x_(e,t,r){var n,i;let a=`/roles${(0,et.odataQuery)([["$select","roleid,description,ismanaged"],["$filter",`name eq '${(0,et.odataLiteral)(t)}' and _businessunitid_value eq ${r}`]])}`,l=((i=(n=(0,Ir.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 Qt.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 Qt.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,et.normalizeGuid)(c,"roleId"):void 0}function _7(e){var t,r;return{teams:((t=e?.teams)!==null&&t!==void 0?t:[]).map(n=>(0,et.normalizeGuid)(n,"teamId")),users:((r=e?.users)!==null&&r!==void 0?r:[]).map(n=>(0,et.normalizeGuid)(n,"userId"))}}function P7(e){return e.map(t=>({entity:t.entity,privilegeName:t.privilegeName,privilegeType:t.privilegeType,scope:t.scope}))}async function k_(e,t){var r,n;let i=(r=t.name)===null||r===void 0?void 0:r.trim();if(!i)throw new Qt.InvalidArgumentError("createSecurityRole: a non-empty role name is required.");let a=t.businessUnitId?(0,et.normalizeGuid)(t.businessUnitId,"businessUnitId"):await N7(e),o=await E7(e,(n=t.privileges)!==null&&n!==void 0?n:[]),s=_7(t.assignTo),l=await x_(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 m=(0,Ir.ensureSuccess)(await e.post(d,p),e.apiUrl(d));l=(0,et.normalizeGuid)((0,Ir.requireCreatedId)(m,"roleid","role"),"roleId")}catch(m){let h;try{h=await x_(e,i,a)}catch{h=void 0}if(!h)throw m;l=h}}await D7(e,l,o,u);let c=await I7(e,l,s);return{roleId:l,name:i,reused:u,appliedPrivileges:P7(o),assignedTeams:c.teams,assignedUsers:c.users}}It.createSecurityRole=k_;async function T7(e,t){var r,n;let i=(r=t.persona)===null||r===void 0?void 0:r.trim();if(!i)throw new Qt.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 k_(e,{name:i,businessUnitId:t.businessUnitId,privileges:a,assignTo:t.assignTo})}It.createPersonaRole=T7;async function O7(e,t){let n=`/roles(${(0,et.normalizeGuid)(t,"roleId")})`;(0,Ir.ensureSuccess)(await e.delete(n),e.apiUrl(n))}It.deleteSecurityRole=O7;var R7=new Map(Object.keys(qu).map(e=>[qu[e],e]));async function x7(e,t){return(await L_(e,t)).map(n=>{let i=Object.keys(km).filter(o=>n[km[o]]!==!1),a=R7.get(n.PrivilegeType);return{name:n.Name,privilegeId:n.PrivilegeId,privilegeType:n.PrivilegeType,...a?{access:a}:{},scopes:i}})}It.getEntityPrivileges=x7});var V_=g(Pr=>{"use strict";Object.defineProperty(Pr,"__esModule",{value:!0});Pr.createMakerSdk=Pr.MakerSdk=Pr.ALREADY_EXISTS_CODE=void 0;var ue=ne(),Yr=os(),F7=qm(),U_=zm(),L7=Xm(),k7=hh(),Mm=yh(),Qe=Cs(),B_=Zc(),Zr=Ps(),Vu=Cg(),Ea=Os(),M7=xs(),st=Pg(),U7=ld(),B7=g_(),$7=yn(),q7=ht(),V7=pi(),Tn=Wf(),$_=pc(),G7=3e5,_r=ge(),On=Z(),Da=E_(),q_=D_(),z7=__(),W7=Nf(),Gu=M_();Pr.ALREADY_EXISTS_CODE="ARTIFACT_ALREADY_EXISTS";var Wu=class{constructor(t){var r,n;this.artifactLocks=new Map,(0,$7.installDomShim)(),this.languageCode=(r=t.languageCode)!==null&&r!==void 0?r:V7.DEFAULT_LCID,this.cacheStalenessMs=(n=t.cacheStalenessMs)!==null&&n!==void 0?n:G7,this.workspace=new U_.WorkspaceManager(t.workspacePath,t.instanceUrl),this.versions=new L7.VersionManager(this.workspace),this.dataverse=new k7.DataverseClient(t.instanceUrl,t.httpClient,t.solutionUniqueName),this.registrations=(0,B7.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,U_.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 ue.LocalEditsWouldBeLostError(t,r,p,l);let m=this.workspace.readArtifact(t,r);if(m){let h=this.versions.getMeta(t,r);if(h&&!h.etag&&l){if(!(0,$_.deepEqual)(h.snapshot,d))throw new ue.LocalEditsWouldBeLostError(t,r,p,l);this.versions.storeMeta(t,r,{...h,etag:l,fetchedAt:(0,_r.nowIso)()})}return(0,Tn.cloneJson)(m)}}return this.workspace.writeArtifact(t,r,d),this.versions.storeMeta(t,r,{etag:l,languageCode:this.languageCode,fetchedAt:(0,_r.nowIso)(),snapshot:(0,Tn.cloneJson)(d),...u?{memberEtags:u}:{},...c?{siblingEtags:c}:{}}),(0,Tn.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,st.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,_r.nowIso)(),isDirty:!1})}catch(s){a.push({componentId:o.objectId,componentType:o.componentType,workflowCategory:o.workflowCategory,reason:"failed",error:zu(s)})}return this.workspace.updateManifest({lastSyncAt:(0,_r.nowIso)()}),{summaries:i,skipped:a}}async fetchEntityMetadata(t){let r=await(0,Mm.fetchEntityMetadataFromApi)(this.dataverse,t);return this.workspace.writeEntityMetadata(t,r),r}findTables(t,r){return(0,Mm.findTables)(this.dataverse,t,r)}findColumns(t,r,n){return(0,Mm.findColumns)(this.dataverse,t,r,n)}createTable(t){return(0,Qe.createTable)(this.dataverse,t)}createColumn(t,r){return(0,Qe.createColumn)(this.dataverse,t,r)}createColumns(t,r){return(0,Qe.createColumns)(this.dataverse,t,r)}updateColumn(t,r,n){return(0,Qe.updateColumn)(this.dataverse,t,r,n)}deleteColumn(t,r){return(0,Qe.deleteColumn)(this.dataverse,t,r)}setFormSecurityRoles(t,r){return(0,B_.setFormSecurityRoles)(this.dataverse,t,r)}getFormSecurityRoles(t){return(0,B_.getFormSecurityRoles)(this.dataverse,t)}setColumnVisualization(t,r,n){return(0,Qe.setColumnVisualization)(this.dataverse,t,r,n)}getColumnVisualization(t,r){return(0,Qe.getColumnVisualization)(this.dataverse,t,r)}createCustomerColumn(t,r){return(0,Qe.createCustomerColumn)(this.dataverse,t,r)}insertStatusValue(t,r){return(0,Qe.insertStatusValue)(this.dataverse,t,r)}updateTable(t,r){return(0,Qe.updateTable)(this.dataverse,t,r)}async setEntityIcon(t,r){if(await(0,Qe.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,On.xmlText)(t)}</entity></entities></importexportxml>`;(0,_r.ensureSuccess)(await this.dataverse.post("/PublishXml",{ParameterXml:n}),this.dataverse.apiUrl("/PublishXml"))}}createAlternateKey(t,r){return(0,Qe.createAlternateKey)(this.dataverse,t,r)}deleteAlternateKey(t,r){return(0,Qe.deleteAlternateKey)(this.dataverse,t,r)}createRelationship(t){return(0,Qe.createRelationship)(this.dataverse,t)}deleteRelationship(t){return(0,Qe.deleteRelationship)(this.dataverse,t)}createGlobalOptionSet(t){return(0,Qe.createGlobalOptionSet)(this.dataverse,t)}deleteGlobalOptionSet(t){return(0,Qe.deleteGlobalOptionSet)(this.dataverse,t)}deleteTable(t){return(0,Qe.deleteTable)(this.dataverse,t)}createSecurityRole(t){return(0,Gu.createSecurityRole)(this.dataverse,t)}createPersonaRole(t){return(0,Gu.createPersonaRole)(this.dataverse,t)}deleteSecurityRole(t){return(0,Gu.deleteSecurityRole)(this.dataverse,t)}getEntityPrivileges(t){return(0,Gu.getEntityPrivileges)(this.dataverse,t)}createRecord(t,r){return(0,Zr.createRecord)(this.dataverse,t,r)}createRecordsBulk(t,r){return(0,Zr.createRecordsBulk)(this.dataverse,t,r)}updateRecord(t,r,n){return(0,Zr.updateRecord)(this.dataverse,t,r,n)}upsertRecord(t,r,n){return(0,Zr.upsertRecord)(this.dataverse,t,r,n)}deleteRecord(t,r){return(0,Zr.deleteRecord)(this.dataverse,t,r)}getRecord(t,r,n){return(0,Zr.getRecord)(this.dataverse,t,r,n)}queryRecords(t,r){return(0,Zr.queryRecords)(this.dataverse,t,r)}seedRecordGraph(t,r){return(0,z7.seedRecordGraph)(this.dataverse,t,r)}resolveArtifact(t,r){return(0,q_.resolveArtifact)(this.dataverse,t,r)}findArtifact(t,r){return(0,q_.findArtifact)(this.dataverse,t,r)}async deleteAppCascade(t,r){let n=await(0,U7.deleteAppCascade)(this.dataverse,t,r),i=(0,On.normalizeGuid)(t,"appModuleId");return this.workspace.readArtifact("app",i)&&this.workspace.deleteArtifact("app",i),n}associateRecords(t,r,n){return(0,Zr.associateRecords)(this.dataverse,t,r,n)}disassociateRecords(t,r,n,i){return(0,Zr.disassociateRecords)(this.dataverse,t,r,n,i)}createWebResource(t){return(0,Vu.createWebResource)(this.dataverse,t)}updateWebResource(t,r){return(0,Vu.updateWebResource)(this.dataverse,t,r)}getWebResource(t){return(0,Vu.getWebResource)(this.dataverse,t)}deleteWebResource(t){return(0,Vu.deleteWebResource)(this.dataverse,t)}getAppSettings(t){return(0,Ea.readAppSettings)(this.dataverse,t)}setAppSetting(t,r,n){return(0,Ea.setAppSetting)(this.dataverse,t,r,n)}setHeaderAndNavigationRefresh(t,r){if(typeof r!="boolean")throw new ue.ValidationError("app",t,[{pointer:"/headerAndNavigationRefresh",rule:M7.HEADER_NAV_BOOLEAN_RULE,message:`enabled must be a boolean, got ${typeof r}`}]);return(0,Ea.setAppSetting)(this.dataverse,t,Ea.HEADER_AND_NAVIGATION_REFRESH,r?Ea.APP_SETTING_ON:Ea.APP_SETTING_OFF)}getSolution(t){return(0,st.getSolution)(this.dataverse,t)}createPublisher(t){return(0,st.createPublisher)(this.dataverse,t)}createSolution(t){return(0,st.createSolution)(this.dataverse,t)}setSolutionVersion(t,r){return(0,st.setSolutionVersion)(this.dataverse,t,r)}addSolutionComponent(t){return(0,st.addSolutionComponent)(this.dataverse,t)}removeSolutionComponent(t,r,n){return(0,st.removeSolutionComponent)(this.dataverse,t,r,n)}exportSolution(t){return(0,st.exportSolution)(this.dataverse,t)}importSolution(t){return(0,st.importSolution)(this.dataverse,t)}deleteSolution(t){return(0,st.deleteSolution)(this.dataverse,t)}async getArtifact(t,r){return this.withArtifactLock(t,r,()=>this.getArtifactUnlocked(t,r))}async getArtifactUnlocked(t,r){return(0,Tn.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 ue.StaleArtifactError(t,r,n);return this.readLocal(t,r)}readLocal(t,r){let n=this.workspace.readArtifact(t,r);if(!n)throw new ue.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,$_.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=Yr.JsonPointer.resolve(i,n);if(a===void 0)throw new ue.PathNotFoundError(t,r,n);return a})}async findElements(t,r,n){return this.withArtifactLock(t,r,async()=>(0,F7.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 ue.ArtifactNotFoundError("entityMetadata",t);return r}getFieldMetadata(t,r){let i=this.getEntityMetadata(t).attributes.find(a=>a.logicalName===r);if(!i)throw new ue.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=Yr.JsonPointer.resolve(a,n);if(o===void 0)throw new ue.PathNotFoundError(t,r,n);let s=ju(o)&&ju(i)?{...o,...i}:i;return Yr.JsonPointer.set(a,n,(0,Tn.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=Yr.JsonPointer.resolve(o,n);if(s===void 0)throw new ue.PathNotFoundError(t,r,n);if(!Array.isArray(s))throw new ue.ValidationError(t,r,n,"parent must be an array");let l=this.assignMissingIds(t,(0,Tn.cloneJson)(i)),u=Q7(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=Yr.JsonPointer.resolve(s,n);if(l===void 0)throw new ue.PathNotFoundError(t,r,n);let u=Yr.JsonPointer.resolve(s,i);if(u===void 0)throw new ue.PathNotFoundError(t,r,i);if(!Array.isArray(u))throw new ue.ValidationError(t,r,i,"move target must be an array");if(i===n||i.startsWith(`${n}/`))throw new ue.ValidationError(t,r,i,"cannot move an element into its own subtree");Yr.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(Yr.JsonPointer.resolve(i,n)===void 0)throw new ue.PathNotFoundError(t,r,n);return Yr.JsonPointer.remove(i,n),this.assertStructurallyValid(t,r,i,H7(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 ue.ValidationError(t,r,u)}retrieveSetting(t,r){return(0,Da.retrieveSetting)(this.dataverse,t,r)}saveSettingValue(t,r,n){return(0,Da.saveSettingValue)(this.dataverse,t,r,n)}getAiReadiness(t){return(0,Da.getAiReadiness)(this.dataverse,t)}setAppAiFeatures(t,r,n){return(0,Da.setAppAiFeatures)(this.dataverse,t,r,n)}configureRowSummary(t,r){return(0,Da.configureRowSummary)(this.dataverse,t,r)}removeRowSummary(t){return(0,Da.removeRowSummary)(this.dataverse,t)}async enrichDefaultViews(t,r,n={}){let i=await(0,W7.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 ue.ValidationError(t,"(new)","/id","created artifact must have an id");return this.workspace.writeArtifact(t,a,i),(0,Tn.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:zu(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,On.normalizeGuid)(r,"id")})${(0,On.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:zu(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),m=u.adapter.toApiPayload(c,d?.snapshot,p);try{let h=d?await u.api.update(this.dataverse,r,m,d.etag,d.memberEtags,d.siblingEtags):await this.createWithMintedId(u,t,r,m),w=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),w=h.id),this.workspace.writeArtifact(t,w,c)),this.versions.storeMeta(t,w,{etag:h.etag,languageCode:this.languageCode,fetchedAt:(0,_r.nowIso)(),snapshot:(0,Tn.cloneJson)(c),...h.memberEtags?{memberEtags:h.memberEtags}:{},...h.siblingEtags?{siblingEtags:h.siblingEtags}:{}}),{type:t,id:w,saved:!0,shipped:!1,publish:(n=h.publish)!==null&&n!==void 0?n:{kind:"notRequested"},...h.publish&&h.publish.kind!=="notRequested"?(()=>{var y;let N=(y=u.publishScope)===null||y===void 0?void 0:y.call(u,w,c);return N?{publishScope:N}:{}})():{},...h.warnings&&h.warnings.length>0?{warnings:h.warnings}:{}}}catch(h){let w=(0,ue.readPartialTokens)(h);if(w&&d){let y={...(i=d.memberEtags)!==null&&i!==void 0?i:{},...(a=w.memberEtags)!==null&&a!==void 0?a:{}},N={...(o=d.siblingEtags)!==null&&o!==void 0?o:{},...(s=w.siblingEtags)!==null&&s!==void 0?s:{}};this.versions.storeMeta(t,r,{...d,...Object.keys(y).length>0?{memberEtags:y}:{},...Object.keys(N).length>0?{siblingEtags:N}:{}})}if(h instanceof ue.SdkError&&h.code===Pr.ALREADY_EXISTS_CODE)return{type:t,id:r,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:h};if(h instanceof ue.SdkError&&h.code===_r.VERSION_CONFLICT_CODE)return{type:t,id:r,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:new ue.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 ue.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 ue.SdkError)||a.code!==_r.VERSION_CONFLICT_CODE?a:new ue.SdkError(Pr.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:zu(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 st.SolutionComponentType.SavedQuery:return"view";case st.SolutionComponentType.SavedQueryVisualization:return"chart";case st.SolutionComponentType.AppModule:return"app";case st.SolutionComponentType.UxAgentProject:return"genPage";case st.SolutionComponentType.Workflow:return t.workflowCategory===2?"businessRule":t.workflowCategory===4&&await this.isBusinessFlowWorkflow(t.objectId)?"bpf":void 0;case st.SolutionComponentType.SystemForm:return await this.isDashboardForm(t.objectId)?"dashboard":"form";default:return}}async isDashboardForm(t){let n=`/systemforms(${(0,On.normalizeGuid)(t,"formId")})${(0,On.odataQuery)([["$select","type"]])}`,i=(0,_r.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,On.normalizeGuid)(t,"workflowId")})${(0,On.odataQuery)([["$select","businessprocesstype"]])}`,i=(0,_r.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 ue.NotImplementedError(r,`no adapter registered for artifact type '${t}'`);return n}};Pr.MakerSdk=Wu;function j7(e){return new Wu(e)}Pr.createMakerSdk=j7;function zu(e){return e instanceof Error?e:new Error(String(e))}function ju(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function H7(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function Q7(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=>ju(i)&&i.id===t.before);return n<0?e.length:n}let r=e.findIndex(n=>ju(n)&&n.id===t.after);return r<0?e.length:r+1}});var G_=g(Hu=>{"use strict";Object.defineProperty(Hu,"__esModule",{value:!0});Hu.ARTIFACT_TYPES=void 0;Hu.ARTIFACT_TYPES=["form","view","businessRule","app","command","chart","dashboard","genPage","bpf"]});var W_=g(z_=>{"use strict";Object.defineProperty(z_,"__esModule",{value:!0})});var H_=g(j_=>{"use strict";Object.defineProperty(j_,"__esModule",{value:!0})});var J_=g(Q_=>{"use strict";Object.defineProperty(Q_,"__esModule",{value:!0})});var K_=g(X_=>{"use strict";Object.defineProperty(X_,"__esModule",{value:!0})});var Z_=g(Y_=>{"use strict";Object.defineProperty(Y_,"__esModule",{value:!0})});var t1=g(e1=>{"use strict";Object.defineProperty(e1,"__esModule",{value:!0})});var n1=g(r1=>{"use strict";Object.defineProperty(r1,"__esModule",{value:!0})});var a1=g(i1=>{"use strict";Object.defineProperty(i1,"__esModule",{value:!0})});var s1=g(o1=>{"use strict";Object.defineProperty(o1,"__esModule",{value:!0})});var u1=g(l1=>{"use strict";Object.defineProperty(l1,"__esModule",{value:!0})});var d1=g(c1=>{"use strict";Object.defineProperty(c1,"__esModule",{value:!0})});var f1=g(p1=>{"use strict";Object.defineProperty(p1,"__esModule",{value:!0})});var h1=g(m1=>{"use strict";Object.defineProperty(m1,"__esModule",{value:!0})});var v1=g(g1=>{"use strict";Object.defineProperty(g1,"__esModule",{value:!0})});var y1=g(b1=>{"use strict";Object.defineProperty(b1,"__esModule",{value:!0})});var A1=g(w1=>{"use strict";Object.defineProperty(w1,"__esModule",{value:!0})});var S1=g(C1=>{"use strict";Object.defineProperty(C1,"__esModule",{value:!0})});var E1=g(N1=>{"use strict";Object.defineProperty(N1,"__esModule",{value:!0})});var I1=g(D1=>{"use strict";Object.defineProperty(D1,"__esModule",{value:!0})});var J7=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]})),Ee=exports&&exports.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&J7(t,e,r)};Object.defineProperty(exports,"__esModule",{value:!0});exports.createMakerSdk=void 0;var X7=V_();Object.defineProperty(exports,"createMakerSdk",{enumerable:!0,get:function(){return X7.createMakerSdk}});Ee(G_(),exports);Ee(W_(),exports);Ee(H_(),exports);Ee(J_(),exports);Ee(K_(),exports);Ee(Z_(),exports);Ee(t1(),exports);Ee(n1(),exports);Ee(a1(),exports);Ee(s1(),exports);Ee(u1(),exports);Ee(d1(),exports);Ee(f1(),exports);Ee(xs(),exports);Ee(h1(),exports);Ee(v1(),exports);Ee(y1(),exports);Ee(A1(),exports);Ee(S1(),exports);Ee(E1(),exports);Ee(I1(),exports);Ee(ne(),exports);diff --git a/plugins/model-apps/skills/app-builder/SKILL.md b/plugins/model-apps/skills/app-builder/SKILL.mdindex 8860a31cf..aa7a1d7ac 100644--- a/plugins/model-apps/skills/app-builder/SKILL.md+++ b/plugins/model-apps/skills/app-builder/SKILL.md@@ -164,6 +164,14 @@ every prompt yourself via `AskUserQuestion`. In short:- **Level (a) — data model**: entities/columns/relationships **derived from those jobs**; run the**early data-model lint** (catches e.g. the relationship-vs-lookup collision before forms areauthored on top).+ - **Descriptions are part of authoring, not a cleanup pass.** Every table, column, view, chart,+ form, dashboard and business rule takes an optional `description`, and you should **write one as+ you create the artifact** — never as a backfill. A name says what a thing is called; a+ description says what it is *for*, and it is the only intent an app carries that an agent can+ read back later when it inspects an app it did not build. Describe the purpose, not the shape:+ `"Severity 1-5; drives the escalation rule and the SLA clock"`, not `"The priority column"`.+ (`commands[]` and `Customer` columns accept one but the SDK cannot write it — you'll get a+ warning; `personas[]` does not take one at all. See the schema reference for why.)- **Level (b) — artifacts + page-intents + design**: **enumerate every surface each job needs andclassify it** per the genpage-first policy above — record CRUD → form + view; anything else(overview/landing, dashboard, KPIs, analytics, guided/wizard flow, composite or comparison@@ -363,11 +371,14 @@ Then open the app in the browser. Refine `app-spec.json` and re-run Phase 2 to i**Teardown (cleanup).** To remove everything an App Spec built — e.g. a live-verification probe or afailed build — run the classifier-safe teardown. It deletes only the artifacts the spec declares, in-dependency order (**app module → security roles → dashboards → command bars → forms → charts → views+dependency order (**app module → dashboards → command bars → forms → security roles → charts → views→ reset enriched default views to drop parent lookups → relationships → AI row summaries → tables[children-first] → web resources (generated app icon + page manifest + declared) → global choices →solution**). Forms/charts/views/relationships are deleted **explicitly before tables** (a table-delete does not reliably cascade cross-references; it does remove the table's own columns). Command+delete does not reliably cascade cross-references; it does remove the table's own columns). Security+roles come **after forms** because a form assigned to a role names it inside its own formxml, which+the platform counts as a dependency, and **before** relationships/tables because a role holding a+table's privileges can block that table's delete. Commandteardown removes the whole command bar for any entity the spec authored commands on. **Teardown onlydeletes tables this build created** — a **system/standard table** (account, contact, …) isauto-detected and **skipped**, and a **reused custom table** is skipped when its entity is flagged@@ -505,7 +516,9 @@ 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) →+→ **business rules** (`businessRules[]` — authored as the workflow object model through the bound+`CreateProcessWithWfomJson` member and activated; **skipped with a warning** on an environment that+does not declare that member) →**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`; then@@ -541,14 +554,35 @@ child view id. Each step emits `[n/total]`.checks **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-capabilities.md`.-- Not in scope (later): business rules, **conditional** command visibility (Power-Fx-only), **titled+- Not in scope (later): **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- security surface today is role-per-persona only — a tracked SDK follow-up).+ multi-area sitemaps, **column-level (field) security**, and **access teams / hierarchy security**+ (both tracked SDK follow-ups). The security surface today is role-per-persona plus per-form role+ assignment, and both of those ship.+- **Environment-gated (may not work where you are running):**+ - **Business rules** (`businessRules[]`). The SDK writes a rule through the bound+ `CreateProcessWithWfomJson` member — the same one the modern business-rule designer uses — and+ **has no fallback**: the client-side workflow-XAML compiler it used to fall back on was removed+ upstream because it covered 4 of the 7 action types and a single clause, so it silently narrowed+ a rule into something that did not say what the author wrote. Environments that do not declare+ the member therefore **cannot host business rules at all** — and that is the common case, not an+ edge case. The build **skips** the rules, warns once naming the+ member, and builds everything else normally, so an app is never left half-created. If rules are+ essential, verify the environment first.- Supported: the full data model — all column types, **AutoNumber primary**, global choices, status- reasons, alternate keys, **N:N + junction-with-payload**; adaptive main forms with **1:N / N:N- sub-grids**; **quick-create / quick-view forms** (`formType`) + **quick-view placement**- (`forms[].quickViews[]`); Choice-column charts; **security roles** (`personas[]` — one role per+ reasons, alternate keys, **N:N + junction-with-payload**; **`required` reconciled on existing+ columns** (an explicit `required` converges on rebuild; an omitted one never demotes);+ **Boolean `defaultValue`**, whole-number **`integerFormat`** (incl. `Duration`), and per-column+ **write permissions** (`isValidForCreate` / `isValidForUpdate` / `isValidForRead` — this is how you+ make a column read-only), all applied on **create and on rebuild**; adaptive+ main forms with **1:N / N:N sub-grids**; **per-field form control** (`readOnly` / `hidden` /+ `after` positioning, plus `prune: false` to edit a subset of a form non-destructively);+ **quick-create / quick-view forms** (`formType`) + **quick-view placement**+ (`forms[].quickViews[]`); **per-form security roles** (`forms[].securityRoles` — name the+ `personas[]` this form is offered to, or `everyone: true`; applied after the roles exist. A form+ with no assignment is visible to **every** role, so this **restricts** a form rather than granting+ it); Choice-column charts; **business rules** (`businessRules[]` — authored as the modern workflow+ object model and activated; see the environment gate above); **security roles** (`personas[]` — one role perpersona sized from its jobs-to-be-done, with app access so the app opens for non-admins);**dashboards** (`dashboards[]` — chart/list/iframe/webresource tiles) + **dashboard sitemapplacement**; **generative pages** (`pages[]` — the genpage-first default, uploaded via