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 2.16.0: bundled SDK update, a required primary column on create, stricter spec gates, quieter teardown (#752)
Akshay Maloofdb8ca580657
diff --git a/plugins/model-apps/.claude-plugin/plugin.json b/plugins/model-apps/.claude-plugin/plugin.jsonindex 96957d071..096a31060 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.15.0",+ "version": "2.16.0","description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.","author": {"name": "Microsoft",diff --git a/plugins/model-apps/.plugin/plugin.json b/plugins/model-apps/.plugin/plugin.jsonindex 96957d071..096a31060 100644--- a/plugins/model-apps/.plugin/plugin.json+++ b/plugins/model-apps/.plugin/plugin.json@@ -1,6 +1,6 @@{"name": "model-apps",- "version": "2.15.0",+ "version": "2.16.0","description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.","author": {"name": "Microsoft",diff --git a/plugins/model-apps/AGENTS.md b/plugins/model-apps/AGENTS.mdindex 9ca6cd6bf..e982321c9 100644--- a/plugins/model-apps/AGENTS.md+++ b/plugins/model-apps/AGENTS.md@@ -338,11 +338,13 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo(measured: moving the flag reorders nothing, and a table's three new forms, all at the same order,were served with the `isdefault` form last). After every form exists, the forms phase promotes the default (an explicit`isDefault` or `entities[].mainFormOrder[0]` on any table; the first Main form only on a table the- spec owns) and then writes Order 0..n-1 onto the spec's Main forms, the ones it does not list keeping- their stored relative order. On a table it orders nothing on, a Main form it creates is created after the- table's others: its order is written into the new form's own `<DisplayConditions>` before the first- push (`createInPlace`), so no interrupted run or later failure can leave it at the Order 0 every new- form gets — a later build could not tell it is new. Only declared forms are written, order-only through `setFormSecurityRoles` so roles+ spec owns) and then writes Order 0..n-1 onto the spec's Main forms (a form the SDK creates has no+ `Order`, so a new form is always written, the first of a table included), the ones it does not+ list keeping their stored relative order. On a table it orders nothing on, a Main form it creates is+ created after the table's others: its order is written into the new form's own `<DisplayConditions>`+ before the first push (`createInPlace`), so no interrupted run or later failure can leave it with no+ order — a form with none takes no slot in the order Maker lists — and a later build could not tell it is+ new. Only declared forms are written, order-only through `setFormSecurityRoles` so rolessurvive; a table ordered by hand (`securityRoles.order`) is left alone; the step is best-effort (✗ anda warning, never a halt). Verify checks the stored order (`form-order`) and what the public`RetrieveFilteredForms` serves the user running it (`form-order-served`). On `build --apply`, the destructive preflight writes `.maker-workspace/destructive-approval.json`@@ -924,9 +926,22 @@ the pipeline and delegates each script's **behavioral spec** to the entries belotherefore pass appDef's tree through `adoptLiveSitemap` (`scripts/lib/sitemap-merge.js`) first: asubarea corresponds by navigation target (a URL keeps the case of its path and query), an area orgroup by a label its level uses once, then by the navigation entries it holds, then by the id an- earlier build gave it (a node none of these identifies is written as new rather than guessed); the+ earlier build gave it, then — for an unlabelled one with no entries, which is all an earlier download+ wrote for each empty group of an environment whose base language is not 1033 — by elimination: one such+ node and one live node with no entries that nothing else paired are each other. A node none of these+ identifies is written as new rather than guessed; when that drops a live node with no entries and its+ title (the spec has more than one unlabelled empty node, or the environment more than one empty live+ one, so which is which would be a guess by position), the build names it (`has no entries, and the+ spec's unlabelled empty groups cannot be matched …`) — label the spec's node to keep it. Thelive `id` and `bag` are kept, and only- what the spec sets is overlaid — chrome it does not name is still removed, as before. Because the SDK+ what the spec sets is overlaid — an icon it does not name is still removed, as before. **A title it does+ not state is kept, never cleared:** an empty or absent `label`/`title` says nothing (the download of an+ environment whose base language is not 1033 once wrote every one empty, and an author who leaves a+ title out has not asked for it to go), so the live title is written back as it is and the build says so+ (`kept the environment's title '…' — the spec has none for it`). The one exception is an entry+ (subarea) whose title the baseline below shows the spec used to state: the author took it out, and the+ edit is applied. An area or group has no target to find a baseline by, so its title is always kept —+ state one to change it. Because the SDKonly patches an existing `<Titles>` on a node with a bag, and reads an empty title as "no edit", atitle added to an entry that had none, or removed from one, is reconciled in the adopted bag at theSDK's language (other languages' titles are kept). Every dashboard entry carries exactly@@ -1379,10 +1394,20 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo"kept"); the rule is matched to it by logical name in any letter case, and a re-run deletes the rule, thenthe table, then the solution.Only a table the run would have deleted is kept this way — a reused (`existing: true`) or system table- keeps its own skip reason. Nothing re-sends the failed delete (a 500 does not prove it did not run). Keeping the table- adds no error of its own: the rule's failure stays reported, and `ok` is false and the exit status a failure as before,- but what still depends on the kept table (its icon web resource, a global choice its column binds, a relationship to- itself) can fail to delete in the same run and is reported too, until a re-run removes the table; a dry run is unchanged. A failed+ keeps its own skip reason, and what hangs on one is sent as it always was. Nothing re-sends the failed delete (a 500 does not+ prove it did not run). Keeping the table adds no error of its own: the rule's failure stays reported, and `ok` is false and the+ exit status a failure as before (so the solution is kept for the re-run too). What only the kept table's existence blocks is+ kept with it, not sent for the platform to refuse — each refusal used to be one more reported failure until the re-run: its+ icon web resource (`entities[].vectorIcon`/`icon`, matched in any letter case), a global choice one of its Choice or+ MultiChoice columns binds (the exact name the column gives, as the build binds it), and a relationship from the table to+ itself (the one relationship planned after the tables). Each is reported as `<step> (kept — …)` naming the table+ (`skip: 'kept'`), says that a re-run deletes it once the table goes, and is deleted by that re-run; an icon or a choice that a+ table the run deletes also uses stays while the kept table needs it, and a step that finds nothing in the environment still+ reads "not found". This is read from the spec alone (`planTeardown` marks such a step with `heldBy`): an icon set or a column+ bound by hand in the environment is not in the spec, so that delete is still sent — and refused — as before. A rule whose+ deactivation succeeded and whose delete failed stays deactivated until the re-run, which deletes the draft rule and its copy as+ it deletes any: teardown does not try to re-activate it, because a failed delete does not prove the rule is still there and+ a second write into a platform that has just failed one is not clearly safe. A dry run is unchanged. A failed**business process flow** keeps no table: its handler's notes say the platform removes the flow'sactivated copy with the flow, and nothing measured says a flow becomes undeletable once its table is gone.Command teardown@@ -1409,6 +1434,26 @@ the pipeline and delegates each script's **behavioral spec** to the entries belodashboards, solution). It reads through a throwaway SDK workspace, never the folder's`.maker-workspace` — a copy an interrupted build left there made the download fail, or describe editsthat were never saved to Dataverse — and writes only the baseline (`last-applied.json`) into it.+ **The navigation titles are read in the language a rebuild of the spec resolves, and only in a language the+ download knows**: `--language-code` (read as the build and verify read it), else the `languageCode` the spec+ already on disk pins, else the environment's base language (one read through the download's own client,+ `readNavigationLanguage`, before the SDK is made). The SDK projects a sitemap in the ONE language+ it is constructed with and reads a node's title as empty when it has none in that language, so an SDK+ built with no language (1033) wrote `"label": ""` for every area, group and entry of a Spanish-only+ environment. A label is a plain string, as a single-language table label is, and the language is never+ written into the spec: the flag decides what is read, not what is pinned, and a flag that names another+ language than the spec on disk pins is refused (`navigation-language-conflict`). When none of the three+ gives a language — the base language could not be read — the download stops before it writes anything+ (`navigation-language-unknown`; the spec and the baseline on disk are as they were) and says how to go on:+ run it again, pass `--language-code`, or pin `languageCode` in the spec. A `--language-code` that names another+ language than the environment's base language is read-time only, so the build and `verify-model-app.js` must be+ given the same flag — or the spec must pin it as `languageCode` — or a rebuild writes those titles as base-language+ titles. It does not fall back to 1033 as the+ build does: the spec it writes is rebuilt later, perhaps where the language can be read, and on a bilingual+ environment whose base language is not English the English titles of a guessed 1033 are non-empty labels,+ which that rebuild writes over the right ones. `--verify` makes the same choice. A title a node holds only in+ another language is not in the spec, and a rebuild into the same environment leaves it as it is (the rule+ for a title the spec does not state, under the sitemap above).The fetched SDK navigation must agree with the selected current XML's full target multiset:entities, generative pages, URLs, dashboards and custom pages, including repeated shortcuts.A missing SDK sitemap or a mismatch is refused with publish-then-download guidance, never emitted@@ -1425,6 +1470,12 @@ the pipeline and delegates each script's **behavioral spec** to the entries belofooter, business-process control, related-entity nav, control parameters, event libraries — and a LOSSYform declared in the spec is *worse* than an absent one, because a rebuild into a fresh environmentrecreates it having silently lost those controls while reporting success.)+ A view whose `<filter>` holds a `<link-entity>` (a condition on related rows, `link-type="any"`) is one more+ reason not to read a view through the SDK's typed `filters`: the SDK keeps the whole filter — the conditions+ beside the link-entity too — only in its own copy of the FetchXML, so the typed tree is empty for it. Nothing+ here reads it that way: the download carries no view and never reads a view's query, and a rebuild changes an+ existing view's columns and description only, the SDK writing the filter back whole (pinned by+ `view-related-rows-filter.test.js` and `rebuild-writes-real-bundle.test.js`).All four survive on the live app (a rebuild into the SAME environment preserves them), but are absentfrom the downloaded spec, so edit them in Maker or a fresh spec.**The omission is reported, not silent** (AB#6686423): every deployed form/view/chart is listed in the@@ -1540,7 +1591,12 @@ the pipeline and delegates each script's **behavioral spec** to the entries beloround-trip** too — `readDashboards` reconstructs each into `dashboards[]` with **id-passthrough tiles**(every tile carries the deployed view/chart ids), so a rebuild recreates the dashboard against theexisting views/charts without re-declaring them (genpage/entity/URL subareas round-trip losslessly). A- dashboard whose tiles cannot be reconstructed is dropped and surfaced in `droppedSubareas`.+ dashboard whose tiles cannot be reconstructed is dropped and surfaced in `droppedSubareas`. A tile+ that a custom control hosts (the Power Apps grid, say) is one of those that cannot: the SDK reads it as+ a list or chart with the parameters of a native tile and tells it apart only by its control class, so+ `readDashboards` leaves it out and names it (`hostsCustomControl`, in `lib/dashboard-tiles.js`, which verify+ asks too) — never emitting the plain tile that would replace the control wherever a rebuild creates the+ dashboard (a rebuild into the same environment reuses the pinned dashboard as it is).**A URL subarea that TARGETS a web resource round-trips too.** The Site Map Designer's "custom pagebacked by an HTML web resource" writes `$webresource:<name>` (Dataverse also serves it at`/WebResources/<name>`) into a URL subarea. Passing that token through used to fail the WHOLE@@ -1564,7 +1620,11 @@ the pipeline and delegates each script's **behavioral spec** to the entries belodropped and counted in `droppedSubareas`.- **`scripts/verify-model-app.js` → `scripts/lib/verify-spec.js`** — read-only reconcile of the App Specagainst what actually deployed; exits non-zero and lists anything missing, catching silent partial- builds. It works through a throwaway SDK workspace, never the folder's `.maker-workspace` (which belongs to+ builds. It validates the spec first under the `deploy` profile, with two compatibility downgrades+ (`relationshipCollisions: 'warn'` and `columnValues: 'warn'`): a spec an earlier release accepted and built — a 1:N and an N:N+ that share a schema name, an AutoNumber column with no format, a `required` that is not `true`, `false` or `"recommended"` — is+ verified, with a warning that names the fix, and is never refused before anything is read (the build, the lint and the+ provisioning gate keep these as errors). It works through a throwaway SDK workspace, never the folder's `.maker-workspace` (which belongs tothe environment it was first opened for): every read it makes goes to the server, so it verifies anyenvironment the app is deployed to and creates or binds nothing in the folder. It only READS the build'sbaseline, `last-applied.json`, from `--workspace`, and only when that baseline describes this@@ -1588,10 +1648,16 @@ the pipeline and delegates each script's **behavioral spec** to the entries belovendored lookup reads one page of ten in no defined order, so a full page is re-read in full and theapp's own cannot sort out of sight. The sitemap subarea check asks the same question (one lookup pername, shared), so the two cannot pick different dashboards — it used to take the first match, and live- a same-named dashboard of another app sorted first and failed a correctly wired nav entry. When the reader supplies `dashboardComponents`, every chart tile's+ a same-named dashboard of another app sorted first and failed a correctly wired nav entry. When the reader supplies `dashboardComponents`, every native chart tile'svisualization and view must belong to the tile's `TargetEntityType` — the cross-wiring a same-namedchart on another table produced. A tile whose owner rows cannot be read is reported unverified, not- passed. The tiles are the PUBLISHED dashboard's: the SDK reads them from the saved layer, and the reader+ passed. Only a NATIVE chart tile is held to that: the Assistant, an iframe, a web resource and any custom+ control are skipped, a chart a custom control hosts among them. The SDK types such a chart `chart` as it does+ a native one, but the spec cannot describe it and the build never writes it, so the chart and view it carries+ are not the spec's to judge — holding it to them failed a dashboard the build had left untouched. It is+ skipped, as before, and not listed `unverified` (that is for a check verify sets out to make); the+ classification is the download's (`lib/dashboard-tiles.js`; `verify-dashboard-custom-control.test.js` runs+ it on the real bundle). The tiles are the PUBLISHED dashboard's: the SDK reads them from the saved layer, and the readertakes them only when that layer's FormXML is the published row's, before and after the read, with thesame `@odata.etag` in between — a dashboard with changes that are not published is unverified. The twoFormXML reads are compared in the languages the published read carries (`lib/formxml-layers.js`): live,@@ -1938,6 +2004,58 @@ the pipeline and delegates each script's **behavioral spec** to the entries belobuild reads only `schemaName`, `displayName`, `autoNumberFormat`, `required` and `maxLength` from`primaryAttribute`; any other key inside it is still accepted and ignored (unlike the table level, it hasno key allow-list).+ - **Primary name column requirement level.** A `required` on `primaryAttribute` (`true` → `ApplicationRequired`, `"recommended"`+ → `Recommended`, `false` → `None`; an omitted one asks nothing) is sent in the table's create as the SDK's+ `createTable({ primaryColumnRequired })`. MEASURED on Dataverse 9.2.26101: an auto-numbered name column keeps the level the+ create sends, but a plain text one is stored not required whatever is sent (the same environment makes it 850 characters long),+ and a later update sets it. So for a level other than `None` the SDK reads the column's level back, sets it with one update+ where it differs, reads it again, and answers the level it read as `primaryColumnRequired` — or refuses with+ `PRIMARY_COLUMN_REQUIRED_NOT_APPLIED`, whose message says the table WAS created. The update is a PUT, so the HTTP client must+ implement `put()` (`lib/sdk-http-client.js` does; a client without one is refused before the table is made, for a plain text+ name column). `provisionDataModel` reports `required <table>.<column> (applied on create)` only for a table whose create it saw+ succeed, and then only for `None` (the create asked it, and the SDK has nothing to read back for it) or for a level the SDK+ answered. Anything else is a failed best-effort step, `required <table>.<column> -> <level>`, with a warning: an SDK that+ answers none or another level, a table found after the answer to its create was lost, or an existing table whose columns could+ not be read — where nothing shows what the name column holds, so an explicit `required: false` is no exception. The build goes+ on, writes nothing for it, and a re-run sets the level the way it does for any existing column. On `PRIMARY_COLUMN_REQUIRED_NOT_APPLIED` the+ build stops, as it does on `TABLE_METADATA_NOT_VISIBLE` (`createNewTable`): the table exists, so a warning says to run the build+ again — it finds the table, does not create it again, and sets the level through the existing-column path (the halt names the+ same step, `operatorRemedy`) — and, for a length asked of a plain text name column, that the length may not have been applied+ either. The SDK's code is never read as an already-exists answer, whatever its cause carries (a 409, the word "duplicate" in the+ platform's reason). A reused table's name column keeps the rule of every existing column: an explicit `required` converges on a+ rebuild, an omitted one is never read as `None`. Pinned by `entity-provision.test.js` (the stand-ins) and+ `table-columns-in-create.test.js` (the real bundle over a stub that stores a plain text name column's level as `None`).+ - **An AutoNumber column needs a format.** The SDK refuses to create an `autonumber` column without an `autoNumberFormat` — an+ `InvalidArgumentError` before any request, for `createColumn` and `createColumns` alike — where the SDK it replaced created a plain+ text column (an autonumber column is a text column that carries a format,+ [Autonumber columns](https://learn.microsoft.com/en-us/power-apps/maker/data-platform/autonumber-fields)). So `autoNumberFormatProblem`+ (`lib/app-spec.js`) refuses a column of type `AutoNumber` whose format is missing, blank or not a string, in `validateAppSpec` AND in the+ provision-entities input gate that `/genpage` and `/app-builder` pass through (`lib/provision-input.js`), before anything is written; the+ message names the table and the column and both ways out (a format such as `"C-{SEQNUM:5}"`, or `type: "Text"`, which is also what a+ column an earlier release made from such a spec is). The structural profile — the one teardown validates under — does not apply it, and+ read-only verification (`verify-model-app.js`) gets a warning in place of the error, as it does for a relationship-name collision+ (`columnValues: 'warn'`): a spec an earlier release built must still tear down and still be verified, and verification creates and+ updates nothing — it only reads whether each column exists. Every other path (the build, the plan, the lint, the provision-entities gate)+ keeps the error; `column-rules-authoring-gates.test.js` pins that and `verify-model-app.test.js` runs the CLI over older specs. Measured against the real bundle+ (`table-columns-in-create.test.js`): a spec that got past the gate halts the data-model phase at that column, after the table is made; a+ REBUILD that finds the column already there never reaches the refusal (`columnOptions` runs only for a column the build creates, and the+ updates the build makes to an existing column carry no format). The primary name column keeps its meaning: an absent or blank+ `primaryAttribute.autoNumberFormat` is a plain text name column, as before. A format with no `{SEQNUM}` token stays the lint's warning.+ Pinned by `column-autonumber-gate.test.js`.+ - **A column's `required` is `true`, `false` or `"recommended"`.** The build reads exactly those (`REQUIRED`, `lib/entity-provision.js`: `true` →+ `ApplicationRequired`, `"recommended"` → `Recommended`, `false` → `None`) and read every other value as `None`, and a bare own-property test took+ any present key for an explicit one — so `"ApplicationRequired"`, `"true"`, `"required"`, `"Recommended"`, `1` or `null` created a new column not+ required and, on an existing column, wrote `None` where the level differed, demoting a column a maker had made Business Required. So+ `requiredValueProblem` (`lib/app-spec.js`) refuses them, on a column and on `primaryAttribute`, in `validateAppSpec` AND in the provision-entities+ input gate (`lib/provision-input.js`): the message names the table, the column and the value, says what to write for the usual slips+ (`"ApplicationRequired"`, `"true"`, `"required"` → `true`; `"Recommended"` → `"recommended"`) and that omitting the key leaves an existing column+ as it is. Neither the structural profile (teardown's) nor verification (a warning) holds a spec to it, for the reason given for the AutoNumber format. `undefined` states nothing, here and+ in the build (`hasExplicitRequired`), so a spec built in code with `required: undefined` is not an explicit `None` that demotes an existing column.+ The other `required`s are untouched: a business process flow step's (a boolean, gated where the flow is), a business rule's `SetBusinessRequired`+ action's, a form field's. What reads a column's `required` takes exactly the accepted set: the build, the form fields and the schema facts (`true`+ only: a recommended column is not a Business Required field) and the plan document (`required`, `recommended`). A downloaded spec carries no+ `required` at all (`download-model-app.js` reads no `RequiredLevel`), so it passes whatever the live columns hold.+ Pinned by `column-required-gate.test.js`.- **Alternate keys over the name column.** The platform validates a key when it is created, and a key may hold atmost 900 bytes — 2 for each character of a text column([Dataverse alternate keys](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/define-alternate-keys-entity#create-alternate-keys)) —@@ -2058,7 +2176,7 @@ scripts/write-page-plan.js ← app-builder Phase 1.5: projects an App Spec into the genpage-plan.md read by page-builder workerspromote-intent-pages.js ← app-builder Phase 1.5: validates every generated page, then atomically flips source: intent → tsxbuild-model-app.js ← app-builder: narrated, idempotent SDK build (dry-run default; --stage data|ui|app|publish; --changed-only; --language-code)- download-model-app.js ← app-builder: pull a deployed app into an editable spec (edit flow)+ download-model-app.js ← app-builder: pull a deployed app into an editable spec (edit flow; takes the build's --language-code: the language the navigation titles are read in, when the spec on disk pins none and the base language cannot be read)teardown-model-app.js ← app-builder: classifier-safe reverse-of-build teardownverify-model-app.js ← app-builder: reconcile the spec against the deployed app (takes the build's --language-code: the language its form labels were written in)preview-form.js ← app-builder: ASCII form wireframe for authoring review@@ -2077,10 +2195,10 @@ scripts/check-griffel-styles.js ← /genpage and /app-builder: a page's `makeStyles` calls hold none of the ten shorthands Griffel's runtime drops (lib/griffel-styles.js; see "Griffel shorthands" below)capture-fixture.js ← Copies /genpage working dir into an eval fixture and runs both runnerslib/- entity-provision.js ← Shared entity-provisioning core (solution + data-model + sample-data): a new table is created with only its primary name attribute and its ordinary columns follow in one atomic change set (`createColumns`), falling back to one request per column; the primary name column's length is always sent (100 unless the spec gives one) and, where the platform did not keep a length the spec gave, set last in the phase — a length a failed attempt left unset is owed to the build's retry (`owedLengths`, paid only to the table that attempt created: proved by its MetadataId, and then written by requests addressed with the ids, which a table made again cannot answer to), and an alternate key over that column is made after it; and `mapLimit`, the bounded fan-out every parallel path reuses+ entity-provision.js ← Shared entity-provisioning core (solution + data-model + sample-data): a new table is created with only its primary name attribute and its ordinary columns follow in one atomic change set (`createColumns`), falling back to one request per column; the primary name column's length is always sent (100 unless the spec gives one), its required level is asked in the create when the spec states one (and said applied only when the SDK confirms it) and, where the platform did not keep a length the spec gave, set last in the phase — a length a failed attempt left unset is owed to the build's retry (`owedLengths`, paid only to the table that attempt created: proved by its MetadataId, and then written by requests addressed with the ids, which a table made again cannot answer to), and an alternate key over that column is made after it; and `mapLimit`, the bounded fan-out every parallel path reusesretry-policy.js ← when the build runs a failed phase again, decided from what the SERVICE said and never from what the maker named: `RETRY` (`NEVER` — a refusal of the spec, an identity or ownership conflict, an approval, a prerequisite, a file on the maker's machine; `SERVICE` — what the failure it wraps says), `judgeFailure(error, { declares })` (an explicit `transient: false` anywhere along the causes wins; then the HTTP status 429, 502, 503, 504; then a condition the service names by the `error.code` of its answer — `TRANSIENT_SERVICE_CODES`, a SQL deadlock victim (the generic SQL error code `0x80044150` AND the platform's `Sql Number: 1205` — the last SQL number the answer gives — in the service's own answer, `isDeadlockVictimAnswer`), and the lag of a column the spec creates (`declares`) — on any status; then a timeout or reset of the transport (by Node's own code when the error carries one, by its words only when it has none); then **any other HTTP status is final** whatever the answer's words say; then the SDK's or plugin's own type — a refusal, whatever it quotes (bar the SDK's wrapper of a failed publish, read by the status of the answer it embeds); then, only for a failure that carries no status at all, the service's own words, never a halt's message), `throttleAskOf` (what a throttled failure asks of the next send: `retryAfterMs` and `retryNotBefore`), `retryPolicyFor` / `retryFrom` (the policy a halt is raised with), `refusal` / `serviceFailure` (the errors the engine itself makes; `serviceFailure`'s `answered` records the OData error of an answer the engine read with a request of its own — its `code` and `message`, nothing else — and the rule reads that code as it reads the SDK's) and `withCause` (the failure a by-value result carries); `BuildHalt` takes `retry`, `retryText` and `statusCode`; build-model-app.js `isTransientHalt` is its one reader, and `tests/halt-retry-policy.test.js` holds every halt in the sources to a row of its tablethrottle-budget.js ← the budget a run allows itself for the waiting its OWN retry layers add when a service throttles — five minutes, shared by the page backend's waits between the sends of a page write (a `$batch` the HTTP client never re-sends) and the build's own waits before it runs a phase again (the upload script's write makes one of its own) (`makeThrottleBudget({ totalMs, warn })`: `fits`, `spend`, `announce` for a wait longer than five seconds, on the `warn` seam the build wires to stderr; `waitDoesNotFit`, the sentence of the `throttle-budget-exhausted` halt: what the service asked, how much is spent, that a later run of the same command continues); it only counts, each layer waits with its own seam. It is NOT a bound on all the waiting of a run: the HTTP client's own re-sends of a throttled read, publish, delete or column create keep their own schedule and are not drawn from it- provision-input.js ← Input validation for entity provisioning (the entry gate of `/genpage` and `/app-builder`; it applies `app-spec.js`'s own `primaryNameLengthProblem`, so a name-column length is refused here exactly as in `validateAppSpec`)+ provision-input.js ← Input validation for entity provisioning (the entry gate of `/genpage` and `/app-builder`; it applies `app-spec.js`'s own `primaryNameLengthProblem`, `autoNumberFormatProblem` and `requiredValueProblem`, so a name-column length, an AutoNumber column with no format and a `required` that is not `true`, `false` or `"recommended"` are refused here exactly as in `validateAppSpec`)dataverse-auth.js ← Shared auth + HTTP helpers (`az account get-access-token`, memoized per process and replaced on a 401 — a synchronous `az` call, which a caller running other probes beside the request opts out of with `refreshOn401: false`; responses decoded as UTF-8 once; a request that fails is reported as `{ error, code? }` — the message and, when Node gave one, Node's own error code (the failures this module words itself have none), which `lib/sdk-http-client.js` reads to decide whether the request is worth sending again; an answer that is not a success, and a transport failure's text, come back from `dataverseRequest` with every token the call sent taken out — the one `scrub` of `sdk-http-client.js`, a success untouched; an environment URL is used only as a Dataverse https origin, `dataverseOrigin`; a request path must stay under `/api/data/v9.2/` as both the client and the server resolve it, `webApiUrl`), the Azure CLI token for the Power Apps service (`getPowerAppsToken`: the same read for another resource, memoized apart from the Dataverse token and asked for only by the Power Apps service client and the connectivity preflight), plus the CLI arg contract (parseArgs/validateFlags, and `readLanguageCodeFlag` — the `--language-code` / `--languageCode` flag as an LCID, which `verify-model-app.js` reads exactly as the build does) and the result printer (`emitResult`, whose `{ ascii: true }` option writes stdout JSON as pure ASCII for a script an agent reads off a console)process-runner.js ← how every script starts az/pac/npm/npx/git: the executable is resolved to an absolute path on PATH, never the project folder, and started without a shell (a Windows batch shim runs through cmd.exe with its arguments checked — except a launcher that only forwards to the native program beside it, the Windows MSI's two-line `pac.cmd` (`@echo off` / `"%~dp0pac.launcher.exe" %*`): it is recognised by its exact lines — `@echo off` on a line of its own, then the forwarding line, as `cmd` reads lines, so a one-line `@echo off "%~dp0x.exe" %*`, which is an `echo`, is not one — and the program beside it (`forwardedProgram`) and that program is started directly, so a `%` or a double quote reaches it unchanged; every other batch file keeps the checked route and its refusal of them); `killProcessTree` ends a stalled child AND everything it started (`taskkill /T /F` on Windows, where `pac.cmd` is cmd.exe → pac.exe, looked up with the System32 folder first on PATH so a PATH without it cannot leave the tree running, and with its window hidden; SIGKILL to the descendants `ps` lists elsewhere, each only once `ps -o lstart= -p` shows its pid still has the start time the listing saw — a descendant that exited meanwhile can have its pid given to an unrelated process; best effort, since two processes can share a one-second start time and the moment between that read and the signal is not covered), through the same audited calls; a child that has already exited is only asked to die, never ended by its pid, which may be another process's by then; synchronous, and it never throws. `spawnResultTree` is `spawnResultSync`'s asynchronous twin (same result shape, never rejects) for a call that may have to be ended: one that outlasts its `timeout`, or writes past `maxBuffer`, has its whole tree ended through `killProcessTree` before the call settles (`ETIMEDOUT`, `ENOBUFS`), after a short wait for the pipes of what was ended; the error says whether they closed (`containment`: `confirmed`, or `unconfirmed` when a process that outlived the ended tree still holds them, with the `pid` the call was started as)cli-failure.js ← how a CLI child failed (timeout / missing / failed), the Azure CLI budget (60 s, `POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS`), so a slow `az` is never reported as missing or signed out; `commandArg` writes an argument of a command a message tells you (or the agent) to paste so that, run from PowerShell (Windows PowerShell 5.1 or PowerShell 7) or a POSIX shell, the program gets it unchanged as one argument — bare when it is plain, single-quoted otherwise (a path from an untrusted checkout can hold `;`, `$(…)` or backticks) — or not at all when no spelling does that in every one of those shells: a quote or a line break, and the values Windows PowerShell changes on their way to a native program (a `"`, white space with a final `\`, the empty value) or both PowerShells read as the stop-parsing token (`--%`), all measured. `commandArgOrPlaceholder` then writes a placeholder and names the value outside the command@@ -2101,6 +2219,7 @@ scripts/form-timeline.js ← pure: the shape Dynamics renders the Notes timeline in (control id, tall cell, spacer rows), what a deployed one lacks, and how to read it in the SDK tree and in published FormXML (shared by the compiler, the build's repair and verify)form-subgrid-placement.js ← pure: where a form's sub-grid sections go (`tab`/`column`/`after`/`before`) — resolving a placement against the declared layout, the order of a column's sections and grids, finding a grid's section in either tree shape (shared by the spec gate, build, verify and the wireframe)form-order.js ← the Main Form Set order: which Main form a table opens with, and which forms the build orders (shared by the spec gate, build and verify)+ dashboard-tiles.js ← pure: whether a tile of a deployed dashboard is a grid or chart a custom control hosts and not a native one — the control class decides, as the SDK reads both as `list`/`chart` with the same parameters (shared by the download, which leaves such a tile out of the spec, and verify, which does not hold it to a chart and view of its table)form-container-match.js ← how an authored tab/section is matched to a deployed one, and the moves that put them in the layout's order (shared by build and verify)ai-app-settings.js ← single source of truth for the per-app AI feature contractinteraction-mode.js ← whether a human is reachable in this run (shared by both skills)@@ -2119,7 +2238,7 @@ scripts/batch-request.js ← a multipart `$batch` REQUEST read the way the service reads it — `readBatchRequest(text, contentType)`: the parts of the boundary the Content-Type declares, a change set one level down, one HTTP request in each part, answered as `{ operations: [{ method, target, contentId, body }] }`, or `{ problem }` for text it cannot read with confidence (cut short, another boundary, a part that is not a request). A body is only ever text: a line in it that looks like a request is not an operation. `app-header-text.js` reads a raw change set with itthrowaway-sdk.js ← `withThrowawaySdk({ env, prefix, httpClient? }, run)`: the bundled SDK, made through `maker-sdk.js`, over a throwaway workspace folder (made by `temp-workspace.js`) that is removed whichever way the run ends (a constructor, a storage or a module that throws included); `run(make)` gets a `make(extra)` for more instances over the same folder and the one client (`make({ languageCode })` is a writer). The one copy of what `apps.js`, `list-tables.js` and `list-languages.js` each wrote outcollection-answers.js ← `requireCollectionAnswers(client, { reads, unreadable })`: the HttpClient the SDK is given, with one addition — a 2xx answer to a read `reads(url)` selects must be a collection (`{ value: [...] }`), or the read throws what `unreadable` says; `unreadableAnswer(error)` finds that error, itself or under the SDK's `ConnectionError`. `guardTableLists(client, makeError)` is its policy for the one read of the environment's table list (`/EntityDefinitions?…`, which only `findTables()` makes), and `maker-sdk.js` applies it to every SDK a script makes: the SDK's `findTables()` is `body.value ?? []`, and the bundle is not edited- temp-workspace.js ← the one maker of the plugin's throwaway workspace folders, and the sweep of the ones a KILLED run left (`makeTempWorkspace(prefix)` in place of `fs.mkdtempSync(path.join(os.tmpdir(), prefix))`, at every entry point that makes an SDK workspace — the page backend, `withThrowawaySdk`, `sdkFirst`, build, download, teardown, verify, the `provision-*` scripts, `ai-preflight`, and `solution-settings`' pac scratch folder). A run killed outright (SIGKILL, "End task", a timeout) never reaches its `finally`, and what it left held the source of every page it read and the environment's address (`solution-settings`' pac scratch folder: a settings template, an exported package or a copy of the settings file, which can hold values; the sweep's note says which a folder held, by its prefix). The folders go together in one folder of the plugin's own, `<temp>/power-platform-skills-model-apps` (`-<uid>` after it on POSIX, where the temp folder is shared). That folder is a courtesy, never a reason for a run to fail: it must be a plain folder that only this user can change — POSIX: owned by the user and writable by no one else; Windows, which tells Node no owner and no permissions: a folder this process MAKES is given an explicit access list before anything is put in it — protected, with only this user, the system and the administrators on it, full control inherited by every workspace and record made inside — and read back, and one that cannot be made so is removed and not used; an EXISTING one is judged by its access list and its owner (`windows-folder-acl.js`) and used only if NO entry of the list, an inherit-only one too, lets anyone else add to it, write to it, delete it or take it over, and the user (or the administrators, who own what an elevated process makes) owns it) — and if it cannot be used, or will not take a new folder (mode 0500, an access list that denies this user; a Windows folder that is being removed refuses a new entry — and its access list cannot be got — for a moment, so the attempt is made again after short pauses, up to six in all, and a folder that is still refusing after the last is not asked again by that process), the workspace is made in the plain temp folder exactly as before, unrecorded and never swept, and an error is reported only when that fails too. Each folder is named for the process that made it (`genpage-4242-AbC123`: the prefix, the pid, `mkdtemp`'s six characters; a prefix that does not end in a hyphen is given one, so that the pid always follows the hyphen a sweep reads it from) and holds an owner record `.owner.json` (`process-owner.js`); the first workspace a process makes sweeps that folder (`sweepDeadWorkspaces`) — only a workspace whose owner is PROVABLY gone is removed (the name's pid must have no process — on Linux a pid that runs is looked into too, since the record's start time can show it was handed out again — and the record must agree with the name; the record is read again, and judged again, just before the removal; what is inside is removed first and the record last, and the record leaves the folder only for as long as the folder itself is being removed — it is renamed out to `<folder>.removing`, which Windows allows even while another process holds it open, and moved back if the folder will not go — and if even that is refused it stays beside the folder, whole, and is never WRITTEN into the folder instead, since a write can be cut off and a damaged record beside the whole one would strand the removal; a sweep that is killed between the move and the removal leaves that file and the empty folder, and the next sweep finishes the removal when the file is a record of the folder's own — its name, a record that names the pid in it, an owner that is gone — and the folder is empty or gone, and leaves anything that does not agree as it is — so a removal that fails, half way or at the very end, leaves a folder still known to be dead and found again by the next sweep (Windows with Node 20 keeps a file that was deleted while open, listed, until the holder lets go, and the folder cannot go meanwhile); at most 100 a run, out of 500 entries looked at: the entries are taken in name order and the next run starts after the last one looked at — a cursor, `.sweep-cursor.json`, one small file in the plugin's folder, written whole and there only while the folder holds more than a run looks at — so that a folder whose first 500 entries must be kept does not hide a dead run's workspace, or a removal a kill left half done, behind them for good), and a folder whose name names a pid that RUNS is not even opened (on Linux its record alone is read, for the start time that can show the pid was handed out again; Linux lets a file another process has open be removed) — on Windows a file that is deleted while another process has it open stays in its folder until that process lets go, so a sweep that read a live run's record could make that run's own removal fail — and the run says so on stderr (`⚠ removed 1 temporary workspace left in … by a run that is no longer running`). A run that may still be going, another machine's, a folder with no readable record (a release before this one's, a damaged record), a link, a file: left as they are. **A path inside a workspace that is given to a program of another make makes the workspace LENT, when it is made** (`makeTempWorkspace(prefix, { lent: true })`, as `solution-settings`' `templateThroughPac` does for pac): on POSIX such a program outlives a run that is killed, so the record — written ONCE, whole, to a file of its own and renamed into place, and never written again — says `lent: true`, and a sweep never takes a lent workspace because its maker is gone: only when its maker is gone AND it is old, neither the folder nor its record written to for seven days (`LENT_KEEP_MS`; pac gets an hour at most). Nothing follows the program or changes the record once it has started (a record that is changed later can be unreadable at that moment), and a record that is unreadable keeps the folder. Every caller that hands a path in a workspace to another program decides that when it makes the workspace. The plugin's folder is removed when the process ends with nothing in it, so a normal run leaves the temp folder as it found it; a folder that cannot be used or a record that cannot be written costs the sweep, never the run. The sweep reads only the plugin's own folder, never the temp folder, which can hold hundreds of thousands of entries+ temp-workspace.js ← the one maker of the plugin's throwaway workspace folders, and the sweep of the ones a KILLED run left (`makeTempWorkspace(prefix)` in place of `fs.mkdtempSync(path.join(os.tmpdir(), prefix))`, at every entry point that makes an SDK workspace — the page backend, `withThrowawaySdk`, `sdkFirst`, build, download, teardown, verify, the `provision-*` scripts, `ai-preflight`, and `solution-settings`' pac scratch folder). A run killed outright (SIGKILL, "End task", a timeout) never reaches its `finally`, and what it left held the source of every page it read and the environment's address (`solution-settings`' pac scratch folder: a settings template, an exported package or a copy of the settings file, which can hold values; the sweep's note says which a folder held, by its prefix). The folders go together in one folder of the plugin's own, `<temp>/power-platform-skills-model-apps` (`-<uid>` after it on POSIX, where the temp folder is shared). That folder is a courtesy, never a reason for a run to fail: it must be a plain folder that only this user can change — POSIX: owned by the user and writable by no one else; Windows, which tells Node no owner and no permissions: a folder this process MAKES is given an explicit access list before anything is put in it — protected, with only this user, the system and the administrators on it, full control inherited by every workspace and record made inside — and read back, and one that cannot be made so is removed and not used; an EXISTING one is judged by its access list and its owner (`windows-folder-acl.js`) and used only if NO entry of the list, an inherit-only one too, lets anyone else add to it, write to it, delete it or take it over, and the user (or the administrators, who own what an elevated process makes) owns it) — and if it cannot be used, or will not take a new folder (mode 0500, an access list that denies this user; a Windows folder that is being removed refuses a new entry — and its access list cannot be got — for a moment, so the attempt is made again after short pauses, up to six in all, and a folder that is still refusing after the last is not asked again by that process), the workspace is made in the plain temp folder exactly as before, unrecorded and never swept, and an error is reported only when that fails too. Each folder is named for the process that made it (`genpage-4242-AbC123`: the prefix, the pid, `mkdtemp`'s six characters; a prefix that does not end in a hyphen is given one, so that the pid always follows the hyphen a sweep reads it from) and holds an owner record `.owner.json` (`process-owner.js`); the first workspace a process makes sweeps that folder (`sweepDeadWorkspaces`) — only a workspace whose owner is PROVABLY gone is removed (the name's pid must have no process — on Linux a pid that runs is looked into too, since the record's start time can show it was handed out again — and the record must agree with the name; the record is read again, and judged again, just before the removal; what is inside is removed first and the record last, and the record leaves the folder only for as long as the folder itself is being removed — it is renamed out to `<folder>.removing`, which Windows allows even while another process holds it open, and moved back if the folder will not go — and if even that is refused it stays beside the folder, whole, and is never WRITTEN into the folder instead, since a write can be cut off and a damaged record beside the whole one would strand the removal; a sweep that is killed between the move and the removal leaves that file and the empty folder, and the next sweep finishes the removal when the file is a record of the folder's own — its name, a record that names the pid in it, an owner that is gone — and the folder is empty or gone, and leaves anything that does not agree as it is — so a removal that fails, half way or at the very end, leaves a folder still known to be dead and found again by the next sweep (Windows with Node 20 keeps a file that was deleted while open, listed, until the holder lets go, and the folder cannot go meanwhile); at most 100 a run, out of 500 entries looked at: the entries are taken in name order and the next run starts after the last one looked at — a cursor, `.sweep-cursor.json`, one small file in the plugin's folder, written whole and there only while the folder holds more than a run looks at — so that a folder whose first 500 entries must be kept does not hide a dead run's workspace, or a removal a kill left half done, behind them for good), and a folder whose name names a pid that RUNS is not even opened (on Linux its record alone is read, for the start time that can show the pid was handed out again; Linux lets a file another process has open be removed) — on Windows a file that is deleted while another process has it open stays in its folder until that process lets go, so a sweep that read a live run's record could make that run's own removal fail — and the run says so on stderr (`⚠ removed 1 temporary workspace left in … by a run that is no longer running`). A run that may still be going, another machine's, a folder with no readable record (a release before this one's, a damaged record), a link, a file: left as they are. **A path inside a workspace that is given to a program of another make makes the workspace LENT, when it is made** (`makeTempWorkspace(prefix, { lent: true })`, as `solution-settings`' `templateThroughPac` does for pac): on POSIX such a program outlives a run that is killed, so the record — written ONCE, whole, to a file of its own and renamed into place, and never written again — says `lent: true`, and a sweep never takes a lent workspace because its maker is gone: only when its maker is gone AND it is old, neither the folder nor its record written to for seven days (`LENT_KEEP_MS`; pac gets an hour at most). Nothing follows the program or changes the record once it has started (a record that is changed later can be unreadable at that moment), and a record that is unreadable keeps the folder. Every caller that hands a path in a workspace to another program decides that when it makes the workspace. The plugin's folder is removed when the process ends with nothing in it, so a normal run leaves the temp folder as it found it — and so does a run that is cut short by `process.exit` or an error nothing catches (the `exit` event): it first removes the workspaces it made and did not lend that are still there, by the steps of a sweep (what is inside first, the record last), since it never reached the `finally` that would have; a LENT workspace is never taken at the end of the run that lent it, and what is not its own is never touched (`rmdir` takes the folder only when it is empty, and a run that loses the folder between making it and making its workspace in it makes it again); the one caller that removes a lent workspace itself, `solution-settings`, does it in a cleanup it registers with `lib/exit-cleanup.js`, which runs after the maker's listener has found the workspace still in the folder and left the folder, so that cleanup calls `pruneWorkspaceParents()` once its workspace is gone — the same `rmdir`, so a run that is cut short while pac runs leaves no empty plugin folder behind (a signal included: it ends a POSIX process with no `exit` event, and that cleanup is what runs). A POSIX signal is NOT one of these ends — its default action ends the process with no JavaScript run, and a listener, which would, replaces that default action in every script that makes a workspace (a process blocked in a synchronous `az` or `pac` call would no longer end when signalled, and the signal would have to be raised again to keep its status) — so a run that is signalled leaves its workspace for the next run's sweep, as a killed one does; a folder that cannot be used or a record that cannot be written costs the sweep, never the run. The sweep reads only the plugin's own folder, never the temp folder, which can hold hundreds of thousands of entriesprocess-owner.js ← who made a lock or a workspace, and whether that process is gone — one place for the pages lock, the temporary workspaces and the snapshot lease's liveness check (`processAlive`, as it always was). `ownerStamp()` is what a maker records (pid, time, host, platform, and on Linux the pid namespace and the process's start time from `/proc`); `ownerState(stamp)` answers `gone` only when the stamp was made on this machine, by this kind of system, in this pid namespace, and no process has the pid (ESRCH) — or, on Linux, a zombie or a process with another start time has it (the pid was handed out again) — `alive` for a process that runs (this one included) and `unknown` for anything else: another machine, a stamp that is missing, damaged or not understood. **On Linux a pid is only a name inside its pid namespace, so the stamp AND the reader must both name theirs (`pid:[…]`, readable and well formed) and name the same one: a side that cannot (a hidden `/proc`: a container, hidepid, a sandbox), or two that cannot, is `unknown`, never "the same pid space".** A recorded `start` that is not `<boot id>:<ticks>` — empty, cut short, damaged inside a record that is still valid JSON — makes the record untrusted (`isOwnerStamp`: kept), and a start read from `/proc` that is not well formed is not compared: only two well-formed starts that differ show a pid handed out again, in the self-pid branch too. `ownerState` is a fact about the maker and only that: a workspace that was handed to a program that outlives its maker is kept by its age instead (`temp-workspace.js`, `lent`). Every doubt keeps; where no start time is cheap to read (Windows, macOS) a pid given to another process makes a dead run look alive, which keeps its lock or folder (the state of things before this module)windows-folder-acl.js ← who can change a folder on Windows, where Node reports no owner and no permissions, and the making of a folder that only this user can: `windowsFolderIsPrivate(folder)` saves the folder's access list with `icacls <folder> /save` (SDDL: SIDs, in every language, not names) and reads the user's SID with `whoami /user /fo csv /nh`, both started through `process-runner.js` with System32 first on PATH, and answers `{ ok, reason, owner? }` — private only when NO entry that grants a right to add to the folder, remove from it, delete it, write its attributes or extended attributes, change who may or take it over names anyone but this user, the system or the administrators (an INHERIT-ONLY entry counts too: it does not apply to the folder, but it is what every workspace and every owner record made in it is given; denials and audits grant nothing; SDDL writes the machine's own Administrator and Guest accounts as the aliases `LA` and `LG`, which are the user's own only for the user whose account that is, as a CI runner's renamed built-in Administrator is; an audit list after the access list, as Windows' own folders carry, is read and ignored) AND the folder is owned by this user or the administrators — whoever owns a folder can rewrite its list, so a list that names only the user does not make a foreign folder the user's. The owner is the one thing `icacls` cannot print (`/save` stores the list and nothing else), so it is read with PowerShell (`[IO.Directory]::GetAccessControl(folder, Owner)`, a SID; the folder goes in through the environment and the script is passed encoded) — half a second, which is why it is the last thing asked (a folder the list has refused never starts it), and PowerShell that cannot run is "not private". The administrators are accepted as owner because a process that runs elevated (a CI runner is one) owns what it makes through that group by default, and the list trusts them anyway. A list that icacls ran and could not save — Windows is removing the folder, which cannot be opened meanwhile — is `unreadable`, a "no" that `temp-workspace.js` does not keep: it asks again after a pause, and drops an answer about a folder that was replaced while it was being judged; whatever else cannot be read, run or understood is not private, and `temp-workspace.js` then makes its workspace in the plain temp folder as before. `makeWindowsFolderPrivate(folder)` is for a folder this process has just made: `icacls <folder> /inheritance:r /grant:r *<user>:(OI)(CI)F *S-1-5-18:(OI)(CI)F *S-1-5-32-544:(OI)(CI)F` replaces its list, and the list is read back and must be exactly that — protected, nothing inherited, three grants, full control for the userpower-apps-service-client.js ← the HttpClient for the SDK's connection and connector reads: GET only, https only, a host allowlist that is exactly the hosts the SDK's connectivity code calls, redirects never followed, the Azure CLI token for the Power Apps service read only for a request that passed and never in a message, a body, a header or a key the service answers with (it is scrubbed, in whole and by part)@@ -3356,7 +3475,14 @@ NODE20_BIN=/path/to/node20/bin node scripts/run-tests.js --with-sdk /path/to/powThe suite runs in a temporary folder of its own (TEMP, TMP and TMPDIR point into it), and the runFAILS when a test leaves a file or folder in it, naming what was left: a test removes everything itmakes. `scripts/tests/helpers/temp-dirs.js` (`makeTempDir`) is the shared way — require it at the top- of the test file, and the folders it makes are removed after the file's last test.+ of the test file, and the folders it makes are removed after the file's last test. The folder the suite+ runs in is the plugin's own, so the run FAILS too, naming the folder, when a test makes a+ `.maker-workspace` there that was not there before the run (a build opens `<app folder>/.maker-workspace`+ unless it is given a workspace, so a test must never hand a build `process.cwd()`; `sdk-build.test.js`+ gives a build that names no app folder one of its own). The runner removes such a folder only when it is+ empty, so that the next run is not blind to the leak; one with anything in it, a link or a file is left where it+ is and the run says so (`kept`), since it cannot tell a test's folder from the workspace of a build another+ process started beside the suite and deletes nothing it cannot show to be its own — delete it by hand.**CI runs this same command** (`.github/workflows/model-apps-script-tests.yml`) on any PR into `main`touching `plugins/model-apps/**`, `evals/model-apps/**`, `shared/telemetry/**`, `shared/skills/**` or theworkflow itself, across ubuntu × windows × macos and Node 20 × 22.@@ -3553,7 +3679,10 @@ makes its folder with `fs.mkdtempSync(path.join(os.tmpdir(), …))`: each callsthat does not). It puts the folder, named for the process that made it and holding an owner record, in a folder of the plugin's own in the tempdirectory, and the first workspace a process makes removes the workspaces of runs that are PROVABLY gone(`lib/process-owner.js`), saying so on stderr; a run that may still be going (its folder is not even opened), another machine's, and a-folder with no readable record are left alone. A sweep looks at no more than 500 entries and removes no more than 100, and the entries it looks at+folder with no readable record are left alone. A run that is cut short by `process.exit` or an error nothing catches removes its own workspaces — not a lent one —+in its `exit` event, before the plugin's folder when that is empty, so only a killed or signalled run leaves one for a sweep (a POSIX signal runs no JavaScript, and a listener for it+would replace its default action in every script: `lib/temp-workspace.js` says why that is not done; `tests/temp-workspace.test.js` ends real children each way,+beside another run's workspace and among runs that make and remove workspaces). A sweep looks at no more than 500 entries and removes no more than 100, and the entries it looks atmove on from one sweep to the next — a cursor, one small file in the plugin's folder, written whole and there only while the folder holds more than asweep looks at — so that a folder whose first 500 entries must be kept does not hide a dead run's workspace, or a removal a kill left half done,behind them for good (`tests/temp-workspace.test.js` builds that folder and sweeps it in one process and in new ones). `tests/killed-run-workspaces.test.js` kills a real page@@ -4366,7 +4495,10 @@ real bundle, because a stub stays green through a change in the SDK's own rule.POSIX — SIGINT, SIGTERM and SIGHUP (the child ends BY the signal) and — on Windows — a REAL Ctrl+C and Ctrl+Break(the child ends with 0xC000013A, as one that registers nothing does: `helpers/console-event.js`); and that a runthat is KILLED for real leaves its folder, copy and all, which a sweep keeps while it is young and removes once it- is old. The tests find the work folder by `helpers/solution-settings-work-folder.js`: its name in either place, the+ is old. `killed-run-workspaces.test.js` also runs the template path over a fake pac that cuts the run short —+ `process.exit`, an error nothing catches and, on POSIX, a SIGTERM — and holds that the workspace lent to pac goes+ and the plugin's folder it was in goes with it (the maker's own listener runs first and cannot take that folder).+ The tests find the work folder by `helpers/solution-settings-work-folder.js`: its name in either place, theplugin's folder of a given temp folder, the files in it but for the owner record, and a refusal of each way ofmaking it (`fs.mkdtempSync`, which the maker calls for both). `private-folder.test.js` runs the Windowssequence over a stand-in for the process runner (the SDDL `icacls /save` writes, the CSV `whoami` prints, the order of@@ -4423,7 +4555,13 @@ real bundle, because a stub stays green through a change in the SDK's own rule.there would fail the teardown step of every table whose model another component had adopted. What the SDKcannot settle throws `ROW_SUMMARY_REMOVAL_UNCONFIRMED` (the skill-row delete's outcome unknown, naming ourmodel) or `ROW_SUMMARY_MODEL_NOT_DELETED` (the model left behind, naming it). Teardown's `aiSummary` step- still treats every failure as best-effort and does not surface these: the table delete that follows reports the+ looks for the skill row first, with the SDK's own request, because `removeRowSummary` answers nothing both+ when it removes a row summary and when it finds none — a step that only called it printed `(1 deleted)` for+ every table without one — and reports a table with none as not found (`teardown-row-summary-lookup.test.js`+ holds the lookup to what the bundle asks for). It is still best-effort for failures: a lookup that cannot be+ made (`not looked up — …`, kept) or a removal that throws (`kept — 1 not removed: <the SDK's words>`) fails+ nothing, and the closing line counts it with the kept steps, not the deleted ones, as its own step line does.+ The table delete that follows reports thedependency if the skill row is still there, and a model left behind blocks only a later row summary for thesame table, by name.- **Changes in the same SDK release that no plugin path reaches** — read these again before a plugin changediff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.mdindex f0d64bbd6..86b83c246 100644--- a/plugins/model-apps/CHANGELOG.md+++ b/plugins/model-apps/CHANGELOG.md@@ -5,6 +5,94 @@ 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.+## [2.16.0]++The bundled SDK is updated to power-platform-ux ccf2c1a1, and a new table's primary (name) column is now created required when the+spec says so. The spec gate refuses two values the build used to misread — an `AutoNumber` column without a format and a `required`+that is not `true`, `false` or `"recommended"` — before anything is written, and `--verify` of an app an earlier release built only+warns about them. Navigation titles survive a download and rebuild on an environment whose base language is not English. Teardown+keeps what only a kept table blocks instead of reporting the platform's refusals, and a run cut short removes its temporary folders.++### Changed++- **A download reads the environment's base language** (one more read, made only when the spec on disk pins no `languageCode` and+ `--language-code` — new on `download-model-app.js`, read-time only — is not given) and reads the navigation titles in that+ language. When it cannot establish the language it stops without writing anything (`navigation-language-unknown`) instead of+ guessing 1033: run it again, or pass `--language-code <lcid>`. A language other than the base language given that way must be+ given to the build and to `verify-model-app.js` too, or pinned as the spec's `languageCode`. On a bilingual environment whose base+ language is not 1033, dashboard tile names are read in the base language.++- **The bundled SDK is updated (power-platform-ux ccf2c1a1).** What a maker can see of it:+ - a business process flow edit the flow cannot hold (a binding with no value, `required` on a step that has no slot for it) fails+ with a message instead of reporting success, and a flow's security that names an access level its table cannot grant is+ refused before any role is written;+ - a command bar control copied with another control's id fails the push instead of overwriting that control;+ - a generative page whose source holds text that only looks like an import of `./RuntimeTypes` (in a string, a template or a+ comment) is refused with a message that names that text's line and column;+ - an answer that lacks the rows or the record it should carry is an error, not an empty result;+ - a workspace copy that an interrupted build of an earlier release left with edits it never pushed is refused at its next push+ and asks for the documented reset (a copy without such edits is simply read again);+ - a dashboard tile that hosts a custom control (the Power Apps grid control, say) is still left out of a download, named in its+ warning, and out of `--verify`: the SDK now reads such a tile as a list or a chart, and the plugin tells it apart by its+ control, so it is never written into `dashboards[]` as a plain tile.+- **An `AutoNumber` column without a usable `autoNumberFormat` is refused when the spec is validated** — by the build and by the+ input gate of `provision-entities.js` that `/genpage` and `/app-builder` go through — before anything is written. The SDK no longer+ creates such a column (it made a plain text column), so the build would have stopped at it after the solution and the tables were+ made. The error names the table and the column and both ways out: a format such as `"C-{SEQNUM:5}"`, or `type: "Text"` for a+ plain text column — which is also what such a column an earlier release built is. A blank format, or one that is not a string, is+ refused the same way. A primary name column without `autoNumberFormat` is still a plain text name column.+- **A column's — or the primary name column's — `required` must be `true`, `false` or `"recommended"`.** Every other value+ (`"ApplicationRequired"`, `"true"`, `"required"`, `"Recommended"`, `1`, `null`) was read as "not required": a new column was+ created not required, and an existing column was written down to None, demoting one a maker had made Business Required. It is now+ refused at validation, naming the table, the column and the value and what to write instead; leaving `required` out still leaves+ an existing column as it is. Both rules are warnings, not errors, for `verify-model-app.js` — which creates and changes nothing —+ so an app built from a spec an earlier release accepted can still be verified, and teardown still accepts such a spec.+- **The forms phase writes the order of every Main form it orders, the first of a table included.** The SDK now creates a form with+ no form order (it wrote `Order="0"`), so on the build that creates a table's Main forms the first of them is written once more. A+ rebuild finds every order in place and writes none.+- **An environment without the row-summary AI template skips the row summaries with one warning.** The SDK now looks the template+ up before it writes anything and refuses an environment that has none (it published a model that named no template and let the+ platform answer). The build confirms that the template list is empty with one read of its own before it skips — a list it+ cannot read as a list of templates stops the build as before — and a throttled or interrupted confirmation read is retried like any+ other read the build makes.++### Fixed++- **A `required` on a new table's primary (name) column is applied when the table is created.** The create sent the name column as+ not required — a plain text name column is stored not required whatever the create asks — and the build still reported+ `required <table>.<column> (applied on create)`; only a rebuild set it. The table's create now asks for the level, the SDK reads+ it back and sets it with one update, and the build says it was applied only when the SDK confirms it for a table the build saw+ created. When the level cannot be confirmed the table still exists: the build stops once (or, for a table found after the answer+ to its create was lost, or whose columns could not be read, warns and goes on), and running it again finds the table and sets the+ level. The table is never created twice.+- **Navigation titles survive a download and rebuild on an environment whose base language is not 1033** (a Spanish-only one, say).+ The download read every title in 1033, a language such an environment does not hold, so it wrote an empty `label`/`title` for every+ area, group and entry, and a rebuild of that spec cleared the titles; on a bilingual environment with another base language it+ wrote the English titles, which a rebuild then wrote over the base-language ones. The download now reads them in the language a+ rebuild resolves (see Changed).+- **A rebuild never clears a navigation title the spec does not state.** An area or a group without a title in the spec keeps the+ title it has, and so does an entry, unless the baseline shows the spec used to state one (then the title is removed, as before); a+ stated title is applied as before. An empty group (or area) of a spec an earlier release wrote is matched to the environment's one+ empty group; where more than one could be meant, none is paired by position and the build names each title it does not keep.+- **Teardown no longer reports a row summary it did not delete.** A table with none reads `⊘ row summary <table> (not found)`+ instead of `✓ … (1 deleted)`, and the closing counts follow. A lookup or a removal that fails is said on the step's line and+ counted as kept, never as a deletion; it still does not fail the teardown.+- **Teardown keeps what only a kept table blocks, instead of reporting the platform's refusals.** When a business rule could not be+ deleted, teardown keeps its table until a re-run (the rule's activated copy can only be deleted while the table exists), but it+ still tried the deletes that follow the tables — the table's icon web resource and a global choice one of its columns binds,+ which the platform refuses while the table exists, and a relationship from the table to itself, which it refuses while the table+ still holds something that refers to its lookup — so one failure was reported as up to four. Those steps are+ now kept with the table, each a `(kept — …)` skip that names it, and the re-run deletes them once the table goes. The run still+ ends as a failure and keeps the solution. The dependency is read from the spec, so an icon or a binding made by hand in the+ environment is still tried and refused as before. A rule whose deactivation succeeded and whose delete failed stays deactivated+ until the re-run.+- **A run cut short by `process.exit` or an error nothing catches removes the workspaces it made and did not lend, and then the+ plugin's temporary folder (`power-platform-skills-model-apps`) when it is empty**, instead of leaving both for the next run. A+ POSIX signal still ends a run as before, and the next run's sweep removes what it left.+- The plan document shows a `"recommended"` column as recommended, not required.+- The test suite no longer leaves `plugins/model-apps/.maker-workspace` behind, and `scripts/run-tests.js` fails a run that makes+ one there (removing it only when it is empty).+## [2.15.0]Generative pages, the environment's apps and tables, connections, connector metadata and deployment settings now go through thediff --git a/plugins/model-apps/references/app-spec-schema-advanced.md b/plugins/model-apps/references/app-spec-schema-advanced.mdindex cc17cff6f..e5aa33234 100644--- a/plugins/model-apps/references/app-spec-schema-advanced.md+++ b/plugins/model-apps/references/app-spec-schema-advanced.md@@ -298,6 +298,16 @@ works through.An id-based chart tile needs `viewId` **and** `entity` (a visualization with no view has nothingto plot); an id-based list tile needs `viewId` and `entity`. Author specs by name; let downloadsuse ids.+- **A tile a custom control hosts is not expressible.** A grid or chart that a custom control hosts (the+ Power Apps grid, say) reads like a native tile, but the spec describes only the four tile types+ above. A download leaves such a tile out and names it in a warning — it never emits the plain grid or+ chart its parameters describe, which would replace the control wherever the dashboard is created from+ the spec. A rebuild into the environment the spec was downloaded from keeps the dashboard as it is+ (a build never edits an existing dashboard's tiles), so the control stays; in another environment the+ dashboard is created without that tile, and the tile is added there in Maker. `--verify` leaves such a tile+ alone too: it holds only a native chart tile to a chart and view of its table. A dashboard whose only+ tiles are such tiles is dropped with its navigation entry, which the download refuses without+ `--allow-lossy-download`.## roleGrants[] (optional — extend a role you did NOT author)diff --git a/plugins/model-apps/references/app-spec-schema.md b/plugins/model-apps/references/app-spec-schema.mdindex 1c1a514fd..b897bf16c 100644--- a/plugins/model-apps/references/app-spec-schema.md+++ b/plugins/model-apps/references/app-spec-schema.md@@ -314,6 +314,15 @@ languages resolves to the same artifact. One option, one value, several names.column or option labelled in several languages comes back as a map, and one labelled in a singlelanguage comes back as a plain string (so no existing spec changes shape). The download emits`pluralName` alongside a localized `displayName`, so its own output re-validates.+A navigation `label` or `title` is always a plain string (the spec has no map form for one), read in the+language a rebuild writes it in: `--language-code`, else the `languageCode` the spec already on disk pins,+else the environment's base language. When none of the three gives one — the base language could not be+read — the download writes nothing (`"code": "navigation-language-unknown"`) rather than guess one: run it+again, or pass `--language-code <lcid>` (it decides the language the titles are read in and is not written+into the spec, so a language other than the environment's base language must be passed to the build and to+`verify-model-app.js` too, or pinned as the spec's `languageCode`, or a rebuild writes those titles as+base-language titles). A title a node holds only in another language is not in the spec, and a rebuild into the+same environment leaves it as it is.## `description` — write one on everything that takes one@@ -463,13 +472,15 @@ spec with its last snapshot, not with the deployed row, so it does not notice).- **Column `type`:** `Text · Memo · Choice · MultiChoice · Boolean · Money · DateTime ·Integer · BigInt · Decimal · Double · File · Image · AutoNumber · Customer`.**Lookups are NOT columns** — declare a `OneToMany` relationship instead.-- **Per-type options** (all optional): `required: true` / `"recommended"`; Text → `maxLength`,+- **Per-type options** (all optional except an AutoNumber column's `autoNumberFormat`): `required: true` /+ `"recommended"` / `false`; Text → `maxLength`,`format` (`Text`/`Email`/`Url`/`Phone`); numeric → `minValue`/`maxValue`/`precision`;Integer → also `integerFormat` (`None`/`Duration`/`TimeZone`/`Language`/`Locale` — e.g. render araw 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"` ++ `autoNumberFormat` (**required** on an AutoNumber column, e.g. `"C-{SEQNUM:5}"` — see the+ AutoNumber note below); Calculated/Rollup → `source: "Calculated"|"Rollup"` +`formula`.- **Write permissions** (optional, every column type **except Customer**): `isValidForCreate` /`isValidForUpdate` / `isValidForRead` — see `isValidForCreate / isValidForUpdate /@@ -480,12 +491,26 @@ spec with its last snapshot, not with the deployed row, so it does not notice).column (not `BigInt`/`Decimal`/`Double`/`Money`, even though they share the same numeric`minValue`/`maxValue`/`precision` options) — either mismatch is rejected by name at validationtime rather than surfacing as a mid-build SDK error.-- **`required` converges on rebuild only when authored explicitly.** For a new column, `true` creates+- **`required` is `true`, `false` or `"recommended"` — and converges on rebuild only when authored+ explicitly.** `true` is Dataverse `ApplicationRequired` (Business Required), `"recommended"` is+ `Recommended` and `false` is `None`. Any other value — `"ApplicationRequired"`, `"true"`,+ `"required"`, `"Recommended"`, `1`, `null` — is refused at validation, on a column and on+ `primaryAttribute` alike, naming the table, the column and the value (the build would otherwise+ read it as not required, and write that over an existing column's level); omit the key instead to+ leave an existing column as it is. For a new column, `true` createsDataverse `ApplicationRequired` and `"recommended"` creates `Recommended`. For a column thatalready 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.+ silently demotes a field a maker already made Business Required. The primary/name column's+ `required` is applied on a **new** table too: it is asked in the table's create, and because a plain+ text name column is stored not required whatever the create asks (an auto-numbered one keeps the+ level), the build's SDK reads the level back and sets it with one update. The build says the level+ was applied on create only once the SDK has confirmed it (for `false`, once it has seen the table+ created). When it cannot be confirmed the table still exists: the build stops (or, for a table found+ after the answer to its create was lost, or an existing table whose columns could not be read,+ warns — `false` too, since nothing shows what the column holds), and running the build again finds+ the table and sets the level as it does for any existing column — it never creates the table twice.- **`defaultValue`, `integerFormat`, and `isValidFor*` converge differently: by re-assertion, notby 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@@ -497,6 +522,10 @@ spec with its last snapshot, not with the deployed row, so it does not notice).(see `globalChoices` below). **Customer** is a polymorphic account/contact lookup.- **AutoNumber** can also be the **primary** column — put `autoNumberFormat` on `primaryAttribute`(above) instead of adding a separate column, so the generated number is the record identity.+ An `AutoNumber` **column** needs its `autoNumberFormat` — a non-blank string such as `"C-{SEQNUM:5}"`.+ One without it is refused when the spec is validated, before anything is built, naming the table and+ the column: the platform would create a plain text column instead, so write `type: "Text"` for a plain+ text column. On the primary column the format stays optional: without one the name column is plain text.- **Primary column length — `primaryAttribute.maxLength`** (optional; a whole number from 1 to 850, themost Dataverse allows for a table's name column — more is refused by Dataverse, soanything else is rejected at validation, for `/genpage` and `/app-builder` input as well). Without it@@ -1074,8 +1103,8 @@ A table's Main forms are served in its **Main Form Set order**, and a user opensthey may open** — unless they switched forms earlier: the platform remembers the last Main form eachuser opened for a table and opens that one for them while they may still open it. The order isstored on each form (its formxml `<DisplayConditions Order="n">`), and `systemform.isdefault` does-not change it: measured, moving the flag reordered nothing, and a table's three new Main forms — all-at the same order, as every new form is — were served with the `isdefault` form *last*.+not change it: measured, moving the flag reordered nothing, and a table's three new Main forms, all at+the same order, were served with the `isdefault` form *last*.- **`forms[].isDefault: true`** — this form opens first: it becomes the table's default **and** comesfirst in the order. Applied on any table.@@ -1617,6 +1646,15 @@ custom control), but the spec validator emits a warning.written onto the live entry it corresponds to (a subarea by its target; an area or group by itslabel), so the live entry's id, its other attributes (`Client`, `Sku`, `AvailableOffline`, …) and itstitles in other languages survive; only the label, title, target and icons the spec sets are applied.+ **A title the spec does not give is kept:** an area, group or entry whose `label` / `title` is empty or+ left out keeps the title it has in the environment, and the build says so — a rebuild never clears one,+ so state a title to change it. (An entry whose title the baseline below shows the spec used to state,+ and the spec now leaves out, loses it: that is an edit.)+ **An area or group with no entries and no label** — what an earlier download wrote for each empty group of an+ environment whose base language is not 1033 — is the environment's empty group when there is one of each. With more than+ one on either side, which is which cannot be told, so none is paired: the spec's are written as new, untitled+ ones, and the build names each environment group it does not keep, with its title. Give the spec's group the+ label it has in the environment to keep it.A `dashboard` entry is written the way the designer writes one, with`Url="/workplace/home_dashboards.aspx"` — without it the app shows a placeholder icon for the entry,and `--verify` fails it.diff --git a/plugins/model-apps/references/authoring-flow.md b/plugins/model-apps/references/authoring-flow.mdindex 508c45965..b1574b511 100644--- a/plugins/model-apps/references/authoring-flow.md+++ b/plugins/model-apps/references/authoring-flow.md@@ -336,8 +336,9 @@ clearly, then use `AskUserQuestion` to confirm or refine:Column `type` is one of: `Text · Memo · Choice · MultiChoice · Boolean · Money · DateTime ·Integer · BigInt · Decimal · Double · File · Image · AutoNumber · Customer`. A `Choice`/`MultiChoice`-column needs `options[]` **or** a `globalChoice` reference. Lookups are **not** a column type —-declare a `OneToMany` relationship instead.+column needs `options[]` **or** a `globalChoice` reference, and an `AutoNumber` column needs an+`autoNumberFormat` such as `"C-{SEQNUM:5}"` (`Text` is the plain text column). Lookups are **not** a+column type — declare a `OneToMany` relationship instead.> **Author from [`references/app-spec-schema.md`](./app-spec-schema.md) — it is the source for> everything an app always has; [`app-spec-schema-advanced.md`](./app-spec-schema-advanced.md)diff --git a/plugins/model-apps/scripts/download-model-app.js b/plugins/model-apps/scripts/download-model-app.jsindex 0933f28bc..6ef0d04bf 100644--- a/plugins/model-apps/scripts/download-model-app.js+++ b/plugins/model-apps/scripts/download-model-app.js@@ -7,7 +7,7 @@// pages (read through the SDK, incl. Maker-authored), its entities (minimal — the build reuses// existing tables idempotently), the icon web resources, and its solution, via hydrate-spec.//-// Usage: node download-model-app.js --env <orgUrl> --app <appId|uniqueName|displayName> --out <dir> [--allow-lossy-download] [--reset-page-keys]+// Usage: node download-model-app.js --env <orgUrl> --app <appId|uniqueName|displayName> --out <dir> [--allow-lossy-download] [--reset-page-keys] [--language-code <lcid>]//// A page's key is its identity in a rebuild, so a download keeps the key each page already has: the one the app's page manifest binds to it, then the one an// earlier download of the SAME app gave it (the app-spec.json already in --out, when its app.uniqueName is this app's). If that earlier spec gives a page keys that@@ -15,11 +15,17 @@// `{ ok: false, code: 'page-keys-ambiguous', error, pages }`. Correct the file and download again, or pass --reset-page-keys to give exactly those pages fresh// keys (minted in page-id order; every other page keeps its key). The switch is a decision about every environment that holds a copy of the earlier spec: it// binds each key to the page it built there, so a fresh key can make that copy update another page.+//+// The app's navigation titles are written in the language a rebuild resolves, and a download writes them only in a language it KNOWS: --language-code <lcid> (read as the build and verify+// read it), else the `languageCode` the app-spec.json already in --out pins, else the environment's base language. When none of the three gives one — the base language could not be read —+// the download stops without writing anything, `{ ok: false, code: 'navigation-language-unknown', error }`: titles read in a guessed language could overwrite the right ones on the next+// rebuild. Run it again, or pass --language-code. The flag only decides the language the titles are read in: it is not written into the spec (a pin there is the author's), and a flag that+// names another language than the spec on disk pins is refused (`navigation-language-conflict`).const fs = require('node:fs');const path = require('node:path');const { assertSafeOutputDir, assertPlainFileTarget, writeFileSafe } = require('./lib/safe-fs.js');-const { parseArgs, validateFlags, emitResult, preflightAuth, dataverseOrigin } = require('./lib/dataverse-auth.js');+const { parseArgs, validateFlags, emitResult, preflightAuth, dataverseOrigin, requireDataverseOrigin, webApiUrl, readOrgLanguageCode, readLanguageCodeFlag } = require('./lib/dataverse-auth.js');const { writeBaseline } = require('./lib/deployed-baseline.js');const { createAzHttpClient } = require('./lib/sdk-http-client.js');const { hydrateSpec, descriptionFromDataverse, withDescription } = require('./lib/hydrate-spec.js');@@ -34,6 +40,7 @@ const { odataGuid } = require('./lib/ai-app-settings.js');const { APP_COMPONENT_ENTITY_SOURCES, appComponentEntities, appComponentRows, currentAppLayer, readAppComponentInventory, downloadAppMainForms, setAppMembershipFloor } = require('./lib/app-components.js');const { mapLimit } = require('./lib/entity-provision.js');const { compareText } = require('./lib/compare-text.js');+const { hostsCustomControl } = require('./lib/dashboard-tiles.js');const { appUniqueName } = require('./lib/sdk-build.js');const { makeTempWorkspace } = require('./lib/temp-workspace.js');@@ -129,6 +136,18 @@ async function readDashboards(sdk, app, warn) {const p = c.parameters || {};const entity = p.TargetEntityType;const viewId = strip(p.ViewId);+ // A grid or chart a custom control hosts reads exactly like a native one (lib/dashboard-tiles.js, which verify shares),+ // so it must be told apart BEFORE the branches below build a plain tile from its parameters. It is left out, and named —+ // never emitted as the plain tile that would replace the control when a rebuild creates the dashboard. A rebuild into+ // this environment is not touched either way: the spec pins the dashboard by its id, and the build reuses a+ // dashboard that exists without applying its tile edits (so it never replaces or removes a tile).+ if (hostsCustomControl(c)) {+ if (typeof warn === 'function') {+ warn(`dashboard '${name}' tile '${c.name || '(unnamed)'}' hosts a custom control, which the App Spec cannot express, so it is omitted from dashboards[]. `+ + 'A rebuild into this environment keeps the dashboard as it is, so the control stays; a rebuild into another environment creates it without this tile — add the tile there in Maker.');+ }+ continue;+ }if (c.type === 'chart' || c.type === 'list') {// The two id-passthrough tile shapes, gated together because they share their required// parameters. EVERY one of these ids is load-bearing: a chart renders a visualization OVER a@@ -462,6 +481,53 @@ function relationshipsSkippedWarning(skipped) {return `${lines.join('\n')}\n`;}+// The language the download's SDK reads the app in, which decides what the app's navigation TITLES are. The SDK projects a sitemap in ONE language, the one it is constructed with: a node's title+// is the `<Title LCID="…">` whose LCID is that language, and "" when the node has none. An SDK built with no language reads 1033, so on an environment whose base language is another — a+// Spanish-only one holds its titles at 3082 and no other — every area, group and entry came back with no title, and the spec said so: `"label": ""` for an app whose every node has one.+//+// It is the language a rebuild of the spec this download writes will resolve, in the order the build resolves it (lib/entity-provision.js resolveLanguageCode): `--language-code` (`flag`), else the+// `languageCode` an author pinned in the spec already on disk (`authored`, which preserveAuthoredLanguageCode carries into the spec this download writes), else the environment's base language.+// A label is then a plain string in that language — the rule a table's label follows too (labelFromDataverse) — and the language itself is never written into the spec, for the reason+// preserveAuthoredLanguageCode gives. A title a node holds in another language is not in the spec: a rebuild into this environment leaves it as it is.+//+// The base language is read through the download's own HTTP client (the build reads the same row through the transport hatch, readOrgLanguageCode), so one set of credentials, retries and+// test seams serves the download.+//+// There is NO fallback. The build, when it cannot read the base language, warns and uses 1033 (resolveLanguageCode), and `--verify`, which describes a deployment as a download does, refuses to+// assume one (its `undetermined` hook). A download is the stricter of the two: the spec it writes is consumed by a build that may well read the language this one could not, and on a bilingual+// environment whose base language is not English the English titles of a guessed 1033 are non-empty labels, which that build writes over the right ones. So a language that cannot be established+// is returned as `unresolved` — the reason — and whoever asked refuses.+// Returns { languageCode, source: 'flag' | 'spec' | 'environment' } or { unresolved }.+async function readNavigationLanguage(env, httpClient, { flag, authored } = {}) {+ if (flag) return { languageCode: flag, source: 'flag' };+ if (authored) return { languageCode: authored, source: 'spec' };+ let why = 'the answer named no language';+ // `readOrgLanguageCode` reads `{ status, data }`, the transport hatch's shape for an answer; the SDK's client answers `{ status, headers, body }` and resolves a non-2xx instead of throwing it.+ // The answer it reads: `GET organizations?$select=languagecode&$top=1` -> `{ "value": [ { "organizationid": "…", "languagecode": 3082 } ] }`. The client takes a FULL URL under the+ // environment and refuses anything else (it attaches the access token), so the query is put under the Web API root the way `dataverseRequest` puts it. The reason a read fails is kept+ // here, because readOrgLanguageCode answers only null for every one of them and the operator needs to know which: a refusal (HTTP 403) is not the service being down (HTTP 503).+ const viaClient = async (envUrl, _method, query) => {+ let res;+ try {+ res = await httpClient.get(webApiUrl(requireDataverseOrigin(envUrl), query));+ } catch (err) {+ why = (err && err.message) || String(err);+ throw err;+ }+ if (res.status < 200 || res.status >= 300) why = `HTTP ${res.status}`;+ return { status: res.status, data: res.body };+ };+ const base = await readOrgLanguageCode(env, viaClient);+ return base ? { languageCode: base, source: 'environment' } : { unresolved: why };+}++// What the download says when no language is known, and how to go on: run it again (the read may only have failed for a moment), name the language, or pin it in the spec.+function navigationLanguageRefusal(why, specPath) {+ return `the environment's base language could not be read (${why}), so the language the app's navigation titles are written in is not known, and a spec written with the titles of a guessed language `+ + 'could overwrite the right ones on the next rebuild. Nothing was written. Run the download again; or name the language with --language-code <lcid> (the flag the build and verify take): '+ + `the environment's base language, for example 1033 or 3082; or pin "languageCode" in ${specPath}.`;+}+// The SDK a download reads through, on a THROWAWAY workspace that is removed afterwards — never the// output folder's `.maker-workspace`, which is the workspace a later build in that folder uses. A// download must describe what is DEPLOYED, and reading through that workspace could not promise it: a@@ -473,6 +539,9 @@ function relationshipsSkippedWarning(skipped) {// Construction happens INSIDE the guard: the constructor builds the filesystem adapter and can throw,// and the caller's `finally` is not reachable until this function returns (as in build-model-app.js).// `deps` is a test seam: the bundle's factories, the HTTP client, and the temp-directory calls.+// `deps.languageCode` is the `--language-code` the operator gave and `deps.authoredLanguageCode` the language the spec on disk pins, if either is there (readNavigationLanguage). The result+// says where the language came from (`languageCode`, `languageSource`) or that there is none (`languageUnresolved`, the reason): the SDK is made either way, in the SDK's own default when there+// is none, and it is the caller's to refuse — whatever it reads with that default is a guess.async function makeDownloadSdk(env, deps = {}) {const workspaceDir = makeTempWorkspace('model-app-download-', { mkdtempSync: deps.mkdtempSync });const cleanup = () => (deps.rmSync || fs.rmSync)(workspaceDir, { recursive: true, force: true });@@ -481,9 +550,21 @@ async function makeDownloadSdk(env, deps = {}) {? deps: require('./lib/maker-sdk.js');const httpClient = deps.httpClient || (deps.createHttpClient || createAzHttpClient)(env);- const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(workspaceDir), instanceUrl: env, httpClient });+ const language = await readNavigationLanguage(env, httpClient, { flag: deps.languageCode, authored: deps.authoredLanguageCode });+ const sdk = createMakerSdk({+ workspaceStorage: createNodeWorkspaceStorage(workspaceDir),+ instanceUrl: env,+ httpClient,+ // The App, Form and Dashboard adapters bake the language in at construction, as the build gives its own SDK (build-model-app.js).+ ...(language.languageCode ? { languageCode: language.languageCode } : {}),+ });await sdk.initWorkspace();- return { sdk, workspaceDir, cleanup };+ return {+ sdk,+ workspaceDir,+ cleanup,+ ...(language.languageCode ? { languageCode: language.languageCode, languageSource: language.source } : { languageUnresolved: language.unresolved }),+ };} catch (err) {cleanup();throw err;@@ -1135,8 +1216,10 @@ const SPEC_TYPE_FROM_ATTRIBUTE_TYPE = {// 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.)+// ONLY such dependency: every other companion rule in `validateAppSpec` / `spec-lint` — Calculated/+// Rollup's formula, Customer's description — is a warning, not an error. An AutoNumber column's+// format IS an error there, and cannot arise here: an auto-number column is a String attribute, so it+// is hydrated as Text, and no AutoNumber column or format is ever emitted.)//// 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@@ -2716,12 +2799,12 @@ async function main(deps = {}) {validateAppSpec: deps.validateAppSpec || validateAppSpec,};const { positional, flags } = parseArgs(argv);- const USAGE = 'Usage: node download-model-app.js --env <url> --app <appId|uniqueName|displayName> --out <dir> [--allow-lossy-download] [--reset-page-keys]';+ const USAGE = 'Usage: node download-model-app.js --env <url> --app <appId|uniqueName|displayName> --out <dir> [--allow-lossy-download] [--reset-page-keys] [--language-code <lcid>]';// `--allow-lossy-download` and `--reset-page-keys` are real boolean switches, so they stay out of needValue; everything else- // feeds a URL, an app id, or a path and must not receive `true`.+ // feeds a URL, an app id, a path or an LCID and must not receive `true`.const flagError = validateFlags(argv, {- known: ['env', 'app', 'out', 'output', 'allow-lossy-download', 'reset-page-keys'],- needValue: ['env', 'app', 'out', 'output'],+ known: ['env', 'app', 'out', 'output', 'allow-lossy-download', 'reset-page-keys', 'language-code', 'languageCode'],+ needValue: ['env', 'app', 'out', 'output', 'language-code', 'languageCode'],});if (flagError) {io.stderr.write(`✗ ${flagError}\n${USAGE}\n`);@@ -2739,6 +2822,16 @@ async function main(deps = {}) {io.exit(1);return;}+ // The language the navigation titles are read in, when the operator names one: read exactly as the build and verify read the flag. A value that is no LCID, or a pair that disagrees, is refused+ // here, before anything is opened — titles read in a language the operator did not mean would be written into the spec as if they were the app's.+ let languageFlag;+ try {+ languageFlag = readLanguageCodeFlag(flags);+ } catch (e) {+ io.stderr.write(`✗ ${e.message}\n${USAGE}\n`);+ io.exit(1);+ return;+ }const outDir = path.resolve(outArg || '.');// Before auth and before the SDK. A link at --out would make the spec and the pages land// outside the directory that was named; a real directory is created if it is missing.@@ -2748,6 +2841,20 @@ async function main(deps = {}) {io.emitResult(false, { ok: false, error: (e && e.message) || String(e) });return;}+ // The spec this download may overwrite, and the language it pins (readAuthoredLanguageCode): the other source of the language the titles are read in.+ const specOnDisk = path.join(outDir, 'app-spec.json');+ const pinnedLanguage = readAuthoredLanguageCode(specOnDisk);+ // The flag outranks the pin, as it does for the build, but the spec this download writes keeps the pin (preserveAuthoredLanguageCode) and the flag is not written into it: titles read in the+ // flag's language and a spec that pins another would be rebuilt in the pin's, which writes one language's text as the other's. So the two must agree.+ if (languageFlag && pinnedLanguage && languageFlag !== pinnedLanguage) {+ io.emitResult(false, {+ ok: false,+ code: 'navigation-language-conflict',+ error: `--language-code ${languageFlag} names another language than the one the app-spec.json in ${outDir} pins ("languageCode": ${pinnedLanguage}): the titles would be read in one language and a rebuild `+ + 'would write them in the other. Pass the same language, or change the pin. Nothing was written.',+ });+ return;+ }// AB#6686427 — prove the ambient Azure CLI identity can actually reach this org BEFORE any read.// Every read below is best-effort by design (a tenant without a setting definition, or a caller// without access to one artifact class, must still produce a usable spec), so an auth failure does@@ -2767,7 +2874,13 @@ async function main(deps = {}) {let outcome = null;const finish = (ok, payload) => { outcome = [ok, payload]; };try {- session = await io.makeDownloadSdk(env, deps);+ session = await io.makeDownloadSdk(env, { ...deps, languageCode: languageFlag, authoredLanguageCode: pinnedLanguage });+ // No language known — the flag, the spec on disk and the environment all gave none — means nothing has been read with a guess yet, and nothing is: the refusal is the result, before the app is+ // resolved, and the spec and baseline on disk are as they were (navigationLanguageRefusal says how to go on).+ if (typeof session.languageUnresolved === 'string') {+ finish(false, { ok: false, code: 'navigation-language-unknown', error: navigationLanguageRefusal(session.languageUnresolved, specOnDisk) });+ return;+ }const sdk = session.sdk;const resolved = await resolveAppId(sdk, appArg);if (resolved.error) { finish(false, { ok: false, error: resolved.error }); return; }@@ -2853,6 +2966,19 @@ async function main(deps = {}) {}}+// The `languageCode` the spec already at `specPath` pins, or undefined when there is no such spec or it pins none (or a value that is no LCID). It is the value preserveAuthoredLanguageCode (below)+// carries into the spec this download writes, read first because the SDK has to be built with it: it is the language a rebuild resolves before the environment's, so it is the one the+// navigation titles are written in. Best-effort like that function: a missing, unreadable or malformed spec just pins nothing.+function readAuthoredLanguageCode(specPath) {+ try {+ if (!fs.existsSync(specPath)) return undefined;+ const lcid = normalizeLanguageCode(JSON.parse(fs.readFileSync(specPath, 'utf8')).languageCode);+ return lcid === null ? undefined : lcid;+ } catch {+ return undefined;+ }+}+// Carry an AUTHOR-PINNED `languageCode` across a download, and only from the spec already on disk.//// Download deliberately does not read `languageCode` from Dataverse. An LCID copied out of the sourcediff --git a/plugins/model-apps/scripts/lib/app-spec-doc.js b/plugins/model-apps/scripts/lib/app-spec-doc.jsindex b6a7c264d..190b24f74 100644--- a/plugins/model-apps/scripts/lib/app-spec-doc.js+++ b/plugins/model-apps/scripts/lib/app-spec-doc.js@@ -148,7 +148,8 @@ function dataModel(spec) {if (pa) out.push(`| ${cell(labelText(pa.displayName, spec && spec.languageCode) || pa.schemaName)} | ${cell(pa.type, 'Text')} | primary name${pa.autoNumberFormat ? `, auto-number \`${cell(pa.autoNumberFormat)}\`` : ''} |`);for (const c of objs(e.columns)) {const notes = [];- if (c.required) notes.push('required');+ if (c.required === true) notes.push('required');+ else if (c.required === 'recommended') notes.push('recommended');// `o.label` is the legacy object-option shape. A LOCALIZED option is also an object but has no// `label` key, so the legacy branch rendered every one as an empty cell — resolve through// labelText first and only then fall back.diff --git a/plugins/model-apps/scripts/lib/app-spec.js b/plugins/model-apps/scripts/lib/app-spec.jsindex 8d25b284f..ef35ed79a 100644--- a/plugins/model-apps/scripts/lib/app-spec.js+++ b/plugins/model-apps/scripts/lib/app-spec.js@@ -871,6 +871,55 @@ function primaryNameLengthProblem(length) {return `primaryAttribute.maxLength must be a whole number from 1 to ${PRIMARY_NAME_MAX_LENGTH} (got ${describeSpecValue(length)})`;}+// A column of type `AutoNumber` needs a format to be created with. The SDK refuses to create one without — an InvalidArgumentError raised before+// any request, for a missing, null, empty or blank format (measured against the vendored bundle for createColumn and createColumns alike; a format+// that is not a string does not get that far: the SDK throws a TypeError of its own) — where the SDK it replaced created a plain text column,+// which is all an autonumber column is until it carries a format.+// See: https://learn.microsoft.com/en-us/power-apps/maker/data-platform/autonumber-fields+// So a spec with an AutoNumber column and no format used to build, as text, and now halts the data-model phase at that column, after the solution+// and the tables exist. It is refused here instead, where nothing has been written, with both ways out: give the column a format, or declare it+// `Text`, which is also what a column an earlier release made from such a spec is.+//+// The ONE rule behind both gates — validateAppSpec and the provision-entities input validator, the entry point of /genpage and /app-builder — so+// that neither accepts what the other refuses. Each puts the table and the column in front of the text it returns (null when the column is fine).+// It looks at the AutoNumber TYPE only: a `Text` column that carries an `autoNumberFormat` is built as it always was (the format is not passed on),+// and the primary name column keeps its own rule — an absent or blank `primaryAttribute.autoNumberFormat` has always meant a plain text name column+// (the table create sends no format for it), a valid spec that builds as before. A format with no {SEQNUM} token stays the lint's warning.+function autoNumberFormatProblem(column) {+ if (!column || column.type !== 'AutoNumber') return null;+ const format = column.autoNumberFormat;+ let found;+ if (format === undefined || format === null) found = 'missing';+ else if (typeof format !== 'string') found = `not a string (got ${describeSpecValue(format)})`;+ else if (!format.trim()) found = 'blank';+ else return null;+ return `is an AutoNumber column but its autoNumberFormat is ${found} — give it a format such as "C-{SEQNUM:5}", or use type "Text" for a plain text column`;+}++// What a column's — or the primary name column's — `required` may be: true (Dataverse's ApplicationRequired, "Business Required"), "recommended"+// (Recommended) or false (None); or nothing, which asks nothing of a new column's create (it is created not required) and leaves an existing column as+// it is. The build reads exactly these (REQUIRED, lib/entity-provision.js) and took every other value for None, so every other value was a silent+// one: `"ApplicationRequired"`, `"true"`, `"required"`, `"Recommended"`, `1` or `null` made a new column not required and, on an existing column —+// which the build reconciles whenever the spec states a `required` — wrote None where the level differed, demoting a column a maker had made+// Business Required. Refused here instead, naming what was written and what to write. `undefined` is "not stated", as it is for every optional+// field of the spec (JSON cannot carry one), and the build reads it that way too (hasExplicitRequired).+// Not the other `required`s of a spec: a business process flow step's (a boolean, gated where the flow is), a business rule's SetBusinessRequired+// action's, a form's.+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/attributerequiredlevel+// The ONE rule behind both gates, like autoNumberFormatProblem; the callers put the column — or `primaryAttribute.required` — in front of the text it+// returns.+function requiredValueProblem(value) {+ if (value === undefined || value === true || value === false || value === 'recommended') return null;+ // The usual slips are the names Dataverse gives the levels, a boolean written as text, and a flag written as a number.+ const spelled = typeof value === 'string' ? value.trim().toLowerCase() : value;+ let hint;+ if (['applicationrequired', 'true', 'required', 'yes', 1].includes(spelled)) hint = 'write true for a required column';+ else if (spelled === 'recommended') hint = 'write "recommended" for a recommended column';+ else if (['none', 'false', 'no', 'optional', 0].includes(spelled)) hint = 'write false for a column that is not required';+ else hint = 'true makes a column required, "recommended" makes it recommended and false makes it not required';+ return `must be true, false or "recommended" (got ${describeSpecValue(value)}) — ${hint}; omit the key to leave an existing column's level as it is`;+}+// The length the spec asks for a table's primary name column, or undefined when it does not ask. The build, its dry-run plan// and its progress total all key on this one answer — it decides whether the build has a "primary column length" step for// the table — so they cannot disagree about it (the same arrangement as quickCreateEnabledFor).@@ -2280,10 +2329,20 @@ function validateSampleDataRows(entityKey, records, errors) {function validateAppSpec(spec, opts = {}) {const profile = opts.profile || 'deploy';+ // The column rules below (an AutoNumber column's format, a `required` value) say what the BUILD can use, so every profile that builds or plans a+ // build holds a spec to them. The structural profile — teardown's, which also serves preview and the eval harness — does not: it reads a spec for+ // the tables and components it names, and a spec an earlier release accepted and built (an AutoNumber column made as text, a `required: "true"`+ // made not required) must still be torn down. The same arrangement as the relationship-name collisions checked at the end of this function.+ const checksColumnValues = profile !== 'structural';const errors = [];// Non-blocking advisories (e.g. a PRE-EXISTING duplicate page name the current run did not create).// Additive to the return shape — callers that only read { ok, errors } are unaffected.const warnings = [];+ // Where the two column rules' findings go: errors, or — for read-only verification, which passes `columnValues: 'warn'` — warnings. Verification creates+ // and updates nothing and only reads whether each column exists, so rules that keep a BUILD from misreading a column's declaration have nothing to+ // protect there, and the spec of an app an earlier release built from a value they refuse must still reach its deployment. The same arrangement as+ // `relationshipCollisions: 'warn'` at the end of this function; every other caller keeps the error.+ const columnValueFindings = opts.columnValues === 'warn' ? warnings : errors;if (!VALIDATION_PROFILES.includes(profile)) {return { ok: false, errors: [`unknown validation profile '${profile}' (valid: ${VALIDATION_PROFILES.join(', ')})`], warnings };}@@ -2466,6 +2525,10 @@ function validateAppSpec(spec, opts = {}) {if (e.primaryAttribute && typeof e.primaryAttribute === 'object') {const lengthProblem = primaryNameLengthProblem(e.primaryAttribute.maxLength);if (lengthProblem) errors.push(`entity ${e.schemaName}: ${lengthProblem}`);+ if (checksColumnValues) {+ const requiredProblem = requiredValueProblem(e.primaryAttribute.required);+ if (requiredProblem) columnValueFindings.push(`entity ${e.schemaName}: primaryAttribute.required ${requiredProblem}`);+ }}if (e.quickCreate !== undefined && typeof e.quickCreate !== 'boolean') {errors.push(`entity ${e.schemaName}: quickCreate must be a boolean`);@@ -2501,6 +2564,13 @@ function validateAppSpec(spec, opts = {}) {if (c.type && !TYPE_MAP[c.type]) {errors.push(`entity ${e.schemaName}: column ${c.schemaName} has unknown type '${c.type}'`);}+ // An AutoNumber column needs a format, and `required` is true, false or "recommended" (see checksColumnValues).+ if (checksColumnValues) {+ const formatProblem = autoNumberFormatProblem(c);+ if (formatProblem) columnValueFindings.push(`entity ${e.schemaName}: column ${c.schemaName} ${formatProblem}`);+ const requiredProblem = requiredValueProblem(c.required);+ if (requiredProblem) columnValueFindings.push(`entity ${e.schemaName}: column ${c.schemaName} required ${requiredProblem}`);+ }if ((c.type === 'Choice' || c.type === 'MultiChoice') && !(Array.isArray(c.options) && c.options.length) && !c.globalChoice) {errors.push(`column ${c.schemaName}: ${c.type} needs options[] or a globalChoice reference`);}@@ -4272,6 +4342,8 @@ module.exports = {validateAppSpec,PRIMARY_NAME_MAX_LENGTH,primaryNameLengthProblem,+ autoNumberFormatProblem,+ requiredValueProblem,askedPrimaryNameLength,keyNeedsNameLength,keyWaitsForNameLength,diff --git a/plugins/model-apps/scripts/lib/dashboard-tiles.js b/plugins/model-apps/scripts/lib/dashboard-tiles.jsnew file mode 100644index 000000000..35d36ba32--- /dev/null+++ b/plugins/model-apps/scripts/lib/dashboard-tiles.js@@ -0,0 +1,38 @@+'use strict';+// Which tile of a DEPLOYED dashboard a custom control hosts. One classification, shared by the download (which leaves such a tile+// out of the spec) and by verify (which does not hold it to the chart and view the spec's own tiles name), so the two cannot+// disagree about what the App Spec can describe.+//+// The SDK types a tile by its control's class, and reads a grid or a chart that a CUSTOM control hosts (the Power Apps grid, say) by+// the grid parameters it carries (`ChartGridMode`, or `indicationOfSubgrid`) — as `list` or `chart`, exactly as it does a native+// tile, with the same `TargetEntityType`, `ViewId` and `ChartGridMode`. Only its class tells them apart:+// <control id="Component1" classid="{E7A81278-8635-4d9e-8D4D-59480B391C5B}" indicationOfSubgrid="true"> native+// <control id="Component2" classid="{F9A8A302-114E-466A-B582-6771B2AE0D92}" uniqueid="{GUID}" indicationOfSubgrid="true"> hosted+// The platform writes the GUID in either case, and with its braces, so the class is compared without them and ignoring case.+//+// Documented dashboards hold charts, grids, iframes and web resources, which is all the App Spec expresses; a control of another+// class is not among them. So the download must not emit it as the plain grid or chart its parameters describe (that replaces the+// control wherever a rebuild creates the dashboard), and verify must not judge it as one (the chart and view it carries are not+// ones the spec declares, and the build never touches the tile).+//+// A component with no class at all (a hand-made one, in a test) is read as native.+// See: https://learn.microsoft.com/en-us/power-apps/developer/model-driven-apps/understand-dashboards-dashboard-components-formxml++// The control class of a native grid and chart tile, in the bare upper-case form `bareClassId` makes of any spelling.+const NATIVE_GRID_CLASS_ID = 'E7A81278-8635-4D9E-8D4D-59480B391C5B';++const bareClassId = (id) => String(id || '').replace(/[{}]/g, '').toUpperCase();++/**+ * True for a tile typed `list` or `chart` whose control is not the native grid and chart control: a grid or a chart that a custom+ * control hosts. False for a native tile, for a tile of any other type (the Assistant, an iframe, a web resource, a custom control+ * that is no grid or chart), and for a component with no class.+ * @param {{ type?: string, classId?: string } | null | undefined} component - a component of the SDK's typed dashboard+ */+function hostsCustomControl(component) {+ if (!component || (component.type !== 'chart' && component.type !== 'list')) return false;+ const classId = bareClassId(component.classId);+ return classId !== '' && classId !== NATIVE_GRID_CLASS_ID;+}++module.exports = { NATIVE_GRID_CLASS_ID, hostsCustomControl };diff --git a/plugins/model-apps/scripts/lib/entity-provision.js b/plugins/model-apps/scripts/lib/entity-provision.jsindex 458a0213b..6766164f5 100644--- a/plugins/model-apps/scripts/lib/entity-provision.js+++ b/plugins/model-apps/scripts/lib/entity-provision.js@@ -50,6 +50,8 @@ const SDK_COLUMN_TYPE = {Integer: 'integer', BigInt: 'bigint', Decimal: 'decimal', Double: 'double',File: 'file', Image: 'image', AutoNumber: 'autonumber',};+// The level a spec's `required` asks for: true, "recommended" or false (None). Those are the only values the spec gate lets through+// (requiredValueProblem, lib/app-spec.js) — it refuses the rest instead of having them read as None here.const REQUIRED = (c) => (c.required === true ? 'ApplicationRequired' : c.required === 'recommended' ? 'Recommended' : 'None');const DEFAULT_LANGUAGE_CODE = 1033;@@ -794,13 +796,29 @@ function inlineColumnsOf(buildable, { primaryName, tableLogical }) {// a plain text name column created this way 850 characters long whatever length is asked (DEFAULT_PRIMARY_NAME_LENGTH), and the// re-run that follows leaves an existing table's name column as it is. Nothing is said for an auto-numbered name column, which// keeps the length asked, or for the longest length there is (850), which the column comes out as either way.+//+// PRIMARY_COLUMN_REQUIRED_NOT_APPLIED is the same statement about a table whose name column was asked to be required+// (`primaryColumnRequired`, sent only when the spec states a `required` for that column). The create ignores the level on a plain text+// name column (measured on Dataverse 9.2.26101), so the SDK reads the level back after the create and sets it with an update; when it+// cannot confirm the level, the table exists with a name column that may not be required. The build stops and says so; the re-run finds+// the table and sets the level on the name column the way it does for any existing column with an explicit `required`.+const nameLengthMayBeIgnored = (createOpts, askedLength) => askedLength !== undefined && askedLength !== PRIMARY_NAME_MAX_LENGTH+ && !createOpts.primaryColumnAutoNumberFormat;+async function createNewTable(sdk, createOpts, { warn, askedLength } = {}) {try {return await sdk.createTable(createOpts);} catch (err) {- if (err && err.code === 'TABLE_METADATA_NOT_VISIBLE' && askedLength !== undefined && askedLength !== PRIMARY_NAME_MAX_LENGTH- && !createOpts.primaryColumnAutoNumberFormat && typeof warn === 'function') {- warn(`table ${createOpts.schemaName} was created, but its metadata could not be read back yet, so the build stops here — the spec asks for a primary name column length of ${askedLength}, which may not have been applied (some environments make a name column created this way ${PRIMARY_NAME_MAX_LENGTH} characters long), and a re-run leaves an existing table's name column as it is: after the re-run, check ${String(createOpts.primaryColumnSchemaName).toLowerCase()} in Maker and set its length there if it matters`);+ if (typeof warn === 'function') {+ const primaryLogical = String(createOpts.primaryColumnSchemaName).toLowerCase();+ if (err && err.code === 'TABLE_METADATA_NOT_VISIBLE' && nameLengthMayBeIgnored(createOpts, askedLength)) {+ warn(`table ${createOpts.schemaName} was created, but its metadata could not be read back yet, so the build stops here — the spec asks for a primary name column length of ${askedLength}, which may not have been applied (some environments make a name column created this way ${PRIMARY_NAME_MAX_LENGTH} characters long), and a re-run leaves an existing table's name column as it is: after the re-run, check ${primaryLogical} in Maker and set its length there if it matters`);+ } else if (err && err.code === 'PRIMARY_COLUMN_REQUIRED_NOT_APPLIED') {+ const length = nameLengthMayBeIgnored(createOpts, askedLength)+ ? `; the spec also asks for a name column length of ${askedLength}, which may not have been applied either (some environments make a name column created this way ${PRIMARY_NAME_MAX_LENGTH} characters long) and a re-run leaves an existing table's name column length as it is: after the re-run, check it in Maker and set it there if it matters`+ : '';+ warn(`table ${createOpts.schemaName} was created, but the required level (${createOpts.primaryColumnRequired}) of its primary name column ${primaryLogical} could not be confirmed, so the build stops here — the table exists: run the build again, which finds it, does not create it again, and sets that level on the column${length}`);+ }}throw err;}@@ -1014,7 +1032,9 @@ function isVisualizationUnsupported(err) {}function hasExplicitRequired(c) {- return c && Object.prototype.hasOwnProperty.call(c, 'required');+ // `undefined` states nothing, like a missing key — validateAppSpec reads it that way (requiredValueProblem). A bare own-property test took it for an+ // explicit None, which on an existing column writes None over a level a maker set. JSON cannot carry an undefined; a spec built in code can.+ return !!c && c.required !== undefined;}function requiredLevelValue(raw) {@@ -1324,7 +1344,23 @@ const RESET_WORKSPACE = 'stop any other build or teardown using the .maker-works// capture forms, views or charts, and the artifact may predate the app (an interrupted FIRST build leaves// views and forms before the app exists). Both codes are pinned against the real bundle in// workspace-projection-real-bundle.test.js.+//+// PRIMARY_COLUMN_REQUIRED_NOT_APPLIED: the table WAS created, but the required level asked of its name column could not be confirmed, and the+// message ends with "Do NOT re-run the create" and the SDK call that sets the level. Running this build again is the fix: it finds the table (it+// is not created twice) and sets the level the way it does for any existing column with an explicit `required`.+//+// ROW_SUMMARY_TEMPLATE_NOT_FOUND: the SDK found no row-summary AI template. The build skips the summaries only for an org that really has none, so it+// reads the template list itself before it does (sdk-build.js, confirmNoTemplate). When that read FAILED, its failure is the cause the build kept+// beneath the SDK's error (the SDK's error has no cause of its own), and this says so: the SDK's words alone read as if the org had been found to have+// no template, when the build could not find out. No step is named: whether a run again helps is the failure's to say (a throttle, an unavailable service+// or a reset connection is run again by the build itself; a refusal is not), not this text's.function operatorRemedy(err) {+ if (err && err.code === 'PRIMARY_COLUMN_REQUIRED_NOT_APPLIED') {+ return ' — the table exists. Run the build again: it finds the table, does not create it again, and sets the required level of its primary name column (the call the message names is made for you).';+ }+ if (err && err.code === 'ROW_SUMMARY_TEMPLATE_NOT_FOUND' && err.cause && typeof err.cause === 'object') {+ return ` — the build then read the template list itself, to confirm that before skipping the row summaries, and that read failed (${err.cause.message || err.cause.code || 'no reason was given'}), so they were not skipped.`;+ }if (err && err.code === 'ARTIFACT_PROJECTION_STALE') {return ` — the workspace copy was saved by an earlier version of this plugin and still holds edits no build pushed (an interrupted build, say). To reset it, ${RESET_WORKSPACE}, and re-run: the build re-reads the copies and re-applies every edit from the spec.`;}@@ -1858,6 +1894,12 @@ async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, laprimaryColumnMaxLength: primaryNameLength(e.primaryAttribute) };// AutoNumber the primary/title column when requested (the order number IS the identity).if (e.primaryAttribute.autoNumberFormat) createOpts.primaryColumnAutoNumberFormat = e.primaryAttribute.autoNumberFormat;+ // The name column's requirement level, when the spec states one (an omitted `required` sends nothing, as before). The create alone+ // does not keep it on a plain text name column (measured on Dataverse 9.2.26101: stored not required whatever is sent, while an+ // auto-numbered one keeps it), so the SDK reads the level back after the create, sets it with one update where it differs, reads it+ // again and answers it as `primaryColumnRequired`; a level it cannot confirm is PRIMARY_COLUMN_REQUIRED_NOT_APPLIED (createNewTable).+ // The update is a PUT, which the SDK refuses to leave unmade: without one on the HTTP client it refuses before it creates anything.+ if (hasExplicitRequired(e.primaryAttribute)) createOpts.primaryColumnRequired = REQUIRED(e.primaryAttribute);// 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);@@ -1866,6 +1908,9 @@ async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, laresult.entities[e.schemaName] = { logicalName: (t.logicalName || logical), entitySetName: t.entitySetName, metadataId: t.metadataId };createdTable = t;} catch (err) {+ // The SDK says of this refusal that the table WAS created. What its cause carries — a 409 from the update, a word in the platform's reason —+ // is no sign that the table's name is taken, so it is never taken for an already-exists answer and "rediscovered".+ if (err && err.code === 'PRIMARY_COLUMN_REQUIRED_NOT_APPLIED') throw err;if (!isAlreadyExists(err)) throw err;// First POST likely succeeded server-side; a transient-network retry hit "already exists".// Rediscover to capture entitySetName (required by later phases). No poisoning concern@@ -2037,9 +2082,26 @@ async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, la});}for (const c of requiredDeclared) {- if (!existingTable || !existingCols.has(c.schemaName.toLowerCase())) {- runner.skip('data-model', `required ${e.schemaName}.${c.schemaName} (applied on create)`);+ if (existingTable && existingCols.has(c.schemaName.toLowerCase())) continue;+ // A column's level is part of its own create request — except the primary name column's: it is asked in the table's create, which+ // does not keep it on a plain text name column, so a level other than None is applied only when the SDK says it read the level back+ // (`primaryColumnRequired`). None has nothing to read back, so what shows it is the create itself — one this build saw succeed. A table+ // the build did not see made (found after its create, the answer being lost, or existing with columns that could not be read) shows+ // nothing about the level, None included: a maker may have set Business Required there. Neither that nor an SDK that answers nothing is+ // reported as applied; the re-run reconciles the level as it does an existing column's. Nothing is written blind.+ const desired = REQUIRED(c);+ if (c === e.primaryAttribute && !(createdTable && (desired === 'None' || createdTable.primaryColumnRequired === desired))) {+ const confirmed = createdTable && createdTable.primaryColumnRequired;+ const why = createdTable+ ? `the SDK confirmed ${confirmed ? `'${confirmed}'` : 'no level'} for the name column of the table it created`+ : existingTable+ ? 'the table exists but its columns could not be read, so its current level is unknown'+ : 'the table was found after its create, so nothing shows that the level was applied';+ await runBestEffort(runner, 'data-model', `required ${e.schemaName}.${c.schemaName} -> ${desired}`, async () => { throw refusal(why); },+ warn, `could not confirm the required level of ${logical}.${String(c.schemaName).toLowerCase()} (${desired}) — a re-run sets it, and the rest of the build continues`);+ continue;}+ runner.skip('data-model', `required ${e.schemaName}.${c.schemaName} (applied on create)`);}for (const c of capabilityDeclared) {if (!existingTable || !existingCols.has(c.schemaName.toLowerCase())) {diff --git a/plugins/model-apps/scripts/lib/form-order.js b/plugins/model-apps/scripts/lib/form-order.jsindex 6d89e48c5..10f1bd4d6 100644--- a/plugins/model-apps/scripts/lib/form-order.js+++ b/plugins/model-apps/scripts/lib/form-order.js@@ -11,10 +11,13 @@// function returns (the forms a given user may open, first to last);// - moving `systemform.isdefault` to another form did not reorder it;// - forms with an EQUAL `Order` are put in an order the platform chooses, which `isdefault` does not-// decide: three new forms, all at the `Order="0"` a new form carries, were served with the-// `isdefault` form LAST — so a table whose Main forms the build had just created did NOT open with+// decide: three new forms, all at the `Order="0"` the SDK then gave every new form, were served with+// the `isdefault` form LAST — so a table whose Main forms the build had just created did NOT open with// the form the build marked as the default;// - a form with no <DisplayConditions> at all is served after every form that has one.+// A form the SDK creates carries `<DisplayConditions FallbackForm="true"><Everyone />` with NO `Order`,+// so it takes no slot in the order Maker lists; the build therefore writes the place of every form it+// orders, the first of a table included, and puts a new form it does not order after the table's others.// So the order is plain formxml, written through the same supported call that sets a form's security// roles (the SDK's setFormSecurityRoles) — the private messages behind Maker's "Form order" dialog are// not needed. What a user actually opens also depends on two things this module does not control: the@@ -98,7 +101,8 @@ function ordersByHand(spec, entityLogical) {/*** The spec's Main forms of a table in the order the build gives them, first to last, or null when the* build orders none of them. `current` maps a form entry to its stored `Order` (a number, or undefined- * when the form has no <DisplayConditions>).+ * when the form has none: no <DisplayConditions> at all, or one without the attribute, as on a form the+ * SDK has just created).** The forms `mainFormOrder` lists come first, in that order; without a list, the default form alone* comes first. The spec's other Main forms follow in their CURRENT relative order (ties, and forms with@@ -129,6 +133,8 @@ function plannedMainFormSequence(spec, entityLogical, current = new Map()) {* <DisplayConditions Order="0" FallbackForm="true"><Everyone /></DisplayConditions>* <DisplayConditions FallbackForm="true" Order="3"><Everyone /></DisplayConditions>* <DisplayConditions Order="2" FallbackForm="false"><Role Id="{GUID}" /></DisplayConditions>+ * <DisplayConditions FallbackForm="true"><Everyone /></DisplayConditions>+ * The last is what the SDK gives a form it creates: present, with no `Order`.* Attribute order varies, so `Order` is read by name from the start tag (which may also be* self-closing). `order` is undefined when the attribute is absent or is not an integer.*/diff --git a/plugins/model-apps/scripts/lib/provision-input.js b/plugins/model-apps/scripts/lib/provision-input.jsindex 370f6482f..583865540 100644--- a/plugins/model-apps/scripts/lib/provision-input.js+++ b/plugins/model-apps/scripts/lib/provision-input.js@@ -5,7 +5,7 @@// App-Spec subset: { solution, entities, relationships, globalChoices?, sampleData? }.// Entities carry FULL schema names (e.g. cr_candidate), not bare suffixes.-const { TYPE_MAP, normalizeLanguageCode, validateLabel, validateChoiceOptionLabels, isLocalizedLabelMap, labelIsMissing, rejectLocalizedGlobalChoice, validateSampleDataRows, ENTITY_KEYS, ENTITY_KEY_HINTS, invalidLanguageCodeMessage, relationshipNameCollisions, relationshipCollisionMessage, primaryNameLengthProblem } = require('./app-spec.js');+const { TYPE_MAP, normalizeLanguageCode, validateLabel, validateChoiceOptionLabels, isLocalizedLabelMap, labelIsMissing, rejectLocalizedGlobalChoice, validateSampleDataRows, ENTITY_KEYS, ENTITY_KEY_HINTS, invalidLanguageCodeMessage, relationshipNameCollisions, relationshipCollisionMessage, primaryNameLengthProblem, autoNumberFormatProblem, requiredValueProblem } = require('./app-spec.js');// Validates provision-entities input. Returns { ok, errors }.function validateProvisionInput(input) {@@ -138,6 +138,10 @@ function validateProvisionInput(input) {if (e.primaryAttribute && typeof e.primaryAttribute === 'object') {const lengthProblem = primaryNameLengthProblem(e.primaryAttribute.maxLength);if (lengthProblem) errors.push(`entity '${e.schemaName}': ${lengthProblem}`);+ // A `required` that is not true, false or "recommended" is read by the build as "not required" — and written over an existing column's level —+ // so it is refused at the gate, by the one rule validateAppSpec applies.+ const requiredProblem = requiredValueProblem(e.primaryAttribute.required);+ if (requiredProblem) errors.push(`entity '${e.schemaName}': primaryAttribute.required ${requiredProblem}`);}// Validate columns@@ -162,6 +166,13 @@ function validateProvisionInput(input) {}validateLabel(c.displayName, `entity '${e.schemaName}': column '${c.schemaName || ''}' displayName`, errors, { baseLanguageCode: input.languageCode });validateChoiceOptionLabels(c.options, `entity '${e.schemaName}': column '${c.schemaName || ''}'`, errors, { baseLanguageCode: input.languageCode });+ // The two column rules a build depends on, which validateAppSpec applies from the same functions: an AutoNumber column needs a format (the SDK+ // refuses to create one without — after the solution and the tables are written, where this gate stops it before the first write), and `required`+ // is true, false or "recommended".+ const formatProblem = autoNumberFormatProblem(c);+ if (formatProblem) errors.push(`entity '${e.schemaName}': column '${c.schemaName || ''}' ${formatProblem}`);+ const requiredProblem = requiredValueProblem(c.required);+ if (requiredProblem) errors.push(`entity '${e.schemaName}': column '${c.schemaName || ''}' required ${requiredProblem}`);}}diff --git a/plugins/model-apps/scripts/lib/sdk-build.js b/plugins/model-apps/scripts/lib/sdk-build.jsindex acdfea730..da07d8009 100644--- a/plugins/model-apps/scripts/lib/sdk-build.js+++ b/plugins/model-apps/scripts/lib/sdk-build.js@@ -4869,11 +4869,13 @@ async function runSdkBuildPhases(spec, opts, owed) {//// Only forms the spec declares are ever written. Where the spec orders the table — `mainFormOrder`,// an explicit `isDefault`, or any table the spec owns — its Main forms get Order 0..n-1 in the- // planned order, skipping any already in place. Elsewhere the order belongs to the environment, and- // the build touches it only to put a Main form it CREATED in this run after the table's other Main- // forms: a new form carries Order 0, so it would otherwise tie with the form everyone opens today —- // or, on a table whose forms carry no order at all, displace it. A table the author orders by hand- // (`securityRoles.order`) is left alone entirely.+ // planned order, skipping any already in place (a form the SDK just created has no Order, so it is+ // always written, the first of a table included). Elsewhere the order belongs to the+ // environment, and the build touches it only to put a Main form it CREATED in this run after the+ // table's other Main forms: a new form carries no Order, and where the platform serves a form with+ // none is not the build's choice, so it could come ahead of the form everyone opens today. (On a+ // table whose forms carry no order at all there is nothing to follow: it comes first, and the build+ // says so.) A table the author orders by hand (`securityRoles.order`) is left alone entirely.//// Best-effort like the promotion above: a failed read or write is reported (✗ and a warning) and// `--verify` fails on the order it reads back, but the build goes on.@@ -4982,9 +4984,9 @@ async function runSdkBuildPhases(spec, opts, owed) {// AB#6736948 — a Main form the build CREATES on a table whose order it does not set is created already// after the table's other Main forms. Its order is written into the new form's own <DisplayConditions>- // (the SDK gives every new form one, at Order 0, in its root bag) BEFORE the first push, so the order is- // part of the create: no interrupted run and no later failure can leave the form at Order 0, which can- // put it ahead of the form the table opens with. A separate write after the create, as first tried,+ // (the SDK gives every new form one, with no Order, in its root bag) BEFORE the first push, so the order+ // is part of the create: no interrupted run and no later failure can leave the form without one, which+ // can put it ahead of the form the table opens with. A separate write after the create, as first tried,// left exactly that on any failure between the two — and a later build cannot tell the form is new.//// The place is (highest order among the table's other Main forms) + 1 + (the form's index among the@@ -5016,9 +5018,9 @@ async function runSdkBuildPhases(spec, opts, owed) {const order = snapshot.error ? APPEND_FALLBACK_ORDER + idx : snapshot.base + 1 + idx;// The root bag of a new form, as the SDK builds it (abridged):// { "c": [ { "i": 1, "node": { "n": "header", … } }, { "i": 2, "node": { "n": "footer", … } },- // { "i": 3, "node": { "n": "DisplayConditions", "a": [["Order", "0"], ["FallbackForm", "true"]],+ // { "i": 3, "node": { "n": "DisplayConditions", "a": [["FallbackForm", "true"]],// "c": [{ "n": "Everyone", "a": [], "c": [] }] } } ] }- // Only the Order attribute changes; the node is replaced whole through the generic surface, as the+ // Only the Order attribute is added; the node is replaced whole through the generic surface, as the// form-events region is (wireFormEvents).const art = await provision.getArtifact('form', formId);const bag = (art && art.bag && Array.isArray(art.bag.c)) ? art.bag.c : [];@@ -5026,6 +5028,8 @@ async function runSdkBuildPhases(spec, opts, owed) {if (at < 0) return;const entry = JSON.parse(JSON.stringify(bag[at]));const attrs = Array.isArray(entry.node.a) ? entry.node.a : [];+ // The SDK gives a new form no Order, so it is added first, as Maker's own file has it. A node that already+ // carries one (an earlier SDK gave every new form Order "0") has it replaced, not repeated.const has = attrs.some((p) => Array.isArray(p) && p[0] === 'Order');entry.node.a = has ? attrs.map((p) => (Array.isArray(p) && p[0] === 'Order' ? ['Order', String(order)] : p)) : [['Order', String(order)], ...attrs];await provision.updateElement('form', formId, `/bag/c/${at}`, entry);@@ -7136,7 +7140,38 @@ async function runSdkBuildPhases(spec, opts, owed) {summaryOverrides.set(String(key).toLowerCase(), val);}const DUPLICATE_MODEL_REASON = 'a model with this name already exists';+ // An org without the AI template a row summary is built from. The SDK reads the template before its first write and refuses with its own+ // code (`configureRowSummary`: ROW_SUMMARY_TEMPLATE_NOT_FOUND, "Nothing was written"), where it used to publish a model that named no template and let the+ // platform answer. It is the same kind of environment gate as the licence refusal below — nothing in the spec can fix it — so it skips the same way.+ const NO_TEMPLATE_REASON = 'no row-summary AI template in this environment';+ // The code alone does not prove that the org has no template, though. The SDK's lookup is+ // GET /msdyn_aitemplates?$select=msdyn_aitemplateid&$filter=msdyn_uniquename eq 'GptPowerPrompt'&$top=1 -> { "value": [ { "msdyn_aitemplateid": "<guid>" } ] }+ // and it raises the code whenever the FIRST row has no `msdyn_aitemplateid`, without checking that there is a row: `{ "value": [] }`, `{ "value": [ {} ] }` and+ // `{ "value": [ null ] }` all raise it. Only the empty list says the org has no template; the other two are answers that cannot be read, and an answer that cannot be+ // read stops the build (as it did before the skip) instead of passing for an environment gate. So the first time the code is seen, the build asks the same question+ // through `queryRecords` — which refuses an answer without its `value` array — and skips only on an empty list. Rows, a row that is no row and a read that fails leave+ // the SDK's own error to stop the build. The verdict is kept: every table's lookup is the same question, so one read settles the whole build.+ // This mirrors the SDK's lookup (its template name, its select) and can go once the SDK raises the code for an empty list only and answers a malformed first row with a+ // ConnectionError. If the SDK ever looks for another template, this read can only fail to confirm, which stops the build: the safe side.+ // `msdyn_aitemplate` is the table behind the SDK's `/msdyn_aitemplates` set:+ // https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/msdyn_aitemplate+ // The verdict is `{ absent }` — true only for an empty list — and, when the read itself failed, `{ absent: false, failure }`, what it threw. The read is two requests, the first time:+ // the one that names the template table's set (the SDK looks it up once and keeps it) and the one that reads the list; either can fail.+ const ROW_SUMMARY_TEMPLATE_NAME = 'GptPowerPrompt';+ let templateVerdict;+ const confirmNoTemplate = async () => {+ if (templateVerdict === undefined) {+ try {+ const rows = await provision.queryRecords('msdyn_aitemplate', { select: ['msdyn_aitemplateid'], filter: `msdyn_uniquename eq '${ROW_SUMMARY_TEMPLATE_NAME}'`, top: 1 });+ templateVerdict = { absent: Array.isArray(rows) && rows.length === 0 };+ } catch (failure) {+ templateVerdict = { absent: false, failure };+ }+ }+ return templateVerdict;+ };const aiSummaryUnsupported = (err) => {+ if (err && err.code === 'ROW_SUMMARY_TEMPLATE_NOT_FOUND') return templateVerdict && templateVerdict.absent ? NO_TEMPLATE_REASON : false;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@@ -7187,7 +7222,25 @@ async function runSdkBuildPhases(spec, opts, owed) {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 });+ let res;+ try {+ res = await provision.configureRowSummary(promptSpec, { solutionUniqueName });+ } catch (err) {+ // `skipIf` is synchronous, so the read that confirms the template is absent is made here, before the error reaches it. The error is never replaced: when the+ // read does not confirm it, it stops the build as it is — the SDK's own error, whole, as the halt's own cause.+ if (err && err.code === 'ROW_SUMMARY_TEMPLATE_NOT_FOUND') {+ const { failure } = await confirmNoTemplate();+ // A read that FAILED is kept beneath the SDK's error. The runner decides from the chain of causes whether the build may run this attempt again (lib/retry-policy.js, judgeFailure): a throttle, an+ // unavailable service or a reset connection that stopped the read has to be on that chain, or the halt is final whatever the read failed with — and the halt's text says that the read failed, and why+ // (operatorRemedy). It is only a failure of the SERVICE that makes the halt transient: a missing template on its own, and a read that answered, however wrongly, stay final. The SDK's error has no+ // cause of its own, so the one it has here is this one. `withCause` is the link a result carries for the same reason (a failure reported by value); an error that cannot take it (a frozen one)+ // stops the build as it did before, final.+ if (failure !== undefined) {+ try { withCause(err, failure); } catch { /* nothing to carry it on */ }+ }+ }+ throw err;+ }result.created.ai.summaries[logical] = res;return res.modelId;}, {@@ -7195,14 +7248,19 @@ async function runSdkBuildPhases(spec, opts, owed) {const reason = aiSummaryUnsupported(err);if (!reason) return false;result.skipped.aiSummaries.push(logical);- pendingAiSummaryReports.push(logical);+ // Nothing was written for a table the SDK refused before its first write, so there is no model to look for.+ if (reason !== NO_TEMPLATE_REASON) pendingAiSummaryReports.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'). Same-name models are kept because this attempt returned no created-model id. Review the reported ids before any separate cleanup. 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.`);+ if (reason === DUPLICATE_MODEL_REASON) {+ opts.warn(`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'). Same-name models are kept because this attempt returned no created-model id. Review the reported ids before any separate cleanup. Everything else in the app was built normally.`);+ } else if (reason === NO_TEMPLATE_REASON) {+ opts.warn(`AI row summaries were NOT created: this environment has no 'GptPowerPrompt' AI template, which a row summary is built from (AI Builder provides it), so none can be authored here, and nothing was written for them. Everything else in the app was built normally. Re-run once the environment has the template, or set ai.summaries.default to "off" (with no per-table enabled:true) to stop requesting them.`);+ } else {+ opts.warn(`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;},diff --git a/plugins/model-apps/scripts/lib/sdk-teardown.js b/plugins/model-apps/scripts/lib/sdk-teardown.jsindex b82ae88f7..afa1cacf9 100644--- a/plugins/model-apps/scripts/lib/sdk-teardown.js+++ b/plugins/model-apps/scripts/lib/sdk-teardown.js@@ -45,7 +45,11 @@// does NOT cascade forms/views/charts/relationships when cross-references exist// (e.g. a form subgrid references another table's view), so teardown deletes// them explicitly first. A table whose business rule could not be deleted (step 3b)-// is KEPT — reported as a `(kept — …)` skip — until a re-run deletes the rule.+// is KEPT — reported as a `(kept — …)` skip — until a re-run deletes the rule. What only+// that table's existence blocks is kept with it, each as a `(kept — …)` skip naming the+// table: its icon web resource (step 9), a global choice one of its columns binds (step 10)+// and a relationship from the table to itself (planned after the tables). The platform refuses the+// first two while the table exists, the third while its lookup is still referenced (one more failure).// 9. web-resources — webresourceset rows (form/command JS, table-icon SVG/raster images, and the// build's generated default app icon) — deleted AFTER tables: a table's icon// web resource is referenced by the TABLE itself, so it can't be removed until@@ -1118,15 +1122,34 @@ const KIND_HANDLERS = {},aiSummary: {// AI row-summary records reference the table and would block its delete; remove them first.- // removeRowSummary is a no-op when the record is absent, so this is safe/idempotent.+ //+ // The SDK's removeRowSummary answers nothing, both when it removes a row summary and when it finds none to remove: it looks up the+ // skill row `ais_RowSummary_<table>` and returns at once without one. A step that only called it reported `(1 deleted)` for every+ // table that had no row summary. So the step looks first, with the SDK's own request (`GET /aiskillconfigs?…$filter=uniquename eq '…'`,+ // which teardown-row-summary-lookup.test.js holds to what the real bundle asks for), and a table with none is "not found" like any+ // other step's. The request is the SDK's own, so a lookup that fails is one the removal would fail too: 404 means the environment has+ // no such table (so no row summary), and any other answer leaves what is there unknown, which the step says rather than guesses.async resolve(sdk, target) {- return [{ id: target.entityLogicalName, entityLogicalName: target.entityLogicalName }];- },- async del(sdk, item) {- if (sdk.removeRowSummary) {- try { await sdk.removeRowSummary({ entityLogicalName: item.entityLogicalName }); } catch { /* best-effort */ }+ const name = `ais_RowSummary_${target.entityLogicalName}`;+ let res;+ try {+ res = await sdk.dataverse.get(`/aiskillconfigs?$select=aiskillconfigid&$filter=uniquename eq '${odataStr(name)}'&$top=1`);+ } catch (err) {+ if (isNotFound(err)) return [];+ return { items: [], skipReason: `not looked up — ${errMsg(err)}; a row summary left behind is reported by the table's delete` };}+ if (res && res.status === 404) return [];+ const rows = res && res.body && res.body.value;+ const unknown = (why) => ({ items: [], skipReason: `not looked up — ${why}; a row summary left behind is reported by the table's delete` });+ if (!res || res.status < 200 || res.status >= 300) return unknown(`the lookup answered ${res && res.status ? `HTTP ${res.status}` : 'nothing'}`);+ if (!Array.isArray(rows)) return unknown('the lookup\'s answer was no list');+ return rows.length ? [{ id: target.entityLogicalName, entityLogicalName: target.entityLogicalName }] : [];},+ del: (sdk, item) => sdk.removeRowSummary({ entityLogicalName: item.entityLogicalName }),+ // Best-effort by design: a removal that fails does not fail the teardown — the table's delete that follows reports the dependency if the+ // skill row is still there. But it is not a deletion either, so it is said on the step's line, in the SDK's own words (a model it could+ // not delete, a skill row it could not confirm gone), where it used to be swallowed and reported as `(1 deleted)`.+ tolerateFailure: (err) => errMsg(err),},solution: {async resolve(sdk, target) {@@ -1145,6 +1168,47 @@ const KIND_HANDLERS = {},};+// Which tables the SPEC says hold a web resource or a global choice. While one of them exists the platform refuses to delete either+// ("The <type>(<id>) component cannot be deleted because it is referenced by N other components" — a component is not deleted while+// another depends on it, https://learn.microsoft.com/en-us/power-platform/alm/dependency-tracking-solution-components). It matters only+// for a table this run KEEPS (runTeardownSteps, `keptTables`); a table that is deleted takes its references with it. Read the way the+// build acted on the spec, so that it names no more than the build made:+// * an ICON: `entities[].vectorIcon` (an SVG web resource) and `entities[].icon` (a raster one), which the build sets on the table+// with setEntityIcon once the web resource exists. It checks the name lower-cased (`builtWrNames`, sdk-build.js), as the spec+// validator does — a web resource's name is not case-sensitive, so neither is this match.+// * a GLOBAL CHOICE a column binds: only a Choice or MultiChoice column does, and the build looks the choice up by the EXACT name the+// column gives (`globalChoiceIds[c.globalChoice]`, entity-provision.js columnOptions). A column that spells it in another letter+// case was never bound — it got inline options of its own — so it holds nothing here.+// Only the spec is read: an icon or a binding made by hand in the environment is not in it, and nothing here can know of it.+// Returns { icons, choices }: lower-cased web resource name -> holders, global choice name -> holders, each holder `{ table, by }`+// with the table's lower-cased logical name, once per table.+function tablesHolding(spec) {+ const icons = new Map();+ const choices = new Map();+ const add = (holders, key, table, by) => {+ const held = holders.get(key) || [];+ if (!held.some((h) => h.table === table)) holders.set(key, [...held, { table, by }]);+ };+ for (const e of spec.entities || []) {+ const table = String(e.schemaName).toLowerCase();+ for (const icon of [e.vectorIcon, e.icon]) {+ if (typeof icon === 'string' && icon) add(icons, icon.toLowerCase(), table, 'icon');+ }+ for (const c of e.columns || []) {+ if (c && (c.type === 'Choice' || c.type === 'MultiChoice') && typeof c.globalChoice === 'string' && c.globalChoice) add(choices, c.globalChoice, table, 'column');+ }+ }+ return { icons, choices };+}++// How a step is held, for the `(kept — …)` line of a step that waits for a table this run keeps. `table` is the name the table's own+// step reports.+const HELD_BY = {+ icon: (table) => `it is the icon of table ${table}`,+ column: (table) => `a column of table ${table} binds it`,+ itself: (table) => `it relates table ${table} to itself`,+};+// Build the ordered teardown plan from an App Spec. Pure — no I/O. Each step names exactly one// artifact target (resolved live at execution time). Steps whose spec section is absent are// simply omitted, so a partial spec tears down only what it declares.@@ -1311,6 +1375,9 @@ function planTeardown(spec) {// forms it cannot prove it authored — stripping a lookup out of somebody's main form is a worse// outcome than leaving a lookup on a table they already own.if (r.type === 'OneToMany' && String(r.referenced || '').toLowerCase() === String(r.referencing || '').toLowerCase()) {+ // Held by its own table for as long as that table exists — the reason it is deferred. A table this run KEEPS (see+ // `keptTables` in runTeardownSteps) keeps it too: the refused delete would be one more reported failure, not a deletion.+ step.heldBy = [{ table: String(r.referenced).toLowerCase(), by: 'itself' }];selfRefRelSteps.push(step);continue;}@@ -1376,6 +1443,9 @@ function planTeardown(spec) {// while the table still exists, so it must come after the tables phase.const declaredWrNames = new Set((spec.webResources || []).map((w) => w && w.name && String(w.name).toLowerCase()).filter(Boolean));+ // `heldBy` on a web resource or global choice step names the tables whose existence blocks its delete (see tablesHolding); a step+ // nothing holds carries none, so every other step is exactly what it was.+ const { icons: iconHolders, choices: choiceHolders } = tablesHolding(spec);for (const wr of spec.webResources || []) {// `external:true` marks a web resource this app merely REFERENCES (a re-declared path/`$webresource`// nav icon whose ownership can't be proven exclusive — see download-model-app iconWebResources). The@@ -1383,7 +1453,8 @@ function planTeardown(spec) {// would break there (fail-safe — an orphan is recoverable, a deleted shared resource is not; same// posture as the `existing:true` protection on downloaded tables). Skip it.if (wr.external === true) continue;- steps.push({ kind: 'webResource', phase: 'web-resources', label: `web resource ${wr.name}`, target: { name: wr.name } });+ const heldBy = iconHolders.get(String(wr.name).toLowerCase());+ steps.push({ kind: 'webResource', phase: 'web-resources', label: `web resource ${wr.name}`, target: { name: wr.name }, ...(heldBy ? { heldBy } : {}) });}// The build generates a default app icon web resource (`<appUnique>_icon`) in the solution when// the spec sets no explicit app.icon; it is referenced by the app module (deleted first), so it@@ -1414,8 +1485,10 @@ function planTeardown(spec) {}// Global option sets last (before the solution container): every column that bound one lives// on a table deleted above, so the shared choice now has no dependents blocking its delete.+ // (A table this run keeps still has its columns — `heldBy`, see tablesHolding.)for (const gc of spec.globalChoices || []) {- steps.push({ kind: 'globalChoice', phase: 'global-choices', label: `global choice ${gc.name}`, target: { name: gc.name, existing: gc.existing === true } });+ const heldBy = choiceHolders.get(gc.name);+ steps.push({ kind: 'globalChoice', phase: 'global-choices', label: `global choice ${gc.name}`, target: { name: gc.name, existing: gc.existing === true }, ...(heldBy ? { heldBy } : {}) });}if (spec.solution) {steps.push({ kind: 'solution', phase: 'solution', label: `solution ${spec.solution.uniqueName}`, target: { uniqueName: spec.solution.uniqueName } });@@ -1435,6 +1508,7 @@ function planTeardown(spec) {//// Reporting both as "undeletable" would send an operator hunting a platform problem that isn't// there. `skippedIds` is retained as the union of both for callers that only need the count.+// A third reason, `failed` (with a `detail`), is a removal the handler tolerates (`tolerateFailure`).// A not-found error counts as already-gone. Throws only on a genuine failure.async function deleteStep(sdk, handler, items, ctx) {const deletedIds = [];@@ -1478,6 +1552,11 @@ async function deleteStep(sdk, handler, items, ctx) {skipped.push({ id: item.id, reason: 'undeletable' });continue;}+ if (typeof handler.tolerateFailure === 'function') {+ // A step that is best-effort by design (aiSummary): not a failure of the teardown, and not a deletion either. The reason is the handler's words.+ skipped.push({ id: item.id, reason: 'failed', detail: handler.tolerateFailure(err) });+ continue;+ }throw err;}}@@ -1596,15 +1675,20 @@ async function runTeardownSteps(spec, opts, deps, deferredResetPublishes) {// there for good, because an answer that says "not found" reads as "already gone" (to the read of the// rule's rows and to the copy's delete alike). Of every step that follows a failed rule, dropping its// table is the only one that turns a failure a re-run could finish into a permanent leftover, so it alone- // waits. The solution is already kept after any failure; a table icon's web resource or a global choice- // that the kept table still references is refused by the platform's own dependency check, as it is for- // any retained table, and that is one more reported failure, not a leftover.+ // waits. The solution is already kept after any failure. What only the kept table's existence blocks — its+ // icon web resource, a global choice one of its columns binds, a relationship from the table to itself — is+ // kept with it (`keptTables`, below), reported as a `(kept — …)` skip: the platform refuses the first two while+ // the table exists and the third while its lookup is still referenced — one more reported failure each, not a leftover.//// Keyed by the table's lower-cased logical name, as the rule step's target names it; the value is the// names of the rules that failed on it. ANY failure of the rule step counts — an unreadable rule, the// definition's delete or the copy's — because each can leave a copy behind. Nothing re-sends the failed// delete: a 500 does not prove the delete did not run, and this plugin sends a delete once.const failedRulesByTable = new Map();+ // The tables this run actually kept for a failed rule: lower-cased logical name -> the name the table's own step reports. Filled by+ // that step, which comes before every step it can hold (the plan's `heldBy`: web resources, global choices and relationships to+ // themselves all follow the tables). What the platform would refuse while such a table exists is not sent.+ const keptTables = new Map();let n = 0;for (const step of plan) {const myN = (n += 1);@@ -1675,11 +1759,24 @@ async function runTeardownSteps(spec, opts, deps, deferredResetPublishes) {// reported as kept for a rule's sake.const failedRules = step.kind === 'table' ? failedRulesByTable.get(String(step.target.logical).toLowerCase()) : undefined;if (failedRules) {+ keptTables.set(String(step.target.logical).toLowerCase(), step.target.schemaName);const why = `${step.label} (kept — business rule(s) on it could not be deleted (${failedRules.map((name) => JSON.stringify(String(name))).join(', ')}), and once the table is gone a rule's activated copy can never be deleted; a re-run deletes the rule(s) first, then the table)`;result.skipped.push(why);emit({ phase: step.phase, status: 'skip', skip: 'kept', label: why, n: myN, total });continue;}+ // What only a kept table's existence blocks waits with it: the platform refuses these deletes while the table exists, so sending+ // them would report a refusal as one more failure beside the rule's (see keptTables). Asked AFTER the resolve, like the table's+ // own keep: a step that found nothing, or was retained for its own reason (an `existing: true` choice or relationship), reports+ // that, as before. Only a table kept for a rule counts — what hangs on a reused or system table is sent as it always was.+ const holders = (step.heldBy || []).filter((h) => keptTables.has(h.table));+ if (holders.length) {+ const many = holders.length > 1;+ const why = `${step.label} (kept — ${holders.map((h) => HELD_BY[h.by](keptTables.get(h.table))).join('; ')}, and ${many ? 'those tables are' : 'that table is'} kept because business rule(s) on ${many ? 'them' : 'it'} could not be deleted; a re-run deletes it once ${many ? 'they are' : 'the table is'} gone)`;+ result.skipped.push(why);+ emit({ phase: step.phase, status: 'skip', skip: 'kept', label: why, n: myN, total });+ continue;+ }const { deletedIds, skipped } = await deleteStep(sdk, handler, items, step.kind === 'resetDefaultViews' || step.kind === 'genpage' ? deferredResetPublishes : undefined);(result.deleted[step.kind] = result.deleted[step.kind] || []).push(...deletedIds);if (step.kind === 'genpage') {@@ -1696,13 +1793,22 @@ async function runTeardownSteps(spec, opts, deps, deferredResetPublishes) {// a different (possibly no) follow-up.const referenced = skipped.filter((s) => s.reason === 'referenced').length;const undeletable = skipped.filter((s) => s.reason === 'undeletable').length;+ const notRemoved = skipped.filter((s) => s.reason === 'failed');const parts = [];if (keptLabels.length) parts.push(`${keptLabels.length} kept: ${keptLabels.join('; ')}`);if (undeletable) parts.push(`${undeletable} undeletable`);if (referenced) parts.push(`${referenced} still referenced`);+ if (notRemoved.length) parts.push(`${notRemoved.length} not removed: ${notRemoved.map((s) => s.detail).join('; ')}`);if (parts.length) {result.skipped.push(`${step.label} (${parts.join(', ')} — skipped)`);}+ // A tolerated removal that wholly failed (`tolerateFailure`) deleted nothing, so it is not an `ok` step: the+ // closing line counts `ok` steps as deleted, and so would count a row summary that is still there. It is a+ // kept step — non-fatal, as before, but said as what it is.+ if (!deletedIds.length && notRemoved.length) {+ emit({ phase: step.phase, status: 'skip', skip: 'kept', label: `${step.label} (kept — ${parts.join(', ')})`, n: myN, total });+ continue;+ }const summary = [`${deletedIds.length} deleted`, ...parts].join(', ');emit({ phase: step.phase, status: 'ok', label: `${step.label} (${summary})`, n: myN, total });} catch (err) {diff --git a/plugins/model-apps/scripts/lib/sitemap-merge.js b/plugins/model-apps/scripts/lib/sitemap-merge.jsindex 214c2b78a..e22109a53 100644--- a/plugins/model-apps/scripts/lib/sitemap-merge.js+++ b/plugins/model-apps/scripts/lib/sitemap-merge.js@@ -102,7 +102,9 @@ const rawAttr = (node, key) => {* - a title where the live node has no `<Titles>` at all: an empty wrapper is added first in the* node (where the SDK puts a synthesized one) for the SDK to fill;* - no title where the live node has one at this language: that `<Title>` is dropped, and the other- * languages' titles are kept — the bag-less write this replaces dropped every language.+ * languages' titles are kept — the bag-less write this replaces dropped every language. Only an+ * entry whose title the spec's baseline shows the author took out ever reaches this: a node the+ * spec merely says nothing about keeps its title (adoptLiveSitemap).* Bag children are `{ i, node }` with absolute child indices (modeled children fill the gaps), so an* insertion shifts every index after it up, and a removal shifts every index after it down — or a* modeled child would fill the vacated slot ahead of the kept ones, e.g. a `<SubArea>` written before@@ -164,8 +166,21 @@ function keepsLiveValue(field, specValue, liveValue, base) {* would collide with an adopted id. `notes` lists what happened to existing nodes, for the build to* report (`node` is 'area' | 'group' | 'subArea'):* { kind: 'kept', node, target, field, live, spec } — see `baseChrome`+ * { kind: 'kept', node, target, field: 'title', live, spec: '', unspecified: true } — the spec gives+ * the node no title, so the live one stays* { kind: 'changed', node, target, field, live, spec, intended? } — the build changes this value;* `intended` when the baseline shows the spec did+ * { kind: 'replaced', node, target, live, unlabelled, empty } — an area or group with no entries whose title+ * the rebuild does not keep: the spec's `unlabelled` empty+ * nodes could not be matched one to one to the environment's+ * `empty` ones, and is written as new (see the passes below)+ *+ * A node's title the spec does not state is KEPT, never cleared. An empty label or title says nothing:+ * the download of an environment whose base language is not 1033 once wrote every one empty, and an+ * author who leaves a title out has not asked for the title to go either. The exception is an ENTRY+ * (subarea) whose title the spec's baseline shows the spec used to state — the author took it out, an+ * edit like any other, so it is applied. Areas and groups have no target to find a baseline by, so+ * theirs are always kept; state a title to change one.** `opts.baseChrome` (optional) maps a subarea target key to `{ title, icon, vectorIcon }` as the spec* last applied to — or downloaded from — this environment described it. With it, a value the spec@@ -181,6 +196,13 @@ function adoptLiveSitemap(desired, live, opts = {}) {const desiredAreas = (desired && Array.isArray(desired.areas)) ? desired.areas : [];const kids = (node, key) => (node && Array.isArray(node[key]) ? node[key] : []);const notes = [];+ // The title an adopted node is written with when the spec gives it none and the live node has one (see above): the live one, which the SDK writes back as it is. True when it was kept.+ const keepUnstatedTitle = (next, liveNode, node, target) => {+ if (text(next.title) !== '' || text(liveNode.title) === '') return false;+ next.title = liveNode.title;+ notes.push({ kind: 'kept', node, target, field: 'title', live: text(liveNode.title), spec: '', unspecified: true });+ return true;+ };// Correspondence is decided in PASSES over a whole level, never node by node in document order: a// weaker rule must not let an earlier node take a live node that a later one matches by a stronger@@ -198,7 +220,12 @@ function adoptLiveSitemap(desired, live, opts = {}) {// node with no entries to go by is recognized — but never a live node whose label an unpaired spec// node still wants, nor two nodes whose entries all differ;// 4. with no label at the SDK's language (a downloaded app titled only in another language) and no- // entries on either side, the next such live node in document order.+ // entries on either side, the next such live node in document order;+ // 5. an unlabelled node with no entries, and a live node with none that nothing above paired — what is+ // left of the empty nodes an earlier download wrote with no label, beside a live one the designer+ // gave an id of its own and a title at the SDK's language. One on each side can only be each other.+ // More than one on either side is a choice by position, which is never made: the live node is+ // replaced, and its title goes with it, so that is said (a `replaced` note).// A repeated label, or none, decides nothing by position where entries can speak. Taking the first// live "Main", or the one whose id appDef's numbering happened to repeat, or the next unlabelled one,// gave a new or reordered node another node's id and bag — with two live "Main"s and the first renamed@@ -246,7 +273,7 @@ function adoptLiveSitemap(desired, live, opts = {}) {}return tied ? null : at;};- const correspond = (want, have, targetsOfNode) => {+ const correspond = (want, have, targetsOfNode, node) => {const live = have.filter((n) => n && typeof n === 'object');const taken = new Set();const match = new Array(want.length);@@ -283,10 +310,24 @@ function adoptLiveSitemap(desired, live, opts = {}) {const l = live.find((n) => !taken.has(n) && text(n.title) === '' && !haveTargets.get(n).size);if (l) pair(i, l);});+ // An unlabelled node with no entries that pass 4 left unpaired means no live node with no entries and no title was free for it, so each live node with no entries that is still free has a+ // title at the SDK's language, and one it is dropped for takes that title with it.+ const bare = [];+ unpaired((d, i) => { if (text(d.title) === '' && !wantTargets[i].size) bare.push(i); });+ if (bare.length) {+ const left = live.filter((n) => !taken.has(n) && !haveTargets.get(n).size && !stillWanted(labelKey(n)));+ if (bare.length === 1 && left.length === 1) {+ pair(bare[0], left[0]);+ } else {+ for (const n of left) {+ if (text(n.title) !== '') notes.push({ kind: 'replaced', node, target: `${node} "${text(n.title)}"`, live: text(n.title), unlabelled: bare.length, empty: left.length });+ }+ }+ }return match;};- const areaMatch = correspond(desiredAreas, liveAreas, areaTargets);- const groupMatch = desiredAreas.map((a, ai) => correspond(kids(a, 'groups'), kids(areaMatch[ai], 'groups'), groupTargets));+ const areaMatch = correspond(desiredAreas, liveAreas, areaTargets, 'area');+ const groupMatch = desiredAreas.map((a, ai) => correspond(kids(a, 'groups'), kids(areaMatch[ai], 'groups'), groupTargets, 'group'));// Subareas correspond by navigation target: first within the live group their own group adopted (an// entry that stayed put), then anywhere (an entry that moved). Each live node is adopted at most once.@@ -314,9 +355,10 @@ function adoptLiveSitemap(desired, live, opts = {}) {if (liveArea) {nextArea.id = liveArea.id;nextArea.bag = cloneBag(liveArea.bag);- reconcileTitleChild(nextArea.bag, area.title, liveArea.title, lcid);- if (text(area.title) !== text(liveArea.title)) {- notes.push({ kind: 'changed', node: 'area', target: `area "${text(liveArea.title) || liveArea.id}"`, field: 'title', live: text(liveArea.title), spec: text(area.title) });+ keepUnstatedTitle(nextArea, liveArea, 'area', `area "${text(liveArea.title)}"`);+ reconcileTitleChild(nextArea.bag, nextArea.title, liveArea.title, lcid);+ if (text(nextArea.title) !== text(liveArea.title)) {+ notes.push({ kind: 'changed', node: 'area', target: `area "${text(liveArea.title) || liveArea.id}"`, field: 'title', live: text(liveArea.title), spec: text(nextArea.title) });}}kids(area, 'groups').forEach((group, gi) => {@@ -325,9 +367,10 @@ function adoptLiveSitemap(desired, live, opts = {}) {if (liveGroup) {nextGroup.id = liveGroup.id;nextGroup.bag = cloneBag(liveGroup.bag);- reconcileTitleChild(nextGroup.bag, group.title, liveGroup.title, lcid);- if (text(group.title) !== text(liveGroup.title)) {- notes.push({ kind: 'changed', node: 'group', target: `group "${text(liveGroup.title) || liveGroup.id}"`, field: 'title', live: text(liveGroup.title), spec: text(group.title) });+ keepUnstatedTitle(nextGroup, liveGroup, 'group', `group "${text(liveGroup.title)}"`);+ reconcileTitleChild(nextGroup.bag, nextGroup.title, liveGroup.title, lcid);+ if (text(nextGroup.title) !== text(liveGroup.title)) {+ notes.push({ kind: 'changed', node: 'group', target: `group "${text(liveGroup.title) || liveGroup.id}"`, field: 'title', live: text(liveGroup.title), spec: text(nextGroup.title) });}}kids(group, 'subAreas').forEach((sub, si) => {@@ -358,6 +401,10 @@ function adoptLiveSitemap(desired, live, opts = {}) {if (text(liveSub[f])) nextSub[f] = liveSub[f];else delete nextSub[f];notes.push({ kind: 'kept', node: 'subArea', target: `nav entry "${label}"`, field: f, live: text(liveSub[f]), spec: text(sub[f]) });+ } else if (f === 'title' && text(sub.title) === '' && !(base && text(base.title) !== '')) {+ // No title in the spec, and nothing to show the spec ever stated one: it says nothing, so the live title stays (keepUnstatedTitle). A baseline that states one+ // is the other case — the author took it out — and falls through to be applied; a baseline with none was handled above.+ keepUnstatedTitle(nextSub, liveSub, 'subArea', `nav entry "${label}"`);} else {notes.push({ kind: 'changed', node: 'subArea', target: `nav entry "${label}"`, field: f, live: text(liveSub[f]), spec: text(sub[f]), ...(base ? { intended: true } : {}) });}@@ -468,12 +515,18 @@ function describeSitemapNotes(notes) {const shown = (v) => (v ? `'${v}'` : '(none)');const lines = [];for (const n of notes || []) {- if (n.kind === 'kept') {+ if (n.kind === 'kept' && n.unspecified) {+ lines.push(`${n.target}: kept the environment's ${n.field} ${shown(n.live)} — the spec has none for it, so it is left as it is. State one in the spec to change it.`);+ } else if (n.kind === 'kept') {lines.push(`${n.target}: kept the environment's ${n.field} ${shown(n.live)} — it changed there after this spec was last applied or downloaded, and the spec still has ${shown(n.spec)}. Change the spec to change it.`);} else if (n.kind === 'changed' && n.node === 'subArea' && !n.intended) {lines.push(`${n.target}: ${n.field} changes from ${shown(n.live)} to the spec's ${shown(n.spec)}. No baseline in this spec's workspace records the entry, so a change made in the designer cannot be told from one made in the spec.`);} else if (n.kind === 'changed' && n.node !== 'subArea') {lines.push(`${n.target}: ${n.field} changes from ${shown(n.live)} to the spec's ${shown(n.spec)}.`);+ } else if (n.kind === 'replaced') {+ // A node with no entries gives nothing to tell it by, and the spec gave it no label: with more than one candidate on either side, which is which would be a guess.+ lines.push(`${n.target}: has no entries, and the spec's unlabelled empty ${n.node}s cannot be matched to the environment's empty ${n.node}s one to one (${n.unlabelled} against ${n.empty}), `+ + `so the spec's are written as new, untitled ${n.node}s and this one, with its title ${shown(n.live)}, is not kept. Label the spec's ${n.node} ${shown(n.live)} to keep it.`);}}return lines;diff --git a/plugins/model-apps/scripts/lib/temp-workspace.js b/plugins/model-apps/scripts/lib/temp-workspace.jsindex f84134a0f..a58af7306 100644--- a/plugins/model-apps/scripts/lib/temp-workspace.js+++ b/plugins/model-apps/scripts/lib/temp-workspace.js@@ -14,10 +14,12 @@// * The first workspace a process makes sweeps that folder first (sweepDeadWorkspaces): a workspace whose owner is PROVABLY gone is removed, and// the run says so on stderr. Everything else is left exactly as it is — a workspace of a run that may still be going, one with no readable record// (made by an earlier release, or damaged), one from another machine, anything that is not a folder.-// * When the process ends, the plugin's folder is removed if nothing is left in it, so a normal run leaves the temp folder as it found it.+// * When the process ends — by itself, by `process.exit` or by an error nothing catches: the `exit` event — the workspaces it made and did not lend that are still there are removed, and then the plugin's folder, if nothing is+// left in it, so a run leaves the temp folder as it found it. A run that is cut short never reached the `finally` that removes its workspace, and it held the source of every page the run read (THE END OF A RUN, below,+// says why this cannot take what another run is using, and why a POSIX signal is not one of these ends).//// IT CHANGES NOTHING ELSE. A caller that gets the folder here does what it did with `fs.mkdtempSync(path.join(os.tmpdir(), prefix))`: it passes the folder to-// the SDK and removes it, with `fs.rmSync`, when it is done. The plugin's own folder is OPTIONAL: if it cannot be used — it is not ours alone, it is a link, the disk+// the SDK and removes it, with `fs.rmSync`, when it is done — and the end of the process does it for a caller that never got there. The plugin's own folder is OPTIONAL: if it cannot be used — it is not ours alone, it is a link, the disk// says no, or it exists and will not take a new folder (mode 0500, a Windows access list that denies it) — the folder is made in the temp directory exactly as before,// unrecorded and never swept, and an error is reported only if that fails too. This is a courtesy to the next run, never a reason for one to fail.// Folders made by an earlier release are loose in the temp folder with no record, and stay where they are.@@ -56,7 +58,28 @@// * The record is moved out of the folder to `<folder>.removing`, beside it, and the folder removed. A sweep that is killed between those two steps leaves an empty folder and that// file, and the next sweep FINISHES the removal — when the file is a record of the folder's own (its name, a record that names the pid in it, an owner that is gone) and the folder// is empty or already gone. Anything that does not agree is left exactly as it is.-// * It never removes the plugin's folder itself: another run may be making a workspace in it that moment.+// * It never removes the plugin's folder itself: another run may be making a workspace in it that moment. (The end of a process takes the folder with `rmdir`, which takes it only when it is empty: THE END OF A RUN, below.)+//+// THE END OF A RUN. The `exit` event — it runs when the event loop empties, on `process.exit` and on an error nothing catches — removes, synchronously and in this order,+// 1. the workspaces this process made here and did not lend (makeTempWorkspace remembers them), by the steps a sweep takes a dead run's (removeWorkspace: what is inside first, the record last, so that a removal that fails —+// Windows holds a file — leaves a folder that is still recorded, and that a later run's sweep takes). A LENT workspace is not one of them: the program it was lent to may still be writing in it, and a lent workspace is taken+// only when it is old (LENT_KEEP_MS), by a sweep;+// 2. the plugin's folder, with `rmdir`.+// A caller that lends a workspace removes it itself, in a cleanup it registers for the end of the process (lib/exit-cleanup.js; solution-settings.js does), and that cleanup runs AFTER this listener, which found the lent workspace+// in the plugin's folder and so left the folder. The cleanup therefore calls `pruneWorkspaceParents()` once its workspace is gone: the same `rmdir` of the plugin's folder, which takes it only when it is empty, so nothing that is not+// the run's own is ever taken, and nothing is removed recursively. (A signal ends a POSIX process with no `exit` event at all; the cleanup that exit-cleanup.js runs for it, and this call, are then all that takes the folder.)+// Why neither takes what another run is using, or is about to use:+// * A workspace of this process is named for its pid and six random characters, so no other run makes, opens or removes it. A sweep never opens a folder whose pid runs (on Linux it reads its record, and a run that is going+// is "alive" there), and this process runs until the last listener of its `exit` event has returned.+// * `rmdir` removes a folder only if it is empty, in one step. Another run's workspace in the plugin's folder — one that is there, or one `mkdtemp` is making that moment, which creates its entry in one step — makes it refuse+// (ENOTEMPTY), and the folder stays. A run that has made the folder and not yet its workspace in it has an empty folder for a moment, and CAN lose it: its `mkdtemp` then fails with ENOENT, which makeTempWorkspace answers by+// making the folder again (MAKE_ATTEMPTS times), and on Windows a folder that is being removed refuses for a moment instead, which it answers by waiting (WAITS_MS). So no run fails for it; the cost is one more mkdir.+// * The workspaces go first, so that the folder is looked at after this process has taken what is its own out of it.+// What is NOT covered is a POSIX signal. The default action of SIGINT, SIGTERM and SIGHUP ends the process at once, and the `exit` event never runs: what the run left stays for the next run's sweep, and the folder goes with the next+// run that ends with nothing in it. Covering it takes a listener in every script that makes a workspace, and a listener REPLACES the default action: a process that is blocked in a synchronous call (`az` or `pac` run to its end, a pause+// for a Windows lock) no longer ends when it is signalled, but when the call returns; the listener must end the process itself, by raising the signal again so that its status stays a signal's; and a script with a handler of its own+// must keep the decision. lib/exit-cleanup.js does all of that, and is used where the leftover holds values a person has not shared (solution-settings.js: the lent folder of pac, while pac runs). What a workspace leaves is a few+// kilobytes until the next run's sweep, which is not worth changing how every script of the plugin ends when it is signalled. SIGKILL and "End task" run nothing, whatever is listened for.//// A SWEEP IS BOUNDED, AND FAIR. It looks at no more than MAX_EXAMINED entries and removes no more than MAX_REMOVED, so a folder that has somehow collected thousands is worked off over several runs and not in the time of one. If the// entries it looked at were always the first ones, a folder whose first MAX_EXAMINED must be kept — folders no record vouches for, a record that cannot be read for a moment — would hide every entry after them for good: a dead run's@@ -230,16 +253,35 @@ function pidOfName(name) {return named ? Number(named[1]) : null;}-// The plugin's folder is removed when the process ends and nothing is left in it. `rmdir` removes a folder only when it is empty — the check and the-// removal are one step — so a workspace another run is making, or has, is never lost to it; a run that was about to make one finds the folder gone-// and makes it again (makeTempWorkspace). One listener for every folder this process used, so a process that uses many (a test) adds one.+// What the end of the process removes (THE END OF A RUN, at the top of this file): the workspaces this process made in the plugin's folder and did not lend, each with the file system it was made through, and then the plugin's folder when+// nothing is left in it. `rmdir` removes a folder only when it is empty — the check and the removal are one step — so a workspace another run is making, or has, is never lost to it; a run that was about to make one finds the+// folder gone and makes it again (makeTempWorkspace). One listener for everything this process used, so a process that uses many folders (a test) adds one. The listener never throws and never touches the exit status: the+// process is ending, there is nobody left to tell, and a failure here is what a later run's sweep is for.+const ownWorkspaces = new Map();const pruneAtExit = new Map();+function removeOwnWorkspace(dir, fsx) {+ try {+ // Gone already (its run removed it) or not a folder at all — a link put there is not followed.+ if (!fsx.lstatSync(dir).isDirectory()) return;+ } catch {+ return;+ }+ try { removeWorkspace(dir, { fs: fsx }); } catch { /* a removal that fails (Windows holds a file) leaves the folder recorded, for a later sweep */ }+ // A folder whose record could not be written has none to move aside, and removeWorkspace leaves it empty.+ try { fsx.rmdirSync(dir); } catch { /* gone, or not empty */ }+}+// The plugin's folder, taken when nothing is left in it: every folder this process used, with `rmdir`, which takes a folder only when it is empty (see above). The end of the process does it after the workspaces it removes, and a caller+// that removes a LENT workspace in a cleanup of its own — which runs after that listener, see THE END OF A RUN — does it again when the workspace is gone. It never throws, and asking again, or for a folder that is gone, costs nothing.+function pruneWorkspaceParents() {+ for (const [folder, fsx] of pruneAtExit) {+ try { fsx.rmdirSync(folder); } catch { /* not empty (another run's workspace, or one that could not be removed), or already gone */ }+ }+}function prune(parent, deps) {if (pruneAtExit.size === 0) {process.once('exit', () => {- for (const [folder, fsx] of pruneAtExit) {- try { fsx.rmdirSync(folder); } catch { /* not empty (a workspace that was left, another run's), or already gone */ }- }+ for (const [dir, fsx] of ownWorkspaces) removeOwnWorkspace(dir, fsx);+ pruneWorkspaceParents();});}pruneAtExit.set(parent, deps.fs || fs);@@ -532,10 +574,10 @@ function sweepOnce(parent, deps) {const refusing = new Set();/**- * A new, empty, private workspace folder, to be used and removed as `fs.mkdtempSync(path.join(os.tmpdir(), prefix))` is.+ * A new, empty, private workspace folder, to be used and removed as `fs.mkdtempSync(path.join(os.tmpdir(), prefix))` is — and removed when the process ends, if the caller never got to it (a workspace that is not lent: see THE END OF A RUN).** `lent: true` is for a folder one of whose paths is to be GIVEN to another program — pac, writing its settings file in it: say so here, when the folder is made, and not later (see the top of- * this file). The record is then written once with that word in it, and a sweep never takes the folder because this run is gone: only when it is old as well (LENT_KEEP_MS).+ * this file). The record is then written once with that word in it, and a sweep never takes the folder because this run is gone: only when it is old as well (LENT_KEEP_MS); and the end of this process does not take it either.* @param {string} prefix what the folder's name starts with (a name, not a path), so a folder left behind says whose it was: `<prefix><pid>-<random>`, with a hyphen put before the pid when the prefix does not end in one* @param {object} [deps] `lent` (see above), and test seams: fs, os, uid, mkdtempSync (what makes the folder, given the path to start its name with), warn, owner, pause (sleeps, given milliseconds), folderPrivacy (the Windows access-list reader), folderProtect (the Windows maker of an access list)* @returns {string} the folder@@ -563,6 +605,8 @@ function makeTempWorkspace(prefix, deps = {}) {let dir;try {ensureParent(parent, deps);+ // From here on the folder may be one this process made, so it is this process's to take away when it ends with nothing in it — also when the workspace below is refused (a full disk) and goes in the temp folder.+ prune(parent, deps);sweepOnce(parent, deps);dir = mkdtemp(path.join(parent, `${named}${stamp.pid}-`));} catch (e) {@@ -580,11 +624,13 @@ function makeTempWorkspace(prefix, deps = {}) {break;}mark(dir, stamp, deps);- prune(parent, deps);+ // The end of the process removes what the run did not — unless it was lent: a program that was given a path in it may still be writing there (see THE END OF A RUN). A `mkdtempSync` seam that answers a+ // folder somewhere else is not the plugin's folder's, and is not touched.+ if (deps.lent !== true && path.dirname(dir) === parent) ownWorkspaces.set(dir, deps.fs || fs);return dir;}}return mkdtemp(path.join((deps.os || os).tmpdir(), prefix));}-module.exports = { PARENT_NAME, OWNER_FILE, REMOVING_SUFFIX, CURSOR_FILE, LENT_KEEP_MS, LIMITS: { MAX_EXAMINED, MAX_REMOVED }, workspaceParent, makeTempWorkspace, sweepDeadWorkspaces, sweepWarning };+module.exports = { PARENT_NAME, OWNER_FILE, REMOVING_SUFFIX, CURSOR_FILE, LENT_KEEP_MS, LIMITS: { MAX_EXAMINED, MAX_REMOVED }, workspaceParent, makeTempWorkspace, sweepDeadWorkspaces, sweepWarning, pruneWorkspaceParents };diff --git a/plugins/model-apps/scripts/lib/verify-spec.js b/plugins/model-apps/scripts/lib/verify-spec.jsindex b003bdba0..4b5c7a9e8 100644--- a/plugins/model-apps/scripts/lib/verify-spec.js+++ b/plugins/model-apps/scripts/lib/verify-spec.js@@ -32,6 +32,7 @@ const { wantsTimeline, timelineVerifyProblem, FULL_BUILD } = require('./form-timconst { placementOf, resolvePlacement, columnSequence, neighbourOf, tokenLabel, findGridSection, AUTO_TAB_NAME } = require('./form-subgrid-placement.js');const { isMainForm, selectDefaultForm, plannedMainFormSequence, displayConditionsOrder, compareServedOrder } = require('./form-order.js');const { hasLabelUses, resolveViewFilterLabels, memoizeChoiceReader, describeProblem } = require('./view-filter-labels.js');+const { hostsCustomControl } = require('./dashboard-tiles.js');// How many verification reads may be in flight at once. A verify pass is nothing but reads, but each is a// Dataverse request that already retries on its own 429s (lib/sdk-http-client.js), so the bound is small:@@ -362,6 +363,14 @@ async function verifySpec(spec, read, opts = {}) {// tables made the build produce exactly that — live, with the dashboard present and verify passing.// So a dashboard is proven only when each chart tile's view and chart both belong to its table.//+ // That is a check of the tiles the BUILD makes, so it holds native chart tiles only. A tile that is no native chart is skipped,+ // as it always was: the Assistant, an iframe, a web resource, and any custom control — a grid or a chart a custom control hosts+ // among them. The SDK types such a chart `chart`, as it does a native one (it used to type every custom-control tile as the+ // Assistant), but the App Spec cannot describe it and the build never writes or edits it, so the chart and view it carries are+ // not ones the spec declares: holding it to them failed a dashboard the build had left untouched. It is skipped, not listed+ // `unverified`, because that is for a check verify sets out to make and cannot decide, and this is one it never makes — the+ // same answer as before the SDK change. The classification is the download's (lib/dashboard-tiles.js), so the two agree.+ //// Existence is checked for every dashboard. The tile check needs `dashboardComponents` on the// reader (additive and reader-gated, like the other content checks); the CLI's reader supplies it.// Every read failure is reported as unverified, never as correct.@@ -434,7 +443,7 @@ async function verifySpec(spec, read, opts = {}) {problems.push(`its tiles could not be read (${(e && e.message) || e}) — unverified, not proven correct`);}for (const c of components || []) {- if (!c || c.type !== 'chart') continue;+ if (!c || c.type !== 'chart' || hostsCustomControl(c)) continue;const p = c.parameters || {};const table = String(p.TargetEntityType || '').toLowerCase();const label = `chart tile '${c.name || '(unnamed)'}'`;diff --git a/plugins/model-apps/scripts/run-tests.js b/plugins/model-apps/scripts/run-tests.jsindex bc8f384e6..11426d5bd 100644--- a/plugins/model-apps/scripts/run-tests.js+++ b/plugins/model-apps/scripts/run-tests.js@@ -5,7 +5,9 @@// is built for the Node-20 ABI; the default Node fails to load it). Prints a combined PASS/FAIL and// exits non-zero on any failure — the "did I break anything?" gate to run before every commit.// The plugin suite runs in a temporary folder of its own, and the run also fails when a test leaves-// a file or folder in it (runPluginSuite, below).+// a file or folder in it, or makes a `.maker-workspace` in the plugin's own folder, which is the+// folder the suite runs in (runPluginSuite, below). That one is removed again only when it is empty:+// what is in it may be another process's, and the run deletes nothing it cannot show to be its own.//// Usage:// node scripts/run-tests.js # plugin suite only@@ -56,13 +58,59 @@ function sdkTestSpec(sdkPath, node20Bin) {};}+// Folders a test must not make in the folder the suite runs in, which is the plugin's own. A build opens its workspace, `<app folder>/.maker-workspace`, unless it is given another, so a test that hands a+// build `process.cwd()` as its app folder (or none, which a build reads as `.`) made `plugins/model-apps/.maker-workspace` and left it there: empty, and in no .gitignore. Nothing about such a folder says+// which test made it, and the next run finds it already there and takes it for one that always was, so a leak of this kind can only be caught by the run that makes it.+const STRAY_NAMES = ['.maker-workspace'];++// Which of them `dir` holds, whatever they are (a link is there too).+function strayFoldersIn(dir) {+ return STRAY_NAMES.filter((name) => {+ try {+ fs.lstatSync(path.join(dir, name));+ return true;+ } catch {+ return false;+ }+ });+}++// Remove `folder` when it is a plain folder with nothing in it, and say whether it is gone. A link is not a plain folder, whatever it points at — Node reports a junction on Windows as a link too — and is never removed:+// a removal that follows it reaches what it points at. `rmdir` is not recursive and refuses a folder that has anything in it (ENOTEMPTY, or EEXIST where the system says so), which is what spares another process's+// workspace. A folder that cannot be removed for any other reason (an empty one that another process holds open, on Windows) is kept too: failing to remove is the safe answer here.+function removeIfEmpty(folder) {+ try {+ if (!fs.lstatSync(folder).isDirectory()) return false;+ fs.rmdirSync(folder);+ return true;+ } catch {+ return false;+ }+}++// What a run made: the stray folders `dir` holds now that it did not hold before the run, named by path (`made`). One that was there before the run is not the run's to answer for, and stays as it is.+//+// That a folder is there now and was not before the run does not make it the suite's. Another process can open its own workspace in the same folder while the suite runs — a build started by hand beside it opens+// `<app folder>/.maker-workspace` — and what is in it is that process's baseline and lock; a removal of everything in the folder, which this once was, took a live build's workspace away. The run cannot tell the two+// apart, so it deletes nothing it cannot show to be its own: it names the folder, and fails on it, and takes it away only when it is empty (removeIfEmpty). What it leaves — a folder with something in it, a link, a+// file — is `kept`, for the developer to delete when they know whose it is. The next run finds a kept folder already there and takes it for one that always was, which is why the report says to delete it (reportStrayFolders).+function settleStrayFolders(dir, before) {+ const made = strayFoldersIn(dir).filter((name) => !before.includes(name)).map((name) => path.join(dir, name));+ const kept = [];+ for (const folder of made) if (!removeIfEmpty(folder)) kept.push(folder);+ return { made, kept };+}+// The plugin suite runs in a temporary folder of its own: TEMP, TMP and TMPDIR point into it, so os.tmpdir() does too,// in every test file and in every process a test starts. Whatever is still in it when the suite ends was left by a test// that did not clean up after itself, so the run names it and fails. A full run used to leave about 260 folders in the// developer's own temp folder, which grew by hundreds of thousands of entries; tests/helpers/temp-dirs.js is the shared// way to clean up. The private folder is removed either way, so a leak never reaches the developer's temp folder.+// The folder the suite runs in is watched too: `made` is what the run made in it that was not there before it (STRAY_NAMES, above), and `kept` the part of that which the run left in place (settleStrayFolders).function runPluginSuite(files, { cwd, stdio = 'inherit', tempParent = os.tmpdir() } = {}) {const tempDir = fs.mkdtempSync(path.join(tempParent, 'model-apps-tests-'));+ const here = cwd || process.cwd();+ const before = strayFoldersIn(here);try {// A process a test runner starts inherits NODE_TEST_CONTEXT, and a `node --test` that has it acts as that runner's// child: given these files, it ran none of them and exited 0 (measured: a test that makes a folder made none). The@@ -70,7 +118,8 @@ function runPluginSuite(files, { cwd, stdio = 'inherit', tempParent = os.tmpdir(const env = withTempDir(process.env, tempDir);delete env.NODE_TEST_CONTEXT;const run = spawnSync(process.execPath, ['--test', ...files], { cwd, stdio, env });- return { status: run.status, left: fs.readdirSync(tempDir).sort() };+ const left = fs.readdirSync(tempDir).sort();+ return { status: run.status, left, ...settleStrayFolders(here, before) };} finally {try {fs.rmSync(tempDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });@@ -81,6 +130,18 @@ function runPluginSuite(files, { cwd, stdio = 'inherit', tempParent = os.tmpdir(}}+// What the run says of the folders it made in the plugin's own folder: each by path, whether it took the folder away again (it was empty) or left it in place, and what to do about it. Nothing is said when it made none.+function reportStrayFolders({ made, kept }) {+ if (made.length === 0) return '';+ const lines = [`\n${made.length} folder(s) made in the plugin's own folder while the suite ran:`];+ for (const folder of made) lines.push(` ${folder} ${kept.includes(folder) ? '(left in place)' : '(empty: removed again)'}`);+ if (kept.length) {+ lines.push('A folder left in place has something in it, or is not a plain folder, and the run does not remove what it cannot show to be its own: another process may have made it while the suite ran (a build started beside the suite opens .maker-workspace in the folder it is given). Delete it by hand once you know it is not in use; until then the next run takes it for one that was always there, and a leak is not caught again.');+ }+ lines.push('A test that runs a build must give it a folder and a workspace of its own: a temporary folder it removes (scripts/tests/helpers/temp-dirs.js), never process.cwd(). With no workspace given, a build opens <app folder>/.maker-workspace.');+ return `${lines.join('\n')}\n`;+}+// os.tmpdir() reads TEMP, then TMP, on Windows, and TMPDIR on macOS and Linux. Windows names are case-insensitive, so every// spelling already in the environment is dropped first: a child handed both `Temp` and `TEMP` would see only one of them,// and not necessarily ours.@@ -115,6 +176,8 @@ function main(argv) {process.stdout.write('A test must remove every file and folder it makes (scripts/tests/helpers/temp-dirs.js).\n');}results.push({ name: 'nothing left in the temporary folder', ok: plugin.left.length === 0 });+ process.stdout.write(reportStrayFolders(plugin));+ results.push({ name: 'nothing made in the plugin folder', ok: plugin.made.length === 0 });// 2) SDK Jest suite (opt-in, Node 20).if (sdkPath) {@@ -157,4 +220,4 @@ if (require.main === module) {process.exit(main(process.argv));}-module.exports = { pluginTestFiles, sdkTestSpec, summarize, runPluginSuite, withTempDir, main };+module.exports = { pluginTestFiles, sdkTestSpec, summarize, runPluginSuite, reportStrayFolders, withTempDir, main };diff --git a/plugins/model-apps/scripts/solution-settings.js b/plugins/model-apps/scripts/solution-settings.jsindex f22a5ebf0..03b95de37 100644--- a/plugins/model-apps/scripts/solution-settings.js+++ b/plugins/model-apps/scripts/solution-settings.js@@ -112,7 +112,7 @@ const { createAzHttpClient, retryAfterMs, scrub, scrubBearer, MIN_SCRUBBED_TOKENconst { sdkFirst } = require('./lib/sdk-first.js');const { runPac } = require('./lib/pac-fallback.js');const { assertPlainFileTarget, assertSafeOutputDir, writeFileSafe, removeTreeWithRetry } = require('./lib/safe-fs.js');-const { makeTempWorkspace } = require('./lib/temp-workspace.js');+const { makeTempWorkspace, pruneWorkspaceParents } = require('./lib/temp-workspace.js');const { createPrivateFile } = require('./lib/private-folder.js');const { onProcessEnd } = require('./lib/exit-cleanup.js');@@ -915,6 +915,10 @@ async function inWorkFolder(holds, work, { empty, prepare = null, prepareFailureconst releaseCleanup = onProcessEnd(() => {const note = removeWorkFolder(dir, holds, empty);if (note) writeNote(note, leaving);+ // This runs after the maker's own listener for the end of the process (lib/temp-workspace.js registered it first), which found this LENT workspace in the plugin's folder and left the folder. The workspace is gone now,+ // so the folder is taken too when nothing else is in it — the same plain `rmdir`, which takes a folder only when it is empty, so nothing that is not this run's is touched. A signal ends a POSIX process with no `exit` event+ // at all, and then this is all that takes the folder.+ pruneWorkspaceParents();}, proc ? { process: proc } : undefined);let value;let failure;diff --git a/plugins/model-apps/scripts/tests/column-autonumber-gate.test.js b/plugins/model-apps/scripts/tests/column-autonumber-gate.test.jsnew file mode 100644index 000000000..4bd8f6676--- /dev/null+++ b/plugins/model-apps/scripts/tests/column-autonumber-gate.test.js@@ -0,0 +1,145 @@+'use strict';++// An `AutoNumber` column needs a usable `autoNumberFormat`, and the spec gate says so before anything is built.+//+// The SDK refuses to create an `autonumber` column without a format, before any request, where the SDK it replaced created a plain text column. A spec+// with an AutoNumber column and no format therefore used to build (as text) and now halts the data-model phase at that column, after the solution and+// the tables exist. The rule lives in lib/app-spec.js (autoNumberFormatProblem) and is applied by BOTH gates a build can come through: validateAppSpec+// (/app-builder) and the provision-entities input validator (/genpage and /app-builder). Teardown validates under the structural profile and must keep+// accepting a spec an earlier release built from such a column, so that profile does not apply it.+//+// What the SDK itself does — the refusal, the halt a spec that got past the gate causes, and a rebuild that finds the column already there — is pinned+// against the real bundle in table-columns-in-create.test.js.++const { test } = require('node:test');+const assert = require('node:assert');+const { validateAppSpec } = require('../lib/app-spec.js');+const { validateProvisionInput } = require('../lib/provision-input.js');+const { provisionEntities } = require('../provision-entities.js');+const { entityFromMetadata } = require('../download-model-app.js');+const { BUILDING_PROFILES, column, nameColumn, appSpec, provisionInput, tail, watchedDeps } = require('./helpers/column-gate-specs.js');++const FORMAT_HINT = 'give it a format such as "C-{SEQNUM:5}", or use type "Text" for a plain text column';+const formatError = (state, name = 'new_ref') => `entity new_ticket: column ${name} is an AutoNumber column but its autoNumberFormat is ${state} — ${FORMAT_HINT}`;++test('an AutoNumber column with no autoNumberFormat is refused before anything is built, naming the table, the column and both ways out', () => {+ for (const profile of BUILDING_PROFILES) {+ for (const spelled of [{}, { autoNumberFormat: undefined }, { autoNumberFormat: null }]) {+ const result = validateAppSpec(appSpec({ columns: [column({ type: 'AutoNumber', ...spelled })] }), { profile });+ assert.strictEqual(result.ok, false, `${profile} ${JSON.stringify(spelled)} must be refused`);+ assert.deepStrictEqual(result.errors, [formatError('missing')], `${profile} ${JSON.stringify(spelled)}`);+ }+ }+});++test('an AutoNumber column whose autoNumberFormat is blank or not a string is refused the same way, saying what was found', () => {+ const found = [+ ['', 'blank'], [' ', 'blank'], ['\t\n', 'blank'],+ [5, 'not a string (got 5)'], [0, 'not a string (got 0)'], [false, 'not a string (got false)'], [true, 'not a string (got true)'],+ [{}, 'not a string (got {})'], [['C-{SEQNUM:5}'], 'not a string (got ["C-{SEQNUM:5}"])'],+ ];+ for (const [format, state] of found) {+ const result = validateAppSpec(appSpec({ columns: [column({ type: 'AutoNumber', autoNumberFormat: format })] }), { profile: 'deploy' });+ assert.strictEqual(result.ok, false, `${JSON.stringify(format)} must be refused`);+ assert.deepStrictEqual(result.errors, [formatError(state)], JSON.stringify(format));+ }+});++test('every AutoNumber column that lacks a format is named, in whichever position it stands', () => {+ const columns = [+ column({ schemaName: 'new_a', type: 'Text' }),+ column({ schemaName: 'new_b', type: 'AutoNumber', autoNumberFormat: 'B-{SEQNUM:4}' }),+ column({ schemaName: 'new_c', type: 'AutoNumber' }),+ column({ schemaName: 'new_d', type: 'Integer' }),+ column({ schemaName: 'new_e', type: 'AutoNumber', autoNumberFormat: ' ' }),+ ];+ const result = validateAppSpec(appSpec({ columns }), { profile: 'deploy' });+ assert.deepStrictEqual(result.errors, [formatError('missing', 'new_c'), formatError('blank', 'new_e')]);+});++test('a usable autoNumberFormat is accepted, and a format on a column that is not AutoNumber is left to the build as before', () => {+ for (const format of ['C-{SEQNUM:5}', 'ABC', '{SEQNUM:3}-{RANDSTRING:4}', ' WO-{SEQNUM:5} ']) {+ const result = validateAppSpec(appSpec({ columns: [column({ type: 'AutoNumber', autoNumberFormat: format })] }), { profile: 'deploy' });+ assert.deepStrictEqual(result.errors, [], JSON.stringify(format));+ }+ const others = [column({ schemaName: 'new_t', type: 'Text' }), column({ schemaName: 'new_u', type: 'Text', autoNumberFormat: '' }), column({ schemaName: 'new_i', type: 'Integer' }), column({ schemaName: 'new_n' })];+ assert.deepStrictEqual(validateAppSpec(appSpec({ columns: others }), { profile: 'deploy' }).errors, []);+});++test('the primary name column is judged as before: with no autoNumberFormat, a blank one or a format, the spec is accepted', () => {+ for (const autoNumberFormat of [undefined, '', null, 'WO-{SEQNUM:5}']) {+ const primaryAttribute = nameColumn(autoNumberFormat === undefined ? {} : { autoNumberFormat });+ assert.deepStrictEqual(validateAppSpec(appSpec({ primaryAttribute }), { profile: 'deploy' }).errors, [], JSON.stringify(autoNumberFormat));+ assert.deepStrictEqual(validateProvisionInput(provisionInput({ primaryAttribute })).errors, [], `${JSON.stringify(autoNumberFormat)} through the provision-entities gate`);+ }+});++test('structural validation, which teardown runs, still accepts a spec an earlier release built with an AutoNumber column that has no format', () => {+ const spec = appSpec({ columns: [column({ type: 'AutoNumber' }), column({ schemaName: 'new_b', type: 'AutoNumber', autoNumberFormat: '' })] });+ assert.deepStrictEqual(validateAppSpec(spec, { profile: 'structural' }).errors, []);+ for (const profile of BUILDING_PROFILES) assert.strictEqual(validateAppSpec(spec, { profile }).ok, false, `${profile} refuses it`);+});++// --- the provision-entities input gate applies the same rule --------------------------------------------------------------------+// It is the only gate between an input file and the first write of /genpage and /app-builder: the publisher and the solution are made before the+// first table, so a column the build cannot create has to stop here.++test('the provision-entities input gate refuses the AutoNumber columns the spec gate refuses, with the same wording', () => {+ for (const format of [undefined, null, '', ' ', 5, true, {}, [], 'C-{SEQNUM:5}']) {+ const columns = [column({ type: 'AutoNumber', ...(format === undefined ? {} : { autoNumberFormat: format }) })];+ const spec = validateAppSpec(appSpec({ columns }), { profile: 'deploy' });+ const input = validateProvisionInput(provisionInput({ columns }));+ const label = JSON.stringify(format);+ assert.strictEqual(input.ok, format === 'C-{SEQNUM:5}', `${label}: only a usable format passes`);+ assert.strictEqual(input.ok, spec.ok, label);+ assert.deepStrictEqual(input.errors.map((e) => tail(e, ' is an AutoNumber column')), spec.errors.map((e) => tail(e, ' is an AutoNumber column')), `${label}: the same verdict and wording from both gates`);+ for (const message of input.errors) assert.ok(message.startsWith("entity 'new_ticket': column 'new_ref' "), message);+ }+});++test('an input with an AutoNumber column that has no format is refused before anything is called — no publisher, no solution, no table', async () => {+ for (const format of [undefined, '', ' ', 5]) {+ const d = watchedDeps();+ const columns = [column({ schemaName: 'new_ref', type: 'AutoNumber', ...(format === undefined ? {} : { autoNumberFormat: format }) })];+ const result = await provisionEntities(provisionInput({ columns }), { apply: true }, { sdk: d.sdk, provision: d.provision });+ assert.strictEqual(result.ok, false, `${JSON.stringify(format)} must be refused`);+ assert.ok(result.errors.some((e) => /^entity 'new_ticket': column 'new_ref' is an AutoNumber column but its autoNumberFormat is /.test(e)), JSON.stringify(result.errors));+ assert.deepStrictEqual(d.touched, [], `${JSON.stringify(format)}: nothing was called`);+ }+ // The dry run refuses it too, rather than planning a build that cannot run.+ const dry = await provisionEntities(provisionInput({ columns: [column({ type: 'AutoNumber' })] }), { apply: false }, watchedDeps());+ assert.strictEqual(dry.ok, false);+});++test('an input whose AutoNumber column has a format is provisioned as before', async () => {+ const d = watchedDeps();+ const input = provisionInput({ columns: [column({ type: 'AutoNumber', autoNumberFormat: 'C-{SEQNUM:5}' }), column({ schemaName: 'new_note', type: 'Text' })], primaryAttribute: nameColumn({ autoNumberFormat: 'WO-{SEQNUM:5}' }) });+ const result = await provisionEntities(input, { apply: true }, { sdk: d.sdk, provision: d.provision });+ assert.strictEqual(result.ok, true, JSON.stringify(result));+ assert.ok(d.touched.includes('createTable'), 'the table was created');+ assert.ok(d.touched.includes('createColumn'), 'and its columns');+});++// --- a downloaded spec passes the gate ----------------------------------------------------------------------------------------------+// An auto-number column is a String attribute (formally a text column with a format), so the download reads it as Text and states no format: the spec it+// makes never carries an AutoNumber column, with or without a format.++test('a downloaded auto-number column is declared Text with no autoNumberFormat, and the spec it makes passes the gate', () => {+ const attribute = (logicalName, extra) => ({ logicalName, displayName: logicalName, attributeType: 'String', isCustomAttribute: true, ...extra });+ const meta = {+ logicalName: 'new_ticket', schemaName: 'new_ticket', displayName: 'Ticket', primaryNameAttribute: 'new_name',+ attributes: [+ attribute('new_name', { AutoNumberFormat: 'WO-{SEQNUM:5}', autoNumberFormat: 'WO-{SEQNUM:5}' }),+ attribute('new_ref', { AutoNumberFormat: 'C-{SEQNUM:5}', autoNumberFormat: 'C-{SEQNUM:5}' }),+ attribute('new_plain', {}),+ ],+ };+ const entity = entityFromMetadata(meta, 'new_ticket');+ assert.deepStrictEqual(entity.columns.map((c) => [c.schemaName, c.type]), [['new_ref', 'Text'], ['new_plain', 'Text']]);+ for (const c of entity.columns) assert.ok(!('autoNumberFormat' in c), `${c.schemaName} states no format`);+ assert.ok(!('autoNumberFormat' in entity.primaryAttribute), 'and neither does the name column');+ for (const profile of ['plan', 'deploy']) {+ const result = validateAppSpec({ schemaVersion: 2, solution: { uniqueName: 'S', publisherPrefix: 'new' }, app: { name: 'A' }, entities: [entity], appShell: { areas: [] } }, { profile });+ assert.deepStrictEqual(result.errors, [], profile);+ }+});diff --git a/plugins/model-apps/scripts/tests/column-required-gate.test.js b/plugins/model-apps/scripts/tests/column-required-gate.test.jsnew file mode 100644index 000000000..e9ab5d34d--- /dev/null+++ b/plugins/model-apps/scripts/tests/column-required-gate.test.js@@ -0,0 +1,260 @@+'use strict';++// `required` on a column, or on the primary name column, is `true`, `false` or "recommended" — and the spec gate says so before anything is built.+//+// Every other value (`"ApplicationRequired"`, `"true"`, `"required"`, `"Recommended"`, `1`, `null` ...) was read by the build as "not required": a new+// column came out not required, and on an EXISTING column — which the build reconciles whenever the spec states a `required` — it wrote None where the level+// differed, demoting a column a maker had made Business Required. The rule lives in lib/app-spec.js (requiredValueProblem) and is applied by BOTH gates a+// build can come through: validateAppSpec (/app-builder) and the provision-entities input validator (/genpage and /app-builder). Teardown validates under the+// structural profile and must keep accepting a spec an earlier release built from such a value, so that profile does not apply it.+//+// What else reads a column's `required` is held to the same set: the build (REQUIRED, lib/entity-provision.js), the plan document, the forms and the schema facts.++const { test } = require('node:test');+const assert = require('node:assert');+const { validateAppSpec } = require('../lib/app-spec.js');+const { validateProvisionInput } = require('../lib/provision-input.js');+const { provisionEntities } = require('../provision-entities.js');+const { makeRunner, provisionDataModel } = require('../lib/entity-provision.js');+const { entityFromMetadata } = require('../download-model-app.js');+const { renderAppSpecDoc } = require('../lib/app-spec-doc.js');+const { BUILDING_PROFILES, column, nameColumn, appSpec, provisionInput, tail, watchedDeps } = require('./helpers/column-gate-specs.js');++const FORMAT_HINT = 'give it a format such as "C-{SEQNUM:5}", or use type "Text" for a plain text column';+const formatError = (state, name) => `entity new_ticket: column ${name} is an AutoNumber column but its autoNumberFormat is ${state} — ${FORMAT_HINT}`;+const OMIT_HINT = "omit the key to leave an existing column's level as it is";+const GENERIC_HINT = 'true makes a column required, "recommended" makes it recommended and false makes it not required';+const requiredError = (value, hint, subject = 'column new_status required') => `entity new_ticket: ${subject} must be true, false or "recommended" (got ${JSON.stringify(value)}) — ${hint}; ${OMIT_HINT}`;++// --- required is true, false or "recommended" ---------------------------------------------------------------------------------------++test('required is accepted as true, false or "recommended", or left out, on a column and on the primary name column, under every profile', () => {+ for (const profile of [...BUILDING_PROFILES, 'structural']) {+ for (const required of [true, false, 'recommended', undefined]) {+ const stated = required === undefined ? {} : { required };+ const result = validateAppSpec(appSpec({ columns: [column({ schemaName: 'new_status', type: 'Text', ...stated })], primaryAttribute: nameColumn(stated) }), { profile });+ assert.deepStrictEqual(result.errors, [], `${profile} ${JSON.stringify(required)}`);+ }+ }+ // An own property that holds `undefined` states nothing, as in any optional field of the spec (JSON cannot carry one).+ assert.deepStrictEqual(validateAppSpec(appSpec({ columns: [column({ schemaName: 'new_status', type: 'Text', required: undefined })], primaryAttribute: nameColumn({ required: undefined }) }), { profile: 'deploy' }).errors, []);+});++test('required refuses every other value, naming the table, the column, the value and the accepted values', () => {+ const slips = [+ 'ApplicationRequired', 'applicationrequired', 'true', 'false', 'required', 'Required', 'Recommended', 'RECOMMENDED', 'None', 'SystemRequired', 'yes', '',+ 1, 0, 2, null, {}, [], ['recommended'], [true],+ ];+ for (const profile of BUILDING_PROFILES) {+ for (const value of slips) {+ const onColumn = validateAppSpec(appSpec({ columns: [column({ schemaName: 'new_status', type: 'Text', required: value })] }), { profile });+ assert.strictEqual(onColumn.ok, false, `${profile} column ${JSON.stringify(value)} must be refused`);+ assert.strictEqual(onColumn.errors.length, 1, `${profile} column ${JSON.stringify(value)}: ${JSON.stringify(onColumn.errors)}`);+ assert.ok(onColumn.errors[0].startsWith(`entity new_ticket: column new_status required must be true, false or "recommended" (got ${JSON.stringify(value)}) — `), onColumn.errors[0]);+ assert.ok(onColumn.errors[0].endsWith(`; ${OMIT_HINT}`), onColumn.errors[0]);++ const onPrimary = validateAppSpec(appSpec({ primaryAttribute: nameColumn({ required: value }) }), { profile });+ assert.strictEqual(onPrimary.ok, false, `${profile} primaryAttribute ${JSON.stringify(value)} must be refused`);+ assert.strictEqual(onPrimary.errors.length, 1, `${profile} primaryAttribute ${JSON.stringify(value)}: ${JSON.stringify(onPrimary.errors)}`);+ assert.ok(onPrimary.errors[0].startsWith(`entity new_ticket: primaryAttribute.required must be true, false or "recommended" (got ${JSON.stringify(value)}) — `), onPrimary.errors[0]);+ }+ }+});++test('the refusal of a required value says what to write for the usual slips, and that leaving the key out keeps an existing column as it is', () => {+ const errorFor = (value) => validateAppSpec(appSpec({ columns: [column({ schemaName: 'new_status', type: 'Text', required: value })] }), { profile: 'deploy' }).errors;+ for (const value of ['ApplicationRequired', 'true', 'required', 'Required', 'yes', 1]) {+ assert.deepStrictEqual(errorFor(value), [requiredError(value, 'write true for a required column')], JSON.stringify(value));+ }+ for (const value of ['Recommended', 'RECOMMENDED', ' recommended']) {+ assert.deepStrictEqual(errorFor(value), [requiredError(value, 'write "recommended" for a recommended column')], JSON.stringify(value));+ }+ for (const value of ['None', 'false', 'no', 'optional', 0]) {+ assert.deepStrictEqual(errorFor(value), [requiredError(value, 'write false for a column that is not required')], JSON.stringify(value));+ }+ for (const value of ['SystemRequired', null, {}, [], '']) {+ assert.deepStrictEqual(errorFor(value), [requiredError(value, GENERIC_HINT)], JSON.stringify(value));+ }+});++test('a column with both problems gets both errors, and a spec with several bad columns names each one', () => {+ const columns = [+ column({ schemaName: 'new_a', type: 'AutoNumber', required: 'true' }),+ column({ schemaName: 'new_b', type: 'Text', required: true }),+ column({ schemaName: 'new_c', type: 'Choice', options: ['A'], required: 'Recommended' }),+ ];+ const result = validateAppSpec(appSpec({ columns, primaryAttribute: nameColumn({ required: 'ApplicationRequired' }) }), { profile: 'deploy' });+ assert.deepStrictEqual(result.errors, [+ requiredError('ApplicationRequired', 'write true for a required column', 'primaryAttribute.required'),+ formatError('missing', 'new_a'),+ requiredError('true', 'write true for a required column', 'column new_a required'),+ requiredError('Recommended', 'write "recommended" for a recommended column', 'column new_c required'),+ ]);+});++test('structural validation, which teardown runs, still accepts a spec an earlier release built with required values the build could not use', () => {+ const spec = appSpec({+ columns: [column({ schemaName: 'new_status', type: 'Text', required: 'ApplicationRequired' }), column({ schemaName: 'new_other', type: 'Text', required: null })],+ primaryAttribute: nameColumn({ required: 'true' }),+ });+ assert.deepStrictEqual(validateAppSpec(spec, { profile: 'structural' }).errors, []);+ for (const profile of BUILDING_PROFILES) assert.strictEqual(validateAppSpec(spec, { profile }).ok, false, `${profile} refuses it`);+});++// --- the provision-entities input gate applies the same rule ----------------------------------------------------------------------+// It is the only gate between an input file and the first write of /genpage and /app-builder: the publisher and the solution are made before the first+// table, so a value the build cannot use has to stop here.++test('the provision-entities input gate refuses the required values the spec gate refuses, on a column and on the primary name column, with the same wording', () => {+ for (const value of [true, false, 'recommended', undefined, 'ApplicationRequired', 'true', 'required', 'Recommended', 'None', 1, 0, null, {}, []]) {+ const stated = value === undefined ? {} : { required: value };+ const columns = [column({ schemaName: 'new_status', type: 'Text', ...stated })];+ const primaryAttribute = nameColumn(stated);+ const spec = validateAppSpec(appSpec({ columns, primaryAttribute }), { profile: 'deploy' });+ const input = validateProvisionInput(provisionInput({ columns, primaryAttribute }));+ const label = JSON.stringify(value);+ assert.strictEqual(input.ok, [true, false, 'recommended', undefined].includes(value), `${label}: only true, false, "recommended" or no value passes`);+ assert.strictEqual(input.ok, spec.ok, label);+ assert.deepStrictEqual(input.errors.map((e) => tail(e, 'required must be')), spec.errors.map((e) => tail(e, 'required must be')), `${label}: the same verdict and wording from both gates`);+ for (const message of input.errors) assert.ok(/^entity 'new_ticket': (primaryAttribute\.required|column 'new_status' required) must be /.test(message), message);+ }+});++test('an input with a required value that is not true, false or "recommended" is refused before anything is called, on a column and on the primary name column', async () => {+ for (const value of ['ApplicationRequired', 'true', 'required', 'Recommended', 1, null]) {+ for (const where of ['column', 'primary']) {+ const d = watchedDeps();+ const input = where === 'column'+ ? provisionInput({ columns: [column({ schemaName: 'new_status', type: 'Text', required: value })] })+ : provisionInput({ primaryAttribute: nameColumn({ required: value }) });+ const result = await provisionEntities(input, { apply: true }, { sdk: d.sdk, provision: d.provision });+ assert.strictEqual(result.ok, false, `${where} ${JSON.stringify(value)} must be refused`);+ assert.strictEqual(result.errors.length, 1, JSON.stringify(result.errors));+ assert.deepStrictEqual(d.touched, [], `${where} ${JSON.stringify(value)}: nothing was called`);+ }+ }+ // The dry run refuses it too, rather than planning a build that cannot run.+ const dry = await provisionEntities(provisionInput({ columns: [column({ schemaName: 'new_status', type: 'Text', required: 'ApplicationRequired' })] }), { apply: false }, watchedDeps());+ assert.strictEqual(dry.ok, false);+});++test('an input that states required validly is provisioned as before', async () => {+ const d = watchedDeps();+ const input = provisionInput({+ columns: [column({ schemaName: 'new_status', type: 'Text', required: true }), column({ schemaName: 'new_other', type: 'Text', required: 'recommended' }), column({ schemaName: 'new_third', type: 'Text', required: false })],+ primaryAttribute: nameColumn({ required: false }),+ });+ const result = await provisionEntities(input, { apply: true }, { sdk: d.sdk, provision: d.provision });+ assert.strictEqual(result.ok, true, JSON.stringify(result));+ assert.ok(d.touched.includes('createTable'), 'the table was created');+});++// --- what the build asks of the platform for each value the gate accepts --------------------------------------------------------------+// The gate's accepted set and the build's reading of a required value are one contract: each accepted value is a level, and the build asks for it.++function recordingSdk(existing = {}) {+ const calls = [];+ return {+ calls,+ sdk: {+ createTable: async (o) => { calls.push(['createTable', o]); return { logicalName: o.schemaName.toLowerCase(), entitySetName: `${o.schemaName.toLowerCase()}s`, metadataId: `tbl-${o.schemaName}`, ...(o.primaryColumnRequired && o.primaryColumnRequired !== 'None' ? { primaryColumnRequired: o.primaryColumnRequired } : {}) }; },+ 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 {}; },+ },+ provision: {+ findTables: async (s) => (existing[s.toLowerCase()] ? [{ logicalName: s.toLowerCase(), entitySetName: `${s.toLowerCase()}s` }] : []),+ findColumns: async () => [],+ fetchEntityMetadata: async (l) => ({ logicalName: l, entitySetName: `${l}s`, relationships: [] }),+ },+ };+}++async function provision(spec, m) {+ const events = [];+ const warnings = [];+ await provisionDataModel({ sdk: m.sdk, provision: m.provision, runner: makeRunner({ emit: (e) => events.push(e), total: 99 }), spec, apply: true, preResolvedLanguageCode: 1033, warn: (w) => warnings.push(w) });+ return { events, warnings };+}++const oneTableSpec = (primaryAttribute, columns) => ({ solution: { uniqueName: 'S', publisherPrefix: 'new' }, relationships: [], entities: [{ schemaName: 'new_ticket', displayName: 'Ticket', primaryAttribute, columns }] });++test('each required value the gate accepts is asked for as the level the schema reference names: true is ApplicationRequired, "recommended" is Recommended, false and no value are None', async () => {+ const m = recordingSdk();+ await provision(oneTableSpec({ schemaName: 'new_name', required: 'recommended' }, [+ { schemaName: 'new_a', type: 'Text', required: true }, { schemaName: 'new_b', type: 'Text', required: 'recommended' },+ { schemaName: 'new_c', type: 'Text', required: false }, { schemaName: 'new_d', type: 'Text' },+ ]), m);+ const levels = Object.fromEntries(m.calls.filter((c) => c[0] === 'createColumn').map((c) => [c[2].schemaName, c[2].required]));+ assert.deepStrictEqual(levels, { new_a: 'ApplicationRequired', new_b: 'Recommended', new_c: 'None', new_d: 'None' });+ assert.strictEqual(m.calls.find((c) => c[0] === 'createTable')[1].primaryColumnRequired, 'Recommended');++ const primaryLevels = [];+ for (const required of [true, false, undefined]) {+ const each = recordingSdk();+ await provision(oneTableSpec({ schemaName: 'new_name', ...(required === undefined ? {} : { required }) }, []), each);+ primaryLevels.push(each.calls.find((c) => c[0] === 'createTable')[1].primaryColumnRequired);+ }+ assert.deepStrictEqual(primaryLevels, ['ApplicationRequired', 'None', undefined], 'an omitted required asks the create for no level at all');+});++test('on an existing column an explicit required converges and a missing one leaves it alone — including an own property that holds undefined, which states nothing', async () => {+ const live = () => [{ logicalName: 'new_status', schemaName: 'new_status', RequiredLevel: { Value: 'ApplicationRequired' } }, { logicalName: 'new_name', schemaName: 'new_name', RequiredLevel: { Value: 'ApplicationRequired' } }];+ const run = async (required, primaryRequired) => {+ const m = recordingSdk({ new_ticket: true });+ m.provision.findColumns = async () => live();+ const stated = (value) => (value === 'absent' ? {} : { required: value });+ const result = await provision(oneTableSpec({ schemaName: 'new_name', ...stated(primaryRequired) }, [{ schemaName: 'new_status', type: 'Text', ...stated(required) }]), m);+ return { writes: m.calls.filter((c) => c[0] === 'updateColumn').map((c) => `${c[2]}:${c[3].required}`), steps: result.events.filter((e) => e.status !== 'start' && /^required /.test(e.label)).map((e) => `${e.status}: ${e.label}`) };+ };+ assert.deepStrictEqual((await run(false, false)).writes, ['new_name:None', 'new_status:None'], 'an explicit false converges: the columns are made not required, the name column first');+ assert.deepStrictEqual((await run('recommended', 'recommended')).writes, ['new_name:Recommended', 'new_status:Recommended']);+ assert.deepStrictEqual((await run(true, true)).writes, [], 'the level the spec states is the level there is');+ assert.deepStrictEqual(await run('absent', 'absent'), { writes: [], steps: [] }, 'a column the spec says nothing about is never written');+ assert.deepStrictEqual(await run(undefined, undefined), { writes: [], steps: [] }, 'and neither is one whose required holds undefined');+});++test('a new table whose primary name column holds required: undefined asks its create for no level, as when the key is left out', async () => {+ const m = recordingSdk();+ const result = await provision(oneTableSpec({ schemaName: 'new_name', required: undefined }, []), m);+ assert.strictEqual('primaryColumnRequired' in m.calls.find((c) => c[0] === 'createTable')[1], false);+ assert.deepStrictEqual(result.events.filter((e) => /^required /.test(e.label)), []);+});++// --- the other readers of a column's required: the plan document ------------------------------------------------------------------------+// The forms and the schema facts read `required === true` and nothing else (a recommended column is not a Business Required form field).++test('the plan document says "recommended" for a recommended column, "required" for a required one, and nothing for the rest', () => {+ const spec = appSpec({ columns: [+ column({ schemaName: 'new_a', displayName: 'Alpha', type: 'Text', required: true }),+ column({ schemaName: 'new_b', displayName: 'Beta', type: 'Text', required: 'recommended' }),+ column({ schemaName: 'new_c', displayName: 'Gamma', type: 'Text', required: false }),+ column({ schemaName: 'new_d', displayName: 'Delta', type: 'Text' }),+ ] });+ const rows = renderAppSpecDoc(spec).split('\n').filter((line) => /^\| (Alpha|Beta|Gamma|Delta) \|/.test(line));+ assert.deepStrictEqual(rows, ['| Alpha | Text | required |', '| Beta | Text | recommended |', '| Gamma | Text | — |', '| Delta | Text | — |']);+});++// --- a downloaded spec passes the gate ---------------------------------------------------------------------------------------------------+// The download carries no RequiredLevel at all, so what it writes passes the rule whatever level the live columns hold.++test('a downloaded table never states a required level, so the spec it makes passes the gate for every level a column can hold', () => {+ const levels = ['None', 'Recommended', 'ApplicationRequired', 'SystemRequired'];+ const attribute = (logicalName, extra) => ({ logicalName, displayName: logicalName, attributeType: 'String', isCustomAttribute: true, ...extra });+ const meta = {+ logicalName: 'new_ticket', schemaName: 'new_ticket', displayName: 'Ticket', primaryNameAttribute: 'new_name',+ attributes: [+ attribute('new_name', { RequiredLevel: { Value: 'ApplicationRequired' }, requiredLevel: 'ApplicationRequired' }),+ ...levels.map((level, i) => attribute(`new_level${i}`, { RequiredLevel: { Value: level }, requiredLevel: level })),+ attribute('new_amount', { attributeType: 'Money', RequiredLevel: { Value: 'ApplicationRequired' } }),+ ],+ };+ const entity = entityFromMetadata(meta, 'new_ticket');+ assert.deepStrictEqual(entity.columns.map((c) => c.schemaName), ['new_level0', 'new_level1', 'new_level2', 'new_level3', 'new_amount']);+ for (const c of entity.columns) assert.ok(!('required' in c), `${c.schemaName} states no required level`);+ assert.ok(!('required' in entity.primaryAttribute), 'and neither does the name column');+ for (const profile of ['plan', 'deploy']) {+ const result = validateAppSpec({ schemaVersion: 2, solution: { uniqueName: 'S', publisherPrefix: 'new' }, app: { name: 'A' }, entities: [entity], appShell: { areas: [] } }, { profile });+ assert.deepStrictEqual(result.errors, [], profile);+ }+});diff --git a/plugins/model-apps/scripts/tests/column-rules-authoring-gates.test.js b/plugins/model-apps/scripts/tests/column-rules-authoring-gates.test.jsnew file mode 100644index 000000000..8022d8ed7--- /dev/null+++ b/plugins/model-apps/scripts/tests/column-rules-authoring-gates.test.js@@ -0,0 +1,129 @@+'use strict';++// The two column rules (lib/app-spec.js: an AutoNumber column needs a format, and `required` is true, false or "recommended") are errors on every path+// that builds, plans or provisions. Read-only verification alone turns them into warnings — verify-model-app.js passes `columnValues: 'warn'`, as it passes+// `relationshipCollisions: 'warn'` — because it creates and updates nothing and the spec of an app an earlier release built must still reach the deployment+// (verify-model-app.test.js runs the CLI over such specs). These tests pin that the downgrade is that narrow: an option only that one caller passes, which moves+// nothing but these two rules, and which no authoring gate takes.++const { test } = require('node:test');+const assert = require('node:assert');+const { validateAppSpec } = require('../lib/app-spec.js');+const { validateProvisionInput } = require('../lib/provision-input.js');+const { lintSpec } = require('../lint-app-spec.js');+const { buildModelApp } = require('../build-model-app.js');+const { provisionEntities } = require('../provision-entities.js');+const { scriptsMatching } = require('./helpers/production-scripts.js');+const { BUILDING_PROFILES, column, nameColumn, appSpec, provisionInput, watchedDeps } = require('./helpers/column-gate-specs.js');++const FORMAT_FINDING = 'entity new_ticket: column new_ref is an AutoNumber column but its autoNumberFormat is missing — give it a format such as "C-{SEQNUM:5}", or use type "Text" for a plain text column';+const OMIT_THE_KEY = "omit the key to leave an existing column's level as it is";+const COLUMN_FINDING = `entity new_ticket: column new_status required must be true, false or "recommended" (got "true") — write true for a required column; ${OMIT_THE_KEY}`;+const PRIMARY_FINDING = `entity new_ticket: primaryAttribute.required must be true, false or "recommended" (got "ApplicationRequired") — write true for a required column; ${OMIT_THE_KEY}`;++// Both rules broken at once, in an order the validator reports them: the name column first, then each column in turn.+const olderSpec = () => appSpec({+ columns: [column({ type: 'AutoNumber' }), column({ schemaName: 'new_status', type: 'Text', required: 'true' })],+ primaryAttribute: nameColumn({ required: 'ApplicationRequired' }),+});+const FINDINGS = [PRIMARY_FINDING, FORMAT_FINDING, COLUMN_FINDING];++// --- the downgrade, as validateAppSpec takes it -----------------------------------------------------------------------------------++test('columnValues: "warn" moves the findings of both rules from errors to warnings, in the wording they have as errors, and moves nothing else', () => {+ const strict = validateAppSpec(olderSpec(), { profile: 'deploy' });+ assert.deepStrictEqual(strict.errors, FINDINGS);+ assert.deepStrictEqual(strict.warnings, []);++ const lenient = validateAppSpec(olderSpec(), { profile: 'deploy', columnValues: 'warn' });+ assert.strictEqual(lenient.ok, true, JSON.stringify(lenient.errors));+ assert.deepStrictEqual(lenient.errors, []);+ assert.deepStrictEqual(lenient.warnings, FINDINGS, 'the same sentences, as warnings');++ // Any other problem of the spec is still an error beside them.+ const spec = olderSpec();+ spec.entities[0].columns.push(column({ schemaName: 'new_bad', type: 'Nope' }));+ const mixed = validateAppSpec(spec, { profile: 'deploy', columnValues: 'warn' });+ assert.strictEqual(mixed.ok, false);+ assert.deepStrictEqual(mixed.errors, ["entity new_ticket: column new_bad has unknown type 'Nope'"]);+ assert.deepStrictEqual(mixed.warnings, FINDINGS);+});++test('only the value "warn" downgrades, and relationshipCollisions: "warn" alone does not', () => {+ for (const options of [{}, { columnValues: undefined }, { columnValues: true }, { columnValues: 'error' }, { columnValues: 'WARN' }, { columnValues: 'warning' }, { relationshipCollisions: 'warn' }]) {+ const result = validateAppSpec(olderSpec(), { profile: 'deploy', ...options });+ assert.strictEqual(result.ok, false, JSON.stringify(options));+ assert.deepStrictEqual(result.errors, FINDINGS, JSON.stringify(options));+ }+ // And the two downgrades are independent: columnValues leaves a relationship-name collision an error.+ const collision = { ...olderSpec(), relationships: [+ { type: 'OneToMany', referenced: 'new_ticket', referencing: 'new_ticket', lookup: { schemaName: 'new_ParentId', displayName: 'Parent' } },+ { type: 'ManyToMany', entity1: 'new_ticket', entity2: 'new_ticket' },+ ] };+ const both = validateAppSpec(collision, { profile: 'deploy', columnValues: 'warn', relationshipCollisions: 'warn' });+ assert.strictEqual(both.ok, true, JSON.stringify(both.errors));+ const columnsOnly = validateAppSpec(collision, { profile: 'deploy', columnValues: 'warn' });+ assert.strictEqual(columnsOnly.ok, false, 'a collision is still an error when only the column rules are downgraded');+ assert.ok(columnsOnly.errors.some((e) => /both use the schema name/.test(e)), JSON.stringify(columnsOnly.errors));+});++test('the structural profile, which never held a spec to these rules, says nothing about them with or without the option', () => {+ for (const options of [{}, { columnValues: 'warn' }]) {+ const result = validateAppSpec(olderSpec(), { profile: 'structural', ...options });+ assert.deepStrictEqual(result.errors, [], JSON.stringify(options));+ assert.deepStrictEqual(result.warnings, [], JSON.stringify(options));+ }+});++test('a spec that satisfies both rules has no finding to move: the result is the same with and without the option', () => {+ const spec = appSpec({ columns: [column({ type: 'AutoNumber', autoNumberFormat: 'C-{SEQNUM:5}', required: 'recommended' })], primaryAttribute: nameColumn({ required: true }) });+ const strict = validateAppSpec(spec, { profile: 'deploy' });+ const lenient = validateAppSpec(spec, { profile: 'deploy', columnValues: 'warn' });+ assert.deepStrictEqual(lenient, strict);+ assert.deepStrictEqual(strict.errors, []);+});++// --- every authoring path keeps them as errors ------------------------------------------------------------------------------------++test('lint (the authoring flow\'s gate, which defaults to the plan profile) reports both rules as schema errors under every profile that builds', () => {+ for (const options of [undefined, ...BUILDING_PROFILES.map((profile) => ({ profile }))]) {+ const report = lintSpec(olderSpec(), options);+ const label = JSON.stringify(options);+ assert.strictEqual(report.ok, false, label);+ for (const finding of FINDINGS) assert.ok(report.errors.includes(`schema: ${finding}`), `${label}: ${finding}\n${JSON.stringify(report.errors)}`);+ assert.ok(!report.warnings.some((w) => FINDINGS.some((f) => w.includes(f))), `${label}: none of them is only a warning`);+ }+});++test('the build refuses both rules before any call — dry run or apply, under the default and the plan profile', async () => {+ for (const options of [{ apply: true }, { apply: false }, { apply: true, profile: 'plan' }, { apply: false, profile: 'deploy' }]) {+ const d = watchedDeps();+ const result = await buildModelApp(olderSpec(), { env: 'https://x', ...options }, { sdk: d.sdk, provisionSdk: d.provision });+ const label = JSON.stringify(options);+ assert.strictEqual(result.ok, false, label);+ assert.deepStrictEqual(result.errors, FINDINGS, label);+ assert.deepStrictEqual(d.touched, [], `${label}: nothing was called`);+ }+});++test('the provision-entities gate has no downgrade: it refuses both rules, however it is called, before anything is called', async () => {+ const input = () => provisionInput({+ columns: [column({ type: 'AutoNumber' }), column({ schemaName: 'new_status', type: 'Text', required: 'true' })],+ primaryAttribute: nameColumn({ required: 'ApplicationRequired' }),+ });+ // An extra argument is ignored: the validator takes the input and nothing else.+ const validated = validateProvisionInput(input(), { columnValues: 'warn' });+ assert.strictEqual(validated.ok, false);+ assert.strictEqual(validated.errors.length, 3, JSON.stringify(validated.errors));+ for (const options of [{ apply: true }, { apply: false }]) {+ const d = watchedDeps();+ const result = await provisionEntities(input(), options, { sdk: d.sdk, provision: d.provision });+ assert.strictEqual(result.ok, false, JSON.stringify(options));+ assert.strictEqual(result.errors.length, 3, JSON.stringify(result.errors));+ assert.deepStrictEqual(d.touched, [], `${JSON.stringify(options)}: nothing was called`);+ }+});++test('no script but the verify CLI passes the downgrade', () => {+ assert.deepStrictEqual(scriptsMatching(/columnValues\s*:\s*['"]warn['"]/), ['verify-model-app.js']);+});diff --git a/plugins/model-apps/scripts/tests/dashboard-tiles.test.js b/plugins/model-apps/scripts/tests/dashboard-tiles.test.jsnew file mode 100644index 000000000..e501375b7--- /dev/null+++ b/plugins/model-apps/scripts/tests/dashboard-tiles.test.js@@ -0,0 +1,56 @@+'use strict';+// lib/dashboard-tiles.js: which tile of a deployed dashboard a custom control hosts. The download (which leaves such a tile out of+// the spec) and verify (which does not hold it to a chart and view of its table) share this one classification, so it is pinned+// here once — and so is the fact that neither of them keeps a copy of its own.+const test = require('node:test');+const assert = require('node:assert');+const fs = require('node:fs');+const path = require('node:path');+const { hostsCustomControl, NATIVE_GRID_CLASS_ID } = require('../lib/dashboard-tiles.js');++const CUSTOM = '{F9A8A302-114E-466A-B582-6771B2AE0D92}';++test('a list or chart tile on the native grid class is not hosted, in any spelling of the class', () => {+ const spellings = [+ '{E7A81278-8635-4d9e-8D4D-59480B391C5B}', // as the platform writes it in a dashboard+ '{E7A81278-8635-4D9E-8D4D-59480B391C5B}',+ '{e7a81278-8635-4d9e-8d4d-59480b391c5b}',+ 'E7A81278-8635-4D9E-8D4D-59480B391C5B',+ 'e7a81278-8635-4d9e-8d4d-59480b391c5b',+ ];+ for (const type of ['list', 'chart']) {+ for (const classId of spellings) assert.strictEqual(hostsCustomControl({ type, classId }), false, `${type} on ${classId}`);+ }+});++test('a list or chart tile on any other class is hosted by a custom control', () => {+ const others = [CUSTOM, CUSTOM.toLowerCase(), CUSTOM.replace(/[{}]/g, ''), '{00000000-0000-4000-8000-000000000000}', '{E7A81278-8635-4D9E-8D4D-59480B391C5C}'];+ for (const type of ['list', 'chart']) {+ for (const classId of others) assert.strictEqual(hostsCustomControl({ type, classId }), true, `${type} on ${classId}`);+ }+});++test('a tile with no class is read as native, and a tile of any other type is never reported', () => {+ for (const component of [{ type: 'list' }, { type: 'chart' }, { type: 'chart', classId: '' }, { type: 'list', classId: null }, { type: 'chart', classId: '{}' }]) {+ assert.strictEqual(hostsCustomControl(component), false, JSON.stringify(component));+ }+ // The Assistant, a custom control that is no grid or chart, an iframe and a web resource keep the handling they always had.+ for (const type of ['assistant', 'unknown', 'iframe', 'webresource', 'timeline', 'powerbi', 'stream', undefined]) {+ assert.strictEqual(hostsCustomControl({ type, classId: CUSTOM }), false, String(type));+ }+ for (const component of [null, undefined, {}]) assert.strictEqual(hostsCustomControl(component), false, String(component));+});++test('the native class is the bare upper-case GUID the comparison makes of every spelling', () => {+ assert.strictEqual(NATIVE_GRID_CLASS_ID, 'E7A81278-8635-4D9E-8D4D-59480B391C5B');+});++test('the download and verify use this classification, and neither defines one of its own', () => {+ const scripts = path.resolve(__dirname, '..');+ for (const file of ['download-model-app.js', path.join('lib', 'verify-spec.js')]) {+ const source = fs.readFileSync(path.join(scripts, file), 'utf8');+ assert.match(source, /const \{ hostsCustomControl \} = require\('\.\/(?:lib\/)?dashboard-tiles\.js'\);/, `${file} requires lib/dashboard-tiles.js`);+ assert.match(source, /\bhostsCustomControl\(/, `${file} asks it`);+ assert.doesNotMatch(source, /\b(?:const|let|function)\s+(?:hostsCustomControl|NATIVE_GRID_CLASS_ID|bareClassId)\b/, `${file} keeps no copy of it`);+ }+});diff --git a/plugins/model-apps/scripts/tests/download-dashboard-custom-control.test.js b/plugins/model-apps/scripts/tests/download-dashboard-custom-control.test.jsnew file mode 100644index 000000000..f3a26fd4e--- /dev/null+++ b/plugins/model-apps/scripts/tests/download-dashboard-custom-control.test.js@@ -0,0 +1,144 @@+'use strict';+// REAL BUNDLE: a dashboard tile that hosts a custom control (the Power Apps grid, say) is named and left out of the+// downloaded spec, never emitted as a plain tile.+//+// The SDK types a dashboard tile by its control's class. The custom-control class used to be read as the Assistant+// whatever it hosted, so such a tile was never a list or a chart; the SDK now types a grid or a chart that a custom+// control hosts by the grid parameters it carries, so the tile reads exactly like a native one — the same+// `TargetEntityType`, `ViewId` and `ChartGridMode` — and differs only by its class. `readDashboards` emits a list or chart+// tile from those parameters, so it would hand back a plain tile for the maker's control: a rebuild into another+// environment would then create the plain grid where the control was, and nothing would have said so.+//+// The App Spec cannot express a custom control, so the tile is left out and the download says which one, as it does for+// every other tile it cannot rebuild. A rebuild into the same environment is not touched by this either way: the spec+// pins the dashboard by its id, and the build reuses a dashboard that exists without applying tile edits.+const test = require('node:test');+const assert = require('node:assert');+const { readDashboards } = require('../download-model-app.js');+const { hydrateSpec } = require('../lib/hydrate-spec.js');+const { runSdkBuild } = require('../lib/sdk-build.js');+const { createHarness } = require('./helpers/form-store-harness.js');++const DASHBOARD_ID = '33333333-3333-4333-8333-333333333333';+const OPEN_VIEW = '11111111-0000-4000-8000-0000000000a1';+const MINE_VIEW = '11111111-0000-4000-8000-0000000000a2';+const CHART_VIEW = '11111111-0000-4000-8000-0000000000a3';+const CHART = '22222222-0000-4000-8000-0000000000b1';+const CUSTOM_CHART = '22222222-0000-4000-8000-0000000000b2';++const {+ NATIVE_CLASS, CUSTOM_CLASS, nativeGrid, nativeChart, customGrid, customChart, iframeTile, webResourceTile, customDescription, dashboardXml,+} = require('./helpers/dashboard-formxml.js');++const GRID_UNIQUE = 'cccccccc-0000-4000-8000-000000000001';+const CHART_UNIQUE = 'cccccccc-0000-4000-8000-000000000002';++const harnesses = [];+test.after(() => { for (const h of harnesses) h.cleanup(); });++// A harness whose one row is a dashboard (systemform type 0) holding `formxml`, and an SDK over it.+async function dashboardOver(formxml) {+ const h = createHarness({ formId: DASHBOARD_ID, entity: 'incident', formName: 'Support board' });+ harnesses.push(h);+ h.store.row = { formid: DASHBOARD_ID, name: 'Support board', description: 'The support lead\u2019s view.', objecttypecode: 'none', type: 0, formxml };+ const { sdk } = await h.freshSdk();+ const app = { siteMap: { areas: [{ groups: [{ subAreas: [{ type: 'DashBoard', dashboardId: DASHBOARD_ID, title: 'Support board' }] }] }] } };+ return { h, sdk, app };+}++const ordinaryTiles = [+ { type: 'list', name: 'Open cases', entity: 'incident', viewId: OPEN_VIEW },+ { type: 'chart', name: 'Cases by status', entity: 'incident', viewId: CHART_VIEW, visualizationId: CHART },+];++test('a dashboard of native tiles downloads as it always did: a list, a chart, an iframe and a web resource, with nothing said', async () => {+ const { sdk, app } = await dashboardOver(dashboardXml([+ [nativeGrid('Component1', 'Open cases', OPEN_VIEW), nativeChart('Component2', 'Cases by status', CHART_VIEW, CHART)],+ [iframeTile('Component3', 'Knowledge', 'https://contoso.example/help'), webResourceTile('Component4', 'Welcome', 'new_welcome.htm')],+ ]));+ const warnings = [];+ const dashboards = await readDashboards(sdk, app, (m) => warnings.push(m));+ assert.deepStrictEqual(dashboards.map((d) => [d.id, d.name]), [[DASHBOARD_ID, 'Support board']]);+ assert.deepStrictEqual(dashboards[0].tiles, [+ ...ordinaryTiles,+ { type: 'iframe', name: 'Knowledge', url: 'https://contoso.example/help' },+ { type: 'webresource', name: 'Welcome', webResource: 'new_welcome.htm' },+ ]);+ assert.deepStrictEqual(warnings, []);+});++test('the SDK reads a tile a custom control hosts like a native one — the same type and parameters — and tells it apart only by its class', async () => {+ // The premise of everything below. If a later bundle stops exposing the class, or types such a tile differently, this+ // fails first and the download has to be looked at again.+ const { sdk } = await dashboardOver(dashboardXml([+ [nativeGrid('Component1', 'Open cases', OPEN_VIEW), customGrid('Component2', 'My cases', MINE_VIEW, GRID_UNIQUE)],+ ], [customDescription(GRID_UNIQUE, MINE_VIEW)]));+ await sdk.fetchArtifact('dashboard', DASHBOARD_ID);+ const [native, hosted] = (await sdk.getArtifact('dashboard', DASHBOARD_ID)).components;+ assert.deepStrictEqual([native.type, hosted.type], ['list', 'list']);+ assert.deepStrictEqual(hosted.parameters.TargetEntityType, native.parameters.TargetEntityType);+ assert.strictEqual(hosted.parameters.ViewId, `{${MINE_VIEW}}`);+ assert.strictEqual(native.classId.replace(/[{}]/g, '').toUpperCase(), NATIVE_CLASS.replace(/[{}]/g, '').toUpperCase());+ assert.strictEqual(hosted.classId.replace(/[{}]/g, '').toUpperCase(), CUSTOM_CLASS.replace(/[{}]/g, '').toUpperCase());+});++test('a tile a custom control hosts is named and left out, not emitted as a plain tile; the dashboard\u2019s other tiles download as before', async () => {+ const { sdk, app } = await dashboardOver(dashboardXml([+ [nativeGrid('Component1', 'Open cases', OPEN_VIEW), customGrid('Component2', 'My cases (grid control)', MINE_VIEW, GRID_UNIQUE)],+ [nativeChart('Component3', 'Cases by status', CHART_VIEW, CHART), customChart('Component4', 'Escalations (chart control)', CHART_VIEW, CUSTOM_CHART, CHART_UNIQUE)],+ ], [customDescription(GRID_UNIQUE, MINE_VIEW), customDescription(CHART_UNIQUE, CHART_VIEW)]));+ const warnings = [];+ const dashboards = await readDashboards(sdk, app, (m) => warnings.push(m));++ assert.deepStrictEqual(dashboards[0].tiles, ordinaryTiles, 'only the native tiles are emitted');+ assert.strictEqual(warnings.length, 2, JSON.stringify(warnings));+ assert.match(warnings[0], /^dashboard 'Support board' tile 'My cases \(grid control\)' hosts a custom control, which the App Spec cannot express, so it is omitted from dashboards\[\]\./);+ assert.match(warnings[1], /^dashboard 'Support board' tile 'Escalations \(chart control\)' hosts a custom control/);+ // What a rebuild does to it, so the maker knows where the control stays and where it has to be put back.+ assert.match(warnings[0], /into this environment keeps the dashboard as it is[^.]*\./);+ assert.match(warnings[0], /into another environment creates it without this tile/);+});++test('a dashboard whose only tile hosts a custom control is dropped, and its navigation entry counts as dropped — what the lossy-download gate refuses on', async () => {+ const { sdk, app } = await dashboardOver(dashboardXml([+ [customGrid('Component1', 'My cases (grid control)', MINE_VIEW, GRID_UNIQUE)],+ ], [customDescription(GRID_UNIQUE, MINE_VIEW)]));+ const warnings = [];+ const dashboards = await readDashboards(sdk, app, (m) => warnings.push(m));+ assert.deepStrictEqual(dashboards, []);+ assert.ok(warnings.some((w) => /tile 'My cases \(grid control\)' hosts a custom control/.test(w)), JSON.stringify(warnings));+ assert.ok(warnings.some((w) => /read OK but produced no recognizable tiles .*its sitemap subarea will be dropped/.test(w)), JSON.stringify(warnings));++ // The subarea is then counted as dropped, which is what the download's lossy-download gate refuses on.+ const spec = await hydrateSpec({+ app: async () => ({ name: 'Support', description: '', uniquename: 'new_support', siteMap: app.siteMap }),+ pages: async () => [], entities: async () => [], webResources: async () => [],+ solution: async () => ({ uniqueName: 'Support', publisherPrefix: 'new' }),+ dashboards: async () => dashboards,+ });+ assert.strictEqual(spec.droppedSubareas, 1);+});++test('a rebuild into the same environment leaves the dashboard, and so the control, as it is', async () => {+ const hosted = dashboardXml([+ [nativeGrid('Component1', 'Open cases', OPEN_VIEW), customGrid('Component2', 'My cases (grid control)', MINE_VIEW, GRID_UNIQUE)],+ ], [customDescription(GRID_UNIQUE, MINE_VIEW)]);+ const { h, sdk, app } = await dashboardOver(hosted);+ const dashboards = await readDashboards(sdk, app);+ const spec = await hydrateSpec({+ app: async () => ({ name: 'Support', description: '', uniquename: 'new_support', siteMap: app.siteMap }),+ pages: async () => [], entities: async () => [], webResources: async () => [],+ solution: async () => ({ uniqueName: 'Support', publisherPrefix: 'new' }),+ dashboards: async () => dashboards,+ });+ assert.deepStrictEqual(spec.dashboards.map((d) => [d.name, d.dashboardId, d.tiles.length]), [['Support board', DASHBOARD_ID, 1]], 'the spec pins the dashboard it was read from');++ const before = h.writes.length;+ const { sdk: rebuilding } = await h.freshSdk();+ const events = [];+ const built = await runSdkBuild(spec, { sdk: rebuilding, apply: true, phases: ['dashboards'], emit: (e) => events.push(e), warn: () => {} });+ assert.strictEqual(built.ok, true);+ assert.deepStrictEqual(h.writes.slice(before).filter((w) => w.method === 'patch' || (w.method === 'post' && /\/systemforms(?:\?|$)/.test(w.url))), [], 'no write reaches the dashboard');+ assert.strictEqual(h.store.row.formxml, hosted, 'its FormXML is unchanged, the hosted control included');+ assert.ok(events.some((e) => e.status === 'skip' && /dashboard "Support board" \(exists — reuse by its dashboardId/.test(e.label)), JSON.stringify(events.map((e) => [e.status, e.label])));+});diff --git a/plugins/model-apps/scripts/tests/download-navigation-language.test.js b/plugins/model-apps/scripts/tests/download-navigation-language.test.jsnew file mode 100644index 000000000..be2245795--- /dev/null+++ b/plugins/model-apps/scripts/tests/download-navigation-language.test.js@@ -0,0 +1,251 @@+'use strict';+// A download writes a rebuildable spec only in a language it KNOWS. The navigation titles it writes are read in the language a rebuild will resolve (the spec on disk's pinned+// `languageCode`, else the environment's base language), and a spec written with the titles of a GUESSED language is worse than none: on a bilingual environment whose base+// language is Spanish, a download whose read of the base language failed fell back to 1033 and wrote the ENGLISH titles as the area and group labels, and a later rebuild, which+// does resolve 3082, wrote them over the Spanish ones — with the spec valid and the baseline matching, so nothing said so.+//+// The build, asked for the same language when the read fails, warns and uses 1033 (resolveLanguageCode), and `--verify`, which describes a deployment as a download does, refuses to+// assume one (its `undetermined` hook). A download describes a deployment, and its output is consumed by a build that may resolve another language, so it is held to the stricter rule: when+// neither `--language-code` nor a spec on disk gives the language and the environment will not say, it stops, writes nothing and says how to go on.+//+// These run `main` — the real `makeDownloadSdk`, the real SDK and the plugin's own HTTP client over a fake Dataverse (helpers/app-sitemap-org.js) — up to and through the point it+// hands the spec to the writer, with `runDownload` replaced by the one read this is about: the app's navigation, hydrated into the App Spec.+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 { main, makeDownloadSdk } = require('../download-model-app.js');+const { hydrateSpec } = require('../lib/hydrate-spec.js');+const { createSitemapOrg, sitemapXml, json, ENV, APP_ID, APP_UNIQUE, DASH } = require('./helpers/app-sitemap-org.js');++const tempDirs = [];+test.after(() => { for (const dir of tempDirs) fs.rmSync(dir, { recursive: true, force: true }); });+const tmp = (prefix) => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));+ tempDirs.push(dir);+ return dir;+};++// Every node holds its title in both languages: a bilingual environment. Its base language is the one the spec's labels must be written in.+const BOTH = { area: { 1033: 'Work', 3082: 'Trabajo' }, group: { 1033: 'Cases', 3082: 'Casos' }, dashboard: { 1033: 'Case dashboard', 3082: 'Panel de casos' } };+const ENGLISH = { area: { 1033: 'Work' }, group: { 1033: 'Cases' }, dashboard: { 1033: 'Case dashboard' } };+const REFUSED = () => json(403, { error: { message: 'the caller has no read privilege on the organization table' } });+const labelsOf = (spec) => ({ area: spec.appShell.areas[0].label, group: spec.appShell.areas[0].groups[0].label });+const asksForLanguage = (org) => org.requests.filter((r) => /\/organizations\?/.test(r.path));++/**+ * `main`, as the CLI runs it, over `org`. `disk` is what the output folder holds before the run: `{ spec, baseline }`, each written as given (an object as JSON). Returns what was printed,+ * how many times the download was asked to read the app (`runs`), and the folder's files.+ */+async function runMain(org, { argv = [], disk = {} } = {}) {+ const outDir = tmp('download-language-');+ if (disk.spec !== undefined) fs.writeFileSync(path.join(outDir, 'app-spec.json'), typeof disk.spec === 'string' ? disk.spec : JSON.stringify(disk.spec));+ if (disk.baseline !== undefined) {+ fs.mkdirSync(path.join(outDir, '.maker-workspace'));+ fs.writeFileSync(path.join(outDir, '.maker-workspace', 'last-applied.json'), disk.baseline);+ }+ const results = [];+ const stderr = [];+ const exits = [];+ let runs = 0;+ const deps = {+ argv: ['--env', ENV, '--app', APP_UNIQUE, '--out', outDir, ...argv],+ stderr: { write: (text) => { stderr.push(String(text)); } },+ exit: (code) => { exits.push(code); },+ emitResult: (ok, payload) => results.push({ ok, payload }),+ preflightAuth: async () => ({ ok: true }),+ makeGenpageSdk: () => ({}),+ httpClient: org.httpClient,+ runDownload: async ({ sdk }) => {+ runs += 1;+ const app = await sdk.fetchArtifact('app', APP_ID);+ const hydrated = await hydrateSpec({+ app: async () => ({ ...app, uniquename: APP_UNIQUE }),+ pages: async () => [],+ entities: async () => [],+ webResources: async () => [],+ solution: async () => ({ uniqueName: 'ContosoCases', publisherPrefix: 'contoso' }),+ dashboards: async () => [{ id: DASH, name: 'Case overview', tiles: [] }],+ });+ return {+ ok: true,+ spec: { schemaVersion: 2, solution: { uniqueName: 'ContosoCases', publisherPrefix: 'contoso' }, app: { name: 'Case Management', uniqueName: APP_UNIQUE }, entities: [], pages: [], appShell: hydrated.appShell },+ pages: [], entities: [], webResources: [], droppedSubareas: 0, droppedSubareaDetails: [], dashboardWarnings: [],+ };+ },+ validateAppSpec: () => ({ ok: true, warnings: [] }),+ };+ await main(deps);+ const files = (dir) => (fs.existsSync(dir) ? fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? files(path.join(dir, e.name)).map((f) => `${e.name}/${f}`) : [e.name])).sort() : []);+ return {+ results,+ stderr: stderr.join(''),+ exits,+ runs,+ files: files(outDir),+ spec: () => JSON.parse(fs.readFileSync(path.join(outDir, 'app-spec.json'), 'utf8')),+ read: (name) => fs.readFileSync(path.join(outDir, name), 'utf8'),+ };+}++const SPANISH_BASE = () => createSitemapOrg({ xml: sitemapXml(BOTH), baseLanguage: 3082, organizationAnswer: REFUSED });++// --- the language cannot be established ---------------------------------------------------------------------------------------------------------------------------++test('a bilingual environment whose base language is Spanish and whose base language is refused gets no spec: the English titles are not written as the labels', async () => {+ const run = await runMain(SPANISH_BASE());+ assert.strictEqual(run.runs, 0, 'nothing was read with a language that is a guess');+ assert.deepStrictEqual(run.files, [], 'and nothing was written');+ assert.strictEqual(run.results.length, 1);+ const [{ ok, payload }] = run.results;+ assert.strictEqual(ok, false);+ assert.strictEqual(payload.ok, false);+ assert.strictEqual(payload.code, 'navigation-language-unknown');+ // Actionable: why, that nothing was written, and the three ways on — again, the flag the build and verify take, or a pin in the spec.+ assert.match(payload.error, /base language could not be read \(HTTP 403\)/);+ assert.match(payload.error, /Nothing was written/);+ assert.match(payload.error, /again/);+ assert.match(payload.error, /--language-code <lcid>/);+ assert.match(payload.error, /"languageCode"/);+ assert.match(payload.error, /app-spec\.json/);+});++test('a spec and a baseline already on disk are not overwritten by a download that could not establish the language', async () => {+ const spec = JSON.stringify({ app: { name: 'Case Management' }, appShell: { areas: [{ label: 'Trabajo', groups: [{ label: 'Casos', subAreas: [] }] }] } }, null, 2);+ const baseline = JSON.stringify({ marker: 'baseline written by the last apply' });+ const run = await runMain(SPANISH_BASE(), { disk: { spec, baseline } });+ assert.strictEqual(run.results[0].payload.code, 'navigation-language-unknown');+ assert.strictEqual(run.read('app-spec.json'), spec, 'the spec on disk is byte for byte what it was');+ assert.strictEqual(run.read('.maker-workspace/last-applied.json'), baseline, 'and so is the baseline');+ assert.deepStrictEqual(run.files, ['.maker-workspace/last-applied.json', 'app-spec.json']);+});++test('every way the base language fails to be read is a refusal that says what happened', async () => {+ for (const [what, answer, why] of [+ ['a refusal', () => json(403, { error: { message: 'no read privilege' } }), /\(HTTP 403\)/],+ ['a service that stays unavailable through the client\u2019s own retries', () => json(503, { error: { message: 'busy' } }), /\(HTTP 503\)/],+ ['an answer with no organization', () => json(200, { value: [] }), /\(the answer named no language\)/],+ ['a language that is no LCID', () => json(200, { value: [{ languagecode: 'es-ES' }] }), /\(the answer named no language\)/],+ ['a request that failed', () => ({ error: 'socket hang up' }), /\(.*socket hang up.*\)/],+ ]) {+ const run = await runMain(createSitemapOrg({ xml: sitemapXml(BOTH), baseLanguage: 3082, organizationAnswer: answer }));+ assert.strictEqual(run.runs, 0, what);+ assert.deepStrictEqual(run.files, [], what);+ assert.strictEqual(run.results[0].payload.code, 'navigation-language-unknown', what);+ assert.match(run.results[0].payload.error, why, `${what}: ${run.results[0].payload.error}`);+ }+});++test('a service that is unavailable for a moment is not a refusal: the client\u2019s own retry reads the language, and the download goes on in it', async () => {+ let answered = 0;+ const org = createSitemapOrg({+ xml: sitemapXml(BOTH),+ baseLanguage: 3082,+ organizationAnswer: () => ((answered += 1) <= 2 ? json(503, { error: { message: 'busy' } }) : json(200, { value: [{ languagecode: 3082 }] })),+ });+ const run = await runMain(org);+ assert.strictEqual(run.results[0].ok, true, JSON.stringify(run.results[0]));+ assert.deepStrictEqual(labelsOf(run.spec()), { area: 'Trabajo', group: 'Casos' });+ assert.ok(answered >= 3, 'the read was sent again');+});++// --- a language the download is given -----------------------------------------------------------------------------------------------------------------------------++test('--language-code names the language the titles are read in, and the environment is not asked', async () => {+ for (const flag of ['--language-code', '--languageCode']) {+ const org = SPANISH_BASE();+ const run = await runMain(org, { argv: [flag, '3082'] });+ assert.strictEqual(run.results[0].ok, true, `${flag}: ${JSON.stringify(run.results[0])}`);+ assert.deepStrictEqual(labelsOf(run.spec()), { area: 'Trabajo', group: 'Casos' }, flag);+ assert.deepStrictEqual(asksForLanguage(org), [], `${flag}: it is given, so it is not read`);+ // A reading instruction, like the flag of the build: the spec is not pinned to it, so it stays what every other environment can rebuild.+ assert.strictEqual('languageCode' in run.spec(), false, flag);+ }+});++test('--language-code is read exactly as the build and verify read it: an LCID, one spelling, no conflict', async () => {+ for (const [argv, said] of [+ [['--language-code', 'es-ES'], /--language-code \/ --languageCode must be digits only, a positive integer LCID up to 65535 \(got 'es-ES'\)/],+ [['--language-code', '0'], /must be digits only/],+ [['--language-code', '70000'], /must be digits only/],+ [['--language-code', '1031', '--languageCode', '1036'], /--language-code '1031' and --languageCode '1036' disagree — pass only one/],+ ]) {+ const org = SPANISH_BASE();+ const run = await runMain(org, { argv });+ assert.deepStrictEqual(run.exits, [1], argv.join(' '));+ assert.match(run.stderr, said, argv.join(' '));+ assert.match(run.stderr, /Usage: node download-model-app\.js .*\[--language-code <lcid>\]/, 'the usage line names the flag');+ assert.deepStrictEqual(run.results, [], 'nothing is printed as a result');+ assert.deepStrictEqual(org.requests, [], 'no request was made');+ }+});++test('the usage line names --language-code, and a misspelling of it is a usage error that suggests it', async () => {+ const run = await runMain(SPANISH_BASE(), { argv: ['--language-cod', '3082'] });+ assert.deepStrictEqual(run.exits, [1]);+ assert.match(run.stderr, /--language-cod \(did you mean --language-code\?\)/);+ assert.match(run.stderr, /\[--language-code <lcid>\]/);+});++test('a language pinned in the spec on disk keeps bypassing the read, and the spec that is written keeps the pin', async () => {+ const org = SPANISH_BASE();+ const run = await runMain(org, { disk: { spec: { languageCode: 3082 } } });+ assert.strictEqual(run.results[0].ok, true, JSON.stringify(run.results[0]));+ assert.deepStrictEqual(labelsOf(run.spec()), { area: 'Trabajo', group: 'Casos' });+ assert.strictEqual(run.spec().languageCode, 3082);+ assert.deepStrictEqual(asksForLanguage(org), []);+});++test('a flag that names another language than the spec on disk pins is refused: the titles would be read in one language and rebuilt in the other', async () => {+ const spec = JSON.stringify({ languageCode: 1036 });+ const run = await runMain(SPANISH_BASE(), { argv: ['--language-code', '3082'], disk: { spec } });+ assert.strictEqual(run.runs, 0);+ assert.strictEqual(run.results[0].ok, false);+ assert.strictEqual(run.results[0].payload.code, 'navigation-language-conflict');+ assert.match(run.results[0].payload.error, /--language-code 3082 .*"languageCode": 1036/);+ assert.strictEqual(run.read('app-spec.json'), spec, 'nothing is overwritten');+ // The same language in both is not a conflict.+ const agreeing = await runMain(SPANISH_BASE(), { argv: ['--language-code', '3082'], disk: { spec: JSON.stringify({ languageCode: 3082 }) } });+ assert.strictEqual(agreeing.results[0].ok, true, JSON.stringify(agreeing.results[0]));+});++// --- the language is read ----------------------------------------------------------------------------------------------------------------------------------------++test('an environment whose base language is read downloads as it did: the labels in that language, no pin, and one read of the language', async () => {+ const spanish = createSitemapOrg({ xml: sitemapXml(BOTH), baseLanguage: 3082 });+ const run = await runMain(spanish);+ assert.strictEqual(run.results[0].ok, true);+ assert.deepStrictEqual(labelsOf(run.spec()), { area: 'Trabajo', group: 'Casos' });+ assert.strictEqual('languageCode' in run.spec(), false);+ assert.strictEqual(asksForLanguage(spanish).length, 1);+ assert.deepStrictEqual(run.files, ['.maker-workspace/last-applied.json', 'app-spec.json']);++ const english = createSitemapOrg({ xml: sitemapXml(ENGLISH), baseLanguage: 1033 });+ const run1033 = await runMain(english);+ assert.strictEqual(run1033.results[0].ok, true);+ assert.deepStrictEqual(labelsOf(run1033.spec()), { area: 'Work', group: 'Cases' });+ assert.strictEqual('languageCode' in run1033.spec(), false);+ assert.strictEqual(asksForLanguage(english).length, 1);+});++// --- what makeDownloadSdk says -----------------------------------------------------------------------------------------------------------------------------------++test('makeDownloadSdk says where the language came from, or that it has none, and never falls back to one', async () => {+ const made = async (org, deps = {}) => {+ const session = await makeDownloadSdk(ENV, { httpClient: org.httpClient, ...deps });+ session.cleanup();+ return session;+ };+ const read = await made(createSitemapOrg({ xml: sitemapXml(BOTH), baseLanguage: 3082 }));+ assert.deepStrictEqual([read.languageCode, read.languageSource, read.languageUnresolved], [3082, 'environment', undefined]);+ const pinned = await made(SPANISH_BASE(), { authoredLanguageCode: 1036 });+ assert.deepStrictEqual([pinned.languageCode, pinned.languageSource], [1036, 'spec']);+ const flagged = await made(SPANISH_BASE(), { languageCode: 3082, authoredLanguageCode: 1036 });+ assert.deepStrictEqual([flagged.languageCode, flagged.languageSource], [3082, 'flag'], 'the flag outranks the pin, as it does for the build');+ const unknown = await made(SPANISH_BASE());+ assert.deepStrictEqual([unknown.languageCode, unknown.languageSource], [undefined, undefined]);+ assert.match(unknown.languageUnresolved, /^HTTP 403$/);+ assert.ok(unknown.sdk, 'the SDK is still made: whoever refuses owns the refusal');+});diff --git a/plugins/model-apps/scripts/tests/download-workspace-isolation.test.js b/plugins/model-apps/scripts/tests/download-workspace-isolation.test.jsindex 86b6f6a9c..02c6701ac 100644--- a/plugins/model-apps/scripts/tests/download-workspace-isolation.test.js+++ b/plugins/model-apps/scripts/tests/download-workspace-isolation.test.js@@ -468,7 +468,7 @@ test('main wires the real download SDK factory to a throwaway workspace and stilstderr: { write: () => {} },emitResult: (ok, payload) => emitResults.push({ ok, payload }),preflightAuth: async () => ({ ok: true }),- createHttpClient: () => ({}),+ createHttpClient: () => ({ get: async () => ({ status: 200, headers: {}, body: { value: [{ languagecode: 1033 }] } }) }),createNodeWorkspaceStorage: (workspaceDir) => {constructed.push(workspaceDir);return { workspaceDir };diff --git a/plugins/model-apps/scripts/tests/entity-provision.test.js b/plugins/model-apps/scripts/tests/entity-provision.test.jsindex 6d93a6833..a4f620235 100644--- a/plugins/model-apps/scripts/tests/entity-provision.test.js+++ b/plugins/model-apps/scripts/tests/entity-provision.test.js@@ -283,6 +283,238 @@ test('provisionDataModel can reconcile required on the primary name column of an);});+// --- the primary name column's requirement level on a NEW table ---------------------------------------------------------------+// The table's create asks for it (`primaryColumnRequired`). The platform does not keep it on a plain text name column, so the SDK reads the+// level back after the create, sets it with an update where it differs, and answers the level it read (`primaryColumnRequired`) — or refuses+// with PRIMARY_COLUMN_REQUIRED_NOT_APPLIED, where the table WAS created. The build says the level was applied on create only when the SDK says so.+const primaryRequiredSpec = (primaryAttribute, columns = []) => ({ solution: { uniqueName: 'S', publisherPrefix: 'new' }, entities: [+ { schemaName: 'new_ticket', displayName: 'Ticket', primaryAttribute: { schemaName: 'new_name', displayName: 'Name', ...primaryAttribute }, columns },+], relationships: [] });+// createTable as the SDK answers it: the level it was asked for, read back, for a level other than None.+const confirmingCreate = (created) => async (o) => {+ created.push(o);+ const result = { logicalName: o.schemaName.toLowerCase(), entitySetName: `${o.schemaName.toLowerCase()}s`, metadataId: `tbl-${o.schemaName}` };+ if (o.primaryColumnRequired && o.primaryColumnRequired !== 'None') result.primaryColumnRequired = o.primaryColumnRequired;+ return result;+};+// What the SDK throws when the level cannot be confirmed: the table exists.+const notApplied = (cause) => Object.assign(+ new Error("Table 'new_ticket' WAS CREATED (MetadataId 11111111-2222-3333-4444-555555555555), but its primary column 'new_name' is still 'None' after the update to 'ApplicationRequired'. Do NOT re-run the create — it will collide on the schema name."),+ { code: 'PRIMARY_COLUMN_REQUIRED_NOT_APPLIED', ...(cause ? { cause } : {}) }+);+const requiredSteps = (events) => events.filter((e) => e.status !== 'start' && /^required /.test(e.label)).map((e) => `${e.status}: ${e.label}`);+async function buildPrimary(m, spec, extra = {}) {+ const events = [];+ const warnings = [];+ const error = await provisionDataModel({ sdk: m.sdk, provision: m.provision, runner: makeRunner({ emit: (e) => events.push(e), total: 10 }), spec, apply: true, preResolvedLanguageCode: 1033, warn: (w) => warnings.push(w), ...extra })+ .then(() => null, (err) => err);+ return { events, warnings, error };+}++test('a new table asks for its primary name column\'s required level in the create and reports it applied on create once the SDK confirms it', async () => {+ for (const [required, level] of [[true, 'ApplicationRequired'], ['recommended', 'Recommended']]) {+ const m = mockSdk();+ const created = [];+ m.sdk.createTable = confirmingCreate(created);+ const { events, warnings, error } = await buildPrimary(m, primaryRequiredSpec({ required }));+ assert.strictEqual(error, null);+ assert.strictEqual(created.length, 1);+ assert.strictEqual(created[0].primaryColumnRequired, level, 'the level is sent in the create');+ assert.deepStrictEqual(requiredSteps(events), ['skip: required new_ticket.new_name (applied on create)']);+ assert.ok(!m.calls.some((c) => c[0] === 'updateColumn'), 'the SDK sets a level the create did not keep; the build writes nothing of its own');+ assert.deepStrictEqual(warnings, []);+ }+});++test('an explicit required:false sends None, which has nothing to confirm, and an omitted required sends no level and says nothing about it', async () => {+ const m = mockSdk();+ const created = [];+ m.sdk.createTable = confirmingCreate(created);+ const none = await buildPrimary(m, primaryRequiredSpec({ required: false }));+ assert.strictEqual(none.error, null);+ assert.strictEqual(created[0].primaryColumnRequired, 'None');+ assert.deepStrictEqual(requiredSteps(none.events), ['skip: required new_ticket.new_name (applied on create)'], 'None is what the create always sent');+ assert.deepStrictEqual(none.warnings, []);++ const omitted = await buildPrimary(m, primaryRequiredSpec({}));+ assert.strictEqual(omitted.error, null);+ assert.ok(!('primaryColumnRequired' in created[1]), 'the create is the one it always was');+ assert.deepStrictEqual(requiredSteps(omitted.events), []);+});++test('a level the SDK does not confirm is not reported as applied: a failed step and a warning, and the build goes on', async () => {+ for (const [what, answer] of [['an SDK that says nothing about it', undefined], ['an answer that names another level', 'Recommended']]) {+ const m = mockSdk();+ m.sdk.createTable = async (o) => ({ logicalName: o.schemaName.toLowerCase(), entitySetName: `${o.schemaName.toLowerCase()}s`, metadataId: `tbl-${o.schemaName}`, ...(answer ? { primaryColumnRequired: answer } : {}) });+ const { events, warnings, error } = await buildPrimary(m, primaryRequiredSpec({ required: true }, [{ schemaName: 'new_priority', type: 'Text' }]));+ assert.strictEqual(error, null, `${what}: the build goes on`);+ assert.deepStrictEqual(requiredSteps(events), ['error: required new_ticket.new_name -> ApplicationRequired'], `${what}: never "applied on create"`);+ assert.strictEqual(warnings.length, 1);+ assert.strictEqual(warnings[0], `could not confirm the required level of new_ticket.new_name (ApplicationRequired) — a re-run sets it, and the rest of the build continues: the SDK confirmed ${answer ? `'${answer}'` : 'no level'} for the name column of the table it created`);+ assert.ok(m.calls.some((c) => c[0] === 'createColumn' && c[2] === 'new_priority'), `${what}: the table's other columns are still created`);+ }+});++test('a table found after its create (the answer was lost) is not reported as having its required level applied either', async () => {+ const m = mockSdk();+ let probes = 0;+ m.provision.findTables = async (s) => (++probes === 1 ? [] : [{ logicalName: s.toLowerCase(), entitySetName: `${s.toLowerCase()}s` }]);+ m.sdk.createTable = async () => { throw Object.assign(new Error('Entities already exist: new_ticket'), { statusCode: 400 }); };+ const { events, warnings, error } = await buildPrimary(m, primaryRequiredSpec({ required: true }));+ assert.strictEqual(error, null);+ assert.deepStrictEqual(requiredSteps(events), ['error: required new_ticket.new_name -> ApplicationRequired']);+ assert.strictEqual(warnings.length, 1);+ assert.match(warnings[0], /could not confirm the required level of new_ticket\.new_name \(ApplicationRequired\) — a re-run sets it.*: the table was found after its create, so nothing shows that the level was applied$/);+});++test('a reused table whose columns could not be read is not reported as having its primary name column\'s required level applied either', async () => {+ const m = mockSdk({ new_ticket: true });+ m.sdk.createTable = async () => { throw new Error('the table is not created again'); };+ m.provision.findColumns = async () => []; // what an unreadable column list comes out as: no column, the name column included+ const { events, warnings, error } = await buildPrimary(m, primaryRequiredSpec({ required: true }));+ assert.strictEqual(error, null);+ assert.deepStrictEqual(requiredSteps(events), ['error: required new_ticket.new_name -> ApplicationRequired'], 'nothing is "applied on create" on a table this build did not create');+ assert.strictEqual(warnings.length, 1);+ assert.match(warnings[0], /could not confirm the required level of new_ticket\.new_name \(ApplicationRequired\) — a re-run sets it.*: the table exists but its columns could not be read, so its current level is unknown$/);+ assert.ok(!m.calls.some((c) => c[0] === 'updateColumn'), 'and nothing is written on a level that is not known');+});++// None is the one level the create can show nothing about even when it succeeds (the SDK has nothing to read back for it), so a build that SAW the create succeed+// reports it applied (above). A table the build did not see made — found after the answer to its create was lost, or an existing table whose columns could not+// be read — shows nothing about the level of its name column, None included: it may hold Business Required, set there by a maker or left by an earlier create.+test('a table found after its create (the answer was lost) is not reported as having required:false applied either', async () => {+ const m = mockSdk();+ let probes = 0;+ m.provision.findTables = async (s) => (++probes === 1 ? [] : [{ logicalName: s.toLowerCase(), entitySetName: `${s.toLowerCase()}s` }]);+ m.sdk.createTable = async () => { throw Object.assign(new Error('Entities already exist: new_ticket'), { statusCode: 400 }); };+ const { events, warnings, error } = await buildPrimary(m, primaryRequiredSpec({ required: false }));+ assert.strictEqual(error, null);+ assert.deepStrictEqual(requiredSteps(events), ['error: required new_ticket.new_name -> None'], 'never "applied on create": nothing shows this build made the table');+ assert.strictEqual(warnings.length, 1);+ assert.match(warnings[0], /could not confirm the required level of new_ticket\.new_name \(None\) — a re-run sets it.*: the table was found after its create, so nothing shows that the level was applied$/);+ assert.ok(!m.calls.some((c) => c[0] === 'updateColumn'), 'and nothing is written on a level that is not known');+});++test('a reused table whose columns could not be read is not reported as having required:false applied either', async () => {+ const m = mockSdk({ new_ticket: true });+ m.sdk.createTable = async () => { throw new Error('the table is not created again'); };+ m.provision.findColumns = async () => []; // what an unreadable column list comes out as: no column, the name column included+ const { events, warnings, error } = await buildPrimary(m, primaryRequiredSpec({ required: false }));+ assert.strictEqual(error, null);+ assert.deepStrictEqual(requiredSteps(events), ['error: required new_ticket.new_name -> None'], 'nothing is "applied on create" on a table this build did not create');+ assert.strictEqual(warnings.length, 1);+ assert.match(warnings[0], /could not confirm the required level of new_ticket\.new_name \(None\) — a re-run sets it.*: the table exists but its columns could not be read, so its current level is unknown$/);+ assert.ok(!m.calls.some((c) => c[0] === 'updateColumn'), 'and nothing is written on a level that is not known');+});++test('a table the build did not see made says nothing about a name column whose spec states no required level', async () => {+ const found = mockSdk();+ let probes = 0;+ found.provision.findTables = async (s) => (++probes === 1 ? [] : [{ logicalName: s.toLowerCase(), entitySetName: `${s.toLowerCase()}s` }]);+ found.sdk.createTable = async () => { throw Object.assign(new Error('Entities already exist: new_ticket'), { statusCode: 400 }); };+ const reused = mockSdk({ new_ticket: true });+ reused.sdk.createTable = async () => { throw new Error('the table is not created again'); };+ reused.provision.findColumns = async () => [];+ for (const [what, m] of [['found after its create', found], ['reused with columns that could not be read', reused]]) {+ const { events, warnings, error } = await buildPrimary(m, primaryRequiredSpec({}));+ assert.strictEqual(error, null, what);+ assert.deepStrictEqual(requiredSteps(events), [], `${what}: no step for a level the spec does not state`);+ assert.deepStrictEqual(warnings, [], what);+ assert.ok(!m.calls.some((c) => c[0] === 'updateColumn'), what);+ }+});++test('a reused table whose name column can be read converges to an explicit required:false, and is left alone once it is None', async () => {+ const run = async (level) => {+ const m = mockSdk({ new_ticket: true });+ m.sdk.createTable = async () => { throw new Error('the table is not created again'); };+ m.provision.findColumns = async () => [{ logicalName: 'new_name', schemaName: 'new_name', RequiredLevel: { Value: level } }];+ return { m, ...(await buildPrimary(m, primaryRequiredSpec({ required: false }))) };+ };+ const required = await run('ApplicationRequired');+ assert.strictEqual(required.error, null);+ assert.deepStrictEqual(required.m.calls.filter((c) => c[0] === 'updateColumn'), [['updateColumn', 'new_ticket', 'new_name', { required: 'None' }]]);+ assert.deepStrictEqual(requiredSteps(required.events), ['ok: required new_ticket.new_name -> None']);+ assert.deepStrictEqual(required.warnings, []);+ const none = await run('None');+ assert.strictEqual(none.error, null);+ assert.ok(!none.m.calls.some((c) => c[0] === 'updateColumn'), 'a level that is already there is not written again');+ assert.deepStrictEqual(requiredSteps(none.events), ['skip: required new_ticket.new_name (already None)']);+ assert.deepStrictEqual(none.warnings, []);+});++test('PRIMARY_COLUMN_REQUIRED_NOT_APPLIED: the table was created, so the build stops once, never looks for it as if its name were taken, and says what to do', async () => {+ const causes = [+ ['no cause', undefined],+ ['a 409 from the update', Object.assign(new Error('HTTP 409 Conflict'), { statusCode: 409 })],+ ['a platform reason that reads like a duplicate', new Error('A record with the same name already exists')],+ ];+ for (const [what, cause] of causes) {+ const m = mockSdk();+ let creates = 0;+ let probes = 0;+ m.sdk.createTable = async () => { creates += 1; throw notApplied(cause); };+ const findTables = m.provision.findTables;+ m.provision.findTables = async (...args) => { probes += 1; return findTables(...args); };+ const { events, warnings, error } = await buildPrimary(m, primaryRequiredSpec({ required: true }, [{ schemaName: 'new_priority', type: 'Text' }]));+ assert.ok(error instanceof BuildHalt && error.code === 'PRIMARY_COLUMN_REQUIRED_NOT_APPLIED' && error.recoverable === true, `${what}: the halt carries the SDK's code`);+ assert.match(error.message, /WAS CREATED/, `${what}: and the SDK's own words`);+ assert.match(error.message, /the table exists\. Run the build again: it finds the table, does not create it again, and sets the required level of its primary name column/);+ assert.strictEqual(creates, 1, `${what}: the create is not repeated`);+ assert.strictEqual(probes, 1, `${what}: the table is looked for once, before the create — never "rediscovered" after it`);+ assert.ok(!m.calls.some((c) => c[0] === 'createColumn'), `${what}: nothing is created beside a table the build stops on`);+ assert.deepStrictEqual(events.filter((e) => e.status === 'error').map((e) => e.label), ['table new_ticket']);+ assert.deepStrictEqual(warnings, ['table new_ticket was created, but the required level (ApplicationRequired) of its primary name column new_name could not be confirmed, so the build stops here — the table exists: run the build again, which finds it, does not create it again, and sets that level on the column']);+ }+});++test('PRIMARY_COLUMN_REQUIRED_NOT_APPLIED with a name column length asked of a plain text column says the length may not have been applied either', async () => {+ const run = async (primaryAttribute) => {+ const m = mockSdk();+ m.sdk.createTable = async () => { throw notApplied(); };+ return buildPrimary(m, primaryRequiredSpec({ required: true, ...primaryAttribute }));+ };+ const plain = await run({ maxLength: 120 });+ assert.strictEqual(plain.warnings.length, 1);+ assert.ok(plain.warnings[0].endsWith('sets that level on the column; the spec also asks for a name column length of 120, which may not have been applied either (some environments make a name column created this way 850 characters long) and a re-run leaves an existing table\'s name column length as it is: after the re-run, check it in Maker and set it there if it matters'), plain.warnings[0]);+ // The platform keeps the length asked of an auto-numbered name column, and 850 is what the column comes out as either way.+ for (const unasked of [{ maxLength: 120, autoNumberFormat: 'WO-{SEQNUM:5}' }, { maxLength: 850 }, {}]) {+ const quiet = await run(unasked);+ assert.ok(quiet.warnings[0].endsWith('sets that level on the column'), `no length said for ${JSON.stringify(unasked)}`);+ }+});++test('the re-run after PRIMARY_COLUMN_REQUIRED_NOT_APPLIED finds the table and sets the level as it does an existing column\'s; the run after that does nothing', async () => {+ const spec = primaryRequiredSpec({ required: true });+ const rerun = async (level) => {+ const m = mockSdk({ new_ticket: true });+ m.sdk.createTable = async () => { throw new Error('the table is not created again'); };+ m.provision.findColumns = async () => [{ logicalName: 'new_name', schemaName: 'new_name', RequiredLevel: { Value: level } }];+ return { m, ...(await buildPrimary(m, spec)) };+ };+ const first = await rerun('None');+ assert.strictEqual(first.error, null);+ assert.deepStrictEqual(first.m.calls.filter((c) => c[0] === 'updateColumn'), [['updateColumn', 'new_ticket', 'new_name', { required: 'ApplicationRequired' }]]);+ assert.deepStrictEqual(requiredSteps(first.events), ['ok: required new_ticket.new_name -> ApplicationRequired']);+ const second = await rerun('ApplicationRequired');+ assert.strictEqual(second.error, null);+ assert.ok(!second.m.calls.some((c) => c[0] === 'updateColumn'), 'a level that is already there is not written again');+ assert.deepStrictEqual(requiredSteps(second.events), ['skip: required new_ticket.new_name (already ApplicationRequired)']);+});++test('a reused table whose primary name column states no required level is left as it is', async () => {+ for (const level of ['None', 'ApplicationRequired']) {+ const m = mockSdk({ new_ticket: true });+ m.sdk.createTable = async () => { throw new Error('the table is not created again'); };+ m.provision.findColumns = async () => [{ logicalName: 'new_name', schemaName: 'new_name', RequiredLevel: { Value: level } }];+ const { events, warnings, error } = await buildPrimary(m, primaryRequiredSpec({}));+ assert.strictEqual(error, null);+ assert.ok(!m.calls.some((c) => c[0] === 'updateColumn'), `a name column that is ${level} is not rewritten`);+ assert.deepStrictEqual(requiredSteps(events), []);+ assert.deepStrictEqual(warnings, []);+ }+});+test('provisionDataModel reads RequiredLevel once when discovery omits it', async () => {const m = mockSdk({ new_ticket: true });const rawGets = [];diff --git a/plugins/model-apps/scripts/tests/form-order-build.test.js b/plugins/model-apps/scripts/tests/form-order-build.test.jsindex ed30b99e3..6234fbb8f 100644--- a/plugins/model-apps/scripts/tests/form-order-build.test.js+++ b/plugins/model-apps/scripts/tests/form-order-build.test.js@@ -3,16 +3,17 @@//// What a table opens with is decided by the ORDER of its Main forms (each form's formxml// `<DisplayConditions Order="n">`), not by `systemform.isdefault`: measured live, moving `isdefault` did-// not reorder the forms a user is served, and three new forms at EQUAL Order (every new form carries-// Order 0) were served with the `isdefault` form LAST. So a build that only promoted `isdefault` left a-// table with three new Main forms opening with an alternate one. These tests drive the forms phase against a-// small model of the environment's forms and pin, per scenario, which forms get which Order, which are-// never touched, and what the build says when it cannot make its choice stick.+// not reorder the forms a user is served, and three new forms at the SAME Order (0, which is what the SDK+// then gave every new form) were served with the `isdefault` form LAST. So a build that only promoted+// `isdefault` left a table with three new Main forms opening with an alternate one. A form the SDK creates+// carries no Order at all, so the build writes each form's place itself. These tests drive the forms+// phase against a small model of the environment's forms and pin, per scenario, which forms get which+// Order, which are never touched, and what the build says when it cannot make its choice stick.const test = require('node:test');const assert = require('node:assert');const { runSdkBuild, planFor } = require('../lib/sdk-build.js');-const { makeSimpleMockSdk } = require('./helpers/mock-sdk.js');+const { makeSimpleMockSdk, rolesOfDisplayConditions, applyRolesWrite } = require('./helpers/mock-sdk.js');const FORM_TYPE = { Main: 2, QuickCreate: 7, QuickView: 6 };const T = 'new_workitem';@@ -46,8 +47,8 @@ function specFor({ existing = false, forms, mainFormOrder, personas } = {}) {// `seed` lists forms that already exist: { id, name, entity?, type?, active?, isdefault?, dc? } where `dc`// is the form's <DisplayConditions> ({ everyone | roleIds, fallbackForm, order }) or undefined for none.// A form the build creates behaves as the SDK's does: its local copy carries the <DisplayConditions> the-// SDK gives every new form (Order 0, offered to everyone) in its root bag, and it exists on the server —-// with whatever that copy says — only once it is pushed.+// SDK gives every new form (offered to everyone, with no Order: helpers/mock-sdk.js seeds it as the bundle+// does) in its root bag, and it exists on the server — with whatever that copy says — only once it is pushed.function makeEnv(seed = [], failures = {}, options = {}) {const { sdk } = makeSimpleMockSdk();const provision = Object.create(sdk);@@ -60,9 +61,9 @@ function makeEnv(seed = [], failures = {}, options = {}) {provision.createArtifact = async (t, def) => {const art = await sdk.createArtifact(t, def);if (t === 'form') {- const local = await sdk.getArtifact('form', art.id);- if (!options.noDisplayConditions) {- local.bag.c.push({ i: 3, node: { n: 'DisplayConditions', a: [['Order', '0'], ['FallbackForm', 'true']], c: [{ n: 'Everyone', a: [], c: [] }] } });+ if (options.noDisplayConditions) {+ const local = await sdk.getArtifact('form', art.id);+ local.bag.c = local.bag.c.filter((e) => !(e && e.node && e.node.n === 'DisplayConditions'));}unpushed.set(art.id, { entity: def.entityLogicalName, name: def.name, type: FORM_TYPE[def.formType || 'Main'] });}@@ -75,9 +76,9 @@ function makeEnv(seed = [], failures = {}, options = {}) {unpushed.delete(id);const local = await sdk.getArtifact('form', id);const node = (local.bag.c.find((e) => e && e.node && e.node.n === 'DisplayConditions') || {}).node;- const order = node ? Number((node.a.find(([n]) => n === 'Order') || [])[1]) : undefined;- add({ id, ...meta, dc: node ? { everyone: true, fallbackForm: true, order } : undefined });- log.push(['created', meta.name, order]);+ const dc = rolesOfDisplayConditions(node);+ add({ id, ...meta, dc });+ log.push(['created', meta.name, dc ? dc.order : undefined]);}return out;};@@ -114,26 +115,14 @@ function makeEnv(seed = [], failures = {}, options = {}) {if (!f) throw new Error(`no form ${id}`);return f.dc ? { ...f.dc } : undefined;};- // The SDK's contract (vendored FormApi): roles/everyone REPLACE the element; order/fallbackForm alone- // re-attach the existing one and change only those attributes — and are refused when there is none.+ // The SDK's contract (vendored FormApi), applied by helpers/mock-sdk.js: roles/everyone REPLACE the element; order/fallbackForm+ // alone re-attach the existing one and change only those attributes — and are refused when there is none.provision.setFormSecurityRoles = async (id, opts) => {const f = forms.get(id);if (!f) throw new Error(`no form ${id}`);log.push(['set', f.name, opts]);if (failures.failWrite) throw new Error(failures.failWrite);- const wantsElement = opts.everyone || (opts.roleIds && opts.roleIds.length > 0);- if (!wantsElement) {- if (!f.dc) throw new Error('`order`/`fallbackForm` were supplied without `roleIds` or `everyone`, but this form has no <DisplayConditions> to attach them to');- if (opts.order !== undefined) f.dc.order = opts.order;- if (opts.fallbackForm !== undefined) f.dc.fallbackForm = opts.fallbackForm;- return;- }- const prior = f.dc || {};- f.dc = {- ...(opts.everyone ? { everyone: true } : { roleIds: [...opts.roleIds] }),- fallbackForm: opts.fallbackForm !== undefined ? opts.fallbackForm : (prior.fallbackForm !== undefined ? prior.fallbackForm : false),- ...(opts.order !== undefined ? { order: opts.order } : (prior.order !== undefined ? { order: prior.order } : {})),- };+ f.dc = applyRolesWrite(f.dc, opts);};provision.addSolutionComponent = async () => undefined;const order = (name) => { const f = byName(name); return f && f.dc ? f.dc.order : undefined; };@@ -163,9 +152,9 @@ test('own table, three new Main forms, no choice made: the first in spec order iconst { res, step, warnings } = await build(specFor(), env);assert.strictEqual(res.ok, true);assert.deepStrictEqual([env.order(STD), env.order(ALT), env.order(SUM)], [0, 1, 2]);- // Every new form arrives with Order 0, so the first is already in place: only the others are written.- assert.deepStrictEqual(env.writes(), [[ALT, { order: 1 }], [SUM, { order: 2 }]]);- assert.deepStrictEqual(env.created(), [[STD, 0], [ALT, 0], [SUM, 0]], 'a table the spec orders is ordered after the creates, not in them');+ // A new form arrives with no Order, so none is in place yet: every Main form is written, the first included.+ assert.deepStrictEqual(env.writes(), [[STD, { order: 0 }], [ALT, { order: 1 }], [SUM, { order: 2 }]]);+ assert.deepStrictEqual(env.created(), [[STD, undefined], [ALT, undefined], [SUM, undefined]], 'a table the spec orders is ordered after the creates, not in them');assert.strictEqual(env.byName(STD).isdefault, true, 'the same form is still promoted to isdefault');const [s] = step(/^form order for new_workitem/);assert.strictEqual(s.status, 'ok');@@ -281,7 +270,7 @@ test('QuickCreate and QuickView forms are never ordered, and do not count as Mai});const env = makeEnv();const { step } = await build(spec, env);- assert.deepStrictEqual(env.writes(), [[ALT, { order: 1 }]]);+ assert.deepStrictEqual(env.writes(), [[STD, { order: 0 }], [ALT, { order: 1 }]]);assert.strictEqual(step(/^form order for/).length, 1);assert.strictEqual(step(/^form order for/)[0].label, "form order for new_workitem: 'Work Item', then 1 more");});@@ -359,8 +348,9 @@ test('existing table, deactivateOtherMainForms on the explicit default is NOT ap});test('existing table, a NEW alternate form and no choice: it is put after the table\u2019s other Main forms, which are not touched', async () => {- // AC 2: adding an alternate form must not change what the table opens with. A new form carries Order 0,- // which would tie with the form everyone opens today — and the platform, not the build, orders a tie.+ // Adding an alternate form must not change what the table opens with. A new form carries no Order, and where the+ // platform serves a form with none among the table's others is not the build's choice — so the build gives it an+ // order of its own, after theirs.const env = makeEnv([{ id: 'e1', name: STD, isdefault: true, dc: { everyone: true, fallbackForm: true, order: 0 } },{ id: 'e3', name: SUM, dc: { everyone: true, fallbackForm: true, order: 3 } },@@ -368,7 +358,7 @@ test('existing table, a NEW alternate form and no choice: it is put after the ta]);const { step, warnings } = await build(specFor({ existing: true }), env);// Highest other order (3) + 1 + its index among the spec's Main forms (1): created at 5, in ONE write —- // the create — never at the Order 0 every new form starts with.+ // the create — so the form is never left without an order, as the SDK makes it.assert.deepStrictEqual(env.created(), [[ALT, 5]]);assert.deepStrictEqual(env.writes(), [], 'no separate order write');assert.strictEqual(env.order(STD), 0);@@ -435,8 +425,8 @@ test('securityRoles WITHOUT an order keeps the position the forms phase gave the});test('a declared Main form the forms phase produced no id for: the table is not ordered, and the step names the form', async () => {- // The guard behind this skip: ordering the other forms without that one would leave it at Order 0,- // tied with the first — so the order the step reports would not be the order users are served.+ // The guard behind this skip: ordering the other forms without that one would leave it with no order,+ // so the order the step reports would not be the order users are served.const env = makeEnv();const basePush = env.provision.pushArtifact;env.provision.pushArtifact = async (t, id) => {@@ -523,8 +513,9 @@ test('the step count stays honest: every planned form-order step is emitted exac// --- a new form is created in its place --------------------------------------------------------------//// On a table whose order the build does not set, a new Main form's order is part of its create. A separate-// write after the create left the form at Order 0 — possibly ahead of the form the table opened with — on-// any failure between the two, and a later build cannot tell the form is new, so it could never repair it.+// write after the create left the form with no order of its own — where the platform serves it is not the+// build's choice, so possibly ahead of the form the table opened with — on any failure between the two, and a+// later build cannot tell the form is new, so it could never repair it.const existingWithOriginal = () => makeEnv([{ id: 'e1', name: STD, isdefault: true, dc: { everyone: true, fallbackForm: true, order: 5 } }]);const addAlternate = () => specFor({ existing: true, forms: [{ entity: T, name: STD, formType: 'Main' }, { entity: T, name: ALT, formType: 'Main' }] });@@ -579,7 +570,7 @@ test('a failure placing a new form fails its create before anything is pushed',return update(t, id, ptr, value);};await assert.rejects(build(addAlternate(), env), /local copy refused the edit/);- assert.strictEqual(env.byName(ALT), undefined, 'the form was never pushed, so nothing is left at Order 0');+ assert.strictEqual(env.byName(ALT), undefined, 'the form was never pushed, so nothing is left without a place');});test('a new form whose SDK copy carries no <DisplayConditions> is created as the SDK makes it, and the build says so', async () => {@@ -592,10 +583,10 @@ test('a new form whose SDK copy carries no <DisplayConditions> is created as thetest('forms on a table the spec orders, or orders by hand, are not placed in their create', async () => {const own = makeEnv();await build(specFor(), own);- assert.deepStrictEqual(own.created(), [[STD, 0], [ALT, 0], [SUM, 0]], 'the order step orders them after the creates');+ assert.deepStrictEqual(own.created(), [[STD, undefined], [ALT, undefined], [SUM, undefined]], 'the order step orders them after the creates');const byHand = makeEnv([{ id: 'e1', name: STD, dc: { everyone: true, fallbackForm: true, order: 5 } }]);await build(specFor({ existing: true, forms: [{ entity: T, name: STD, formType: 'Main', securityRoles: { everyone: true, order: 1 } }, { entity: T, name: ALT, formType: 'Main' }] }), byHand);- assert.deepStrictEqual(byHand.created(), [[ALT, 0]], 'the author orders this table');+ assert.deepStrictEqual(byHand.created(), [[ALT, undefined]], 'the author orders this table: the form is left as the SDK makes it, with no order');});// A form with no order at all is served after every form that has one. Appending the new form after thediff --git a/plugins/model-apps/scripts/tests/form-order-real-bundle.test.js b/plugins/model-apps/scripts/tests/form-order-real-bundle.test.jsindex 55b532199..fe9b2a41c 100644--- a/plugins/model-apps/scripts/tests/form-order-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/form-order-real-bundle.test.js@@ -8,6 +8,8 @@ const os = require('node:os');const path = require('node:path');const fs = require('node:fs');+const { runSdkBuild } = require('../lib/sdk-build.js');+const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');const FORM_ID = '11111111-1111-1111-1111-111111111111';const ROLE_A = '22222222-2222-2222-2222-222222222222';@@ -105,6 +107,25 @@ test('order-only write on a role-restricted form preserves both roles and Fallbaassert.strictEqual(withoutDisplayConditions(xml), withoutDisplayConditions(original));});+test('a DisplayConditions with no Order — what a form the SDK creates carries — reads as order undefined, and an order-only write adds the attribute and keeps Everyone and FallbackForm', async () => {+ // The forms phase writes Order 0..n-1 onto the Main forms it was asked to order (writeFormOrder), and a form it just created starts+ // with none: the first form is written too.+ const original = '<form><tabs><tab name="general" /></tabs><DisplayConditions FallbackForm="true"><Everyone /></DisplayConditions></form>';+ const { sdk, calls } = await freshSdk(original);+ const stored = await sdk.getFormSecurityRoles(FORM_ID);+ assert.strictEqual(stored.order, undefined);+ assert.strictEqual(stored.everyone, true);+ assert.strictEqual(stored.fallbackForm, true);++ await sdk.setFormSecurityRoles(FORM_ID, { order: 0 });++ const xml = patchCall(calls).body.formxml;+ assert.match(xml, /<DisplayConditions\b[^>]*Order="0"[^>]*>/);+ assert.match(xml, /FallbackForm="true"/);+ assert.match(xml, /<Everyone\s*\/>/);+ assert.strictEqual(withoutDisplayConditions(xml), withoutDisplayConditions(original), 'the rest of the form is unchanged');+});+test('forms without DisplayConditions refuse order-only writes, while everyone+fallback+order adds the element', async () => {const original = '<form><tabs><tab name="general" /></tabs></form>';const { sdk, calls } = await freshSdk(original);@@ -149,9 +170,11 @@ test('a row whose type cannot be read is refused too, never taken for a Main for// The build places a Main form it creates on a table whose order it does not set IN ITS CREATE// (createInPlace, sdk-build.js): it finds the <DisplayConditions> the SDK gives the new form in its root-// bag and replaces that node before the first push. This pins the SDK side of that: if the node moved or-// were rebuilt at push time, forms would silently be created at Order 0 again.-test('a new form carries <DisplayConditions Order="0"> in its root bag, and an edit to it before the first push is what the create writes', async () => {+// bag and writes the form's order into it before the first push. The SDK gives it no Order (a form with+// none takes no slot in the maker's form order: GetFormsOrderInfo says -1 for it), so the build ADDS the+// attribute, first, as the maker's own file has it. This pins the SDK side of that: if the node moved or+// were rebuilt at push time, forms would silently be created with no order again.+test('a new form carries <DisplayConditions FallbackForm="true"> with no Order in its root bag, and the Order the build adds to it before the first push is what the create writes', async () => {const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'form-order-create-'));tempDirs.push(dir);@@ -173,11 +196,12 @@ test('a new form carries <DisplayConditions Order="0"> in its root bag, and an econst local = await sdk.getArtifact('form', art.id);const at = local.bag.c.findIndex((e) => e && e.node && e.node.n === 'DisplayConditions');assert.ok(at >= 0, `no DisplayConditions in the new form's root bag: ${JSON.stringify(local.bag.c.map((e) => e.node && e.node.n))}`);- assert.deepStrictEqual(local.bag.c[at].node.a, [['Order', '0'], ['FallbackForm', 'true']]);+ assert.deepStrictEqual(local.bag.c[at].node.a, [['FallbackForm', 'true']], 'access is unchanged (everyone, fallback) and the form takes no slot in the form order');assert.deepStrictEqual(local.bag.c[at].node.c.map((c) => c.n), ['Everyone']);+ // What createInPlace writes: the order goes first, the attributes the SDK gave the node stay.const entry = JSON.parse(JSON.stringify(local.bag.c[at]));- entry.node.a = entry.node.a.map(([n, v]) => (n === 'Order' ? [n, '7'] : [n, v]));+ entry.node.a = [['Order', '7'], ...entry.node.a];await sdk.updateElement('form', art.id, `/bag/c/${at}`, entry);await sdk.pushArtifact('form', art.id);@@ -188,3 +212,214 @@ test('a new form carries <DisplayConditions Order="0"> in its root bag, and an eassert.strictEqual((xml.match(/<DisplayConditions\b/g) || []).length, 1, 'one element, not a second default one');assert.match(xml, /<header\b/, 'the rest of the form is written as the SDK built it');});++// --- the whole forms phase, on the real bundle ---------------------------------------------------------------------+//+// `runSdkBuild` over the vendored SDK and a small fake org that keeps EVERY systemform row. The tests above pin what+// the SDK does with one form; these pin what the build asks of it across a table's forms — which writes it makes, and+// what each form's stored <DisplayConditions> says afterwards. The build tests that model the environment+// (form-order-build.test.js, over helpers/mock-sdk.js) are checked against these answers, not only against their model.+const TABLE = 'new_workitem';+const STD = 'Work Item';+const ALT = 'My Work \u2014 Work Item';+const SUM = 'Work Item \u2014 Summary';+const guid = (n) => `00000000-0000-4000-8000-${String(n).padStart(12, '0')}`;++// The `Order` in a form's formxml <DisplayConditions>, or undefined when the element has none.+const storedOrder = (formxml) => {+ const attribute = /<DisplayConditions\b[^>]*\sOrder="(-?\d+)"/.exec(String(formxml));+ return attribute ? Number(attribute[1]) : undefined;+};++const mainFormsSpec = (names, { existing = false } = {}) => ({+ solution: { uniqueName: 'FO', displayName: 'FO', publisherPrefix: 'new' },+ app: { name: 'FO App', description: 'd' },+ entities: [{+ schemaName: TABLE, displayName: 'Work Item', pluralName: 'Work Items',+ primaryAttribute: { schemaName: 'new_name', displayName: 'Name' },+ columns: [{ schemaName: 'new_notes', displayName: 'Notes', type: 'Memo' }],+ ...(existing ? { existing: true } : {}),+ }],+ forms: names.map((name) => ({ entity: TABLE, name, formType: 'Main' })),+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'W', subAreas: [{ entity: TABLE, title: 'Work Items' }] }] }] },+});++function fakeFormsOrg(seed = []) {+ const rows = new Map();+ const revisions = new Map();+ const requests = [];+ const addRow = (row) => {+ rows.set(row.formid, { type: FORM_TYPE_MAIN, objecttypecode: TABLE, formactivationstate: 1, isdefault: false, ...row });+ revisions.set(row.formid, 1);+ };+ seed.forEach(addRow);+ // The filters the build sends for a form, as the platform evaluates them:+ // objecttypecode eq 'new_workitem' and name eq 'Work Item' and type eq 2+ // objecttypecode eq 'new_workitem' and type eq 2 and formactivationstate eq 1+ // formid eq 00000000-0000-4000-8000-000000000001+ const matching = (filter) => [...rows.values()].filter((row) => {+ const byId = /^formid eq (\S+)$/.exec(filter);+ if (byId) return row.formid === byId[1];+ const table = /objecttypecode eq '([^']+)'/.exec(filter);+ const name = / name eq '((?:[^']|'')*)'/.exec(filter);+ const type = / type eq (\d+)/.exec(filter);+ return (!table || row.objecttypecode === table[1])+ && (!name || row.name === name[1].replace(/''/g, "'"))+ && (!type || Number(row.type) === Number(type[1]))+ && (!/ formactivationstate eq 1/.test(filter) || row.formactivationstate === 1);+ });+ const reply = (body, status = 200, headers = {}) => ({ status, headers, body });+ const idOf = (url) => (/\/systemforms\(([0-9a-f-]+)\)/i.exec(url) || [])[1];+ const httpClient = {+ get: async (url) => {+ const decoded = decodeURIComponent(url);+ requests.push({ method: 'get', url: decoded });+ if (/EntityDefinitions\(LogicalName='systemform'\)/.test(decoded)) return reply({ EntitySetName: 'systemforms' });+ if (decoded.includes(`EntityDefinitions(LogicalName='${TABLE}')/Attributes`)) {+ return reply({ value: [{ LogicalName: 'new_name', AttributeType: 'String' }, { LogicalName: 'new_notes', AttributeType: 'Memo' }] });+ }+ if (decoded.includes(`EntityDefinitions(LogicalName='${TABLE}')`)) {+ return reply({ LogicalName: TABLE, EntitySetName: `${TABLE}s`, ObjectTypeCode: 10001, MetadataId: guid(900) });+ }+ const id = idOf(decoded);+ if (id && /RetrieveUnpublished\(\)/.test(decoded)) {+ // The unpublished document's content token. The row's own token, read separately, is the one a PATCH sends back.+ return reply(selectedColumns(url, { ...rows.get(id), '@odata.etag': `W/"content-${revisions.get(id)}"` }));+ }+ if (id) return reply({ formid: id, '@odata.etag': `W/"row-${revisions.get(id)}"` }, 200, { etag: `W/"row-${revisions.get(id)}"` });+ if (/\/systemforms(?:\?|$)/.test(decoded)) {+ const filter = (/\$filter=([^&]*)/.exec(decoded) || [])[1] || '';+ const top = Number((/\$top=(\d+)/.exec(decoded) || [])[1] || Infinity);+ return reply({ value: matching(filter).slice(0, top).map((row) => selectedColumns(url, row)) });+ }+ return assert.fail(`unexpected GET: ${decoded}`);+ },+ post: async (url, body) => {+ const decoded = decodeURIComponent(url);+ requests.push({ method: 'post', url: decoded, body });+ if (/\/systemforms(?:\?|$)/.test(decoded)) {+ // The SDK sends the id it minted for the new form as `formid`, and the platform keeps it.+ const id = body.formid || guid(rows.size + 1);+ addRow({ ...body, formid: id });+ return reply(undefined, 204, { 'odata-entityid': `https://contoso.crm.dynamics.com/api/data/v9.0/systemforms(${id})` });+ }+ if (/\/(?:AddSolutionComponent|PublishXml)(?:\?|$)/.test(decoded)) return reply({}, 204);+ return assert.fail(`unexpected POST: ${decoded}`);+ },+ patch: async (url, body) => {+ const decoded = decodeURIComponent(url);+ requests.push({ method: 'patch', url: decoded, body });+ const id = idOf(decoded);+ assert.ok(rows.has(id), `a PATCH of a form that does not exist: ${decoded}`);+ Object.assign(rows.get(id), body);+ revisions.set(id, revisions.get(id) + 1);+ return reply({}, 204);+ },+ put: async (url) => assert.fail(`unexpected PUT: ${url}`),+ delete: async (url) => assert.fail(`unexpected DELETE: ${url}`),+ };+ // A new SDK over a new workspace each time: a rebuild must not lean on an earlier run's local copy.+ const newSdk = async () => {+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'form-order-org-'));+ tempDirs.push(dir);+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: 'https://contoso.crm.dynamics.com', httpClient });+ await sdk.initWorkspace();+ return sdk;+ };+ const byName = (name) => [...rows.values()].find((row) => row.name === name);+ const creates = () => requests.filter((r) => r.method === 'post' && /\/systemforms(?:\?|$)/.test(r.url));+ // The writes of a form's formxml after its create, as [form name, the Order the write leaves in it].+ const formxmlWrites = () => requests+ .filter((r) => r.method === 'patch' && r.body && r.body.formxml !== undefined)+ .map((r) => [rows.get(idOf(r.url)).name, storedOrder(r.body.formxml)]);+ return { rows, requests, byName, creates, formxmlWrites, newSdk };+}++async function buildForms(spec, sdk) {+ const warnings = [];+ const res = await runSdkBuild(spec, { sdk, apply: true, phases: ['forms'], emit: () => {}, warn: (m) => warnings.push(String(m)) });+ return { res, warnings };+}++test('forms phase on the real bundle, a table the spec creates: every Main form is written its place — the first too, a new form has no Order — and a rebuild writes none', async () => {+ const org = fakeFormsOrg();+ const spec = mainFormsSpec([STD, ALT, SUM]);+ const built = await buildForms(spec, await org.newSdk());+ assert.strictEqual(built.res.ok, true);++ // The create is the SDK's own, with no Order: a table the spec orders is ordered after every form exists.+ assert.strictEqual(org.creates().length, 3);+ for (const create of org.creates()) {+ assert.match(create.body.formxml, /<DisplayConditions FallbackForm="true"><Everyone \/><\/DisplayConditions>/);+ }+ assert.deepStrictEqual([STD, ALT, SUM].map((name) => storedOrder(org.byName(name).formxml)), [0, 1, 2]);+ assert.deepStrictEqual(org.formxmlWrites().sort((a, b) => a[1] - b[1]), [[STD, 0], [ALT, 1], [SUM, 2]], 'one write per form, the first included: it is not found already at 0');+ for (const name of [STD, ALT, SUM]) {+ assert.match(org.byName(name).formxml, /<DisplayConditions\b[^>]*FallbackForm="true"[^>]*><Everyone \/>/, `${name}: an order-only write keeps everyone and fallback`);+ }+ assert.deepStrictEqual([STD, ALT, SUM].map((name) => org.byName(name).isdefault), [true, false, false]);++ const written = org.formxmlWrites().length;+ const rebuilt = await buildForms(spec, await org.newSdk());+ assert.strictEqual(rebuilt.res.ok, true);+ assert.strictEqual(org.formxmlWrites().length, written, 'a rebuild finds every order in place and writes none');+ assert.deepStrictEqual(rebuilt.warnings.filter((w) => /form order/.test(w)), []);+});++test('forms phase on the real bundle, a table the spec does not order: a new Main form is created already after the table\u2019s other Main forms, in its create', async () => {+ const ordered = '<form><tabs /><DisplayConditions Order="5" FallbackForm="true"><Everyone /></DisplayConditions></form>';+ const unordered = '<form><tabs /></form>';+ const org = fakeFormsOrg([+ { formid: guid(100), name: STD, isdefault: true, formxml: ordered },+ { formid: guid(101), name: 'Information', formxml: unordered },+ ]);+ const { res, warnings } = await buildForms(mainFormsSpec([ALT], { existing: true }), await org.newSdk());+ assert.strictEqual(res.ok, true);++ // The highest order among the others (5), plus 1, plus the form's index among the spec's Main forms of the table (0).+ assert.strictEqual(org.creates().length, 1);+ assert.match(org.creates()[0].body.formxml, /<DisplayConditions Order="6" FallbackForm="true"><Everyone \/><\/DisplayConditions>/);+ assert.strictEqual(storedOrder(org.byName(ALT).formxml), 6);+ assert.deepStrictEqual(org.formxmlWrites(), [], 'no separate order write: the order is part of the create');+ assert.strictEqual(org.byName(STD).formxml, ordered, 'the form the table opens with is not touched');+ assert.strictEqual(org.byName('Information').formxml, unordered, 'nor is a form the spec does not declare');+ // A form with no order is served after every form that has one, so the new form still comes before it: the build says so.+ assert.ok(warnings.some((w) => /before 'Information', which has no form order/.test(w)), JSON.stringify(warnings));+});++// helpers/mock-sdk.js stands in for the SDK in the build tests that run a whole build. A stand-in that models a created+// form differently from the bundle makes those tests pin the wrong behaviour — the first new form of a table the spec+// orders needs an order write only because the bundle gives it none — so the parts that decide it are compared here:+// the <DisplayConditions> a created form carries, and how a read and a write of its roles answer afterwards.+test('the shared SDK mock creates a form as the real bundle does, and answers the same reads and writes of its roles', async () => {+ const { makeSimpleMockSdk } = require('./helpers/mock-sdk.js');+ const real = await fakeFormsOrg().newSdk();+ const mock = makeSimpleMockSdk().sdk;+ const definition = { name: 'Probe', entityLogicalName: TABLE, formType: 'Main' };+ const realArtifact = await real.createArtifact('form', definition);+ const mockArtifact = await mock.createArtifact('form', definition);+ const conditionsOf = async (sdk, artifact) => {+ const bag = (await sdk.getArtifact('form', artifact.id)).bag.c;+ return (bag.find((e) => e && e.node && e.node.n === 'DisplayConditions') || {}).node;+ };+ assert.deepStrictEqual(await conditionsOf(mock, mockArtifact), await conditionsOf(real, realArtifact));++ const realId = (await real.pushArtifact('form', realArtifact.id)).id;+ const mockId = (await mock.pushArtifact('form', mockArtifact.id)).id;+ const sameRoles = async (when) => assert.deepStrictEqual(await mock.getFormSecurityRoles(mockId), await real.getFormSecurityRoles(realId), when);+ await sameRoles('as created');+ assert.strictEqual((await real.getFormSecurityRoles(realId)).order, undefined, 'the bundle gives a created form no order');++ // Each write is applied to both: an order alone, a role list (which replaces everyone and keeps the order and the+ // fallback setting), attributes alone on a role list, everyone again, and `{}`, which removes the element.+ for (const write of [{ order: 0 }, { roleIds: [ROLE_A, ROLE_B] }, { order: 4, fallbackForm: false }, { everyone: true }, {}]) {+ await real.setFormSecurityRoles(realId, write);+ await mock.setFormSecurityRoles(mockId, write);+ await sameRoles(`after ${JSON.stringify(write)}`);+ }+ assert.strictEqual(await real.getFormSecurityRoles(realId), undefined, 'the element is gone');+ // With no element to attach them to, an order alone is refused by both.+ await assert.rejects(real.setFormSecurityRoles(realId, { order: 1 }), /no <DisplayConditions> to attach them to/);+ await assert.rejects(mock.setFormSecurityRoles(mockId, { order: 1 }), /no <DisplayConditions> to attach them to/);+});diff --git a/plugins/model-apps/scripts/tests/form-security-roles.test.js b/plugins/model-apps/scripts/tests/form-security-roles.test.jsindex 8acecb3e1..40e711141 100644--- a/plugins/model-apps/scripts/tests/form-security-roles.test.js+++ b/plugins/model-apps/scripts/tests/form-security-roles.test.js@@ -89,6 +89,11 @@ async function build(spec, { failSet, warn } = {}) {return { res, calls, events };}+// The forms phase also gives a new table's first Main form its place, `{ order: 0 }` — a form the SDK creates has no Order — through+// the same call. These tests are about the roles the security phase writes, which are the writes that carry `roleIds` or `everyone`.+const isRolesWrite = (call) => call[0] === 'setFormSecurityRoles' && (call[2].roleIds !== undefined || call[2].everyone === true);+const rolesWrites = (calls) => calls.filter(isRolesWrite);+// --- the multi-Main-form warning ------------------------------------------------------------------//// `created.forms` keeps ONE id per entity, so a second Main form silently replaces the first there.@@ -138,8 +143,8 @@ test('a form offered to two personas resolves them to the roles this build creatconst { 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]))}`);+ const set = rolesWrites(calls)[0];+ assert.ok(set, `setFormSecurityRoles must be called with the roles; 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.@@ -152,14 +157,14 @@ test('role assignment runs AFTER the roles are created, never before', async ()// 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');+ const set = calls.findIndex(isRolesWrite);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');+ const set = rolesWrites(calls)[0];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');@@ -169,16 +174,16 @@ 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];+ const bareOpts = rolesWrites(bare.calls)[0][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];+ const fullOpts = rolesWrites(full.calls)[0][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];+ const falsyOpts = rolesWrites(falsy.calls)[0][2];assert.strictEqual(falsyOpts.fallbackForm, false);assert.strictEqual(falsyOpts.order, 0);});@@ -193,10 +198,12 @@ test('a persona the build did not create HALTS — it must never silently hide t'the halt must name the offending persona and how to fix it');});-test('a form without securityRoles is left alone entirely', async () => {+test('a form without securityRoles gets no role write — the only write is its place in the form order', async () => {const { calls } = await build(specWithFormRoles(null));- assert.strictEqual(calls.some((c) => c[0] === 'setFormSecurityRoles'), false,+ assert.strictEqual(calls.some(isRolesWrite), false,'omitting securityRoles must not touch the form — every role can see it, which is the default');+ assert.deepStrictEqual(calls.filter((c) => c[0] === 'setFormSecurityRoles').map((c) => c[2]), [{ order: 0 }],+ 'a form the SDK creates has no order, so the forms phase writes the first form of its table');});test('a failure to assign roles HALTS the build', async () => {@@ -228,7 +235,7 @@ test('a non-Main form is addressed by its own identity, not the entity default',{ entity: 'new_ticket', name: 'Quick', formType: 'QuickCreate', securityRoles: { personas: ['Dispatcher'] } },];const { res, calls } = await build(spec);- const set = calls.find((c) => c[0] === 'setFormSecurityRoles');+ const set = rolesWrites(calls)[0];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');@@ -342,7 +349,7 @@ test('a persona named in a DIFFERENT CASE resolves — the gate and the build muconst { 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');+ const set = rolesWrites(calls)[0];assert.deepStrictEqual(set[2], { roleIds: [ROLE_DISPATCHER] });});@@ -352,7 +359,7 @@ test('surrounding whitespace in a persona name also resolves', async () => {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] });+ assert.deepStrictEqual(rolesWrites(calls)[0][2], { roleIds: [ROLE_DISPATCHER] });});test('the case-insensitive persona lookup DEPENDS on personas[] being unique case-insensitively', () => {diff --git a/plugins/model-apps/scripts/tests/helpers/app-sitemap-org.js b/plugins/model-apps/scripts/tests/helpers/app-sitemap-org.jsnew file mode 100644index 000000000..27839d584--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/app-sitemap-org.js@@ -0,0 +1,109 @@+'use strict';+// A fake Dataverse for the REAL vendored SDK that holds one app and its sitemap, for tests of how an environment's navigation titles are read and written+// in each language. It is the transport of the plugin's own az-token HttpClient (`createAzHttpClient`), so the SDK is driven through the real client — and the client's+// rules (a request is a FULL URL under the environment, or it is refused) hold for everything a test makes it send, the download's read of the base language included.+// It answers the reads `fetchArtifact('app')` and an app push make, the base-language read a download makes (`organizations?$select=languagecode&$top=1`), and records+// every request and every sitemap the SDK writes:+//+// const org = createSitemapOrg({ xml: sitemapXml({ area: { 3082: 'Trabajo' } }), baseLanguage: 3082 });+// const { sdk, dispose } = await createSdk(org, { languageCode: 3082 }); // the SDK as a build makes it: in the language it writes titles in+// org.requests every request, in order, as { method, path } with the path below the host, decoded+// org.written() the sitemap XML the SDK last wrote, or '' when it wrote none+//+// `org.httpClient` is the SDK's HttpClient, which `makeDownloadSdk(env, { httpClient })` takes too. `organizationAnswer()` replaces the answer to the base-language read+// (a low-level answer: `{ statusCode, headers, body }`, or `{ error }` for a request that failed).+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const { createAzHttpClient } = require('../../lib/sdk-http-client.js');++const BUNDLE = path.resolve(__dirname, '..', '..', 'vendor', 'cds-maker-sdk.cjs');+const ENV = 'https://contoso.crm.dynamics.com';+const APP_ID = '11111111-1111-1111-1111-111111111111';+const APP_UNIQUE_ID = '22222222-2222-2222-2222-222222222222';+const APP_UNIQUE = 'contoso_casemanagement';+const SITEMAP_ID = '33333333-3333-3333-3333-333333333333';+const DASH = '44444444-4444-4444-4444-444444444444';+const TABLE_METADATA_ID = '55555555-5555-5555-5555-555555555555';+const ROLE_ID = '66666666-6666-6666-6666-666666666666';++const json = (statusCode, body, headers = {}) => ({ statusCode, headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify(body) });++// `{ 1033: 'Work', 3082: 'Trabajo' }` as the `<Titles>` the platform stores: one `<Title LCID="…" Title="…" />` per language. No languages is no `<Titles>` at all, as+// for a table entry, which the app shows under the table's own name.+const titles = (byLanguage) => {+ const entries = Object.entries(byLanguage || {});+ return entries.length ? `<Titles>${entries.map(([lcid, title]) => `<Title LCID="${lcid}" Title="${title}" />`).join('')}</Titles>` : '';+};++// The sitemap the app designer writes for one area, one group and two entries: a table and a dashboard. Each of area, group and dashboard takes its titles by language.+const sitemapXml = ({ area = {}, group = {}, dashboard = {} } = {}) => '<SiteMap IntroducedVersion="7.0.0.0">'+ + `<Area Id="area_0" ShowGroups="true" ResourceId="SitemapDesigner.NewTitle" DescriptionResourceId="SitemapDesigner.NewTitle" IntroducedVersion="7.0.0.0">${titles(area)}`+ + `<Group Id="group_0_0" ResourceId="SitemapDesigner.NewGroup" DescriptionResourceId="SitemapDesigner.NewGroup" ToolTipResourseId="SitemapDesigner.Unknown" IntroducedVersion="7.0.0.0" IsProfile="false">${titles(group)}`+ + '<SubArea Id="sub_0_0_0" Entity="contoso_case" ResourceId="SitemapDesigner.NewSubArea" Client="All,Outlook,OutlookLaptopClient,OutlookWorkstationClient,Web" Sku="All,OnPremise,Live,SPLA" AvailableOffline="true" PassParams="false" />'+ + `<SubArea Id="sub_0_0_1" DefaultDashboard="${DASH}" Url="/workplace/home_dashboards.aspx" ResourceId="SitemapDesigner.NewSubArea" Client="All,Outlook,OutlookLaptopClient,OutlookWorkstationClient,Web" Sku="All,OnPremise,Live,SPLA" AvailableOffline="true" PassParams="false">${titles(dashboard)}</SubArea>`+ + '</Group></Area></SiteMap>';++function createSitemapOrg({ xml, baseLanguage = 1033, organizationAnswer } = {}) {+ const requests = [];+ const writes = [];+ const appRow = () => ({ appmoduleid: APP_ID, appmoduleidunique: APP_UNIQUE_ID, name: 'Case Management', uniquename: APP_UNIQUE, description: '', '@odata.etag': 'W/"1"' });+ const sitemapRow = () => ({ sitemapid: SITEMAP_ID, sitemapnameunique: APP_UNIQUE, sitemapxml: xml, '@odata.etag': 'W/"1"' });+ const etag = { etag: 'W/"1"' };+ const written = (where, body) => {+ let parsed;+ try { parsed = body ? JSON.parse(body) : undefined; } catch { parsed = undefined; }+ if (/\/sitemaps\b/.test(where) && parsed && parsed.sitemapxml) writes.push(String(parsed.sitemapxml));+ };+ async function request({ url, method, body }) {+ const u = new URL(url);+ const where = decodeURIComponent(u.pathname + u.search);+ requests.push({ method, path: where });+ if (method === 'POST') {+ written(where, body);+ return { statusCode: 204, headers: { 'odata-entityid': `${ENV}/api/data/v9.0/appmodules(${APP_ID})` }, body: '' };+ }+ if (method === 'PATCH') {+ written(where, body);+ return { statusCode: 204, headers: {}, body: '' };+ }+ if (method !== 'GET') return { statusCode: 204, headers: {}, body: '' };+ if (/\/organizations\?/.test(where)) {+ return organizationAnswer ? organizationAnswer() : json(200, { value: [{ organizationid: '77777777-7777-7777-7777-777777777777', languagecode: baseLanguage }] });+ }+ const metadata = /EntityDefinitions\(LogicalName='([^']+)'\)/.exec(where);+ if (metadata) return json(200, { LogicalName: metadata[1], MetadataId: TABLE_METADATA_ID, EntitySetName: `${metadata[1]}s` });+ if (/\/appmodulecomponents/.test(where)) {+ const wantsSitemap = /componenttype eq 62/.test(where);+ return json(200, { value: wantsSitemap ? [{ objectid: SITEMAP_ID, componenttype: 62 }] : [{ objectid: TABLE_METADATA_ID, componenttype: 1 }] });+ }+ if (/\/sitemaps/.test(where)) {+ const many = /RetrieveUnpublishedMultiple/i.test(where) || /\/sitemaps\?/.test(where);+ return json(200, many ? { value: [sitemapRow()] } : sitemapRow(), etag);+ }+ if (/\/appmodules/.test(where)) {+ const many = /RetrieveUnpublishedMultiple/i.test(where) || /\/appmodules\?/.test(where);+ return json(200, many ? { value: [appRow()] } : appRow(), etag);+ }+ if (/\/roles/.test(where)) return json(200, { value: [{ roleid: ROLE_ID }] });+ return json(200, { value: [] });+ }+ const httpClient = createAzHttpClient(ENV, { getToken: () => 'token', request, sleep: async () => {} });+ return { httpClient, request, requests, written: () => writes[writes.length - 1] || '' };+}++// The real SDK over that org, in a throwaway workspace `dispose` removes. `languageCode` is the construction-time language the SDK reads and writes sitemap titles in.+async function createSdk(org, { languageCode } = {}) {+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'app-sitemap-org-'));+ const sdk = createMakerSdk({+ workspaceStorage: createNodeWorkspaceStorage(dir),+ instanceUrl: ENV,+ httpClient: org.httpClient,+ ...(languageCode ? { languageCode } : {}),+ });+ await sdk.initWorkspace();+ return { sdk, dispose: () => fs.rmSync(dir, { recursive: true, force: true }) };+}++module.exports = { createSitemapOrg, createSdk, sitemapXml, titles, json, ENV, APP_ID, APP_UNIQUE, DASH };diff --git a/plugins/model-apps/scripts/tests/helpers/column-gate-specs.js b/plugins/model-apps/scripts/tests/helpers/column-gate-specs.jsnew file mode 100644index 000000000..f6bd87d20--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/column-gate-specs.js@@ -0,0 +1,54 @@+'use strict';++// Spec builders shared by the tests of the two column rules a build depends on (column-autonumber-gate.test.js and column-required-gate.test.js): one+// small spec with one table, as the App Spec gate and the provision-entities input gate each take it, and the doubles the CLI's testable core runs+// against, which record every call so a test can say that nothing was called.++// The profiles whose spec is going to be built, or planned for a build. The structural profile (teardown's) is not one of them.+const BUILDING_PROFILES = ['design', 'plan', 'deploy'];++const column = (extra) => ({ schemaName: 'new_ref', displayName: 'Reference', ...extra });+const nameColumn = (extra = {}) => ({ schemaName: 'new_name', displayName: 'Name', ...extra });++// The smallest App Spec that validates under every profile, with one table whose columns and name column the test gives.+function appSpec({ columns = [], primaryAttribute = nameColumn() } = {}) {+ return {+ schemaVersion: 2,+ solution: { uniqueName: 'S', publisherPrefix: 'new' },+ app: { name: 'A' },+ entities: [{ schemaName: 'new_ticket', displayName: 'Ticket', primaryAttribute, columns }],+ forms: [],+ };+}++// The same table as the input of the provision-entities CLI (the App Spec subset /genpage and /app-builder pass through first).+function provisionInput({ columns = [], primaryAttribute = nameColumn() } = {}) {+ return {+ solution: { uniqueName: 'S', publisherPrefix: 'new' },+ entities: [{ schemaName: 'new_ticket', displayName: 'Ticket', primaryAttribute, columns }],+ relationships: [],+ };+}++// An error message from where `from` begins: the two gates word the table and the column differently (`entity new_ticket: column new_ref ...` and+// `entity 'new_ticket': column 'new_ref' ...`) and share what follows.+const tail = (message, from) => message.slice(message.indexOf(from));++// The CLI's testable core takes the SDK and the discovery client as dependencies. Both are watched: `touched` lists every method called on either, in order.+function watchedDeps() {+ const touched = [];+ const watch = (target) => new Proxy(target, { get: (t, key) => (typeof t[key] === 'function' ? (...args) => { touched.push(String(key)); return t[key](...args); } : t[key]) });+ const sdk = {+ queryRecords: async () => [{ solutionid: 's' }], createPublisher: async () => ({ id: 'p' }), createSolution: async () => ({ id: 's' }),+ createTable: async (o) => ({ logicalName: o.schemaName.toLowerCase(), entitySetName: `${o.schemaName.toLowerCase()}s`, metadataId: `tbl-${o.schemaName}` }),+ updateTable: async () => ({}), updateColumn: async () => ({}),+ createColumn: async (l, o) => ({ logicalName: o.schemaName.toLowerCase(), metadataId: `col-${o.schemaName}` }),+ createGlobalOptionSet: async () => ({ metadataId: 'g' }), insertStatusValue: async () => 1, createAlternateKey: async () => ({}),+ createCustomerColumn: async (l, o) => ({ logicalName: o.schemaName.toLowerCase(), metadataId: `col-${o.schemaName}` }),+ createRelationship: async (o) => ({ schemaName: o.schemaName, metadataId: `rel-${o.schemaName}` }),+ };+ const provision = { findTables: async () => [], findColumns: async () => [], fetchEntityMetadata: async (l) => ({ logicalName: l, entitySetName: `${l}s`, relationships: [] }), queryRecords: async () => [{ solutionid: 's' }] };+ return { touched, sdk: watch(sdk), provision: watch(provision) };+}++module.exports = { BUILDING_PROFILES, column, nameColumn, appSpec, provisionInput, tail, watchedDeps };diff --git a/plugins/model-apps/scripts/tests/helpers/dashboard-formxml.js b/plugins/model-apps/scripts/tests/helpers/dashboard-formxml.jsnew file mode 100644index 000000000..bdd0b24fe--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/dashboard-formxml.js@@ -0,0 +1,56 @@+'use strict';+// A dashboard's FormXML, shaped like the ones the platform stores, for the tests that drive the REAL bundle over a+// dashboard (download-dashboard-custom-control.test.js, verify-dashboard-custom-control.test.js): one tab and one section+// of four equal columns, a row per group of tiles, the control descriptions after the tabs, and the access element last.+//+// The class of a native grid or chart tile, spelled as the platform writes it in a dashboard (the case varies between+// sources), and the class every custom control shares.+const NATIVE_CLASS = '{E7A81278-8635-4d9e-8D4D-59480B391C5B}';+const CUSTOM_CLASS = '{F9A8A302-114E-466A-B582-6771B2AE0D92}';+const IFRAME_CLASS = '{FD2A7985-3187-444E-908D-6624B21F69C0}';+const WEB_RESOURCE_CLASS = '{9FDF5F91-88B1-47F4-AD53-C11EFC01A01D}';+// The uniqueid that makes a control on the custom-control class the Assistant, and not a grid or chart a custom control hosts.+const ASSISTANT_UNIQUE_ID = '3ff9a528-dd50-4aca-8f10-2e5ed73513ad';++// A tile's parameters, in the platform's order. `mode` is `Grid` or `Chart`.+const gridParameters = ({ mode = 'Grid', view, chart = '' }) => `<parameters><TargetEntityType>incident</TargetEntityType><ChartGridMode>${mode}</ChartGridMode>`+ + '<EnableQuickFind>true</EnableQuickFind><EnableViewPicker>true</EnableViewPicker><EnableJumpBar>true</EnableJumpBar><RecordsPerPage>8</RecordsPerPage>'+ + `<HeaderColorCode>#F3F3F3</HeaderColorCode><ViewId>{${view}}</ViewId><IsUserView>false</IsUserView><ViewIds>{${view}}</ViewIds><AutoExpand>Fixed</AutoExpand>`+ + `<VisualizationId>${chart ? `{${chart}}` : ''}</VisualizationId><IsUserChart>false</IsUserChart><EnableChartPicker>${chart ? 'true' : 'false'}</EnableChartPicker><RelationshipName /></parameters>`;++let cells = 0;+const cell = (label, control, { colspan = 2, rowspan = 8 } = {}) => {+ cells += 1;+ return `<cell colspan="${colspan}" rowspan="${rowspan}" showlabel="false" id="{aaaaaaaa-0000-4000-8000-${String(cells).padStart(12, '0')}}" auto="false">`+ + `<labels><label description="${label}" languagecode="1033" /></labels>${control}</cell>`;+};+const nativeGrid = (id, label, view) => cell(label, `<control id="${id}" classid="${NATIVE_CLASS}" indicationOfSubgrid="true">${gridParameters({ view })}</control>`);+const nativeChart = (id, label, view, chart) => cell(label, `<control id="${id}" classid="${NATIVE_CLASS}" indicationOfSubgrid="true">${gridParameters({ mode: 'Chart', view, chart })}</control>`);+// A grid or a chart a custom control hosts: the custom-control class and the control's own `uniqueid`, the grid parameters+// of a native tile, and a description of the hosted control among the dashboard's `controlDescriptions` (see dashboardXml).+const customGrid = (id, label, view, uniqueId) => cell(label, `<control id="${id}" classid="${CUSTOM_CLASS}" uniqueid="{${uniqueId}}" indicationOfSubgrid="true">${gridParameters({ view })}</control>`);+const customChart = (id, label, view, chart, uniqueId) => cell(label, `<control id="${id}" classid="${CUSTOM_CLASS}" uniqueid="{${uniqueId}}" indicationOfSubgrid="true">${gridParameters({ mode: 'Chart', view, chart })}</control>`);+// The Assistant: the custom-control class again, with its own uniqueid and none of the grid parameters.+const assistantTile = (id, label) => cell(label, `<control id="${id}" classid="${CUSTOM_CLASS}" uniqueid="{${ASSISTANT_UNIQUE_ID}}"><parameters /></control>`);+// Any other custom control: the custom-control class with a uniqueid of its own and no grid markers, so it is no grid or chart.+const otherCustomControl = (id, label, uniqueId) => cell(label, `<control id="${id}" classid="${CUSTOM_CLASS}" uniqueid="{${uniqueId}}"><parameters><Mode>compact</Mode></parameters></control>`);+const iframeTile = (id, label, url) => cell(label, `<control id="${id}" classid="${IFRAME_CLASS}"><parameters><Url>${url}</Url><PassParameters>false</PassParameters><Security>false</Security><Scrolling>auto</Scrolling><Border>true</Border></parameters></control>`, { colspan: 4, rowspan: 6 });+const webResourceTile = (id, label, name) => cell(label, `<control id="${id}" classid="${WEB_RESOURCE_CLASS}"><parameters><WebResourceName>${name}</WebResourceName><Url>${name}</Url><PassParameters>false</PassParameters><Security>false</Security><Scrolling>auto</Scrolling><Border>true</Border></parameters></control>`, { colspan: 4, rowspan: 6 });++const customDescription = (uniqueId, view) => `<controlDescription forControl="{${uniqueId}}"><customControl formFactor="0" name="MscrmControls.Grid.GridControl"><parameters>`+ + `<ViewId>{${view}}</ViewId><IsUserView>false</IsUserView><TargetEntityType>incident</TargetEntityType></parameters></customControl></controlDescription>`;++// `rows` is a list of rows, each a list of cells built by the functions above; `descriptions` are the control descriptions.+function dashboardXml(rows, descriptions = []) {+ cells = 0;+ const body = rows.map((row) => `<row>${row.join('')}</row>`).join('');+ return '<form><tabs><tab verticallayout="true" id="{bbbbbbbb-0000-4000-8000-000000000001}"><labels><label description="Tab" languagecode="1033" /></labels>'+ + '<columns><column width="100%"><sections><section showlabel="false" showbar="false" columns="1111" id="{bbbbbbbb-0000-4000-8000-000000000002}">'+ + `<labels><label description="Section" languagecode="1033" /></labels><rows>${body}</rows></section></sections></column></columns></tab></tabs>`+ + `<controlDescriptions>${descriptions.join('')}</controlDescriptions><DisplayConditions FallbackForm="true"><Everyone /></DisplayConditions></form>`;+}++module.exports = {+ NATIVE_CLASS, CUSTOM_CLASS, IFRAME_CLASS, WEB_RESOURCE_CLASS, ASSISTANT_UNIQUE_ID,+ nativeGrid, nativeChart, customGrid, customChart, assistantTile, otherCustomControl, iframeTile, webResourceTile, customDescription, dashboardXml,+};diff --git a/plugins/model-apps/scripts/tests/helpers/kill-target-client.js b/plugins/model-apps/scripts/tests/helpers/kill-target-client.jsindex 0ded171ab..b1144d4ca 100644--- a/plugins/model-apps/scripts/tests/helpers/kill-target-client.js+++ b/plugins/model-apps/scripts/tests/helpers/kill-target-client.js@@ -163,6 +163,11 @@ function startTarget(t, args, { env = {} } = {}) {if (!ended) child.kill('SIGKILL');return ending();},+ // A signal a program can handle, sent the way a parent or a timeout sends one — POSIX only: on Windows it is TerminateProcess, as above. Resolves with how the process ended: `{ code, signal }`.+ async signal(name) {+ if (!ended) child.kill(name);+ return ending();+ },};started.push({ args, pid: child.pid, child, isEnded: () => ended, said: () => ({ stdout: out.slice(-1000), stderr: err.slice(-1000), ended }) });armWatchdog();diff --git a/plugins/model-apps/scripts/tests/helpers/kill-target.js b/plugins/model-apps/scripts/tests/helpers/kill-target.jsindex 37727a8e8..9a9073796 100644--- a/plugins/model-apps/scripts/tests/helpers/kill-target.js+++ b/plugins/model-apps/scripts/tests/helpers/kill-target.js@@ -16,6 +16,14 @@// and waits to be killed.// node kill-target.js workspace-exit <prefix> makes one, removes it as a run does when it is done, and ends: `done`.// node kill-target.js workspace-keep <prefix> makes one and ends without removing it (a run that failed to): `workspace <folder>`.+// node kill-target.js workspace-abort <prefix> <how> [lent|removed]+// makes a workspace, puts a file in it and says `workspace <folder>`, then ends the way a run that is cut short does: <how> `exit` is process.exit(7), `throw` an error nothing catches (thrown from a timer, which ends+// the process with status 1). With `lent` the workspace is made LENT to another program (makeTempWorkspace(prefix, { lent: true })); with `removed` it is removed first, as the run's own `finally` would have.+// node kill-target.js workspace-listeners <prefix>+// makes one and says what the process listens for once it has — `listeners {"SIGINT":0,"SIGTERM":0,"SIGHUP":0,"SIGBREAK":0}` — then removes it and ends: `done`.+// node kill-target.js workspace-refused <prefix>+// makes one with a maker that refuses to make a folder inside the plugin's own folder (a full disk: ENOSPC), so that the workspace is made in the temp folder itself — which it says, `workspace <folder>` —+// and removes it, and ends: `done`. The plugin's folder was made, for the workspace that was refused.// node kill-target.js workspace-loop <prefix> <n> <ms> [<gateFile>]// n times: sweeps, makes a workspace, puts a file in it, waits <ms>, sweeps, checks that its own workspace is still whole (and recorded, if it is in the plugin's folder), removes it.// Says `ready`, waits for <gateFile> when one is given, and says `loop-done <how many times a workspace of its own was gone or unrecorded> <how many were made in the plain temp folder>`.@@ -28,6 +36,10 @@// node kill-target.js pac-worker <settingsFile> <workDir>// the fake pac's program: writes the first half of <settingsFile>, writes its pid to <workDir>/worker.json, waits for <workDir>/resume, writes the rest and// <workDir>/worker-result.json (what its write said), and ends.+// node kill-target.js pac-template-abort <workDir> <how>+// runs the deployment-settings template through pac as `pac-template` does, over a fake pac that starts no program: it writes the first half of the settings file in the folder it was given,+// says `workspace <folder>`, and then the run is cut short while pac "runs" — <how> `exit` is process.exit(7), `throw` an error nothing catches (thrown from a timer, which ends the process with+// status 1), `wait` nothing: the process waits to be signalled or killed.// node kill-target.js lent-worker <workDir>// makes a workspace LENT (`makeTempWorkspace(prefix, { lent: true })`, as solution-settings.js does for pac), says `workspace <folder>`, waits for <workDir>/go — a test that wants// to do something to the record meanwhile (hold it exclusively) does it then — and starts the `pac-worker` program, detached, in the folder: `worker <pid>`. Then waits to be killed.@@ -117,6 +129,35 @@ async function main() {const folder = makeTempWorkspace(args[0]);fs.writeFileSync(path.join(folder, 'page.tsx'), 'x');say(`workspace ${folder}`);+ } else if (mode === 'workspace-abort') {+ const { makeTempWorkspace } = require('../../lib/temp-workspace.js');+ const [prefix, how, option] = args;+ const folder = makeTempWorkspace(prefix, option === 'lent' ? { lent: true } : {});+ fs.writeFileSync(path.join(folder, 'page.tsx'), 'x');+ if (option === 'removed') fs.rmSync(folder, { recursive: true, force: true });+ say(`workspace ${folder}`);+ if (how === 'exit') process.exit(7);+ // From a timer, so that nothing in this file catches it: the process ends as it does for any error that nothing catches.+ if (how === 'throw') setImmediate(() => { throw new Error('an error nothing catches'); });+ } else if (mode === 'workspace-listeners') {+ const { makeTempWorkspace } = require('../../lib/temp-workspace.js');+ const folder = makeTempWorkspace(args[0]);+ const listeners = Object.fromEntries(['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGBREAK'].map((signal) => [signal, process.listenerCount(signal)]));+ say(`listeners ${JSON.stringify(listeners)}`);+ fs.rmSync(folder, { recursive: true, force: true });+ say('done');+ } else if (mode === 'workspace-refused') {+ const { makeTempWorkspace, workspaceParent } = require('../../lib/temp-workspace.js');+ const parent = workspaceParent();+ const folder = makeTempWorkspace(args[0], {+ mkdtempSync: (start) => {+ if (path.dirname(start) === parent) throw Object.assign(new Error(`ENOSPC: no space left on device, mkdir '${start}'`), { code: 'ENOSPC' });+ return fs.mkdtempSync(start);+ },+ });+ say(`workspace ${folder}`);+ fs.rmSync(folder, { recursive: true, force: true });+ say('done');} else if (mode === 'workspace-loop') {const { makeTempWorkspace, sweepDeadWorkspaces, workspaceParent } = require('../../lib/temp-workspace.js');const [prefix, iterations, ms, gate] = args;@@ -169,6 +210,22 @@ async function main() {await runTemplate({ command: 'template', packagePath, outPath: path.join(workDir, 'settings-out.json'), force: false }, { pac: { spawn } });say('done');process.exit(0);+ } else if (mode === 'pac-template-abort') {+ const [workDir, how] = args;+ const { runTemplate } = require('../../solution-settings.js');+ const packagePath = path.join(workDir, 'package.zip');+ fs.writeFileSync(packagePath, Buffer.from([0x50, 0x4b, 0x03, 0x04, 0x01]));+ const spawn = (_name, pacArgs) => {+ const settingsFile = pacArgs[pacArgs.indexOf('--settings-file') + 1];+ fs.writeFileSync(settingsFile, '{"EnvironmentVariables":');+ say(`workspace ${path.dirname(settingsFile)}`);+ if (how === 'exit') process.exit(7);+ // From a timer, so that nothing in this file catches it: the process ends as it does for any error that nothing catches.+ if (how === 'throw') setImmediate(() => { throw new Error('an error nothing catches'); });+ return new Promise(() => {});+ };+ wait();+ await runTemplate({ command: 'template', packagePath, outPath: path.join(workDir, 'settings-out.json'), force: false }, { pac: { spawn } });} else if (mode === 'lent-worker') {const [workDir] = args;const { makeTempWorkspace } = require('../../lib/temp-workspace.js');diff --git a/plugins/model-apps/scripts/tests/helpers/mock-sdk.js b/plugins/model-apps/scripts/tests/helpers/mock-sdk.jsindex 8ebde8c94..42dbfcf19 100644--- a/plugins/model-apps/scripts/tests/helpers/mock-sdk.js+++ b/plugins/model-apps/scripts/tests/helpers/mock-sdk.js@@ -14,12 +14,56 @@ function jpGet(o, p) { let c = o; for (const t of (p === '' ? [] : p.split('/').function jpSet(o, p, v) { const ts = p.split('/').slice(1); const l = ts.pop(); let c = o; for (const t of ts) c = c[t]; c[l] = v; }function jpRemove(o, p) { const ts = p.split('/').slice(1); const l = ts.pop(); let c = o; for (const t of ts) c = c[t]; if (Array.isArray(c)) c.splice(Number(l), 1); else delete c[l]; }const jclone = (v) => JSON.parse(JSON.stringify(v));-function seedForm(id) { return { id, tabs: [{ columns: [{ sections: [{ name: 'section_general', columns: 1, rows: [] }] }] }], bag: { a: [], c: [] } }; }+// The <DisplayConditions> the bundle gives every form it CREATES, as an entry of the form's root bag: offered to everyone,+// eligible as a fallback, and with no `Order` — a new form takes no slot in the maker's form order, so the build gives it+// one. The bundle's own entry sits at index 3, after the typed `tabs` and the header and footer it also adds.+// form-order-real-bundle.test.js compares all of this with the bundle.+const newFormDisplayConditions = () => ({ i: 3, node: { n: 'DisplayConditions', a: [['FallbackForm', 'true']], c: [{ n: 'Everyone', a: [], c: [] }] } });+// What `getFormSecurityRoles` answers for a stored <DisplayConditions> node, as the bundle reads it: `order` is left out+// when the element has none, `fallbackForm` is true only for "true", a role id is bare and lower-case, and a form with no+// element answers undefined (no display condition at all, which is not "offered to everyone").+function rolesOfDisplayConditions(node) {+ if (!node) return undefined;+ const attribute = (name) => { const pair = (node.a || []).find((p) => p[0] === name); return pair ? pair[1] : undefined; };+ const children = node.c || [];+ const roleIds = children.filter((c) => c.n === 'Role').map((c) => String(((c.a || []).find((p) => p[0] === 'Id') || [])[1] || '').replace(/[{}]/g, '').toLowerCase()).filter(Boolean);+ const order = attribute('Order');+ return {+ ...(children.some((c) => c.n === 'Everyone') ? { everyone: true } : {}),+ ...(roleIds.length ? { roleIds } : {}),+ fallbackForm: attribute('FallbackForm') === 'true',+ ...(order !== undefined && order !== '' ? { order: Number(order) } : {}),+ };+}+// What a form stores after `setFormSecurityRoles(formId, opts)`, as the bundle applies it to the roles `stored` holds+// (undefined: no element). `everyone` or a role list REPLACES the element and keeps the order and the fallback setting+// unless they are given; an order or fallback setting alone edits the existing element and is refused when there is none;+// `{}` removes the element.+function applyRolesWrite(stored, opts) {+ const roleIds = (opts.roleIds || []).map((id) => String(id).replace(/[{}]/g, '').toLowerCase());+ if (opts.everyone && roleIds.length) throw new Error('setFormSecurityRoles: `everyone` and `roleIds` are mutually exclusive — the platform models <Everyone /> as a replacement for the <Role> list, not an addition to it.');+ if (!opts.everyone && !roleIds.length) {+ if (opts.order === undefined && opts.fallbackForm === undefined) return undefined;+ if (!stored) throw new Error('setFormSecurityRoles: `order`/`fallbackForm` were supplied without `roleIds` or `everyone`, but this form has no <DisplayConditions> to attach them to. Pass the roles as well.');+ return { ...stored, ...(opts.order !== undefined ? { order: opts.order } : {}), ...(opts.fallbackForm !== undefined ? { fallbackForm: opts.fallbackForm } : {}) };+ }+ const prior = stored || {};+ return {+ ...(opts.everyone ? { everyone: true } : { roleIds }),+ fallbackForm: opts.fallbackForm !== undefined ? opts.fallbackForm : prior.fallbackForm === true,+ ...(opts.order !== undefined ? { order: opts.order } : (prior.order !== undefined ? { order: prior.order } : {})),+ };+}+function seedForm(id, created) { return { id, tabs: [{ columns: [{ sections: [{ name: 'section_general', columns: 1, rows: [] }] }] }], bag: { a: [], c: created ? [newFormDisplayConditions()] : [] } }; }function makeSimpleMockSdk() {const calls = [];let idc = 0;const store = {};+ const createdForms = new Set();+ // The roles a form THIS mock created holds once it is pushed (see getFormSecurityRoles); an entry of undefined is a+ // form whose <DisplayConditions> was removed.+ const storedRoles = new Map();const sdk = {queryRecords: async (e) => (e === 'solution' ? [] : [{ publisherid: 'pub-1' }]),createPublisher: async () => ({ id: 'pub-new' }),@@ -47,12 +91,22 @@ function makeSimpleMockSdk() {createArtifact: (t, def) => {calls.push(['createArtifact', t]);const id = `${t}-${++idc}`;- const art = t === 'form' ? Object.assign(seedForm(id), { name: def.name, entityLogicalName: def.entityLogicalName, formType: def.formType, status: def.status })+ const art = t === 'form' ? Object.assign(seedForm(id, true), { name: def.name, entityLogicalName: def.entityLogicalName, formType: def.formType, status: def.status }): t === 'dashboard' ? Object.assign({ id, components: [] }, def) : Object.assign({ id }, def);- art.id = id; store[`${t}:${id}`] = art; return jclone(art);+ art.id = id; store[`${t}:${id}`] = art;+ if (t === 'form') createdForms.add(id);+ return jclone(art);},createWebResource: async (o) => { calls.push(['createWebResource', o.name]); return { id: `wr-${++idc}`, name: o.name }; },- pushArtifact: async (t, id) => ({ type: t, id, saved: true, shipped: false, publish: { kind: 'notRequested' } }),+ pushArtifact: async (t, id) => {+ // A form this mock created is stored as its local copy says at its FIRST push: the build edits that copy before it+ // (createInPlace writes the order into it), and later changes to a form reach the environment through their own calls.+ if (t === 'form' && createdForms.has(id) && !storedRoles.has(id)) {+ const entry = ((store[`form:${id}`] || {}).bag.c || []).find((e) => e && e.node && e.node.n === 'DisplayConditions');+ storedRoles.set(id, rolesOfDisplayConditions(entry && entry.node));+ }+ return { type: t, id, saved: true, shipped: false, publish: { kind: 'notRequested' } };+ },getArtifact: async (t, id) => { await Promise.resolve(); return store[`${t}:${id}`] || { id, columns: [] }; },fetchArtifact: async (t, id) => { if (!store[`${t}:${id}`]) store[`${t}:${id}`] = t === 'form' ? seedForm(id) : t === 'app' ? { id, siteMap: { areas: [] } } : { id, columns: [] }; return store[`${t}:${id}`]; },addElement: async (t, id, ptr, el) => { await Promise.resolve(); const a = store[`${t}:${id}`] || (store[`${t}:${id}`] = { id }); const arr = jpGet(a, ptr); if (Array.isArray(arr)) arr.push(jclone(el)); return jclone(a); },@@ -61,11 +115,19 @@ function makeSimpleMockSdk() {updateRecord: async () => undefined,addSolutionComponent: async () => undefined,publishArtifact: async (type, id) => ({ type, id, shipped: true, publish: { kind: 'verified' } }),- // A form's <DisplayConditions> as a new form carries them (Order 0, offered to everyone). The forms- // phase reads them to set each table's Main Form Set order (AB#6736948), and writes only the forms- // that are not yet in place — so a table with one Main form costs no write.- getFormSecurityRoles: async () => ({ everyone: true, fallbackForm: true, order: 0 }),- setFormSecurityRoles: async (formId, opts) => { calls.push(['setFormSecurityRoles', formId, opts]); },+ // A form's <DisplayConditions>, read back as the bundle reads them. A form this mock created holds what its local copy+ // said at its first push — the element the bundle gives every new form, with NO order — so the forms phase writes the+ // order of every Main form it sets, the first of a table included, and a rebuild finds it in place. A form the mock+ // never created already exists in the environment, and is answered as the first form of its table (order 0).+ getFormSecurityRoles: async (formId) => {+ if (!storedRoles.has(formId)) return { everyone: true, fallbackForm: true, order: 0 };+ const stored = storedRoles.get(formId);+ return stored === undefined ? undefined : jclone(stored);+ },+ setFormSecurityRoles: async (formId, opts) => {+ calls.push(['setFormSecurityRoles', formId, opts]);+ if (storedRoles.has(formId)) storedRoles.set(formId, applyRolesWrite(storedRoles.get(formId), opts));+ },getAiReadiness: async (opts) => { calls.push(['getAiReadiness', opts]); return { enabled: true }; },// The real SDK writes every requested value (Off included) and lists each one it proves; the// build encodes flags to setting values first, so no feature arrives here as a falsy boolean.@@ -80,4 +142,4 @@ function makeSimpleMockSdk() {return { sdk, calls };}-module.exports = { makeSimpleMockSdk };+module.exports = { makeSimpleMockSdk, newFormDisplayConditions, rolesOfDisplayConditions, applyRolesWrite };diff --git a/plugins/model-apps/scripts/tests/helpers/solution-settings-work-folder.js b/plugins/model-apps/scripts/tests/helpers/solution-settings-work-folder.jsindex 1a79444bd..18591a350 100644--- a/plugins/model-apps/scripts/tests/helpers/solution-settings-work-folder.js+++ b/plugins/model-apps/scripts/tests/helpers/solution-settings-work-folder.js@@ -103,8 +103,8 @@ function refusingWorkFolders(t, { plugin = 'ENOSPC', plain = 'EACCES' } = {}) {};t.after(() => {fs.mkdtempSync = real;- // The maker makes the plugin's folder before it asks it for a workspace, and removes it when the process ends only if a workspace was made in it: with none, it is this test's to remove (`rmdir` takes- // an empty folder and nothing else).+ // The maker makes the plugin's folder before it asks it for a workspace, and takes it away when the process ends if nothing is in it, a refused workspace included: the tests that follow in this process should not find it+ // either, so it is this test's to remove now (`rmdir` takes an empty folder and nothing else).try { fs.rmdirSync(pluginFolderOf()); } catch { /* not there, or something is in it */ }});return refused;diff --git a/plugins/model-apps/scripts/tests/killed-run-workspaces.test.js b/plugins/model-apps/scripts/tests/killed-run-workspaces.test.jsindex c4c1931e8..f08a5b437 100644--- a/plugins/model-apps/scripts/tests/killed-run-workspaces.test.js+++ b/plugins/model-apps/scripts/tests/killed-run-workspaces.test.js@@ -179,3 +179,32 @@ test('a run that lends its workspace to a program and finishes normally removesassert.deepStrictEqual(JSON.parse(fs.readFileSync(path.join(work, 'settings-out.json'), 'utf8')), { EnvironmentVariables: [], ConnectionReferences: [] }, 'and wrote what pac wrote, at --out');assert.deepStrictEqual(fs.readdirSync(root).filter((name) => name !== path.basename(work)), [], 'nothing of the plugin\'s is left in the temp folder');});++// The end of a run takes the plugin's folder when nothing is left in it (lib/temp-workspace.js), but a workspace that is LENT is not the maker's to take: the cleanup that solution-settings.js registers for the end of the+// process (lib/exit-cleanup.js) removes it. That cleanup runs after the maker's own listener, which has by then found the lent workspace still in the plugin's folder and left the folder — so the folder was left behind, empty,+// by every run that was cut short while pac ran. REAL processes, over a fake pac that cuts the run short.+for (const [what, how, status] of [['process.exit(7)', 'exit', 7], ['an error nothing catches', 'throw', 1]]) {+ test(`a run that ends by ${what} while pac runs takes the workspace it lent to pac and the plugin's folder with it, and ends with the status it would have had`, async (t) => {+ const root = privateTempRoot(t);+ const work = fs.mkdtempSync(path.join(root, 'work-'));+ const run = startTarget(t, ['pac-template-abort', work, how], { env: tempEnv(root) });+ const folder = (await run.waitFor(/^workspace /, WORKER_TIME)).slice('workspace '.length);+ assert.strictEqual(path.dirname(folder), workspaceParent({ os: { tmpdir: () => root } }), 'pac was given a folder in the plugin\'s own folder');+ const ended = await run.exited;+ assert.deepStrictEqual([ended.code, ended.signal], [status, null], 'the status is the one the run would have ended with');+ assert.ok(!fs.existsSync(folder), 'the workspace lent to pac is removed: it held the settings file pac was writing');+ assert.deepStrictEqual(fs.readdirSync(root), [path.basename(work)], 'and the temp folder is as the run found it: the plugin\'s folder is not left behind, empty');+ });+}++// A signal ends a POSIX process with no `exit` event, so the maker's listener never runs: the cleanup of solution-settings.js (the signal handler of lib/exit-cleanup.js) is all that runs, and it takes the folder too.+test('POSIX: a run that is signalled while pac runs takes the workspace it lent to pac and the plugin\'s folder with it, and ends BY the signal', { skip: process.platform === 'win32' && 'a signal is TerminateProcess on Windows: nothing runs' }, async (t) => {+ const root = privateTempRoot(t);+ const work = fs.mkdtempSync(path.join(root, 'work-'));+ const run = startTarget(t, ['pac-template-abort', work, 'wait'], { env: tempEnv(root) });+ const folder = (await run.waitFor(/^workspace /, WORKER_TIME)).slice('workspace '.length);+ const ended = await run.signal('SIGTERM');+ assert.deepStrictEqual([ended.code, ended.signal], [null, 'SIGTERM'], 'ended by the signal, and not by an exit status');+ assert.ok(!fs.existsSync(folder), 'the workspace lent to pac is removed');+ assert.deepStrictEqual(fs.readdirSync(root), [path.basename(work)], 'and so is the plugin\'s folder');+});diff --git a/plugins/model-apps/scripts/tests/nav-titles-base-language-real-bundle.test.js b/plugins/model-apps/scripts/tests/nav-titles-base-language-real-bundle.test.jsnew file mode 100644index 000000000..3c50cba3b--- /dev/null+++ b/plugins/model-apps/scripts/tests/nav-titles-base-language-real-bundle.test.js@@ -0,0 +1,316 @@+'use strict';+// REAL-BUNDLE tests for an environment whose base language is not 1033: its navigation titles in a download, and in the rebuild of what the download wrote.+//+// Reported on a Spanish-only environment (base language 3082, no other language provisioned): a download wrote an empty `label` / `title` for every area, group and+// entry, and a rebuild of that spec wrote the navigation titles back as nothing. The SDK projects a sitemap's titles in ONE language, the one it is constructed with: a node's+// title is the `<Title LCID="…">` whose LCID is that language, and "" when it has none. The download built its SDK with no language, which is 1033 — a language the+// environment does not hold — so every title read as "", and the build, which does pass the environment's language, then took that "" for the author's wish to have no title.+//+// These drive the real bundle over a fake Dataverse (helpers/app-sitemap-org.js), the real `makeDownloadSdk`, `hydrateSpec`, `appDef` and `adoptLiveSitemap`, and read the+// sitemap XML the SDK actually writes.+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 { makeDownloadSdk, main } = require('../download-model-app.js');+const { hydrateSpec } = require('../lib/hydrate-spec.js');+const { appDef } = require('../lib/sdk-build.js');+const { adoptLiveSitemap, describeSitemapNotes, chromeByTargetKey } = require('../lib/sitemap-merge.js');+const { createSitemapOrg, createSdk, sitemapXml, titles, json, ENV, APP_ID, APP_UNIQUE, DASH } = require('./helpers/app-sitemap-org.js');++const DASHBOARD_NAME = 'Case overview';+const CREATED = { dashboards: { [DASHBOARD_NAME]: DASH } };++const tempDirs = [];+test.after(() => { for (const dir of tempDirs) fs.rmSync(dir, { recursive: true, force: true }); });+const tmp = (prefix) => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));+ tempDirs.push(dir);+ return dir;+};++// The titles each node of the fixture sitemap holds, by language: { area, group, table, dashboard } -> { <lcid>: title }. A node with no `<Titles>` holds none.+function heldTitles(xml) {+ const by = (fragment) => Object.fromEntries([...String(fragment || '').matchAll(/<Title LCID="(\d+)" Title="([^"]*)" \/>/g)].map((m) => [m[1], m[2]]));+ const first = (re) => (re.exec(xml) || [])[1];+ const entry = (needle) => (new RegExp(`<SubArea\\b[^>]*${needle}[^>]*?(?:/>|>(.*?)</SubArea>)`).exec(xml) || [])[1];+ return {+ area: by(first(/<Area\b[^>]*>(<Titles>.*?<\/Titles>)/)),+ group: by(first(/<Group\b[^>]*>(<Titles>.*?<\/Titles>)/)),+ table: by(entry('Entity="contoso_case"')),+ dashboard: by(entry('DefaultDashboard=')),+ };+}++// What a download reads of the app: the SDK as `makeDownloadSdk` makes it, then the App Spec's navigation `hydrateSpec` writes from it.+async function download(org, deps = {}) {+ const made = await makeDownloadSdk(ENV, { httpClient: org.httpClient, ...deps });+ try {+ const app = await made.sdk.fetchArtifact('app', APP_ID);+ const spec = await hydrateSpec({+ app: async () => ({ ...app, uniquename: APP_UNIQUE }),+ pages: async () => [],+ entities: async () => [],+ webResources: async () => [],+ solution: async () => ({ uniqueName: 'ContosoCases', publisherPrefix: 'contoso' }),+ dashboards: async () => [{ id: DASH, name: DASHBOARD_NAME, tiles: [] }],+ });+ return { app, spec, shell: spec.appShell, languageUnresolved: made.languageUnresolved };+ } finally {+ made.cleanup();+ }+}+const labels = (shell) => {+ const group = shell.areas[0].groups[0];+ return { area: shell.areas[0].label, group: group.label, entries: group.subAreas.map((s) => s.title) };+};+const asksForLanguage = (org) => org.requests.filter((r) => /\/organizations\?/.test(r.path));++const SPANISH = { area: { 3082: 'Trabajo' }, group: { 3082: 'Casos' }, dashboard: { 3082: 'Panel de casos' } };+const ENGLISH = { area: { 1033: 'Work' }, group: { 1033: 'Cases' }, dashboard: { 1033: 'Case dashboard' } };+const BOTH = { area: { 1033: 'Work', 3082: 'Trabajo' }, group: { 1033: 'Cases', 3082: 'Casos' }, dashboard: { 1033: 'Case dashboard', 3082: 'Panel de casos' } };++// --- the download ----------------------------------------------------------------------------------------------------------------------------------------------------++test('REAL BUNDLE: a download of a Spanish-only environment writes the navigation titles it holds', async () => {+ const org = createSitemapOrg({ xml: sitemapXml(SPANISH), baseLanguage: 3082 });+ const { shell, languageUnresolved } = await download(org);+ assert.deepStrictEqual(labels(shell), { area: 'Trabajo', group: 'Casos', entries: ['', 'Panel de casos'] });+ // The shape is the App Spec's own and carries no language: the table entry has no title of its own (the app shows the table's name), the dashboard entry names its dashboard.+ assert.deepStrictEqual(shell, { areas: [{ label: 'Trabajo', groups: [{ label: 'Casos', subAreas: [{ title: '', entity: 'contoso_case' }, { title: 'Panel de casos', dashboard: DASHBOARD_NAME }] }] }] });+ assert.strictEqual(languageUnresolved, undefined, 'the language was read');+});++test('REAL BUNDLE: an English environment downloads exactly the titles it always did', async () => {+ const org = createSitemapOrg({ xml: sitemapXml(ENGLISH), baseLanguage: 1033 });+ const { shell, languageUnresolved } = await download(org);+ assert.deepStrictEqual(shell, { areas: [{ label: 'Work', groups: [{ label: 'Cases', subAreas: [{ title: '', entity: 'contoso_case' }, { title: 'Case dashboard', dashboard: DASHBOARD_NAME }] }] }] });+ assert.strictEqual(languageUnresolved, undefined);+});++test('REAL BUNDLE: a download asks the environment for its base language once', async () => {+ const org = createSitemapOrg({ xml: sitemapXml(ENGLISH), baseLanguage: 1033 });+ await download(org);+ assert.strictEqual(asksForLanguage(org).length, 1);+});++test('REAL BUNDLE: a bilingual environment downloads the titles in its base language, whichever that is', async () => {+ const english = await download(createSitemapOrg({ xml: sitemapXml(BOTH), baseLanguage: 1033 }));+ assert.deepStrictEqual(labels(english.shell), { area: 'Work', group: 'Cases', entries: ['', 'Case dashboard'] });+ // The App Spec labels are written at the language a rebuild resolves, which is the base language: Spanish text must not come back as the Spanish title\u2019s English twin.+ const spanish = await download(createSitemapOrg({ xml: sitemapXml(BOTH), baseLanguage: 3082 }));+ assert.deepStrictEqual(labels(spanish.shell), { area: 'Trabajo', group: 'Casos', entries: ['', 'Panel de casos'] });+});++test('REAL BUNDLE: a language an author pinned in the spec on disk is the one the titles are read in, and the environment is not asked', async () => {+ const org = createSitemapOrg({ xml: sitemapXml({ area: { 1033: 'Work', 1036: 'Travail' }, group: { 1033: 'Cases', 1036: 'Dossiers' }, dashboard: { 1033: 'Dashboard', 1036: 'Tableau' } }), baseLanguage: 1033 });+ const { shell } = await download(org, { authoredLanguageCode: 1036 });+ assert.deepStrictEqual(labels(shell), { area: 'Travail', group: 'Dossiers', entries: ['', 'Tableau'] });+ assert.deepStrictEqual(asksForLanguage(org), [], 'a rebuild resolves the pinned language before the environment\u2019s, so the download does too');+});++// A base language that cannot be read is no language: download-navigation-language.test.js holds what the download does then (it stops and writes nothing).++// --- what `main` hands it ---------------------------------------------------------------------------------------------------------------------------------------++function mainDeps(outDir, seen, extraArgv = []) {+ const stderr = [];+ const results = [];+ return {+ stderr,+ results,+ deps: {+ argv: ['--env', ENV, '--app', APP_UNIQUE, '--out', outDir, ...extraArgv],+ stderr: { write: (text) => { stderr.push(String(text)); } },+ emitResult: (ok, payload) => results.push({ ok, payload }),+ preflightAuth: async () => ({ ok: true }),+ makeGenpageSdk: () => ({}),+ makeDownloadSdk: async (env, passed) => {+ seen.push(passed);+ return { sdk: { queryRecords: async (_set, opts = {}) => (/uniquename eq/.test(opts.filter || '') ? [{ appmoduleid: APP_ID }] : [{ uniquename: APP_UNIQUE }]) }, cleanup() {} };+ },+ runDownload: async () => ({+ ok: true,+ spec: { schemaVersion: 2, solution: { uniqueName: 'ContosoCases', publisherPrefix: 'contoso' }, app: { name: 'Case Management', uniqueName: APP_UNIQUE }, entities: [], pages: [], appShell: { areas: [] } },+ pages: [], entities: [], webResources: [], droppedSubareas: 0, droppedSubareaDetails: [], dashboardWarnings: [],+ }),+ validateAppSpec: () => ({ ok: true, warnings: [] }),+ },+ };+}++test('main hands the download SDK the language pinned in the spec already on disk, and the language it was given', async () => {+ const outDir = tmp('nav-main-');+ fs.writeFileSync(path.join(outDir, 'app-spec.json'), JSON.stringify({ languageCode: 3082 }));+ const seen = [];+ const { deps } = mainDeps(outDir, seen);+ await main(deps);+ assert.strictEqual(seen.length, 1);+ assert.strictEqual(seen[0].authoredLanguageCode, 3082);+ assert.strictEqual(seen[0].languageCode, undefined, 'no flag, no language of the operator\u2019s');+ const flagged = [];+ await main(mainDeps(tmp('nav-main-'), flagged, ['--language-code', '1036']).deps);+ assert.strictEqual(flagged[0].languageCode, 1036);+ assert.strictEqual(flagged[0].authoredLanguageCode, undefined);+});++test('main pins no language for a spec that has none, an unreadable one, or one whose language is not an LCID', async () => {+ for (const [what, write] of [+ ['no spec on disk', () => {}],+ ['a spec that is not JSON', (dir) => fs.writeFileSync(path.join(dir, 'app-spec.json'), '{ nope')],+ ['a spec with no language', (dir) => fs.writeFileSync(path.join(dir, 'app-spec.json'), JSON.stringify({ app: {} }))],+ ['a language that is no LCID', (dir) => fs.writeFileSync(path.join(dir, 'app-spec.json'), JSON.stringify({ languageCode: 'es-ES' }))],+ ]) {+ const outDir = tmp('nav-main-');+ write(outDir);+ const seen = [];+ const { deps, stderr } = mainDeps(outDir, seen);+ await main(deps);+ assert.strictEqual(seen.length, 1, what);+ assert.strictEqual(seen[0].authoredLanguageCode, undefined, what);+ assert.ok(!stderr.some((line) => /base language/.test(line)), `${what}: nothing is said about a language nobody asked about`);+ }+});++// --- the rebuild -----------------------------------------------------------------------------------------------------------------------------------------------++const specFor = (shell) => ({ solution: { uniqueName: 'ContosoCases', publisherPrefix: 'contoso' }, app: { name: 'Case Management', uniqueName: APP_UNIQUE }, appShell: shell });++/** What the build does for an existing app: fetch it in the language the build resolved, re-attach the spec's navigation to the live nodes, write, push. */+async function rebuild(org, shell, { languageCode, baseChrome } = {}) {+ const { sdk, dispose } = await createSdk(org, { languageCode });+ try {+ await sdk.fetchArtifact('app', APP_ID);+ const live = await sdk.getArtifact('app', APP_ID);+ const { siteMap, notes } = adoptLiveSitemap(appDef(specFor(shell), CREATED).siteMap, live.siteMap, { lcid: languageCode, baseChrome });+ await sdk.updateElement('app', APP_ID, '/siteMap', siteMap);+ await sdk.pushArtifact('app', APP_ID);+ return { xml: org.written(), notes };+ } finally {+ dispose();+ }+}++test('REAL BUNDLE: the spec an earlier download wrote on a Spanish-only environment, with every label empty, rebuilds with every title as it was', async () => {+ const xml = sitemapXml(SPANISH);+ const emptied = { areas: [{ label: '', groups: [{ label: '', subAreas: [{ title: '', entity: 'contoso_case' }, { title: '', dashboard: DASHBOARD_NAME }] }] }] };+ const { xml: written, notes } = await rebuild(createSitemapOrg({ xml, baseLanguage: 3082 }), emptied, { languageCode: 3082 });+ assert.deepStrictEqual(heldTitles(written), heldTitles(xml), `the titles are as they were:\n${written}`);+ assert.deepStrictEqual(heldTitles(written), { area: { 3082: 'Trabajo' }, group: { 3082: 'Casos' }, table: {}, dashboard: { 3082: 'Panel de casos' } });+ const lines = describeSitemapNotes(notes);+ assert.strictEqual(lines.length, 3, JSON.stringify(lines));+ for (const [line, node, title] of [[lines[0], 'area', 'Trabajo'], [lines[1], 'group', 'Casos'], [lines[2], 'nav entry', 'Panel de casos']]) {+ assert.match(line, new RegExp(`^${node} "${title}": kept the environment's title '${title}' \u2014 the spec has none for it`), line);+ }+});++test('REAL BUNDLE: the same spec rebuilds with every title as it was when the download that wrote it also left its baseline', async () => {+ const xml = sitemapXml(SPANISH);+ const emptied = { areas: [{ label: '', groups: [{ label: '', subAreas: [{ title: '', entity: 'contoso_case' }, { title: '', dashboard: DASHBOARD_NAME }] }] }] };+ const { xml: written, notes } = await rebuild(createSitemapOrg({ xml, baseLanguage: 3082 }), emptied, { languageCode: 3082, baseChrome: chromeByTargetKey(specFor(emptied), CREATED) });+ assert.deepStrictEqual(heldTitles(written), heldTitles(xml), `the titles are as they were:\n${written}`);+ assert.strictEqual(describeSitemapNotes(notes).length, 3, 'an area, a group and an entry the spec says nothing about: each kept, each said');+});++test('REAL BUNDLE: a title the spec states is written, as it always was, and the language the spec does not mention is not touched', async () => {+ const xml = sitemapXml(BOTH);+ const stated = { areas: [{ label: 'Operaciones', groups: [{ label: 'Expedientes', subAreas: [{ title: '', entity: 'contoso_case' }, { title: 'Resumen', dashboard: DASHBOARD_NAME }] }] }] };+ const { xml: written, notes } = await rebuild(createSitemapOrg({ xml, baseLanguage: 3082 }), stated, { languageCode: 3082 });+ assert.deepStrictEqual(heldTitles(written), {+ area: { 1033: 'Work', 3082: 'Operaciones' },+ group: { 1033: 'Cases', 3082: 'Expedientes' },+ table: {},+ dashboard: { 1033: 'Case dashboard', 3082: 'Resumen' },+ });+ assert.deepStrictEqual(describeSitemapNotes(notes).map((line) => line.replace(/ to the spec's .*$/, '')), [+ 'area "Trabajo": title changes from \'Trabajo\'',+ 'group "Casos": title changes from \'Casos\'',+ 'nav entry "Panel de casos": title changes from \'Panel de casos\'',+ ]);+});++for (const [what, titlesByNode, baseLanguage] of [+ ['a Spanish-only environment', SPANISH, 3082],+ ['an English environment', ENGLISH, 1033],+ ['a bilingual environment whose base language is English', BOTH, 1033],+ ['a bilingual environment whose base language is Spanish', BOTH, 3082],+]) {+ test(`REAL BUNDLE: ${what} downloads and rebuilds with every title, in every language, as it was`, async () => {+ const xml = sitemapXml(titlesByNode);+ const { shell } = await download(createSitemapOrg({ xml, baseLanguage }));+ const { xml: written, notes } = await rebuild(createSitemapOrg({ xml, baseLanguage }), shell, { languageCode: baseLanguage });+ assert.deepStrictEqual(heldTitles(written), heldTitles(xml), `${what}:\n${written}`);+ assert.deepStrictEqual(describeSitemapNotes(notes), [], 'the spec says what the environment holds: there is nothing to report');+ });+}++test('REAL BUNDLE: the baseline a download writes for the spec it wrote keeps a title the environment gained since, whatever language it is in', async () => {+ const downloadedFrom = sitemapXml(SPANISH);+ const { shell } = await download(createSitemapOrg({ xml: downloadedFrom, baseLanguage: 3082 }));+ const baseline = specFor(shell);+ const renamed = sitemapXml({ ...SPANISH, dashboard: { 3082: 'Panel de expedientes' } });+ const { xml: written, notes } = await rebuild(createSitemapOrg({ xml: renamed, baseLanguage: 3082 }), shell, { languageCode: 3082, baseChrome: chromeByTargetKey(baseline, CREATED) });+ assert.deepStrictEqual(heldTitles(written).dashboard, { 3082: 'Panel de expedientes' }, 'the designer\u2019s rename survives a rebuild of the stale spec');+ assert.ok(describeSitemapNotes(notes).some((line) => /kept the environment's title 'Panel de expedientes'/.test(line)), JSON.stringify(describeSitemapNotes(notes)));+});++// --- a group with no entries -----------------------------------------------------------------------------------------------------------------------------------+// The spec an earlier download wrote on such an environment holds a group for each EMPTY group the environment has too, with its label left out; and the live group has an id the+// designer gave it (`designer_future`), which a spec cannot name. With no label and no entries it has nothing to be recognized by, so a rebuild wrote a new, untitled group+// in its place and the title was gone.+const emptyGroupXml = (id, byLanguage) => `<Group Id="${id}" ResourceId="SitemapDesigner.NewGroup" DescriptionResourceId="SitemapDesigner.NewGroup" ToolTipResourseId="SitemapDesigner.Unknown" IntroducedVersion="7.0.0.0" IsProfile="false">${titles(byLanguage)}</Group>`;+const withEmptyGroups = (xml, ...groups) => xml.replace('</Area>', `${groups.join('')}</Area>`);+// The titles the group `id` holds in the sitemap XML the SDK wrote, by language; null when the group is not in it.+const groupTitles = (xml, id) => {+ const group = new RegExp(`<Group\\b[^>]*Id="${id}"[^>]*?(?:/>|>(.*?)</Group>)`).exec(xml);+ return group ? Object.fromEntries([...String(group[1] || '').matchAll(/<Title LCID="(\d+)" Title="([^"]*)" \/>/g)].map((m) => [m[1], m[2]])) : null;+};+const downloadedBefore = (...emptyGroupLabels) => ({ areas: [{ label: '', groups: [+ { label: '', subAreas: [{ title: '', entity: 'contoso_case' }, { title: '', dashboard: DASHBOARD_NAME }] },+ ...emptyGroupLabels.map((label) => ({ label, subAreas: [] })),+] }] });+const noEntries = (lines) => lines.filter((line) => /has no entries/.test(line));++test('REAL BUNDLE: the spec an earlier download wrote, with an unlabelled empty group beside the environment\u2019s one empty group, rebuilds with that group and its title as they were', async () => {+ const xml = withEmptyGroups(sitemapXml(SPANISH), emptyGroupXml('designer_future', { 3082: 'Futuro' }));+ const emptied = downloadedBefore('');+ const { xml: written, notes } = await rebuild(createSitemapOrg({ xml, baseLanguage: 3082 }), emptied, { languageCode: 3082, baseChrome: chromeByTargetKey(specFor(emptied), CREATED) });+ assert.deepStrictEqual(groupTitles(written, 'designer_future'), { 3082: 'Futuro' }, `the empty group is as it was:\n${written}`);+ assert.strictEqual(groupTitles(written, 'group_0_1'), null, 'and no new group stands in its place');+ assert.deepStrictEqual(heldTitles(written).group, { 3082: 'Casos' }, 'the group beside it is as it was too');+ assert.ok(describeSitemapNotes(notes).includes('group "Futuro": kept the environment\'s title \'Futuro\' \u2014 the spec has none for it, so it is left as it is. State one in the spec to change it.'), JSON.stringify(describeSitemapNotes(notes)));+});++test('REAL BUNDLE: with two unlabelled empty groups and two empty groups in the environment nothing is paired by position, and the rebuild names the titles it does not keep', async () => {+ const xml = withEmptyGroups(sitemapXml(SPANISH), emptyGroupXml('designer_future', { 3082: 'Futuro' }), emptyGroupXml('designer_past', { 3082: 'Pasado' }));+ const emptied = downloadedBefore('', '');+ const { xml: written, notes } = await rebuild(createSitemapOrg({ xml, baseLanguage: 3082 }), emptied, { languageCode: 3082, baseChrome: chromeByTargetKey(specFor(emptied), CREATED) });+ assert.strictEqual(groupTitles(written, 'designer_future'), null, `neither empty group is kept:\n${written}`);+ assert.strictEqual(groupTitles(written, 'designer_past'), null);+ assert.deepStrictEqual([groupTitles(written, 'group_0_1'), groupTitles(written, 'group_0_2')], [{}, {}], 'the spec\u2019s two groups are written as new, untitled ones');+ assert.deepStrictEqual(heldTitles(written).group, { 3082: 'Casos' });+ const said = noEntries(describeSitemapNotes(notes));+ assert.strictEqual(said.length, 2, JSON.stringify(said));+ assert.match(said[0], /^group "Futuro": has no entries, and the spec's unlabelled empty groups cannot be matched to the environment's empty groups one to one \(2 against 2\), so the spec's are written as new, untitled groups and this one, with its title 'Futuro', is not kept\. Label the spec's group 'Futuro' to keep it\.$/);+ assert.match(said[1], /^group "Pasado": has no entries, .*\(2 against 2\).*, with its title 'Pasado', is not kept\. Label the spec's group 'Pasado' to keep it\.$/);+});++test('REAL BUNDLE: labelling the spec\u2019s group, as the note says, keeps that title by its label and settles the other group by elimination', async () => {+ const xml = withEmptyGroups(sitemapXml(SPANISH), emptyGroupXml('designer_future', { 3082: 'Futuro' }), emptyGroupXml('designer_past', { 3082: 'Pasado' }));+ const labelled = downloadedBefore('Futuro', '');+ const { xml: written, notes } = await rebuild(createSitemapOrg({ xml, baseLanguage: 3082 }), labelled, { languageCode: 3082 });+ assert.deepStrictEqual(groupTitles(written, 'designer_future'), { 3082: 'Futuro' });+ assert.deepStrictEqual(groupTitles(written, 'designer_past'), { 3082: 'Pasado' });+ assert.deepStrictEqual(noEntries(describeSitemapNotes(notes)), []);+});++test('REAL BUNDLE: an empty group of the environment that the spec does not list is dropped, as the spec says, and nothing is said of it', async () => {+ const xml = withEmptyGroups(sitemapXml(SPANISH), emptyGroupXml('designer_future', { 3082: 'Futuro' }));+ const listed = downloadedBefore();+ const { xml: written, notes } = await rebuild(createSitemapOrg({ xml, baseLanguage: 3082 }), listed, { languageCode: 3082, baseChrome: chromeByTargetKey(specFor(listed), CREATED) });+ assert.strictEqual(groupTitles(written, 'designer_future'), null);+ assert.deepStrictEqual(noEntries(describeSitemapNotes(notes)), []);+ assert.ok(!describeSitemapNotes(notes).some((line) => /Futuro/.test(line)), JSON.stringify(describeSitemapNotes(notes)));+});diff --git a/plugins/model-apps/scripts/tests/rebuild-writes-real-bundle.test.js b/plugins/model-apps/scripts/tests/rebuild-writes-real-bundle.test.jsindex 7ddc53b36..3307fc067 100644--- a/plugins/model-apps/scripts/tests/rebuild-writes-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/rebuild-writes-real-bundle.test.js@@ -641,6 +641,35 @@ test('rebuild writes: a spec column a maker removed from a view in Dataverse isassert.deepEqual(s.fake.unpublished(), [], 'and it is published');});+// A view's filter can hold a `<link-entity>`: a condition on RELATED rows ("tickets with a task that has a due date",+// `link-type="any"`). The SDK keeps such a filter — the whole of it, its sibling conditions included — only in its own copy+// of the view's FetchXML, so the typed `filters` of a fetched view are empty. A rebuild changes a view's columns and+// description and nothing else of its query, so the filter a maker made must come through it untouched.+test('rebuild writes: a view whose filter holds a related-rows condition keeps it when a column is added, and an unchanged rebuild writes nothing', async () => {+ const s = scenario();+ await s.build(specFor());+ const view = () => s.fake.rows('savedqueries').find((r) => r.data.name === 'Open Tickets');+ const filter = '<filter type="and"><condition attribute="new_code" operator="eq" value="A" />'+ + '<link-entity name="new_task" from="new_taskid" to="new_taskid" link-type="any"><filter type="and"><condition attribute="new_due" operator="not-null" /></filter></link-entity></filter>';+ // The maker adds the condition in the designer: the query gains the filter, and the row moves on.+ view().data.fetchxml = view().data.fetchxml.replace(/<\/entity>/, `${filter}</entity>`);+ view().version += 1;++ const grown = await s.build(specFor({ viewColumns: ['new_name', 'new_code', 'new_area'] }));+ assert.equal(grown.writes['PATCH savedqueries'], 1, JSON.stringify(grown.writes));+ const [save] = s.fake.saves(grown.mark);+ assert.match(save.body.layoutxml, /<cell name="new_area"/, 'the spec\u2019s new column is written');+ assert.match(save.body.fetchxml, /<attribute name="new_area"/, 'and fetched');+ const spaced = (xml) => xml.replace(/\s*\/>/g, ' />');+ assert.ok(spaced(save.body.fetchxml).includes(spaced(filter)), `the filter, link-entity and all, is written back as it was:\n${save.body.fetchxml}`);+ assert.ok(spaced(view().data.fetchxml).includes(spaced(filter)), 'and is what the view holds now');++ const again = await s.build(specFor({ viewColumns: ['new_name', 'new_code', 'new_area'] }));+ assert.equal(again.writes['PATCH savedqueries'], undefined, JSON.stringify(again.writes));+ assert.ok(spaced(view().data.fetchxml).includes(spaced(filter)));+ assert.deepEqual(s.fake.unpublished(), []);+});+test('rebuild writes: a description the spec sets, changed by a maker in Dataverse, is pushed back', async () => {const s = scenario();const spec = () => specFor({ viewDescription: 'Spec text.' });diff --git a/plugins/model-apps/scripts/tests/run-cleanup.test.js b/plugins/model-apps/scripts/tests/run-cleanup.test.jsindex 31ee278e9..6b3e31924 100644--- a/plugins/model-apps/scripts/tests/run-cleanup.test.js+++ b/plugins/model-apps/scripts/tests/run-cleanup.test.js@@ -5,12 +5,14 @@ const fs = require('node:fs');const os = require('node:os');const path = require('node:path');const { runSdkBuild } = require('../lib/sdk-build.js');+const { isTransientHalt } = require('../build-model-app.js');const { makeSimpleMockSdk } = require('./helpers/mock-sdk.js');const OLDEST = '11111111-1111-4111-8111-111111111111';const PREEXISTING = '22222222-2222-4222-8222-222222222222';const CREATED = '33333333-3333-4333-8333-333333333333';const EXTRA = '44444444-4444-4444-8444-444444444444';+const TEMPLATE = '55555555-5555-4555-8555-555555555555';const RULE = 'Contoso close rule';const MODEL = 'contoso_ticket row summary';@@ -191,7 +193,10 @@ test('the real SDK rolls back only its new model id while plugin cleanup keeps sinstanceUrl: 'https://contoso.crm.dynamics.com',httpClient: {get: async (url) => {- if (url.includes('/aiskillconfigs?') || url.includes('/msdyn_aitemplates?')) return response({ value: [] });+ if (url.includes('/aiskillconfigs?')) return response({ value: [] });+ // The SDK reads the row-summary template before it writes anything and refuses an org that has none+ // (ROW_SUMMARY_TEMPLATE_NOT_FOUND), so the org of this test has it: the model is published, which is what is rolled back.+ if (url.includes('/msdyn_aitemplates?')) return response({ value: [{ msdyn_aitemplateid: TEMPLATE }] });if (url.includes("/EntityDefinitions(LogicalName='contoso_ticket')")) return response({ MetadataId: OLDEST });throw new Error(`unexpected offline GET ${url}`);},@@ -212,3 +217,338 @@ test('the real SDK rolls back only its new model id while plugin cleanup keeps sassert.ok(wireDeletes[0].endsWith(`/msdyn_aimodels(${newId})`));assert.deepEqual(state.deletes, [], 'the plugin must not follow the exact-id rollback with a name-only delete');});++// An org without the AI template a row summary is built from is an environment gate like the licence refusal: the SDK reads the+// template before its first write and refuses with ROW_SUMMARY_TEMPLATE_NOT_FOUND ("Nothing was written"), so the summary is skipped with+// one warning and the build goes on — and, as nothing was written, there is no model to look for or report.+test('an org with no row-summary AI template skips the summary with one warning and looks for no model', async () => {+ const { sdk } = makeSimpleMockSdk();+ const queries = [];+ const deletes = [];+ const warnings = [];+ const events = [];+ sdk.configureRowSummary = async () => {+ throw Object.assign(new Error("Cannot configure the row summary of 'contoso_ticket': this org has no AI template 'GptPowerPrompt' (msdyn_aitemplates), which a row-summary model is built from. Nothing was written."), { code: 'ROW_SUMMARY_TEMPLATE_NOT_FOUND' });+ };+ sdk.queryRecords = async (entity) => { queries.push(entity); return []; };+ sdk.deleteRecord = async (entity, id) => { deletes.push({ entity, id }); };+ const s = spec();+ s.entities.push({ ...s.entities[0], schemaName: 'contoso_request' });+ s.ai.summaries.tables.contoso_request = { enabled: true };++ const r = await runSdkBuild(s, { sdk, apply: true, phases: ['ai-features'], warn: (w) => warnings.push(w), emit: (e) => events.push(e) });++ assert.equal(r.ok, true, 'the build goes on');+ assert.deepEqual(r.skipped.aiSummaries, ['contoso_ticket', 'contoso_request']);+ assert.deepEqual(events.filter((e) => e.status === 'skip' && /^row summary for /.test(e.label)).map((e) => e.label),+ ['row summary for contoso_ticket (no row-summary AI template in this environment)', 'row summary for contoso_request (no row-summary AI template in this environment)']);+ assert.equal(warnings.length, 1, `one warning for two tables, got ${JSON.stringify(warnings)}`);+ assert.match(warnings[0], /AI row summaries were NOT created: this environment has no 'GptPowerPrompt' AI template/);+ assert.match(warnings[0], /nothing was written for them/);+ assert.deepEqual(queries.filter((entity) => entity === 'msdyn_aimodel'), [], 'nothing was written, so no same-name model is looked for');+ assert.deepEqual(deletes, []);+});++test('the real SDK refuses a row summary on an org with no AI template before any write, and the build skips it', async (t) => {+ const { createMakerSdk, createNodeWorkspaceStorage } = require('../vendor/cds-maker-sdk.cjs');+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'contoso-summary-template-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const writes = [];+ const response = (body) => ({ status: 200, headers: {}, body });+ const real = createMakerSdk({+ workspaceStorage: createNodeWorkspaceStorage(dir),+ instanceUrl: 'https://contoso.crm.dynamics.com',+ httpClient: {+ get: async (url) => {+ if (url.includes('/aiskillconfigs?') || url.includes('/msdyn_aitemplates?')) return response({ value: [] });+ if (url.includes("/EntityDefinitions(LogicalName='contoso_ticket')")) return response({ MetadataId: OLDEST });+ throw new Error(`unexpected offline GET ${url}`);+ },+ post: async (url) => { writes.push(`POST ${url}`); return response({}); },+ patch: async (url) => { writes.push(`PATCH ${url}`); return response({}); },+ put: async (url) => { writes.push(`PUT ${url}`); return response({}); },+ delete: async (url) => { writes.push(`DELETE ${url}`); return { status: 204, headers: {}, body: {} }; },+ },+ });+ await real.initWorkspace();+ const { sdk, state } = summarySdk('ModelNotSupported');+ sdk.configureRowSummary = real.configureRowSummary.bind(real);++ const r = await runSdkBuild(spec(), { sdk, apply: true, phases: ['ai-features'], warn: (w) => state.warnings.push(w) });++ assert.equal(r.ok, true);+ assert.deepEqual(r.skipped.aiSummaries, ['contoso_ticket']);+ assert.deepEqual(writes, [], 'the SDK read the template first and wrote nothing');+ assert.deepEqual(state.queries, [], 'no model inventory read: nothing was written for it to report');+ assert.ok(state.warnings.some((w) => /no 'GptPowerPrompt' AI template/.test(w)));+});++// An org whose template list comes back without a template. The SDK takes the FIRST row of the list and reads its `msdyn_aitemplateid` without checking+// that there is a row, so it raises ROW_SUMMARY_TEMPLATE_NOT_FOUND for an empty list and for a list whose first row is no row alike:+// { "value": [] } { "value": [ {} ] } { "value": [ null ] }+// Only the empty list says the org has no template. The others are answers that cannot be read, and an answer that cannot be read stops the build, as it did+// before the skip above — so the build asks the template list itself, once, before it skips, and skips only on an empty list.+const TEMPLATE_LIST = "/msdyn_aitemplates?$select=msdyn_aitemplateid&$filter=msdyn_uniquename eq 'GptPowerPrompt'&$top=1";+const listOf = (value) => ({ status: 200, headers: {}, body: { value } });++// The real SDK over a transport that answers the template list from `answers` and the template table's set from `entitySet` (one answer per request for each, the last one+// repeating) and records every request, writes included. An answer that is an Error is what the transport throws: the request got no answer at all, as when a connection is reset.+// The mock SDK the build drives gets the real `configureRowSummary` (the errors it throws are kept, `sdkErrors`) and `queryRecords`.+async function orgWithTemplateAnswers(t, answers, entitySet = [{ status: 200, headers: {}, body: { EntitySetName: 'msdyn_aitemplates' } }]) {+ const { createMakerSdk, createNodeWorkspaceStorage } = require('../vendor/cds-maker-sdk.cjs');+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'contoso-summary-confirm-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const requests = [];+ const sdkErrors = [];+ let templateReads = 0;+ let entitySetReads = 0;+ const scripted = (list, n) => {+ const answer = list[Math.min(n, list.length - 1)];+ if (answer instanceof Error) throw answer;+ return answer;+ };+ const seen = (method, url) => requests.push(`${method} ${decodeURIComponent(url.replace(/^https:\/\/contoso\.crm\.dynamics\.com\/api\/data\/v9\.\d+/, ''))}`);+ const write = (method) => async (url) => { seen(method, url); return { status: 200, headers: {}, body: {} }; };+ const real = createMakerSdk({+ workspaceStorage: createNodeWorkspaceStorage(dir),+ instanceUrl: 'https://contoso.crm.dynamics.com',+ httpClient: {+ get: async (url) => {+ seen('GET', url);+ if (url.includes('/aiskillconfigs?')) return listOf([]);+ if (url.includes('/msdyn_aitemplates?')) return scripted(answers, templateReads++);+ if (url.includes("/EntityDefinitions(LogicalName='msdyn_aitemplate')")) return scripted(entitySet, entitySetReads++);+ if (/\/EntityDefinitions\(LogicalName='contoso_\w+'\)/.test(url)) return { status: 200, headers: {}, body: { MetadataId: OLDEST } };+ throw new Error(`unexpected offline GET ${url}`);+ },+ post: write('POST'), patch: write('PATCH'), put: write('PUT'), delete: write('DELETE'),+ },+ });+ await real.initWorkspace();+ const { sdk } = makeSimpleMockSdk();+ sdk.configureRowSummary = async (...args) => {+ try { return await real.configureRowSummary(...args); } catch (err) { sdkErrors.push(err); throw err; }+ };+ sdk.queryRecords = real.queryRecords.bind(real);+ return {+ sdk,+ sdkErrors,+ requests,+ templateReads: () => requests.filter((request) => request.startsWith('GET /msdyn_aitemplates?')),+ writes: () => requests.filter((request) => !request.startsWith('GET ')),+ };+}++const bothTables = () => {+ const s = spec();+ s.entities.push({ ...s.entities[0], schemaName: 'contoso_request' });+ s.ai.summaries.tables.contoso_request = { enabled: true };+ return s;+};++// The build stops with the SDK's own error, whole: the halt's code and words are the SDK's, and the SDK's error is its cause.+const stoppedBySdkError = (err) => {+ assert.equal(err.name, 'BuildHalt');+ assert.equal(err.code, 'ROW_SUMMARY_TEMPLATE_NOT_FOUND');+ assert.equal(err.cause.code, 'ROW_SUMMARY_TEMPLATE_NOT_FOUND', "the SDK's own error is what stopped the build");+ assert.match(err.message, /^ai-features failed: Cannot configure the row summary of 'contoso_ticket'/);+ return true;+};++// ...and for good, when the confirming read ANSWERED, however wrongly: nothing says that a run again could help (the halt's policy is `never`, and so is the check the build's own retry makes), and there is no+// failure of the read to keep or to explain, so the halt carries the SDK's words alone.+const stoppedForGood = (err) => {+ stoppedBySdkError(err);+ assert.equal(err.retry, 'never');+ assert.equal(isTransientHalt(err), false);+ assert.equal(err.cause.cause, undefined);+ assert.equal(err.message, `ai-features failed: ${err.cause.message}`);+ return true;+};++test('an org whose template list is empty skips every summary with one warning and writes nothing, and the build confirms it with one read of the list, however many tables ask', async (t) => {+ const org = await orgWithTemplateAnswers(t, [listOf([])]);+ const warnings = [];+ const events = [];+ const r = await runSdkBuild(bothTables(), { sdk: org.sdk, apply: true, phases: ['ai-features'], warn: (w) => warnings.push(w), emit: (e) => events.push(e) });+ assert.equal(r.ok, true);+ assert.deepEqual(r.skipped.aiSummaries, ['contoso_ticket', 'contoso_request']);+ assert.deepEqual(events.filter((e) => e.status === 'skip' && /^row summary for /.test(e.label)).map((e) => e.label),+ ['row summary for contoso_ticket (no row-summary AI template in this environment)', 'row summary for contoso_request (no row-summary AI template in this environment)']);+ assert.equal(warnings.length, 1, `one warning for two tables, got ${JSON.stringify(warnings)}`);+ assert.match(warnings[0], /no 'GptPowerPrompt' AI template/);+ assert.deepEqual(org.writes(), []);+ // The SDK reads the list for each table (two reads) and the build asks it once more, for the first table only; every one of the three is the same request,+ // so the build asks exactly what the SDK asked. The one other read names the template table's set, which the SDK looks up once and keeps.+ assert.deepEqual(org.templateReads(), Array(3).fill(`GET ${TEMPLATE_LIST}`));+ assert.deepEqual(org.requests.filter((request) => request.includes("LogicalName='msdyn_aitemplate'")), ["GET /EntityDefinitions(LogicalName='msdyn_aitemplate')?$select=EntitySetName"]);+});++for (const [what, list] of [['a first row with no id', [{}]], ['a first row that is not a row', [null]]]) {+ test(`${what} in the template list is not an org without the template: the build stops with the SDK's error and skips nothing`, async (t) => {+ const org = await orgWithTemplateAnswers(t, [listOf(list)]);+ const warnings = [];+ const events = [];+ await assert.rejects(runSdkBuild(spec(), { sdk: org.sdk, apply: true, phases: ['ai-features'], warn: (w) => warnings.push(w), emit: (e) => events.push(e) }), stoppedForGood);+ assert.deepEqual(warnings, [], 'nothing was skipped, so nothing says it was');+ assert.deepEqual(events.filter((e) => e.status === 'skip'), []);+ assert.deepEqual(org.writes(), []);+ assert.equal(org.templateReads().length, 2, 'the SDK read the list, and the build asked it once more');+ });+}++test("a template that the build finds when it asks again, after the SDK read none, is not an org without one: the build stops with the SDK's error", async (t) => {+ const org = await orgWithTemplateAnswers(t, [listOf([]), listOf([{ msdyn_aitemplateid: TEMPLATE }])]);+ const warnings = [];+ await assert.rejects(runSdkBuild(spec(), { sdk: org.sdk, apply: true, phases: ['ai-features'], warn: (w) => warnings.push(w) }), stoppedForGood);+ assert.deepEqual(warnings, []);+ assert.deepEqual(org.writes(), []);+});++// What a FAILURE of the confirming read does to the halt. The build runs this attempt again, by itself, for a failure the SERVICE calls transient — a throttle (429), a service that is down or overloaded+// (503), a connection that was reset — and reads that from the errors along the halt's causes (lib/retry-policy.js, judgeFailure). So the read's failure has to be on that chain, under the SDK's error, which+// stays the halt's own cause: a halt that kept only the SDK's refusal was final whatever the read had failed with. Either request of the confirming read can fail: the one that names the template table's set+// (the SDK looks it up once) and the one that reads the list. Each is scripted to fail once and then to answer, so that a second attempt can finish.+const refusedWith = (status, message) => ({ status, headers: {}, body: { error: { message } } });+const connectionReset = () => Object.assign(new Error('Request failed: read ECONNRESET'), { code: 'ECONNRESET' });+const confirmingRequests = [+ ["the read that names the template table's set", (failure) => ({ answers: [listOf([])], entitySet: [failure, { status: 200, headers: {}, body: { EntitySetName: 'msdyn_aitemplates' } }] }), /could not resolve EntitySetName/],+ ['the read of the template list', (failure) => ({ answers: [listOf([]), failure, listOf([])] }), /malformed page/],+];+// The halt of a failed confirmation: the SDK's error itself is its cause, the read's failure is kept under that error, and the halt's text says that the read failed, and why.+const stoppedByFailedConfirmation = (org) => (err) => {+ stoppedBySdkError(err);+ assert.equal(err.cause, org.sdkErrors[0], "the halt's own cause is the SDK's error itself, not a copy of it");+ assert.ok(err.cause.cause, "the read's failure is kept under the SDK's error");+ assert.match(err.message, /, to confirm that before skipping the row summaries, and that read failed \(/);+ assert.ok(err.message.includes(err.cause.cause.message), `the halt says why the read failed: ${err.message}`);+ return true;+};++for (const [where, scriptFor, malformedWords] of confirmingRequests) {+ for (const [what, make, status] of [['a throttle', () => refusedWith(429, 'Contoso throttled'), 429], ['an unavailable service', () => refusedWith(503, 'Contoso unavailable'), 503], ['a reset connection', connectionReset, 0]]) {+ test(`${what} on ${where} that confirms the absence is a transient halt, which a second attempt can finish`, async (t) => {+ const { answers, entitySet } = scriptFor(make());+ const org = await orgWithTemplateAnswers(t, answers, entitySet);+ const options = (warnings) => ({ sdk: org.sdk, apply: true, phases: ['ai-features'], warn: (w) => warnings.push(w) });+ const warnings = [];+ await assert.rejects(runSdkBuild(spec(), options(warnings)), (err) => {+ assert.equal(isTransientHalt(err, { spec: spec() }), true, 'the build runs this attempt again');+ assert.equal(err.retry, 'service');+ assert.equal(err.cause.cause.code, 'CONNECTION_ERROR');+ assert.equal(err.cause.cause.statusCode, status);+ return stoppedByFailedConfirmation(org)(err);+ });+ assert.deepEqual(warnings, [], 'nothing was skipped, so nothing says it was');+ assert.deepEqual(org.writes(), []);+ // The attempt after it asks again, and this time the org answers: the list is empty, so the summary is skipped, as it is for any org without the template.+ const again = [];+ const r = await runSdkBuild(spec(), options(again));+ assert.equal(r.ok, true);+ assert.deepEqual(r.skipped.aiSummaries, ['contoso_ticket']);+ assert.equal(again.length, 1);+ assert.match(again[0], /no 'GptPowerPrompt' AI template/);+ });+ }++ // A refusal, and an answer with nothing in it (a 200 whose body has no list, no table set): neither is the service saying that a run again can help.+ for (const [what, answer, words] of [['a refusal (403)', refusedWith(403, 'Contoso permission denied'), /Contoso permission denied/], ['an answer with nothing in it (a 200 without its content)', { status: 200, headers: {}, body: {} }, malformedWords]]) {+ test(`${what} on ${where} that confirms the absence is final, and the halt says the read failed and why`, async (t) => {+ const { answers, entitySet } = scriptFor(answer);+ const org = await orgWithTemplateAnswers(t, answers, entitySet);+ const warnings = [];+ await assert.rejects(runSdkBuild(spec(), { sdk: org.sdk, apply: true, phases: ['ai-features'], warn: (w) => warnings.push(w) }), (err) => {+ assert.equal(err.retry, 'never');+ assert.equal(isTransientHalt(err, { spec: spec() }), false);+ stoppedByFailedConfirmation(org)(err);+ assert.match(err.message, words);+ return true;+ });+ assert.deepEqual(warnings, []);+ assert.deepEqual(org.writes(), []);+ });+ }+}++test('the build confirms the absence of the template with the question the SDK asks, and asks it once for the whole build', async () => {+ const { sdk } = makeSimpleMockSdk();+ const reads = [];+ sdk.configureRowSummary = async () => { throw Object.assign(new Error("Cannot configure the row summary of 'contoso_ticket': this org has no AI template"), { code: 'ROW_SUMMARY_TEMPLATE_NOT_FOUND' }); };+ sdk.queryRecords = async (entity, query) => { reads.push([entity, query]); return []; };+ const r = await runSdkBuild(bothTables(), { sdk, apply: true, phases: ['ai-features'], warn: () => {} });+ assert.deepEqual(r.skipped.aiSummaries, ['contoso_ticket', 'contoso_request']);+ assert.deepEqual(reads, [['msdyn_aitemplate', { select: ['msdyn_aitemplateid'], filter: "msdyn_uniquename eq 'GptPowerPrompt'", top: 1 }]]);+});++test("every answer to the confirming read but an empty list leaves the SDK's own error to stop the build, and a missing template is never a transient halt", async () => {+ // [what the read does, what it answers (or throws), the reason a failed read gives]+ const answers = [+ ['a first row with no id', () => [{}], null],+ ['a first row that is not a row', () => [null], null],+ ['a template', () => [{ msdyn_aitemplateid: TEMPLATE }], null],+ ['no list', () => undefined, null],+ ['a list that is not one', () => 'bad', null],+ ['a read that fails', () => { throw new Error('Contoso template read failed'); }, 'Contoso template read failed'],+ // Only what the SERVICE answered (a status, a reset) can make a halt transient: the words of a failure that has none are not read, so this is no more transient than the read above.+ ['a read that fails in words that say to try again', () => { throw new Error('Please try again later.'); }, 'Please try again later.'],+ ];+ for (const [what, answer, failed] of answers) {+ const { sdk } = makeSimpleMockSdk();+ const refusal = Object.assign(new Error("Cannot configure the row summary of 'contoso_ticket': this org has no AI template 'GptPowerPrompt' (msdyn_aitemplates), which a row-summary model is built from. Nothing was written."), { code: 'ROW_SUMMARY_TEMPLATE_NOT_FOUND' });+ sdk.configureRowSummary = async () => { throw refusal; };+ sdk.queryRecords = async () => answer();+ const warnings = [];+ await assert.rejects(runSdkBuild(spec(), { sdk, apply: true, phases: ['ai-features'], warn: (w) => warnings.push(w) }), (err) => {+ assert.equal(err.name, 'BuildHalt', what);+ assert.equal(err.code, 'ROW_SUMMARY_TEMPLATE_NOT_FOUND', what);+ assert.equal(err.cause, refusal, `${what}: the SDK's error itself is the cause`);+ assert.equal(err.retry, 'never', what);+ assert.equal(isTransientHalt(err), false, what);+ // A read that threw is kept under the SDK's error and named in the halt's text; one that answered, however wrongly, has failed at nothing, and the halt is the SDK's words alone.+ assert.equal(refusal.cause && refusal.cause.message, failed || undefined, what);+ assert.equal(err.message, `ai-features failed: ${refusal.message}${failed ? ` — the build then read the template list itself, to confirm that before skipping the row summaries, and that read failed (${failed}), so they were not skipped.` : ''}`, what);+ return true;+ });+ assert.deepEqual(warnings, [], what);+ }+});++test('an SDK error that cannot carry the failure of the confirming read still stops the build with the SDK\'s own words, and says nothing about a read it cannot attach', async () => {+ const { sdk } = makeSimpleMockSdk();+ const refusal = Object.freeze(Object.assign(new Error("Cannot configure the row summary of 'contoso_ticket': this org has no AI template 'GptPowerPrompt' (msdyn_aitemplates), which a row-summary model is built from. Nothing was written."), { code: 'ROW_SUMMARY_TEMPLATE_NOT_FOUND' }));+ sdk.configureRowSummary = async () => { throw refusal; };+ sdk.queryRecords = async () => { throw Object.assign(new Error('HTTP 503 from https://contoso.crm.dynamics.com/api/data/v9.0/msdyn_aitemplates: Contoso unavailable'), { code: 'CONNECTION_ERROR', statusCode: 503 }); };+ await assert.rejects(runSdkBuild(spec(), { sdk, apply: true, phases: ['ai-features'], warn: () => {} }), (err) => {+ assert.equal(err.name, 'BuildHalt');+ assert.equal(err.cause, refusal, "the SDK's error itself is the cause");+ assert.equal(refusal.cause, undefined, 'nothing could be attached to it');+ assert.equal(err.retry, 'never', 'as before: the failure of the read is not on the chain');+ assert.equal(err.message, `ai-features failed: ${refusal.message}`);+ return true;+ });+});++test('only the exact template code starts the confirming read: a refusal of another kind is skipped or stops the build as it always did, with no read of the template list', async () => {+ for (const code of ['DuplicateRecordKey', 'ModelNotSupported']) {+ const { sdk, state } = summarySdk(code);+ const entities = [];+ const inventory = sdk.queryRecords;+ sdk.queryRecords = async (entity, query) => { entities.push(entity); return inventory(entity, query); };+ const r = await runSdkBuild(spec(), { sdk, apply: true, phases: ['ai-features'], warn: (w) => state.warnings.push(w) });+ assert.equal(r.ok, true, code);+ assert.deepEqual(entities, ['msdyn_aimodel'], `${code}: only the model inventory that the skip reports`);+ }+ const lookalikes = [+ ['a longer code', () => Object.assign(new Error('not available'), { code: 'ROW_SUMMARY_TEMPLATE_NOT_FOUND_EXTRA' })],+ ['a mention in the message', () => Object.assign(new Error('ROW_SUMMARY_TEMPLATE_NOT_FOUND'), { code: 'CONNECTION_ERROR' })],+ ['a code in the cause', () => Object.assign(new Error('permission denied'), { code: 'CONNECTION_ERROR', cause: { code: 'ROW_SUMMARY_TEMPLATE_NOT_FOUND' } })],+ ];+ for (const [what, make] of lookalikes) {+ const { sdk } = makeSimpleMockSdk();+ const entities = [];+ sdk.configureRowSummary = async () => { throw make(); };+ sdk.queryRecords = async (entity) => { entities.push(entity); return []; };+ await assert.rejects(runSdkBuild(spec(), { sdk, apply: true, phases: ['ai-features'], warn: () => {} }), (err) => err.name === 'BuildHalt', what);+ assert.deepEqual(entities, [], `${what}: no read of the template list`);+ }+});diff --git a/plugins/model-apps/scripts/tests/run-tests.test.js b/plugins/model-apps/scripts/tests/run-tests.test.jsindex 5e44970da..c84f67aff 100644--- a/plugins/model-apps/scripts/tests/run-tests.test.js+++ b/plugins/model-apps/scripts/tests/run-tests.test.js@@ -4,8 +4,8 @@ const assert = require('node:assert');const fs = require('node:fs');const os = require('node:os');const path = require('node:path');-const { execFileSync } = require('node:child_process');-const { pluginTestFiles, sdkTestSpec, summarize, runPluginSuite, withTempDir } = require('../run-tests.js');+const { execFileSync, spawn } = require('node:child_process');+const { pluginTestFiles, sdkTestSpec, summarize, runPluginSuite, reportStrayFolders, withTempDir } = require('../run-tests.js');const { makeTempDir } = require('./helpers/temp-dirs.js');test('pluginTestFiles discovers every *.test.js as a scripts/tests path, sorted', () => {@@ -92,7 +92,7 @@ test('runPluginSuite runs the suite in a temporary folder of its own, names what'',].join('\n'));- assert.deepStrictEqual(runPluginSuite(['clean.test.js'], { cwd: work, stdio: 'pipe', tempParent: parent }), { status: 0, left: [] });+ assert.deepStrictEqual(runPluginSuite(['clean.test.js'], { cwd: work, stdio: 'pipe', tempParent: parent }), { status: 0, left: [], made: [], kept: [] });const leaky = runPluginSuite(['leaky.test.js'], { cwd: work, stdio: 'pipe', tempParent: parent });assert.strictEqual(leaky.status, 0, 'the leaking test itself passes: only the check catches it');assert.strictEqual(leaky.left.length, 1, leaky.left.join(', '));@@ -100,6 +100,132 @@ test('runPluginSuite runs the suite in a temporary folder of its own, names whatassert.deepStrictEqual(fs.readdirSync(parent), [], "the suite's temporary folder is removed either way");});+// A build's workspace is `<app folder>/.maker-workspace` unless it is given another, so a test that handed a build `process.cwd()` as its app folder — the suite runs in the plugin's own folder — made+// `plugins/model-apps/.maker-workspace` and left it behind, empty. The run names such a folder and fails, and it removes the folder when it is empty: a leftover is not a leak the next run can see, since it+// would find the folder already there and take it for one that was always there.+test('runPluginSuite names a .maker-workspace the suite made in its working folder and removes it when it is empty — and leaves alone one that was there before the run', () => {+ const root = makeTempDir('runtests-cwd-');+ const work = path.join(root, 'work');+ const parent = path.join(root, 'temp');+ fs.mkdirSync(work);+ fs.mkdirSync(parent);+ fs.writeFileSync(path.join(work, 'clean.test.js'), "const test = require('node:test');\ntest('makes nothing', () => {});\n");+ fs.writeFileSync(path.join(work, 'stray.test.js'), [+ "const test = require('node:test');",+ "const fs = require('node:fs');",+ "const path = require('node:path');",+ "test('makes the workspace a build opens when it is given no other', () => { fs.mkdirSync(path.join(process.cwd(), '.maker-workspace')); });",+ '',+ ].join('\n'));+ const run = (file) => runPluginSuite([file], { cwd: work, stdio: 'pipe', tempParent: parent });++ const stray = run('stray.test.js');+ assert.strictEqual(stray.status, 0, 'the test itself passes: only the check catches it');+ assert.deepStrictEqual(stray.made, [path.join(work, '.maker-workspace')], 'the folder is named, by its path');+ assert.deepStrictEqual(stray.left, [], 'it is not in the temporary folder');+ assert.deepStrictEqual(stray.kept, [], 'nothing is left in place: it held nothing');+ assert.ok(!fs.existsSync(path.join(work, '.maker-workspace')), 'and it is removed, being empty, so that the next run is not blind to the leak');++ // One that was there before the run is nobody's to answer for, and stays as it is, with what is in it.+ fs.mkdirSync(path.join(work, '.maker-workspace'));+ fs.writeFileSync(path.join(work, '.maker-workspace', 'last-applied.json'), '{}');+ assert.deepStrictEqual(run('clean.test.js'), { status: 0, left: [], made: [], kept: [] });+ assert.deepStrictEqual(fs.readdirSync(path.join(work, '.maker-workspace')), ['last-applied.json']);+});++// The folder the suite runs in is shared: a build started by hand beside the suite opens its own `.maker-workspace` there, and the run cannot tell that folder from one a test made — all it knows is that the+// folder was not there before the run. So it never takes what it cannot show to be its own: a folder with anything in it is named, and left where it is with everything in it, whoever made it. (It used to remove+// such a folder with all that was in it, which took the baseline and the lock of a build that was still running.)+test('runPluginSuite names a .maker-workspace that holds something and leaves it where it is, with everything in it — a build running beside the suite keeps its workspace', async () => {+ const root = makeTempDir('runtests-beside-');+ const work = path.join(root, 'work');+ const parent = path.join(root, 'temp');+ fs.mkdirSync(work);+ fs.mkdirSync(parent);+ const waiting = [+ "const fs = require('node:fs');",+ "const waitFor = (file) => { const until = Date.now() + 60000; while (!fs.existsSync(file)) { if (Date.now() > until) process.exit(2); Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10); } };",+ ];+ // The suite's one test makes no workspace: it only waits until the build beside it has made its own, so that the folder appears while the suite runs.+ fs.writeFileSync(path.join(work, 'beside.test.js'), [+ "const test = require('node:test');",+ ...waiting,+ "test('makes no workspace, and lets the build beside it make its own', () => { fs.writeFileSync('suite-started', ''); waitFor('build-wrote'); });",+ '',+ ].join('\n'));+ const build = spawn(process.execPath, ['-e', [+ ...waiting,+ "waitFor('suite-started');",+ "fs.mkdirSync('.maker-workspace/apps', { recursive: true });",+ "fs.writeFileSync('.maker-workspace/last-applied.json', '{\"generation\":123}');",+ "fs.writeFileSync('.maker-workspace/apps/app.json', '{}');",+ "fs.writeFileSync('build-wrote', '');",+ "waitFor('suite-ended');",+ ].join('\n')], { cwd: work, stdio: 'ignore', windowsHide: true });+ const ended = new Promise((resolve) => build.once('exit', resolve));+ try {+ const run = runPluginSuite(['beside.test.js'], { cwd: work, stdio: 'pipe', tempParent: parent });+ const workspace = path.join(work, '.maker-workspace');+ assert.strictEqual(run.status, 0, 'the test itself passes: only the check catches it');+ assert.deepStrictEqual(run.made, [workspace], 'the folder was not there before the run, so it is named, and the run fails on it');+ assert.strictEqual(build.exitCode, null, 'the build beside the suite is still running');+ assert.strictEqual(fs.readFileSync(path.join(workspace, 'last-applied.json'), 'utf8'), '{"generation":123}', 'its baseline is as it wrote it');+ assert.ok(fs.existsSync(path.join(workspace, 'apps', 'app.json')), 'and what is nested in its folder is there');+ assert.deepStrictEqual(run.kept, [workspace], "the run says it left the folder in place: it is not the run's to remove");+ } finally {+ fs.writeFileSync(path.join(work, 'suite-ended'), '');+ await ended;+ }+});++// A removal that follows a link reaches what the link points at, and a link is no folder that a run could have found empty, so a `.maker-workspace` that is a link — or anything else that is not a plain folder — is+// named, and neither followed nor removed. (A junction on Windows, which needs no privilege to make; a symbolic link elsewhere.)+test('runPluginSuite names a .maker-workspace that is a link or a file and removes neither — what a link points at is never reached', () => {+ const root = makeTempDir('runtests-link-');+ const parent = path.join(root, 'temp');+ const elsewhere = path.join(root, 'elsewhere');+ fs.mkdirSync(parent);+ fs.mkdirSync(elsewhere);+ fs.writeFileSync(path.join(elsewhere, 'last-applied.json'), '{}');+ const kinds = {+ link: `fs.symlinkSync(${JSON.stringify(elsewhere)}, path.join(process.cwd(), '.maker-workspace'), 'junction');`,+ file: "fs.writeFileSync(path.join(process.cwd(), '.maker-workspace'), 'not a folder');",+ };+ for (const [kind, make] of Object.entries(kinds)) {+ const work = path.join(root, `work-${kind}`);+ fs.mkdirSync(work);+ fs.writeFileSync(path.join(work, `${kind}.test.js`), [+ "const test = require('node:test');",+ "const fs = require('node:fs');",+ "const path = require('node:path');",+ `test('makes a ${kind} where the workspace would be', () => { ${make} });`,+ '',+ ].join('\n'));+ const run = runPluginSuite([`${kind}.test.js`], { cwd: work, stdio: 'pipe', tempParent: parent });+ const workspace = path.join(work, '.maker-workspace');+ assert.strictEqual(run.status, 0, `${kind}: the test itself passes`);+ assert.deepStrictEqual(run.made, [workspace], `${kind}: it is named`);+ assert.deepStrictEqual(run.kept, [workspace], `${kind}: and left in place`);+ }+ assert.ok(fs.lstatSync(path.join(root, 'work-link', '.maker-workspace')).isSymbolicLink(), 'the link is still a link');+ assert.strictEqual(fs.readFileSync(path.join(elsewhere, 'last-applied.json'), 'utf8'), '{}', 'and what it points at was not reached');+ assert.strictEqual(fs.readFileSync(path.join(root, 'work-file', '.maker-workspace'), 'utf8'), 'not a folder', 'the file is as it was');+});++test('the report of what the run made in the plugin folder says which folder it removed and which it left in place, and what to do about the latter', () => {+ assert.strictEqual(reportStrayFolders({ made: [], kept: [] }), '', 'nothing made, nothing said');+ const removed = reportStrayFolders({ made: ['/p/.maker-workspace'], kept: [] });+ assert.match(removed, /^\n1 folder\(s\) made in the plugin's own folder while the suite ran:\n {2}\/p\/\.maker-workspace {2}\(empty: removed again\)\n/);+ assert.doesNotMatch(removed, /by hand/, 'there is nothing to delete when the run took the folder away');+ assert.match(removed, /never process\.cwd\(\)/, 'and the way to avoid it is said either way');+ const left = reportStrayFolders({ made: ['/a/.maker-workspace', '/b/.maker-workspace'], kept: ['/b/.maker-workspace'] });+ assert.match(left, /\n {2}\/a\/\.maker-workspace {2}\(empty: removed again\)\n/);+ assert.match(left, /\n {2}\/b\/\.maker-workspace {2}\(left in place\)\n/);+ assert.match(left, /another process may have made it/);+ assert.match(left, /Delete it by hand/);+ assert.match(left, /never process\.cwd\(\)/);+});+test('withTempDir points TEMP, TMP and TMPDIR at the folder whatever their spelling, and keeps the rest', () => {const env = withTempDir({ Temp: 'C:\\old', tmp: 'C:\\old', TMPDIR: '/old', PATH: 'p', Other: 'x' }, 'D:\\suite');assert.deepStrictEqual(env, { PATH: 'p', Other: 'x', TEMP: 'D:\\suite', TMP: 'D:\\suite', TMPDIR: 'D:\\suite' });@@ -116,10 +242,11 @@ test('summarize fails the run when the suite left something in its temporary fol// main() is the gate CI runs, and it is not run here (it runs this whole suite), so its wiring is read from the source:// the suite goes through runPluginSuite and what it left decides a result of its own.-test('the regression gate runs the plugin suite through runPluginSuite and fails on what it left behind', () => {+test('the regression gate runs the plugin suite through runPluginSuite and fails on what it left behind, in its temporary folder and in the plugin\'s own', () => {const source = fs.readFileSync(path.join(__dirname, '..', 'run-tests.js'), 'utf8');assert.match(source, /const plugin = runPluginSuite\(files, \{ cwd: pluginRoot \}\);/);assert.match(source, /results\.push\(\{ name: 'nothing left in the temporary folder', ok: plugin\.left\.length === 0 \}\);/);+ assert.match(source, /results\.push\(\{ name: 'nothing made in the plugin folder', ok: plugin\.made\.length === 0 \}\);/);});// --- CI workflow scoping ---------------------------------------------------------------------diff --git a/plugins/model-apps/scripts/tests/sdk-build-pages-migrate.test.js b/plugins/model-apps/scripts/tests/sdk-build-pages-migrate.test.jsindex 57ab20c84..d99f4e0d0 100644--- a/plugins/model-apps/scripts/tests/sdk-build-pages-migrate.test.js+++ b/plugins/model-apps/scripts/tests/sdk-build-pages-migrate.test.js@@ -163,16 +163,20 @@ test('intent page (no codeFile) is skipped — nothing written, no throw', asyncconst genpage = fakeGenpage();const events = [];- await assert.doesNotReject(- runSdkBuild(v2, {- sdk, apply: true, env: 'https://x.dynamics.com', appDir: process.cwd(),- genpage, phases: ['solution', 'data-model', 'app-shell', 'pages'],- emit: (e) => events.push(e),- }),- 'intent page should not throw'- );-- assert.deepStrictEqual([genpage.of('create').length, genpage.of('update').length], [0, 0], 'no page written for an intent page');- // The skip event should be emitted so the plan log reflects it.- assert.ok(events.some((e) => e.status === 'skip' && /Overview/.test(e.label)), 'skip event emitted for the intent page');+ // The build opens its workspace in `<appDir>/.maker-workspace` when it is given none, so the app folder is one of the test's own, removed after it — never `process.cwd()`, which is the plugin's folder.+ const appDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mig-pages-'));+ try {+ await assert.doesNotReject(+ runSdkBuild(v2, {+ sdk, apply: true, env: 'https://x.dynamics.com', appDir,+ genpage, phases: ['solution', 'data-model', 'app-shell', 'pages'],+ emit: (e) => events.push(e),+ }),+ 'intent page should not throw'+ );++ assert.deepStrictEqual([genpage.of('create').length, genpage.of('update').length], [0, 0], 'no page written for an intent page');+ // The skip event should be emitted so the plan log reflects it.+ assert.ok(events.some((e) => e.status === 'skip' && /Overview/.test(e.label)), 'skip event emitted for the intent page');+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }});diff --git a/plugins/model-apps/scripts/tests/sdk-build.test.js b/plugins/model-apps/scripts/tests/sdk-build.test.jsindex dae7cb3f2..ca6c66217 100644--- a/plugins/model-apps/scripts/tests/sdk-build.test.js+++ b/plugins/model-apps/scripts/tests/sdk-build.test.js@@ -6,6 +6,7 @@ const os = require('node:os');const path = require('node:path');const { commandDef, chartDef, runSdkBuild: runSdkBuildWithRealWaits, 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');+const { makeTempDir } = require('./helpers/temp-dirs.js');// The AI phase's proof after a publish waits 500 ms between reads of an override row that is not there yet, as --verify// does. No test below is about that wait (it is pinned through `proofBudget`), and every one that leaves a row absent// would otherwise sleep a second for it.@@ -23,7 +24,12 @@ function pageBackend(double) {update: (id, o) => written(double.upload({ ...o, pageId: id }), o),};}-const runSdkBuild = (spec, opts = {}) => runSdkBuildWithRealWaits(spec, { proofDelayMs: 0, ...opts, ...(opts.genpageCli ? { genpage: pageBackend(opts.genpageCli) } : {}) });+// A build that runs the pages phase opens its workspace in `<appDir>/.maker-workspace` — unless it is given a `workspaceDir` — and an `appDir` it is not given is the folder the tests run in, which is the+// plugin's own: every such build took its pages lock there and left `plugins/model-apps/.maker-workspace` behind, empty (scripts/run-tests.js fails a run that makes it). A call that names neither is given an+// app folder of this file's own, one for all of those calls — as the plugin's folder was — removed after the file's last test. It is only a place for the lock: none of these tests reads a file from it.+let defaultAppDir;+const appFolderOf = (opts) => (opts.appDir === undefined && opts.workspaceDir === undefined ? { appDir: defaultAppDir || (defaultAppDir = makeTempDir('sdkb-app-')) } : {});+const runSdkBuild = (spec, opts = {}) => runSdkBuildWithRealWaits(spec, { proofDelayMs: 0, ...opts, ...appFolderOf(opts), ...(opts.genpageCli ? { genpage: pageBackend(opts.genpageCli) } : {}) });// Real GUIDs for the three-authority sitemap mock. SELF_* identify THIS app's appmodule + sitemap// so fetchSitemap(appUnique) resolves to opts.liveSitemapXml; otherApps get synthetic ids. Ids that flow@@ -6738,8 +6744,12 @@ test('an EXISTING page-backed app writes its sitemap ONCE, in the finalizer, wittest('an EXISTING app with NO page subareas still pushes its sitemap in app-shell (unchanged behavior)', async () => {const spec = makeSpec(); // entity subarea only, no pagesconst { sdk, calls } = mockSdk({ artifactsExist: true, existingSitemap: PRIOR_SITEMAP });- await runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir: process.cwd(), phases: ['solution', 'data-model', 'app-shell'] });- assert.ok(find(calls, 'updateElement').some((c) => c.args[2] === '/siteMap'), 'a no-page existing app keeps pushing its sitemap in app-shell');+ // The build opens its workspace in `<appDir>/.maker-workspace` when it is given none, so the app folder is one of the test's own, removed after it: never `process.cwd()`, which is the plugin's own folder.+ const appDir = stagePages([]);+ try {+ await runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, phases: ['solution', 'data-model', 'app-shell'] });+ assert.ok(find(calls, 'updateElement').some((c) => c.args[2] === '/siteMap'), 'a no-page existing app keeps pushing its sitemap in app-shell');+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }});// ── Three-authority safety gates: existence-driven crash-safety, discriminated reads,diff --git a/plugins/model-apps/scripts/tests/sdk-teardown.test.js b/plugins/model-apps/scripts/tests/sdk-teardown.test.jsindex 57db3b679..f01087af2 100644--- a/plugins/model-apps/scripts/tests/sdk-teardown.test.js+++ b/plugins/model-apps/scripts/tests/sdk-teardown.test.js@@ -1405,8 +1405,8 @@ const ruleWorld = (over = {}) => ruleEnvironment({});const keptTableLabel = (table, ruleNames) => `table ${table} (kept — business rule(s) on it could not be deleted (${ruleNames.map((n) => JSON.stringify(n)).join(', ')}), and once the table is gone a rule's activated copy can never be deleted; a re-run deletes the rule(s) first, then the table)`;// Every SDK call of a run as one line each, in order — the request sequence the assertions compare.-const ruleRequests = (sdk, from = 0) => sdk.calls.slice(from).map((c) => [c.method, c.entitySet, c.kind, c.type, c.query, c.logical, c.id, c.data && JSON.stringify(c.data)].filter(Boolean).join(' '));-const ruleWrites = (sdk, from = 0) => ruleRequests(sdk, from).filter((line) => /^(updateRecord|deleteRecord|deleteTable|deleteSolution|deleteRemoteArtifact|deleteWebResource) /.test(line));+const ruleRequests = (sdk, from = 0) => sdk.calls.slice(from).map((c) => [c.method, c.entitySet, c.kind, c.type, c.query, c.logical, c.id, c.name, c.schemaName, c.data && JSON.stringify(c.data)].filter(Boolean).join(' '));+const ruleWrites = (sdk, from = 0) => ruleRequests(sdk, from).filter((line) => /^(updateRecord|deleteRecord|deleteTable|deleteSolution|deleteRemoteArtifact|deleteWebResource|deleteRelationship|deleteGlobalOptionSet) /.test(line));test('a business rule whose definition cannot be deleted keeps ITS table (and the solution); everything else is deleted as before', async () => {const sdk = ruleWorld({ failNextDelete: ['gate-def'] });@@ -1669,6 +1669,355 @@ test('a dry run is unchanged: the same plan, nothing read or written, nothing keassert.deepStrictEqual(sdk.calls, []);});+// --- what only a kept table's existence blocks is kept with it ------------------------------------+//+// A table kept for a failed rule (above) goes on existing, and the platform refuses to delete three things for as long as it does+// (HTTP 400 "... cannot be deleted because it is referenced by N other components"): the table's ICON web resource, a GLOBAL CHOICE+// that one of its columns binds, and a relationship from the table to ITSELF (the plan defers that one behind the tables: its lookup+// sits on the table, so it goes with the table and never before it). Teardown used to send those deletes anyway and report each+// refusal as one more failed step next to the one real failure — the rule — until a re-run. They are now kept with the table: a+// `(kept — …)` skip that names it, and the re-run deletes them once the table goes. The run still ends as a failure, with the+// solution kept.+//+// `icons`, `bound` and `selfRef` are what the ENVIRONMENT holds: the web resources each table is the icon of, the global choices its+// columns bind, and the table a relationship to itself hangs on. Each is refused only while that table exists, and a table's delete+// takes its own relationship to itself with it (the plan relies on that: the deferred delete then reads "not found").+function dependentsEnvironment({ icons = {}, bound = {}, selfRef = {}, ...state }) {+ const sdk = ruleEnvironment(state);+ const exists = (table) => sdk.db.tables.has(table);+ const refused = (what, id, by) => Object.assign(new Error(`HTTP 400: The ${what}(${id}) component cannot be deleted because it is referenced by ${by} other components.`), { statusCode: 400 });+ const deleteWebResource = sdk.deleteWebResource;+ sdk.deleteWebResource = async (id) => {+ const row = Object.values(sdk.db.webresources).find((w) => w.webresourceid === id);+ if (row && Object.entries(icons).some(([table, names]) => exists(table) && names.includes(row.name))) {+ sdk.calls.push({ method: 'deleteWebResource', id });+ throw refused('WebResource', id, 1);+ }+ return deleteWebResource(id);+ };+ const deleteGlobalOptionSet = sdk.deleteGlobalOptionSet;+ sdk.deleteGlobalOptionSet = async (name) => {+ if (Object.entries(bound).some(([table, names]) => exists(table) && names.includes(name))) {+ sdk.calls.push({ method: 'deleteGlobalOptionSet', name });+ throw refused('OptionSet', name, 1);+ }+ return deleteGlobalOptionSet(name);+ };+ const deleteRelationship = sdk.deleteRelationship;+ sdk.deleteRelationship = async (schemaName) => {+ if (sdk.db.relationships.has(schemaName) && selfRef[schemaName] && exists(selfRef[schemaName])) {+ sdk.calls.push({ method: 'deleteRelationship', schemaName });+ throw refused('EntityRelationship', schemaName, 2);+ }+ return deleteRelationship(schemaName);+ };+ const deleteTable = sdk.deleteTable;+ sdk.deleteTable = async (logical) => {+ try {+ return await deleteTable(logical);+ } finally {+ for (const [schemaName, table] of Object.entries(selfRef)) if (table === logical && !exists(table)) sdk.db.relationships.delete(schemaName);+ }+ };+ return sdk;+}++// Two tables: `new_ticket` carries the rule that fails and `new_customer` is deleted as ever. Each has an icon, a column that binds a+// global choice and a relationship to itself; the script is a web resource that is nobody's icon, and one more relationship joins the+// two tables (it goes before any table, so a table kept later does not hold it).+const dependentsSpec = (over = {}) => ({+ solution: { uniqueName: 'S', publisherPrefix: 'new' },+ entities: [+ { schemaName: 'new_ticket', primaryAttribute: { schemaName: 'new_name' }, vectorIcon: 'new_ticket.svg', columns: [{ schemaName: 'new_priority', type: 'Choice', globalChoice: 'new_priority' }] },+ { schemaName: 'new_customer', primaryAttribute: { schemaName: 'new_name' }, vectorIcon: 'new_customer.svg', columns: [{ schemaName: 'new_tier', type: 'Choice', globalChoice: 'new_tier' }] },+ ],+ relationships: [+ { type: 'OneToMany', referenced: 'new_customer', referencing: 'new_ticket', lookup: { schemaName: 'new_CustomerId' } },+ { type: 'OneToMany', referenced: 'new_ticket', referencing: 'new_ticket', lookup: { schemaName: 'new_ParentTicketId' } },+ { type: 'OneToMany', referenced: 'new_customer', referencing: 'new_customer', lookup: { schemaName: 'new_ParentCustomerId' } },+ ],+ webResources: [+ { name: 'new_ticket.svg', type: 'svg', content: '<svg/>' },+ { name: 'new_customer.svg', type: 'svg', content: '<svg/>' },+ { name: 'new_ticket.js', type: 'js', content: '' },+ ],+ globalChoices: [+ { name: 'new_priority', displayName: 'Priority', options: ['Low', 'High'] },+ { name: 'new_tier', displayName: 'Tier', options: ['Gold', 'Silver'] },+ ],+ businessRules: [{ entity: 'new_ticket', name: 'Gate' }],+ ...over,+});+const dependentsWorld = (over = {}) => dependentsEnvironment({+ tables: ['new_ticket', 'new_customer'],+ relationships: ['new_customer_new_ticket', 'new_ticket_new_ticket', 'new_customer_new_customer'],+ webresources: {+ 'new_ticket.svg': { webresourceid: 'wr-ticket', name: 'new_ticket.svg' },+ 'new_customer.svg': { webresourceid: 'wr-customer', name: 'new_customer.svg' },+ 'new_ticket.js': { webresourceid: 'wr-js', name: 'new_ticket.js' },+ },+ globalchoices: ['new_priority', 'new_tier'],+ rules: ruleRows('Gate', 'new_ticket', 'gate'),+ icons: { new_ticket: ['new_ticket.svg'], new_customer: ['new_customer.svg'] },+ bound: { new_ticket: ['new_priority'], new_customer: ['new_tier'] },+ selfRef: { new_ticket_new_ticket: 'new_ticket', new_customer_new_customer: 'new_customer' },+ ...over,+});+const keptWithTable = (label, how, tables = 1) => `${label} (kept — ${how}, and ${tables > 1 ? 'those tables are' : 'that table is'} kept because business rule(s) on ${tables > 1 ? 'them' : 'it'} could not be deleted; a re-run deletes it once ${tables > 1 ? 'they are' : 'the table is'} gone)`;+const solutionKept = /^solution S \(kept — 1 earlier step\(s\) failed/;++test('a table kept for a failed rule keeps its icon, the global choice its column binds and its relationship to itself too — one failure is reported, everything else goes as before', async () => {+ const sdk = dependentsWorld({ failNextDelete: ['gate-def'] });+ const events = [];+ const res = await runTeardown(dependentsSpec(), { apply: true }, { sdk, emit: (e) => events.push(e) });++ // The one real failure. Before, the platform's three refusals were reported next to it, as three more failed steps.+ assert.strictEqual(res.ok, false, 'the rule failed, so the run is a failure');+ assert.deepStrictEqual(res.errors.map((e) => e.step), ['business rule "Gate" (new_ticket)']);+ assert.deepStrictEqual(events.filter((e) => e.status === 'error').map((e) => e.label), ['business rule "Gate" (new_ticket)']);++ // What is kept, in the order the plan reaches it — each a `(kept — …)` skip that names the table, and the solution last.+ assert.deepStrictEqual(res.skipped.slice(0, 4), [+ keptTableLabel('new_ticket', ['Gate']),+ keptWithTable('relationship new_ticket_new_ticket', 'it relates table new_ticket to itself'),+ keptWithTable('web resource new_ticket.svg', 'it is the icon of table new_ticket'),+ keptWithTable('global choice new_priority', 'a column of table new_ticket binds it'),+ ]);+ assert.strictEqual(res.skipped.length, 5, JSON.stringify(res.skipped));+ assert.match(res.skipped[4], solutionKept, 'the solution is kept for the re-run, as for any earlier failure');+ assert.deepStrictEqual(events.filter((e) => e.status === 'skip').map((e) => [e.phase, e.skip]), [+ ['tables', 'kept'], ['relationships', 'kept'], ['web-resources', 'kept'], ['global-choices', 'kept'], ['solution', 'kept'],+ ], 'each is a kept skip, which the summary counts as kept');++ // What was deleted as before: the other table with everything it holds, the script, the relationship between the two tables.+ assert.deepStrictEqual(res.deleted.table, ['new_customer']);+ assert.deepStrictEqual(res.deleted.webResource, ['wr-customer', 'wr-js']);+ assert.deepStrictEqual(res.deleted.globalChoice, ['new_tier']);+ assert.deepStrictEqual(res.deleted.relationship, ['new_customer_new_ticket', 'new_customer_new_customer']);++ // What the environment holds afterwards: the table with the rule and everything that hangs on it, nothing the platform refused.+ assert.deepStrictEqual([...sdk.db.tables], ['new_ticket']);+ assert.deepStrictEqual(Object.keys(sdk.db.webresources), ['new_ticket.svg']);+ assert.deepStrictEqual([...sdk.db.globalchoices], ['new_priority']);+ assert.deepStrictEqual([...sdk.db.relationships], ['new_ticket_new_ticket']);+ assert.deepStrictEqual(sdk.workflowIds(), ['gate-def', 'gate-copy']);+ assert.deepStrictEqual(Object.keys(sdk.db.solutions), ['S']);+ assert.deepStrictEqual(sdk.stranded(), []);++ // No delete the platform would refuse is sent, and the failed rule delete is still sent once.+ const sent = ruleWrites(sdk);+ for (const refusedDelete of ['deleteWebResource wr-ticket', 'deleteGlobalOptionSet new_priority', 'deleteRelationship new_ticket_new_ticket']) {+ assert.ok(!sent.includes(refusedDelete), `${refusedDelete} was sent: ${sent.join(' | ')}`);+ }+ assert.strictEqual(sent.filter((line) => line === 'deleteRecord workflow gate-def').length, 1);+});++test('the re-run, with the fault gone, deletes the rule, the table and everything that was kept with it', async () => {+ const sdk = dependentsWorld({ failNextDelete: ['gate-def'] });+ const failed = await runTeardown(dependentsSpec(), { apply: true }, { sdk, emit: () => {} });+ assert.strictEqual(failed.ok, false);++ const from = sdk.calls.length;+ const again = await runTeardown(dependentsSpec(), { apply: true }, { sdk, emit: () => {} });+ assert.strictEqual(again.ok, true, JSON.stringify(again.errors));+ assert.deepStrictEqual(again.skipped.filter((s) => /kept/.test(s)), [], 'nothing is kept once the rule is deletable');+ assert.deepStrictEqual(ruleWrites(sdk, from), [+ 'deleteRecord workflow gate-def',+ 'deleteRecord workflow gate-copy',+ 'deleteRelationship new_customer_new_ticket', // gone in the first run: the tolerated not-found+ 'deleteTable new_ticket',+ 'deleteTable new_customer', // gone in the first run+ 'deleteRelationship new_ticket_new_ticket', // went with its table: the tolerated not-found the plan counts on+ 'deleteRelationship new_customer_new_customer',+ 'deleteWebResource wr-ticket',+ 'deleteGlobalOptionSet new_priority',+ 'deleteGlobalOptionSet new_tier',+ 'deleteSolution sol-1',+ ]);+ assert.deepStrictEqual([...sdk.db.tables], []);+ assert.deepStrictEqual(Object.keys(sdk.db.webresources), []);+ assert.deepStrictEqual([...sdk.db.globalchoices], []);+ assert.deepStrictEqual([...sdk.db.relationships], []);+ assert.deepStrictEqual(sdk.workflowIds(), []);+ assert.deepStrictEqual(Object.keys(sdk.db.solutions), []);+});++// The control: with no failed rule nothing is kept, and every request goes out as it always did — in the same order, the same number.+test('with no failed rule the same spec is torn down exactly as before: the same requests in the same order, nothing kept', async () => {+ const sdk = dependentsWorld();+ const res = await runTeardown(dependentsSpec(), { apply: true }, { sdk, emit: () => {} });+ assert.strictEqual(res.ok, true, JSON.stringify(res.errors));+ assert.deepStrictEqual(res.skipped, []);+ assert.deepStrictEqual(ruleRequests(sdk), [+ 'queryRecords workflow',+ 'updateRecord workflow gate-def {"statecode":0,"statuscode":1}',+ 'deleteRecord workflow gate-def',+ 'deleteRecord workflow gate-copy',+ 'deleteRelationship new_customer_new_ticket',+ 'findTables new_ticket',+ 'deleteTable new_ticket',+ 'findTables new_customer',+ 'deleteTable new_customer',+ 'deleteRelationship new_ticket_new_ticket',+ 'deleteRelationship new_customer_new_customer',+ 'resolveArtifact webResource',+ 'deleteWebResource wr-ticket',+ 'resolveArtifact webResource',+ 'deleteWebResource wr-customer',+ 'resolveArtifact webResource',+ 'deleteWebResource wr-js',+ 'deleteGlobalOptionSet new_priority',+ 'deleteGlobalOptionSet new_tier',+ 'resolveArtifact solution',+ 'deleteSolution sol-1',+ ]);+ assert.deepStrictEqual([...sdk.db.tables], []);+ assert.deepStrictEqual(Object.keys(sdk.db.webresources), []);+ assert.deepStrictEqual([...sdk.db.globalchoices], []);+ assert.deepStrictEqual([...sdk.db.relationships], []);+});++test('an icon and a global choice that the kept table and a deleted table share stay while the kept table needs them', async () => {+ const shared = (spec) => ({+ ...spec,+ entities: spec.entities.map((e) => ({ ...e, vectorIcon: 'shared.svg', columns: [{ schemaName: 'new_level', type: 'Choice', globalChoice: 'new_level' }] })),+ webResources: [{ name: 'shared.svg', type: 'svg', content: '<svg/>' }],+ globalChoices: [{ name: 'new_level', displayName: 'Level', options: ['Low', 'High'] }],+ });+ const sdk = dependentsWorld({+ failNextDelete: ['gate-def'],+ webresources: { 'shared.svg': { webresourceid: 'wr-shared', name: 'shared.svg' } },+ globalchoices: ['new_level'],+ icons: { new_ticket: ['shared.svg'], new_customer: ['shared.svg'] },+ bound: { new_ticket: ['new_level'], new_customer: ['new_level'] },+ });+ const res = await runTeardown(shared(dependentsSpec()), { apply: true }, { sdk, emit: () => {} });++ assert.deepStrictEqual(res.errors.map((e) => e.step), ['business rule "Gate" (new_ticket)']);+ // Named by the table that is kept — the other table is deleted in this run and holds nothing.+ assert.ok(res.skipped.includes(keptWithTable('web resource shared.svg', 'it is the icon of table new_ticket')), JSON.stringify(res.skipped));+ assert.ok(res.skipped.includes(keptWithTable('global choice new_level', 'a column of table new_ticket binds it')), JSON.stringify(res.skipped));+ assert.deepStrictEqual(res.deleted.table, ['new_customer']);+ assert.deepStrictEqual(Object.keys(sdk.db.webresources), ['shared.svg']);+ assert.deepStrictEqual([...sdk.db.globalchoices], ['new_level']);++ // Once the other table is deleted too (a later run, the rule deletable) both go with the last table that needed them.+ const again = await runTeardown(shared(dependentsSpec()), { apply: true }, { sdk, emit: () => {} });+ assert.strictEqual(again.ok, true, JSON.stringify(again.errors));+ assert.deepStrictEqual(Object.keys(sdk.db.webresources), []);+ assert.deepStrictEqual([...sdk.db.globalchoices], []);+});++test('an icon shared by two kept tables names both, and a table the run deletes holds nothing', async () => {+ const sdk = dependentsWorld({+ failNextDelete: ['gate-def', 'lock-def'],+ rules: [...ruleRows('Gate', 'new_ticket', 'gate'), ...ruleRows('Lock', 'new_customer', 'lock')],+ webresources: { 'shared.svg': { webresourceid: 'wr-shared', name: 'shared.svg' } },+ icons: { new_ticket: ['shared.svg'], new_customer: ['shared.svg'] },+ });+ const spec = dependentsSpec({+ entities: dependentsSpec().entities.map((e) => ({ ...e, vectorIcon: 'shared.svg' })),+ webResources: [{ name: 'shared.svg', type: 'svg', content: '<svg/>' }],+ businessRules: [{ entity: 'new_ticket', name: 'Gate' }, { entity: 'new_customer', name: 'Lock' }],+ });+ const res = await runTeardown(spec, { apply: true }, { sdk, emit: () => {} });+ assert.deepStrictEqual(res.errors.map((e) => e.step), ['business rule "Gate" (new_ticket)', 'business rule "Lock" (new_customer)']);+ assert.ok(res.skipped.includes(keptWithTable('web resource shared.svg', 'it is the icon of table new_ticket; it is the icon of table new_customer', 2)), JSON.stringify(res.skipped));+ assert.deepStrictEqual(Object.keys(sdk.db.webresources), ['shared.svg']);+ assert.deepStrictEqual([...sdk.db.tables].sort(), ['new_customer', 'new_ticket']);+});++test('a reused table that a failed rule is on is not a table this run keeps — what hangs on it is sent, and refused, exactly as before', async () => {+ const sdk = dependentsWorld({ failNextDelete: ['gate-def'] });+ const spec = dependentsSpec();+ spec.entities[0].existing = true;+ const res = await runTeardown(spec, { apply: true }, { sdk, emit: () => {} });+ assert.deepStrictEqual(res.errors.map((e) => e.step), [+ 'business rule "Gate" (new_ticket)',+ 'relationship new_ticket_new_ticket',+ 'web resource new_ticket.svg',+ 'global choice new_priority',+ ]);+ assert.ok(res.skipped.includes('table new_ticket (reused table (existing: true) — not created by this build)'), JSON.stringify(res.skipped));+ assert.ok(!res.skipped.some((s) => /^(relationship|web resource|global choice) .*kept — .*business rule/.test(s)), 'its own reason stands; nothing else is kept for a rule');+});++test('a kept table\'s icon that the environment no longer has reads "not found", as before — nothing is kept for what is not there', async () => {+ const sdk = dependentsWorld({ failNextDelete: ['gate-def'], webresources: { 'new_customer.svg': { webresourceid: 'wr-customer', name: 'new_customer.svg' } } });+ const events = [];+ const res = await runTeardown(dependentsSpec(), { apply: true }, { sdk, emit: (e) => events.push(e) });+ assert.ok(res.skipped.includes('web resource new_ticket.svg'), JSON.stringify(res.skipped));+ assert.ok(events.some((e) => e.phase === 'web-resources' && e.status === 'skip' && e.skip === 'not-found' && e.label === 'web resource new_ticket.svg (not found)'), JSON.stringify(events.filter((e) => e.phase === 'web-resources')));+});++test('the plan says which tables hold a web resource, a global choice and a relationship to itself — and the plan itself is as it was', () => {+ const steps = planTeardown(dependentsSpec());+ const heldBy = (kind, key) => (steps.find((s) => s.kind === kind && (s.target.name === key || s.target.schemaName === key)) || {}).heldBy;+ assert.deepStrictEqual(heldBy('webResource', 'new_ticket.svg'), [{ table: 'new_ticket', by: 'icon' }]);+ assert.deepStrictEqual(heldBy('webResource', 'new_customer.svg'), [{ table: 'new_customer', by: 'icon' }]);+ assert.strictEqual(heldBy('webResource', 'new_ticket.js'), undefined, 'a script is nobody\'s icon');+ assert.deepStrictEqual(heldBy('globalChoice', 'new_priority'), [{ table: 'new_ticket', by: 'column' }]);+ assert.deepStrictEqual(heldBy('relationship', 'new_ticket_new_ticket'), [{ table: 'new_ticket', by: 'itself' }]);+ assert.strictEqual(heldBy('relationship', 'new_customer_new_ticket'), undefined, 'a relationship between two tables goes before the tables, so no table holds it');+ // Same labels, same order — a dry run prints exactly this.+ assert.deepStrictEqual(steps.map((s) => s.label), [+ 'business rule "Gate" (new_ticket)',+ 'reset default views for new_ticket (drop parent lookups)',+ 'reset default views for new_customer (drop parent lookups)',+ 'relationship new_customer_new_ticket',+ 'table new_ticket',+ 'table new_customer',+ 'relationship new_ticket_new_ticket',+ 'relationship new_customer_new_customer',+ 'web resource new_ticket.svg',+ 'web resource new_customer.svg',+ 'web resource new_ticket.js',+ 'global choice new_priority',+ 'global choice new_tier',+ 'solution S',+ ]);+});++test('what a table holds follows how the build made it: an icon by its lower-cased name, a global choice by the exact name a Choice column asks for', () => {+ const spec = {+ solution: { uniqueName: 'S', publisherPrefix: 'new' },+ entities: [{+ schemaName: 'new_Ticket',+ primaryAttribute: { schemaName: 'new_name' },+ vectorIcon: 'NEW_Glyph.svg',+ icon: 'new_photo.png',+ columns: [+ { schemaName: 'new_tags', type: 'MultiChoice', globalChoice: 'new_tags' },+ // The build binds a column by looking the name up exactly, so a reference in another letter case was never bound: the column got+ // inline options of its own instead, and the global choice has nothing to wait for.+ { schemaName: 'new_stage', type: 'Choice', globalChoice: 'NEW_STAGE' },+ // Only a Choice or MultiChoice column binds a global choice; on any other type the name is ignored.+ { schemaName: 'new_note', type: 'Text', globalChoice: 'new_note' },+ ],+ }],+ relationships: [+ { type: 'OneToMany', referenced: 'New_Ticket', referencing: 'new_ticket', lookup: { schemaName: 'new_ParentId' } },+ { type: 'ManyToMany', schemaName: 'new_ticket_related', entity1: 'new_ticket', entity2: 'new_ticket' },+ ],+ webResources: [{ name: 'new_glyph.svg', type: 'svg', content: '<svg/>' }, { name: 'new_photo.png', type: 'png', contentBase64: '' }],+ globalChoices: [{ name: 'new_tags', options: ['a'] }, { name: 'new_stage', options: ['a'] }, { name: 'new_note', options: ['a'] }],+ };+ const steps = planTeardown(spec);+ const heldBy = (kind, key) => (steps.find((s) => s.kind === kind && (s.target.name === key || s.target.schemaName === key)) || {}).heldBy;+ assert.deepStrictEqual(heldBy('webResource', 'new_glyph.svg'), [{ table: 'new_ticket', by: 'icon' }], 'a web resource name is not case-sensitive');+ assert.deepStrictEqual(heldBy('webResource', 'new_photo.png'), [{ table: 'new_ticket', by: 'icon' }], 'the raster icon holds its web resource too');+ assert.deepStrictEqual(heldBy('globalChoice', 'new_tags'), [{ table: 'new_ticket', by: 'column' }]);+ assert.strictEqual(heldBy('globalChoice', 'new_stage'), undefined);+ assert.strictEqual(heldBy('globalChoice', 'new_note'), undefined);+ const relationships = steps.filter((s) => s.kind === 'relationship');+ assert.deepStrictEqual(relationships.map((s) => [s.target.schemaName, s.heldBy]), [+ ['new_ticket_related', undefined], // the many-to-many, planned before the tables, as it always was+ ['new_ticket_new_ticket', [{ table: 'new_ticket', by: 'itself' }]],+ ]);+ assert.ok(steps.findIndex((s) => s === relationships[0]) < steps.findIndex((s) => s.kind === 'table'));+ assert.ok(steps.findIndex((s) => s === relationships[1]) > steps.findIndex((s) => s.kind === 'table'));+});+// --- helpers ----------------------------------------------------------------------------test('odataStr doubles single quotes (OData literal escaping)', () => {@@ -1724,7 +2073,7 @@ test('teardown plans an ai-summaries step (before tables) for each candidate andassert.strictEqual(plan[aiIdx].phase, 'ai-summaries');assert.strictEqual(plan[aiIdx].target.entityLogicalName, 'new_memo');- // Run with a mock sdk that records removeRowSummary calls+ // Run with a mock sdk that records removeRowSummary calls. The environment holds a row summary for the table: the step looks for the skill row before it removes one.const removeCalls = [];const sdk = {resolveArtifact: async (kind, identity) => {@@ -1732,6 +2081,7 @@ test('teardown plans an ai-summaries step (before tables) for each candidate andif (kind === 'solution') return [{ id: 'sol-1', name: 'AiTest' }];return [];},+ dataverse: { get: async (url) => (/^\/aiskillconfigs\?/.test(url) ? { status: 200, body: { value: [{ aiskillconfigid: 'skill-1' }] } } : { status: 200, body: { value: [] } }) },removeRowSummary: async (args) => { removeCalls.push(args); },deleteTable: async () => { const e = new Error('not found'); e.statusCode = 404; throw e; },deleteSolution: async () => {},diff --git a/plugins/model-apps/scripts/tests/sitemap-adopt-real-bundle.test.js b/plugins/model-apps/scripts/tests/sitemap-adopt-real-bundle.test.jsindex 5504ff8d5..3c2fde53b 100644--- a/plugins/model-apps/scripts/tests/sitemap-adopt-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/sitemap-adopt-real-bundle.test.js@@ -180,7 +180,9 @@ test('REAL BUNDLE: a title the spec itself changes is applied, with nothing to r// The SDK only PATCHES an existing <Titles> on a node that has a bag, and reads an empty typed title as// "no edit" — so a title added to an entry that had none, or removed from one that had it, must be// reconciled in the adopted bag, or it would silently not happen (it did happen on the bag-less path).-test('REAL BUNDLE: a title added to an entry that had none is written; a removed one is dropped, other languages kept', async () => {+// A title is removed only when the spec's baseline shows the author took it out: a spec that merely+// says nothing about the title never clears one (nav-titles-base-language-real-bundle.test.js).+test('REAL BUNDLE: a title added to an entry that had none is written; one the baseline shows the author took out is dropped, other languages kept', async () => {const untitled = '<SiteMap IntroducedVersion="7.0.0.0"><Area Id="area_ops" ResourceId="Contoso.AreaRes"><Titles><Title LCID="1033" Title="Operations" /></Titles>'+ '<Group Id="grp_main"><Titles><Title LCID="1033" Title="Main" /></Titles>'+ `${LEGACY_DASHBOARD_TAG}<Titles><Title LCID="1033" Title="Event operations" /></Titles></SubArea>`@@ -191,10 +193,16 @@ test('REAL BUNDLE: a title added to an entry that had none is written; a removedconst spec = specFor();delete spec.appShell.areas[0].groups[0].subAreas[0].title; // the dashboard entry's title removed- const removed = await rebuild(deployedXml(), spec);+ const removed = await rebuild(deployedXml(), spec, { baseChrome: chromeByTargetKey(specFor(), CREATED) });const dash = removed.xml.slice(removed.xml.indexOf(LEGACY_DASHBOARD_TAG), removed.xml.indexOf('</SubArea>', removed.xml.indexOf(LEGACY_DASHBOARD_TAG)));assert.doesNotMatch(dash, /LCID="1033"/, 'the title at the SDK\u2019s language is gone');assert.match(dash, /<Title LCID="1036" Title="Opérations \(FR\)" \/>/, 'another language\u2019s title is not the spec\u2019s to drop');++ // With no baseline nothing shows the spec ever stated the title: it says nothing about it, so it stays, with the other language beside it.+ const kept = await rebuild(deployedXml(), spec);+ const keptDash = kept.xml.slice(kept.xml.indexOf(LEGACY_DASHBOARD_TAG), kept.xml.indexOf('</SubArea>', kept.xml.indexOf(LEGACY_DASHBOARD_TAG)));+ assert.match(keptDash, /<Title LCID="1033" Title="Event operations" \/><Title LCID="1036" Title="Opérations \(FR\)" \/>/, keptDash);+ assert.ok(describeSitemapNotes(kept.notes).some((l) => /^nav entry "Event operations": kept the environment's title 'Event operations' \u2014 the spec has none for it/.test(l)), JSON.stringify(describeSitemapNotes(kept.notes)));});test('REAL BUNDLE: renaming the dashboard in the spec, as the build asks, keeps the baseline lined up', async () => {@@ -236,10 +244,10 @@ test('REAL BUNDLE: a spec downloaded from another environment lines up by the idassert.ok(describeSitemapNotes(notes).some((l) => /kept the environment's title 'Event operations'/.test(l)));});-test('REAL BUNDLE: removing a group\u2019s title leaves its description ahead of its entries', async () => {+test('REAL BUNDLE: a group the spec gives no label keeps its title, with its description still ahead of its entries', async () => {// A group an earlier build created (so it corresponds by its id) that the designer gave a description.- // Its label is then removed from the spec: the title goes, and the description must stay before the- // subareas, where the sitemap schema requires it.+ // Its label is not in the spec: its title stays, and the title and the description stay before the+ // subareas, where the sitemap schema requires them.const xml = '<SiteMap IntroducedVersion="7.0.0.0"><Area Id="area_0" ShowGroups="true"><Titles><Title LCID="1033" Title="Operations" /></Titles>'+ '<Group Id="group_0_0"><Titles><Title LCID="1033" Title="Main" /></Titles><Descriptions><Description LCID="1033" Description="Day-to-day work" /></Descriptions>'+ `${LEGACY_DASHBOARD_TAG}<Titles><Title LCID="1033" Title="Event operations" /></Titles></SubArea>`@@ -249,8 +257,8 @@ test('REAL BUNDLE: removing a group\u2019s title leaves its description ahead ofdelete spec.appShell.areas[0].groups[0].label;const out = await rebuild(xml, spec);const group = out.xml.slice(out.xml.indexOf('<Group'), out.xml.indexOf('</Group>'));- assert.match(group, /^<Group Id="group_0_0"><Descriptions><Description LCID="1033" Description="Day-to-day work" \/><\/Descriptions><SubArea Id="ops_dashboard"/, group);- assert.doesNotMatch(group, /<Titles><Title LCID="1033" Title="Main"/, 'the removed title is gone');+ assert.match(group, /^<Group Id="group_0_0"><Titles><Title LCID="1033" Title="Main" \/><\/Titles><Descriptions><Description LCID="1033" Description="Day-to-day work" \/><\/Descriptions><SubArea Id="ops_dashboard"/, group);+ assert.ok(describeSitemapNotes(out.notes).some((l) => /^group "Main": kept the environment's title 'Main' \u2014 the spec has none for it/.test(l)), JSON.stringify(describeSitemapNotes(out.notes)));});// A generative page entry the spec gives no icon holds the page icon the platform gives it — the SDK writes it, as the app designer does — so a rebuild finds an icon live that neither the spec nor itsdiff --git a/plugins/model-apps/scripts/tests/sitemap-merge-unstated-titles.test.js b/plugins/model-apps/scripts/tests/sitemap-merge-unstated-titles.test.jsnew file mode 100644index 000000000..f9f85c4b6--- /dev/null+++ b/plugins/model-apps/scripts/tests/sitemap-merge-unstated-titles.test.js@@ -0,0 +1,205 @@+'use strict';+// Unit tests for what a rebuild does with the title of a navigation node the spec gives none (lib/sitemap-merge.js). The same rules end to end, through the real SDK, are in+// nav-titles-base-language-real-bundle.test.js and sitemap-adopt-real-bundle.test.js.+//+// A spec's empty label or title says nothing, it does not ask for none: the download of an environment whose base language is not 1033 once wrote every label empty, and+// the spec an author leaves a title out of has not asked for the title to go either. So a title the live node holds is kept — unless the spec's baseline shows the author took+// the title of an ENTRY out of a spec that had stated it, which is an edit and is applied. Areas and groups have no target to find a baseline by, so they are always kept.+const { test } = require('node:test');+const assert = require('node:assert');+const { adoptLiveSitemap, chromeByTargetKey, describeSitemapNotes } = require('../lib/sitemap-merge.js');++const bag = (id, children = []) => ({ a: [['Id', id]], c: children });+const titlesChild = (i, byLanguage) => ({ i, node: { n: 'Titles', a: [], c: Object.entries(byLanguage).map(([lcid, title]) => ({ n: 'Title', a: [['LCID', lcid], ['Title', title]], c: [] })) } });+const tree = (areas) => ({ areas });+const entry = (id, entity, title, b) => ({ id, type: 'Entity', entity, title, ...(b ? { bag: b } : {}) });+const live = () => tree([{ id: 'area_0', title: 'Trabajo', bag: bag('area_0', [titlesChild(0, { 3082: 'Trabajo' })]), groups: [+ { id: 'group_0_0', title: 'Casos', bag: bag('group_0_0', [titlesChild(0, { 3082: 'Casos' })]), subAreas: [+ entry('sub_0_0_0', 'contoso_case', 'Expedientes', bag('sub_0_0_0', [titlesChild(0, { 3082: 'Expedientes' })])),+ ] },+] }]);+const desired = ({ area, group, title }) => tree([{ id: 'area_0', title: area, groups: [{ id: 'group_0_0', title: group, subAreas: [entry('sub_0_0_0', 'contoso_case', title)] }] }]);+const specOf = (label, groupLabel, title) => ({ appShell: { areas: [{ label, groups: [{ label: groupLabel, subAreas: [{ entity: 'contoso_case', ...(title === undefined ? {} : { title }) }] }] }] } });+const kinds = (notes) => notes.map((n) => [n.kind, n.node, n.field, n.unspecified === true]);++test('an area or group the spec gives no label keeps the title it has, whether the label is empty, blank or absent', () => {+ for (const nothing of ['', ' ', undefined, null]) {+ const { siteMap, notes } = adoptLiveSitemap(desired({ area: nothing, group: nothing, title: 'Expedientes' }), live(), { lcid: 3082 });+ const area = siteMap.areas[0];+ assert.strictEqual(area.title, 'Trabajo', JSON.stringify(nothing));+ assert.strictEqual(area.groups[0].title, 'Casos', JSON.stringify(nothing));+ assert.deepStrictEqual(area.bag.c.map((e) => e.node.n), ['Titles'], 'and its titles are still there to be written back');+ assert.deepStrictEqual(kinds(notes), [['kept', 'area', 'title', true], ['kept', 'group', 'title', true]], JSON.stringify(nothing));+ }+});++test('the notes for a title kept because the spec gives none say so, once per node, and name what a spec can do about it', () => {+ const { notes } = adoptLiveSitemap(desired({ area: '', group: '', title: '' }), live(), { lcid: 3082 });+ assert.deepStrictEqual(describeSitemapNotes(notes), [+ 'area "Trabajo": kept the environment\'s title \'Trabajo\' \u2014 the spec has none for it, so it is left as it is. State one in the spec to change it.',+ 'group "Casos": kept the environment\'s title \'Casos\' \u2014 the spec has none for it, so it is left as it is. State one in the spec to change it.',+ 'nav entry "Expedientes": kept the environment\'s title \'Expedientes\' \u2014 the spec has none for it, so it is left as it is. State one in the spec to change it.',+ ]);+});++test('a node the spec gives no title and the environment holds none for says nothing and changes nothing', () => {+ const untitled = tree([{ id: 'area_0', title: '', bag: bag('area_0'), groups: [{ id: 'group_0_0', title: '', bag: bag('group_0_0'), subAreas: [entry('sub_0_0_0', 'contoso_case', '', bag('sub_0_0_0'))] }] }]);+ const { siteMap, notes } = adoptLiveSitemap(desired({ area: '', group: '', title: '' }), untitled, { lcid: 3082 });+ assert.deepStrictEqual(notes, []);+ assert.deepStrictEqual(siteMap.areas[0].bag.c, [], 'no empty <Titles> is invented for it');+ assert.strictEqual(siteMap.areas[0].title, '');+});++test('a node whose live title is in another language only is the spec\u2019s to title, and nothing of the other language is touched', () => {+ const onlyFrench = tree([{ id: 'area_0', title: '', bag: bag('area_0', [titlesChild(0, { 1036: 'Travail' })]), groups: [{ id: 'group_0_0', title: '', bag: bag('group_0_0'), subAreas: [] }] }]);+ const { siteMap, notes } = adoptLiveSitemap(tree([{ id: 'area_0', title: 'Work', groups: [{ id: 'group_0_0', title: '', subAreas: [] }] }]), onlyFrench, { lcid: 1033 });+ assert.deepStrictEqual(notes.map((n) => [n.kind, n.live, n.spec]), [['changed', '', 'Work']]);+ assert.deepStrictEqual(siteMap.areas[0].bag.c[0].node.c.map((t) => t.a[0][1]), ['1036'], 'the French title is as it was; the SDK adds the English one beside it');+});++test('a title the spec states is applied, with a note, as before', () => {+ const { siteMap, notes } = adoptLiveSitemap(desired({ area: 'Operaciones', group: 'Expedientes', title: 'Casos' }), live(), { lcid: 3082 });+ assert.strictEqual(siteMap.areas[0].title, 'Operaciones');+ assert.strictEqual(siteMap.areas[0].groups[0].title, 'Expedientes');+ assert.strictEqual(siteMap.areas[0].groups[0].subAreas[0].title, 'Casos');+ assert.deepStrictEqual(kinds(notes), [['changed', 'area', 'title', false], ['changed', 'group', 'title', false], ['changed', 'subArea', 'title', false]]);+});++test('an entry the spec gives no title keeps its own when no baseline says the spec ever stated one', () => {+ for (const [what, opts] of [['no baseline', {}], ['a baseline that does not list the entry', { baseChrome: chromeByTargetKey({ appShell: { areas: [] } }) }]]) {+ const { siteMap, notes } = adoptLiveSitemap(desired({ area: 'Trabajo', group: 'Casos', title: undefined }), live(), { lcid: 3082, ...opts });+ const sub = siteMap.areas[0].groups[0].subAreas[0];+ assert.strictEqual(sub.title, 'Expedientes', what);+ assert.deepStrictEqual(kinds(notes), [['kept', 'subArea', 'title', true]], what);+ }+});++test('an entry the spec and its baseline both give no title keeps the title the environment gained, as it did, and says so as it did', () => {+ const baseline = specOf('Trabajo', 'Casos');+ const { siteMap, notes } = adoptLiveSitemap(desired({ area: 'Trabajo', group: 'Casos', title: undefined }), live(), { lcid: 3082, baseChrome: chromeByTargetKey(baseline) });+ assert.strictEqual(siteMap.areas[0].groups[0].subAreas[0].title, 'Expedientes');+ assert.deepStrictEqual(kinds(notes), [['kept', 'subArea', 'title', false]]);+ assert.match(describeSitemapNotes(notes)[0], /^nav entry "Expedientes": kept the environment's title 'Expedientes' \u2014 it changed there after this spec was last applied or downloaded, and the spec still has \(none\)\./);+});++test('an entry whose title the spec\u2019s baseline states and the spec now leaves out loses it: an author\u2019s edit, applied, with the other languages kept', () => {+ const both = live();+ both.areas[0].groups[0].subAreas[0].bag = bag('sub_0_0_0', [titlesChild(0, { 1033: 'Cases', 3082: 'Expedientes' }), { i: 1, node: { n: 'Privilege', a: [['Entity', 'contoso_case']], c: [] } }]);+ const baseline = specOf('Trabajo', 'Casos', 'Expedientes');+ const { siteMap, notes } = adoptLiveSitemap(desired({ area: 'Trabajo', group: 'Casos', title: undefined }), both, { lcid: 3082, baseChrome: chromeByTargetKey(baseline) });+ const sub = siteMap.areas[0].groups[0].subAreas[0];+ assert.ok(!sub.title, 'no typed title: the SDK is not asked to write one');+ assert.deepStrictEqual(sub.bag.c.map((e) => [e.i, e.node.n]), [[0, 'Titles'], [1, 'Privilege']]);+ assert.deepStrictEqual(sub.bag.c[0].node.c.map((t) => t.a[0][1]), ['1033'], 'only the title at the build\u2019s language goes');+ assert.deepStrictEqual(kinds(notes), [['changed', 'subArea', 'title', false]]);+ assert.strictEqual(notes[0].intended, true);+ assert.deepStrictEqual(describeSitemapNotes(notes), [], 'an edit the author made is not repeated back');+});++test('removing an entry\u2019s last title keeps its other children where the schema wants them', () => {+ const only = live();+ only.areas[0].groups[0].subAreas[0].bag = bag('sub_0_0_0', [titlesChild(0, { 3082: 'Expedientes' }), { i: 1, node: { n: 'Privilege', a: [['Entity', 'contoso_case']], c: [] } }]);+ const baseline = specOf('Trabajo', 'Casos', 'Expedientes');+ const { siteMap } = adoptLiveSitemap(desired({ area: 'Trabajo', group: 'Casos', title: undefined }), only, { lcid: 3082, baseChrome: chromeByTargetKey(baseline) });+ assert.deepStrictEqual(siteMap.areas[0].groups[0].subAreas[0].bag.c.map((e) => [e.i, e.node.n]), [[0, 'Privilege']], 'the wrapper goes with its last title and the next child moves up');+ assert.deepStrictEqual(only.areas[0].groups[0].subAreas[0].bag.c.map((e) => e.i), [0, 1], 'the live bag is not touched');+});++// --- a group or area with no entries ---------------------------------------------------------------------------------------------------------------------------+// A node with no entries has nothing to correspond to a live node by, and a spec that gives it no label has not said which one it is. The spec an earlier download wrote for an+// environment whose base language is not 1033 holds exactly that for every empty group the environment has (`label: ""`, no entries), beside a live group the designer gave an id+// of its own (`designer_future`) and a title in the environment's language. The two are paired only when nothing else could be meant: one such node on each side. When more than one+// could be, nothing is paired by position, and the live node a rebuild then replaces is named, with its title.+const emptyGroup = (id, title) => ({ id, title, bag: bag(id, [titlesChild(0, { 3082: title })]), subAreas: [] });+const liveWithGroups = (...groups) => {+ const t = live();+ t.areas[0].groups.push(...groups);+ return t;+};+// What an earlier download wrote: the populated group, and a group per empty one, each given the label in `labels`.+const downloadedGroups = (...labels) => tree([{ id: 'area_0', title: '', groups: [+ { id: 'group_0_0', title: '', subAreas: [entry('sub_0_0_0', 'contoso_case', '')] },+ ...labels.map((title, k) => ({ id: `group_0_${k + 1}`, title, subAreas: [] })),+] }]);+const groupsOf = (siteMap) => siteMap.areas[0].groups;+const replaced = (notes) => notes.filter((n) => n.kind === 'replaced');+const lost = (node, unlabelled, empty, title) => `${node} "${title}": has no entries, and the spec's unlabelled empty ${node}s cannot be matched to the environment's empty ${node}s one to one (${unlabelled} against ${empty}), `+ + `so the spec's are written as new, untitled ${node}s and this one, with its title '${title}', is not kept. Label the spec's ${node} '${title}' to keep it.`;++test('an unlabelled empty group beside the one empty group the environment holds is that group: its id, its titles and its title stay', () => {+ const { siteMap, notes } = adoptLiveSitemap(downloadedGroups(''), liveWithGroups(emptyGroup('designer_future', 'Futuro')), { lcid: 3082 });+ const future = groupsOf(siteMap)[1];+ assert.deepStrictEqual([future.id, future.title], ['designer_future', 'Futuro']);+ assert.deepStrictEqual(future.bag.c.map((e) => e.node.n), ['Titles'], 'and its titles are still there to be written back');+ assert.deepStrictEqual(replaced(notes), []);+ assert.ok(describeSitemapNotes(notes).includes('group "Futuro": kept the environment\'s title \'Futuro\' \u2014 the spec has none for it, so it is left as it is. State one in the spec to change it.'), JSON.stringify(describeSitemapNotes(notes)));+});++test('two unlabelled empty groups and two empty groups of the environment are not paired by position: the notes name both titles', () => {+ const { siteMap, notes } = adoptLiveSitemap(downloadedGroups('', ''), liveWithGroups(emptyGroup('designer_future', 'Futuro'), emptyGroup('designer_past', 'Pasado')), { lcid: 3082 });+ assert.deepStrictEqual(groupsOf(siteMap).map((g) => [g.id, g.title, g.bag !== undefined]), [['group_0_0', 'Casos', true], ['group_0_1', '', false], ['group_0_2', '', false]], 'new, untitled groups: neither took a live group\u2019s id or bag');+ assert.deepStrictEqual(replaced(notes).map((n) => [n.node, n.target, n.live]), [['group', 'group "Futuro"', 'Futuro'], ['group', 'group "Pasado"', 'Pasado']]);+ assert.deepStrictEqual(describeSitemapNotes(notes).filter((l) => /has no entries/.test(l)), [lost('group', 2, 2, 'Futuro'), lost('group', 2, 2, 'Pasado')]);+});++test('one unlabelled empty group beside two empty groups of the environment is no better told: neither is paired, and both are named', () => {+ const { siteMap, notes } = adoptLiveSitemap(downloadedGroups(''), liveWithGroups(emptyGroup('designer_future', 'Futuro'), emptyGroup('designer_past', 'Pasado')), { lcid: 3082 });+ assert.deepStrictEqual(groupsOf(siteMap).map((g) => [g.id, g.title, g.bag !== undefined]), [['group_0_0', 'Casos', true], ['group_0_1', '', false]]);+ assert.deepStrictEqual(describeSitemapNotes(notes).filter((l) => /has no entries/.test(l)), [lost('group', 1, 2, 'Futuro'), lost('group', 1, 2, 'Pasado')]);+});++test('two unlabelled empty groups beside one empty group of the environment: it is paired with neither, and named', () => {+ const { siteMap, notes } = adoptLiveSitemap(downloadedGroups('', ''), liveWithGroups(emptyGroup('designer_future', 'Futuro')), { lcid: 3082 });+ assert.deepStrictEqual(groupsOf(siteMap).map((g) => [g.id, g.title, g.bag !== undefined]), [['group_0_0', 'Casos', true], ['group_0_1', '', false], ['group_0_2', '', false]]);+ assert.deepStrictEqual(describeSitemapNotes(notes).filter((l) => /has no entries/.test(l)), [lost('group', 2, 1, 'Futuro')]);+});++test('an empty group of the environment that the spec has no unlabelled empty group for is not paired, and nothing is said of it: the spec does not list it', () => {+ const { siteMap, notes } = adoptLiveSitemap(downloadedGroups(), liveWithGroups(emptyGroup('designer_future', 'Futuro')), { lcid: 3082 });+ assert.deepStrictEqual(groupsOf(siteMap).map((g) => g.id), ['group_0_0']);+ assert.deepStrictEqual(replaced(notes), []);+ assert.ok(!describeSitemapNotes(notes).some((l) => /Futuro/.test(l)), JSON.stringify(describeSitemapNotes(notes)));+});++test('a group the spec labels with another label than the environment\u2019s empty group does is its own, and the environment\u2019s is not paired with it or said to be lost', () => {+ const { siteMap, notes } = adoptLiveSitemap(downloadedGroups('Nuevo'), liveWithGroups(emptyGroup('designer_future', 'Futuro')), { lcid: 3082 });+ assert.deepStrictEqual(groupsOf(siteMap).map((g) => [g.id, g.title, g.bag !== undefined]), [['group_0_0', 'Casos', true], ['group_0_1', 'Nuevo', false]]);+ assert.deepStrictEqual(replaced(notes), []);+});++test('an empty group the spec labels takes its own live group, and an unlabelled one beside it has nothing left to be paired with, so nothing is said', () => {+ const { siteMap, notes } = adoptLiveSitemap(downloadedGroups('Futuro', ''), liveWithGroups(emptyGroup('designer_future', 'Futuro')), { lcid: 3082 });+ assert.deepStrictEqual(groupsOf(siteMap).map((g) => [g.id, g.title]), [['group_0_0', 'Casos'], ['designer_future', 'Futuro'], ['group_0_2', '']]);+ assert.deepStrictEqual(replaced(notes), []);+});++test('an unlabelled empty group is still paired with a live one that has no title at the build\u2019s language, as before, and neither says anything', () => {+ const french = { id: 'designer_fr', title: '', bag: bag('designer_fr', [titlesChild(0, { 1036: 'Futur' })]), subAreas: [] };+ const { siteMap, notes } = adoptLiveSitemap(downloadedGroups(''), liveWithGroups(french), { lcid: 3082 });+ const paired = groupsOf(siteMap)[1];+ assert.strictEqual(paired.id, 'designer_fr');+ assert.deepStrictEqual(paired.bag.c[0].node.c.map((t) => t.a[0][1]), ['1036'], 'its other language is as it was');+ assert.deepStrictEqual(replaced(notes), []);+ assert.ok(!describeSitemapNotes(notes).some((l) => /Futur/.test(l)));+});++// An area with no entries at all is the same case one level up.+const emptyArea = (id, title) => ({ id, title, bag: bag(id, [titlesChild(0, { 3082: title })]), groups: [] });+const liveWithAreas = (...areas) => {+ const t = live();+ t.areas.push(...areas);+ return t;+};+const downloadedAreas = (...labels) => tree([+ { id: 'area_0', title: '', groups: [{ id: 'group_0_0', title: '', subAreas: [entry('sub_0_0_0', 'contoso_case', '')] }] },+ ...labels.map((title, k) => ({ id: `area_${k + 1}`, title, groups: [] })),+]);++test('an unlabelled empty area beside the one empty area the environment holds is that area; with two on each side nothing is paired and both are named', () => {+ const one = adoptLiveSitemap(downloadedAreas(''), liveWithAreas(emptyArea('designer_future', 'Futuro')), { lcid: 3082 });+ assert.deepStrictEqual(one.siteMap.areas.map((a) => [a.id, a.title]), [['area_0', 'Trabajo'], ['designer_future', 'Futuro']]);+ assert.deepStrictEqual(replaced(one.notes), []);+ const two = adoptLiveSitemap(downloadedAreas('', ''), liveWithAreas(emptyArea('designer_future', 'Futuro'), emptyArea('designer_past', 'Pasado')), { lcid: 3082 });+ assert.deepStrictEqual(two.siteMap.areas.map((a) => [a.id, a.title, a.bag !== undefined]), [['area_0', 'Trabajo', true], ['area_1', '', false], ['area_2', '', false]]);+ assert.deepStrictEqual(describeSitemapNotes(two.notes).filter((l) => /has no entries/.test(l)), [lost('area', 2, 2, 'Futuro'), lost('area', 2, 2, 'Pasado')]);+});diff --git a/plugins/model-apps/scripts/tests/sitemap-merge.test.js b/plugins/model-apps/scripts/tests/sitemap-merge.test.jsindex f7e06e87c..a8a8c9190 100644--- a/plugins/model-apps/scripts/tests/sitemap-merge.test.js+++ b/plugins/model-apps/scripts/tests/sitemap-merge.test.js@@ -329,10 +329,9 @@ test('keepsLiveValue is the keep rule: spec unchanged since the baseline, enviroassert.strictEqual(keepsLiveValue('nope', 'a', 'b', base), false);});-test('removing a node\u2019s last title keeps its other children ahead of the nodes the spec models', () => {- // A group titled only at the SDK's language, with a description: <Titles/><Descriptions/><SubArea/>.- // Its title is removed. The Descriptions child must move up to the vacated first slot — the sitemap- // schema puts Titles and Descriptions before the SubAreas — rather than a SubArea filling it.+test('a group the spec gives no label keeps its title, and every child of its bag where the schema wants it', () => {+ // A group titled only at the SDK's language, with a description: <Titles/><Descriptions/><SubArea/>. The spec gives it no label, so the title stays and the Titles and Descriptions+ // children keep the slots ahead of the nodes the spec models — the sitemap schema puts them before the SubAreas.const groupBag = { a: [['Id', 'group_0_0']], c: [{ i: 0, node: { n: 'Titles', a: [], c: [{ n: 'Title', a: [['LCID', '1033'], ['Title', 'Main']] }] } },{ i: 1, node: { n: 'Descriptions', a: [], c: [{ n: 'Description', a: [['LCID', '1033'], ['Description', 'D']] }] } },@@ -340,13 +339,14 @@ test('removing a node\u2019s last title keeps its other children ahead of the noconst live = tree([{ id: 'area_0', title: 'M', bag: bag('area_0'), groups: [{ id: 'group_0_0', title: 'Main', bag: groupBag, subAreas: [entitySub('s', 'new_x', 'X', bag('s'))] }] }]);const desired = tree([{ id: 'area_0', title: 'M', groups: [{ id: 'group_0_0', title: undefined, subAreas: [entitySub('sub_0_0_0', 'new_x', 'X')] }] }]);const group = adoptLiveSitemap(desired, live).siteMap.areas[0].groups[0];- assert.deepStrictEqual(group.bag.c.map((e) => [e.i, e.node.n]), [[0, 'Descriptions']]);+ assert.strictEqual(group.title, 'Main');+ assert.deepStrictEqual(group.bag.c.map((e) => [e.i, e.node.n]), [[0, 'Titles'], [1, 'Descriptions']]);assert.deepStrictEqual(groupBag.c.map((e) => e.i), [0, 1], 'the live bag is not touched');- // A title in another language keeps the wrapper, and every index with it.+ // A title in another language is beside it, and is not the spec's to touch either.groupBag.c[0].node.c.push({ n: 'Title', a: [['LCID', '1036'], ['Title', 'Principal']] });const kept = adoptLiveSitemap(desired, live).siteMap.areas[0].groups[0];assert.deepStrictEqual(kept.bag.c.map((e) => [e.i, e.node.n]), [[0, 'Titles'], [1, 'Descriptions']]);- assert.deepStrictEqual(kept.bag.c[0].node.c.map((t) => t.a[0][1]), ['1036']);+ assert.deepStrictEqual(kept.bag.c[0].node.c.map((t) => t.a[0][1]), ['1033', '1036']);});test('nothing live (a first write, or an unreadable copy) leaves the desired tree as it is', () => {diff --git a/plugins/model-apps/scripts/tests/table-columns-in-create.test.js b/plugins/model-apps/scripts/tests/table-columns-in-create.test.jsindex 7742b1951..472948913 100644--- a/plugins/model-apps/scripts/tests/table-columns-in-create.test.js+++ b/plugins/model-apps/scripts/tests/table-columns-in-create.test.js@@ -134,6 +134,9 @@ function fakeDataverse({tableReadBack = null, // (table) => response | undefined; overrides the read the SDK makes of a table it just createdlookupLag = 0, // how many reads of a new table BY NAME answer 404 before it shows (the metadata-read lag)keepsAskedLength = false, // the environment that keeps the length asked of a plain text primary column in a one-attribute create+ keepsAskedRequired = false, // the environment that keeps the required level asked of a plain text primary column (the one measured stores it None whatever is sent)+ levelRead = null, // (n) => response | undefined; overrides the typed read of one column's RequiredLevel (the SDK's check of a primary column's level)+ columnListRead = null, // (n) => response | undefined; overrides the read of all of a table's columns with their RequiredLevel (the build's read of what an existing table holds)lengthRead = null, // (n) => response | undefined; overrides the typed read of a text column's MaxLengthidentityRead = null, // (n) => response | undefined; overrides the read of which table answers to a name (its MetadataId and primary name column)updateFails = null, // (body) => response | falsy, for the PUT of a typed column; a falsy answer lets it through@@ -146,6 +149,8 @@ function fakeDataverse({const optionSets = new Map();let attributeReadCount = 0;let lengthReadCount = 0;+ let levelReadCount = 0;+ let columnListReadCount = 0;let identityReadCount = 0;const reply = (status, body, headers = {}) => ({ status, headers, body });const refuse = (path, response) => { refusals.push({ path, message: response.body && response.body.error && response.body.error.message }); return response; };@@ -211,6 +216,9 @@ function fakeDataverse({return override || (t ? reply(200, { value: rows }) : reply(404, { error: { message: 'no such table' } }));}if ((m = /^\/EntityDefinitions\(LogicalName='([^']+)'\)\/Attributes\?\$select=LogicalName,RequiredLevel$/.exec(p))) {+ columnListReadCount += 1;+ const override = columnListRead && columnListRead(columnListReadCount);+ if (override) return override;const t = tables.get(m[1]);return t ? reply(200, { value: [...t.columns.values()].map((c) => ({ LogicalName: c.row.LogicalName, RequiredLevel: c.body.RequiredLevel })) }) : reply(404, { error: { message: 'no such table' } });}@@ -225,6 +233,16 @@ function fakeDataverse({if (!column) return reply(404, { error: { message: `no table or column ${m[1]} / ${m[2]}` } });return reply(200, { MaxLength: column.row.LogicalName === t.primaryName ? t.primaryLength : column.body.MaxLength, MetadataId: column.row.MetadataId });}+ // The read of ONE column's requirement level, by names: the SDK's check, after a create that asked for a primary column to be required, of+ // the level the platform kept (createTable, `primaryColumnRequired`). It selects RequiredLevel and nothing else.+ if ((m = /^\/EntityDefinitions\(LogicalName='([^']+)'\)\/Attributes\(LogicalName='([^']+)'\)\?\$select=RequiredLevel$/.exec(p))) {+ levelReadCount += 1;+ const override = levelRead && levelRead(levelReadCount);+ if (override) return override;+ const t = tables.get(m[1]);+ const column = t && t.columns.get(m[2]);+ return column ? reply(200, { RequiredLevel: column.body.RequiredLevel, MetadataId: column.row.MetadataId }) : reply(404, { error: { message: `no column ${m[2]}` } });+ }// The two reads of the SDK's updateColumn: the column's id and type by name, then its whole typed definition by id.if ((m = /^\/EntityDefinitions\(LogicalName='([^']+)'\)\/Attributes\(LogicalName='([^']+)'\)\?\$select=MetadataId,AttributeType$/.exec(p))) {const t = tables.get(m[1]);@@ -266,7 +284,12 @@ function fakeDataverse({const collision = firstTaken(table, body.Attributes);if (collision) return refuse(p, duplicateAttribute(collision, logical));tables.set(logical, table);- addColumn(table, body.Attributes[0]);+ // The requirement level of the primary name column in a create that carries only that column (measured on Dataverse 9.2.26101,+ // AB#6770007): an auto-numbered column keeps the level the create sends, a plain text one is stored `None` whatever is sent,+ // and a later update (a PUT) sets it.+ const primary = clone(body.Attributes[0]);+ if (!primary.AutoNumberFormat && !keepsAskedRequired) primary.RequiredLevel = { ...primary.RequiredLevel, Value: 'None' };+ addColumn(table, primary);if (createCommitsThenFails) return refuse(p, createCommitsThenFails(body));return created(`EntityDefinitions(${table.id})`);}@@ -333,6 +356,8 @@ function fakeDataverse({const t = tableAt(m[1]);const column = t && columnAt(t, m[2]);if (!column) return reply(404, { error: { message: `no table or column ${m[1]} / ${m[2]}` } });+ // The PUT replaces the definition, level included: what the SDK read is what it writes back, with the one change it was asked for.+ if (body.RequiredLevel !== undefined) column.body = { ...column.body, RequiredLevel: clone(body.RequiredLevel) };if (column.row.LogicalName === t.primaryName) t.primaryLength = body.MaxLength;else column.body = { ...column.body, MaxLength: body.MaxLength };return reply(204, null);@@ -384,7 +409,7 @@ function fakeDataverse({return reply(200, changeSetAnswer(operations.map((op) => ({ contentId: op.contentId, status: 204 }))));};}- return { httpClient, log, refusals, tables, attributeReadCount: () => attributeReadCount, lengthReadCount: () => lengthReadCount, identityReadCount: () => identityReadCount };+ return { httpClient, log, refusals, tables, attributeReadCount: () => attributeReadCount, lengthReadCount: () => lengthReadCount, identityReadCount: () => identityReadCount, levelReadCount: () => levelReadCount };}// What another maker does while the build waits to retry: deletes a table and makes it again. The same logical names then answer for a@@ -1347,6 +1372,231 @@ test('TABLE_METADATA_NOT_VISIBLE out of a create whose name column is auto-numbeassert.ok(longest.error instanceof BuildHalt, 'the build still stops');});+// --- the primary name column's requirement level on a new table (AB#6770007) -------------------------------------------------------+// The table's create asks for it (`primaryColumnRequired`). Measured on Dataverse 9.2.26101: an auto-numbered name column keeps the level the+// create sends, a plain text one is stored not required whatever is sent, and an update (a PUT) sets it. The real SDK reads the level back,+// updates it where it differs, reads it again, and answers it; the build says "applied on create" only when it does — and when it cannot, the+// table exists, the build stops once, and the re-run finds the table and sets the level as it does for any existing column.+const requiredName = (extra = {}) => ({ schemaName: 'new_name', displayName: 'Name', required: true, ...extra });+const levelOf = (dv, logical = 'new_ticket', column = 'new_name') => dv.tables.get(logical).columns.get(column).body.RequiredLevel.Value;+const levelReads = (run) => gets(run).filter((r) => /\/Attributes\(LogicalName='[^']+'\)\?\$select=RequiredLevel$/.test(r.path));+const requiredSteps = (events) => events.filter((e) => e.status !== 'start' && /^required /.test(e.label)).map((e) => `${e.status}: ${e.label}`);++test('a required auto-numbered name column keeps the level the create sends: the SDK reads it once, updates nothing, and the build reports it applied on create', async () => {+ const run = await provisionOver(oneTable([], requiredName({ autoNumberFormat: 'WO-{SEQNUM:5}' })));+ assert.strictEqual(tablePosts(run)[0].body.Attributes[0].RequiredLevel.Value, 'ApplicationRequired', 'the level is in the create');+ assert.strictEqual(levelOf(run.dv), 'ApplicationRequired');+ assert.strictEqual(levelReads(run).length, 1, 'read once, to confirm it');+ assert.deepStrictEqual(puts(run), [], 'and nothing is updated');+ assert.deepStrictEqual(requiredSteps(run.events), ['skip: required new_ticket.new_name (applied on create)']);+ assert.deepStrictEqual(run.warnings, []);+});++test('a required plain text name column is stored not required by the create, so the SDK sets the level with one update — and the build reports it applied on create', async () => {+ const run = await provisionOver(oneTable([], requiredName()));+ assert.strictEqual(tablePosts(run)[0].body.Attributes[0].RequiredLevel.Value, 'ApplicationRequired', 'the level is asked in the create');+ assert.strictEqual(puts(run).length, 1, 'one update');+ assert.strictEqual(puts(run)[0].body.RequiredLevel.Value, 'ApplicationRequired');+ assert.strictEqual(puts(run)[0].headers['MSCRM.MergeLabels'], 'true', 'which merges the labels already stored');+ assert.strictEqual(levelOf(run.dv), 'ApplicationRequired', 'what the platform holds');+ assert.strictEqual(levelReads(run).length, 2, 'the level is read before the update and again after it');+ assert.deepStrictEqual(requiredSteps(run.events), ['skip: required new_ticket.new_name (applied on create)']);+ assert.deepStrictEqual(run.warnings, []);+ // `recommended` is a level too.+ const recommended = await provisionOver(oneTable([], requiredName({ required: 'recommended' })));+ assert.strictEqual(levelOf(recommended.dv), 'Recommended');+ assert.deepStrictEqual(requiredSteps(recommended.events), ['skip: required new_ticket.new_name (applied on create)']);+});++test('an environment that keeps the level asked of a plain text name column is read once and updated not at all', async () => {+ const run = await provisionOver(oneTable([], requiredName()), { dataverse: { keepsAskedRequired: true } });+ assert.strictEqual(levelOf(run.dv), 'ApplicationRequired');+ assert.strictEqual(levelReads(run).length, 1);+ assert.deepStrictEqual(puts(run), []);+ assert.deepStrictEqual(requiredSteps(run.events), ['skip: required new_ticket.new_name (applied on create)']);+});++test('a name column without an explicit required is created as ever — no level asked, none read, none updated — and an explicit required:false sends None and reads nothing back', async () => {+ const omitted = await provisionOver(oneTable([]));+ assert.strictEqual(tablePosts(omitted)[0].body.Attributes[0].RequiredLevel.Value, 'None');+ assert.deepStrictEqual(levelReads(omitted), []);+ assert.deepStrictEqual(puts(omitted), []);+ assert.deepStrictEqual(requiredSteps(omitted.events), []);+ const off = await provisionOver(oneTable([], requiredName({ required: false })));+ assert.deepStrictEqual(tablePosts(off).map((r) => r.body), tablePosts(omitted).map((r) => r.body), 'the same request: None is what the create always sent');+ assert.deepStrictEqual(levelReads(off), [], 'there is nothing to confirm');+ assert.deepStrictEqual(puts(off), []);+ assert.deepStrictEqual(requiredSteps(off.events), ['skip: required new_ticket.new_name (applied on create)']);+});++test('the level and the length asked of a plain text name column are both set, one update each, and the second does not undo the first', async () => {+ const run = await provisionOver(oneTable([], requiredName({ maxLength: 120 })));+ assert.strictEqual(puts(run).length, 2, 'the SDK\'s update of the level, then the build\'s update of the length');+ assert.strictEqual(puts(run)[0].body.RequiredLevel.Value, 'ApplicationRequired');+ assert.strictEqual(puts(run)[1].body.MaxLength, 120);+ assert.strictEqual(puts(run)[1].body.RequiredLevel.Value, 'ApplicationRequired', 'the length update is written from a read that already holds the level');+ assert.strictEqual(run.dv.tables.get('new_ticket').primaryLength, 120);+ assert.strictEqual(levelOf(run.dv), 'ApplicationRequired');+ assert.deepStrictEqual(run.warnings, []);+});++test('a name column level the platform will not take: the SDK refuses with PRIMARY_COLUMN_REQUIRED_NOT_APPLIED, the build stops once with the table made, and the re-run finds the table and sets the level — and a run after that changes nothing', async () => {+ const refuse = () => ({ status: 400, headers: {}, body: { error: { message: 'The attribute cannot be changed right now' } } });+ const spec = oneTable([textColumn('new_a')], requiredName());+ const run = await provisionOver(spec, { dataverse: { updateFails: refuse }, capture: true });+ assert.ok(run.error instanceof BuildHalt && run.error.code === 'PRIMARY_COLUMN_REQUIRED_NOT_APPLIED' && run.error.recoverable === true, `the halt carries the SDK's code: ${run.error && run.error.message}`);+ assert.match(run.error.message, /WAS CREATED/);+ assert.match(run.error.message, /Run the build again: it finds the table, does not create it again/);+ assert.strictEqual(tablePosts(run).length, 1, 'the table was created once');+ assert.strictEqual(levelOf(run.dv), 'None', 'it exists, with a name column that is not required');+ assert.deepStrictEqual(columnPosts(run).concat(batchPosts(run)), [], 'no column is created beside it');+ assert.strictEqual(run.warnings.length, 1);+ assert.match(run.warnings[0], /^table new_ticket was created, but the required level \(ApplicationRequired\) of its primary name column new_name could not be confirmed, so the build stops here — the table exists: run the build again, which finds it, does not create it again, and sets that level on the column/);++ // The re-run, against a platform that takes the update: the table is found, not created, and its level is reconciled like an existing column's.+ const run2 = fakeDataverse();+ run2.tables.set('new_ticket', run.dv.tables.get('new_ticket'));+ const again = async (dv) => {+ const sdk = await realSdk(dv.httpClient);+ const events = [];+ const warnings = [];+ await provisionDataModel({ sdk, provision: sdk, runner: makeRunner({ emit: (e) => events.push(e), total: 99 }), spec, apply: true, preResolvedLanguageCode: 1033, provisionedLanguages: async () => [1033], sleep: async () => {}, warn: (m) => warnings.push(m) });+ return { events, warnings };+ };+ const second = await again(run2);+ assert.strictEqual(run2.log.filter((r) => r.method === 'POST' && r.path === '/EntityDefinitions').length, 0, 'the table is not created again');+ assert.strictEqual(levelOf(run2), 'ApplicationRequired');+ assert.deepStrictEqual(requiredSteps(second.events), ['ok: required new_ticket.new_name -> ApplicationRequired']);+ assert.deepStrictEqual(second.warnings, []);+ assert.deepStrictEqual(second.events.filter((e) => e.status === 'ok').map((e) => e.label).filter((l) => /^column /.test(l)), ['column new_ticket.new_a (Text)'], 'and the column the first run never reached is created');++ // A third run has nothing left to do for the level.+ const putsBefore = run2.log.filter((r) => r.method === 'PUT').length;+ const third = await again(run2);+ assert.strictEqual(run2.log.filter((r) => r.method === 'PUT').length, putsBefore, 'no update');+ assert.deepStrictEqual(requiredSteps(third.events), ['skip: required new_ticket.new_name (already ApplicationRequired)']);+});++test('a name column level the SDK cannot read back is not taken for the one asked: PRIMARY_COLUMN_REQUIRED_NOT_APPLIED, the table is made once and not made again', async () => {+ const unreadable = () => ({ status: 200, headers: {}, body: {} });+ const run = await provisionOver(oneTable([], requiredName()), { dataverse: { levelRead: unreadable }, capture: true });+ assert.ok(run.error instanceof BuildHalt && run.error.code === 'PRIMARY_COLUMN_REQUIRED_NOT_APPLIED', run.error && run.error.message);+ assert.strictEqual(tablePosts(run).length, 1);+ assert.strictEqual(run.warnings.length, 1);+ // The new table's read-back failing is the same refusal when a level was asked: the table exists, and the level was neither applied nor checked.+ const down = await provisionOver(oneTable([], requiredName()), { dataverse: { tableReadBack: () => ({ status: 500, headers: {}, body: { error: { message: 'An unexpected error occurred.' } } }) }, capture: true });+ assert.ok(down.error instanceof BuildHalt && down.error.code === 'PRIMARY_COLUMN_REQUIRED_NOT_APPLIED', down.error && down.error.message);+ assert.match(down.error.message, /was NOT applied or checked|reading it back failed/);+ assert.strictEqual(tablePosts(down).length, 1, 'the create is not repeated');+});++test('a spec that asks for a required name column and a length gets one warning that names both when the level cannot be confirmed on an environment that ignores the length', async () => {+ const refuse = () => ({ status: 400, headers: {}, body: { error: { message: 'no' } } });+ const run = await provisionOver(oneTable([], requiredName({ maxLength: 120 })), { dataverse: { updateFails: refuse }, capture: true });+ assert.ok(run.error instanceof BuildHalt && run.error.code === 'PRIMARY_COLUMN_REQUIRED_NOT_APPLIED');+ assert.strictEqual(run.warnings.length, 1);+ assert.match(run.warnings[0], /sets that level on the column; the spec also asks for a name column length of 120, which may not have been applied either/);+ assert.strictEqual(run.dv.tables.get('new_ticket').primaryLength, 850, 'and it was not: a re-run leaves an existing table\'s name column length as it is');+});++test('a table that exists and whose name column states no required level is left as it is: nothing written, nothing narrated about the level', async () => {+ const first = await provisionOver(oneTable([]));+ const again = fakeDataverse();+ again.tables.set('new_ticket', first.dv.tables.get('new_ticket'));+ const sdk = await realSdk(again.httpClient);+ const events = [];+ await provisionDataModel({ sdk, provision: sdk, runner: makeRunner({ emit: (e) => events.push(e), total: 99 }), spec: oneTable([]), apply: true, preResolvedLanguageCode: 1033, provisionedLanguages: async () => [1033], sleep: async () => {}, warn: () => {} });+ assert.deepStrictEqual(again.log.filter((r) => r.method !== 'GET'), [], 'no write of any kind');+ assert.deepStrictEqual(requiredSteps(events), []);+ assert.strictEqual(levelOf(again), 'None');+});++// An explicit required:false asks the create for None, and the SDK has nothing to read back for it, so a build that SAW the create succeed has nothing to+// add (the tests above). A table it did not see made shows nothing about its name column's level, None included: the column may hold Business Required, set+// by a maker or left by an earlier create — so the step is the same failed, warned one a level above None gets, and the re-run sets it.+// A table that is already there, made by an earlier run whose name column was asked required, in a stub of its own (so the run under test has a log of its own).+async function existingTicket(dataverse = {}) {+ const earlier = await provisionOver(oneTable([], requiredName()));+ const dv = fakeDataverse(dataverse);+ dv.tables.set('new_ticket', earlier.dv.tables.get('new_ticket'));+ return dv;+}+async function buildOn(dv, spec) {+ const sdk = await realSdk(dv.httpClient);+ const events = [];+ const warnings = [];+ const error = await provisionDataModel({ sdk, provision: sdk, runner: makeRunner({ emit: (e) => events.push(e), total: 99 }), spec, apply: true, preResolvedLanguageCode: 1033, provisionedLanguages: async () => [1033], sleep: async () => {}, warn: (m) => warnings.push(m) })+ .then(() => null, (err) => err);+ return { events, warnings, error };+}++test('a table found after its create (the answer was lost) is not reported as having required:false applied either: nothing is written, and the re-run sets the level', async () => {+ const dv = await existingTicket();+ dv.tables.get('new_ticket').lagReads = 1; // the look for the table before the create does not see it yet, so the create is tried and refused+ const spec = oneTable([], requiredName({ required: false }));+ const first = await buildOn(dv, spec);+ assert.strictEqual(first.error, null);+ assert.strictEqual(tablePosts({ dv }).length, 1, 'the create was tried, once');+ assert.deepStrictEqual(requiredSteps(first.events), ['error: required new_ticket.new_name -> None'], 'nothing shows this build made the table, so nothing is "applied on create"');+ assert.deepStrictEqual(first.warnings, ['could not confirm the required level of new_ticket.new_name (None) — a re-run sets it, and the rest of the build continues: the table was found after its create, so nothing shows that the level was applied']);+ assert.deepStrictEqual(dv.log.filter((r) => r.method === 'PUT'), [], 'no update on a level that is not known');+ assert.strictEqual(levelOf(dv), 'ApplicationRequired', 'the column holds what it held');++ // The re-run finds the table at once, reads its name column, and sets the level the spec says; the run after that has nothing left to do.+ const second = await buildOn(dv, spec);+ assert.strictEqual(second.error, null);+ assert.strictEqual(tablePosts({ dv }).length, 1, 'the table is not created again');+ assert.deepStrictEqual(requiredSteps(second.events), ['ok: required new_ticket.new_name -> None']);+ assert.deepStrictEqual(second.warnings, []);+ assert.strictEqual(levelOf(dv), 'None');+ const putsBefore = dv.log.filter((r) => r.method === 'PUT').length;+ assert.strictEqual(putsBefore, 1, 'one update, by the re-run');+ const third = await buildOn(dv, spec);+ assert.strictEqual(dv.log.filter((r) => r.method === 'PUT').length, putsBefore, 'no update');+ assert.deepStrictEqual(requiredSteps(third.events), ['skip: required new_ticket.new_name (already None)']);+});++test('a reused table whose columns could not be read is not reported as having required:false applied either: nothing is written, and the re-run sets the level', async () => {+ let down = true;+ const dv = await existingTicket({ columnListRead: () => (down ? { status: 503, headers: {}, body: { error: { message: 'metadata collection unavailable' } } } : undefined) });+ const spec = oneTable([], requiredName({ required: false }));+ const first = await buildOn(dv, spec);+ assert.strictEqual(first.error, null);+ assert.strictEqual(tablePosts({ dv }).length, 0, 'the table is found before the create, so no create is tried');+ assert.deepStrictEqual(requiredSteps(first.events), ['error: required new_ticket.new_name -> None'], 'nothing is "applied on create" on a table this build did not create');+ assert.strictEqual(first.warnings.length, 2);+ assert.match(first.warnings[0], /^could not read existing columns for new_ticket \(HTTP 503\)/);+ assert.strictEqual(first.warnings[1], 'could not confirm the required level of new_ticket.new_name (None) — a re-run sets it, and the rest of the build continues: the table exists but its columns could not be read, so its current level is unknown');+ assert.deepStrictEqual(dv.log.filter((r) => r.method !== 'GET'), [], 'no write of any kind on a level that is not known');+ assert.strictEqual(levelOf(dv), 'ApplicationRequired', 'the column holds what it held');++ down = false;+ const second = await buildOn(dv, spec);+ assert.strictEqual(second.error, null);+ assert.deepStrictEqual(requiredSteps(second.events), ['ok: required new_ticket.new_name -> None']);+ assert.deepStrictEqual(second.warnings, []);+ assert.strictEqual(levelOf(dv), 'None');+});++test('through the plugin\'s own HTTP client — which has put() — a required plain text name column is made required, and without a put() nothing is created at all', async () => {+ const dv = fakeDataverse();+ const { httpClient, sent } = throughAzHttpClient(dv);+ assert.strictEqual(typeof httpClient.put, 'function', 'the client can send the update the SDK needs');+ const sdk = await realSdk(httpClient);+ const events = [];+ await provisionDataModel({ sdk, provision: sdk, runner: makeRunner({ emit: (e) => events.push(e), total: 99 }), spec: oneTable([], requiredName()), apply: true, preResolvedLanguageCode: 1033, provisionedLanguages: async () => [1033], sleep: async () => {}, warn: () => {} });+ assert.strictEqual(levelOf(dv), 'ApplicationRequired');+ assert.deepStrictEqual(sent.filter((s) => s.method === 'PUT').map((s) => JSON.parse(s.body).RequiredLevel.Value), ['ApplicationRequired']);+ assert.deepStrictEqual(requiredSteps(events), ['skip: required new_ticket.new_name (applied on create)']);++ // A client without put() cannot finish what the create leaves undone for a plain text name column, so the SDK refuses BEFORE it creates the table.+ const bare = fakeDataverse();+ delete bare.httpClient.put;+ const bareSdk = await realSdk(bare.httpClient);+ await assert.rejects(provisionDataModel({ sdk: bareSdk, provision: bareSdk, runner: makeRunner({ emit: () => {}, total: 99 }), spec: oneTable([], requiredName()), apply: true, preResolvedLanguageCode: 1033, provisionedLanguages: async () => [1033], sleep: async () => {}, warn: () => {} }), (err) => err instanceof BuildHalt && /needs an HttpClient that implements put\(\)/.test(err.message));+ assert.deepStrictEqual(bare.log.filter((r) => r.method === 'POST'), [], 'no table was created');+});+// The order of a new table's steps is the previous release's — the table, quick create, then the columns: the ordinary ones together// in one change set, then those that take their own request, one by one in spec order. The name column's length, which the previous// release never set, is the one step added to that order, and it comes LAST, after every labelled create of the phase (see the@@ -3476,4 +3726,71 @@ test('where the read of the column that pays a debt fails, nothing is written anassert.deepStrictEqual([...run.dv.tables.get('new_ticket').keys.keys()], ['new_namekey']);});+// --- an AutoNumber column needs a format: what the SDK does, and what the spec gate keeps the build from -------------------------+// The SDK refuses to create an `autonumber` column without a format — before any request — where the SDK it replaced created a plain text column.+// validateAppSpec and the provision-entities input gate refuse such a spec before anything is written (column-autonumber-gate.test.js); these tests+// pin the SDK behaviour that makes the rule necessary, so a bundle that changes it is noticed, and what the build does with a spec that got past the gate.++const autoNumberColumn = (extra = {}) => ({ schemaName: 'new_ref', displayName: 'Reference', type: 'AutoNumber', ...extra });++test('the SDK refuses to create an autonumber column that has no format — before any request, one column or a change set — and still creates one that has', async () => {+ for (const format of [undefined, null, '', ' ']) {+ const dv = fakeDataverse();+ const sdk = await realSdk(dv.httpClient);+ const options = { schemaName: 'new_ref', displayName: 'Reference', type: 'autonumber', languageCode: 1033, ...(format === undefined ? {} : { autoNumberFormat: format }) };+ for (const create of [() => sdk.createColumn('new_ticket', options), () => sdk.createColumns('new_ticket', [options])]) {+ await assert.rejects(create, (err) => err.code === 'INVALID_ARGUMENT' && /an 'autonumber' column needs an 'autoNumberFormat'/.test(err.message) && /'new_ref' has none/.test(err.message), `${JSON.stringify(format)}`);+ }+ assert.deepStrictEqual(dv.log, [], `${JSON.stringify(format)}: nothing was sent`);+ }+ // A format that is not a string never gets as far as that message, but is refused before any request all the same.+ for (const format of [5, {}, true, ['C-{SEQNUM:5}']]) {+ const dv = fakeDataverse();+ const sdk = await realSdk(dv.httpClient);+ await assert.rejects(() => sdk.createColumn('new_ticket', { schemaName: 'new_ref', displayName: 'Reference', type: 'autonumber', languageCode: 1033, autoNumberFormat: format }), `${JSON.stringify(format)}`);+ assert.deepStrictEqual(dv.log, [], `${JSON.stringify(format)}: nothing was sent`);+ }+ // With a format the column is created, and the format is in the request.+ const run = await provisionOver(oneTable([autoNumberColumn({ autoNumberFormat: 'C-{SEQNUM:5}' })]));+ assert.strictEqual(inlineNames(run).includes('new_ref'), true);+ assert.strictEqual(batchColumns(run).find((a) => a.SchemaName === 'new_ref').AutoNumberFormat, 'C-{SEQNUM:5}');+});++test('a spec that got past the gate with an AutoNumber column and no format stops the build at that column — the table is already made — whichever way the columns are created', async () => {+ for (const inlineColumns of [true, false]) {+ const run = await provisionOver(oneTable([textColumn('new_a'), autoNumberColumn(), textColumn('new_b')]), { capture: true, inlineColumns });+ assert.ok(run.error instanceof BuildHalt, `inlineColumns ${inlineColumns}: ${run.error && run.error.message}`);+ assert.match(run.error.message, /an 'autonumber' column needs an 'autoNumberFormat'/, 'the SDK\'s own words reach the author');+ assert.strictEqual(run.error.code, 'INVALID_ARGUMENT');+ assert.strictEqual(run.error.recoverable, false, 'a run again cannot get past it');+ assert.deepStrictEqual(run.events.filter((e) => e.status !== 'start').map((e) => `${e.status}: ${e.label}`), ['ok: table new_ticket', 'ok: column new_ticket.new_a (Text)', 'error: column new_ticket.new_ref (AutoNumber)']);+ assert.strictEqual(tablePosts(run).length, 1, 'the table was created first');+ assert.deepStrictEqual([...run.dv.tables.get('new_ticket').columns.keys()].filter((name) => /^new_/.test(name)), ['new_name', 'new_a'], 'the column before it was made, the one after it was never reached, and no plain text column stands in for it');+ assert.strictEqual(run.dv.refusals.length, 0, 'the platform was never asked to create it');+ }+});++test('a rebuild that finds the AutoNumber column already there never reaches the SDK\'s refusal — the column is skipped and nothing is written for it', async () => {+ // The column an earlier release made from a spec with no format is a plain text column. The next build of that spec finds it by name and does not create it.+ const first = await provisionOver(oneTable([{ schemaName: 'new_ref', displayName: 'Reference', type: 'Text' }]));+ assert.strictEqual(first.dv.tables.get('new_ticket').columns.has('new_ref'), true);+ const again = fakeDataverse();+ again.tables.set('new_ticket', first.dv.tables.get('new_ticket'));+ const sdk = await realSdk(again.httpClient);+ const events = [];+ const warnings = [];+ await provisionDataModel({ sdk, provision: sdk, runner: makeRunner({ emit: (e) => events.push(e), total: 99 }), spec: oneTable([autoNumberColumn()]), apply: true, preResolvedLanguageCode: 1033, provisionedLanguages: async () => [1033], sleep: async () => {}, warn: (m) => warnings.push(m) });+ assert.deepStrictEqual(events.filter((e) => e.status === 'skip').map((e) => e.label), ['table new_ticket (exists — reuse)', 'column new_ticket.new_ref (exists)']);+ assert.deepStrictEqual(events.filter((e) => e.status === 'error'), []);+ assert.deepStrictEqual(again.log.filter((r) => r.method !== 'GET'), [], 'no write of any kind');+ assert.deepStrictEqual(warnings, []);+ // The same when the spec states a required level for it: the level is reconciled through updateColumn, which never carries a format.+ const stated = fakeDataverse();+ stated.tables.set('new_ticket', first.dv.tables.get('new_ticket'));+ const statedSdk = await realSdk(stated.httpClient);+ await provisionDataModel({ sdk: statedSdk, provision: statedSdk, runner: makeRunner({ emit: () => {}, total: 99 }), spec: oneTable([autoNumberColumn({ required: true })]), apply: true, preResolvedLanguageCode: 1033, provisionedLanguages: async () => [1033], sleep: async () => {}, warn: () => {} });+ assert.deepStrictEqual(stated.log.filter((r) => r.method === 'POST'), [], 'nothing is created');+ for (const put of stated.log.filter((r) => r.method === 'PUT')) assert.ok(!('AutoNumberFormat' in put.body), 'an update of the column carries no format');+});+diff --git a/plugins/model-apps/scripts/tests/teardown-row-summary-lookup.test.js b/plugins/model-apps/scripts/tests/teardown-row-summary-lookup.test.jsnew file mode 100644index 000000000..4c053fb81--- /dev/null+++ b/plugins/model-apps/scripts/tests/teardown-row-summary-lookup.test.js@@ -0,0 +1,231 @@+'use strict';+// Teardown's row-summary step says what it found. The SDK's `removeRowSummary` answers nothing whether it removed a row summary or found none to remove, and the step took+// "the call did not throw" for "one was deleted": a table with no row summary was reported `✓ row summary <table> (1 deleted)`, in the line and in the closing count. The step now+// looks first — with the request the SDK itself makes — and reports what that read found, like every other step. The step stays best-effort, as it always was (a failure of+// the lookup or of the removal fails nothing), but what it could not do is said on its line instead of being counted as a deletion.+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 { runTeardown, KIND_HANDLERS } = require('../lib/sdk-teardown.js');+const { teardownModelApp: engineTeardownModelApp } = require('../teardown-model-app.js');+const { createMakerSdk, createNodeWorkspaceStorage } = require('../lib/maker-sdk.js');+const { createAzHttpClient } = require('../lib/sdk-http-client.js');++const ENV = 'https://contoso.crm.dynamics.com';+const teardownModelApp = (spec, opts, deps) => engineTeardownModelApp(spec, { env: ENV, ...opts }, deps);++// A spec whose one table gets a row summary: the build would make one for the Memo column, so teardown plans its removal.+const SPEC = {+ solution: { uniqueName: 'AiTest', publisherPrefix: 'new' },+ app: { name: 'AiApp' },+ entities: [{ schemaName: 'new_memo', displayName: 'Memo', primaryAttribute: { schemaName: 'new_name' }, columns: [{ schemaName: 'new_body', displayName: 'Body', type: 'Memo' }] }],+ relationships: [],+ ai: { summaries: { default: 'auto' } },+};+const SKILL_ROW = { aiskillconfigid: '11111111-1111-1111-1111-111111111111' };+const LOOKUP = "/aiskillconfigs?$select=aiskillconfigid&$filter=uniquename eq 'ais_RowSummary_new_memo'&$top=1";++// An SDK double whose Dataverse holds `rows` as the skill rows the lookup finds, and which records every call. `lookup` and `remove` replace the answer of the read and the+// removal (to answer another status, or to throw). `solution: false` is an environment without the spec's solution, so that nothing else of the plan is deleted either.+function summarySdk({ rows = [], lookup, remove, solution = true } = {}) {+ const calls = [];+ const sdk = {+ resolveArtifact: async (kind) => (kind === 'solution' && solution ? [{ id: 'sol-1', name: 'AiTest' }] : []),+ queryRecords: async () => [],+ dataverse: {+ get: async (url) => {+ calls.push({ method: 'get', path: url });+ return lookup ? lookup() : { status: 200, body: { value: rows } };+ },+ },+ removeRowSummary: async (args) => {+ calls.push({ method: 'removeRowSummary', ...args });+ if (remove) throw remove();+ },+ deleteTable: async () => { throw Object.assign(new Error('Could not find an entity with specified id'), { statusCode: 404 }); },+ deleteSolution: async () => {},+ };+ return { sdk, calls, removals: () => calls.filter((c) => c.method === 'removeRowSummary') };+}++const stepEvents = (events) => events.filter((e) => e.phase === 'ai-summaries' && e.status !== 'start');+async function run(sdk, spec = SPEC) {+ const events = [];+ const result = await runTeardown(spec, { apply: true }, { sdk, emit: (e) => events.push(e) });+ return { result, events: stepEvents(events) };+}++test('a table with no row summary is reported as not found, and nothing is sent to remove one', async () => {+ const { sdk, removals } = summarySdk({ rows: [] });+ const { result, events } = await run(sdk);+ assert.strictEqual(result.ok, true, JSON.stringify(result.errors));+ assert.deepStrictEqual(events.map((e) => [e.status, e.skip, e.label]), [['skip', 'not-found', 'row summary new_memo (not found)']]);+ assert.deepStrictEqual(removals(), [], 'there is nothing to remove');+ assert.strictEqual(result.deleted.aiSummary, undefined, 'and nothing deleted is counted');+ assert.ok(result.skipped.includes('row summary new_memo'));+});++test('a row summary the environment holds is removed once, and reported as deleted', async () => {+ const { sdk, removals } = summarySdk({ rows: [SKILL_ROW] });+ const { result, events } = await run(sdk);+ assert.strictEqual(result.ok, true, JSON.stringify(result.errors));+ assert.deepStrictEqual(events.map((e) => [e.status, e.label]), [['ok', 'row summary new_memo (1 deleted)']]);+ assert.deepStrictEqual(removals().map((c) => c.entityLogicalName), ['new_memo']);+ assert.deepStrictEqual(result.deleted.aiSummary, ['new_memo']);+});++test('the step looks for the skill row by the SDK\u2019s own request, before it removes anything', async () => {+ const { sdk, calls } = summarySdk({ rows: [SKILL_ROW] });+ await run(sdk);+ assert.deepStrictEqual(calls.filter((c) => c.method === 'get').map((c) => c.path), [LOOKUP]);+ assert.ok(calls.findIndex((c) => c.method === 'get') < calls.findIndex((c) => c.method === 'removeRowSummary'));+});++test('an environment that has no AI skill table holds no row summary: not found, not a failure', async () => {+ const { sdk, removals } = summarySdk({ lookup: () => ({ status: 404, body: { error: { message: "Resource not found for the segment 'aiskillconfigs'." } } }) });+ const { result, events } = await run(sdk);+ assert.strictEqual(result.ok, true, JSON.stringify(result.errors));+ assert.deepStrictEqual(events.map((e) => [e.status, e.skip, e.label]), [['skip', 'not-found', 'row summary new_memo (not found)']]);+ assert.deepStrictEqual(removals(), []);+});++test('a lookup that cannot be made leaves what is there unknown: said on the step, nothing removed, nothing failed', async () => {+ for (const [what, lookup, reason] of [+ ['a refusal', () => ({ status: 403, body: { error: { message: 'no read privilege' } } }), /^row summary new_memo \(not looked up \u2014 the lookup answered HTTP 403; a row summary left behind is reported by the table's delete\)$/],+ ['an answer that is no list', () => ({ status: 200, body: { value: 'busy' } }), /^row summary new_memo \(not looked up \u2014 the lookup's answer was no list; a row summary left behind is reported by the table's delete\)$/],+ ['a request that failed', () => { throw new Error('socket hang up'); }, /^row summary new_memo \(not looked up \u2014 socket hang up; a row summary left behind is reported by the table's delete\)$/],+ ]) {+ const { sdk, removals } = summarySdk({ lookup });+ const { result, events } = await run(sdk);+ assert.strictEqual(result.ok, true, `${what}: the step is best-effort, as it was: ${JSON.stringify(result.errors)}`);+ assert.deepStrictEqual(events.map((e) => [e.status, e.skip]), [['skip', 'kept']], what);+ assert.match(events[0].label, reason, what);+ assert.deepStrictEqual(removals(), [], `${what}: the SDK\u2019s own removal would have made the same request`);+ }+});++test('a removal that fails is not a deletion: said on the step in the SDK\u2019s words, kept like a step that left its artifact, and it still fails nothing', async () => {+ const words = "The row summary of 'new_memo' was removed, but its AI model '22222222-2222-2222-2222-222222222222' was not deleted (HTTP 400: refused).";+ const { sdk, removals } = summarySdk({ rows: [SKILL_ROW], remove: () => Object.assign(new Error(words), { code: 'ROW_SUMMARY_MODEL_NOT_DELETED' }) });+ const { result, events } = await run(sdk);+ assert.strictEqual(result.ok, true, 'best-effort: the table\u2019s delete that follows reports what still depends on the row summary');+ assert.deepStrictEqual(events.map((e) => [e.status, e.skip, e.label]), [['skip', 'kept', `row summary new_memo (kept \u2014 1 not removed: ${words})`]]);+ assert.strictEqual(removals().length, 1);+ assert.deepStrictEqual(result.deleted.aiSummary, []);+ assert.deepStrictEqual(result.skipped.filter((s) => /^row summary new_memo/.test(s)), [`row summary new_memo (1 not removed: ${words} \u2014 skipped)`]);+});++// The review's case: the table is kept (`existing: true`) and every other artifact is absent, so nothing at all is deleted. The closing line counts the events the engine emitted, so a wholly failed+// removal that was emitted as a step that deleted something put a deletion in the total that the step line and the JSON result both deny.+const RETAINED = { ...SPEC, entities: [{ ...SPEC.entities[0], existing: true }] };+const CLOSING_WHEN_NOTHING_WAS_DELETED = /\u2014 0 deleted, 5 not found, 0 failed, 2 kept \(7 steps\)$/;++test('a removal that wholly fails is not in the closing count of deleted steps: it is kept, with the table that is kept', async () => {+ const words = 'HTTP 403 from https://contoso.crm.dynamics.com/api/data/v9.0/aiskillconfigs(11111111-1111-1111-1111-111111111111): no delete privilege';+ const logs = [];+ const { sdk } = summarySdk({ rows: [SKILL_ROW], solution: false, remove: () => new Error(words) });+ const result = await teardownModelApp(RETAINED, { apply: true, allowDestructive: true }, { sdk, log: (m) => logs.push(m) });+ assert.strictEqual(result.ok, true, JSON.stringify(result.errors));+ assert.deepStrictEqual(result.deleted.aiSummary, [], 'the JSON result deletes nothing');+ assert.ok(logs.some((l) => l === ` [3/7] \u2298 row summary new_memo (kept \u2014 1 not removed: ${words})`), logs.join('\n'));+ assert.match(logs.find((l) => /teardown complete/.test(l)), CLOSING_WHEN_NOTHING_WAS_DELETED, logs.join('\n'));+});++test('a removal that succeeds is still counted as the deletion it is, beside the table that is kept', async () => {+ const logs = [];+ const { sdk } = summarySdk({ rows: [SKILL_ROW], solution: false });+ await teardownModelApp(RETAINED, { apply: true, allowDestructive: true }, { sdk, log: (m) => logs.push(m) });+ assert.match(logs.find((l) => /teardown complete/.test(l)), /\u2014 1 deleted, 5 not found, 0 failed, 1 kept \(7 steps\)$/, logs.join('\n'));+});++test('the printed step and the closing counts follow what was found', async () => {+ const tally = async (options) => {+ const logs = [];+ const { sdk } = summarySdk(options);+ const result = await teardownModelApp(SPEC, { apply: true, allowDestructive: true }, { sdk, log: (m) => logs.push(m) });+ assert.strictEqual(result.ok, true, JSON.stringify(result.errors));+ const closing = /\u2014 (\d+) deleted, (\d+) not found, 0 failed \((\d+) steps\)/.exec(logs.find((l) => /teardown complete/.test(l)));+ assert.ok(closing, logs.join('\n'));+ return { logs, deleted: Number(closing[1]), notFound: Number(closing[2]), steps: Number(closing[3]) };+ };+ const none = await tally({ rows: [] });+ const one = await tally({ rows: [SKILL_ROW] });+ assert.ok(none.logs.some((l) => /^ {2}\[\d+\/\d+\] \u2298 row summary new_memo \(not found\)$/.test(l)), none.logs.join('\n'));+ assert.ok(!none.logs.some((l) => /row summary new_memo \(1 deleted\)/.test(l)));+ assert.ok(one.logs.some((l) => /^ {2}\[\d+\/\d+\] \u2713 row summary new_memo \(1 deleted\)$/.test(l)), one.logs.join('\n'));+ // The same plan, so the one step that differs moves one count into the other: a summary nothing held is not a deletion.+ assert.strictEqual(none.steps, one.steps);+ assert.strictEqual(one.deleted - none.deleted, 1);+ assert.strictEqual(none.notFound - one.notFound, 1);+});++// --- the real SDK ----------------------------------------------------------------------------------------------------------------------------------------------++// `removeRowSummary` finds the row summary by its skill row — `GET /aiskillconfigs?…$filter=uniquename eq 'ais_RowSummary_<table>'` — and the step must look for the same row, or a+// row summary the SDK would remove is reported as not there and left to block the table's delete. The unique name is a constant inside the bundle, so the one the step uses is held to what+// the real bundle asks for, over a fake Dataverse that answers by the filter.+function fakeSkillOrg({ rows = [], status = 200, deleteStatus = 204 } = {}) {+ const requests = [];+ const json = (statusCode, body) => ({ statusCode, headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });+ async function request({ url, method }) {+ const where = decodeURIComponent(new URL(url).pathname + new URL(url).search);+ requests.push({ method, path: where });+ if (method === 'GET' && /\/aiskillconfigs\?/.test(where)) return json(status, status === 200 ? { value: rows } : { error: { message: "Resource not found for the segment 'aiskillconfigs'." } });+ // The skill row's own delete, and the read the bundle makes to settle one that failed: the row is still there.+ if (method === 'DELETE' && /\/aiskillconfigs\(/.test(where)) return deleteStatus >= 400 ? json(deleteStatus, { error: { message: 'no delete privilege' } }) : { statusCode: deleteStatus, headers: {}, body: '' };+ if (method === 'GET' && /\/aiskillconfigs\(/.test(where)) return json(200, { aiskillconfigid: SKILL_ROW.aiskillconfigid });+ const table = /EntityDefinitions\(LogicalName='([^']+)'\)/.exec(where);+ if (method === 'GET' && table) return json(200, { LogicalName: table[1], EntitySetName: `${table[1]}s`, MetadataId: '55555555-5555-5555-5555-555555555555' });+ return method === 'GET' ? json(200, { value: [] }) : { statusCode: 204, headers: {}, body: '' };+ }+ const httpClient = createAzHttpClient(ENV, { getToken: () => 'token', request, sleep: async () => {} });+ return { httpClient, requests };+}+const dirs = [];+test.after(() => { for (const dir of dirs) fs.rmSync(dir, { recursive: true, force: true }); });+async function realSdk(org) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'teardown-summary-'));+ dirs.push(dir);+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: ENV, httpClient: org.httpClient });+ await sdk.initWorkspace();+ return sdk;+}+const skillFilters = (requests) => requests.map((r) => /\/aiskillconfigs\?.*\$filter=([^&]+)/.exec(r.path)).filter(Boolean).map((m) => m[1]);++test('REAL BUNDLE: the step\u2019s lookup asks for the unique name the bundle\u2019s own removal asks for', async () => {+ const bundleOrg = fakeSkillOrg();+ await (await realSdk(bundleOrg)).removeRowSummary({ entityLogicalName: 'new_memo' });+ const stepOrg = fakeSkillOrg();+ assert.deepStrictEqual(await KIND_HANDLERS.aiSummary.resolve(await realSdk(stepOrg), { entityLogicalName: 'new_memo' }), []);+ assert.deepStrictEqual(skillFilters(bundleOrg.requests), ["uniquename eq 'ais_RowSummary_new_memo'"]);+ assert.deepStrictEqual(skillFilters(stepOrg.requests), skillFilters(bundleOrg.requests));+ assert.strictEqual(stepOrg.requests.length, 1, 'one read, and nothing else is asked');+});++test('REAL BUNDLE: a skill row the environment holds is found, and one it does not hold is not', async () => {+ const found = await KIND_HANDLERS.aiSummary.resolve(await realSdk(fakeSkillOrg({ rows: [SKILL_ROW] })), { entityLogicalName: 'new_memo' });+ assert.deepStrictEqual(found, [{ id: 'new_memo', entityLogicalName: 'new_memo' }]);+ assert.deepStrictEqual(await KIND_HANDLERS.aiSummary.resolve(await realSdk(fakeSkillOrg({ rows: [] })), { entityLogicalName: 'new_memo' }), []);+});++test('REAL BUNDLE: an environment with no AI skill table is reported as not found through the whole teardown', async () => {+ const sdk = await realSdk(fakeSkillOrg({ status: 404 }));+ // No app and no solution in the plan: what the real SDK would be asked about them is not this test's.+ const { result, events } = await run(sdk, { entities: SPEC.entities, ai: SPEC.ai });+ assert.deepStrictEqual(events.map((e) => [e.status, e.label]), [['skip', 'row summary new_memo (not found)']], JSON.stringify(result.errors));+});++test('REAL BUNDLE: a skill row the caller may not delete is kept, with the platform\u2019s refusal, and the closing counts say that nothing was deleted', async () => {+ const org = fakeSkillOrg({ rows: [SKILL_ROW], deleteStatus: 403 });+ const logs = [];+ const result = await teardownModelApp(RETAINED, { apply: true, allowDestructive: true }, { sdk: await realSdk(org), log: (m) => logs.push(m) });+ assert.strictEqual(result.ok, true, `${JSON.stringify(result.errors)}\n${logs.join('\n')}`);+ assert.deepStrictEqual(result.deleted.aiSummary, []);+ const line = logs.find((l) => /row summary new_memo/.test(l));+ assert.match(line, /^ {2}\[3\/7\] \u2298 row summary new_memo \(kept \u2014 1 not removed: HTTP 403 from https:\/\/contoso\.crm\.dynamics\.com\/api\/data\/v9\.0\/aiskillconfigs\(11111111-1111-1111-1111-111111111111\): no delete privilege\)$/, line);+ assert.match(logs.find((l) => /teardown complete/.test(l)), CLOSING_WHEN_NOTHING_WAS_DELETED, logs.join('\n'));+ assert.deepStrictEqual(org.requests.filter((r) => r.method === 'DELETE').map((r) => r.path.replace(/^\/api\/data\/v9\.\d\//, '')), ['aiskillconfigs(11111111-1111-1111-1111-111111111111)'], 'the delete was sent once and its refusal was the answer');+});diff --git a/plugins/model-apps/scripts/tests/temp-workspace.test.js b/plugins/model-apps/scripts/tests/temp-workspace.test.jsindex 8961bfac5..76b0c9708 100644--- a/plugins/model-apps/scripts/tests/temp-workspace.test.js+++ b/plugins/model-apps/scripts/tests/temp-workspace.test.js@@ -9,7 +9,7 @@ const fs = require('node:fs');const os = require('node:os');const path = require('node:path');const {- PARENT_NAME, OWNER_FILE, REMOVING_SUFFIX, CURSOR_FILE, LENT_KEEP_MS, LIMITS, workspaceParent, makeTempWorkspace, sweepDeadWorkspaces, sweepWarning,+ PARENT_NAME, OWNER_FILE, REMOVING_SUFFIX, CURSOR_FILE, LENT_KEEP_MS, LIMITS, workspaceParent, makeTempWorkspace, sweepDeadWorkspaces, sweepWarning, pruneWorkspaceParents,} = require('../lib/temp-workspace.js');const { ownerStamp, isOwnerStamp } = require('../lib/process-owner.js');const { privateTempRoot, tempEnv, startTarget, deadPid, pause, waitUntil } = require('./helpers/kill-target-client.js');@@ -631,22 +631,155 @@ test('REAL PROCESSES: runs that make and remove workspaces while others sweepfor (const run of runs) assert.strictEqual((await run.exited).code, 0, `a run ended cleanly — none had its own removal fail: ${run.stderr()}`);});-test('when a process ends it removes the plugin\'s folder if nothing is left in it — and leaves it if a workspace was left', async (t) => {+test('when a process ends it removes the plugin\'s folder if nothing is left in it', async (t) => {const root = privateTempRoot(t);- const deps = { os: { tmpdir: () => root } };const clean = startTarget(t, ['workspace-exit', 'genpage-'], { env: tempEnv(root) });await clean.waitFor(/^done$/);await clean.exited;assert.deepStrictEqual(fs.readdirSync(root), [], 'a normal run leaves the temp folder as it found it');+});++// A cleanup of a caller's own — the one solution-settings.js registers with lib/exit-cleanup.js, which removes the workspace it LENT — runs after the maker's listener for the end of the process, so it asks for the same removal of+// the plugin's folder once the workspace is gone. The removal is the same one: a plain `rmdir`, which takes a folder only when it is empty.+test('pruneWorkspaceParents takes the plugin\'s folder when nothing is left in it, and only then — a workspace in it, lent or not, keeps it, whole', (t) => {+ const { deps } = tempRoot(t);+ const lent = makeTempWorkspace('solution-settings-', { ...deps, lent: true });+ const own = makeTempWorkspace('genpage-', deps);+ const parent = workspaceParent(deps);+ pruneWorkspaceParents();+ assert.deepStrictEqual(entriesOf(parent), [path.basename(lent), path.basename(own)].sort(), 'the folder holds two workspaces: it is not taken, and neither of them is');+ assert.ok(fs.existsSync(path.join(lent, OWNER_FILE)) && fs.existsSync(path.join(own, OWNER_FILE)), 'whole, and still recorded');+ fs.rmSync(own, { recursive: true, force: true });+ pruneWorkspaceParents();+ assert.deepStrictEqual(entriesOf(parent), [path.basename(lent)], 'one workspace left in it: the folder stays');+ fs.rmSync(lent, { recursive: true, force: true });+ pruneWorkspaceParents();+ assert.ok(!fs.existsSync(parent), 'nothing left in it: it is taken');+ assert.doesNotThrow(() => pruneWorkspaceParents(), 'and asking again, with the folder gone, is no failure');+});++// ── A run that is cut short ────────────────────────────────────────────────────────────────────────────────────────────────────────────────+// What ends a run in a way JavaScript can see — process.exit, and an error nothing catches — runs the `exit` event, and a run that ends so has usually not reached the `finally` that removes its workspace. The workspace and+// the plugin's folder it is in were left for the next run: its sweep takes the workspace, and the folder stays until some run ends with nothing in it. So the end of a run takes, besides the folder when it is empty, the+// workspaces the run itself made and did not lend (a run that lends one is not the one to say when the program it lent it to is done). A signal is not one of these ends: the default action of SIGINT and SIGTERM ends+// the process with no JavaScript run, and a listener, which would, replaces that default action — for every script that makes a workspace.+const ABORTS = [['process.exit(7)', 'exit', 7], ['an error nothing catches', 'throw', 1]];++for (const [what, how, status] of ABORTS) {+ test(`a run that ends by ${what} with its workspace still there takes the workspace and the plugin's folder with it, and ends with the status it would have had`, async (t) => {+ const root = privateTempRoot(t);+ const run = startTarget(t, ['workspace-abort', 'genpage-', how], { env: tempEnv(root) });+ const made = (await run.waitFor(/^workspace /)).slice('workspace '.length);+ assert.strictEqual(path.dirname(made), workspaceParent({ os: { tmpdir: () => root } }), 'the run made its workspace in the plugin\'s folder');+ const ended = await run.exited;+ assert.deepStrictEqual([ended.code, ended.signal], [status, null], 'the status is the one the run would have ended with');+ assert.deepStrictEqual(fs.readdirSync(root), [], 'the temp folder is as the run found it: the workspace is gone, and so is the plugin\'s folder');+ });++ test(`a run that removed its workspace before it ended by ${what} leaves nothing either, and ends with the same status`, async (t) => {+ const root = privateTempRoot(t);+ const run = startTarget(t, ['workspace-abort', 'genpage-', how, 'removed'], { env: tempEnv(root) });+ await run.waitFor(/^workspace /);+ const ended = await run.exited;+ assert.deepStrictEqual([ended.code, ended.signal], [status, null]);+ assert.deepStrictEqual(fs.readdirSync(root), []);+ });+}++test('a run that ends by process.exit or an error nothing catches takes only what is its own: while another run\'s workspace is in the plugin\'s folder, that workspace is whole and the folder stays', async (t) => {+ const root = privateTempRoot(t);+ const deps = { os: { tmpdir: () => root } };+ const other = startTarget(t, ['workspace', 'genpage-'], { env: tempEnv(root) });+ const theirs = (await other.waitFor(/^workspace /)).slice('workspace '.length);+ // Both ways out, and a run that ends by itself, at the same time.+ const runs = [...ABORTS.map(([what, how, status]) => ({ what, args: ['workspace-abort', 'genpage-', how], status })), { what: 'the end of its event loop', args: ['workspace-keep', 'genpage-'], status: 0 }]+ .map((run) => ({ ...run, target: startTarget(t, run.args, { env: tempEnv(root) }) }));+ const made = await Promise.all(runs.map(async (run) => (await run.target.waitFor(/^workspace /)).slice('workspace '.length)));+ const ended = await Promise.all(runs.map((run) => run.target.exited));+ runs.forEach((run, i) => {+ assert.strictEqual(ended[i].code, run.status, `${run.what}: the status`);+ assert.ok(!fs.existsSync(made[i]), `${run.what}: its own workspace is gone`);+ });+ assert.ok(fs.existsSync(path.join(theirs, 'page.tsx')) && isOwnerStamp(JSON.parse(fs.readFileSync(path.join(theirs, OWNER_FILE), 'utf8'))), 'the workspace of the run that is going is whole, and still recorded');+ assert.deepStrictEqual(fs.readdirSync(workspaceParent(deps)), [path.basename(theirs)], 'it is all the plugin\'s folder holds');+ // Once that run is gone too, a sweep takes its workspace — and not the folder, which the end of a run takes when it is empty.+ await other.kill();+ assert.deepStrictEqual(sweepDeadWorkspaces(deps).removed.map((r) => r.name), [path.basename(theirs)]);+ assert.ok(fs.existsSync(workspaceParent(deps)));+});++test('REAL PROCESSES: runs that are cut short while others make and remove workspaces take only what is their own — none finds its workspace gone or unrecorded, and every run ends with its status', async (t) => {+ const root = privateTempRoot(t);+ const deps = { os: { tmpdir: () => root } };+ const gate = path.join(root, 'go');+ const RUNS = 2;+ const ITERATIONS = 40;+ const loops = Array.from({ length: RUNS }, () => startTarget(t, ['workspace-loop', 'genpage-', String(ITERATIONS), '10', gate], { env: tempEnv(root) }));+ await Promise.all(loops.map((run) => run.waitFor(/^ready$/)));+ fs.writeFileSync(gate, '');+ // While they work, runs that are cut short come and go in the same folder: each makes a workspace and ends without removing it, so that its end removes it — beside the workspaces of the runs that are going, and+ // in the moments between theirs, when the folder is empty.+ const ends = [];+ for (let i = 0; i < 4; i += 1) {+ const [, how, status] = ABORTS[i % ABORTS.length];+ const run = startTarget(t, ['workspace-abort', 'genpage-', how], { env: tempEnv(root) });+ await run.waitFor(/^workspace /);+ ends.push({ expected: status, actual: (await run.exited).code });+ }+ const answers = await Promise.all(loops.map((run) => run.waitFor(/^loop-done \d+ \d+$/)));+ const lost = answers.reduce((sum, line) => sum + Number(line.split(' ')[1]), 0);+ assert.strictEqual(lost, 0, `no run found its own workspace gone, or unrecorded in the plugin's folder: ${answers.join(', ')}`);+ assert.deepStrictEqual(ends.map((e) => e.actual), ends.map((e) => e.expected), 'the runs that were cut short ended with the status they would have had');+ for (const run of loops) assert.strictEqual((await run.exited).code, 0, `a run that makes and removes workspaces ended cleanly: ${run.stderr()}`);+ assert.deepStrictEqual(fs.existsSync(workspaceParent(deps)) ? fs.readdirSync(workspaceParent(deps)) : [], [], 'and no workspace is left in the plugin\'s folder');+});++test('a workspace lent to another program is not taken when the run that lent it ends — the program may still be writing in it — and the plugin\'s folder stays with it', async (t) => {+ const root = privateTempRoot(t);+ const run = startTarget(t, ['workspace-abort', 'solution-settings-', 'exit', 'lent'], { env: tempEnv(root) });+ const lent = (await run.waitFor(/^workspace /)).slice('workspace '.length);+ assert.strictEqual((await run.exited).code, 7);+ assert.ok(fs.existsSync(path.join(lent, 'page.tsx')), 'the lent workspace is whole');+ assert.strictEqual(JSON.parse(fs.readFileSync(path.join(lent, OWNER_FILE), 'utf8')).lent, true, 'and still recorded as lent');+ assert.deepStrictEqual(fs.readdirSync(root), [path.basename(workspaceParent({ os: { tmpdir: () => root } }))]);+});+test('a run that ends without removing its workspace — its event loop empties, nothing calls process.exit — takes the workspace and the plugin\'s folder with it', async (t) => {+ const root = privateTempRoot(t);const careless = startTarget(t, ['workspace-keep', 'genpage-'], { env: tempEnv(root) });- const left = (await careless.waitFor(/^workspace /)).slice('workspace '.length);- await careless.exited;- assert.ok(fs.existsSync(path.join(left, 'page.tsx')), 'a workspace a run did not remove is left where it is');- assert.deepStrictEqual(fs.readdirSync(root), [path.basename(workspaceParent(deps))], 'in the plugin\'s folder');- // The run has ended — it is gone — so the next sweep takes its workspace, and not the folder.+ await careless.waitFor(/^workspace /);+ const ended = await careless.exited;+ assert.deepStrictEqual([ended.code, ended.signal], [0, null]);+ assert.deepStrictEqual(fs.readdirSync(root), []);+});++test('a plugin\'s folder that a run made, and then could make no workspace in, is removed when the run ends — the workspace goes in the temp folder as before', async (t) => {+ const root = privateTempRoot(t);+ const run = startTarget(t, ['workspace-refused', 'genpage-'], { env: tempEnv(root) });+ const plain = (await run.waitFor(/^workspace /)).slice('workspace '.length);+ assert.strictEqual(path.dirname(plain), root, 'the workspace is in the temp folder itself');+ await run.waitFor(/^done$/);+ assert.strictEqual((await run.exited).code, 0);+ assert.deepStrictEqual(fs.readdirSync(root), [], 'and the plugin\'s folder, made for the workspace that was refused, is not left behind');+});++test('the maker listens for no signal, so a signal ends a run as it always did', async (t) => {+ const root = privateTempRoot(t);+ const run = startTarget(t, ['workspace-listeners', 'genpage-'], { env: tempEnv(root) });+ const heard = JSON.parse((await run.waitFor(/^listeners /)).slice('listeners '.length));+ assert.deepStrictEqual(heard, { SIGINT: 0, SIGTERM: 0, SIGHUP: 0, SIGBREAK: 0 }, 'a listener replaces the default action of the signal, and has to put it back by hand');+ await run.exited;+});++test('POSIX: SIGTERM ends a run that holds a workspace BY the signal, as it ends a process with no listener — no JavaScript runs, so the workspace is left for the next run\'s sweep', onlyPosix, async (t) => {+ const root = privateTempRoot(t);+ const deps = { os: { tmpdir: () => root } };+ const run = startTarget(t, ['workspace', 'genpage-'], { env: tempEnv(root) });+ const left = (await run.waitFor(/^workspace /)).slice('workspace '.length);+ const ended = await run.signal('SIGTERM');+ assert.deepStrictEqual([ended.code, ended.signal], [null, 'SIGTERM'], 'ended by the signal, and not by an exit status');+ assert.ok(fs.existsSync(path.join(left, 'page.tsx')), 'the workspace is left where it is');assert.deepStrictEqual(sweepDeadWorkspaces(deps).removed.map((r) => r.name), [path.basename(left)]);- assert.ok(fs.existsSync(workspaceParent(deps)));});// ---------------------------------------------------------------------------------------------------------------------diff --git a/plugins/model-apps/scripts/tests/vendor-sdk-smoke.test.js b/plugins/model-apps/scripts/tests/vendor-sdk-smoke.test.jsindex 083f85aa9..c2eb312a6 100644--- a/plugins/model-apps/scripts/tests/vendor-sdk-smoke.test.js+++ b/plugins/model-apps/scripts/tests/vendor-sdk-smoke.test.js@@ -545,7 +545,8 @@ test('CONTRACT: queryRecords({ paginate:true }) THROWS on a malformed page inste// A well-formed OData collection page always carries `value` as an array (empty only on the last page).// A missing/null/non-array `value` — or a bare-string `value` that `for..of` would iterate char-by-char// — must fail LOUD (returning partial results silently under-counts, which is dangerous for the- // cross-app page scan and cascade-delete enumeration). The single-page (non-paginate) path stays lenient.+ // cross-app page scan and cascade-delete enumeration). Since the SDK's defect pass the single-page (non-paginate) path is+ // just as strict: an absent collection is not an empty one, so a 2xx answer without `value` is a ConnectionError there too.const meta = (url) => { const ln = (url.match(/LogicalName='([^']+)'/) || [])[1] || 'x'; return { status: 200, headers: {}, body: { MetadataId: '33333333-3333-3333-3333-333333333333', EntitySetName: `${ln}s`, LogicalName: ln } }; };// (a) malformed MID-pagination: page 1 is a valid page + nextLink, page 2 has value:null → THROW (not page-1-only).@@ -566,13 +567,15 @@ test('CONTRACT: queryRecords({ paginate:true }) THROWS on a malformed page inste};await assert.rejects(async () => (await sdkWith(strClient)).queryRecords('appmodule', { paginate: true }), /malformed page|value/i, 'a bare-string value throws (no char-row fabrication)');- // (c) the single-page (non-paginate) path is UNCHANGED — a missing value is leniently treated as empty.- const lenientClient = {- get: async (url) => { if (/EntityDefinitions\(LogicalName=/i.test(url)) return meta(url); return { status: 200, headers: {}, body: {} }; },+ // (c) the single-page (non-paginate) path refuses a missing `value` too — never an empty result. It used to read it as empty.+ const bodyOf = (body) => ({+ get: async (url) => { if (/EntityDefinitions\(LogicalName=/i.test(url)) return meta(url); return { status: 200, headers: {}, body }; },post: async () => ({ status: 204, headers: {}, body: {} }), patch: async () => ({ status: 204, headers: {}, body: {} }), delete: async () => ({ status: 204, headers: {}, body: {} }), put: async () => ({ status: 204, headers: {}, body: {} }),- };- const rows = await (await sdkWith(lenientClient)).queryRecords('appmodule', {});- assert.deepStrictEqual(rows, [], 'the non-paginate single-page path stays lenient (missing value → empty)');+ });+ await assert.rejects(async () => (await sdkWith(bodyOf({}))).queryRecords('appmodule', {}), (e) => e && e.code === 'CONNECTION_ERROR' && /malformed page/.test(e.message), 'a missing value is a ConnectionError, not an empty result');+ await assert.rejects(async () => (await sdkWith(bodyOf({ value: 'abc' }))).queryRecords('appmodule', {}), (e) => e && e.code === 'CONNECTION_ERROR' && /malformed page/.test(e.message), 'and so is a value that is not an array');+ // A well-formed EMPTY page is an empty result: the only absence there is.+ assert.deepStrictEqual(await (await sdkWith(bodyOf({ value: [] }))).queryRecords('appmodule', {}), [], 'a well-formed empty page is still an empty result');});test('CONTRACT: createGlobalOptionSet is idempotent by Name — reuses an existing set (no duplicate POST), fixing rebuild id-loss', async () => {diff --git a/plugins/model-apps/scripts/tests/verify-dashboard-custom-control.test.js b/plugins/model-apps/scripts/tests/verify-dashboard-custom-control.test.jsnew file mode 100644index 000000000..ba4e0ef54--- /dev/null+++ b/plugins/model-apps/scripts/tests/verify-dashboard-custom-control.test.js@@ -0,0 +1,127 @@+'use strict';+// REAL BUNDLE: what `--verify` says of a dashboard that holds a chart tile a custom control hosts.+//+// Verify holds every chart tile of a deployed dashboard to the table it shows: its chart and its view must belong to the tile's+// `TargetEntityType`, because the platform publishes a tile whose chart is another table's and nothing else would say so. That+// is a check of the tiles the BUILD makes from the spec. The SDK types a chart that a custom control hosts `chart`, as it does a+// native one (it used to type every custom-control tile as the Assistant, which verify skipped), so the check read such a tile as+// a native chart. A host that carries no native visualization made the dashboard fail — "its chart or view could not be+// resolved" — and with it `build --verify` of a build that had written nothing to the dashboard.+//+// The App Spec cannot express a custom control, so a download leaves the tile out and a rebuild never touches it; verify leaves+// it alone too, as it did before. A native chart tile is still held to its table, and the Assistant and any other custom control+// are skipped as they always were. The classification is the download's: lib/dashboard-tiles.js.+const test = require('node:test');+const assert = require('node:assert');+const { makeTempDir } = require('./helpers/temp-dirs.js');+const { createMakerSdk, createNodeWorkspaceStorage } = require('../vendor/cds-maker-sdk.cjs');+const { verifySpec } = require('../lib/verify-spec.js');+const { readerFor } = require('../verify-model-app.js');+const { createFakeDataverse } = require('./helpers/fake-dataverse.js');+const {+ nativeGrid, nativeChart, customGrid, customChart, assistantTile, otherCustomControl, customDescription, dashboardXml,+} = require('./helpers/dashboard-formxml.js');++const API = 'https://contoso.crm.dynamics.com/api/data/v9.0';+const DASHBOARD_ID = '33333333-3333-4333-8333-333333333333';+const OPEN_VIEW = '11111111-0000-4000-8000-0000000000a1';+const CHART_VIEW = '11111111-0000-4000-8000-0000000000a3';+const CHART = '22222222-0000-4000-8000-0000000000b1';+const OTHER_TABLE_CHART = '22222222-0000-4000-8000-0000000000b9';+const GRID_UNIQUE = 'cccccccc-0000-4000-8000-000000000001';+const CHART_UNIQUE = 'cccccccc-0000-4000-8000-000000000002';+const OTHER_UNIQUE = 'cccccccc-0000-4000-8000-000000000003';++// The charts and views the environment holds, each by the table it belongs to, whatever the dashboard says about them.+const ENVIRONMENT = {+ charts: { [CHART]: 'incident', [OTHER_TABLE_CHART]: 'account' },+ views: { [OPEN_VIEW]: 'incident', [CHART_VIEW]: 'incident' },+};++// `verifySpec` over the REAL SDK and the real reader seam (`readerFor`), against a fake environment that holds one dashboard+// (the spec pins it by its id, as a download writes it) and the charts and views above. The spec declares the native tile only.+async function verifying(formxml) {+ const fake = createFakeDataverse({ entities: { incident: {} } });+ const post = (set, body) => fake.httpClient.post(`${API}/${set}`, body);+ await post('systemforms', { formid: DASHBOARD_ID, name: 'Support board', description: '', type: 0, objecttypecode: 'none', formxml });+ for (const [id, table] of Object.entries(ENVIRONMENT.charts)) await post('savedqueryvisualizations', { savedqueryvisualizationid: id, name: `chart ${id}`, primaryentitytypecode: table });+ for (const [id, table] of Object.entries(ENVIRONMENT.views)) await post('savedqueries', { savedqueryid: id, name: `view ${id}`, returnedtypecode: table, querytype: 0 });+ const sdk = createMakerSdk({+ workspaceStorage: createNodeWorkspaceStorage(makeTempDir('verify-dashboard-')),+ instanceUrl: 'https://contoso.crm.dynamics.com',+ httpClient: fake.httpClient,+ });+ await sdk.initWorkspace();+ const spec = {+ solution: { uniqueName: 'Support', displayName: 'Support', publisherPrefix: 'new' },+ app: { name: 'Support', uniqueName: 'new_support' },+ entities: [],+ appShell: { areas: [] },+ dashboards: [{ name: 'Support board', dashboardId: DASHBOARD_ID, tiles: [{ type: 'list', name: 'Open cases', entity: 'incident', viewId: OPEN_VIEW }] }],+ };+ const result = await verifySpec(spec, readerFor(sdk, 'new_support', {}), { concurrency: 1 });+ return { result, check: result.checks.find((c) => c.kind === 'dashboard') };+}++const OPEN_CASES = () => nativeGrid('Component1', 'Open cases', OPEN_VIEW);+const BY_STATUS = () => nativeChart('Component2', 'Cases by status', CHART_VIEW, CHART);++test('a native chart tile whose chart and view belong to its table verifies', async () => {+ const { result, check } = await verifying(dashboardXml([[OPEN_CASES(), BY_STATUS()]]));+ assert.strictEqual(check.present, true, check.detail);+ assert.strictEqual(result.ok, true, JSON.stringify(result.missing));+});++test('a chart a custom control hosts, with no native visualization, does not fail the dashboard it sits on', async () => {+ const { result, check } = await verifying(dashboardXml(+ [[OPEN_CASES(), customChart('Component2', 'Custom-rendered chart', CHART_VIEW, '', CHART_UNIQUE)]],+ [customDescription(CHART_UNIQUE, CHART_VIEW)]+ ));+ assert.strictEqual(check.present, true, check.detail);+ assert.deepStrictEqual(result.missing, []);+ assert.strictEqual(result.ok, true);+ assert.strictEqual(result.unverified, undefined, 'and nothing is reported about it: verify did not look at a tile the spec cannot describe');+});++test('a chart a custom control hosts is not held to its table at all: the ids it carries are not the spec\u2019s to judge', async () => {+ const { check } = await verifying(dashboardXml([[+ OPEN_CASES(),+ customChart('Component2', 'Escalations (chart control)', CHART_VIEW, OTHER_TABLE_CHART, CHART_UNIQUE),+ customGrid('Component3', 'My cases (grid control)', OPEN_VIEW, GRID_UNIQUE),+ ]], [customDescription(CHART_UNIQUE, CHART_VIEW), customDescription(GRID_UNIQUE, OPEN_VIEW)]));+ assert.strictEqual(check.present, true, check.detail);+});++test('a native chart tile is still held to its table: a chart of another table fails the dashboard, and says which tile', async () => {+ const { result, check } = await verifying(dashboardXml([[+ OPEN_CASES(),+ nativeChart('Component2', 'Cases by status', CHART_VIEW, OTHER_TABLE_CHART),+ ]]));+ assert.strictEqual(check.present, false);+ assert.match(check.detail, /^chart tile 'Cases by status' shows incident, but its chart belongs to account$/);+ assert.strictEqual(result.ok, false);+});++test('a native chart tile with no visualization to look up is still unverified, which fails the dashboard', async () => {+ const { check } = await verifying(dashboardXml([[OPEN_CASES(), nativeChart('Component2', 'Cases by status', CHART_VIEW, '')]]));+ assert.strictEqual(check.present, false);+ assert.match(check.detail, /^chart tile 'Cases by status': its chart or view could not be resolved — unverified, not proven correct$/);+});++test('a native chart beside a hosted one is still checked, and it alone fails the dashboard', async () => {+ const { check } = await verifying(dashboardXml(+ [[OPEN_CASES(), customChart('Component2', 'Custom-rendered chart', CHART_VIEW, '', CHART_UNIQUE), nativeChart('Component3', 'Cases by status', CHART_VIEW, OTHER_TABLE_CHART)]],+ [customDescription(CHART_UNIQUE, CHART_VIEW)]+ ));+ assert.strictEqual(check.present, false);+ assert.match(check.detail, /^chart tile 'Cases by status' shows incident, but its chart belongs to account$/, 'only the native tile is named');+});++test('the Assistant, and a custom control that is no grid or chart, are skipped as they always were', async () => {+ const { result, check } = await verifying(dashboardXml([+ [OPEN_CASES(), BY_STATUS()],+ [assistantTile('Component3', 'Assistant'), otherCustomControl('Component4', 'Compact card', OTHER_UNIQUE)],+ ]));+ assert.strictEqual(check.present, true, check.detail);+ assert.strictEqual(result.ok, true, JSON.stringify(result.missing));+});diff --git a/plugins/model-apps/scripts/tests/verify-model-app.test.js b/plugins/model-apps/scripts/tests/verify-model-app.test.jsindex 00e7a3514..5a997148b 100644--- a/plugins/model-apps/scripts/tests/verify-model-app.test.js+++ b/plugins/model-apps/scripts/tests/verify-model-app.test.js@@ -8,6 +8,7 @@ const vm = require('node:vm');const { readerFor, appIdFor } = require('../verify-model-app.js');const { verifySpec } = require('../lib/verify-spec.js');const { validateFlagsFromParsed } = require('./helpers/fake-auth.js');+const { appSpec, column, nameColumn } = require('./helpers/column-gate-specs.js');const GP_OVERVIEW = '13ecbc57-a3a4-4132-b0a2-a6c6b12691e8';const GP_DETAIL = '5c0a4889-45fd-46ea-91a8-ff876914d644';@@ -781,6 +782,94 @@ test('verify CLI still verifies an older colliding spec and names the holder', aassert.ok(emitted.payload.missing.some((m) => /not as the declared N:N/.test(m)), JSON.stringify(emitted.payload));});+// --- an app deployed from a spec an earlier release accepted can still be verified ----------------------------------------------------+// Two rules keep a BUILD from misreading a column's declaration (lib/app-spec.js): an AutoNumber column needs a format, and `required` is true, false or+// "recommended". Verification creates and updates nothing and only reads whether each column exists, so the spec of an app an earlier release built — an+// AutoNumber column made as plain text, a `required: "true"` made not required — must still reach the deployment. The CLI passes columnValues: 'warn', as it+// passes relationshipCollisions: 'warn': the findings are warnings that name the column and the fix, and the verdict is the deployment's.+async function verifyOlderSpec(specObject) {+ const reads = [];+ const harness = loadVerifyCli({+ parseResult: { positional: [], flags: { env: 'https://contoso.crm.dynamics.com', spec: '@app-spec.json', workspace: 'D:\\Projects\\_temp\\verify-older-spec' } },+ realGates: true,+ specObject,+ sdkFactory: () => ({+ initWorkspace: async () => {},+ findTables: async () => { reads.push('tables'); return [{ logicalName: 'new_ticket' }]; },+ findColumns: async (name) => { reads.push(`columns ${name}`); return [{ logicalName: 'new_name' }, { logicalName: 'new_ref' }, { logicalName: 'new_status' }]; },+ queryRecords: async (set) => (set === 'appmodule' ? [{ appmoduleid: '11111111-2222-3333-4444-555555555555' }] : []),+ fetchEntityMetadata: async () => ({ Relationships: [] }),+ resolveArtifact: async () => [],+ retrieveSetting: async () => null,+ }),+ });+ await harness.main();+ return { reads, emitted: harness.events.find((e) => e.type === 'emitResult'), stderr: harness.stderr.join('') };+}++const OMIT_THE_KEY = "omit the key to leave an existing column's level as it is";+const OLDER_SPECS = [+ ['an AutoNumber column with no format', { columns: [column({ type: 'AutoNumber' })] },+ 'column new_ref is an AutoNumber column but its autoNumberFormat is missing — give it a format such as "C-{SEQNUM:5}", or use type "Text" for a plain text column'],+ ['an AutoNumber column with a blank format', { columns: [column({ type: 'AutoNumber', autoNumberFormat: ' ' })] },+ 'column new_ref is an AutoNumber column but its autoNumberFormat is blank — give it a format such as "C-{SEQNUM:5}", or use type "Text" for a plain text column'],+ ['a column whose required is null', { columns: [column({ type: 'Text', required: null })] },+ `column new_ref required must be true, false or "recommended" (got null) — true makes a column required, "recommended" makes it recommended and false makes it not required; ${OMIT_THE_KEY}`],+ ['a column whose required is the string "true"', { columns: [column({ type: 'Text', required: 'true' })] },+ `column new_ref required must be true, false or "recommended" (got "true") — write true for a required column; ${OMIT_THE_KEY}`],+ ['a column whose required is "ApplicationRequired"', { columns: [column({ type: 'Text', required: 'ApplicationRequired' })] },+ `column new_ref required must be true, false or "recommended" (got "ApplicationRequired") — write true for a required column; ${OMIT_THE_KEY}`],+ ['a primary name column whose required is "ApplicationRequired"', { primaryAttribute: nameColumn({ required: 'ApplicationRequired' }) },+ `primaryAttribute.required must be true, false or "recommended" (got "ApplicationRequired") — write true for a required column; ${OMIT_THE_KEY}`],+];++test('verify CLI still verifies the deployment of a spec an earlier release accepted — and warns, naming the column and the fix', async () => {+ for (const [label, parts, finding] of OLDER_SPECS) {+ const { reads, emitted, stderr } = await verifyOlderSpec(appSpec(parts));+ assert.ok(emitted, `${label}: a result is emitted`);+ assert.strictEqual(emitted.ok, true, `${label}: verification ran and passed — ${JSON.stringify(emitted.payload)}`);+ assert.ok(emitted.payload.total > 0 && emitted.payload.present === emitted.payload.total, `${label}: the deployment was checked — ${JSON.stringify(emitted.payload)}`);+ assert.ok(!('errors' in emitted.payload) || emitted.payload.errors.length === 0, `${label}: no schema error stops it — ${JSON.stringify(emitted.payload)}`);+ assert.ok(reads.includes('columns new_ticket'), `${label}: the deployed columns were read — ${JSON.stringify(reads)}`);+ assert.ok(stderr.includes(`WARNING: entity new_ticket: ${finding}\n`), `${label}: the warning names the column and the fix\n${stderr}`);+ assert.match(stderr, /✓ verify PASS/, label);+ }+});++test('verify CLI warns once for each finding of an older spec, in the spec\'s order, and still reaches the deployment', async () => {+ const spec = appSpec({+ columns: [column({ type: 'AutoNumber', required: 'true' }), column({ schemaName: 'new_status', type: 'Text', required: null })],+ primaryAttribute: nameColumn({ required: 'ApplicationRequired' }),+ });+ const { emitted, stderr } = await verifyOlderSpec(spec);+ assert.strictEqual(emitted.ok, true, JSON.stringify(emitted.payload));+ const warnings = stderr.split('\n').filter((line) => line.startsWith('WARNING: '));+ assert.deepStrictEqual(warnings.map((line) => line.slice(0, line.indexOf(' — '))), [+ 'WARNING: entity new_ticket: primaryAttribute.required must be true, false or "recommended" (got "ApplicationRequired")',+ 'WARNING: entity new_ticket: column new_ref is an AutoNumber column but its autoNumberFormat is missing',+ 'WARNING: entity new_ticket: column new_ref required must be true, false or "recommended" (got "true")',+ 'WARNING: entity new_ticket: column new_status required must be true, false or "recommended" (got null)',+ ]);+});++test('verify CLI says nothing about these rules for a spec that satisfies them, and gives the same verdict', async () => {+ const spec = appSpec({ columns: [column({ type: 'AutoNumber', autoNumberFormat: 'C-{SEQNUM:5}', required: 'recommended' })], primaryAttribute: nameColumn({ required: false }) });+ const { reads, emitted, stderr } = await verifyOlderSpec(spec);+ assert.strictEqual(emitted.ok, true, JSON.stringify(emitted.payload));+ assert.ok(emitted.payload.total > 0 && emitted.payload.present === emitted.payload.total, JSON.stringify(emitted.payload));+ assert.ok(reads.includes('columns new_ticket'), JSON.stringify(reads));+ assert.ok(!/WARNING:/.test(stderr), `no warning: ${stderr}`);+ assert.match(stderr, /✓ verify PASS/);+});++test('verify CLI still refuses a spec that is invalid for another reason — before any read — and the column rules are no part of that refusal', async () => {+ const spec = appSpec({ columns: [column({ type: 'AutoNumber' }), column({ schemaName: 'new_bad', type: 'Nope' })] });+ const { reads, emitted } = await verifyOlderSpec(spec);+ assert.strictEqual(emitted.ok, false);+ assert.deepStrictEqual(emitted.payload.errors, ["entity new_ticket: column new_bad has unknown type 'Nope'"]);+ assert.deepStrictEqual(reads, [], 'nothing was read');+});+test('verify CLI entrypoint converts SDK startup errors into emitResult failures', async () => {const harness = loadVerifyCli({parseResult: {diff --git a/plugins/model-apps/scripts/tests/view-related-rows-filter.test.js b/plugins/model-apps/scripts/tests/view-related-rows-filter.test.jsnew file mode 100644index 000000000..97a8a4f7c--- /dev/null+++ b/plugins/model-apps/scripts/tests/view-related-rows-filter.test.js@@ -0,0 +1,101 @@+'use strict';+// A view's filter can hold a `<link-entity>`: a condition on RELATED rows ("accounts with a contact that has an email address",+// `link-type="any"`). The SDK keeps such a filter — the conditions beside the link-entity in the same `<filter>` included —+// only in its own copy of the view's FetchXML, so the typed `filters` of a fetched view are EMPTY for it.+//+// Nothing the plugin does reads a view's filters through that typed tree, and these tests pin why it loses nothing:+// - the build changes an existing view's columns and description and nothing else of its query, and the SDK writes the+// filter back as it was (rebuild-writes-real-bundle.test.js drives that through a whole rebuild);+// - a download carries no view at all — `views[]` is emitted empty and each deployed view is only named in the report of+// what the spec leaves out — so a filter the typed tree cannot show is never half-emitted.+// If a later bundle fills the typed tree, or a later download reads a view's query, these are the tests to look at again.+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 { readDescriptionInventory, notRoundTrippedSummary, notRoundTrippedWarning } = require('../download-model-app.js');+const { hydrateSpec } = require('../lib/hydrate-spec.js');+const { currentReadSdk, APP, CURRENT } = require('./helpers/app-membership-sdk.js');++const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');+const VIEW_ID = '00000000-0000-4000-8000-0000000000bb';+const VIEW_NAME = 'Accounts with a reachable contact';++// The related-rows filter, as FetchXML writes it: the `<link-entity>` is a child of the `<filter>`, beside a plain condition.+const RELATED_FILTER = '<filter type="and"><condition attribute="statecode" operator="eq" value="0" />'+ + '<link-entity name="contact" from="parentcustomerid" to="accountid" link-type="any">'+ + '<filter type="and"><condition attribute="emailaddress1" operator="not-null" /></filter></link-entity></filter>';+const VIEW_FETCH = `<fetch version="1.0" mapping="logical"><entity name="account"><attribute name="name" /><attribute name="accountid" /><order attribute="name" descending="false" />${RELATED_FILTER}</entity></fetch>`;+const VIEW_LAYOUT = '<grid name="resultset" object="1" jump="name" select="1" icon="1" preview="1"><row name="result" id="accountid"><cell name="name" width="300" /></row></grid>';++const dirs = [];+test.after(() => { for (const dir of dirs) fs.rmSync(dir, { recursive: true, force: true }); });++test('REAL BUNDLE: a view whose filter holds a related-rows link-entity has no typed filters — the whole filter lives in the SDK\u2019s copy of the query, which a column edit writes back', async () => {+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'view-related-'));+ dirs.push(dir);+ const patches = [];+ const row = { '@odata.etag': 'W/"4180012"', savedqueryid: VIEW_ID, name: VIEW_NAME, description: '', returnedtypecode: 'account', querytype: 0, isdefault: false, fetchxml: VIEW_FETCH, layoutxml: VIEW_LAYOUT };+ const httpClient = {+ get: async (url) => (/\/savedqueries\([^)]+\)/.test(url) ? { status: 200, headers: {}, body: row } : { status: 200, headers: {}, body: {} }),+ post: async () => ({ status: 204, headers: {}, body: {} }),+ patch: async (url, body) => { patches.push(body); return { status: 204, headers: {}, body: {} }; },+ delete: async () => ({ status: 204, headers: {}, body: {} }),+ put: async () => ({ status: 204, headers: {}, body: {} }),+ };+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: 'https://contoso.crm.dynamics.com', httpClient });+ await sdk.initWorkspace();+ await sdk.fetchArtifact('view', VIEW_ID);+ const view = await sdk.getArtifact('view', VIEW_ID);++ // The typed tree is empty — the plain `statecode` condition beside the link-entity is not in it either — and the filter is in the bag.+ assert.deepStrictEqual(view.filters, { type: 'and', conditions: [], groups: [] });+ assert.strictEqual(view.linkEntities, undefined);+ const bag = JSON.stringify(view.fetchBag);+ assert.ok(bag.includes('"link-entity"') && bag.includes('"any"') && bag.includes('emailaddress1'), 'the related-rows condition is kept in the bag');++ // A column edit, as a rebuild makes it, writes the filter back whole: both conditions and the link-entity with its own.+ await sdk.updateElement('view', VIEW_ID, '/columns', [...view.columns, { name: 'telephone1', width: 100, order: view.columns.length }]);+ const pushed = await sdk.pushArtifact('view', VIEW_ID);+ assert.notStrictEqual(pushed.saved, false, JSON.stringify(pushed.error && pushed.error.message));+ assert.strictEqual(patches.length, 1);+ const spaced = (xml) => xml.replace(/\s*\/>/g, ' />');+ assert.ok(spaced(patches[0].fetchxml).includes(spaced(RELATED_FILTER)), `the filter is written back as it was:\n${patches[0].fetchxml}`);+ assert.match(patches[0].fetchxml, /<attribute name="telephone1"/, 'and the new column is fetched');+});++test('a download carries no view — its query is never read, so a filter the typed tree cannot show is named with the view and never partly emitted', async () => {+ const selects = [];+ const sdk = {+ queryRecords: async (set, opts) => {+ const filter = (opts && opts.filter) || '';+ if (set === 'appmodule') return [{ appmoduleidunique: CURRENT }];+ if (set === 'appmodulecomponent' && /componenttype eq 26/.test(filter)) return [{ objectid: VIEW_ID }];+ if (set === 'savedquery') {+ selects.push(opts.select);+ return [{ savedqueryid: VIEW_ID, name: VIEW_NAME, returnedtypecode: 'account', description: 'Accounts a salesperson can ring.' }];+ }+ if (set === 'solution') return [{ solutionid: '00000000-0000-4000-8000-0000000000ee' }];+ return [];+ },+ dataverse: { get: async () => ({ status: 200, headers: {}, body: { value: [] } }) },+ };++ const inventory = await readDescriptionInventory(currentReadSdk(sdk, { appId: APP, layerId: CURRENT }), APP, 'ContosoSolution');+ assert.deepStrictEqual(inventory.views, [{ id: VIEW_ID, name: VIEW_NAME, entity: 'account', description: 'Accounts a salesperson can ring.' }]);+ assert.ok(selects.length > 0, 'the view row was read');+ assert.ok(selects.flat().every((column) => !/^(fetchxml|layoutxml)$/i.test(column)), `no column of the view\u2019s query is selected: ${JSON.stringify(selects)}`);++ // The spec holds no view, and the view is reported by name as something the spec leaves out.+ const spec = await hydrateSpec({+ app: async () => ({ name: 'Sales', description: '', uniquename: 'new_sales', siteMap: { areas: [] } }),+ pages: async () => [], entities: async () => [], webResources: async () => [],+ solution: async () => ({ uniqueName: 'Sales', publisherPrefix: 'new' }),+ });+ assert.deepStrictEqual(spec.views, []);+ const warning = notRoundTrippedWarning(notRoundTrippedSummary(inventory));+ assert.match(warning, new RegExp(`views: ${VIEW_NAME}`));+ assert.match(warning, /THIS environment leaves them untouched/);+});diff --git a/plugins/model-apps/scripts/vendor/PROVENANCE.json b/plugins/model-apps/scripts/vendor/PROVENANCE.jsonindex 3a7c83c48..707ba670b 100644--- a/plugins/model-apps/scripts/vendor/PROVENANCE.json+++ b/plugins/model-apps/scripts/vendor/PROVENANCE.json@@ -1,13 +1,13 @@{- "commit": "2d6f9c9f556cb20fce36d4764f3b618c6268b711",+ "commit": "ccf2c1a11a829fe261199936493aa12f3e2bd0ed","dirtySdkPackage": 0,- "libBuiltAt": "2026-10-13T23:12:08.257Z",- "newestSrcAt": "2026-10-13T23:06:00.253Z",+ "libBuiltAt": "2026-10-19T15:37:01.994Z",+ "newestSrcAt": "2026-10-18T02:54:15.290Z","libIsStale": false,"nostub": false,"esbuildVersion": "0.28.1","nodeVersion": "v20.20.2",- "builtAt": "2026-10-13T23:12:43.825Z",- "bundleSha256": "8e0316becce9e45f9641a067eba9e653869cde77dc82da080676da5c152cfebf",- "bundleBytes": 1005262+ "builtAt": "2026-10-19T15:38:54.180Z",+ "bundleSha256": "b8497fbc98f732df23b83d4002818612a9f41c1b94bff7bbeefc5cc60e910f36",+ "bundleBytes": 1057824}diff --git a/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs b/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjsindex 3a2e676a1..f359733cc 100644--- a/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs+++ b/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs@@ -25,56 +25,56 @@}globalThis.document=globalThis.document||globalThis.window.document;})();-var tU=Object.create;var hc=Object.defineProperty;var rU=Object.getOwnPropertyDescriptor;var nU=Object.getOwnPropertyNames;var iU=Object.getPrototypeOf,oU=Object.prototype.hasOwnProperty;var k=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var v=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},jr=(e,t)=>{for(var r in t)hc(e,r,{get:t[r],enumerable:!0})},mc=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of nU(t))!oU.call(e,i)&&i!==r&&hc(e,i,{get:()=>t[i],enumerable:!(n=rU(t,i))||n.enumerable});return e},Ki=(e,t,r)=>(mc(e,t,"default"),r&&mc(r,t,"default")),we=(e,t,r)=>(r=e!=null?tU(iU(e)):{},mc(t||!e||!e.__esModule?hc(r,"default",{value:e,enumerable:!0}):r,e)),kr=e=>mc(hc({},"__esModule",{value:!0}),e);var Ji=v(T=>{"use strict";Object.defineProperty(T,"__esModule",{value:!0});T.DateTimeBehavior=T.PrecisionSource=T.StringFormatName=T.SourceType=T.ImeMode=T.SolutionEntityTypeCodeExtToComponentTypeCode=T.SolutionComponentTypeCodeToEntityTypeCodeExt=T.SolutionComponentVirtualAttributeSubtype=T.EntityTypeCode=T.SolutionComponentTypeCodeExt=T.RootComponentBehavior=T.SolutionComponentTypeCode=T.EntityKeyIndexStatus=T.ViewStateCode=T.ViewStatusCode=T.RelationshipSecurityTypes=T.CascadeType=T.RelationshipTypeExt=T.RelationshipType=T.AppSubType=T.BusinessProcessType=T.WorkflowCategory=T.WorkflowScope=T.WorkflowTypeCode=T.StatusCodeEnabledDisabled=T.StateCodeEnabledDisabled=T.StatusCode=T.StateCode=T.OptionSetType=T.AttributeTypeCodeNum=T.AttributeFormatName=T.AttributeFormatCode=T.AttributeTypeName=T.AttributeTypeCode=T.PluginSourceType=T.AuthType=T.PluginIsolationMode=T.ComponentState=T.ChartType=T.ChartsType=T.ViewType=T.AttributeType=T.ActivationState=T.FormPresentation=T.FormType=T.TableTypeCode=T.TableTypes=T.ActivityTypeMask=T.PrincipalType=T.OwnershipTypes=void 0;T.QueryType=T.KnownCustomSolutionComponentEntitySetName=T.TeamTypeEnum=T.EnvironmentVariableDefinitionTypeEnum=T.ConnectorTypeEnum=T.RoleInheritance=T.DefaultRoleTemplates=T.DeleteDependencyErrorCode=T.ServiceEndpointConnectionMode=T.ServiceEndpointContract=T.ServiceNamespaceFormat=T.ConnectionRoleCategory=T.ReportTypeCode=T.SdkMessageProcessingMode=T.SupportedDeployment=T.SdkMessageProcessingStage=T.WebResourceTypeCode=T.IntegerFormat=T.DateTimeFormat=void 0;var Gv;(function(e){e.None="None",e.UserOwned="UserOwned",e.TeamOwned="TeamOwned",e.BusinessOwned="BusinessOwned",e.OrganizationOwned="OrganizationOwned",e.BusinessParented="BusinessParented",e.Filtered="Filtered"})(Gv||(T.OwnershipTypes=Gv={}));var Wv;(function(e){e.User="Microsoft.Dynamics.CRM.systemuser",e.Team="Microsoft.Dynamics.CRM.team"})(Wv||(T.PrincipalType=Wv={}));var zv;(function(e){e[e.DoNotDisplayInActivityMenus=0]="DoNotDisplayInActivityMenus",e[e.DisplayInActivityMenus=1]="DisplayInActivityMenus"})(zv||(T.ActivityTypeMask=zv={}));var jv;(function(e){e.Activity="Activity",e.Virtual="Virtual",e.Standard="Standard",e.Elastic="Elastic"})(jv||(T.TableTypes=jv={}));var Hv;(function(e){e.Standard="Standard",e.Virtual="Virtual",e.Elastic="Elastic"})(Hv||(T.TableTypeCode=Hv={}));var Kv;(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"})(Kv||(T.FormType=Kv={}));var Jv;(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(Jv||(T.FormPresentation=Jv={}));var Yv;(function(e){e[e.Inactive=0]="Inactive",e[e.Active=1]="Active"})(Yv||(T.ActivationState=Yv={}));var Qv;(function(e){e[e.String=0]="String",e[e.Number=1]="Number",e[e.Picklist=2]="Picklist"})(Qv||(T.AttributeType=Qv={}));var Xv;(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"})(Xv||(T.ViewType=Xv={}));var Zv;(function(e){e[e.ASPChart=0]="ASPChart",e[e.PowerBI=1]="PowerBI"})(Zv||(T.ChartsType=Zv={}));var ew;(function(e){e[e.DataAndInteractionCentric=0]="DataAndInteractionCentric",e[e.InteractionCentric=1]="InteractionCentric"})(ew||(T.ChartType=ew={}));var tw;(function(e){e[e.Published=0]="Published",e[e.Unpublished=1]="Unpublished",e[e.Deleted=2]="Deleted",e[e.DeletedUnpublished=3]="DeletedUnpublished"})(tw||(T.ComponentState=tw={}));var rw;(function(e){e[e.None=1]="None",e[e.Sandbox=2]="Sandbox",e[e.External=3]="External"})(rw||(T.PluginIsolationMode=rw={}));var nw;(function(e){e[e.BasicAuth=0]="BasicAuth"})(nw||(T.AuthType=nw={}));var iw;(function(e){e[e.Database=0]="Database",e[e.Disk=1]="Disk",e[e.Normal=2]="Normal",e[e.AzureWebApp=3]="AzureWebApp"})(iw||(T.PluginSourceType=iw={}));var ow;(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"})(ow||(T.AttributeTypeCode=ow={}));var aw;(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"})(aw||(T.AttributeTypeName=aw={}));var sw;(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"})(sw||(T.AttributeFormatCode=sw={}));var lw;(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"})(lw||(T.AttributeFormatName=lw={}));var uw;(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"})(uw||(T.AttributeTypeCodeNum=uw={}));var cw;(function(e){e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean"})(cw||(T.OptionSetType=cw={}));var dw;(function(e){e[e.Draft=0]="Draft",e[e.Activated=1]="Activated"})(dw||(T.StateCode=dw={}));var fw;(function(e){e[e.Draft=1]="Draft",e[e.Activated=2]="Activated"})(fw||(T.StatusCode=fw={}));var pw;(function(e){e[e.Enabled=0]="Enabled",e[e.Disabled=1]="Disabled"})(pw||(T.StateCodeEnabledDisabled=pw={}));var mw;(function(e){e[e.Enabled=1]="Enabled",e[e.Disabled=2]="Disabled"})(mw||(T.StatusCodeEnabledDisabled=mw={}));var hw;(function(e){e[e.Definition=1]="Definition",e[e.Activation=2]="Activation",e[e.Template=3]="Template"})(hw||(T.WorkflowTypeCode=hw={}));var gw;(function(e){e[e.User=1]="User",e[e.BusinessUnit=2]="BusinessUnit",e[e.ParentChildBusinessUnit=3]="ParentChildBusinessUnit",e[e.Organization=4]="Organization"})(gw||(T.WorkflowScope=gw={}));var yw;(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"})(yw||(T.WorkflowCategory=yw={}));var bw;(function(e){e[e.None=-1]="None",e[e.BusinessFlow=0]="BusinessFlow",e[e.TaskFlow=1]="TaskFlow"})(bw||(T.BusinessProcessType=bw={}));var vw;(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"})(vw||(T.AppSubType=vw={}));var ww;(function(e){e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(ww||(T.RelationshipType=ww={}));var Cw;(function(e){e.ManyToOneRelationship="ManyToOneRelationship",e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(Cw||(T.RelationshipTypeExt=Cw={}));var Ew;(function(e){e.NoCascade="NoCascade",e.Cascade="Cascade",e.Active="Active",e.UserOwned="UserOwned",e.RemoveLink="RemoveLink",e.Restrict="Restrict"})(Ew||(T.CascadeType=Ew={}));var Aw;(function(e){e.None="None",e.Append="Append",e.ParentChild="ParentChild",e.Pointer="Pointer",e.Inheritance="Inheritance"})(Aw||(T.RelationshipSecurityTypes=Aw={}));var Sw;(function(e){e[e.Active=1]="Active",e[e.Inactive=2]="Inactive"})(Sw||(T.ViewStatusCode=Sw={}));var Nw;(function(e){e[e.Active=0]="Active",e[e.Inactive=1]="Inactive"})(Nw||(T.ViewStateCode=Nw={}));var _w;(function(e){e.Active="Active",e.Failed="Failed",e.InProgress="InProgress",e.Pending="Pending"})(_w||(T.EntityKeyIndexStatus=_w={}));var Tw;(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"})(Tw||(T.SolutionComponentTypeCode=Tw={}));var Dw;(function(e){e[e.IncludeSubcomponents=0]="IncludeSubcomponents",e[e.DoNotIncludeSubcomponents=1]="DoNotIncludeSubcomponents",e[e.IncludeAsShellOnly=2]="IncludeAsShellOnly"})(Dw||(T.RootComponentBehavior=Dw={}));var gc;(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"})(gc||(T.SolutionComponentTypeCodeExt=gc={}));var yc;(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"})(yc||(T.EntityTypeCode=yc={}));var Iw;(function(e){e.MultiSelectPicklist="MultiSelectPicklist",e.File="File",e.Image="Image"})(Iw||(T.SolutionComponentVirtualAttributeSubtype=Iw={}));function aU(e){let t=gc[e];return yc[t]}T.SolutionComponentTypeCodeToEntityTypeCodeExt=aU;function sU(e){let t=yc[e];return gc[t]}T.SolutionEntityTypeCodeExtToComponentTypeCode=sU;var Ow;(function(e){e.Active="Active",e.Auto="Auto",e.Disabled="Disabled",e.Inactive="Inactive"})(Ow||(T.ImeMode=Ow={}));var Pw;(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"})(Pw||(T.SourceType=Pw={}));var Rw;(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"})(Rw||(T.StringFormatName=Rw={}));var Lw;(function(e){e[e.PrecisionProperty=0]="PrecisionProperty",e[e.Organization=1]="Organization",e[e.TransactionCurrency=2]="TransactionCurrency"})(Lw||(T.PrecisionSource=Lw={}));var kw;(function(e){e.UserLocal="UserLocal",e.DateOnly="DateOnly",e.TimeZoneIndependent="TimeZoneIndependent"})(kw||(T.DateTimeBehavior=kw={}));var xw;(function(e){e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(xw||(T.DateTimeFormat=xw={}));var $w;(function(e){e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})($w||(T.IntegerFormat=$w={}));var Fw;(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"})(Fw||(T.WebResourceTypeCode=Fw={}));var Mw;(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"})(Mw||(T.SdkMessageProcessingStage=Mw={}));var Uw;(function(e){e[e.ServerOnly=0]="ServerOnly",e[e.OutlookClientOnly=1]="OutlookClientOnly",e[e.Both=2]="Both"})(Uw||(T.SupportedDeployment=Uw={}));var Bw;(function(e){e[e.Synchronous=0]="Synchronous",e[e.Asynchronous=1]="Asynchronous"})(Bw||(T.SdkMessageProcessingMode=Bw={}));var qw;(function(e){e[e.ReportingServicesReport=1]="ReportingServicesReport",e[e.OtherReport=2]="OtherReport",e[e.LinkedReport=3]="LinkedReport"})(qw||(T.ReportTypeCode=qw={}));var Vw;(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"})(Vw||(T.ConnectionRoleCategory=Vw={}));var Gw;(function(e){e[e.Name=1]="Name",e[e.Address=2]="Address"})(Gw||(T.ServiceNamespaceFormat=Gw={}));var Ww;(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"})(Ww||(T.ServiceEndpointContract=Ww={}));var zw;(function(e){e[e.Normal=1]="Normal",e[e.Federated=2]="Federated"})(zw||(T.ServiceEndpointConnectionMode=zw={}));var jw;(function(e){e.CannotDeleteInUseComponent="0x8004f01f",e.CannotDeleteInUseAttribute="0x80048418",e.CannotDeleteInUseOptionSet="0x80048417",e.CannotDeleteInUseEntity="0x80048420",e.CannotUninstallWithDependencies="0x8004F01D"})(jw||(T.DeleteDependencyErrorCode=jw={}));var Hw;(function(e){e.SystemAdministrator="627090FF-40A3-4053-8790-584EDC5BE201",e.SystemCustomizer="119F245C-3CC8-4B62-B31C-D1A046CED15D"})(Hw||(T.DefaultRoleTemplates=Hw={}));var Kw;(function(e){e[e.DefaultTeamPrivilege=0]="DefaultTeamPrivilege",e[e.DirectUserAndTeamPrivilege=1]="DirectUserAndTeamPrivilege"})(Kw||(T.RoleInheritance=Kw={}));var Jw;(function(e){e[e.NotSpecified=0]="NotSpecified",e[e.CustomConnector=1]="CustomConnector"})(Jw||(T.ConnectorTypeEnum=Jw={}));var Yw;(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"})(Yw||(T.EnvironmentVariableDefinitionTypeEnum=Yw={}));var Qw;(function(e){e[e.Owner=0]="Owner",e[e.Access=1]="Access",e[e.AADSecurityGroup=2]="AADSecurityGroup",e[e.AADOfficeGroup=3]="AADOfficeGroup"})(Qw||(T.TeamTypeEnum=Qw={}));var Xw;(function(e){e.Bots="bots"})(Xw||(T.KnownCustomSolutionComponentEntitySetName=Xw={}));var Zw;(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"})(Zw||(T.QueryType=Zw={}))});var Q=v(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.IncompatibleWorkspaceError=X.PathTraversalError=X.AmbiguousArtifactError=X.JsonPointerError=X.NotImplementedError=X.WorkspaceOrgMismatchError=X.WorkspaceNotInitializedError=X.attachCause=X.ConnectionError=X.VersionConflictError=X.LocalEditsWouldBeLostError=X.StaleArtifactError=X.InvalidArgumentError=X.ValidationError=X.PathNotFoundError=X.ArtifactNotFoundError=X.readCleanupWarnings=X.withCleanupWarnings=X.readPartialEnrichment=X.withPartialEnrichment=X.readPartialTokens=X.withPartialTokens=X.SdkError=void 0;var gt=class extends Error{constructor(t,r){super(r),this.code=t,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}};X.SdkError=gt;var eC=Symbol.for("cds-maker-sdk.partialWriteTokens");function lU(e,t){return typeof e=="object"&&e!==null&&(e[eC]=t),e}X.withPartialTokens=lU;function uU(e){return hm(e,eC)}X.readPartialTokens=uU;function hm(e,t){let r=e;for(let n=0;r&&typeof r=="object"&&n<8;n++){let i=r[t];if(i&&typeof i=="object")return i;r=r.cause}}var tC=Symbol.for("cds-maker-sdk.partialDefaultViewEnrichment");function cU(e,t){return typeof e=="object"&&e!==null&&(e[tC]=t),e}X.withPartialEnrichment=cU;function dU(e){return hm(e,tC)}X.readPartialEnrichment=dU;var Zp=Symbol.for("cds-maker-sdk.cleanupWarnings");function fU(e,t){if(typeof e=="object"&&e!==null&&t.length>0){let r=e,n=r[Zp];r[Zp]=[...Array.isArray(n)?n:[],...t]}return e}X.withCleanupWarnings=fU;function pU(e){let t=hm(e,Zp);return t?[...t]:void 0}X.readCleanupWarnings=pU;var em=class extends gt{constructor(t,r){super("ARTIFACT_NOT_FOUND",`Artifact ${t}/${r} not found in workspace`),this.type=t,this.id=r}};X.ArtifactNotFoundError=em;var tm=class extends gt{constructor(t,r,n){super("PATH_NOT_FOUND",`Path ${n} not found in ${t}/${r}`),this.type=t,this.id=r,this.pointer=n}};X.PathNotFoundError=tm;var rm=class extends gt{constructor(t,r,n,i){var o,a,s,l;let u=Array.isArray(n)?n:[{pointer:n,rule:i??"invalid",message:i??"invalid"}];super("VALIDATION_ERROR",`Validation failed for ${t}/${r}:+var eq=Object.create;var qc=Object.defineProperty;var tq=Object.getOwnPropertyDescriptor;var rq=Object.getOwnPropertyNames;var nq=Object.getPrototypeOf,iq=Object.prototype.hasOwnProperty;var k=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var v=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},nn=(e,t)=>{for(var r in t)qc(e,r,{get:t[r],enumerable:!0})},Bc=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of rq(t))!iq.call(e,i)&&i!==r&&qc(e,i,{get:()=>t[i],enumerable:!(n=tq(t,i))||n.enumerable});return e},so=(e,t,r)=>(Bc(e,t,"default"),r&&Bc(r,t,"default")),Ce=(e,t,r)=>(r=e!=null?eq(nq(e)):{},Bc(t||!e||!e.__esModule?qc(r,"default",{value:e,enumerable:!0}):r,e)),zr=e=>Bc(qc({},"__esModule",{value:!0}),e);var lo=v(T=>{"use strict";Object.defineProperty(T,"__esModule",{value:!0});T.DateTimeBehavior=T.PrecisionSource=T.StringFormatName=T.SourceType=T.ImeMode=T.SolutionEntityTypeCodeExtToComponentTypeCode=T.SolutionComponentTypeCodeToEntityTypeCodeExt=T.SolutionComponentVirtualAttributeSubtype=T.EntityTypeCode=T.SolutionComponentTypeCodeExt=T.RootComponentBehavior=T.SolutionComponentTypeCode=T.EntityKeyIndexStatus=T.ViewStateCode=T.ViewStatusCode=T.RelationshipSecurityTypes=T.CascadeType=T.RelationshipTypeExt=T.RelationshipType=T.AppSubType=T.BusinessProcessType=T.WorkflowCategory=T.WorkflowScope=T.WorkflowTypeCode=T.StatusCodeEnabledDisabled=T.StateCodeEnabledDisabled=T.StatusCode=T.StateCode=T.OptionSetType=T.AttributeTypeCodeNum=T.AttributeFormatName=T.AttributeFormatCode=T.AttributeTypeName=T.AttributeTypeCode=T.PluginSourceType=T.AuthType=T.PluginIsolationMode=T.ComponentState=T.ChartType=T.ChartsType=T.ViewType=T.AttributeType=T.ActivationState=T.FormPresentation=T.FormType=T.TableTypeCode=T.TableTypes=T.ActivityTypeMask=T.PrincipalType=T.OwnershipTypes=void 0;T.QueryType=T.KnownCustomSolutionComponentEntitySetName=T.TeamTypeEnum=T.EnvironmentVariableDefinitionTypeEnum=T.ConnectorTypeEnum=T.RoleInheritance=T.DefaultRoleTemplates=T.DeleteDependencyErrorCode=T.ServiceEndpointConnectionMode=T.ServiceEndpointContract=T.ServiceNamespaceFormat=T.ConnectionRoleCategory=T.ReportTypeCode=T.SdkMessageProcessingMode=T.SupportedDeployment=T.SdkMessageProcessingStage=T.WebResourceTypeCode=T.IntegerFormat=T.DateTimeFormat=void 0;var qw;(function(e){e.None="None",e.UserOwned="UserOwned",e.TeamOwned="TeamOwned",e.BusinessOwned="BusinessOwned",e.OrganizationOwned="OrganizationOwned",e.BusinessParented="BusinessParented",e.Filtered="Filtered"})(qw||(T.OwnershipTypes=qw={}));var Vw;(function(e){e.User="Microsoft.Dynamics.CRM.systemuser",e.Team="Microsoft.Dynamics.CRM.team"})(Vw||(T.PrincipalType=Vw={}));var Gw;(function(e){e[e.DoNotDisplayInActivityMenus=0]="DoNotDisplayInActivityMenus",e[e.DisplayInActivityMenus=1]="DisplayInActivityMenus"})(Gw||(T.ActivityTypeMask=Gw={}));var Ww;(function(e){e.Activity="Activity",e.Virtual="Virtual",e.Standard="Standard",e.Elastic="Elastic"})(Ww||(T.TableTypes=Ww={}));var zw;(function(e){e.Standard="Standard",e.Virtual="Virtual",e.Elastic="Elastic"})(zw||(T.TableTypeCode=zw={}));var jw;(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"})(jw||(T.FormType=jw={}));var Hw;(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(Hw||(T.FormPresentation=Hw={}));var Kw;(function(e){e[e.Inactive=0]="Inactive",e[e.Active=1]="Active"})(Kw||(T.ActivationState=Kw={}));var Jw;(function(e){e[e.String=0]="String",e[e.Number=1]="Number",e[e.Picklist=2]="Picklist"})(Jw||(T.AttributeType=Jw={}));var Yw;(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"})(Yw||(T.ViewType=Yw={}));var Qw;(function(e){e[e.ASPChart=0]="ASPChart",e[e.PowerBI=1]="PowerBI"})(Qw||(T.ChartsType=Qw={}));var Xw;(function(e){e[e.DataAndInteractionCentric=0]="DataAndInteractionCentric",e[e.InteractionCentric=1]="InteractionCentric"})(Xw||(T.ChartType=Xw={}));var Zw;(function(e){e[e.Published=0]="Published",e[e.Unpublished=1]="Unpublished",e[e.Deleted=2]="Deleted",e[e.DeletedUnpublished=3]="DeletedUnpublished"})(Zw||(T.ComponentState=Zw={}));var eC;(function(e){e[e.None=1]="None",e[e.Sandbox=2]="Sandbox",e[e.External=3]="External"})(eC||(T.PluginIsolationMode=eC={}));var tC;(function(e){e[e.BasicAuth=0]="BasicAuth"})(tC||(T.AuthType=tC={}));var rC;(function(e){e[e.Database=0]="Database",e[e.Disk=1]="Disk",e[e.Normal=2]="Normal",e[e.AzureWebApp=3]="AzureWebApp"})(rC||(T.PluginSourceType=rC={}));var nC;(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"})(nC||(T.AttributeTypeCode=nC={}));var iC;(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"})(iC||(T.AttributeTypeName=iC={}));var oC;(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"})(oC||(T.AttributeFormatCode=oC={}));var aC;(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"})(aC||(T.AttributeFormatName=aC={}));var sC;(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"})(sC||(T.AttributeTypeCodeNum=sC={}));var lC;(function(e){e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean"})(lC||(T.OptionSetType=lC={}));var uC;(function(e){e[e.Draft=0]="Draft",e[e.Activated=1]="Activated"})(uC||(T.StateCode=uC={}));var cC;(function(e){e[e.Draft=1]="Draft",e[e.Activated=2]="Activated"})(cC||(T.StatusCode=cC={}));var dC;(function(e){e[e.Enabled=0]="Enabled",e[e.Disabled=1]="Disabled"})(dC||(T.StateCodeEnabledDisabled=dC={}));var fC;(function(e){e[e.Enabled=1]="Enabled",e[e.Disabled=2]="Disabled"})(fC||(T.StatusCodeEnabledDisabled=fC={}));var pC;(function(e){e[e.Definition=1]="Definition",e[e.Activation=2]="Activation",e[e.Template=3]="Template"})(pC||(T.WorkflowTypeCode=pC={}));var mC;(function(e){e[e.User=1]="User",e[e.BusinessUnit=2]="BusinessUnit",e[e.ParentChildBusinessUnit=3]="ParentChildBusinessUnit",e[e.Organization=4]="Organization"})(mC||(T.WorkflowScope=mC={}));var hC;(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"})(hC||(T.WorkflowCategory=hC={}));var gC;(function(e){e[e.None=-1]="None",e[e.BusinessFlow=0]="BusinessFlow",e[e.TaskFlow=1]="TaskFlow"})(gC||(T.BusinessProcessType=gC={}));var yC;(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"})(yC||(T.AppSubType=yC={}));var bC;(function(e){e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(bC||(T.RelationshipType=bC={}));var vC;(function(e){e.ManyToOneRelationship="ManyToOneRelationship",e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(vC||(T.RelationshipTypeExt=vC={}));var wC;(function(e){e.NoCascade="NoCascade",e.Cascade="Cascade",e.Active="Active",e.UserOwned="UserOwned",e.RemoveLink="RemoveLink",e.Restrict="Restrict"})(wC||(T.CascadeType=wC={}));var CC;(function(e){e.None="None",e.Append="Append",e.ParentChild="ParentChild",e.Pointer="Pointer",e.Inheritance="Inheritance"})(CC||(T.RelationshipSecurityTypes=CC={}));var EC;(function(e){e[e.Active=1]="Active",e[e.Inactive=2]="Inactive"})(EC||(T.ViewStatusCode=EC={}));var AC;(function(e){e[e.Active=0]="Active",e[e.Inactive=1]="Inactive"})(AC||(T.ViewStateCode=AC={}));var SC;(function(e){e.Active="Active",e.Failed="Failed",e.InProgress="InProgress",e.Pending="Pending"})(SC||(T.EntityKeyIndexStatus=SC={}));var NC;(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"})(NC||(T.SolutionComponentTypeCode=NC={}));var _C;(function(e){e[e.IncludeSubcomponents=0]="IncludeSubcomponents",e[e.DoNotIncludeSubcomponents=1]="DoNotIncludeSubcomponents",e[e.IncludeAsShellOnly=2]="IncludeAsShellOnly"})(_C||(T.RootComponentBehavior=_C={}));var Vc;(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"})(Vc||(T.SolutionComponentTypeCodeExt=Vc={}));var Gc;(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"})(Gc||(T.EntityTypeCode=Gc={}));var TC;(function(e){e.MultiSelectPicklist="MultiSelectPicklist",e.File="File",e.Image="Image"})(TC||(T.SolutionComponentVirtualAttributeSubtype=TC={}));function oq(e){let t=Vc[e];return Gc[t]}T.SolutionComponentTypeCodeToEntityTypeCodeExt=oq;function aq(e){let t=Gc[e];return Vc[t]}T.SolutionEntityTypeCodeExtToComponentTypeCode=aq;var DC;(function(e){e.Active="Active",e.Auto="Auto",e.Disabled="Disabled",e.Inactive="Inactive"})(DC||(T.ImeMode=DC={}));var IC;(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"})(IC||(T.SourceType=IC={}));var OC;(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"})(OC||(T.StringFormatName=OC={}));var PC;(function(e){e[e.PrecisionProperty=0]="PrecisionProperty",e[e.Organization=1]="Organization",e[e.TransactionCurrency=2]="TransactionCurrency"})(PC||(T.PrecisionSource=PC={}));var RC;(function(e){e.UserLocal="UserLocal",e.DateOnly="DateOnly",e.TimeZoneIndependent="TimeZoneIndependent"})(RC||(T.DateTimeBehavior=RC={}));var LC;(function(e){e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(LC||(T.DateTimeFormat=LC={}));var kC;(function(e){e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(kC||(T.IntegerFormat=kC={}));var $C;(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"})($C||(T.WebResourceTypeCode=$C={}));var xC;(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"})(xC||(T.SdkMessageProcessingStage=xC={}));var FC;(function(e){e[e.ServerOnly=0]="ServerOnly",e[e.OutlookClientOnly=1]="OutlookClientOnly",e[e.Both=2]="Both"})(FC||(T.SupportedDeployment=FC={}));var MC;(function(e){e[e.Synchronous=0]="Synchronous",e[e.Asynchronous=1]="Asynchronous"})(MC||(T.SdkMessageProcessingMode=MC={}));var UC;(function(e){e[e.ReportingServicesReport=1]="ReportingServicesReport",e[e.OtherReport=2]="OtherReport",e[e.LinkedReport=3]="LinkedReport"})(UC||(T.ReportTypeCode=UC={}));var BC;(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"})(BC||(T.ConnectionRoleCategory=BC={}));var qC;(function(e){e[e.Name=1]="Name",e[e.Address=2]="Address"})(qC||(T.ServiceNamespaceFormat=qC={}));var VC;(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"})(VC||(T.ServiceEndpointContract=VC={}));var GC;(function(e){e[e.Normal=1]="Normal",e[e.Federated=2]="Federated"})(GC||(T.ServiceEndpointConnectionMode=GC={}));var WC;(function(e){e.CannotDeleteInUseComponent="0x8004f01f",e.CannotDeleteInUseAttribute="0x80048418",e.CannotDeleteInUseOptionSet="0x80048417",e.CannotDeleteInUseEntity="0x80048420",e.CannotUninstallWithDependencies="0x8004F01D"})(WC||(T.DeleteDependencyErrorCode=WC={}));var zC;(function(e){e.SystemAdministrator="627090FF-40A3-4053-8790-584EDC5BE201",e.SystemCustomizer="119F245C-3CC8-4B62-B31C-D1A046CED15D"})(zC||(T.DefaultRoleTemplates=zC={}));var jC;(function(e){e[e.DefaultTeamPrivilege=0]="DefaultTeamPrivilege",e[e.DirectUserAndTeamPrivilege=1]="DirectUserAndTeamPrivilege"})(jC||(T.RoleInheritance=jC={}));var HC;(function(e){e[e.NotSpecified=0]="NotSpecified",e[e.CustomConnector=1]="CustomConnector"})(HC||(T.ConnectorTypeEnum=HC={}));var KC;(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"})(KC||(T.EnvironmentVariableDefinitionTypeEnum=KC={}));var JC;(function(e){e[e.Owner=0]="Owner",e[e.Access=1]="Access",e[e.AADSecurityGroup=2]="AADSecurityGroup",e[e.AADOfficeGroup=3]="AADOfficeGroup"})(JC||(T.TeamTypeEnum=JC={}));var YC;(function(e){e.Bots="bots"})(YC||(T.KnownCustomSolutionComponentEntitySetName=YC={}));var QC;(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"})(QC||(T.QueryType=QC={}))});var Q=v(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.IncompatibleWorkspaceError=X.PathTraversalError=X.AmbiguousArtifactError=X.JsonPointerError=X.NotImplementedError=X.WorkspaceOrgMismatchError=X.WorkspaceNotInitializedError=X.attachCause=X.ConnectionError=X.VersionConflictError=X.LocalEditsWouldBeLostError=X.StaleArtifactError=X.InvalidArgumentError=X.ValidationError=X.PathNotFoundError=X.ArtifactNotFoundError=X.readPcfRegistrationProgress=X.withPcfRegistrationProgress=X.readCleanupWarnings=X.withCleanupWarnings=X.readPartialEnrichment=X.withPartialEnrichment=X.readPartialTokens=X.withPartialTokens=X.SdkError=void 0;var _t=class extends Error{constructor(t,r){super(r),this.code=t,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}};X.SdkError=_t;var XC=Symbol.for("cds-maker-sdk.partialWriteTokens");function sq(e,t){return typeof e=="object"&&e!==null&&(e[XC]=t),e}X.withPartialTokens=sq;function lq(e){return Wc(e,XC)}X.readPartialTokens=lq;function Wc(e,t){let r=e;for(let n=0;r&&typeof r=="object"&&n<8;n++){let i=r[t];if(i&&typeof i=="object")return i;r=r.cause}}var ZC=Symbol.for("cds-maker-sdk.partialDefaultViewEnrichment");function uq(e,t){return typeof e=="object"&&e!==null&&(e[ZC]=t),e}X.withPartialEnrichment=uq;function cq(e){return Wc(e,ZC)}X.readPartialEnrichment=cq;var qm=Symbol.for("cds-maker-sdk.cleanupWarnings");function dq(e,t){if(typeof e=="object"&&e!==null&&t.length>0){let r=e,n=r[qm];r[qm]=[...Array.isArray(n)?n:[],...t]}return e}X.withCleanupWarnings=dq;function fq(e){let t=Wc(e,qm);return t?[...t]:void 0}X.readCleanupWarnings=fq;var eE=Symbol.for("cds-maker-sdk.pcfRegistrationProgress");function tE(e){return{...e,written:[...e.written],unconfirmed:[...e.unconfirmed],published:[...e.published],publishedUnknown:[...e.publishedUnknown],temporaries:[...e.temporaries]}}function pq(e,t){return typeof e=="object"&&e!==null&&(e[eE]=tE(t)),e}X.withPcfRegistrationProgress=pq;function mq(e){let t=Wc(e,eE);return t?tE(t):void 0}X.readPcfRegistrationProgress=mq;var Vm=class extends _t{constructor(t,r){super("ARTIFACT_NOT_FOUND",`Artifact ${t}/${r} not found in workspace`),this.type=t,this.id=r}};X.ArtifactNotFoundError=Vm;var Gm=class extends _t{constructor(t,r,n){super("PATH_NOT_FOUND",`Path ${n} not found in ${t}/${r}`),this.type=t,this.id=r,this.pointer=n}};X.PathNotFoundError=Gm;var Wm=class extends _t{constructor(t,r,n,i){var o,a,s,l;let u=Array.isArray(n)?n:[{pointer:n,rule:i??"invalid",message:i??"invalid"}];super("VALIDATION_ERROR",`Validation failed for ${t}/${r}:`+u.map(c=>` \u2022 ${c.pointer}: ${c.message} [${c.rule}]`).join(`-`)),this.type=t,this.id=r,this.issues=u,this.pointer=(a=(o=u[0])===null||o===void 0?void 0:o.pointer)!==null&&a!==void 0?a:"",this.rule=(l=(s=u[0])===null||s===void 0?void 0:s.rule)!==null&&l!==void 0?l:"invalid"}};X.ValidationError=rm;var nm=class extends gt{constructor(t){super("INVALID_ARGUMENT",t)}};X.InvalidArgumentError=nm;var im=class extends gt{constructor(t,r,n,i="revalidated"){super("STALE_ARTIFACT",i==="pushed"?`Cannot apply the edit at ${n} to ${t}/${r}: a push made after this pointer's copy was read replaced the local copy with the record the server holds, which differs from that copy (ids and defaults the SDK filled in at save, a rewrite the platform made on save, or another writer's save), so the pointer may now identify a different node. Read the whole artifact (getArtifact), re-derive the pointer, and retry.`:`Cannot apply the edit at ${n} to ${t}/${r}: the cached copy was stale and the server copy has since changed, so any pointer derived from the old copy may now identify a different node. The local copy has been refreshed \u2014 re-read the artifact, re-derive the pointer, and retry.`),this.type=t,this.id=r,this.pointer=n,this.reason=i}};X.StaleArtifactError=im;var om=class extends gt{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}};X.LocalEditsWouldBeLostError=om;var am=class extends gt{constructor(t,r,n,i,o){super("VERSION_CONFLICT",`Version conflict for ${t}/${r}: local=${n??"(none)"}, server=${i??"(none)"}. Re-fetch and reapply changes.${o?` ${o}`:""}`),this.type=t,this.id=r,this.localEtag=n,this.serverEtag=i,this.detail=o}};X.VersionConflictError=am;var sm=class extends gt{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,Object.defineProperty(this,"cause",{value:i,enumerable:!1,writable:!1,configurable:!0})}};X.ConnectionError=sm;function mU(e,t){return typeof e=="object"&&e!==null&&Object.defineProperty(e,"cause",{value:t,enumerable:!1,writable:!0,configurable:!0}),e}X.attachCause=mU;var lm=class extends gt{constructor(t){super("WORKSPACE_NOT_INITIALIZED",`Workspace not initialized at ${t}. Call initWorkspace() first.`),this.workspacePath=t}};X.WorkspaceNotInitializedError=lm;var um=class extends gt{constructor(t,r){super("WORKSPACE_ORG_MISMATCH",`This workspace belongs to ${t?`'${t}'`:"no recorded org"}, but this SDK targets '${r}'. Its local copies, baselines and cached metadata are that org's, so nothing was read or written. Use one workspace per org, or call cleanWorkspace() to discard this workspace's contents and bind it to '${r}'.`),this.workspaceInstanceUrl=t,this.instanceUrl=r}};X.WorkspaceOrgMismatchError=um;var cm=class extends gt{constructor(t,r){super("NOT_IMPLEMENTED",`Operation '${t}' is not implemented yet${r?`: ${r}`:""}.`),this.operation=t}};X.NotImplementedError=cm;var dm=class extends gt{constructor(t,r){super("INVALID_JSON_POINTER",`Invalid JSON Pointer '${t}': ${r}`),this.pointer=t}};X.JsonPointerError=dm;var fm=class extends gt{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}};X.AmbiguousArtifactError=fm;var pm=class extends gt{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}};X.PathTraversalError=pm;var mm=class extends gt{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}};X.IncompatibleWorkspaceError=mm});var ue=v(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.odataQuery=Xe.normalizeGuid=Xe.createSafeXmlElement=Xe.assertNoControlChars=Xe.assertODataName=Xe.assertXmlName=Xe.xmlText=Xe.odataPathLiteral=Xe.odataLiteral=void 0;var bc=Q();function rC(e){return String(e??"").replace(/'/g,"''")}Xe.odataLiteral=rC;function hU(e){return encodeURIComponent(rC(e))}Xe.odataPathLiteral=hU;function gU(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}Xe.xmlText=gU;function nC(e,t){let r=String(e??""),n=/^[A-Za-z_][0-9A-Za-z_.-]*$/,i=r.split(":");if(!(i.length<=2&&i.every(a=>n.test(a))&&!/^xmlns/i.test(r)))throw new bc.InvalidArgumentError(`${t} must be a valid XML element name (got '${e}')`);return e}Xe.assertXmlName=nC;function yU(e,t){let r=String(e??"");if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new bc.InvalidArgumentError(`${t} must be a valid OData identifier (letters, digits, underscore): got '${e}'`);return e}Xe.assertODataName=yU;function bU(e,t){if(/[\u0000-\u001F\u007F]/.test(String(e??"")))throw new bc.InvalidArgumentError(`${t} must not contain control characters (including CR/LF): they would inject additional lines into the request`);return e}Xe.assertNoControlChars=bU;function vU(e,t,r){return e.createElement(nC(t,r))}Xe.createSafeXmlElement=vU;var wU=/^[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 CU(e,t){let r=String(e??""),n=r.length===38&&r.startsWith("{")&&r.endsWith("}")?r.slice(1,-1):r;if(!wU.test(n))throw new bc.InvalidArgumentError(`${t} must be a valid GUID (got '${e}')`);return n.toLowerCase()}Xe.normalizeGuid=CU;function EU(e){let t=[];for(let[r,n]of e)n!=null&&n!==""&&t.push(`${r}=${encodeURIComponent(String(n))}`);return t.length>0?`?${t.join("&")}`:""}Xe.odataQuery=EU});var ye=v(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.nowIso=j.isAlreadyDeleted=j.deleteRecord=j.resendAppSearchIndexRace=j.resendDeadlockVictim=j.resendWhile=j.isAppSearchIndexRace=j.namesAppSearchIndexRace=j.isTransactionNotStarted=j.TRANSACTION_NOT_STARTED_CODE=j.LOCK_BACKOFF_MS=j.isConcurrencyLockRefusal=j.CONCURRENCY_LOCK_CODE=j.AMBIGUOUS_WRITE_STATUSES=j.DEADLOCK_BACKOFF_MS=j.isSqlDeadlockVictim=j.ensureSuccess=j.resolveCreatedId=j.requireCreatedId=j.withClientMintedId=j.readCreatedId=j.readRowEtag=j.readEtag=j.requireEtag=j.isVersionToken=j.echoWrite=j.UPDATE_NO_ETAG_CODE=j.VERSION_CONFLICT_CODE=void 0;var La=Q(),ka=ue();j.VERSION_CONFLICT_CODE="VERSION_CONFLICT";j.UPDATE_NO_ETAG_CODE="ARTIFACT_UPDATE_NO_ETAG";function AU(e,t){return{query:`?$select=${encodeURIComponent(e)}`,options:{headers:{...t??{},Prefer:"return=representation"}}}}j.echoWrite=AU;function iC(e){return typeof e=="string"&&e.trim()!==""&&e.trim()!=="*"}j.isVersionToken=iC;function SU(e,t,r){if(!iC(e))throw new La.SdkError(j.UPDATE_NO_ETAG_CODE,`Refusing to push ${t} '${r}': ${e?`the concurrency token held for it ('${e}') is not a version`:"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}j.requireEtag=SU;function oC(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}j.readEtag=oC;async function NU(e,t,r,n){let i=`/${t}(${n})${(0,ka.odataQuery)([["$select",r]])}`;return oC(ym(await e.get(i),e.apiUrl(i)))}j.readRowEtag=NU;function gm(e,t){var r;let n=e.body;if(n&&typeof n[t]=="string")return(0,ka.normalizeGuid)(n[t],t);let i=(r=e.headers)!==null&&r!==void 0?r:{};for(let o of Object.keys(i))if(o.toLowerCase()==="odata-entityid"){let a=/\(([0-9a-fA-F-]{36})\)/.exec(i[o]);if(a)return(0,ka.normalizeGuid)(a[1],t)}return null}j.readCreatedId=gm;function _U(e,t,r){return r?{...e,[t]:(0,ka.normalizeGuid)(r,t)}:e}j.withClientMintedId=_U;function TU(e,t,r){let n=gm(e,t);if(!n)throw new La.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`);return n}j.requireCreatedId=TU;function DU(e,t,r,n){let i=gm(e,t);if(i)return i;if(n)return(0,ka.normalizeGuid)(n,t);throw new La.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`)}j.resolveCreatedId=DU;function ym(e,t){if(e.status===412)throw new La.SdkError(j.VERSION_CONFLICT_CODE,`Version conflict (412) from ${t}`);if(e.status<200||e.status>=300)throw new La.ConnectionError(t,e.status,kU(e.body),e.body);return e}j.ensureSuccess=ym;function aC(e){if(e.status!==500||e.body===void 0||e.body===null)return!1;let t=typeof e.body=="string"?e.body:JSON.stringify(e.body);return/\bSql Number:\s*1205\b/i.test(t)}j.isSqlDeadlockVictim=aC;j.DEADLOCK_BACKOFF_MS=[1e3,2e3,4e3];j.AMBIGUOUS_WRITE_STATUSES=new Set([408,502,503,504]);j.CONCURRENCY_LOCK_CODE="0x80071151";function IU(e){var t,r;if(e.status!==429)return!1;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return typeof n=="string"&&n.toLowerCase()===j.CONCURRENCY_LOCK_CODE}j.isConcurrencyLockRefusal=IU;j.LOCK_BACKOFF_MS=[2e3,3e3,...Array.from({length:35},()=>5e3)];j.TRANSACTION_NOT_STARTED_CODE="0x80040251";function OU(e){var t,r;if(e.status!==500)return!1;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return typeof n=="string"&&n.toLowerCase()===j.TRANSACTION_NOT_STARTED_CODE}j.isTransactionNotStarted=OU;var PU=/(?:^|[^a-z0-9_])AppModule_DVTableSearch_M365AppModuleId(?![a-z0-9_])/i;function sC(e){return PU.test(e)&&/\bSql Number:\s*547\b/i.test(e)}j.namesAppSearchIndexRace=sC;function lC(e){return e.status!==400||e.body===void 0||e.body===null?!1:sC(typeof e.body=="string"?e.body:JSON.stringify(e.body))}j.isAppSearchIndexRace=lC;async function bm(e,t,r=j.DEADLOCK_BACKOFF_MS){for(let n=0;;n+=1){let i=await t();if(n>=r.length||!e(i))return i;await new Promise(o=>setTimeout(o,r[n]))}}j.resendWhile=bm;function RU(e){return bm(aC,e,j.DEADLOCK_BACKOFF_MS)}j.resendDeadlockVictim=RU;function LU(e){return bm(lC,e,j.DEADLOCK_BACKOFF_MS)}j.resendAppSearchIndexRace=LU;function kU(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 xU(e,t,r,n){let i=(0,ka.normalizeGuid)(r,"id"),o=`/${t}(${i})`;ym(await e.delete(o,n?{headers:{"If-Match":n}}:void 0),e.apiUrl(o))}j.deleteRecord=xU;function $U(e){return e instanceof La.ConnectionError&&e.statusCode===404}j.isAlreadyDeleted=$U;function FU(){return new Date().toISOString()}j.nowIso=FU});var Xt=v(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.describeMalformedValue=xa.collectPages=void 0;var uC=ye(),vm=Q();async function MU(e,t,r,n,i){let o=[],a=new Set,s=e.apiUrl(t),l=(0,uC.ensureSuccess)(await e.get(t,i),s);for(n?.(l);;){let u=l.body,c=u?.value;if(!Array.isArray(c))throw new vm.ConnectionError(s,l.status,`${r}: paginated read returned a malformed page \u2014 expected an OData 'value' array but got ${wm(c)}; refusing to return partial results.`);for(let f of c)o.push(f);let d=u?.["@odata.nextLink"];if(d==null)break;if(typeof d!="string"||d.length===0)throw new vm.ConnectionError(s,l.status,`${r}: paginated read returned a malformed @odata.nextLink (${wm(d)}); cannot follow it, and refusing to return partial results.`);if(a.has(d))throw new vm.InvalidArgumentError(`${r}: aborting pagination \u2014 the server returned a repeated @odata.nextLink ('${d}'), which would loop indefinitely.`);a.add(d),s=d,l=(0,uC.ensureSuccess)(await e.getAbsolute(d,i),d)}return o}xa.collectPages=MU;function wm(e){return e===null?"null":e===void 0?"undefined (missing)":`a ${typeof e}`}xa.describeMalformedValue=wm});var Cm=v(ko=>{"use strict";Object.defineProperty(ko,"__esModule",{value:!0});ko.assertWorkflowKind=ko.WORKFLOW_KIND_MISMATCH_CODE=void 0;var Lo=Ji(),UU=Q(),cC=ye(),BU=ue();ko.WORKFLOW_KIND_MISMATCH_CODE="WORKFLOW_KIND_MISMATCH";var dC={[Lo.WorkflowCategory.Workflow]:"classic workflow",[Lo.WorkflowCategory.Dialog]:"dialog",[Lo.WorkflowCategory.BusinessRule]:"business rule",[Lo.WorkflowCategory.Action]:"custom action",[Lo.WorkflowCategory.BusinessProcessFlow]:"business process flow",[Lo.WorkflowCategory.Flow]:"cloud flow",[Lo.WorkflowCategory.UIFlow]:"desktop flow"};async function qU(e,t,r){var n,i;let o=`/workflows(${t})${(0,BU.odataQuery)([["$select","category"]])}`,a=await e.get(o);if(a.status===404)return null;(0,cC.ensureSuccess)(a,e.apiUrl(o));let s=(n=a.body)===null||n===void 0?void 0:n.category,l=typeof s=="number"?s:typeof s=="string"&&s!==""?Number(s):NaN;if(l!==r){let u=Number.isFinite(l)?`a ${(i=dC[l])!==null&&i!==void 0?i:"process"} (category ${l})`:"a process whose category could not be read";throw new UU.SdkError(ko.WORKFLOW_KIND_MISMATCH_CODE,`Refusing to delete workflow '${t}' as a ${dC[r]}: it is ${u}. Nothing was changed. Check the id.`)}return(0,cC.readEtag)(a)}ko.assertWorkflowKind=qU});var Am=v(Hr=>{"use strict";Object.defineProperty(Hr,"__esModule",{value:!0});Hr.deleteWorkflowResending=Hr.isWorkflowDeleteUnsettled=Hr.failedAfterResend=Hr.WORKFLOW_DELETE_UNSETTLED_CODE=void 0;var ml=Q(),fi=ye(),pC=ue();Hr.WORKFLOW_DELETE_UNSETTLED_CODE="WORKFLOW_DELETE_UNSETTLED";var mC=new WeakSet;function Em(e){return typeof e=="object"&&e!==null&&mC.add(e),e}function VU(e){return typeof e=="object"&&e!==null&&mC.has(e)}Hr.failedAfterResend=VU;function GU(e){return e instanceof ml.SdkError&&e.code===Hr.WORKFLOW_DELETE_UNSETTLED_CODE}Hr.isWorkflowDeleteUnsettled=GU;function WU(e,t){try{(0,fi.ensureSuccess)(e,t)}catch(r){return r}}function zU(e){return(0,fi.isSqlDeadlockVictim)(e)?"lost a SQL deadlock (HTTP 500, Sql Number 1205)":`lost its transaction (HTTP 500 ${fi.TRANSACTION_NOT_STARTED_CODE})`}async function fC(e,t){try{return(await e.get(`/workflows(${t})${(0,pC.odataQuery)([["$select","workflowid"]])}`)).status===404}catch{return!1}}async function jU(e,t,{bindingToken:r,kindName:n,deactivated:i=!1,resendDeadlockVictim:o=!1,ifMatchOnFirst:a=!1}){let s=(0,pC.normalizeGuid)(t,"id");if(a&&!r)throw new ml.InvalidArgumentError(`Refusing to delete ${n} '${s}': its delete must be conditional on a token this operation holds, and it holds none.`);let l=`/workflows(${s})`,u=e.apiUrl(l),c=m=>(0,fi.isTransactionNotStarted)(m)||o&&(0,fi.isSqlDeadlockVictim)(m),d=0,f,p;try{p=await(0,fi.resendWhile)(c,async()=>{d+=1;let m=d>1||a,h=await e.delete(l,m?{headers:{"If-Match":r}}:void 0);return f=f??h,h},r?fi.DEADLOCK_BACKOFF_MS:[])}catch(m){if(m instanceof ml.ConnectionError&&m.statusCode===0&&r&&await fC(e,s))return;throw d>1?Em(m):m}if(!(d>1&&p.status===404)){if(d>1&&p.status===412){let m=zU(f),h=new ml.SdkError(Hr.WORKFLOW_DELETE_UNSETTLED_CODE,`Deleting ${n} '${s}' ${m}, and its re-send was refused (HTTP 412): the row at that id is no longer the version this delete checked \u2014 it was edited, or deleted and re-created at the same id \u2014 so nothing more was deleted. `+(i?"This delete had deactivated the process first and has NOT re-activated it: it MAY be left DISABLED. ":"")+"Read the row before deleting it again.");throw Em((0,ml.attachCause)(h,WU(f,u)))}if(!(r&&fi.AMBIGUOUS_WRITE_STATUSES.has(p.status)&&await fC(e,s)))try{(0,fi.ensureSuccess)(p,u)}catch(m){throw d>1?Em(m):m}}}Hr.deleteWorkflowResending=jU});var Sm=v(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.businessRuleApi=xn.BUSINESS_RULE_LEFT_DEACTIVATED_CODE=xn.WFOM_API_UNAVAILABLE_CODE=void 0;var kn=Ji(),HU=Xt(),KU=Cm(),JU=Am(),Ft=ye(),pi=ue(),wc=Q();xn.WFOM_API_UNAVAILABLE_CODE="BUSINESS_RULE_API_UNAVAILABLE";xn.BUSINESS_RULE_LEFT_DEACTIVATED_CODE="BUSINESS_RULE_LEFT_DEACTIVATED";async function hC(e,t,r,n){let i=`/workflows(${XU})/Microsoft.Dynamics.CRM.${t}`;try{return(0,Ft.ensureSuccess)(await e.post(i,{Entity:r.Entity,WfomJson:r.WfomJson},{headers:n}),e.apiUrl(i))}catch(o){throw o?.statusCode!==404?o:new wc.SdkError(xn.WFOM_API_UNAVAILABLE_CODE,`Business-rule authoring (preview) is not enabled on this environment yet: it does not expose 'Microsoft.Dynamics.CRM.${t}'. The bound members are still rolling out, so re-check once the release flag reaches this environment. Nothing was written. The SDK does NOT fall back to generating workflow XAML: that covered only 4 of the 7 action types and would silently save a rule different from the one you wrote.`)}}async function YU(e,t){let r=`/workflows(${t})${(0,pi.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,Ft.readEtag)(n),statecode:typeof i?.statecode=="number"?i.statecode:null,statuscode:typeof i?.statuscode=="number"?i.statuscode:null}}catch{return null}}async function QU(e,t,r){let n=await YU(e,t);if(n===null||n.etag===null)throw new wc.SdkError(Ft.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 wc.SdkError(Ft.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 XU="00000000-0000-0000-0000-000000000000",vc={"Content-Type":"application/json",Accept:"application/json","OData-Version":"4.0","OData-MaxVersion":"4.0"},ZU="workflowid,name,description,primaryentity,statecode,category,type",eB="category eq 2 and type eq 1";async function gC(e,t,r){var n;if(r==="Draft")return null;let i=(0,pi.normalizeGuid)(t,"workflowid"),o=r==="Active",a={statecode:o?kn.StateCode.Activated:kn.StateCode.Draft,statuscode:o?kn.StatusCode.Activated:kn.StatusCode.Draft},s=`/workflows(${i})`,l=(0,Ft.ensureSuccess)(await e.patch(s,a,{headers:vc}),e.apiUrl(s));return(n=(0,Ft.readEtag)(l))!==null&&n!==void 0?n:await hl(e,i)}async function hl(e,t){let r=`/workflows(${t})${(0,pi.odataQuery)([["$select","workflowid"]])}`;try{let n=await e.get(r);return n.status>=200&&n.status<300?(0,Ft.readEtag)(n):null}catch{return null}}async function tB(e,t,r){let n=await hl(e,t),i=await r(),o=(0,Ft.readEtag)(i);if(o)return{response:i,etag:o};let a=await hl(e,t);return{response:i,etag:n!==null&&n===a?a:null}}xn.businessRuleApi={async get(e,t){let r=(0,pi.normalizeGuid)(t,"id"),n=`/workflows(${r})/Microsoft.Dynamics.CRM.RetrieveProcessWithWfomJson`,{response:i,etag:o}=await tB(e,r,async()=>(0,Ft.ensureSuccess)(await e.get(n),e.apiUrl(n)));return{raw:i.body,etag:o}},async list(e,t){let r=[eB];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,pi.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,pi.odataQuery)([["$select",ZU],["$filter",r.join(" and ")]])}`;return(await(0,HU.collectPages)(e,n,"listArtifacts('businessRule')")).map(o=>{var a,s;return{type:"businessRule",id:(a=o.workflowid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",entityLogicalName:o.primaryentity,isDirty:!1}})},async create(e,t){var r;let n=t,i=(0,pi.normalizeGuid)(n.Entity.workflowid,"workflowid"),o=await hC(e,"CreateProcessWithWfomJson",n,vc),a=(0,Ft.resolveCreatedId)(o,"workflowid","business rule",i),s=null;try{s=await gC(e,a,n.status)}catch(l){try{await(0,Ft.deleteRecord)(e,"workflows",a)}catch{}throw l}return{id:a,etag:(r=s??(0,Ft.readEtag)(o))!==null&&r!==void 0?r:await hl(e,a)}},async update(e,t,r,n){var i,o;let a=r,s=(0,pi.normalizeGuid)(t,"id"),l=`/workflows(${s})`,u={...vc,"If-Match":(0,Ft.requireEtag)(n,"business rule",s)},c=await QU(e,s,u["If-Match"]),d=c.statecode===kn.StateCode.Activated;d&&(0,Ft.ensureSuccess)(await e.patch(l,{statecode:kn.StateCode.Draft,statuscode:kn.StatusCode.Draft},{headers:u}),e.apiUrl(l));let f;try{f=await hC(e,"UpdateProcessWithWfomJson",a,u)}catch(m){if(d)try{(0,Ft.ensureSuccess)(await e.patch(l,{statecode:kn.StateCode.Activated,statuscode:(i=c.statuscode)!==null&&i!==void 0?i:kn.StatusCode.Activated},{headers:vc}),e.apiUrl(l))}catch(h){throw new wc.SdkError(xn.BUSINESS_RULE_LEFT_DEACTIVATED_CODE,`The business-rule write failed AND the rule could not be re-activated, so '${s}' is left DEACTIVATED (Draft) on the server. Re-activate it before relying on it. Original write failure: ${m instanceof Error?m.message:String(m)}. Restore failure: ${h instanceof Error?h.message:String(h)}`)}throw m}let p=await gC(e,s,a.status);return{id:s,etag:(o=p??(0,Ft.readEtag)(f))!==null&&o!==void 0?o:await hl(e,s)}},async delete(e,t){let r=(0,pi.normalizeGuid)(t,"id"),n=await(0,KU.assertWorkflowKind)(e,r,kn.WorkflowCategory.BusinessRule);return(0,JU.deleteWorkflowResending)(e,r,{bindingToken:n,kindName:"business rule"})}}});var Kr=v(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.publishBoundEntity=yt.boundEntityPublishScope=yt.publishGenPageById=yt.publishDashboardById=yt.publishWebResourceById=yt.publishEntity=yt.publishAppModule=yt.publishXml=void 0;var yC=ye(),gl=ue(),bC="/PublishXml";async function $a(e,t){(0,yC.ensureSuccess)(await(0,yC.resendDeadlockVictim)(()=>e.post(bC,{ParameterXml:t})),e.apiUrl(bC))}yt.publishXml=$a;function rB(e,t){return $a(e,`<importexportxml><appmodules><appmodule>${(0,gl.xmlText)(t)}</appmodule></appmodules></importexportxml>`)}yt.publishAppModule=rB;function vC(e,t){return $a(e,`<importexportxml><entities><entity>${(0,gl.xmlText)(t)}</entity></entities></importexportxml>`)}yt.publishEntity=vC;function nB(e,t){return $a(e,`<importexportxml><webresources><webresource>${(0,gl.xmlText)(t)}</webresource></webresources></importexportxml>`)}yt.publishWebResourceById=nB;function iB(e,t){return $a(e,`<importexportxml><dashboards><dashboard>${(0,gl.xmlText)(t)}</dashboard></dashboards></importexportxml>`)}yt.publishDashboardById=iB;function oB(e,t){return $a(e,`<importexportxml><uxagentprojects><uxagentproject>${(0,gl.xmlText)(t)}</uxagentproject></uxagentprojects></importexportxml>`)}yt.publishGenPageById=oB;function aB(e){let t=e?.entityLogicalName;return t?{envelope:"entity",entityLogicalName:t,blastRadiusWarning:"ENTITY_ENVELOPE_ALSO_SHIPS_UNRELATED_UNPUBLISHED_CHANGES"}:{envelope:"entity"}}yt.boundEntityPublishScope=aB;function sB(e,t){let r=t?.entityLogicalName;return r?vC(e,r):Promise.resolve()}yt.publishBoundEntity=sB});var Fa=v(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});Ec.JsonPointer=void 0;var xr=Q(),Cc=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 xr.JsonPointerError(t,'non-empty pointers must start with "/"');return t.substring(1).split("/").map(r=>{if(/~(?![01])/.test(r))throw new xr.JsonPointerError(t,`invalid '~' escape in token '${r}' (expected ~0 or ~1)`);return e.decodeToken(r)})}static compile(t){return t.length===0?"":"/"+t.map(r=>e.encodeToken(r)).join("/")}static resolve(t,r){let n=e.parse(r),i=t;for(let o of n)if(Array.isArray(i)){let a=e.toArrayIndex(o,i.length);if(a===void 0)return;i=i[a]}else if(i!==null&&typeof i=="object"){let a=i;if(e.isReservedToken(o)||!Object.prototype.hasOwnProperty.call(a,o))return;i=a[o]}else return;return i}static set(t,r,n){let i=e.parse(r);if(i.length===0)throw new xr.JsonPointerError(r,"cannot set the document root");let{parent:o,lastToken:a}=e.resolveParent(t,i,r);if(Array.isArray(o)){let s=e.toArrayIndex(a,o.length);if(s===void 0)throw new xr.JsonPointerError(r,`'${a}' is not a valid array index`);if(s>o.length)throw new xr.JsonPointerError(r,`array index '${a}' is out of range`);o[s]=n}else{if(e.isReservedToken(a))throw new xr.JsonPointerError(r,`refusing to write reserved property '${a}'`);o[a]=n}}static remove(t,r){let n=e.parse(r);if(n.length===0)throw new xr.JsonPointerError(r,"cannot remove the document root");let{parent:i,lastToken:o}=e.resolveParent(t,n,r);if(Array.isArray(i)){let a=e.toArrayIndex(o,i.length);if(a===void 0||a>=i.length)throw new xr.JsonPointerError(r,`array index '${o}' is out of range`);i.splice(a,1)}else{if(e.isReservedToken(o))throw new xr.JsonPointerError(r,`refusing to remove reserved property '${o}'`);delete i[o]}}static add(t,r,n,i){let o=e.parse(r);if(o.length>0&&o[o.length-1]==="-"){let l=e.compile(o.slice(0,-1)),u=e.resolve(t,l);if(!Array.isArray(u))throw new xr.JsonPointerError(r,"add target must be an array");u.push(n);return}let a=e.resolve(t,r);if(!Array.isArray(a))throw new xr.JsonPointerError(r,"add target must be an array");let s=i===void 0?a.length:i;if(s<0||s>a.length)throw new xr.JsonPointerError(r,`insert index ${s} is out of range`);a.splice(s,0,n)}static parent(t){let r=e.parse(t);return r.pop(),e.compile(r)}static lastToken(t){let r=e.parse(t);return r.length===0?"":r[r.length-1]}static append(t,r){return`${t}/${e.encodeToken(String(r))}`}static resolveParent(t,r,n){let i=r[r.length-1],o=e.compile(r.slice(0,-1)),a=e.resolve(t,o);if(a===null||typeof a!="object")throw new xr.JsonPointerError(n,"parent path does not resolve to an object or array");return{parent:a,lastToken:i}}static toArrayIndex(t,r){if(t==="-")return r;if(/^(0|[1-9][0-9]*)$/.test(t))return Number(t)}};Ec.JsonPointer=Cc;Cc.RESERVED_TOKENS=new Set(["__proto__","prototype","constructor"])});var CC=v(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});Ac.findElements=void 0;var wC=Fa();function lB(e,t){let r=[];return Nm(e,"",t,r),r}Ac.findElements=lB;function Nm(e,t,r,n){if(!(e===null||typeof e!="object"))if(r(e,t)&&n.push({pointer:t,value:e}),Array.isArray(e))e.forEach((i,o)=>{Nm(i,wC.JsonPointer.append(t,o),r,n)});else for(let i of Object.keys(e))Nm(e[i],wC.JsonPointer.append(t,i),r,n)}});var _m=v($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.assertMutationResult=$n.assertExistsResult=$n.assertReadResult=$n.assertStorageContract=void 0;var uB=["readText","writeTextAtomic","deleteFile","deleteByPrefix"],cB=["ensureContainer","exists"];function dB(e){if(typeof e!="object"||e===null)throw new Error("workspaceStorage must be an object implementing WorkspaceStorage.");for(let t of uB)if(typeof e[t]!="function")throw new Error(`workspaceStorage is missing the required method '${t}'.`);for(let t of cB){let r=e[t];if(r!==void 0&&typeof r!="function")throw new Error(`workspaceStorage.${t} must be a function when present.`)}return e}$n.assertStorageContract=dB;function fB(e,t){if(e===null||typeof e=="string")return e;throw new Error(`workspaceStorage.readText must resolve to a string or null for ${t}; got ${typeof e}. Absence is null \u2014 resolving undefined would make a present value look absent.`)}$n.assertReadResult=fB;function pB(e,t){if(typeof e=="boolean")return e;throw new Error(`workspaceStorage.exists must resolve to a boolean for ${t}; got ${typeof e}. A truthy non-boolean would make an absent value look present.`)}$n.assertExistsResult=pB;function mB(e,t){if(e!==void 0)throw new Error(`workspaceStorage.${t} must resolve to undefined; got ${typeof e}. A status-returning implementation would let a failed write be reported as a completed one.`)}$n.assertMutationResult=mB});var Tm=v(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});Ma.retryTransientIoAsync=Ma.retryTransientIo=void 0;var hB=new Set(["EPERM","EACCES","EBUSY","UNKNOWN"]),gB=5,EC=10;function yB(e){for(let t=1;;t+=1)try{return e()}catch(r){if(!AC(r,t))throw r;vB(EC*t)}}Ma.retryTransientIo=yB;async function bB(e){for(let t=1;;t+=1)try{return await e()}catch(r){if(!AC(r,t))throw r;await new Promise(n=>setTimeout(n,EC*t))}}Ma.retryTransientIoAsync=bB;function AC(e,t){let r=e.code;return t<gB&&!!r&&hB.has(r)}function vB(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{let t=Date.now()+e;for(;Date.now()<t;);}}});var DC=v($r=>{"use strict";Object.defineProperty($r,"__esModule",{value:!0});$r.canonicalArtifactId=$r.WorkspaceManager=$r.WORKSPACE_SCHEMA_VERSION=$r.retryTransientIo=void 0;var Mt=_m(),Fn=Q(),wB=Tm();Object.defineProperty($r,"retryTransientIo",{enumerable:!0,get:function(){return wB.retryTransientIo}});function SC(e){let t=e;return typeof t.pathFor=="function"&&typeof t.getRoot=="function"?e:null}$r.WORKSPACE_SCHEMA_VERSION=1;var Yi={form:"forms",view:"views",businessRule:"business-rules",app:"apps",command:"commands",chart:"charts",dashboard:"dashboards",genPage:"gen-pages",bpf:"business-process-flows"},CB="manifest.json",Ua=".metadata",Dm="entities";function NC(e){try{return Promise.resolve(e())}catch(t){return Promise.reject(t)}}function Im(e){if(e.schemaVersion!==void 0&&e.schemaVersion>$r.WORKSPACE_SCHEMA_VERSION)throw new Fn.IncompatibleWorkspaceError(e.schemaVersion,$r.WORKSPACE_SCHEMA_VERSION)}function _C(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Sc(e){return e.trim().toLowerCase().replace(/\/+$/,"")}var Om=class{withManifest(t){let r=this.manifestQueue.then(t,t);return this.manifestQueue=r.then(()=>{},()=>{}),r}constructor(t,r,n){if(this.workspaceLabel=t,this.instanceUrl=r,this.manifestQueue=Promise.resolve(),this.bound=!1,n==null)throw new Error("WorkspaceManager requires a WorkspaceStorage. Node callers can build one with `createNodeWorkspaceStorage(path)` from '@maker-studio/cds-maker-sdk/node'.");this.storage=n}artifactKey(t,r){return this.assertSafeId(r),[Yi[t],`${yl(r)}.json`]}metaKey(t,r){return this.assertSafeId(r),[Ua,Yi[t],`${yl(r)}.meta.json`]}entityKey(t){return this.assertSafeId(t),[Ua,Dm,`${t.toLowerCase()}.json`]}fsStore(){let t=SC(this.storage);if(!t)throw new Error("This workspace is not filesystem-backed, so it has no physical paths. Use the artifact/metadata/manifest accessors instead of the path helpers.");return t}getRoot(){let t=SC(this.storage);return t?t.getRoot():this.workspaceLabel}getArtifactDir(t){return this.fsStore().pathFor([Yi[t]])}getArtifactFilePath(t,r){return this.fsStore().pathFor(this.artifactKey(t,r))}getMetaFilePath(t,r){return this.fsStore().pathFor(this.metaKey(t,r))}getEntityMetaFilePath(t){return this.fsStore().pathFor(this.entityKey(t))}assertSafeId(t){if(typeof t!="string"||t.length===0||/[\u0000-\u001f]/.test(t)||t.includes("/")||t.includes("\\")||t.includes(":")||t==="."||t===".."||t.includes(".."))throw new Fn.PathTraversalError(String(t),this.workspaceLabel)}get manifestKey(){return[CB]}assertDataKey(t,r){if(!Array.isArray(t)||t.length<2)throw new Fn.InvalidArgumentError(`${r} writes only inside the workspace's folders; '${String(t)}' is at its root, where only the manifest lives \u2014 and the manifest is changed only by the workspace itself.`);t.forEach(n=>this.assertSafeId(n))}async init(){let t=await this.withManifest(async()=>{let r=await this.readStoredManifest();return r.present&&this.assertBoundHere(r.value),r.present});await this.ensureLayout(),t||await this.withManifest(async()=>{let r=await this.readStoredManifest();if(r.present){this.assertBoundHere(r.value);return}let n={instanceUrl:this.instanceUrl,createdAt:new Date().toISOString(),artifacts:[]};await this.writeManifest(n)}),this.bound=!0}async readStoredManifest(){let t=(0,Mt.assertReadResult)(await this.storage.readText(this.manifestKey),"manifest.json");return t===null?{present:!1}:{present:!0,value:JSON.parse(t)}}async ensureLayout(){if(!this.storage.ensureContainer)return;let t=this.storage.ensureContainer.bind(this.storage),r=[[Ua,Dm]];for(let i of Object.keys(Yi))r.push([Yi[i]],[Ua,Yi[i]]);let n=await Promise.allSettled(r.map(i=>NC(()=>t(i))));for(let i of n){if(i.status==="rejected")throw i.reason;(0,Mt.assertMutationResult)(i.value,"ensureContainer")}}async isInitialized(){return this.storage.exists?(0,Mt.assertExistsResult)(await this.storage.exists(this.manifestKey),"manifest.json"):(0,Mt.assertReadResult)(await this.storage.readText(this.manifestKey),"manifest.json")!==null}async ensureInitialized(){if(!this.bound){await this.verifyBinding();return}if(!await this.isInitialized())throw new Fn.WorkspaceNotInitializedError(this.workspaceLabel)}async ensureReady(){await this.ensureInitialized()}async ensureBound(){this.bound||await this.verifyBinding()}verifyBinding(){if(!this.verifying){let t=()=>{this.verifying=void 0};this.verifying=this.readAndCheckBinding().then(t,r=>{throw t(),r})}return this.verifying}async readAndCheckBinding(){let t=await this.readStoredManifest();if(!t.present)throw new Fn.WorkspaceNotInitializedError(this.workspaceLabel);this.assertBoundHere(t.value),this.bound=!0}assertBoundHere(t){if(!_C(t))throw new Fn.WorkspaceOrgMismatchError("",this.instanceUrl);Im(t);let r=typeof t.instanceUrl=="string"?t.instanceUrl.trim():"",n=Sc(r);if(!n||n!==Sc(this.instanceUrl))throw new Fn.WorkspaceOrgMismatchError(r,this.instanceUrl)}async clean(){let t=await this.readStoredManifest();if(!t.present||!_C(t.value))throw new Fn.WorkspaceNotInitializedError(this.workspaceLabel);let r=t.value;Im(r);let n=Object.keys(Yi).map(o=>[Yi[o]]);n.push([Ua]);let i=await Promise.allSettled(n.map(o=>NC(()=>this.storage.deleteByPrefix(o))));for(let o of i){if(o.status==="rejected")throw o.reason;(0,Mt.assertMutationResult)(o.value,"deleteByPrefix")}await this.ensureLayout(),await this.withManifest(()=>this.writeManifest({...r,instanceUrl:this.instanceUrl,artifacts:[],lastSyncAt:void 0})),this.bound=!0}async readArtifact(t,r){return await this.ensureInitialized(),this.readJsonUnchecked(this.artifactKey(t,r))}async readArtifactWithText(t,r){await this.ensureInitialized();let n=this.artifactKey(t,r),i=(0,Mt.assertReadResult)(await this.storage.readText(n),n.join("/"));return i===null?null:{artifact:JSON.parse(i),text:i}}async writeArtifact(t,r,n,i){await this.ensureInitialized();let o=TC(n);if(i!==void 0&&o===i){await this.upsertManifestEntry(t,r,n,{unlessCurrent:!0});return}(0,Mt.assertMutationResult)(await this.storage.writeTextAtomic(this.artifactKey(t,r),o),"writeTextAtomic"),await this.upsertManifestEntry(t,r,n)}async deleteArtifact(t,r){await this.ensureInitialized(),(0,Mt.assertMutationResult)(await this.storage.deleteFile(this.artifactKey(t,r)),"deleteFile"),(0,Mt.assertMutationResult)(await this.storage.deleteFile(this.metaKey(t,r)),"deleteFile");let n=yl(r);await this.withManifest(async()=>{let i=await this.getManifest();i.artifacts=i.artifacts.filter(o=>!(o.type===t&&o.id===n)),await this.writeManifest(i)})}async readMeta(t,r){return await this.ensureBound(),this.readJsonUnchecked(this.metaKey(t,r))}async writeMeta(t,r,n){await this.ensureBound(),await this.writeJsonUnchecked(this.metaKey(t,r),n)}async listArtifacts(t,r){return await this.ensureInitialized(),(await this.getManifest()).artifacts.filter(n=>!(t&&n.type!==t||r?.entityLogicalName&&n.entityLogicalName!==r.entityLogicalName))}async readEntityMetadata(t){await this.ensureInitialized();let r=await this.readJsonUnchecked(this.entityKey(t));return!r||typeof r.schemaName!="string"||typeof r.primaryNameAttribute!="string"||typeof r.primaryIdAttribute!="string"||typeof r.isCustomEntity!="boolean"?null:r}async writeEntityMetadata(t,r){await this.ensureInitialized(),await this.writeJsonUnchecked(this.entityKey(t),r)}async dropEntityMetadata(t){if(await this.ensureInitialized(),t===void 0){(0,Mt.assertMutationResult)(await this.storage.deleteByPrefix([Ua,Dm]),"deleteByPrefix");return}(0,Mt.assertMutationResult)(await this.storage.deleteFile(this.entityKey(t)),"deleteFile")}async getManifest(){await this.ensureInitialized();let t=await this.readJsonUnchecked(this.manifestKey);if(!t)throw new Fn.WorkspaceNotInitializedError(this.workspaceLabel);return Im(t),t}async writeManifest(t){await this.writeJsonUnchecked(this.manifestKey,{...t,schemaVersion:$r.WORKSPACE_SCHEMA_VERSION})}async updateManifest(t){await this.withManifest(async()=>{let r=await this.getManifest();if(t.instanceUrl!==void 0&&Sc(String(t.instanceUrl))!==Sc(r.instanceUrl))throw new Fn.InvalidArgumentError("updateManifest cannot change the workspace's org: it is bound to the org it was created for. cleanWorkspace() discards its contents and binds it to the org of the SDK that calls it.");await this.writeManifest({...r,...t,instanceUrl:r.instanceUrl})})}async upsertManifestEntry(t,r,n,i={}){await this.withManifest(async()=>{let o=await this.getManifest(),a=yl(r),s=n,l=typeof s.name=="string"?s.name:`${t}:${a}`,u=typeof s.entityLogicalName=="string"?s.entityLogicalName:void 0,c=o.artifacts.find(d=>d.type===t&&d.id===a);i.unlessCurrent&&c?.name===l&&c.entityLogicalName===u||(c?(c.name=l,c.entityLogicalName=u):o.artifacts.push({type:t,id:a,name:l,entityLogicalName:u,isDirty:!1}),await this.writeManifest(o))})}async readJson(t){return await this.ensureBound(),this.readJsonUnchecked(t)}async writeJson(t,r){this.assertDataKey(t,"writeJson"),await this.ensureBound(),await this.writeJsonUnchecked(t,r)}async removeFile(t){this.assertDataKey(t,"removeFile"),await this.ensureBound(),(0,Mt.assertMutationResult)(await this.storage.deleteFile(t),"deleteFile")}async exists(t){return await this.ensureBound(),this.storage.exists?(0,Mt.assertExistsResult)(await this.storage.exists(t),t.join("/")):(0,Mt.assertReadResult)(await this.storage.readText(t),t.join("/"))!==null}async readJsonUnchecked(t){let r=(0,Mt.assertReadResult)(await this.storage.readText(t),t.join("/"));return r===null?null:JSON.parse(r)}async writeJsonUnchecked(t,r){(0,Mt.assertMutationResult)(await this.storage.writeTextAtomic(t,TC(r)),"writeTextAtomic")}};$r.WorkspaceManager=Om;function TC(e){return`${JSON.stringify(e,null,2)}-`}function yl(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()}$r.canonicalArtifactId=yl});var Pm=v(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.deepEqual=Ba.deepDiff=void 0;var EB=Fa();function AB(e,t){let r=[];return OC(e,t,"",r,0),r}Ba.deepDiff=AB;var Nc=Symbol("missing"),_c=512;function OC(e,t,r,n,i){if(e===t)return;if(i>_c)throw new RangeError(`deepDiff exceeded the maximum supported depth of ${_c}`);let o=Tc(e),a=Tc(t);if(o&&a&&Array.isArray(e)===Array.isArray(t)){let s=SB(e,t);for(let l of s){let u=IC(e,l),c=IC(t,l),d=EB.JsonPointer.append(r,l);u===Nc?n.push({pointer:d,type:"added",newValue:c}):c===Nc?n.push({pointer:d,type:"removed",oldValue:u}):OC(u,c,d,n,i+1)}return}PC(e,t)||n.push({pointer:r,type:"modified",oldValue:e,newValue:t})}function Tc(e){return e!==null&&typeof e=="object"}function SB(e,t){if(Array.isArray(e)&&Array.isArray(t)){let n=Math.max(e.length,t.length),i=[];for(let o=0;o<n;o++)i.push(String(o));return i}let r=new Set([...Object.keys(e),...Object.keys(t)]);return Array.from(r)}function IC(e,t){if(Array.isArray(e)){let r=Number(t);return r<e.length?e[r]:Nc}return t in e?e[t]:Nc}function PC(e,t){return RC(e,t,0)}Ba.deepEqual=PC;function RC(e,t,r){if(e===t)return!0;if(r>_c)throw new RangeError(`deepEqual exceeded the maximum supported depth of ${_c}`);if(!Tc(e)||!Tc(t)||Array.isArray(e)!==Array.isArray(t))return!1;let n=Object.keys(e),i=Object.keys(t);return n.length!==i.length?!1:n.every(o=>o in t&&RC(e[o],t[o],r+1))}});var kC=v(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.VersionManager=qa.PROJECTION_VERSION=void 0;var LC=Pm();qa.PROJECTION_VERSION=7;var Rm=class{constructor(t){this.workspace=t}async storeMeta(t,r,n,i){var o;let a=i===void 0?await this.getMeta(t,r):i,s=((o=n.snapshot)===null||o===void 0?void 0:o.status)==="Active",l=a?.everActivated===!0||s;await this.workspace.writeMeta(t,r,l?{...n,everActivated:l}:n)}async getMeta(t,r){return this.workspace.readMeta(t,r)}async isDirty(t,r,n){let i=await this.workspace.readArtifact(t,r);if(i===null)return!1;let o=n===void 0?await this.getMeta(t,r):n;return o?!(0,LC.deepEqual)(o.snapshot,i):!0}async diff(t,r){let n=await this.workspace.readArtifact(t,r),i=await this.getMeta(t,r),o;return n===null?o=i?[{pointer:"",type:"removed",oldValue:i.snapshot}]:[]:i?o=(0,LC.deepDiff)(i.snapshot,n):o=[{pointer:"",type:"added",newValue:n}],{artifactType:t,artifactId:r,changes:o}}async checkConflict(t,r,n){let i=await this.getMeta(t,r);return!i||i.etag===null?!1:i.etag!==n}};qa.VersionManager=Rm});var $C=v((Lm,xC)=>{(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof Lm=="object"?xC.exports=t():e.compareVersions=t()})(Lm,function(){var e=/^v?(?:\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+))?(?:-[\da-z\-]+(?:\.[\da-z\-]+)*)?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;function t(o,a){return o.indexOf(a)===-1?o.length:o.indexOf(a)}function r(o){var a=o.replace(/^v/,"").replace(/\+.*$/,""),s=t(a,"-"),l=a.substring(0,s).split(".");return l.push(a.substring(s+1)),l}function n(o){return isNaN(Number(o))?o:Number(o)}function i(o){if(typeof o!="string")throw new TypeError("Invalid argument expected string");if(!e.test(o))throw new Error("Invalid argument not valid semver ('"+o+"' received)")}return function(a,s){[a,s].forEach(i);for(var l=r(a),u=r(s),c=0;c<Math.max(l.length-1,u.length-1);c++){var d=parseInt(l[c]||0,10),f=parseInt(u[c]||0,10);if(d>f)return 1;if(f>d)return-1}var p=l[l.length-1],m=u[u.length-1];if(p&&m){var h=p.split(".").map(n),g=m.split(".").map(n);for(c=0;c<Math.max(h.length,g.length);c++){if(h[c]===void 0||typeof g[c]=="string"&&typeof h[c]=="number")return-1;if(g[c]===void 0||typeof h[c]=="string"&&typeof g[c]=="number"||h[c]>g[c])return 1;if(g[c]>h[c])return-1}}else if(p||m)return p?-1:1;return 0}})});var qC=v(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.EnvironmentFlowHostingType=ze.EnvironmentDisableReasonCode=ze.EnvironmentMigrationConstants=ze.EnvironmentProvisioningStates=ze.EnvironmentLocations=ze.EnvironmentCreationTypeConstants=ze.EnvironmentType=ze.EnvironmentSkuConstants=ze.environmentPermissions=ze.DatabaseType=void 0;var FC;(function(e){e.CommonDataService="CommonDataService",e.None="None"})(FC||(ze.DatabaseType=FC={}));ze.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"};ze.EnvironmentSkuConstants={NotSpecified:"NotSpecified",Standard:"Standard",Premium:"Premium",Developer:"Developer",Basic:"Basic",Production:"Production",Sandbox:"Sandbox",Trial:"Trial",Default:"Default",Teams:"Teams",Platform:"Platform"};var MC;(function(e){e[e.CDS2=0]="CDS2",e[e.CDS1=1]="CDS1",e[e.Empty=2]="Empty"})(MC||(ze.EnvironmentType=MC={}));ze.EnvironmentCreationTypeConstants={NotSpecified:"NotSpecified",Legacy:"Legacy",DefaultTenant:"DefaultTenant",User:"User",CommonDataModelLegacy:"CommonDataModelLegacy"};ze.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"};ze.EnvironmentProvisioningStates={NotSpecified:"NotSpecified",Succeeded:"Succeeded",Deleting:"Deleting",Deleted:"Deleted",FailedDeleting:"FailedDeleting",LinkedDatabaseProvisioning:"LinkedDatabaseProvisioning",LinkedDatabaseFailedProvisioning:"LinkedDatabaseFailedProvisioning",LinkedDatabaseFailedConfiguring:"LinkedDatabaseFailedConfiguring",LinkedDatabaseUnavailable:"LinkedDatabaseUnavailable",Creating:"Creating"};ze.EnvironmentMigrationConstants={phases:{completed:"Completed"}};var UC;(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"})(UC||(ze.EnvironmentDisableReasonCode=UC={}));var BC;(function(e){e.LogicApps="LogicApps",e.SelfHostSingleTenant="SelfHostSingleTenant",e.SelfHostMultiTenant="SelfHostMultiTenant"})(BC||(ze.EnvironmentFlowHostingType=BC={}))});var JC=v(_=>{"use strict";var NB=_&&_.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(_,"__esModule",{value:!0});_.hasCommonDataServiceDatabase=_.getEnvironmentDiscoveryUrl=_.getEnvironmentWebApiUrl=_.getEnvironmentInstanceApiUrl=_.getEnvironmentLanguageCode=_.getEnvironmentUpdateCadence=_.checkVersions=_.isCds2EnvironmentVersionAtLeast=_.getSecurityOrConnectedGroupId=_.hasSecurityGroupId=_.doesCds2VersionSupportApiVersion9_1=_.doesCds2EnvironmentSupportApiVersion9_1=_.cdsVersionSupportingOSColorEdit=_.getEnvironmentDisplayName=_.getEnvironmentName=_.isEnvironmentInFirstReleaseCluster=_.isEnvironmentInPreprodCluster=_.isEnvironmentInTestCluster=_.isLiteEnvironmentUpgrading=_.isEnvironmentExpired=_.isEnvironmentInDeletedState=_.isEnvironmentInCreatingState=_.isDatabaseInProvisioningState=_.canUserCreateDatabase=_.isDisabledEnvironment=_.isDefaultEnvironment=_.isTrialEnvironment=_.isPlatformEnvironment=_.isTeamsEnvironment=_.isSandboxEnvironment=_.isProdEnvironment=_.isDevEnvironment=_.getEnvironmentType=_.getCrmInstanceName=_.getCrmInstanceUrl=_.getCrmAppDesignerUrl=_.getDevResourcesUrl=_.isEnvironmentInSuccessfulState=_.getAllThemesUrl=_.getAllPublishersUrl=_.getAllSolutionsUrl=_.getSecurityRolesUrl=_.getSecurityUsersUrl=_.environmentHasCds2Database=_.DEFAULT_SOLUTION_UNIQUE_NAME=_.DEFAULT_SOLUTION_ID=_.crmBapSolutionId=_.doesUserHavePermission=_.getLinkedEnvironmentMetadata=_.getCrmVersion=void 0;_.doesUserHaveFlowRunOnlyPermission=_.isUserPautoMakerWithoutDataAccess=_.isUserPautoMakerWithDataAccess=_.doesUserHaveCreateFlowPermission=_.equalsIgnoreCase=_.doesUserHaveCreateDatabasePermission=_.doesUserHaveDatabaseTablePermissions=_.isUserMakerWithoutDataAccess=_.isUserMakerWithDataAccess=_.doesUserHaveCreateAppPermission=_.doesUserHaveAdminPermission=void 0;var _B=NB($C()),Te=qC(),bl=xm();function TB(e){let t=hi(e);return t&&t.version}_.getCrmVersion=TB;function hi(e){return e&&e.properties&&e.properties.linkedEnvironmentMetadata}_.getLinkedEnvironmentMetadata=hi;function mi(e,t){return e?!!e[t]:!1}_.doesUserHavePermission=mi;_.crmBapSolutionId="00000001-0000-0000-0001-00000000009b";_.DEFAULT_SOLUTION_ID="fd140aaf-4df4-11dd-bd17-0019b9312238";_.DEFAULT_SOLUTION_UNIQUE_NAME="Default";function xo(e){return!!hi(e)&&VC(e)}_.environmentHasCds2Database=xo;function DB(e){if(e&&xo(e)){let t=Qi(e);return(0,bl.getCrmAdminSecurityRolesUrl)(t)}return""}_.getSecurityUsersUrl=DB;function IB(e){if(e&&xo(e)){let t=Qi(e);return(0,bl.getCrmAdminSecurityUsersUrl)(t)}return""}_.getSecurityRolesUrl=IB;function OB(e){if(e&&xo(e)){let t=Qi(e);(0,bl.getCrmAllSolutionsUrl)(t)}return""}_.getAllSolutionsUrl=OB;function PB(e){if(e&&xo(e)){let t=Qi(e);return(0,bl.getCrmAllPublishersUrl)(t)}return""}_.getAllPublishersUrl=PB;function RB(e){return e&&xo(e)?Qi(e):""}_.getAllThemesUrl=RB;function VC(e){return!!e&&e.properties&&!!e.properties.provisioningState&&e.properties.provisioningState.toUpperCase()===Te.EnvironmentProvisioningStates.Succeeded.toUpperCase()}_.isEnvironmentInSuccessfulState=VC;function LB(e){if(e&&xo(e)){let t=Qi(e);return(0,bl.getCrmDevResourcesUrl)(t)}return""}_.getDevResourcesUrl=LB;function kB(e){return`${e}designer/app/{${_.crmBapSolutionId}}/CreateNewApp}}`}_.getCrmAppDesignerUrl=kB;function Qi(e){let t=hi(e);if(t){let r=t.instanceUrl;return r?r.endsWith("/")?r:r+"/":""}return""}_.getCrmInstanceUrl=Qi;function xB(e){let t=hi(e);return t?t.uniqueName:""}_.getCrmInstanceName=xB;function $B(e){return hi(e)?Te.EnvironmentType.CDS2:e&&e.properties&&e.properties.namespace?Te.EnvironmentType.CDS1:Te.EnvironmentType.Empty}_.getEnvironmentType=$B;function FB(e){return e&&e.properties&&e.properties.environmentSku===Te.EnvironmentSkuConstants.Developer}_.isDevEnvironment=FB;function MB(e){return e&&e.properties&&e.properties.environmentSku===Te.EnvironmentSkuConstants.Production}_.isProdEnvironment=MB;function UB(e){return e&&e.properties&&e.properties.environmentSku===Te.EnvironmentSkuConstants.Sandbox}_.isSandboxEnvironment=UB;function vl(e){return e&&e.properties&&e.properties.environmentSku===Te.EnvironmentSkuConstants.Teams}_.isTeamsEnvironment=vl;function BB(e){return e&&e.properties&&e.properties.environmentSku===Te.EnvironmentSkuConstants.Platform}_.isPlatformEnvironment=BB;var qB=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.environmentSku)===Te.EnvironmentSkuConstants.Trial};_.isTrialEnvironment=qB;function VB(e){return e&&e.properties&&(e.properties.isDefault||e.properties.creationType===Te.EnvironmentCreationTypeConstants.DefaultTenant)}_.isDefaultEnvironment=VB;function GB(e){return e&&e.properties&&!!e.properties.states&&!!e.properties.states.runtime&&e.properties.states.runtime.id==="Disabled"}_.isDisabledEnvironment=GB;function WB(e){return e&&e.properties&&mi(e.properties.permissions,Te.environmentPermissions.CreateDatabase)}_.canUserCreateDatabase=WB;function zB(e){return!!(e&&e.properties&&e.properties.provisioningState&&KC(e.properties.provisioningState,Te.EnvironmentProvisioningStates.LinkedDatabaseProvisioning))}_.isDatabaseInProvisioningState=zB;function jB(e){return!!e&&!!e.properties&&e.properties.provisioningState===Te.EnvironmentProvisioningStates.Creating}_.isEnvironmentInCreatingState=jB;function HB(e){return e&&e.properties&&(e.properties.provisioningState===Te.EnvironmentProvisioningStates.Deleted||e.properties.provisioningState===Te.EnvironmentProvisioningStates.Deleting||e.properties.provisioningState===Te.EnvironmentProvisioningStates.FailedDeleting)}_.isEnvironmentInDeletedState=HB;function KB(e){return!!e&&!!e.properties&&!!e.properties.expirationTime&&Date.parse(e.properties.expirationTime)<Date.now()}_.isEnvironmentExpired=KB;function JB(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"}_.isLiteEnvironmentUpgrading=JB;function YB(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Test"}_.isEnvironmentInTestCluster=YB;function QB(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Preprod"}_.isEnvironmentInPreprodCluster=QB;function XB(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="FirstRelease"}_.isEnvironmentInFirstReleaseCluster=XB;function ZB(e){return e&&e.name||""}_.getEnvironmentName=ZB;function eq(e){return e&&e.properties&&e.properties.displayName||""}_.getEnvironmentDisplayName=eq;var GC="9.1.0.8202";_.cdsVersionSupportingOSColorEdit="9.1.0000.20708";function tq(e){return jC(e,GC)}_.doesCds2EnvironmentSupportApiVersion9_1=tq;function rq(e){return km(e,GC)}_.doesCds2VersionSupportApiVersion9_1=rq;function WC(e){let t=hi(e);if(t)return t.securityGroupId}function zC(e){return e&&e.properties&&e.properties.connectedGroups}function nq(e,t){let r=zC(e);return!!r&&!!r.find(n=>n.id===t)||WC(e)===t}_.hasSecurityGroupId=nq;function iq(e){let t=zC(e);return t&&t.length>0&&t[0].id?t[0].id:WC(e)}_.getSecurityOrConnectedGroupId=iq;function jC(e,t){let r=e.version;return r?km(r,t):!1}_.isCds2EnvironmentVersionAtLeast=jC;function km(e,t){return t?e?(0,_B.default)(e,t)>=0:!1:!0}_.checkVersions=km;function oq(e){return e&&e.properties&&e.properties.updateCadence&&e.properties.updateCadence.id||"NotSpecified"}_.getEnvironmentUpdateCadence=oq;function aq(e){let t=hi(e);return t?Number(t.baseLanguage):0}_.getEnvironmentLanguageCode=aq;function HC(e){let t=hi(e);return t?t.instanceApiUrl:void 0}_.getEnvironmentInstanceApiUrl=HC;function sq(e){let t=HC(e);return t?t+"/api/data/v9.2":""}_.getEnvironmentWebApiUrl=sq;function lq(e){let t=Qi(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"}_.getEnvironmentDiscoveryUrl=lq;var uq=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.databaseType)===Te.DatabaseType.CommonDataService};_.hasCommonDataServiceDatabase=uq;var cq=e=>{var t;return mi((t=e.properties)===null||t===void 0?void 0:t.permissions,Te.environmentPermissions.AdminReadEnvironment)};_.doesUserHaveAdminPermission=cq;var dq=e=>{var t;return mi((t=e.properties)===null||t===void 0?void 0:t.permissions,Te.environmentPermissions.CreatePowerApp)};_.doesUserHaveCreateAppPermission=dq;var fq=e=>(0,_.doesUserHaveAdminPermission)(e)&&(0,_.hasCommonDataServiceDatabase)(e)?!0:(0,_.doesUserHaveCreateAppPermission)(e)?vl(e)||(0,_.doesUserHaveDatabaseTablePermissions)(e):!1;_.isUserMakerWithDataAccess=fq;var pq=e=>(0,_.doesUserHaveCreateAppPermission)(e)&&!vl(e)&&!(0,_.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,_.doesUserHaveAdminPermission)(e)||!(0,_.hasCommonDataServiceDatabase)(e));_.isUserMakerWithoutDataAccess=pq;var mq=e=>[Te.environmentPermissions.CreateDatabaseEntities,Te.environmentPermissions.ListDatabaseEntities,Te.environmentPermissions.UpdateDatabaseEntities,Te.environmentPermissions.DeleteDatabaseEntities].every(t=>{var r;return mi((r=e.properties)===null||r===void 0?void 0:r.permissions,t)});_.doesUserHaveDatabaseTablePermissions=mq;var hq=e=>{var t;return mi((t=e.properties)===null||t===void 0?void 0:t.permissions,Te.environmentPermissions.CreateDatabase)};_.doesUserHaveCreateDatabasePermission=hq;function KC(e,t){return!e&&!t?!0:!e||!t?!1:e.toUpperCase()===t.toUpperCase()}_.equalsIgnoreCase=KC;var gq=e=>{var t;return mi((t=e.properties)===null||t===void 0?void 0:t.permissions,Te.environmentPermissions.CreateFlow)};_.doesUserHaveCreateFlowPermission=gq;var yq=e=>(0,_.doesUserHaveAdminPermission)(e)&&(0,_.hasCommonDataServiceDatabase)(e)?!0:(0,_.doesUserHaveCreateFlowPermission)(e)?vl(e)||(0,_.doesUserHaveDatabaseTablePermissions)(e):!1;_.isUserPautoMakerWithDataAccess=yq;var bq=e=>(0,_.doesUserHaveCreateFlowPermission)(e)&&!vl(e)&&!(0,_.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,_.doesUserHaveAdminPermission)(e)||!(0,_.hasCommonDataServiceDatabase)(e));_.isUserPautoMakerWithoutDataAccess=bq;var vq=e=>{var t,r;return!mi((t=e.properties)===null||t===void 0?void 0:t.permissions,Te.environmentPermissions.CreateFlow)&&mi((r=e.properties)===null||r===void 0?void 0:r.permissions,Te.environmentPermissions.ReadEnvironment)};_.doesUserHaveFlowRunOnlyPermission=vq});var xm=v(S=>{"use strict";Object.defineProperty(S,"__esModule",{value:!0});S.getRequiredComponentsQueryUrl=S.solutionComponentCountSummariesQueryUrl=S.solutionComponentSummariesQueryUrl=S.solutionComponentConfigurationsQueryUrl=S.chartsQueryUrl=S.workflowsQueryUrl=S.entityDefinitionsQueryUrl=S.solutionComponentDefinitionsQueryUrl=S.getCreateNewArticleTemplateUrl=S.getCreateNewPublisherUrl=S.getEnableSecurityRolesUrl=S.getArticleTemplateUrl=S.getFieldSecurityProfileDesignerUrl=S.getSecurityRoleDesignerUrl=S.getMailMergeTemplateDesignerUrl=S.getEmailTemplateDesignerUrl=S.getConnectionRoleDesignerUrl=S.getSiteMapDesignerUrl=S.getWebResourceFileUrl=S.getWebResourceDesignerUrl=S.getReportDesignerUrl=S.getBusinessProcessFlowDesignerUrl=S.getProcessShareUrl=S.getProcessDesignerUrl=S.getChartDesignerUrl=S.getOpenModernEntityDashboardUrl=S.getNewModernEntityDashboardUrl=S.getNewModernDashboardUrl=S.getOpenModernDashboardUrl=S.getDashboardDesignerUrl=S.getAppModuleDesignerUrl=S.privilegesQueryUrls=S.xrmApiUrl=S.getPlayAppModuleUrl=S.getCrmAdminSecurityUsersUrl=S.getCrmAdminSecurityRolesUrl=S.getCrmMyAppsUrl=S.getCrmAppDesignerUrl=S.getCrmDevResourcesUrl=S.getCrmAllPublishersUrl=S.getCrmAllSolutionsUrl=S.getSolutionPublisherUrl=S.getExportTranslationFileName=S.getExportSolutionTranslationUrl=S.getImportSolutionTranslationUrl=S.getShowSolutionDependenciesUrl=S.getShowComponentDependenciesUrl=S.cdsServiceUrl=S.ODATA_NEXT_LINK=S.ODATA_MAX_PAGE_SIZE=void 0;S.retrieveOrganizationResources=S.getUCIEntityRecordEditUrl=S.getUCIEntityRecordBaseUrl=S.getBusinessRuleDesignerUri=S.retrieveUnpublishedSuffix=S.getSavePowerSettingUri=S.getPowerSettingUri=S.getPowerSettingsUri=S.RetrievePlatform=S.getAppSettingOverrideUri=S.AppSettingOverrideName=S.getOrgSettingOverrideUri=S.OrgSettingOverrideName=S.getSettingDefinitionsUri=S.retrieveFeatureControlSettingsByNamespaceUrl=S.retrieveDeploymentPipelineConfigAppUrl=S.SPNPrincipalIdUrl=S.retrieveDeploymentEnvironmentInfoUrl=S.devSolutionInfoUrl=S.deployOperationStatusUrl=S.getAIGeneratedDeploymentNotesUrl=S.deploymentStageRunUrl=S.validatePackageAsyncUrl=S.deployPackageAsyncUrl=S.updateDeploymentStageRunUrl=S.createDeploymentStageRunUrl=S.retrieveDeploymentStagesUrl=S.retrievePipelinesUrl=S.retrieveDeploymentPipelineInfoUrl=S.getDeploymentStageRunsUrl=S.appDeploymentUrls=S.getProvisionLanguageUrl=S.getSolutionQueryUrl=S.getSolutionsByUniqueNameQueryUrl=S.solutionsQueryUrl=S.getDependentComponentsWithMetadataQueryUrl=void 0;var YC=JC();S.ODATA_MAX_PAGE_SIZE="odata.maxpagesize";S.ODATA_NEXT_LINK="@odata.nextLink";S.cdsServiceUrl="https://cds-org/";var Cl;(function(e){e.AllSolutions="11",e.AllPublishers="10",e.DevResources="05"})(Cl||(Cl={}));function wq(e,t,r,n){return`${e}tools/dependency/dependencyviewdialog.aspx?appSolutionId=%7b${t}%7d&dType=1&objectid=%7b${r}%7d&objecttype=${n}&operationtype=showdependency`}S.getShowComponentDependenciesUrl=wq;function Cq(e,t){let r=`dType=1&isproactivecheck=true&objecttype=7100&operationtype=dependenciesforuninstall&objectid=${t}`;return`${e}tools/dependency/dependencyviewdialog.aspx?${r}`}S.getShowSolutionDependenciesUrl=Cq;function Eq(e,t){return`${e}tools/muiProvisioning/Dialogs/LangTranslationsImport.aspx?dType=1&appSolutionId=${t}`}S.getImportSolutionTranslationUrl=Eq;function Aq(e,t){return`${e}_grid/cmds/dlg_exportsolution.aspx?command=exporttranslation&appSolutionId=${t}`}S.getExportSolutionTranslationUrl=Aq;function Sq(e,t){return e!==void 0&&t!==void 0&&`CrmTranslations_${e}_${t.replace(/[.]/g,"_")}.zip`||""}S.getExportTranslationFileName=Sq;function Nq(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`}S.getSolutionPublisherUrl=Nq;function $m(e,t){return`${e}tools/systemcustomization/systemCustomization.aspx?pid=${t}`}function _q(e){return $m(e,Cl.AllSolutions)}S.getCrmAllSolutionsUrl=_q;function Tq(e){return $m(e,Cl.AllPublishers)}S.getCrmAllPublishersUrl=Tq;function Dq(e){return $m(e,Cl.DevResources)}S.getCrmDevResourcesUrl=Dq;function Iq(e,t=YC.crmBapSolutionId){return`${e}designer/app/${t}#/CreateNewApp`}S.getCrmAppDesignerUrl=Iq;function Oq(e){return`${e}apps`}S.getCrmMyAppsUrl=Oq;function Pq(e){return QC(e,"role")+"&forceUCI=0"}S.getCrmAdminSecurityRolesUrl=Pq;function Rq(e){return`${QC(e,"systemuser")}&forceclassic=1`}S.getCrmAdminSecurityUsersUrl=Rq;function QC(e,t){return`${e}main.aspx?pagetype=entitylist&etn=${t}`}function Lq(e,t){return`${e}main.aspx?appid=${t}`}S.getPlayAppModuleUrl=Lq;S.xrmApiUrl="api/data/v9.0";S.privilegesQueryUrls={systemUserInfo:e=>`${e}${S.xrmApiUrl}/WhoAmI`,userPrivileges:(e,t)=>`${e}${S.xrmApiUrl}/systemusers(${t})/Microsoft.Dynamics.CRM.RetrieveUserPrivileges`,systemPrivileges:e=>`${e}${S.xrmApiUrl}/privileges/Microsoft.Dynamics.CRM.RetrievePrivilegeSet`};function kq(e,t,r=YC.crmBapSolutionId){return`${e}designer/app/${r}/${t}/AppDesignerCanvas/${t}`}S.getAppModuleDesignerUrl=kq;function xq(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${r}%7d&extraqs=%26formId%3d%7b${t}%7d%26dashboardType%3d1030&pagetype=${`${n?"ic":""}dashboardeditor`}`}S.getDashboardDesignerUrl=xq;function $q(e,t,r){return`/e/${e}/s/${t}/dashboard/${r}`}S.getOpenModernDashboardUrl=$q;function Fq(e,t,r){let n=r!==void 0?r.toString():void 0;return`/e/${e}/s/${t}/dashboard/new${n?`/${n}`:""}`}S.getNewModernDashboardUrl=Fq;function Mq(e,t,r,n){let i=n!==void 0?n.toString():void 0;return`/e/${e}/s/${t}/n/${r}/dashboard/new${i?`/${i}`:""}`}S.getNewModernEntityDashboardUrl=Mq;function Uq(e,t,r,n){return`/e/${e}/s/${t}/n/${r}/dashboard/${n}`}S.getOpenModernEntityDashboardUrl=Uq;function Bq(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${t}%7d&extraqs=etc=${r||""}`+(n?`%26id=${n}`:"")+"&pagetype=vizdesigner"}S.getChartDesignerUrl=Bq;function qq(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}S.getProcessDesignerUrl=qq;function Vq(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}S.getProcessShareUrl=Vq;function Gq(e,t){return`${e}Tools/ProcessControl/UnifiedProcessDesigner.aspx?id=${t}`}S.getBusinessProcessFlowDesignerUrl=Gq;function Wq(e,t,r){return`${e}CRMReports/reportproperty.aspx?appSolutionId=%7b${r}%7d&disablePersonal=true&id=%7b${t}%7d`}S.getReportDesignerUrl=Wq;function zq(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`}S.getWebResourceDesignerUrl=zq;function jq(e,t){return`${e}WebResources/${t}`}S.getWebResourceFileUrl=jq;function Hq(e,t,r){return`${e}designer/sitemap/${r}/${t}/SiteMapHome/${t}`}S.getSiteMapDesignerUrl=Hq;function Kq(e,t,r){return`${e}connections/connectionroles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}S.getConnectionRoleDesignerUrl=Kq;function Jq(e,t,r){return`${e}tools/emailtemplateeditor/emailtemplateeditor.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}S.getEmailTemplateDesignerUrl=Jq;function Yq(e,t,r){return`${e}tools/mailmerge/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}S.getMailMergeTemplateDesignerUrl=Yq;function Qq(e,t,r){return`${e}biz/roles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}S.getSecurityRoleDesignerUrl=Qq;function Xq(e,t,r){return`${e}biz/fieldsecurityprofiles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}S.getFieldSecurityProfileDesignerUrl=Xq;function Zq(e,t,r){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?_CreateFromId=%7b${t}%7d&_CreateFromType=7100&appSolutionId=%7b${t}%7d&id=%7b${r}%7d`}S.getArticleTemplateUrl=Zq;function e3(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}`}S.getEnableSecurityRolesUrl=e3;function t3(e){return`${e}tools/publisher/edit.aspx`}S.getCreateNewPublisherUrl=t3;function r3(e,t){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?appSolutionId=${t}`}S.getCreateNewArticleTemplateUrl=r3;S.solutionComponentDefinitionsQueryUrl="api/data/v9.0/solutioncomponentdefinitions";S.entityDefinitionsQueryUrl="api/data/v9.0/EntityDefinitions?$select=EntitySetName,DisplayName,LogicalName&$filter=";S.workflowsQueryUrl="api/data/v9.0/workflows";S.chartsQueryUrl="/api/data/v9.0/savedqueryvisualizations";S.solutionComponentConfigurationsQueryUrl="/api/data/v9.1/solutioncomponentconfigurations?$filter=isdisplayable eq true&$select=name";S.solutionComponentSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentsummaries";S.solutionComponentCountSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentcountsummaries";function n3(e,t){return`${S.xrmApiUrl}/RetrieveRequiredComponents(ObjectId=${e},ComponentType=${t})`}S.getRequiredComponentsQueryUrl=n3;function i3(e,t){return`${S.cdsServiceUrl}${S.xrmApiUrl}/RetrieveDependentComponentsWithMetadata(ObjectId=${e},ComponentType=${t})`}S.getDependentComponentsWithMetadataQueryUrl=i3;S.solutionsQueryUrl="/api/data/v9.0/solutions?$expand=publisherid&$filter=(isvisible eq true)";function o3(e){return`/api/data/v9.0/solutions?$expand=publisherid&$filter=(uniquename eq '${e}')`}S.getSolutionsByUniqueNameQueryUrl=o3;function a3(e){return`/api/data/v9.0/solutions(${e})?$expand=publisherid`}S.getSolutionQueryUrl=a3;function s3(e){return`${e}api/data/v9.1/ProvisionLanguageForUser`}S.getProvisionLanguageUrl=s3;S.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 l3(e,t,r,n=!1,i=!1,o=!1,a=!1,s=!1,l=!1,u=!1){return`/api/data/v9.1/deploymentstageruns+`)),this.type=t,this.id=r,this.issues=u,this.pointer=(a=(o=u[0])===null||o===void 0?void 0:o.pointer)!==null&&a!==void 0?a:"",this.rule=(l=(s=u[0])===null||s===void 0?void 0:s.rule)!==null&&l!==void 0?l:"invalid"}};X.ValidationError=Wm;var zm=class extends _t{constructor(t){super("INVALID_ARGUMENT",t)}};X.InvalidArgumentError=zm;var jm=class extends _t{constructor(t,r,n,i="revalidated"){super("STALE_ARTIFACT",i==="pushed"?`Cannot apply the edit at ${n} to ${t}/${r}: a push made after this pointer's copy was read replaced the local copy with the record the server holds, which differs from that copy (ids and defaults the SDK filled in at save, a rewrite the platform made on save, or another writer's save), so the pointer may now identify a different node. Read the whole artifact (getArtifact), re-derive the pointer, and retry.`:`Cannot apply the edit at ${n} to ${t}/${r}: the cached copy was stale and the server copy has since changed, so any pointer derived from the old copy may now identify a different node. The local copy has been refreshed \u2014 re-read the artifact, re-derive the pointer, and retry.`),this.type=t,this.id=r,this.pointer=n,this.reason=i}};X.StaleArtifactError=jm;var Hm=class extends _t{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}};X.LocalEditsWouldBeLostError=Hm;var Km=class extends _t{constructor(t,r,n,i,o){super("VERSION_CONFLICT",`Version conflict for ${t}/${r}: local=${n??"(none)"}, server=${i??"(none)"}. Re-fetch and reapply changes.${o?` ${o}`:""}`),this.type=t,this.id=r,this.localEtag=n,this.serverEtag=i,this.detail=o}};X.VersionConflictError=Km;var Jm=class extends _t{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,Object.defineProperty(this,"cause",{value:i,enumerable:!1,writable:!1,configurable:!0})}};X.ConnectionError=Jm;function hq(e,t){return typeof e=="object"&&e!==null&&Object.defineProperty(e,"cause",{value:t,enumerable:!1,writable:!0,configurable:!0}),e}X.attachCause=hq;var Ym=class extends _t{constructor(t){super("WORKSPACE_NOT_INITIALIZED",`Workspace not initialized at ${t}. Call initWorkspace() first.`),this.workspacePath=t}};X.WorkspaceNotInitializedError=Ym;var Qm=class extends _t{constructor(t,r){super("WORKSPACE_ORG_MISMATCH",`This workspace belongs to ${t?`'${t}'`:"no recorded org"}, but this SDK targets '${r}'. Its local copies, baselines and cached metadata are that org's, so nothing was read or written. Use one workspace per org, or call cleanWorkspace() to discard this workspace's contents and bind it to '${r}'.`),this.workspaceInstanceUrl=t,this.instanceUrl=r}};X.WorkspaceOrgMismatchError=Qm;var Xm=class extends _t{constructor(t,r){super("NOT_IMPLEMENTED",`Operation '${t}' is not implemented yet${r?`: ${r}`:""}.`),this.operation=t}};X.NotImplementedError=Xm;var Zm=class extends _t{constructor(t,r){super("INVALID_JSON_POINTER",`Invalid JSON Pointer '${t}': ${r}`),this.pointer=t}};X.JsonPointerError=Zm;var eh=class extends _t{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}};X.AmbiguousArtifactError=eh;var th=class extends _t{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}};X.PathTraversalError=th;var rh=class extends _t{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}};X.IncompatibleWorkspaceError=rh});var oe=v(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.odataQuery=at.normalizeGuid=at.createSafeXmlElement=at.assertNoControlChars=at.assertODataName=at.assertXmlName=at.xmlText=at.odataPathLiteral=at.odataLiteral=void 0;var zc=Q();function rE(e){return String(e??"").replace(/'/g,"''")}at.odataLiteral=rE;function gq(e){return encodeURIComponent(rE(e))}at.odataPathLiteral=gq;function yq(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}at.xmlText=yq;function nE(e,t){let r=String(e??""),n=/^[A-Za-z_][0-9A-Za-z_.-]*$/,i=r.split(":");if(!(i.length<=2&&i.every(a=>n.test(a))&&!/^xmlns/i.test(r)))throw new zc.InvalidArgumentError(`${t} must be a valid XML element name (got '${e}')`);return e}at.assertXmlName=nE;function bq(e,t){let r=String(e??"");if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new zc.InvalidArgumentError(`${t} must be a valid OData identifier (letters, digits, underscore): got '${e}'`);return e}at.assertODataName=bq;function vq(e,t){if(/[\u0000-\u001F\u007F]/.test(String(e??"")))throw new zc.InvalidArgumentError(`${t} must not contain control characters (including CR/LF): they would inject additional lines into the request`);return e}at.assertNoControlChars=vq;function wq(e,t,r){return e.createElement(nE(t,r))}at.createSafeXmlElement=wq;var Cq=/^[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 Eq(e,t){let r=String(e??""),n=r.length===38&&r.startsWith("{")&&r.endsWith("}")?r.slice(1,-1):r;if(!Cq.test(n))throw new zc.InvalidArgumentError(`${t} must be a valid GUID (got '${e}')`);return n.toLowerCase()}at.normalizeGuid=Eq;function Aq(e){let t=[];for(let[r,n]of e)n!=null&&n!==""&&t.push(`${r}=${encodeURIComponent(String(n))}`);return t.length>0?`?${t.join("&")}`:""}at.odataQuery=Aq});var fe=v(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.nowIso=j.isAlreadyDeleted=j.deleteRecord=j.resendAppSearchIndexRace=j.resendDeadlockVictim=j.resendWhile=j.isAppSearchIndexRace=j.namesAppSearchIndexRace=j.isTransactionNotStarted=j.TRANSACTION_NOT_STARTED_CODE=j.LOCK_BACKOFF_MS=j.isConcurrencyLockRefusal=j.CONCURRENCY_LOCK_CODE=j.AMBIGUOUS_WRITE_STATUSES=j.DEADLOCK_BACKOFF_MS=j.isSqlDeadlockVictim=j.ensureSuccess=j.resolveCreatedId=j.requireCreatedId=j.withClientMintedId=j.readCreatedId=j.readRowEtag=j.readEtag=j.requireEtag=j.isVersionToken=j.echoWrite=j.UPDATE_NO_ETAG_CODE=j.VERSION_CONFLICT_CODE=void 0;var Ka=Q(),Ja=oe();j.VERSION_CONFLICT_CODE="VERSION_CONFLICT";j.UPDATE_NO_ETAG_CODE="ARTIFACT_UPDATE_NO_ETAG";function Sq(e,t){return{query:`?$select=${encodeURIComponent(e)}`,options:{headers:{...t??{},Prefer:"return=representation"}}}}j.echoWrite=Sq;function iE(e){return typeof e=="string"&&e.trim()!==""&&e.trim()!=="*"}j.isVersionToken=iE;function Nq(e,t,r){if(!iE(e))throw new Ka.SdkError(j.UPDATE_NO_ETAG_CODE,`Refusing to push ${t} '${r}': ${e?`the concurrency token held for it ('${e}') is not a version`:"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}j.requireEtag=Nq;function oE(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}j.readEtag=oE;async function _q(e,t,r,n){let i=`/${t}(${n})${(0,Ja.odataQuery)([["$select",r]])}`;return oE(ih(await e.get(i),e.apiUrl(i)))}j.readRowEtag=_q;function nh(e,t){var r;let n=e.body;if(n&&typeof n[t]=="string")return(0,Ja.normalizeGuid)(n[t],t);let i=(r=e.headers)!==null&&r!==void 0?r:{};for(let o of Object.keys(i))if(o.toLowerCase()==="odata-entityid"){let a=/\(([0-9a-fA-F-]{36})\)/.exec(i[o]);if(a)return(0,Ja.normalizeGuid)(a[1],t)}return null}j.readCreatedId=nh;function Tq(e,t,r){return r?{...e,[t]:(0,Ja.normalizeGuid)(r,t)}:e}j.withClientMintedId=Tq;function Dq(e,t,r){let n=nh(e,t);if(!n)throw new Ka.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`);return n}j.requireCreatedId=Dq;function Iq(e,t,r,n){let i=nh(e,t);if(i)return i;if(n)return(0,Ja.normalizeGuid)(n,t);throw new Ka.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`)}j.resolveCreatedId=Iq;function ih(e,t){if(e.status===412)throw new Ka.SdkError(j.VERSION_CONFLICT_CODE,`Version conflict (412) from ${t}`);if(e.status<200||e.status>=300)throw new Ka.ConnectionError(t,e.status,$q(e.body),e.body);return e}j.ensureSuccess=ih;function aE(e){if(e.status!==500||e.body===void 0||e.body===null)return!1;let t=typeof e.body=="string"?e.body:JSON.stringify(e.body);return/\bSql Number:\s*1205\b/i.test(t)}j.isSqlDeadlockVictim=aE;j.DEADLOCK_BACKOFF_MS=[1e3,2e3,4e3];j.AMBIGUOUS_WRITE_STATUSES=new Set([408,502,503,504]);j.CONCURRENCY_LOCK_CODE="0x80071151";function Oq(e){var t,r;if(e.status!==429)return!1;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return typeof n=="string"&&n.toLowerCase()===j.CONCURRENCY_LOCK_CODE}j.isConcurrencyLockRefusal=Oq;j.LOCK_BACKOFF_MS=[2e3,3e3,...Array.from({length:35},()=>5e3)];j.TRANSACTION_NOT_STARTED_CODE="0x80040251";function Pq(e){var t,r;if(e.status!==500)return!1;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return typeof n=="string"&&n.toLowerCase()===j.TRANSACTION_NOT_STARTED_CODE}j.isTransactionNotStarted=Pq;var Rq=/(?:^|[^a-z0-9_])AppModule_DVTableSearch_M365AppModuleId(?![a-z0-9_])/i;function sE(e){return Rq.test(e)&&/\bSql Number:\s*547\b/i.test(e)}j.namesAppSearchIndexRace=sE;function lE(e){return e.status!==400||e.body===void 0||e.body===null?!1:sE(typeof e.body=="string"?e.body:JSON.stringify(e.body))}j.isAppSearchIndexRace=lE;async function oh(e,t,r=j.DEADLOCK_BACKOFF_MS){for(let n=0;;n+=1){let i=await t();if(n>=r.length||!e(i))return i;await new Promise(o=>setTimeout(o,r[n]))}}j.resendWhile=oh;function Lq(e){return oh(aE,e,j.DEADLOCK_BACKOFF_MS)}j.resendDeadlockVictim=Lq;function kq(e){return oh(lE,e,j.DEADLOCK_BACKOFF_MS)}j.resendAppSearchIndexRace=kq;function $q(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 xq(e,t,r,n){let i=(0,Ja.normalizeGuid)(r,"id"),o=`/${t}(${i})`;ih(await e.delete(o,n?{headers:{"If-Match":n}}:void 0),e.apiUrl(o))}j.deleteRecord=xq;function Fq(e){return e instanceof Ka.ConnectionError&&e.statusCode===404}j.isAlreadyDeleted=Fq;function Mq(){return new Date().toISOString()}j.nowIso=Mq});var Tt=v(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});Ya.describeMalformedValue=Ya.collectPages=void 0;var uE=fe(),ah=Q();async function Uq(e,t,r,n,i){let o=[],a=new Set,s=e.apiUrl(t),l=(0,uE.ensureSuccess)(await e.get(t,i),s);for(n?.(l);;){let u=l.body,c=u?.value;if(!Array.isArray(c))throw new ah.ConnectionError(s,l.status,`${r}: paginated read returned a malformed page \u2014 expected an OData 'value' array but got ${sh(c)}; refusing to return partial results.`);for(let f of c)o.push(f);let d=u?.["@odata.nextLink"];if(d==null)break;if(typeof d!="string"||d.length===0)throw new ah.ConnectionError(s,l.status,`${r}: paginated read returned a malformed @odata.nextLink (${sh(d)}); cannot follow it, and refusing to return partial results.`);if(a.has(d))throw new ah.InvalidArgumentError(`${r}: aborting pagination \u2014 the server returned a repeated @odata.nextLink ('${d}'), which would loop indefinitely.`);a.add(d),s=d,l=(0,uE.ensureSuccess)(await e.getAbsolute(d,i),d)}return o}Ya.collectPages=Uq;function sh(e){return e===null?"null":e===void 0?"undefined (missing)":`a ${typeof e}`}Ya.describeMalformedValue=sh});var lh=v(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});Ho.assertWorkflowKind=Ho.WORKFLOW_KIND_MISMATCH_CODE=void 0;var jo=lo(),Bq=Q(),cE=fe(),qq=oe();Ho.WORKFLOW_KIND_MISMATCH_CODE="WORKFLOW_KIND_MISMATCH";var dE={[jo.WorkflowCategory.Workflow]:"classic workflow",[jo.WorkflowCategory.Dialog]:"dialog",[jo.WorkflowCategory.BusinessRule]:"business rule",[jo.WorkflowCategory.Action]:"custom action",[jo.WorkflowCategory.BusinessProcessFlow]:"business process flow",[jo.WorkflowCategory.Flow]:"cloud flow",[jo.WorkflowCategory.UIFlow]:"desktop flow"};async function Vq(e,t,r){var n,i;let o=`/workflows(${t})${(0,qq.odataQuery)([["$select","category"]])}`,a=await e.get(o);if(a.status===404)return null;(0,cE.ensureSuccess)(a,e.apiUrl(o));let s=(n=a.body)===null||n===void 0?void 0:n.category,l=typeof s=="number"?s:typeof s=="string"&&s!==""?Number(s):NaN;if(l!==r){let u=Number.isFinite(l)?`a ${(i=dE[l])!==null&&i!==void 0?i:"process"} (category ${l})`:"a process whose category could not be read";throw new Bq.SdkError(Ho.WORKFLOW_KIND_MISMATCH_CODE,`Refusing to delete workflow '${t}' as a ${dE[r]}: it is ${u}. Nothing was changed. Check the id.`)}return(0,cE.readEtag)(a)}Ho.assertWorkflowKind=Vq});var ch=v(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.deleteWorkflowResending=on.isWorkflowDeleteUnsettled=on.failedAfterResend=on.WORKFLOW_DELETE_UNSETTLED_CODE=void 0;var $l=Q(),_i=fe(),pE=oe();on.WORKFLOW_DELETE_UNSETTLED_CODE="WORKFLOW_DELETE_UNSETTLED";var mE=new WeakSet;function uh(e){return typeof e=="object"&&e!==null&&mE.add(e),e}function Gq(e){return typeof e=="object"&&e!==null&&mE.has(e)}on.failedAfterResend=Gq;function Wq(e){return e instanceof $l.SdkError&&e.code===on.WORKFLOW_DELETE_UNSETTLED_CODE}on.isWorkflowDeleteUnsettled=Wq;function zq(e,t){try{(0,_i.ensureSuccess)(e,t)}catch(r){return r}}function jq(e){return(0,_i.isSqlDeadlockVictim)(e)?"lost a SQL deadlock (HTTP 500, Sql Number 1205)":`lost its transaction (HTTP 500 ${_i.TRANSACTION_NOT_STARTED_CODE})`}async function fE(e,t){try{return(await e.get(`/workflows(${t})${(0,pE.odataQuery)([["$select","workflowid"]])}`)).status===404}catch{return!1}}async function Hq(e,t,{bindingToken:r,kindName:n,deactivated:i=!1,resendDeadlockVictim:o=!1,ifMatchOnFirst:a=!1}){let s=(0,pE.normalizeGuid)(t,"id");if(a&&!r)throw new $l.InvalidArgumentError(`Refusing to delete ${n} '${s}': its delete must be conditional on a token this operation holds, and it holds none.`);let l=`/workflows(${s})`,u=e.apiUrl(l),c=p=>(0,_i.isTransactionNotStarted)(p)||o&&(0,_i.isSqlDeadlockVictim)(p),d=0,f,m;try{m=await(0,_i.resendWhile)(c,async()=>{d+=1;let p=d>1||a,h=await e.delete(l,p?{headers:{"If-Match":r}}:void 0);return f=f??h,h},r?_i.DEADLOCK_BACKOFF_MS:[])}catch(p){if(p instanceof $l.ConnectionError&&p.statusCode===0&&r&&await fE(e,s))return;throw d>1?uh(p):p}if(!(d>1&&m.status===404)){if(d>1&&m.status===412){let p=jq(f),h=new $l.SdkError(on.WORKFLOW_DELETE_UNSETTLED_CODE,`Deleting ${n} '${s}' ${p}, and its re-send was refused (HTTP 412): the row at that id is no longer the version this delete checked \u2014 it was edited, or deleted and re-created at the same id \u2014 so nothing more was deleted. `+(i?"This delete had deactivated the process first and has NOT re-activated it: it MAY be left DISABLED. ":"")+"Read the row before deleting it again.");throw uh((0,$l.attachCause)(h,zq(f,u)))}if(!(r&&_i.AMBIGUOUS_WRITE_STATUSES.has(m.status)&&await fE(e,s)))try{(0,_i.ensureSuccess)(m,u)}catch(p){throw d>1?uh(p):p}}}on.deleteWorkflowResending=Hq});var dh=v(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.businessRuleApi=Hn.BUSINESS_RULE_LEFT_DEACTIVATED_CODE=Hn.WFOM_API_UNAVAILABLE_CODE=void 0;var jn=lo(),Kq=Tt(),Jq=lh(),Yq=ch(),Kt=fe(),Ti=oe(),Hc=Q();Hn.WFOM_API_UNAVAILABLE_CODE="BUSINESS_RULE_API_UNAVAILABLE";Hn.BUSINESS_RULE_LEFT_DEACTIVATED_CODE="BUSINESS_RULE_LEFT_DEACTIVATED";async function hE(e,t,r,n){let i=`/workflows(${Zq})/Microsoft.Dynamics.CRM.${t}`;try{return(0,Kt.ensureSuccess)(await e.post(i,{Entity:r.Entity,WfomJson:r.WfomJson},{headers:n}),e.apiUrl(i))}catch(o){throw o?.statusCode!==404?o:new Hc.SdkError(Hn.WFOM_API_UNAVAILABLE_CODE,`Business-rule authoring (preview) is not enabled on this environment yet: it does not expose 'Microsoft.Dynamics.CRM.${t}'. The bound members are still rolling out, so re-check once the release flag reaches this environment. Nothing was written. The SDK does NOT fall back to generating workflow XAML: that covered only 4 of the 7 action types and would silently save a rule different from the one you wrote.`)}}async function Qq(e,t){let r=`/workflows(${t})${(0,Ti.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,Kt.readEtag)(n),statecode:typeof i?.statecode=="number"?i.statecode:null,statuscode:typeof i?.statuscode=="number"?i.statuscode:null}}catch{return null}}async function Xq(e,t,r){let n=await Qq(e,t);if(n===null||n.etag===null)throw new Hc.SdkError(Kt.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 Hc.SdkError(Kt.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 Zq="00000000-0000-0000-0000-000000000000",jc={"Content-Type":"application/json",Accept:"application/json","OData-Version":"4.0","OData-MaxVersion":"4.0"},e3="workflowid,name,description,primaryentity,statecode,category,type",t3="category eq 2 and type eq 1";async function gE(e,t,r){var n;if(r==="Draft")return null;let i=(0,Ti.normalizeGuid)(t,"workflowid"),o=r==="Active",a={statecode:o?jn.StateCode.Activated:jn.StateCode.Draft,statuscode:o?jn.StatusCode.Activated:jn.StatusCode.Draft},s=`/workflows(${i})`,l=(0,Kt.ensureSuccess)(await e.patch(s,a,{headers:jc}),e.apiUrl(s));return(n=(0,Kt.readEtag)(l))!==null&&n!==void 0?n:await xl(e,i)}async function xl(e,t){let r=`/workflows(${t})${(0,Ti.odataQuery)([["$select","workflowid"]])}`;try{let n=await e.get(r);return n.status>=200&&n.status<300?(0,Kt.readEtag)(n):null}catch{return null}}async function r3(e,t,r){let n=await xl(e,t),i=await r(),o=(0,Kt.readEtag)(i);if(o)return{response:i,etag:o};let a=await xl(e,t);return{response:i,etag:n!==null&&n===a?a:null}}Hn.businessRuleApi={async get(e,t){let r=(0,Ti.normalizeGuid)(t,"id"),n=`/workflows(${r})/Microsoft.Dynamics.CRM.RetrieveProcessWithWfomJson`,{response:i,etag:o}=await r3(e,r,async()=>(0,Kt.ensureSuccess)(await e.get(n),e.apiUrl(n)));return{raw:i.body,etag:o}},async list(e,t){let r=[t3];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,Ti.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,Ti.odataQuery)([["$select",e3],["$filter",r.join(" and ")]])}`;return(await(0,Kq.collectPages)(e,n,"listArtifacts('businessRule')")).map(o=>{var a,s;return{type:"businessRule",id:(a=o.workflowid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",entityLogicalName:o.primaryentity,isDirty:!1}})},async create(e,t){var r;let n=t,i=(0,Ti.normalizeGuid)(n.Entity.workflowid,"workflowid"),o=await hE(e,"CreateProcessWithWfomJson",n,jc),a=(0,Kt.resolveCreatedId)(o,"workflowid","business rule",i),s=null;try{s=await gE(e,a,n.status)}catch(l){try{await(0,Kt.deleteRecord)(e,"workflows",a)}catch{}throw l}return{id:a,etag:(r=s??(0,Kt.readEtag)(o))!==null&&r!==void 0?r:await xl(e,a)}},async update(e,t,r,n){var i,o;let a=r,s=(0,Ti.normalizeGuid)(t,"id"),l=`/workflows(${s})`,u={...jc,"If-Match":(0,Kt.requireEtag)(n,"business rule",s)},c=await Xq(e,s,u["If-Match"]),d=c.statecode===jn.StateCode.Activated;d&&(0,Kt.ensureSuccess)(await e.patch(l,{statecode:jn.StateCode.Draft,statuscode:jn.StatusCode.Draft},{headers:u}),e.apiUrl(l));let f;try{f=await hE(e,"UpdateProcessWithWfomJson",a,u)}catch(p){if(d)try{(0,Kt.ensureSuccess)(await e.patch(l,{statecode:jn.StateCode.Activated,statuscode:(i=c.statuscode)!==null&&i!==void 0?i:jn.StatusCode.Activated},{headers:jc}),e.apiUrl(l))}catch(h){throw new Hc.SdkError(Hn.BUSINESS_RULE_LEFT_DEACTIVATED_CODE,`The business-rule write failed AND the rule could not be re-activated, so '${s}' is left DEACTIVATED (Draft) on the server. Re-activate it before relying on it. Original write failure: ${p instanceof Error?p.message:String(p)}. Restore failure: ${h instanceof Error?h.message:String(h)}`)}throw p}let m=await gE(e,s,a.status);return{id:s,etag:(o=m??(0,Kt.readEtag)(f))!==null&&o!==void 0?o:await xl(e,s)}},async delete(e,t){let r=(0,Ti.normalizeGuid)(t,"id"),n=await(0,Jq.assertWorkflowKind)(e,r,jn.WorkflowCategory.BusinessRule);return(0,Yq.deleteWorkflowResending)(e,r,{bindingToken:n,kindName:"business rule"})}}});var jr=v(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.publishBoundEntity=st.boundEntityPublishScope=st.publishGenPageById=st.publishDashboardById=st.publishWebResourceById=st.publishEntity=st.publishAppModule=st.publishAllXml=st.publishXml=void 0;var Kc=fe(),Fl=oe(),yE="/PublishXml";async function Qa(e,t){(0,Kc.ensureSuccess)(await(0,Kc.resendDeadlockVictim)(()=>e.post(yE,{ParameterXml:t})),e.apiUrl(yE))}st.publishXml=Qa;var bE="/PublishAllXml";async function n3(e){(0,Kc.ensureSuccess)(await(0,Kc.resendDeadlockVictim)(()=>e.post(bE,{})),e.apiUrl(bE))}st.publishAllXml=n3;function i3(e,t){return Qa(e,`<importexportxml><appmodules><appmodule>${(0,Fl.xmlText)(t)}</appmodule></appmodules></importexportxml>`)}st.publishAppModule=i3;function vE(e,t){return Qa(e,`<importexportxml><entities><entity>${(0,Fl.xmlText)(t)}</entity></entities></importexportxml>`)}st.publishEntity=vE;function o3(e,t){return Qa(e,`<importexportxml><webresources><webresource>${(0,Fl.xmlText)(t)}</webresource></webresources></importexportxml>`)}st.publishWebResourceById=o3;function a3(e,t){return Qa(e,`<importexportxml><dashboards><dashboard>${(0,Fl.xmlText)(t)}</dashboard></dashboards></importexportxml>`)}st.publishDashboardById=a3;function s3(e,t){return Qa(e,`<importexportxml><uxagentprojects><uxagentproject>${(0,Fl.xmlText)(t)}</uxagentproject></uxagentprojects></importexportxml>`)}st.publishGenPageById=s3;function l3(e){let t=e?.entityLogicalName;return t?{envelope:"entity",entityLogicalName:t,blastRadiusWarning:"ENTITY_ENVELOPE_ALSO_SHIPS_UNRELATED_UNPUBLISHED_CHANGES"}:{envelope:"entity"}}st.boundEntityPublishScope=l3;function u3(e,t){let r=t?.entityLogicalName;return r?vE(e,r):Promise.resolve()}st.publishBoundEntity=u3});var Xa=v(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});Yc.JsonPointer=void 0;var Hr=Q(),Jc=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 Hr.JsonPointerError(t,'non-empty pointers must start with "/"');return t.substring(1).split("/").map(r=>{if(/~(?![01])/.test(r))throw new Hr.JsonPointerError(t,`invalid '~' escape in token '${r}' (expected ~0 or ~1)`);return e.decodeToken(r)})}static compile(t){return t.length===0?"":"/"+t.map(r=>e.encodeToken(r)).join("/")}static resolve(t,r){let n=e.parse(r),i=t;for(let o of n)if(Array.isArray(i)){let a=e.toArrayIndex(o,i.length);if(a===void 0)return;i=i[a]}else if(i!==null&&typeof i=="object"){let a=i;if(e.isReservedToken(o)||!Object.prototype.hasOwnProperty.call(a,o))return;i=a[o]}else return;return i}static set(t,r,n){let i=e.parse(r);if(i.length===0)throw new Hr.JsonPointerError(r,"cannot set the document root");let{parent:o,lastToken:a}=e.resolveParent(t,i,r);if(Array.isArray(o)){let s=e.toArrayIndex(a,o.length);if(s===void 0)throw new Hr.JsonPointerError(r,`'${a}' is not a valid array index`);if(s>o.length)throw new Hr.JsonPointerError(r,`array index '${a}' is out of range`);o[s]=n}else{if(e.isReservedToken(a))throw new Hr.JsonPointerError(r,`refusing to write reserved property '${a}'`);o[a]=n}}static remove(t,r){let n=e.parse(r);if(n.length===0)throw new Hr.JsonPointerError(r,"cannot remove the document root");let{parent:i,lastToken:o}=e.resolveParent(t,n,r);if(Array.isArray(i)){let a=e.toArrayIndex(o,i.length);if(a===void 0||a>=i.length)throw new Hr.JsonPointerError(r,`array index '${o}' is out of range`);i.splice(a,1)}else{if(e.isReservedToken(o))throw new Hr.JsonPointerError(r,`refusing to remove reserved property '${o}'`);delete i[o]}}static add(t,r,n,i){let o=e.parse(r);if(o.length>0&&o[o.length-1]==="-"){let l=e.compile(o.slice(0,-1)),u=e.resolve(t,l);if(!Array.isArray(u))throw new Hr.JsonPointerError(r,"add target must be an array");u.push(n);return}let a=e.resolve(t,r);if(!Array.isArray(a))throw new Hr.JsonPointerError(r,"add target must be an array");let s=i===void 0?a.length:i;if(s<0||s>a.length)throw new Hr.JsonPointerError(r,`insert index ${s} is out of range`);a.splice(s,0,n)}static parent(t){let r=e.parse(t);return r.pop(),e.compile(r)}static lastToken(t){let r=e.parse(t);return r.length===0?"":r[r.length-1]}static append(t,r){return`${t}/${e.encodeToken(String(r))}`}static resolveParent(t,r,n){let i=r[r.length-1],o=e.compile(r.slice(0,-1)),a=e.resolve(t,o);if(a===null||typeof a!="object")throw new Hr.JsonPointerError(n,"parent path does not resolve to an object or array");return{parent:a,lastToken:i}}static toArrayIndex(t,r){if(t==="-")return r;if(/^(0|[1-9][0-9]*)$/.test(t))return Number(t)}};Yc.JsonPointer=Jc;Jc.RESERVED_TOKENS=new Set(["__proto__","prototype","constructor"])});var CE=v(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});Qc.findElements=void 0;var wE=Xa();function c3(e,t){let r=[];return fh(e,"",t,r),r}Qc.findElements=c3;function fh(e,t,r,n){if(!(e===null||typeof e!="object"))if(r(e,t)&&n.push({pointer:t,value:e}),Array.isArray(e))e.forEach((i,o)=>{fh(i,wE.JsonPointer.append(t,o),r,n)});else for(let i of Object.keys(e))fh(e[i],wE.JsonPointer.append(t,i),r,n)}});var ph=v(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.assertMutationResult=Kn.assertExistsResult=Kn.assertReadResult=Kn.assertStorageContract=void 0;var d3=["readText","writeTextAtomic","deleteFile","deleteByPrefix"],f3=["ensureContainer","exists"];function p3(e){if(typeof e!="object"||e===null)throw new Error("workspaceStorage must be an object implementing WorkspaceStorage.");for(let t of d3)if(typeof e[t]!="function")throw new Error(`workspaceStorage is missing the required method '${t}'.`);for(let t of f3){let r=e[t];if(r!==void 0&&typeof r!="function")throw new Error(`workspaceStorage.${t} must be a function when present.`)}return e}Kn.assertStorageContract=p3;function m3(e,t){if(e===null||typeof e=="string")return e;throw new Error(`workspaceStorage.readText must resolve to a string or null for ${t}; got ${typeof e}. Absence is null \u2014 resolving undefined would make a present value look absent.`)}Kn.assertReadResult=m3;function h3(e,t){if(typeof e=="boolean")return e;throw new Error(`workspaceStorage.exists must resolve to a boolean for ${t}; got ${typeof e}. A truthy non-boolean would make an absent value look present.`)}Kn.assertExistsResult=h3;function g3(e,t){if(e!==void 0)throw new Error(`workspaceStorage.${t} must resolve to undefined; got ${typeof e}. A status-returning implementation would let a failed write be reported as a completed one.`)}Kn.assertMutationResult=g3});var mh=v(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});Za.retryTransientIoAsync=Za.retryTransientIo=void 0;var y3=new Set(["EPERM","EACCES","EBUSY","UNKNOWN"]),b3=5,EE=10;function v3(e){for(let t=1;;t+=1)try{return e()}catch(r){if(!AE(r,t))throw r;C3(EE*t)}}Za.retryTransientIo=v3;async function w3(e){for(let t=1;;t+=1)try{return await e()}catch(r){if(!AE(r,t))throw r;await new Promise(n=>setTimeout(n,EE*t))}}Za.retryTransientIoAsync=w3;function AE(e,t){let r=e.code;return t<b3&&!!r&&y3.has(r)}function C3(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{let t=Date.now()+e;for(;Date.now()<t;);}}});var DE=v(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});Kr.canonicalArtifactId=Kr.WorkspaceManager=Kr.WORKSPACE_SCHEMA_VERSION=Kr.retryTransientIo=void 0;var Jt=ph(),Jn=Q(),E3=mh();Object.defineProperty(Kr,"retryTransientIo",{enumerable:!0,get:function(){return E3.retryTransientIo}});function SE(e){let t=e;return typeof t.pathFor=="function"&&typeof t.getRoot=="function"?e:null}Kr.WORKSPACE_SCHEMA_VERSION=1;var uo={form:"forms",view:"views",businessRule:"business-rules",app:"apps",command:"commands",chart:"charts",dashboard:"dashboards",genPage:"gen-pages",bpf:"business-process-flows"},A3="manifest.json",es=".metadata",hh="entities";function NE(e){try{return Promise.resolve(e())}catch(t){return Promise.reject(t)}}function gh(e){if(e.schemaVersion!==void 0&&e.schemaVersion>Kr.WORKSPACE_SCHEMA_VERSION)throw new Jn.IncompatibleWorkspaceError(e.schemaVersion,Kr.WORKSPACE_SCHEMA_VERSION)}function _E(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xc(e){return e.trim().toLowerCase().replace(/\/+$/,"")}var yh=class{withManifest(t){let r=this.manifestQueue.then(t,t);return this.manifestQueue=r.then(()=>{},()=>{}),r}constructor(t,r,n){if(this.workspaceLabel=t,this.instanceUrl=r,this.manifestQueue=Promise.resolve(),this.bound=!1,n==null)throw new Error("WorkspaceManager requires a WorkspaceStorage. Node callers can build one with `createNodeWorkspaceStorage(path)` from '@maker-studio/cds-maker-sdk/node'.");this.storage=n}artifactKey(t,r){return this.assertSafeId(r),[uo[t],`${Ml(r)}.json`]}metaKey(t,r){return this.assertSafeId(r),[es,uo[t],`${Ml(r)}.meta.json`]}entityKey(t){return this.assertSafeId(t),[es,hh,`${t.toLowerCase()}.json`]}fsStore(){let t=SE(this.storage);if(!t)throw new Error("This workspace is not filesystem-backed, so it has no physical paths. Use the artifact/metadata/manifest accessors instead of the path helpers.");return t}getRoot(){let t=SE(this.storage);return t?t.getRoot():this.workspaceLabel}getArtifactDir(t){return this.fsStore().pathFor([uo[t]])}getArtifactFilePath(t,r){return this.fsStore().pathFor(this.artifactKey(t,r))}getMetaFilePath(t,r){return this.fsStore().pathFor(this.metaKey(t,r))}getEntityMetaFilePath(t){return this.fsStore().pathFor(this.entityKey(t))}assertSafeId(t){if(typeof t!="string"||t.length===0||/[\u0000-\u001f]/.test(t)||t.includes("/")||t.includes("\\")||t.includes(":")||t==="."||t===".."||t.includes(".."))throw new Jn.PathTraversalError(String(t),this.workspaceLabel)}get manifestKey(){return[A3]}assertDataKey(t,r){if(!Array.isArray(t)||t.length<2)throw new Jn.InvalidArgumentError(`${r} writes only inside the workspace's folders; '${String(t)}' is at its root, where only the manifest lives \u2014 and the manifest is changed only by the workspace itself.`);t.forEach(n=>this.assertSafeId(n))}async init(){let t=await this.withManifest(async()=>{let r=await this.readStoredManifest();return r.present&&this.assertBoundHere(r.value),r.present});await this.ensureLayout(),t||await this.withManifest(async()=>{let r=await this.readStoredManifest();if(r.present){this.assertBoundHere(r.value);return}let n={instanceUrl:this.instanceUrl,createdAt:new Date().toISOString(),artifacts:[]};await this.writeManifest(n)}),this.bound=!0}async readStoredManifest(){let t=(0,Jt.assertReadResult)(await this.storage.readText(this.manifestKey),"manifest.json");return t===null?{present:!1}:{present:!0,value:JSON.parse(t)}}async ensureLayout(){if(!this.storage.ensureContainer)return;let t=this.storage.ensureContainer.bind(this.storage),r=[[es,hh]];for(let i of Object.keys(uo))r.push([uo[i]],[es,uo[i]]);let n=await Promise.allSettled(r.map(i=>NE(()=>t(i))));for(let i of n){if(i.status==="rejected")throw i.reason;(0,Jt.assertMutationResult)(i.value,"ensureContainer")}}async isInitialized(){return this.storage.exists?(0,Jt.assertExistsResult)(await this.storage.exists(this.manifestKey),"manifest.json"):(0,Jt.assertReadResult)(await this.storage.readText(this.manifestKey),"manifest.json")!==null}async ensureInitialized(){if(!this.bound){await this.verifyBinding();return}if(!await this.isInitialized())throw new Jn.WorkspaceNotInitializedError(this.workspaceLabel)}async ensureReady(){await this.ensureInitialized()}async ensureBound(){this.bound||await this.verifyBinding()}verifyBinding(){if(!this.verifying){let t=()=>{this.verifying=void 0};this.verifying=this.readAndCheckBinding().then(t,r=>{throw t(),r})}return this.verifying}async readAndCheckBinding(){let t=await this.readStoredManifest();if(!t.present)throw new Jn.WorkspaceNotInitializedError(this.workspaceLabel);this.assertBoundHere(t.value),this.bound=!0}assertBoundHere(t){if(!_E(t))throw new Jn.WorkspaceOrgMismatchError("",this.instanceUrl);gh(t);let r=typeof t.instanceUrl=="string"?t.instanceUrl.trim():"",n=Xc(r);if(!n||n!==Xc(this.instanceUrl))throw new Jn.WorkspaceOrgMismatchError(r,this.instanceUrl)}async clean(){let t=await this.readStoredManifest();if(!t.present||!_E(t.value))throw new Jn.WorkspaceNotInitializedError(this.workspaceLabel);let r=t.value;gh(r);let n=Object.keys(uo).map(o=>[uo[o]]);n.push([es]);let i=await Promise.allSettled(n.map(o=>NE(()=>this.storage.deleteByPrefix(o))));for(let o of i){if(o.status==="rejected")throw o.reason;(0,Jt.assertMutationResult)(o.value,"deleteByPrefix")}await this.ensureLayout(),await this.withManifest(()=>this.writeManifest({...r,instanceUrl:this.instanceUrl,artifacts:[],lastSyncAt:void 0})),this.bound=!0}async readArtifact(t,r){return await this.ensureInitialized(),this.readJsonUnchecked(this.artifactKey(t,r))}async readArtifactWithText(t,r){await this.ensureInitialized();let n=this.artifactKey(t,r),i=(0,Jt.assertReadResult)(await this.storage.readText(n),n.join("/"));return i===null?null:{artifact:JSON.parse(i),text:i}}async writeArtifact(t,r,n,i){await this.ensureInitialized();let o=TE(n);if(i!==void 0&&o===i){await this.upsertManifestEntry(t,r,n,{unlessCurrent:!0});return}(0,Jt.assertMutationResult)(await this.storage.writeTextAtomic(this.artifactKey(t,r),o),"writeTextAtomic"),await this.upsertManifestEntry(t,r,n)}async deleteArtifact(t,r){await this.ensureInitialized(),(0,Jt.assertMutationResult)(await this.storage.deleteFile(this.artifactKey(t,r)),"deleteFile"),(0,Jt.assertMutationResult)(await this.storage.deleteFile(this.metaKey(t,r)),"deleteFile");let n=Ml(r);await this.withManifest(async()=>{let i=await this.getManifest();i.artifacts=i.artifacts.filter(o=>!(o.type===t&&o.id===n)),await this.writeManifest(i)})}async readMeta(t,r){return await this.ensureBound(),this.readJsonUnchecked(this.metaKey(t,r))}async writeMeta(t,r,n){await this.ensureBound(),await this.writeJsonUnchecked(this.metaKey(t,r),n)}async listArtifacts(t,r){return await this.ensureInitialized(),(await this.getManifest()).artifacts.filter(n=>!(t&&n.type!==t||r?.entityLogicalName&&n.entityLogicalName!==r.entityLogicalName))}async readEntityMetadata(t){await this.ensureInitialized();let r=await this.readJsonUnchecked(this.entityKey(t));return!r||typeof r.schemaName!="string"||typeof r.primaryNameAttribute!="string"||typeof r.primaryIdAttribute!="string"||typeof r.isCustomEntity!="boolean"?null:r}async writeEntityMetadata(t,r){await this.ensureInitialized(),await this.writeJsonUnchecked(this.entityKey(t),r)}async dropEntityMetadata(t){if(await this.ensureInitialized(),t===void 0){(0,Jt.assertMutationResult)(await this.storage.deleteByPrefix([es,hh]),"deleteByPrefix");return}(0,Jt.assertMutationResult)(await this.storage.deleteFile(this.entityKey(t)),"deleteFile")}async getManifest(){await this.ensureInitialized();let t=await this.readJsonUnchecked(this.manifestKey);if(!t)throw new Jn.WorkspaceNotInitializedError(this.workspaceLabel);return gh(t),t}async writeManifest(t){await this.writeJsonUnchecked(this.manifestKey,{...t,schemaVersion:Kr.WORKSPACE_SCHEMA_VERSION})}async updateManifest(t){await this.withManifest(async()=>{let r=await this.getManifest();if(t.instanceUrl!==void 0&&Xc(String(t.instanceUrl))!==Xc(r.instanceUrl))throw new Jn.InvalidArgumentError("updateManifest cannot change the workspace's org: it is bound to the org it was created for. cleanWorkspace() discards its contents and binds it to the org of the SDK that calls it.");await this.writeManifest({...r,...t,instanceUrl:r.instanceUrl})})}async upsertManifestEntry(t,r,n,i={}){await this.withManifest(async()=>{let o=await this.getManifest(),a=Ml(r),s=n,l=typeof s.name=="string"?s.name:`${t}:${a}`,u=typeof s.entityLogicalName=="string"?s.entityLogicalName:void 0,c=o.artifacts.find(d=>d.type===t&&d.id===a);i.unlessCurrent&&c?.name===l&&c.entityLogicalName===u||(c?(c.name=l,c.entityLogicalName=u):o.artifacts.push({type:t,id:a,name:l,entityLogicalName:u,isDirty:!1}),await this.writeManifest(o))})}async readJson(t){return await this.ensureBound(),this.readJsonUnchecked(t)}async writeJson(t,r){this.assertDataKey(t,"writeJson"),await this.ensureBound(),await this.writeJsonUnchecked(t,r)}async removeFile(t){this.assertDataKey(t,"removeFile"),await this.ensureBound(),(0,Jt.assertMutationResult)(await this.storage.deleteFile(t),"deleteFile")}async exists(t){return await this.ensureBound(),this.storage.exists?(0,Jt.assertExistsResult)(await this.storage.exists(t),t.join("/")):(0,Jt.assertReadResult)(await this.storage.readText(t),t.join("/"))!==null}async readJsonUnchecked(t){let r=(0,Jt.assertReadResult)(await this.storage.readText(t),t.join("/"));return r===null?null:JSON.parse(r)}async writeJsonUnchecked(t,r){(0,Jt.assertMutationResult)(await this.storage.writeTextAtomic(t,TE(r)),"writeTextAtomic")}};Kr.WorkspaceManager=yh;function TE(e){return`${JSON.stringify(e,null,2)}+`}function Ml(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()}Kr.canonicalArtifactId=Ml});var bh=v(ts=>{"use strict";Object.defineProperty(ts,"__esModule",{value:!0});ts.deepEqual=ts.deepDiff=void 0;var S3=Xa();function N3(e,t){let r=[];return OE(e,t,"",r,0),r}ts.deepDiff=N3;var Zc=Symbol("missing"),ed=512;function OE(e,t,r,n,i){if(e===t)return;if(i>ed)throw new RangeError(`deepDiff exceeded the maximum supported depth of ${ed}`);let o=td(e),a=td(t);if(o&&a&&Array.isArray(e)===Array.isArray(t)){let s=_3(e,t);for(let l of s){let u=IE(e,l),c=IE(t,l),d=S3.JsonPointer.append(r,l);u===Zc?n.push({pointer:d,type:"added",newValue:c}):c===Zc?n.push({pointer:d,type:"removed",oldValue:u}):OE(u,c,d,n,i+1)}return}PE(e,t)||n.push({pointer:r,type:"modified",oldValue:e,newValue:t})}function td(e){return e!==null&&typeof e=="object"}function _3(e,t){if(Array.isArray(e)&&Array.isArray(t)){let n=Math.max(e.length,t.length),i=[];for(let o=0;o<n;o++)i.push(String(o));return i}let r=new Set([...Object.keys(e),...Object.keys(t)]);return Array.from(r)}function IE(e,t){if(Array.isArray(e)){let r=Number(t);return r<e.length?e[r]:Zc}return t in e?e[t]:Zc}function PE(e,t){return RE(e,t,0)}ts.deepEqual=PE;function RE(e,t,r){if(e===t)return!0;if(r>ed)throw new RangeError(`deepEqual exceeded the maximum supported depth of ${ed}`);if(!td(e)||!td(t)||Array.isArray(e)!==Array.isArray(t))return!1;let n=Object.keys(e),i=Object.keys(t);return n.length!==i.length?!1:n.every(o=>o in t&&RE(e[o],t[o],r+1))}});var kE=v(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});rs.VersionManager=rs.PROJECTION_VERSION=void 0;var LE=bh(),T3=fe();rs.PROJECTION_VERSION=8;var vh=class{constructor(t){this.workspace=t}async storeMeta(t,r,n,i){var o;let a=i===void 0?await this.getMeta(t,r):i,s=((o=n.snapshot)===null||o===void 0?void 0:o.status)==="Active",l=a?.everActivated===!0||s;await this.workspace.writeMeta(t,r,l?{...n,everActivated:l}:n)}async getMeta(t,r){return this.workspace.readMeta(t,r)}async isDirty(t,r,n){let i=await this.workspace.readArtifact(t,r);if(i===null)return!1;let o=n===void 0?await this.getMeta(t,r):n;return o?!(0,LE.deepEqual)(o.snapshot,i):!0}async diff(t,r){let n=await this.workspace.readArtifact(t,r),i=await this.getMeta(t,r),o;return n===null?o=i?[{pointer:"",type:"removed",oldValue:i.snapshot}]:[]:i?o=(0,LE.deepDiff)(i.snapshot,n):o=[{pointer:"",type:"added",newValue:n}],{artifactType:t,artifactId:r,changes:o}}async checkConflict(t,r,n){let i=await this.getMeta(t,r);return!i||!(0,T3.isVersionToken)(i.etag)?!0:i.etag!==n}};rs.VersionManager=vh});var xE=v((wh,$E)=>{(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof wh=="object"?$E.exports=t():e.compareVersions=t()})(wh,function(){var e=/^v?(?:\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+))?(?:-[\da-z\-]+(?:\.[\da-z\-]+)*)?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;function t(o,a){return o.indexOf(a)===-1?o.length:o.indexOf(a)}function r(o){var a=o.replace(/^v/,"").replace(/\+.*$/,""),s=t(a,"-"),l=a.substring(0,s).split(".");return l.push(a.substring(s+1)),l}function n(o){return isNaN(Number(o))?o:Number(o)}function i(o){if(typeof o!="string")throw new TypeError("Invalid argument expected string");if(!e.test(o))throw new Error("Invalid argument not valid semver ('"+o+"' received)")}return function(a,s){[a,s].forEach(i);for(var l=r(a),u=r(s),c=0;c<Math.max(l.length-1,u.length-1);c++){var d=parseInt(l[c]||0,10),f=parseInt(u[c]||0,10);if(d>f)return 1;if(f>d)return-1}var m=l[l.length-1],p=u[u.length-1];if(m&&p){var h=m.split(".").map(n),g=p.split(".").map(n);for(c=0;c<Math.max(h.length,g.length);c++){if(h[c]===void 0||typeof g[c]=="string"&&typeof h[c]=="number")return-1;if(g[c]===void 0||typeof h[c]=="string"&&typeof g[c]=="number"||h[c]>g[c])return 1;if(g[c]>h[c])return-1}}else if(m||p)return m?-1:1;return 0}})});var qE=v(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.EnvironmentFlowHostingType=Je.EnvironmentDisableReasonCode=Je.EnvironmentMigrationConstants=Je.EnvironmentProvisioningStates=Je.EnvironmentLocations=Je.EnvironmentCreationTypeConstants=Je.EnvironmentType=Je.EnvironmentSkuConstants=Je.environmentPermissions=Je.DatabaseType=void 0;var FE;(function(e){e.CommonDataService="CommonDataService",e.None="None"})(FE||(Je.DatabaseType=FE={}));Je.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"};Je.EnvironmentSkuConstants={NotSpecified:"NotSpecified",Standard:"Standard",Premium:"Premium",Developer:"Developer",Basic:"Basic",Production:"Production",Sandbox:"Sandbox",Trial:"Trial",Default:"Default",Teams:"Teams",Platform:"Platform"};var ME;(function(e){e[e.CDS2=0]="CDS2",e[e.CDS1=1]="CDS1",e[e.Empty=2]="Empty"})(ME||(Je.EnvironmentType=ME={}));Je.EnvironmentCreationTypeConstants={NotSpecified:"NotSpecified",Legacy:"Legacy",DefaultTenant:"DefaultTenant",User:"User",CommonDataModelLegacy:"CommonDataModelLegacy"};Je.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"};Je.EnvironmentProvisioningStates={NotSpecified:"NotSpecified",Succeeded:"Succeeded",Deleting:"Deleting",Deleted:"Deleted",FailedDeleting:"FailedDeleting",LinkedDatabaseProvisioning:"LinkedDatabaseProvisioning",LinkedDatabaseFailedProvisioning:"LinkedDatabaseFailedProvisioning",LinkedDatabaseFailedConfiguring:"LinkedDatabaseFailedConfiguring",LinkedDatabaseUnavailable:"LinkedDatabaseUnavailable",Creating:"Creating"};Je.EnvironmentMigrationConstants={phases:{completed:"Completed"}};var UE;(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"})(UE||(Je.EnvironmentDisableReasonCode=UE={}));var BE;(function(e){e.LogicApps="LogicApps",e.SelfHostSingleTenant="SelfHostSingleTenant",e.SelfHostMultiTenant="SelfHostMultiTenant"})(BE||(Je.EnvironmentFlowHostingType=BE={}))});var JE=v(_=>{"use strict";var D3=_&&_.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(_,"__esModule",{value:!0});_.hasCommonDataServiceDatabase=_.getEnvironmentDiscoveryUrl=_.getEnvironmentWebApiUrl=_.getEnvironmentInstanceApiUrl=_.getEnvironmentLanguageCode=_.getEnvironmentUpdateCadence=_.checkVersions=_.isCds2EnvironmentVersionAtLeast=_.getSecurityOrConnectedGroupId=_.hasSecurityGroupId=_.doesCds2VersionSupportApiVersion9_1=_.doesCds2EnvironmentSupportApiVersion9_1=_.cdsVersionSupportingOSColorEdit=_.getEnvironmentDisplayName=_.getEnvironmentName=_.isEnvironmentInFirstReleaseCluster=_.isEnvironmentInPreprodCluster=_.isEnvironmentInTestCluster=_.isLiteEnvironmentUpgrading=_.isEnvironmentExpired=_.isEnvironmentInDeletedState=_.isEnvironmentInCreatingState=_.isDatabaseInProvisioningState=_.canUserCreateDatabase=_.isDisabledEnvironment=_.isDefaultEnvironment=_.isTrialEnvironment=_.isPlatformEnvironment=_.isTeamsEnvironment=_.isSandboxEnvironment=_.isProdEnvironment=_.isDevEnvironment=_.getEnvironmentType=_.getCrmInstanceName=_.getCrmInstanceUrl=_.getCrmAppDesignerUrl=_.getDevResourcesUrl=_.isEnvironmentInSuccessfulState=_.getAllThemesUrl=_.getAllPublishersUrl=_.getAllSolutionsUrl=_.getSecurityRolesUrl=_.getSecurityUsersUrl=_.environmentHasCds2Database=_.DEFAULT_SOLUTION_UNIQUE_NAME=_.DEFAULT_SOLUTION_ID=_.crmBapSolutionId=_.doesUserHavePermission=_.getLinkedEnvironmentMetadata=_.getCrmVersion=void 0;_.doesUserHaveFlowRunOnlyPermission=_.isUserPautoMakerWithoutDataAccess=_.isUserPautoMakerWithDataAccess=_.doesUserHaveCreateFlowPermission=_.equalsIgnoreCase=_.doesUserHaveCreateDatabasePermission=_.doesUserHaveDatabaseTablePermissions=_.isUserMakerWithoutDataAccess=_.isUserMakerWithDataAccess=_.doesUserHaveCreateAppPermission=_.doesUserHaveAdminPermission=void 0;var I3=D3(xE()),Oe=qE(),Ul=Eh();function O3(e){let t=Ii(e);return t&&t.version}_.getCrmVersion=O3;function Ii(e){return e&&e.properties&&e.properties.linkedEnvironmentMetadata}_.getLinkedEnvironmentMetadata=Ii;function Di(e,t){return e?!!e[t]:!1}_.doesUserHavePermission=Di;_.crmBapSolutionId="00000001-0000-0000-0001-00000000009b";_.DEFAULT_SOLUTION_ID="fd140aaf-4df4-11dd-bd17-0019b9312238";_.DEFAULT_SOLUTION_UNIQUE_NAME="Default";function Ko(e){return!!Ii(e)&&VE(e)}_.environmentHasCds2Database=Ko;function P3(e){if(e&&Ko(e)){let t=co(e);return(0,Ul.getCrmAdminSecurityRolesUrl)(t)}return""}_.getSecurityUsersUrl=P3;function R3(e){if(e&&Ko(e)){let t=co(e);return(0,Ul.getCrmAdminSecurityUsersUrl)(t)}return""}_.getSecurityRolesUrl=R3;function L3(e){if(e&&Ko(e)){let t=co(e);(0,Ul.getCrmAllSolutionsUrl)(t)}return""}_.getAllSolutionsUrl=L3;function k3(e){if(e&&Ko(e)){let t=co(e);return(0,Ul.getCrmAllPublishersUrl)(t)}return""}_.getAllPublishersUrl=k3;function $3(e){return e&&Ko(e)?co(e):""}_.getAllThemesUrl=$3;function VE(e){return!!e&&e.properties&&!!e.properties.provisioningState&&e.properties.provisioningState.toUpperCase()===Oe.EnvironmentProvisioningStates.Succeeded.toUpperCase()}_.isEnvironmentInSuccessfulState=VE;function x3(e){if(e&&Ko(e)){let t=co(e);return(0,Ul.getCrmDevResourcesUrl)(t)}return""}_.getDevResourcesUrl=x3;function F3(e){return`${e}designer/app/{${_.crmBapSolutionId}}/CreateNewApp}}`}_.getCrmAppDesignerUrl=F3;function co(e){let t=Ii(e);if(t){let r=t.instanceUrl;return r?r.endsWith("/")?r:r+"/":""}return""}_.getCrmInstanceUrl=co;function M3(e){let t=Ii(e);return t?t.uniqueName:""}_.getCrmInstanceName=M3;function U3(e){return Ii(e)?Oe.EnvironmentType.CDS2:e&&e.properties&&e.properties.namespace?Oe.EnvironmentType.CDS1:Oe.EnvironmentType.Empty}_.getEnvironmentType=U3;function B3(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Developer}_.isDevEnvironment=B3;function q3(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Production}_.isProdEnvironment=q3;function V3(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Sandbox}_.isSandboxEnvironment=V3;function Bl(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Teams}_.isTeamsEnvironment=Bl;function G3(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Platform}_.isPlatformEnvironment=G3;var W3=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.environmentSku)===Oe.EnvironmentSkuConstants.Trial};_.isTrialEnvironment=W3;function z3(e){return e&&e.properties&&(e.properties.isDefault||e.properties.creationType===Oe.EnvironmentCreationTypeConstants.DefaultTenant)}_.isDefaultEnvironment=z3;function j3(e){return e&&e.properties&&!!e.properties.states&&!!e.properties.states.runtime&&e.properties.states.runtime.id==="Disabled"}_.isDisabledEnvironment=j3;function H3(e){return e&&e.properties&&Di(e.properties.permissions,Oe.environmentPermissions.CreateDatabase)}_.canUserCreateDatabase=H3;function K3(e){return!!(e&&e.properties&&e.properties.provisioningState&&KE(e.properties.provisioningState,Oe.EnvironmentProvisioningStates.LinkedDatabaseProvisioning))}_.isDatabaseInProvisioningState=K3;function J3(e){return!!e&&!!e.properties&&e.properties.provisioningState===Oe.EnvironmentProvisioningStates.Creating}_.isEnvironmentInCreatingState=J3;function Y3(e){return e&&e.properties&&(e.properties.provisioningState===Oe.EnvironmentProvisioningStates.Deleted||e.properties.provisioningState===Oe.EnvironmentProvisioningStates.Deleting||e.properties.provisioningState===Oe.EnvironmentProvisioningStates.FailedDeleting)}_.isEnvironmentInDeletedState=Y3;function Q3(e){return!!e&&!!e.properties&&!!e.properties.expirationTime&&Date.parse(e.properties.expirationTime)<Date.now()}_.isEnvironmentExpired=Q3;function X3(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"}_.isLiteEnvironmentUpgrading=X3;function Z3(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Test"}_.isEnvironmentInTestCluster=Z3;function e4(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Preprod"}_.isEnvironmentInPreprodCluster=e4;function t4(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="FirstRelease"}_.isEnvironmentInFirstReleaseCluster=t4;function r4(e){return e&&e.name||""}_.getEnvironmentName=r4;function n4(e){return e&&e.properties&&e.properties.displayName||""}_.getEnvironmentDisplayName=n4;var GE="9.1.0.8202";_.cdsVersionSupportingOSColorEdit="9.1.0000.20708";function i4(e){return jE(e,GE)}_.doesCds2EnvironmentSupportApiVersion9_1=i4;function o4(e){return Ch(e,GE)}_.doesCds2VersionSupportApiVersion9_1=o4;function WE(e){let t=Ii(e);if(t)return t.securityGroupId}function zE(e){return e&&e.properties&&e.properties.connectedGroups}function a4(e,t){let r=zE(e);return!!r&&!!r.find(n=>n.id===t)||WE(e)===t}_.hasSecurityGroupId=a4;function s4(e){let t=zE(e);return t&&t.length>0&&t[0].id?t[0].id:WE(e)}_.getSecurityOrConnectedGroupId=s4;function jE(e,t){let r=e.version;return r?Ch(r,t):!1}_.isCds2EnvironmentVersionAtLeast=jE;function Ch(e,t){return t?e?(0,I3.default)(e,t)>=0:!1:!0}_.checkVersions=Ch;function l4(e){return e&&e.properties&&e.properties.updateCadence&&e.properties.updateCadence.id||"NotSpecified"}_.getEnvironmentUpdateCadence=l4;function u4(e){let t=Ii(e);return t?Number(t.baseLanguage):0}_.getEnvironmentLanguageCode=u4;function HE(e){let t=Ii(e);return t?t.instanceApiUrl:void 0}_.getEnvironmentInstanceApiUrl=HE;function c4(e){let t=HE(e);return t?t+"/api/data/v9.2":""}_.getEnvironmentWebApiUrl=c4;function d4(e){let t=co(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"}_.getEnvironmentDiscoveryUrl=d4;var f4=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.databaseType)===Oe.DatabaseType.CommonDataService};_.hasCommonDataServiceDatabase=f4;var p4=e=>{var t;return Di((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.AdminReadEnvironment)};_.doesUserHaveAdminPermission=p4;var m4=e=>{var t;return Di((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreatePowerApp)};_.doesUserHaveCreateAppPermission=m4;var h4=e=>(0,_.doesUserHaveAdminPermission)(e)&&(0,_.hasCommonDataServiceDatabase)(e)?!0:(0,_.doesUserHaveCreateAppPermission)(e)?Bl(e)||(0,_.doesUserHaveDatabaseTablePermissions)(e):!1;_.isUserMakerWithDataAccess=h4;var g4=e=>(0,_.doesUserHaveCreateAppPermission)(e)&&!Bl(e)&&!(0,_.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,_.doesUserHaveAdminPermission)(e)||!(0,_.hasCommonDataServiceDatabase)(e));_.isUserMakerWithoutDataAccess=g4;var y4=e=>[Oe.environmentPermissions.CreateDatabaseEntities,Oe.environmentPermissions.ListDatabaseEntities,Oe.environmentPermissions.UpdateDatabaseEntities,Oe.environmentPermissions.DeleteDatabaseEntities].every(t=>{var r;return Di((r=e.properties)===null||r===void 0?void 0:r.permissions,t)});_.doesUserHaveDatabaseTablePermissions=y4;var b4=e=>{var t;return Di((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreateDatabase)};_.doesUserHaveCreateDatabasePermission=b4;function KE(e,t){return!e&&!t?!0:!e||!t?!1:e.toUpperCase()===t.toUpperCase()}_.equalsIgnoreCase=KE;var v4=e=>{var t;return Di((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreateFlow)};_.doesUserHaveCreateFlowPermission=v4;var w4=e=>(0,_.doesUserHaveAdminPermission)(e)&&(0,_.hasCommonDataServiceDatabase)(e)?!0:(0,_.doesUserHaveCreateFlowPermission)(e)?Bl(e)||(0,_.doesUserHaveDatabaseTablePermissions)(e):!1;_.isUserPautoMakerWithDataAccess=w4;var C4=e=>(0,_.doesUserHaveCreateFlowPermission)(e)&&!Bl(e)&&!(0,_.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,_.doesUserHaveAdminPermission)(e)||!(0,_.hasCommonDataServiceDatabase)(e));_.isUserPautoMakerWithoutDataAccess=C4;var E4=e=>{var t,r;return!Di((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreateFlow)&&Di((r=e.properties)===null||r===void 0?void 0:r.permissions,Oe.environmentPermissions.ReadEnvironment)};_.doesUserHaveFlowRunOnlyPermission=E4});var Eh=v(A=>{"use strict";Object.defineProperty(A,"__esModule",{value:!0});A.getRequiredComponentsQueryUrl=A.solutionComponentCountSummariesQueryUrl=A.solutionComponentSummariesQueryUrl=A.solutionComponentConfigurationsQueryUrl=A.chartsQueryUrl=A.workflowsQueryUrl=A.entityDefinitionsQueryUrl=A.solutionComponentDefinitionsQueryUrl=A.getCreateNewArticleTemplateUrl=A.getCreateNewPublisherUrl=A.getEnableSecurityRolesUrl=A.getArticleTemplateUrl=A.getFieldSecurityProfileDesignerUrl=A.getSecurityRoleDesignerUrl=A.getMailMergeTemplateDesignerUrl=A.getEmailTemplateDesignerUrl=A.getConnectionRoleDesignerUrl=A.getSiteMapDesignerUrl=A.getWebResourceFileUrl=A.getWebResourceDesignerUrl=A.getReportDesignerUrl=A.getBusinessProcessFlowDesignerUrl=A.getProcessShareUrl=A.getProcessDesignerUrl=A.getChartDesignerUrl=A.getOpenModernEntityDashboardUrl=A.getNewModernEntityDashboardUrl=A.getNewModernDashboardUrl=A.getOpenModernDashboardUrl=A.getDashboardDesignerUrl=A.getAppModuleDesignerUrl=A.privilegesQueryUrls=A.xrmApiUrl=A.getPlayAppModuleUrl=A.getCrmAdminSecurityUsersUrl=A.getCrmAdminSecurityRolesUrl=A.getCrmMyAppsUrl=A.getCrmAppDesignerUrl=A.getCrmDevResourcesUrl=A.getCrmAllPublishersUrl=A.getCrmAllSolutionsUrl=A.getSolutionPublisherUrl=A.getExportTranslationFileName=A.getExportSolutionTranslationUrl=A.getImportSolutionTranslationUrl=A.getShowSolutionDependenciesUrl=A.getShowComponentDependenciesUrl=A.cdsServiceUrl=A.ODATA_NEXT_LINK=A.ODATA_MAX_PAGE_SIZE=void 0;A.retrieveOrganizationResources=A.getUCIEntityRecordEditUrl=A.getUCIEntityRecordBaseUrl=A.getBusinessRuleDesignerUri=A.retrieveUnpublishedSuffix=A.getSavePowerSettingUri=A.getPowerSettingUri=A.getPowerSettingsUri=A.RetrievePlatform=A.getAppSettingOverrideUri=A.AppSettingOverrideName=A.getOrgSettingOverrideUri=A.OrgSettingOverrideName=A.getSettingDefinitionsUri=A.retrieveFeatureControlSettingsByNamespaceUrl=A.retrieveDeploymentPipelineConfigAppUrl=A.SPNPrincipalIdUrl=A.retrieveDeploymentEnvironmentInfoUrl=A.devSolutionInfoUrl=A.deployOperationStatusUrl=A.getAIGeneratedDeploymentNotesUrl=A.deploymentStageRunUrl=A.validatePackageAsyncUrl=A.deployPackageAsyncUrl=A.updateDeploymentStageRunUrl=A.createDeploymentStageRunUrl=A.retrieveDeploymentStagesUrl=A.retrievePipelinesUrl=A.retrieveDeploymentPipelineInfoUrl=A.getDeploymentStageRunsUrl=A.appDeploymentUrls=A.getProvisionLanguageUrl=A.getSolutionQueryUrl=A.getSolutionsByUniqueNameQueryUrl=A.solutionsQueryUrl=A.getDependentComponentsWithMetadataQueryUrl=void 0;var YE=JE();A.ODATA_MAX_PAGE_SIZE="odata.maxpagesize";A.ODATA_NEXT_LINK="@odata.nextLink";A.cdsServiceUrl="https://cds-org/";var Vl;(function(e){e.AllSolutions="11",e.AllPublishers="10",e.DevResources="05"})(Vl||(Vl={}));function A4(e,t,r,n){return`${e}tools/dependency/dependencyviewdialog.aspx?appSolutionId=%7b${t}%7d&dType=1&objectid=%7b${r}%7d&objecttype=${n}&operationtype=showdependency`}A.getShowComponentDependenciesUrl=A4;function S4(e,t){let r=`dType=1&isproactivecheck=true&objecttype=7100&operationtype=dependenciesforuninstall&objectid=${t}`;return`${e}tools/dependency/dependencyviewdialog.aspx?${r}`}A.getShowSolutionDependenciesUrl=S4;function N4(e,t){return`${e}tools/muiProvisioning/Dialogs/LangTranslationsImport.aspx?dType=1&appSolutionId=${t}`}A.getImportSolutionTranslationUrl=N4;function _4(e,t){return`${e}_grid/cmds/dlg_exportsolution.aspx?command=exporttranslation&appSolutionId=${t}`}A.getExportSolutionTranslationUrl=_4;function T4(e,t){return e!==void 0&&t!==void 0&&`CrmTranslations_${e}_${t.replace(/[.]/g,"_")}.zip`||""}A.getExportTranslationFileName=T4;function D4(e,t,r){return r?`${e}tools/publisher/edit.aspx?appSolutionId=%7b${r}%7d&id=%7b${t}%7d`:`${e}tools/publisher/edit.aspx?id=%7b${t}%7d`}A.getSolutionPublisherUrl=D4;function Ah(e,t){return`${e}tools/systemcustomization/systemCustomization.aspx?pid=${t}`}function I4(e){return Ah(e,Vl.AllSolutions)}A.getCrmAllSolutionsUrl=I4;function O4(e){return Ah(e,Vl.AllPublishers)}A.getCrmAllPublishersUrl=O4;function P4(e){return Ah(e,Vl.DevResources)}A.getCrmDevResourcesUrl=P4;function R4(e,t=YE.crmBapSolutionId){return`${e}designer/app/${t}#/CreateNewApp`}A.getCrmAppDesignerUrl=R4;function L4(e){return`${e}apps`}A.getCrmMyAppsUrl=L4;function k4(e){return QE(e,"role")+"&forceUCI=0"}A.getCrmAdminSecurityRolesUrl=k4;function $4(e){return`${QE(e,"systemuser")}&forceclassic=1`}A.getCrmAdminSecurityUsersUrl=$4;function QE(e,t){return`${e}main.aspx?pagetype=entitylist&etn=${t}`}function x4(e,t){return`${e}main.aspx?appid=${t}`}A.getPlayAppModuleUrl=x4;A.xrmApiUrl="api/data/v9.0";A.privilegesQueryUrls={systemUserInfo:e=>`${e}${A.xrmApiUrl}/WhoAmI`,userPrivileges:(e,t)=>`${e}${A.xrmApiUrl}/systemusers(${t})/Microsoft.Dynamics.CRM.RetrieveUserPrivileges`,systemPrivileges:e=>`${e}${A.xrmApiUrl}/privileges/Microsoft.Dynamics.CRM.RetrievePrivilegeSet`};function F4(e,t,r=YE.crmBapSolutionId){return`${e}designer/app/${r}/${t}/AppDesignerCanvas/${t}`}A.getAppModuleDesignerUrl=F4;function M4(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${r}%7d&extraqs=%26formId%3d%7b${t}%7d%26dashboardType%3d1030&pagetype=${`${n?"ic":""}dashboardeditor`}`}A.getDashboardDesignerUrl=M4;function U4(e,t,r){return`/e/${e}/s/${t}/dashboard/${r}`}A.getOpenModernDashboardUrl=U4;function B4(e,t,r){let n=r!==void 0?r.toString():void 0;return`/e/${e}/s/${t}/dashboard/new${n?`/${n}`:""}`}A.getNewModernDashboardUrl=B4;function q4(e,t,r,n){let i=n!==void 0?n.toString():void 0;return`/e/${e}/s/${t}/n/${r}/dashboard/new${i?`/${i}`:""}`}A.getNewModernEntityDashboardUrl=q4;function V4(e,t,r,n){return`/e/${e}/s/${t}/n/${r}/dashboard/${n}`}A.getOpenModernEntityDashboardUrl=V4;function G4(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${t}%7d&extraqs=etc=${r||""}`+(n?`%26id=${n}`:"")+"&pagetype=vizdesigner"}A.getChartDesignerUrl=G4;function W4(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getProcessDesignerUrl=W4;function z4(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getProcessShareUrl=z4;function j4(e,t){return`${e}Tools/ProcessControl/UnifiedProcessDesigner.aspx?id=${t}`}A.getBusinessProcessFlowDesignerUrl=j4;function H4(e,t,r){return`${e}CRMReports/reportproperty.aspx?appSolutionId=%7b${r}%7d&disablePersonal=true&id=%7b${t}%7d`}A.getReportDesignerUrl=H4;function K4(e,t,r){return`${e}main.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&etc=9333&id=%7b${t}%7d&pagetype=webresourceedit`}A.getWebResourceDesignerUrl=K4;function J4(e,t){return`${e}WebResources/${t}`}A.getWebResourceFileUrl=J4;function Y4(e,t,r){return`${e}designer/sitemap/${r}/${t}/SiteMapHome/${t}`}A.getSiteMapDesignerUrl=Y4;function Q4(e,t,r){return`${e}connections/connectionroles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getConnectionRoleDesignerUrl=Q4;function X4(e,t,r){return`${e}tools/emailtemplateeditor/emailtemplateeditor.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getEmailTemplateDesignerUrl=X4;function Z4(e,t,r){return`${e}tools/mailmerge/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getMailMergeTemplateDesignerUrl=Z4;function eV(e,t,r){return`${e}biz/roles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getSecurityRoleDesignerUrl=eV;function tV(e,t,r){return`${e}biz/fieldsecurityprofiles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getFieldSecurityProfileDesignerUrl=tV;function rV(e,t,r){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?_CreateFromId=%7b${t}%7d&_CreateFromType=7100&appSolutionId=%7b${t}%7d&id=%7b${r}%7d`}A.getArticleTemplateUrl=rV;function nV(e,t,r,n){return`${e}tools/FormEditor/Dialogs/FormRoleAssignment.aspx?appSolutionId=%7b${t}%7d&dType=1&formId=%7b${r}%7d&objectTypeCode=0&type=${n}`}A.getEnableSecurityRolesUrl=nV;function iV(e){return`${e}tools/publisher/edit.aspx`}A.getCreateNewPublisherUrl=iV;function oV(e,t){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?appSolutionId=${t}`}A.getCreateNewArticleTemplateUrl=oV;A.solutionComponentDefinitionsQueryUrl="api/data/v9.0/solutioncomponentdefinitions";A.entityDefinitionsQueryUrl="api/data/v9.0/EntityDefinitions?$select=EntitySetName,DisplayName,LogicalName&$filter=";A.workflowsQueryUrl="api/data/v9.0/workflows";A.chartsQueryUrl="/api/data/v9.0/savedqueryvisualizations";A.solutionComponentConfigurationsQueryUrl="/api/data/v9.1/solutioncomponentconfigurations?$filter=isdisplayable eq true&$select=name";A.solutionComponentSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentsummaries";A.solutionComponentCountSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentcountsummaries";function aV(e,t){return`${A.xrmApiUrl}/RetrieveRequiredComponents(ObjectId=${e},ComponentType=${t})`}A.getRequiredComponentsQueryUrl=aV;function sV(e,t){return`${A.cdsServiceUrl}${A.xrmApiUrl}/RetrieveDependentComponentsWithMetadata(ObjectId=${e},ComponentType=${t})`}A.getDependentComponentsWithMetadataQueryUrl=sV;A.solutionsQueryUrl="/api/data/v9.0/solutions?$expand=publisherid&$filter=(isvisible eq true)";function lV(e){return`/api/data/v9.0/solutions?$expand=publisherid&$filter=(uniquename eq '${e}')`}A.getSolutionsByUniqueNameQueryUrl=lV;function uV(e){return`/api/data/v9.0/solutions(${e})?$expand=publisherid`}A.getSolutionQueryUrl=uV;function cV(e){return`${e}api/data/v9.1/ProvisionLanguageForUser`}A.getProvisionLanguageUrl=cV;A.appDeploymentUrls={associateEnvironmentToPipelineUrl:e=>`/api/data/v9.0/deploymentpipelines(${e})/deploymentpipeline_deploymentenvironment/$ref`,deploymentArtifactsUrl:"/api/data/v9.0/deploymentartifacts",deploymentEnvironmentUrl:"/api/data/v9.0/deploymentenvironments",deploymentPipelinesUrl:"/api/data/v9.0/deploymentpipelines",deploymentStagesUrl:"/api/data/v9.0/deploymentstages",retrieveDeploymentPipelinesUrl:e=>`/api/data/v9.0/RetrieveDeploymentPipelines(SourceEnvironmentId='${e}')`,deletePipelinesUrl:e=>`/api/data/v9.0/deploymentpipelines(${e})`};function dV(e,t,r,n=!1,i=!1,o=!1,a=!1,s=!1,l=!1,u=!1){return`/api/data/v9.1/deploymentstageruns?$select=artifactname,artifactversion,deploymentstagerunid,devenvironmentid,endtime,errormessage,${s?"_artifactid_value,isredeployment,":""}${n?"deploymentnotes,":""}operation,operationdetails,operationstatus,${l?"retrycount,":""}${i?"scheduledtime,":""}${u?"solutionid,":""}stagerunstatus,starttime,suboperation,targetenvironmentid,${o?"predeploymentstepnotes,":""}validationresults,${a?"approvalcomments,":""}_devdeploymentenvironment_value,_targetdeploymentenvironment_value&$expand=deploymentstageid($select=deploymentstageid,name,_deploymentpipelineid_value),targetdeploymentenvironment($select=deploymentenvironmentid,environmentid,name),createdby($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)${l?",RetryUser($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)":""}&$filter=deploymentstageid/_deploymentpipelineid_value eq ${e} and devenvironmentid eq '${t}' and artifactname eq '${r}' and ((operation ne 200000201) or (operation eq 200000201 and operationstatus eq 200000003))- &$orderby=starttime desc`}S.getDeploymentStageRunsUrl=l3;function u3(e,t,r){return`/api/data/v9.1/RetrieveDeploymentPipelineInfo(DeploymentPipelineId=${e},SourceEnvironmentId='${t}',ArtifactName='${r}')`}S.retrieveDeploymentPipelineInfoUrl=u3;function c3(e){return`/api/data/v9.0/deploymentenvironments+ &$orderby=starttime desc`}A.getDeploymentStageRunsUrl=dV;function fV(e,t,r){return`/api/data/v9.1/RetrieveDeploymentPipelineInfo(DeploymentPipelineId=${e},SourceEnvironmentId='${t}',ArtifactName='${r}')`}A.retrieveDeploymentPipelineInfoUrl=fV;function pV(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}')`}S.retrievePipelinesUrl=c3;function d3(e){return`/api/data/v9.0/deploymentstages+ &$filter=(environmentid eq '${e}')`}A.retrievePipelinesUrl=pV;function mV(e){return`/api/data/v9.0/deploymentstages?$filter=(_deploymentpipelineid_value eq ${e})&$select=name,description,deploymentstageid,_previousdeploymentstageid_value- &$expand=targetdeploymentenvironmentid($select=deploymentenvironmentid,environmentid,name)`}S.retrieveDeploymentStagesUrl=d3;function f3(){return"/api/data/v9.0/deploymentstageruns?$select=deploymentstagerunid"}S.createDeploymentStageRunUrl=f3;function p3(e){return`/api/data/v9.0/deploymentstageruns(${e})`}S.updateDeploymentStageRunUrl=p3;function m3(){return"/api/data/v9.0/DeployPackageAsync"}S.deployPackageAsyncUrl=m3;function h3(){return"/api/data/v9.0/ValidatePackageAsync"}S.validatePackageAsyncUrl=h3;function g3(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)":""}`}S.deploymentStageRunUrl=g3;function y3(e){return`/api/data/v9.0/deploymentstageruns(${e})- ?$select=aigenerateddeploymentnotes,deploymentstagerunid`}S.getAIGeneratedDeploymentNotesUrl=y3;function b3(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)`}A.retrieveDeploymentStagesUrl=mV;function hV(){return"/api/data/v9.0/deploymentstageruns?$select=deploymentstagerunid"}A.createDeploymentStageRunUrl=hV;function gV(e){return`/api/data/v9.0/deploymentstageruns(${e})`}A.updateDeploymentStageRunUrl=gV;function yV(){return"/api/data/v9.0/DeployPackageAsync"}A.deployPackageAsyncUrl=yV;function bV(){return"/api/data/v9.0/ValidatePackageAsync"}A.validatePackageAsyncUrl=bV;function vV(e,t=!1,r=!1){return`/api/data/v9.0/deploymentstageruns(${e})+ ?$select=deploymentstagerunid,stagerunstatus,errormessage,operation,operationdetails,operationstatus,${t?"scheduledtime,":""}targetenvironmentid,validationresults,artifactname,deploymentsettingsjson${r?"&$expand=createdby($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)":""}`}A.deploymentStageRunUrl=vV;function wV(e){return`/api/data/v9.0/deploymentstageruns(${e})+ ?$select=aigenerateddeploymentnotes,deploymentstagerunid`}A.getAIGeneratedDeploymentNotesUrl=wV;function CV(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`}S.deployOperationStatusUrl=b3;function v3(e){return`/api/data/v9.0/solutions(${e})- ?$select=solutionid,uniquename,version`}S.devSolutionInfoUrl=v3;function w3(e){return`/api/data/v9.0/deploymentenvironments+ &$select=_deploymentstageid_value,deploymentstagerunid,stagerunstatus,operation,operationstatus,suboperation,artifactname`}A.deployOperationStatusUrl=CV;function EV(e){return`/api/data/v9.0/solutions(${e})+ ?$select=solutionid,uniquename,version`}A.devSolutionInfoUrl=EV;function AV(e){return`/api/data/v9.0/deploymentenvironments?$select=deploymentenvironmentid,environmentid,environmenttype,name- &$filter=(environmentid eq '${e}')`}S.retrieveDeploymentEnvironmentInfoUrl=w3;var C3=e=>`/api/data/v9.0/systemusers+ &$filter=(environmentid eq '${e}')`}A.retrieveDeploymentEnvironmentInfoUrl=AV;var SV=e=>`/api/data/v9.0/systemusers?$select=azureactivedirectoryobjectid- &$filter=(applicationid eq '${e}')`;S.SPNPrincipalIdUrl=C3;function E3(){return"/api/data/v9.0/appmodules?$filter=(uniquename eq 'AppDeploymentConfiguration')"}S.retrieveDeploymentPipelineConfigAppUrl=E3;S.retrieveFeatureControlSettingsByNamespaceUrl="/api/data/v9.1/RetrieveFeatureControlSettingsByNamespace";function A3(e){return`/api/data/v9.0/settingdefinitions${e}`}S.getSettingDefinitionsUri=A3;S.OrgSettingOverrideName="organizationsettings";function S3(e,t=!1){let r=`/api/data/v9.0/${S.OrgSettingOverrideName}${e}`;return t?`${S.cdsServiceUrl}${r}`:r}S.getOrgSettingOverrideUri=S3;S.AppSettingOverrideName="appsettings";function N3(e,t=!1){let r=`/api/data/v9.0/${S.AppSettingOverrideName}${e}`;return t?`${S.cdsServiceUrl.replace("/$","")}${r}`:r}S.getAppSettingOverrideUri=N3;var wl;(function(e){e[e.All=0]="All",e[e.IsPlatformOnly=1]="IsPlatformOnly",e[e.NotPlatformOnly=2]="NotPlatformOnly"})(wl||(S.RetrievePlatform=wl={}));function _3(e,t,r,n=wl.All,i=!1){let o=[];e&&o.push(`AppUniqueName='${e}'`),t!=null&&o.push(`ReleaseLevel=${t}`),r&&o.push(`RetrieveHiddenSettings=${r}`),n!==wl.All&&o.push(`RetrievePlatformSettings=${n===wl.IsPlatformOnly?1:0}`);let a="/api/data/v9.0/RetrieveUnpublishedOverridableSettingsInfo";return o.length&&(a=`${a}(${o.join(",")})`),i?`${S.cdsServiceUrl}${a}`:a}S.getPowerSettingsUri=_3;function T3(e,t,r,n=!1){let i=[`SettingName='${e}'`];t!==void 0&&i.push(`SolutionName='${t}'`),r!==void 0&&i.push(`AppUniqueName='${r}'`);let o="/api/data/v9.0/RetrieveUnpublishedSettingInfo";return i.length&&(o=`${o}(${i.join(",")})`),n?`${S.cdsServiceUrl}${o}`:o}S.getPowerSettingUri=T3;function D3(e=!1){let t="/api/data/v9.0/SaveSettingValue()";return e?`${S.cdsServiceUrl}${t}`:t}S.getSavePowerSettingUri=D3;S.retrieveUnpublishedSuffix="Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()";function I3(e){return`tools/systemcustomization/businessrules/businessRulesDesigner.aspx?BRlaunchpoint=BRGrid&appSolutionId={${e}}`}S.getBusinessRuleDesignerUri=I3;function XC({environmentInstanceUrl:e,entityLogicalName:t}){return e&&t?`${e}main.aspx?cmdbar=true&forceUCI=1&navbar=off&newWindow=true&pageType=entityRecord&etn=${t}`:void 0}S.getUCIEntityRecordBaseUrl=XC;function O3({baseUrl:e,environmentInstanceUrl:t,entityLogicalName:r,recordId:n}){let i=e||XC({environmentInstanceUrl:t,entityLogicalName:r});return i&&n?`${i}&id=${n}`:void 0}S.getUCIEntityRecordEditUrl=O3;S.retrieveOrganizationResources=`${S.cdsServiceUrl}api/data/v9.0/RetrieveOrganizationResources`});var tE=v(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});Dc.DataverseClient=void 0;var P3=xm(),$o=Q(),ZC=ye(),R3=new Set(["entitydefinitions","relationshipdefinitions","globaloptionsetdefinitions"]);function L3(e){var t,r,n,i;let o=e.split("?")[0].split("/").filter(l=>l!==""),a=((t=o[0])===null||t===void 0?void 0:t.toLowerCase())==="api"&&((r=o[1])===null||r===void 0?void 0:r.toLowerCase())==="data"&&/^v\d/i.test((n=o[2])!==null&&n!==void 0?n:""),s=((i=o[a?3:0])!==null&&i!==void 0?i:"").split("(")[0].toLowerCase();return R3.has(s)}function k3(e){let t=e.indexOf("://"),r=t===-1?"":e.slice(t+3),n=r.search(/[/?#]/),i=n===-1?"":r.slice(n),o=i.search(/[?#]/);return o===-1?i:i.slice(0,o)}function eE(e,t){var r;if(!L3(e))return t;let n=(r=t?.headers)!==null&&r!==void 0?r:{};return Object.keys(n).some(i=>i.toLowerCase()==="consistency")?t:{...t,headers:{...n,Consistency:"Strong"}}}var Fm=class{constructor(t,r,n,i=1){this.instanceUrl=t,this.httpClient=r,this.solutionUniqueName=n,this.readConcurrency=i}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}/${P3.xrmApiUrl}${n}`}async send(t,r){try{return await r()}catch(n){throw n instanceof $o.SdkError?n:new $o.ConnectionError(t,0,n instanceof Error?n.message:String(n),n)}}get(t,r){let n=this.apiUrl(t),i=eE(t,r);return(0,ZC.resendDeadlockVictim)(()=>this.send(n,()=>this.httpClient.get(n,i)))}getAbsolute(t,r){this.assertSameOrigin(t);let n=eE(k3(t),r);return(0,ZC.resendDeadlockVictim)(()=>this.send(t,()=>this.httpClient.get(t,n)))}assertSameOrigin(t){let r,n;try{r=new URL(t),n=new URL(this.instanceUrl)}catch{throw new $o.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${t}'`)}if(r.protocol!==n.protocol||r.host!==n.host)throw new $o.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 $o.InvalidArgumentError("The injected HttpClient does not implement postRaw(), required for atomic $batch change sets");let i=this.apiUrl("/$batch"),o={...n,headers:{...n?.headers,"Content-Type":`multipart/mixed;boundary=${r}`}};return this.send(i,()=>this.httpClient.postRaw(i,t,o))}patch(t,r,n){let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.patch(i,r,this.withSolution(n)))}get supportsBinaryPatch(){return typeof this.httpClient.patchRaw=="function"}patchRaw(t,r,n){if(!this.httpClient.patchRaw)throw new $o.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 $o.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)))}};Dc.DataverseClient=Fm});var iE=v(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.findColumns=Zt.findTables=Zt.readCheckColumns=Zt.readColumnHints=Zt.fetchEntityMetadataFromApi=Zt.COLUMN_DETAIL_VERSION=void 0;var Pc=ye(),fr=ue();function Jr(e){var t,r;return(r=(t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)!==null&&r!==void 0?r:""}Zt.COLUMN_DETAIL_VERSION=2;function Mm(e){var t,r;return typeof((t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)=="string"||((r=e?.LocalizedLabels)!==null&&r!==void 0?r:[]).some(n=>typeof n?.Label=="string")}function Fo(e){let t=e?.LocalizedLabels;if(!Array.isArray(t)||t.length<2)return;let r={};for(let n of t)typeof n?.LanguageCode=="number"&&typeof n.Label=="string"&&(r[n.LanguageCode]=n.Label);return Object.keys(r).length?r:void 0}async function Ic(e,t){return(await Rc(e,t)).rows}async function Rc(e,t){var r,n;let i=await e.get(t);return i.status<200||i.status>=300?{rows:[],ok:!1}:{rows:(n=(r=i.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[],ok:!0}}function Fr(e){return`/EntityDefinitions(LogicalName='${(0,fr.odataPathLiteral)(e)}')`}async function x3(e,t,r){let n=await Ic(e,`${Fr(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata${(0,fr.odataQuery)([["$select","LogicalName,MaxLength"]])}`);for(let i of n){let o=r.get(i.LogicalName);o&&typeof i.MaxLength=="number"&&(o.maxLength=i.MaxLength)}}function $3(e){return`${Fr(e)}/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata${(0,fr.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`}async function F3(e,t){var r;let{rows:n}=await e;for(let i of n){let o=t.get(i.LogicalName);o&&(!((r=i.OptionSet)===null||r===void 0)&&r.Options)&&(o.options=i.OptionSet.Options.map(a=>{var s;return{value:(s=a.Value)!==null&&s!==void 0?s:0,label:Jr(a.Label),...Fo(a.Label)?{localizedLabel:Fo(a.Label)}:{}}}))}}function Um(e){var t;return{value:(t=e.Value)!==null&&t!==void 0?t:0,label:Jr(e.Label),...e.InvariantName?{invariantName:e.InvariantName}:{},...e.Color?{color:e.Color}:{}}}async function M3(e,t,r){var n;let i=c=>Rc(e,c).catch(()=>({rows:[],ok:!1})),o=["MultiSelectPicklistAttributeMetadata","StateAttributeMetadata","StatusAttributeMetadata"],a=await Promise.all([r.catch(()=>({rows:[],ok:!1})),...o.map(c=>i(`${Fr(t)}/Attributes/Microsoft.Dynamics.CRM.${c}${(0,fr.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`))]),s=new Map,l=!0;for(let{rows:c}of a)for(let d of c)!((n=d.OptionSet)===null||n===void 0)&&n.Options&&(l=l&&d.OptionSet.Options.every(f=>Mm(f.Label)),s.set(d.LogicalName,d.OptionSet.Options.map(Um)));let u=await i(`${Fr(t)}/Attributes/Microsoft.Dynamics.CRM.BooleanAttributeMetadata${(0,fr.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=TrueOption,FalseOption)"]])}`);for(let c of u.rows){let d=c.OptionSet;d?.TrueOption&&d.FalseOption&&(l=l&&Mm(d.TrueOption.Label)&&Mm(d.FalseOption.Label),s.set(c.LogicalName,[Um(d.FalseOption),Um(d.TrueOption)]))}return{byColumn:s,complete:l&&u.ok&&a.every(c=>c.ok)}}async function U3(e,t,r){let{rows:n,ok:i}=await Rc(e,`${Fr(t)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata${(0,fr.odataQuery)([["$select","LogicalName,Targets"]])}`);for(let o of n){let a=r.get(o.LogicalName);a&&o.Targets&&(a.targets=o.Targets)}return i}function Oc(e,t){return e<t?-1:e>t?1:0}var rE={OneToMany:0,ManyToOne:1,ManyToMany:2};function B3(e,t){return rE[e.type]-rE[t.type]||Oc(e.schemaName,t.schemaName)||Oc(e.relatedEntity,t.relatedEntity)||Oc(e.relatedAttribute,t.relatedAttribute)}async function q3(e,t){var r,n,i,o;let a=[],s=await Ic(e,`${Fr(t)}/OneToManyRelationships${(0,fr.odataQuery)([["$select","SchemaName,ReferencingEntity,ReferencingAttribute"]])}`);for(let c of s)a.push({schemaName:c.SchemaName,type:"OneToMany",relatedEntity:(r=c.ReferencingEntity)!==null&&r!==void 0?r:"",relatedAttribute:(n=c.ReferencingAttribute)!==null&&n!==void 0?n:""});let l=await Ic(e,`${Fr(t)}/ManyToOneRelationships${(0,fr.odataQuery)([["$select","SchemaName,ReferencedEntity,ReferencedAttribute"]])}`);for(let c of l)a.push({schemaName:c.SchemaName,type:"ManyToOne",relatedEntity:(i=c.ReferencedEntity)!==null&&i!==void 0?i:"",relatedAttribute:(o=c.ReferencedAttribute)!==null&&o!==void 0?o:""});let u=await Ic(e,`${Fr(t)}/ManyToManyRelationships${(0,fr.odataQuery)([["$select","SchemaName,Entity1LogicalName,Entity2LogicalName"]])}`);for(let c of u){let d=c.Entity1LogicalName===t?c.Entity2LogicalName:c.Entity1LogicalName;a.push({schemaName:c.SchemaName,type:"ManyToMany",relatedEntity:d??"",relatedAttribute:""})}return a.sort(B3)}async function V3(e,t){var r,n,i,o,a;let s=`${Fr(t)}`+(0,fr.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,Description,EntitySetName,IsCustomEntity,PrimaryNameAttribute,PrimaryIdAttribute,PrimaryImageAttribute"],["$expand","Attributes($select=LogicalName,DisplayName,Description,AttributeType,AttributeTypeName,IsCustomAttribute,IsValidForUpdate,IsValidForRead,AttributeOf)"]]),u=(0,Pc.ensureSuccess)(await e.get(s),e.apiUrl(s)).body,c=((r=u.Attributes)!==null&&r!==void 0?r:[]).map(g=>{var b,w,E;return{logicalName:g.LogicalName,displayName:Jr(g.DisplayName),...Fo(g.DisplayName)?{localizedDisplayName:Fo(g.DisplayName)}:{},attributeType:(b=g.AttributeType)!==null&&b!==void 0?b:"Unknown",isCustomAttribute:!!g.IsCustomAttribute,attributeTypeName:(E=(w=g.AttributeTypeName)===null||w===void 0?void 0:w.Value)!==null&&E!==void 0?E:"",...typeof g.IsValidForUpdate=="boolean"?{isValidForUpdate:g.IsValidForUpdate}:{},...typeof g.IsValidForRead=="boolean"?{isValidForRead:g.IsValidForRead}:{},...g.AttributeOf?{attributeOf:g.AttributeOf}:{},...Jr(g.Description)?{description:Jr(g.Description)}:{}}}).sort((g,b)=>Oc(g.logicalName,b.logicalName)),d=new Map(c.map(g=>[g.logicalName,g])),f=Rc(e,$3(t)),[,,p,m,h]=await Promise.all([x3(e,t,d),F3(f,d),M3(e,t,f),U3(e,t,d),q3(e,t)]);for(let g of c){let b=p.byColumn.get(g.logicalName);b&&(g.choices=b)}return{logicalName:u.LogicalName,schemaName:(n=u.SchemaName)!==null&&n!==void 0?n:u.LogicalName,displayName:Jr(u.DisplayName),...Fo(u.DisplayName)?{localizedDisplayName:Fo(u.DisplayName)}:{},entitySetName:(i=u.EntitySetName)!==null&&i!==void 0?i:"",primaryNameAttribute:(o=u.PrimaryNameAttribute)!==null&&o!==void 0?o:"",primaryIdAttribute:(a=u.PrimaryIdAttribute)!==null&&a!==void 0?a:"",...u.PrimaryImageAttribute?{primaryImageAttribute:u.PrimaryImageAttribute}:{},isCustomEntity:!!u.IsCustomEntity,...Jr(u.Description)?{description:Jr(u.Description)}:{},columnDetailComplete:p.complete&&m,columnDetailVersion:Zt.COLUMN_DETAIL_VERSION,attributes:c,relationships:h}}Zt.fetchEntityMetadataFromApi=V3;var nE=40;async function Bm(e,t,r,n){var i,o;let a=[...new Set(n.filter(l=>l!==""))],s=[];for(let l=0;l<a.length;l+=nE){let u=a.slice(l,l+nE).map(f=>`LogicalName eq '${(0,fr.odataLiteral)(f)}'`).join(" or "),c=t+(0,fr.odataQuery)([["$select",r],["$filter",u]]),d=(0,Pc.ensureSuccess)(await e.get(c),e.apiUrl(c));s.push(...(o=(i=d.body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[])}return s}async function G3(e,t,r){return(await Bm(e,`${Fr(t)}/Attributes`,"LogicalName,AttributeType,DisplayName",r)).map(i=>{var o;let a=Fo(i.DisplayName);return{logicalName:i.LogicalName,displayName:Jr(i.DisplayName),...a?{localizedDisplayName:a}:{},attributeType:(o=i.AttributeType)!==null&&o!==void 0?o:"Unknown"}})}Zt.readColumnHints=G3;async function W3(e,t,r){let i=(await Bm(e,`${Fr(t)}/Attributes`,"LogicalName,AttributeType,DisplayName,IsCustomAttribute",r)).map(s=>{var l;return{logicalName:s.LogicalName,displayName:Jr(s.DisplayName),attributeType:(l=s.AttributeType)!==null&&l!==void 0?l:"Unknown",isCustomAttribute:!!s.IsCustomAttribute}}),o=new Map(i.filter(s=>s.attributeType==="String").map(s=>[s.logicalName,s])),a=await Bm(e,`${Fr(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata`,"LogicalName,MaxLength",[...o.keys()]);for(let s of a){let l=o.get(s.LogicalName);l&&typeof s.MaxLength=="number"&&(l.maxLength=s.MaxLength)}return i}Zt.readCheckColumns=W3;async function z3(e,t,r){var n,i;let o=`/EntityDefinitions${(0,fr.odataQuery)([["$select","LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity"]])}`,s=(i=(n=(0,Pc.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[],l=(t??"").toLowerCase(),u=s.filter(c=>!r?.customOnly||c.IsCustomEntity).map(c=>{var d,f;return{logicalName:c.LogicalName,schemaName:(d=c.SchemaName)!==null&&d!==void 0?d:c.LogicalName,displayName:Jr(c.DisplayName),entitySetName:(f=c.EntitySetName)!==null&&f!==void 0?f:"",isCustom:!!c.IsCustomEntity}}).filter(c=>c.logicalName.toLowerCase().includes(l)||c.schemaName.toLowerCase().includes(l)||c.displayName.toLowerCase().includes(l));return typeof r?.top=="number"?u.slice(0,r.top):u}Zt.findTables=z3;async function j3(e,t,r,n){var i,o;let a=`${Fr(t)}/Attributes`+(0,fr.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute"]]),l=(o=(i=(0,Pc.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[],u=(r??"").toLowerCase(),c=l.map(d=>{var f,p;return{logicalName:d.LogicalName,schemaName:(f=d.SchemaName)!==null&&f!==void 0?f:d.LogicalName,displayName:Jr(d.DisplayName),attributeType:(p=d.AttributeType)!==null&&p!==void 0?p:"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}Zt.findColumns=j3});var Gm=v(pr=>{"use strict";Object.defineProperty(pr,"__esModule",{value:!0});pr.renderTypeRegistrations=pr.buildGenPageLegacyEnums=pr.renderGenPageAuthoringTypes=pr.buildGenPageRuntimeTypes=pr.toDesignerEntity=pr.TABLE_LOGICAL_NAME=void 0;pr.TABLE_LOGICAL_NAME=/^[a-z_][a-z0-9_]*$/;function qm(e){return e.replace(/[\r\n\u2028\u2029]+/g," ")}var H3=new Set(["createdby","createdon","createdonbehalfby","importsequencenumber","modifiedby","modifiedon","modifiedonbehalfby","overriddencreatedon","ownerid","owningbusinessunit","owningteam","owninguser","timezoneruleversionnumber","utcconversiontimezonecode","versionnumber"]);function Lc(e){var t;return((t=e.attributeTypeName)!==null&&t!==void 0?t:"").replace(/Type$/,"").toLowerCase()}function sE(e){var t,r;let n=e.choices;if(!n||n.length===0)return;let i=Lc(e)==="boolean",o={};for(let a of n)o[a.value]={text:(r=(t=a.invariantName)!==null&&t!==void 0?t:a.label)!==null&&r!==void 0?r:"",value:a.value,...!i&&a.color?{color:a.color}:{}};return o}function oE(e,t){return e.logicalName<t.logicalName?-1:e.logicalName>t.logicalName?1:0}function lE(e){return!H3.has(e.logicalName)&&(!e.attributeOf||Lc(e)==="image")&&e.isValidForRead!==!1}var aE=new Set(["boolean","picklist","multiselectpicklist","state","status"]);function uE(e){let t=e.primaryImageAttribute,r=new Set([e.primaryIdAttribute,e.primaryNameAttribute,t,t?`${t}_url`:void 0,"processid","statecode","statuscode"].filter(o=>!!o)),n=e.attributes.filter(o=>r.has(o.logicalName)).sort(oE),i=e.attributes.filter(o=>!r.has(o.logicalName)).sort(oE);return[...n,...i]}function Vm(e){var t;let r=[],n=new Set,i=uE(e);for(let o of i){let a=Lc(o),s=a==="image";lE(o)&&(s&&o.attributeOf&&n.add(o.attributeOf),r.push({AttributeTypeName:a,IsReadOnly:!o.isValidForUpdate,LogicalName:o.logicalName,OptionSet:sE(o),Targets:o.targets,Description:o.description,MaxLength:o.maxLength}))}return{Description:(t=e.description)!==null&&t!==void 0?t:"",LogicalName:e.logicalName,PrimaryIdAttribute:e.primaryIdAttribute,Attributes:r.filter(o=>!n.has(o.LogicalName))}}pr.toDesignerEntity=Vm;function cE(e,t="None"){let r={};for(let n of e)r[n.logicalName]=Vm(n);return pE(r,t)}pr.buildGenPageRuntimeTypes=cE;var dE=`export interface TableRegistrations extends BaseTableRegistrations {-`,fE=`export interface EnumRegistrations extends BaseEnumRegistrations {-`;function K3(e,t){return e.length>0?cE(e,t).text:hE(`${dE}}-`,`${fE}}-`,"","")}pr.renderGenPageAuthoringTypes=K3;function J3(e){let t=new Set;for(let n of e)for(let i of Vm(n).Attributes)aE.has(i.AttributeTypeName)&&t.add(`${n.logicalName}_${i.LogicalName}`);let r=new Map;for(let n of e)for(let i of uE(n)){let o=`${n.logicalName}_${i.logicalName}`,a=sE(i);if(lE(i)||!aE.has(Lc(i))||!a||t.has(o)||r.has(o))continue;let s={name:o,runtime:{},labels:new Map};r.set(o,{declaration:mE(o,a,!1,s),model:s})}return r}pr.buildGenPageLegacyEnums=J3;function pE(e,t="None"){var r,n;let i=new Map,o=Object.values(e);if(o.length===0)return{text:"",enums:i};let a=t==="ColorsDefaultsConstraints"||t==="ColorsDefaultsConstraintsDescriptions",s=t==="ColorsDefaultsConstraintsDescriptions",l=dE,u=fE,c="",d="";for(let f of o){s&&f.Description&&(c+=`// ${qm(f.Description)}+ &$filter=(applicationid eq '${e}')`;A.SPNPrincipalIdUrl=SV;function NV(){return"/api/data/v9.0/appmodules?$filter=(uniquename eq 'AppDeploymentConfiguration')"}A.retrieveDeploymentPipelineConfigAppUrl=NV;A.retrieveFeatureControlSettingsByNamespaceUrl="/api/data/v9.1/RetrieveFeatureControlSettingsByNamespace";function _V(e){return`/api/data/v9.0/settingdefinitions${e}`}A.getSettingDefinitionsUri=_V;A.OrgSettingOverrideName="organizationsettings";function TV(e,t=!1){let r=`/api/data/v9.0/${A.OrgSettingOverrideName}${e}`;return t?`${A.cdsServiceUrl}${r}`:r}A.getOrgSettingOverrideUri=TV;A.AppSettingOverrideName="appsettings";function DV(e,t=!1){let r=`/api/data/v9.0/${A.AppSettingOverrideName}${e}`;return t?`${A.cdsServiceUrl.replace("/$","")}${r}`:r}A.getAppSettingOverrideUri=DV;var ql;(function(e){e[e.All=0]="All",e[e.IsPlatformOnly=1]="IsPlatformOnly",e[e.NotPlatformOnly=2]="NotPlatformOnly"})(ql||(A.RetrievePlatform=ql={}));function IV(e,t,r,n=ql.All,i=!1){let o=[];e&&o.push(`AppUniqueName='${e}'`),t!=null&&o.push(`ReleaseLevel=${t}`),r&&o.push(`RetrieveHiddenSettings=${r}`),n!==ql.All&&o.push(`RetrievePlatformSettings=${n===ql.IsPlatformOnly?1:0}`);let a="/api/data/v9.0/RetrieveUnpublishedOverridableSettingsInfo";return o.length&&(a=`${a}(${o.join(",")})`),i?`${A.cdsServiceUrl}${a}`:a}A.getPowerSettingsUri=IV;function OV(e,t,r,n=!1){let i=[`SettingName='${e}'`];t!==void 0&&i.push(`SolutionName='${t}'`),r!==void 0&&i.push(`AppUniqueName='${r}'`);let o="/api/data/v9.0/RetrieveUnpublishedSettingInfo";return i.length&&(o=`${o}(${i.join(",")})`),n?`${A.cdsServiceUrl}${o}`:o}A.getPowerSettingUri=OV;function PV(e=!1){let t="/api/data/v9.0/SaveSettingValue()";return e?`${A.cdsServiceUrl}${t}`:t}A.getSavePowerSettingUri=PV;A.retrieveUnpublishedSuffix="Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()";function RV(e){return`tools/systemcustomization/businessrules/businessRulesDesigner.aspx?BRlaunchpoint=BRGrid&appSolutionId={${e}}`}A.getBusinessRuleDesignerUri=RV;function XE({environmentInstanceUrl:e,entityLogicalName:t}){return e&&t?`${e}main.aspx?cmdbar=true&forceUCI=1&navbar=off&newWindow=true&pageType=entityRecord&etn=${t}`:void 0}A.getUCIEntityRecordBaseUrl=XE;function LV({baseUrl:e,environmentInstanceUrl:t,entityLogicalName:r,recordId:n}){let i=e||XE({environmentInstanceUrl:t,entityLogicalName:r});return i&&n?`${i}&id=${n}`:void 0}A.getUCIEntityRecordEditUrl=LV;A.retrieveOrganizationResources=`${A.cdsServiceUrl}api/data/v9.0/RetrieveOrganizationResources`});var tA=v(rd=>{"use strict";Object.defineProperty(rd,"__esModule",{value:!0});rd.DataverseClient=void 0;var kV=Eh(),Jo=Q(),ZE=fe(),$V=new Set(["entitydefinitions","relationshipdefinitions","globaloptionsetdefinitions"]);function xV(e){var t,r,n,i;let o=e.split("?")[0].split("/").filter(l=>l!==""),a=((t=o[0])===null||t===void 0?void 0:t.toLowerCase())==="api"&&((r=o[1])===null||r===void 0?void 0:r.toLowerCase())==="data"&&/^v\d/i.test((n=o[2])!==null&&n!==void 0?n:""),s=((i=o[a?3:0])!==null&&i!==void 0?i:"").split("(")[0].toLowerCase();return $V.has(s)}function FV(e){let t=e.indexOf("://"),r=t===-1?"":e.slice(t+3),n=r.search(/[/?#]/),i=n===-1?"":r.slice(n),o=i.search(/[?#]/);return o===-1?i:i.slice(0,o)}function eA(e,t){var r;if(!xV(e))return t;let n=(r=t?.headers)!==null&&r!==void 0?r:{};return Object.keys(n).some(i=>i.toLowerCase()==="consistency")?t:{...t,headers:{...n,Consistency:"Strong"}}}var Sh=class e{constructor(t,r,n,i=1){this.instanceUrl=t,this.httpClient=r,this.solutionUniqueName=n,this.readConcurrency=i}withSolutionScope(t){return new e(this.instanceUrl,this.httpClient,t,this.readConcurrency)}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}/${kV.xrmApiUrl}${n}`}async send(t,r){try{return await r()}catch(n){throw n instanceof Jo.SdkError?n:new Jo.ConnectionError(t,0,n instanceof Error?n.message:String(n),n)}}get(t,r){let n=this.apiUrl(t),i=eA(t,r);return(0,ZE.resendDeadlockVictim)(()=>this.send(n,()=>this.httpClient.get(n,i)))}getAbsolute(t,r){this.assertSameOrigin(t);let n=eA(FV(t),r);return(0,ZE.resendDeadlockVictim)(()=>this.send(t,()=>this.httpClient.get(t,n)))}assertSameOrigin(t){let r,n;try{r=new URL(t),n=new URL(this.instanceUrl)}catch{throw new Jo.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${t}'`)}if(r.protocol!==n.protocol||r.host!==n.host)throw new Jo.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 supportsPut(){return typeof this.httpClient.put=="function"}get solutionName(){return this.solutionUniqueName}postBatch(t,r,n){if(!this.httpClient.postRaw)throw new Jo.InvalidArgumentError("The injected HttpClient does not implement postRaw(), required for atomic $batch change sets");let i=this.apiUrl("/$batch"),o={...n,headers:{...n?.headers,"Content-Type":`multipart/mixed;boundary=${r}`}};return this.send(i,()=>this.httpClient.postRaw(i,t,o))}patch(t,r,n){let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.patch(i,r,this.withSolution(n)))}get supportsBinaryPatch(){return typeof this.httpClient.patchRaw=="function"}patchRaw(t,r,n){if(!this.httpClient.patchRaw)throw new Jo.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 Jo.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)))}};rd.DataverseClient=Sh});var iA=v(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.findColumns=cr.findTables=cr.readCheckColumns=cr.readColumnHints=cr.fetchEntityMetadataFromApi=cr.COLUMN_DETAIL_VERSION=void 0;var od=fe(),Ar=oe();function an(e){var t,r;return(r=(t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)!==null&&r!==void 0?r:""}cr.COLUMN_DETAIL_VERSION=2;function Nh(e){var t,r;return typeof((t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)=="string"||((r=e?.LocalizedLabels)!==null&&r!==void 0?r:[]).some(n=>typeof n?.Label=="string")}function Yo(e){let t=e?.LocalizedLabels;if(!Array.isArray(t)||t.length<2)return;let r={};for(let n of t)typeof n?.LanguageCode=="number"&&typeof n.Label=="string"&&(r[n.LanguageCode]=n.Label);return Object.keys(r).length?r:void 0}async function nd(e,t){return(await ad(e,t)).rows}async function ad(e,t){var r,n;let i=await e.get(t);return i.status<200||i.status>=300?{rows:[],ok:!1}:{rows:(n=(r=i.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[],ok:!0}}function Jr(e){return`/EntityDefinitions(LogicalName='${(0,Ar.odataPathLiteral)(e)}')`}async function MV(e,t,r){let n=await nd(e,`${Jr(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata${(0,Ar.odataQuery)([["$select","LogicalName,MaxLength"]])}`);for(let i of n){let o=r.get(i.LogicalName);o&&typeof i.MaxLength=="number"&&(o.maxLength=i.MaxLength)}}function UV(e){return`${Jr(e)}/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata${(0,Ar.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`}async function BV(e,t){var r;let{rows:n}=await e;for(let i of n){let o=t.get(i.LogicalName);o&&(!((r=i.OptionSet)===null||r===void 0)&&r.Options)&&(o.options=i.OptionSet.Options.map(a=>{var s;return{value:(s=a.Value)!==null&&s!==void 0?s:0,label:an(a.Label),...Yo(a.Label)?{localizedLabel:Yo(a.Label)}:{}}}))}}function _h(e){var t;return{value:(t=e.Value)!==null&&t!==void 0?t:0,label:an(e.Label),...e.InvariantName?{invariantName:e.InvariantName}:{},...e.Color?{color:e.Color}:{}}}async function qV(e,t,r){var n;let i=c=>ad(e,c).catch(()=>({rows:[],ok:!1})),o=["MultiSelectPicklistAttributeMetadata","StateAttributeMetadata","StatusAttributeMetadata"],a=await Promise.all([r.catch(()=>({rows:[],ok:!1})),...o.map(c=>i(`${Jr(t)}/Attributes/Microsoft.Dynamics.CRM.${c}${(0,Ar.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`))]),s=new Map,l=!0;for(let{rows:c}of a)for(let d of c)!((n=d.OptionSet)===null||n===void 0)&&n.Options&&(l=l&&d.OptionSet.Options.every(f=>Nh(f.Label)),s.set(d.LogicalName,d.OptionSet.Options.map(_h)));let u=await i(`${Jr(t)}/Attributes/Microsoft.Dynamics.CRM.BooleanAttributeMetadata${(0,Ar.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=TrueOption,FalseOption)"]])}`);for(let c of u.rows){let d=c.OptionSet;d?.TrueOption&&d.FalseOption&&(l=l&&Nh(d.TrueOption.Label)&&Nh(d.FalseOption.Label),s.set(c.LogicalName,[_h(d.FalseOption),_h(d.TrueOption)]))}return{byColumn:s,complete:l&&u.ok&&a.every(c=>c.ok)}}async function VV(e,t,r){let{rows:n,ok:i}=await ad(e,`${Jr(t)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata${(0,Ar.odataQuery)([["$select","LogicalName,Targets"]])}`);for(let o of n){let a=r.get(o.LogicalName);a&&o.Targets&&(a.targets=o.Targets)}return i}function id(e,t){return e<t?-1:e>t?1:0}var rA={OneToMany:0,ManyToOne:1,ManyToMany:2};function GV(e,t){return rA[e.type]-rA[t.type]||id(e.schemaName,t.schemaName)||id(e.relatedEntity,t.relatedEntity)||id(e.relatedAttribute,t.relatedAttribute)}async function WV(e,t){var r,n,i,o;let a=[],s=await nd(e,`${Jr(t)}/OneToManyRelationships${(0,Ar.odataQuery)([["$select","SchemaName,ReferencingEntity,ReferencingAttribute"]])}`);for(let c of s)a.push({schemaName:c.SchemaName,type:"OneToMany",relatedEntity:(r=c.ReferencingEntity)!==null&&r!==void 0?r:"",relatedAttribute:(n=c.ReferencingAttribute)!==null&&n!==void 0?n:""});let l=await nd(e,`${Jr(t)}/ManyToOneRelationships${(0,Ar.odataQuery)([["$select","SchemaName,ReferencedEntity,ReferencedAttribute"]])}`);for(let c of l)a.push({schemaName:c.SchemaName,type:"ManyToOne",relatedEntity:(i=c.ReferencedEntity)!==null&&i!==void 0?i:"",relatedAttribute:(o=c.ReferencedAttribute)!==null&&o!==void 0?o:""});let u=await nd(e,`${Jr(t)}/ManyToManyRelationships${(0,Ar.odataQuery)([["$select","SchemaName,Entity1LogicalName,Entity2LogicalName"]])}`);for(let c of u){let d=c.Entity1LogicalName===t?c.Entity2LogicalName:c.Entity1LogicalName;a.push({schemaName:c.SchemaName,type:"ManyToMany",relatedEntity:d??"",relatedAttribute:""})}return a.sort(GV)}async function zV(e,t){var r,n,i,o,a;let s=`${Jr(t)}`+(0,Ar.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,Description,EntitySetName,IsCustomEntity,PrimaryNameAttribute,PrimaryIdAttribute,PrimaryImageAttribute"],["$expand","Attributes($select=LogicalName,DisplayName,Description,AttributeType,AttributeTypeName,IsCustomAttribute,IsValidForUpdate,IsValidForRead,AttributeOf)"]]),u=(0,od.ensureSuccess)(await e.get(s),e.apiUrl(s)).body,c=((r=u.Attributes)!==null&&r!==void 0?r:[]).map(g=>{var b,w,C;return{logicalName:g.LogicalName,displayName:an(g.DisplayName),...Yo(g.DisplayName)?{localizedDisplayName:Yo(g.DisplayName)}:{},attributeType:(b=g.AttributeType)!==null&&b!==void 0?b:"Unknown",isCustomAttribute:!!g.IsCustomAttribute,attributeTypeName:(C=(w=g.AttributeTypeName)===null||w===void 0?void 0:w.Value)!==null&&C!==void 0?C:"",...typeof g.IsValidForUpdate=="boolean"?{isValidForUpdate:g.IsValidForUpdate}:{},...typeof g.IsValidForRead=="boolean"?{isValidForRead:g.IsValidForRead}:{},...g.AttributeOf?{attributeOf:g.AttributeOf}:{},...an(g.Description)?{description:an(g.Description)}:{}}}).sort((g,b)=>id(g.logicalName,b.logicalName)),d=new Map(c.map(g=>[g.logicalName,g])),f=ad(e,UV(t)),[,,m,p,h]=await Promise.all([MV(e,t,d),BV(f,d),qV(e,t,f),VV(e,t,d),WV(e,t)]);for(let g of c){let b=m.byColumn.get(g.logicalName);b&&(g.choices=b)}return{logicalName:u.LogicalName,schemaName:(n=u.SchemaName)!==null&&n!==void 0?n:u.LogicalName,displayName:an(u.DisplayName),...Yo(u.DisplayName)?{localizedDisplayName:Yo(u.DisplayName)}:{},entitySetName:(i=u.EntitySetName)!==null&&i!==void 0?i:"",primaryNameAttribute:(o=u.PrimaryNameAttribute)!==null&&o!==void 0?o:"",primaryIdAttribute:(a=u.PrimaryIdAttribute)!==null&&a!==void 0?a:"",...u.PrimaryImageAttribute?{primaryImageAttribute:u.PrimaryImageAttribute}:{},isCustomEntity:!!u.IsCustomEntity,...an(u.Description)?{description:an(u.Description)}:{},columnDetailComplete:m.complete&&p,columnDetailVersion:cr.COLUMN_DETAIL_VERSION,attributes:c,relationships:h}}cr.fetchEntityMetadataFromApi=zV;var nA=40;async function Th(e,t,r,n){var i,o;let a=[...new Set(n.filter(l=>l!==""))],s=[];for(let l=0;l<a.length;l+=nA){let u=a.slice(l,l+nA).map(f=>`LogicalName eq '${(0,Ar.odataLiteral)(f)}'`).join(" or "),c=t+(0,Ar.odataQuery)([["$select",r],["$filter",u]]),d=(0,od.ensureSuccess)(await e.get(c),e.apiUrl(c));s.push(...(o=(i=d.body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[])}return s}async function jV(e,t,r){return(await Th(e,`${Jr(t)}/Attributes`,"LogicalName,AttributeType,DisplayName",r)).map(i=>{var o;let a=Yo(i.DisplayName);return{logicalName:i.LogicalName,displayName:an(i.DisplayName),...a?{localizedDisplayName:a}:{},attributeType:(o=i.AttributeType)!==null&&o!==void 0?o:"Unknown"}})}cr.readColumnHints=jV;async function HV(e,t,r){let i=(await Th(e,`${Jr(t)}/Attributes`,"LogicalName,AttributeType,DisplayName,IsCustomAttribute",r)).map(s=>{var l;return{logicalName:s.LogicalName,displayName:an(s.DisplayName),attributeType:(l=s.AttributeType)!==null&&l!==void 0?l:"Unknown",isCustomAttribute:!!s.IsCustomAttribute}}),o=new Map(i.filter(s=>s.attributeType==="String").map(s=>[s.logicalName,s])),a=await Th(e,`${Jr(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata`,"LogicalName,MaxLength",[...o.keys()]);for(let s of a){let l=o.get(s.LogicalName);l&&typeof s.MaxLength=="number"&&(l.maxLength=s.MaxLength)}return i}cr.readCheckColumns=HV;async function KV(e,t,r){var n,i;let o=`/EntityDefinitions${(0,Ar.odataQuery)([["$select","LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity"]])}`,s=(i=(n=(0,od.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[],l=(t??"").toLowerCase(),u=s.filter(c=>!r?.customOnly||c.IsCustomEntity).map(c=>{var d,f;return{logicalName:c.LogicalName,schemaName:(d=c.SchemaName)!==null&&d!==void 0?d:c.LogicalName,displayName:an(c.DisplayName),entitySetName:(f=c.EntitySetName)!==null&&f!==void 0?f:"",isCustom:!!c.IsCustomEntity}}).filter(c=>c.logicalName.toLowerCase().includes(l)||c.schemaName.toLowerCase().includes(l)||c.displayName.toLowerCase().includes(l));return typeof r?.top=="number"?u.slice(0,r.top):u}cr.findTables=KV;async function JV(e,t,r,n){var i,o;let a=`${Jr(t)}/Attributes`+(0,Ar.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute"]]),l=(o=(i=(0,od.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[],u=(r??"").toLowerCase(),c=l.map(d=>{var f,m;return{logicalName:d.LogicalName,schemaName:(f=d.SchemaName)!==null&&f!==void 0?f:d.LogicalName,displayName:an(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}cr.findColumns=JV});var Oh=v(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.renderTypeRegistrations=Sr.buildGenPageLegacyEnums=Sr.renderGenPageAuthoringTypes=Sr.buildGenPageRuntimeTypes=Sr.toDesignerEntity=Sr.TABLE_LOGICAL_NAME=void 0;Sr.TABLE_LOGICAL_NAME=/^[a-z_][a-z0-9_]*$/;function Dh(e){return e.replace(/[\r\n\u2028\u2029]+/g," ")}var YV=new Set(["createdby","createdon","createdonbehalfby","importsequencenumber","modifiedby","modifiedon","modifiedonbehalfby","overriddencreatedon","ownerid","owningbusinessunit","owningteam","owninguser","timezoneruleversionnumber","utcconversiontimezonecode","versionnumber"]);function sd(e){var t;return((t=e.attributeTypeName)!==null&&t!==void 0?t:"").replace(/Type$/,"").toLowerCase()}function sA(e){var t,r;let n=e.choices;if(!n||n.length===0)return;let i=sd(e)==="boolean",o={};for(let a of n)o[a.value]={text:(r=(t=a.invariantName)!==null&&t!==void 0?t:a.label)!==null&&r!==void 0?r:"",value:a.value,...!i&&a.color?{color:a.color}:{}};return o}function oA(e,t){return e.logicalName<t.logicalName?-1:e.logicalName>t.logicalName?1:0}function lA(e){return!YV.has(e.logicalName)&&(!e.attributeOf||sd(e)==="image")&&e.isValidForRead!==!1}var aA=new Set(["boolean","picklist","multiselectpicklist","state","status"]);function uA(e){let t=e.primaryImageAttribute,r=new Set([e.primaryIdAttribute,e.primaryNameAttribute,t,t?`${t}_url`:void 0,"processid","statecode","statuscode"].filter(o=>!!o)),n=e.attributes.filter(o=>r.has(o.logicalName)).sort(oA),i=e.attributes.filter(o=>!r.has(o.logicalName)).sort(oA);return[...n,...i]}function Ih(e){var t;let r=[],n=new Set,i=uA(e);for(let o of i){let a=sd(o),s=a==="image";lA(o)&&(s&&o.attributeOf&&n.add(o.attributeOf),r.push({AttributeTypeName:a,IsReadOnly:!o.isValidForUpdate,LogicalName:o.logicalName,OptionSet:sA(o),Targets:o.targets,Description:o.description,MaxLength:o.maxLength}))}return{Description:(t=e.description)!==null&&t!==void 0?t:"",LogicalName:e.logicalName,PrimaryIdAttribute:e.primaryIdAttribute,Attributes:r.filter(o=>!n.has(o.LogicalName))}}Sr.toDesignerEntity=Ih;function cA(e,t="None"){let r={};for(let n of e)r[n.logicalName]=Ih(n);return pA(r,t)}Sr.buildGenPageRuntimeTypes=cA;var dA=`export interface TableRegistrations extends BaseTableRegistrations {+`,fA=`export interface EnumRegistrations extends BaseEnumRegistrations {+`;function QV(e,t){return e.length>0?cA(e,t).text:hA(`${dA}}+`,`${fA}}+`,"","")}Sr.renderGenPageAuthoringTypes=QV;function XV(e){let t=new Set;for(let n of e)for(let i of Ih(n).Attributes)aA.has(i.AttributeTypeName)&&t.add(`${n.logicalName}_${i.LogicalName}`);let r=new Map;for(let n of e)for(let i of uA(n)){let o=`${n.logicalName}_${i.logicalName}`,a=sA(i);if(lA(i)||!aA.has(sd(i))||!a||t.has(o)||r.has(o))continue;let s={name:o,runtime:{},labels:new Map};r.set(o,{declaration:mA(o,a,!1,s),model:s})}return r}Sr.buildGenPageLegacyEnums=XV;function pA(e,t="None"){var r,n;let i=new Map,o=Object.values(e);if(o.length===0)return{text:"",enums:i};let a=t==="ColorsDefaultsConstraints"||t==="ColorsDefaultsConstraintsDescriptions",s=t==="ColorsDefaultsConstraintsDescriptions",l=dA,u=fA,c="",d="";for(let f of o){s&&f.Description&&(c+=`// ${Dh(f.Description)}`),c+=`export type ${f.LogicalName} = TableRow<{// Primary Key Columnreadonly ${f.PrimaryIdAttribute}: string,`,l+=` "${f.LogicalName}": ${f.LogicalName},-`;for(let p of f.Attributes){if(p.LogicalName===f.PrimaryIdAttribute)continue;let m=`${p.IsReadOnly?" readonly ":""}${p.LogicalName}`,h=!0;switch(p.AttributeTypeName){case"string":case"memo":case"uniqueidentifier":case"entityname":m+=`: string,-`;break;case"integer":case"double":case"decimal":case"money":case"bigint":m+=`: number,-`;break;case"datetime":m+=`: Date,-`;break;case"customer":case"lookup":{let g=(r=p.Targets)!==null&&r!==void 0?r:p.AttributeTypeName==="customer"?["account","contact"]:void 0;if(!g||g.length===0){h=!1;break}m=` // Foreign Key Column- ${p.IsReadOnly||g.every(w=>!e[w])?" readonly ":""}_${p.LogicalName}_value: `;let b="";for(let w of g)b+=`${b.length===0?"":" | "}\`/${w}(\${string})\``;m+=`${b},-`;break}case"boolean":case"picklist":case"multiselectpicklist":case"state":case"status":{let g=`${f.LogicalName}_${p.LogicalName}`;m+=`: ${g},-`;let b=(n=i.get(g))!==null&&n!==void 0?n:{name:g,runtime:{},labels:new Map};i.set(g,b),d+=mE(g,p.OptionSet,a,b),u+=` "${f.LogicalName}-${p.LogicalName}": ${g},+`;for(let m of f.Attributes){if(m.LogicalName===f.PrimaryIdAttribute)continue;let p=`${m.IsReadOnly?" readonly ":""}${m.LogicalName}`,h=!0;switch(m.AttributeTypeName){case"string":case"memo":case"uniqueidentifier":case"entityname":p+=`: string,+`;break;case"integer":case"double":case"decimal":case"money":case"bigint":p+=`: number,+`;break;case"datetime":p+=`: Date,+`;break;case"customer":case"lookup":{let g=(r=m.Targets)!==null&&r!==void 0?r:m.AttributeTypeName==="customer"?["account","contact"]:void 0;if(!g||g.length===0){h=!1;break}p=` // Foreign Key Column+ ${m.IsReadOnly||g.every(w=>!e[w])?" readonly ":""}_${m.LogicalName}_value: `;let b="";for(let w of g)b+=`${b.length===0?"":" | "}\`/${w}(\${string})\``;p+=`${b},+`;break}case"boolean":case"picklist":case"multiselectpicklist":case"state":case"status":{let g=`${f.LogicalName}_${m.LogicalName}`;p+=`: ${g},+`;let b=(n=i.get(g))!==null&&n!==void 0?n:{name:g,runtime:{},labels:new Map};i.set(g,b),d+=mA(g,m.OptionSet,a,b),u+=` "${f.LogicalName}-${m.LogicalName}": ${g},`;break}case"image":c+=` // This is an image encoded as a base64 string-`,m+=`: string,-`;break;default:h=!1}h&&(s&&p.Description&&(c+=` // ${qm(p.Description)}-`),a&&p.MaxLength&&(c+=" // Maximum length: "+p.MaxLength+`-`),c+=` ${m}`)}c+=`}>+`,p+=`: string,+`;break;default:h=!1}h&&(s&&m.Description&&(c+=` // ${Dh(m.Description)}+`),a&&m.MaxLength&&(c+=" // Maximum length: "+m.MaxLength+`+`),c+=` ${p}`)}c+=`}>`}return l+=`}`,u+=`}-`,{text:hE(l,u,c,d),enums:i}}pr.renderTypeRegistrations=pE;function mE(e,t,r,n){var i;let o=`const enum ${e} {-`;for(let a of Object.values(t??{}))if(a){r&&(o+=`${a.color?`// Option Color: ${qm(a.color)}+`,{text:hA(l,u,c,d),enums:i}}Sr.renderTypeRegistrations=pA;function mA(e,t,r,n){var i;let o=`const enum ${e} {+`;for(let a of Object.values(t??{}))if(a){r&&(o+=`${a.color?`// Option Color: ${Dh(a.color)}`:""}`),o+=`${JSON.stringify(a.text)} = ${a.value},`,n.runtime[a.text]=a.value,n.runtime[String(a.value)]=a.text;let s=(i=n.labels.get(a.text))!==null&&i!==void 0?i:[];s.includes(a.value)||s.push(a.value),n.labels.set(a.text,s)}return`${o}}-`}function hE(e,t,r,n){return`+`}function hA(e,t,r,n){return`// ---------------- Type Definitions which can be imported from ./RuntimeTypes -------------------------${e}${t}@@ -345,23 +345,23 @@ export interface GeneratedComponentProps {dataApi: UxAgentDataApi;pageInput?: PageInput;}-`}});var bE=v(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});kc.generateGenPageRuntimeTypes=void 0;var yE=Gm(),Mo=Q(),gE=new Set(["None","ColorsDefaultsConstraints","ColorsDefaultsConstraintsDescriptions"]),Uo="generateGenPageRuntimeTypes";async function Y3(e,t,r){let n=Q3(t),i=X3(r),o=[];for(let a of n){let s=await e(a);if(s.columnDetailComplete!==!0)throw new Mo.SdkError("GENPAGE_DATA_SOURCE_INCOMPLETE",`${Uo}: the column metadata of data source '${a}' could not be read completely (a choice or lookup read failed, or returned options with no label), so its RuntimeTypes would lack enums a page can use. Retry.`);o.push(s)}return(0,yE.renderGenPageAuthoringTypes)(o,i)}kc.generateGenPageRuntimeTypes=Y3;function Q3(e){if(!Array.isArray(e))throw new Mo.InvalidArgumentError(`${Uo}: dataSources must be an array of table logical names`);let t=new Set;for(let r of e){if(typeof r!="string"||!yE.TABLE_LOGICAL_NAME.test(r))throw new Mo.InvalidArgumentError(`${Uo}: a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(r)}'`);if(t.has(r))throw new Mo.InvalidArgumentError(`${Uo}: data source '${r}' is listed twice; a page's dataSources hold each table once`);t.add(r)}return[...t]}function X3(e){if(e===void 0)return"None";if(e===null||typeof e!="object"||Array.isArray(e))throw new Mo.InvalidArgumentError(`${Uo}: options must be an object`);let t=Object.keys(e).filter(n=>n!=="detail");if(t.length>0)throw new Mo.InvalidArgumentError(`${Uo}: unknown option '${t[0]}' (the only option is 'detail')`);let r=e.detail===void 0?"None":e.detail;if(typeof r!="string"||!gE.has(r))throw new Mo.InvalidArgumentError(`${Uo}: detail must be one of ${[...gE].map(n=>`'${n}'`).join(", ")}, got '${String(r)}'`);return r}});var SE=v(Bo=>{"use strict";Object.defineProperty(Bo,"__esModule",{value:!0});Bo.getEnvironmentLanguages=Bo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE=void 0;var Z3=Q(),CE=ye();Bo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE="ENVIRONMENT_LANGUAGES_UNREADABLE";var vE="/organizations?$select=languagecode",e4="/RetrieveProvisionedLanguages()",t4="/RetrieveAvailableLanguages()";function EE(e,t){return new Z3.SdkError(Bo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE,`The org's languages could not be read: ${e} ${t}. Nothing is assumed in its place \u2014 retry, or check the caller's access to the org.`)}function AE(e){return typeof e=="number"&&Number.isInteger(e)&&e>0}async function wE(e,t,r,n){let i=(0,CE.ensureSuccess)(await e.get(t),e.apiUrl(t)).body,o=i?.[r];if(!Array.isArray(o)||o.length===0||!o.every(AE))throw EE(n,`answered no list of language codes in '${r}'`);return[...new Set(o)]}async function r4(e){var t;let r=(0,CE.ensureSuccess)(await e.get(vE),e.apiUrl(vE)).body,n=r?.value,i=Array.isArray(n)&&n.length===1?(t=n[0])===null||t===void 0?void 0:t.languagecode:void 0;if(!AE(i))throw EE("the organization read","did not answer one row with a language code");let o=await wE(e,e4,"RetrieveProvisionedLanguages","RetrieveProvisionedLanguages"),a=await wE(e,t4,"LocaleIds","RetrieveAvailableLanguages");return{baseLanguage:i,available:a,provisioned:o}}Bo.getEnvironmentLanguages=r4});var Al=v(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.projectConnectorOperationSchema=Ze.projectConnectorOperations=Ze.validateConnectorSwagger=Ze.CONNECTOR_SCHEMA_TOO_LARGE_CODE=Ze.CONNECTOR_OPERATION_NOT_FOUND_CODE=Ze.CONNECTOR_SWAGGER_UNSUPPORTED_CODE=Ze.CONNECTIVITY_RESPONSE_UNREADABLE_CODE=void 0;var El=Q();Ze.CONNECTIVITY_RESPONSE_UNREADABLE_CODE="CONNECTIVITY_RESPONSE_UNREADABLE";Ze.CONNECTOR_SWAGGER_UNSUPPORTED_CODE="CONNECTOR_SWAGGER_UNSUPPORTED";Ze.CONNECTOR_OPERATION_NOT_FOUND_CODE="CONNECTOR_OPERATION_NOT_FOUND";Ze.CONNECTOR_SCHEMA_TOO_LARGE_CODE="CONNECTOR_SCHEMA_TOO_LARGE";var NE=64,_E=128,TE=2e5,DE=4e6,n4=new Set(["get","put","post","delete","patch","head","options"]),i4=new Set(["query","header","path","formData","body"]);function Yr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function yn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function bt(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function Ke(e){return e.length>80?`'${e.slice(0,80)}\u2026'`:`'${e}'`}function ke(e,t){return new El.SdkError(Ze.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`The connector's swagger could not be read: ${e} ${t}. Nothing was skipped or assumed in its place.`)}function Xi(e,t){return new El.SdkError(Ze.CONNECTOR_SWAGGER_UNSUPPORTED_CODE,`The connector's swagger is outside the supported contract (Swagger 2.0 as the Power Apps API serves it): ${e} ${t}.`)}function o4(e,t){let r=e;for(let n of t.slice(2).split("/")){let i=n.replace(/~1/g,"/").replace(/~0/g,"~");if(typeof r!="object"||r===null||!yn(r,i))return{found:!1};r=r[i]}return{found:!0,value:r}}function jm(e,t,r){if(!t.startsWith("#/"))throw Xi(r,`has a $ref that is not a local '#/\u2026' pointer (${Ke(t)})`);if(t.includes("%"))throw Xi(r,`has a $ref with a percent-encoded character (${Ke(t)}), which is not decoded`);if(/~(?![01])/.test(t))throw ke(r,`has a $ref with a malformed escape (${Ke(t)}): a '~' not followed by 0 or 1`);let n=o4(e,t);if(!n.found)throw ke(r,`has a $ref that does not resolve (${Ke(t)})`);return n.value}function xc(e,t){if(yn(e,"$ref")){if(typeof e.$ref!="string")throw ke(t,`has a $ref that is ${bt(e.$ref)}, not a string`);return e.$ref}}function a4(e,t,r){if(!Yr(t))throw ke(r,`is ${bt(t)}, not a parameter object`);let n=t,i=xc(t,r);if(i!==void 0){let s=jm(e,i,r);if(!Yr(s))throw ke(r,`has a $ref (${Ke(i)}) that resolves to ${bt(s)}, not a parameter object`);if(xc(s,`${r} \u2192 ${Ke(i)}`)!==void 0)throw Xi(r,`has a $ref (${Ke(i)}) to a parameter that is itself a $ref`);n=s}if(typeof n.name!="string")throw ke(r,"has no string name");let o=n.in;if(typeof o!="string"||!i4.has(o))throw ke(r,`has an in that is ${typeof o=="string"?Ke(o):bt(o)}, not one of query, header, path, formData or body`);if(yn(n,"required")&&typeof n.required!="boolean")throw ke(r,`has a required that is ${bt(n.required)}, not a boolean`);let a=n["x-ms-visibility"];if(yn(n,"x-ms-visibility")&&typeof a!="string")throw ke(r,`has an x-ms-visibility that is ${bt(a)}, not a string`);return{name:n.name,in:o,required:n.required===!0,internal:a==="internal"}}function Wm(e){return`${e.in}:${e.name}`}function OE(e,t,r){if(!yn(t,"parameters"))return[];let n=t.parameters;if(!Array.isArray(n))throw ke(r,`has parameters that are ${bt(n)}, not an array`);let i=new Set;return n.map((o,a)=>{let s=`${r} parameters[${a}]`,l=a4(e,o,s),u=Wm(l);if(i.has(u))throw ke(s,`repeats the parameter ${Ke(l.name)} in ${Ke(l.in)}, which must be unique in its list`);return i.add(u),l})}function PE(e,t,r){let n=t.responses;if(!yn(n,"200"))return;let i=`${r} response 200`,o=n[200];if(!Yr(o))throw ke(i,`is ${bt(o)}, not a response object`);let a=o,s=xc(o,i);if(s!==void 0){if(s.startsWith("#/")&&!/^#\/responses\/[^/]+$/.test(s))throw ke(i,`has a $ref (${Ke(s)}) that does not name a response ('#/responses/<name>')`);let l=jm(e,s,i);if(!Yr(l))throw ke(i,`has a $ref (${Ke(s)}) that resolves to ${bt(l)}, not a response object`);if(xc(l,`${i} \u2192 ${Ke(s)}`)!==void 0)throw Xi(i,`has a $ref (${Ke(s)}) to a response that is itself a $ref`);a=l}if(yn(a,"content"))throw Xi(i,"is an OpenAPI 3 response (it has content), not a Swagger 2.0 one");if(yn(a,"schema")){if(!Yr(a.schema))throw ke(i,`has a schema that is ${bt(a.schema)}, not an object`);return a.schema}}function IE(e,t,r){if(!yn(e,t))return;let n=e[t];if(typeof n!="string")throw ke(r,`has a ${t} that is ${bt(n)}, not a string`);return n}function s4(e,t,r,n,i){if(!Yr(t))throw ke(r,`is ${bt(t)}, not an operation object`);let o=t.operationId;if(typeof o!="string")throw ke(r,`has no string operationId (${bt(o)})`);if(n.has(o))throw ke(r,`repeats the operationId ${Ke(o)}, which must be unique in the document`);n.add(o);let a=IE(t,"summary",r),s=IE(t,"description",r),l=OE(e,t,r);if(!Yr(t.responses))throw ke(r,`has no responses object (${bt(t.responses)})`);return PE(e,t,r),{id:o,summary:a,description:s,node:t,where:r,parameters:l,pathParameters:i}}function Hm(e){if(!Yr(e))throw ke("the document",`is ${bt(e)}, not an object`);if(yn(e,"openapi"))throw Xi("the document","is OpenAPI 3 (it has an openapi member), not Swagger 2.0");if(!yn(e,"swagger"))throw ke("the document","names no Swagger version");if(e.swagger!=="2.0")throw Xi("the document",`declares swagger ${Ke(String(e.swagger))}, not 2.0`);let t=e.paths;if(!Yr(t))throw ke("the document",`has paths that are ${bt(t)}, not an object`);let r=[],n=new Set;for(let i of Object.keys(t)){let o=t[i],a=`paths[${Ke(i)}]`;if(!Yr(o))throw ke(a,`is ${bt(o)}, not a path item object`);let s=[];for(let l of Object.keys(o))if(n4.has(l.toLowerCase()))r.push(s4(e,o[l],`${a}.${l}`,n,s));else if(l==="parameters")for(let u of OE(e,o,a))s.push(u);else if(!l.startsWith("x-"))throw Xi(a,`has a ${Ke(l)} member; a path item may hold only HTTP methods, parameters and x- extensions`)}return{document:e,operations:r}}function l4(e){Hm(e)}Ze.validateConnectorSwagger=l4;var zm=class{constructor(t,r){this.root=t,this.where=r,this.nodes=0,this.characters=0,this.path=[]}run(t){return this.visit(t,0)}tooLarge(t){return new El.SdkError(Ze.CONNECTOR_SCHEMA_TOO_LARGE_CODE,`The response schema of ${this.where} is too large to return: it has ${t}. That is far above any connector measured, so this one is not read.`)}node(){if(this.nodes+=1,this.nodes>TE)throw this.tooLarge(`more than ${TE} nodes`)}text(t){if(this.characters+=t,this.characters>DE)throw this.tooLarge(`more than ${DE} characters of strings and keys`)}checkDepth(t){if(t>_E)throw this.tooLarge(`nesting deeper than ${_E} levels`)}visit(t,r){if(this.checkDepth(r),Array.isArray(t)){this.node();let n=[];for(let i of t)n.push(this.visit(i,r+1));return n}if(Yr(t)){if(typeof t.$ref=="string")return this.reference(t.$ref,r);this.node();let n={};for(let i of Object.keys(t))this.text(i.length),Object.defineProperty(n,i,{value:this.visit(t[i],r+1),enumerable:!0,writable:!0,configurable:!0});return n}return this.node(),typeof t=="string"&&this.text(t.length),t}reference(t,r){if(this.path.includes(t)){this.checkDepth(r+1);let o=t.slice(t.lastIndexOf("/")+1);return this.node(),this.text(4),this.node(),this.text(o.length),{$ref:o}}if(this.path.length>=NE)throw this.tooLarge(`a $ref chain of more than ${NE} references`);let n=jm(this.root,t,this.where);if(!Yr(n))throw ke(this.where,`has a schema $ref (${Ke(t)}) that resolves to ${bt(n)}, not a schema object`);this.path.push(t);let i=this.visit(n,r);return this.path.pop(),i}};function u4(e){let{operations:t}=Hm(e);return{operations:t.map(r=>{var n,i;return{name:r.id,summary:(i=(n=r.summary)!==null&&n!==void 0?n:r.description)!==null&&i!==void 0?i:null}})}}Ze.projectConnectorOperations=u4;function c4(e,t){if(typeof t!="string"||t==="")throw new El.InvalidArgumentError("operationId must be a non-empty string.");let{document:r,operations:n}=Hm(e),i=n.find(u=>u.id===t);if(!i)throw new El.SdkError(Ze.CONNECTOR_OPERATION_NOT_FOUND_CODE,`The connector has no operation with the id ${Ke(t)} (ids are matched exactly, case included). List the connector\u2019s operations to see its ids.`);let o=new Set(i.parameters.map(Wm)),a=[...i.parameters,...i.pathParameters.filter(u=>!o.has(Wm(u)))].filter(u=>!u.internal).map(({name:u,required:c})=>({name:u,required:c})),s=PE(r,i.node,i.where),l=s===void 0?{}:new zm(r,`${i.where} (${Ke(i.id)})`).run(s);return{operation:i.id,parameters:a,response:l}}Ze.projectConnectorOperationSchema=c4});var qo=v(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.readEnvironmentName=J.readConnection=J.connectorShortName=J.CONNECTOR_PREFIX=J.connectivityUnauthorized=J.errorCodeOf=J.messageOf=J.environmentFilter=J.unreadable=J.connectivityCloudOf=J.sameOrigin=J.parseUrl=J.bounded=J.kindOf=J.isObject=J.CONNECTOR_RUNTIME_UNSUPPORTED_CODE=J.CONNECTOR_NOT_TABULAR_CODE=J.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE=J.CONNECTIVITY_UNAUTHORIZED_CODE=J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE=J.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE=J.CONNECTIVITY_NOT_CONFIGURED_CODE=void 0;var Sl=Q(),d4=ye(),f4=Al();J.CONNECTIVITY_NOT_CONFIGURED_CODE="CONNECTIVITY_NOT_CONFIGURED";J.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE="CONNECTIVITY_CLOUD_UNSUPPORTED";J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE="CONNECTIVITY_ENVIRONMENT_UNVERIFIED";J.CONNECTIVITY_UNAUTHORIZED_CODE="CONNECTIVITY_UNAUTHORIZED";J.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE="CONNECTIVITY_ROUTE_DECOMMISSIONED";J.CONNECTOR_NOT_TABULAR_CODE="CONNECTOR_NOT_TABULAR";J.CONNECTOR_RUNTIME_UNSUPPORTED_CODE="CONNECTOR_RUNTIME_UNSUPPORTED";function mr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}J.isObject=mr;function Va(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}J.kindOf=Va;function Ga(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}J.bounded=Ga;function LE(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}J.parseUrl=LE;function p4(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}J.sameOrigin=p4;var m4=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,h4=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/;function g4(e){let t=LE(e),r=t?t.host.toLowerCase():"";if(h4.test(r))return"Test";let n=m4.exec(r);return n&&n[1]!=="9"?"Public":"Unsupported"}J.connectivityCloudOf=g4;function Mn(e,t){return new Sl.SdkError(f4.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}J.unreadable=Mn;function y4(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}J.environmentFilter=y4;function b4(e){if(typeof e=="string"&&e.length>0)return Ga(e,500);if(mr(e)){let t=mr(e.error)?e.error.message:void 0;for(let r of[t,e.Message,e.message])if(typeof r=="string")return Ga(r,500)}return"request failed"}J.messageOf=b4;function kE(e){return mr(e)&&mr(e.error)?e.error.code:void 0}J.errorCodeOf=kE;function v4(e){if(mr(e)&&mr(e.error)&&mr(e.error.innererror))return e.error.innererror.code}function w4(e,t,r){let n=[],i=kE(t);typeof i=="string"&&i.length>0&&n.push(Ga(i,80));let o=v4(t);typeof o=="string"&&o.length>0&&n.push(Ga(o,80));let a=n.length>0?` (${n.join("; ")})`:"";return(0,Sl.attachCause)(new Sl.SdkError(J.CONNECTIVITY_UNAUTHORIZED_CODE,`A connectivity request was refused with HTTP ${e}${a}: the token's audience, scopes, expiry, or access was rejected. Supply a valid token for this route, or fall back to pac.`),r)}J.connectivityUnauthorized=w4;J.CONNECTOR_PREFIX="/providers/Microsoft.PowerApps/apis/";var C4=/^[A-Za-z0-9_.-]{1,128}$/,E4=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]);function A4(e){if(typeof e=="string"){let r=e.slice(0,J.CONNECTOR_PREFIX.length).toLowerCase()===J.CONNECTOR_PREFIX.toLowerCase()?e.slice(J.CONNECTOR_PREFIX.length):e;if(C4.test(r)&&!/^\.{1,2}$/.test(r))return r}throw new Sl.InvalidArgumentError(`connector must be a connector's short name ('shared_office365users') or its full API id ('${J.CONNECTOR_PREFIX}shared_office365users'); got ${typeof e=="string"?`'${Ga(e,80)}'`:Va(e)}.`)}J.connectorShortName=A4;function S4(e,t,r){let n=`Connection row ${t}`;if(!mr(e))throw Mn(n,`it is ${Va(e)}, not an object`);let i=e.properties;if(!mr(i))throw Mn(n,`its properties are ${Va(i)}, not an object`);let o=i.apiId;if(typeof o!="string"||o.slice(0,J.CONNECTOR_PREFIX.length).toLowerCase()!==J.CONNECTOR_PREFIX.toLowerCase())throw Mn(n,`its apiId is not '${J.CONNECTOR_PREFIX}<connector>'`);let a=o.slice(J.CONNECTOR_PREFIX.length);if(a===""||a.includes("/"))throw Mn(n,"its apiId names no single connector");if(E4.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw Mn(n,"it has no name");let l=i.environment,u=mr(l)?l.name:void 0;if(typeof u!="string"||u.toLowerCase()!==r.toLowerCase())throw Mn(n,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw Mn(n,`its displayName is ${Va(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw Mn(n,`its statuses are ${Va(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let p=mr(f)?f.status:void 0;if(typeof p!="string")throw Mn(n,"one of its statuses has no string status");return p})}}J.readConnection=S4;var RE="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'";async function N4(e){let t=(0,d4.ensureSuccess)(await e.get(RE),e.apiUrl(RE)).body,r=mr(t)?t.Detail:void 0,n=mr(r)?r.EnvironmentId:void 0;if(typeof n!="string"||n==="")throw new Sl.SdkError(J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,"The environment of this org could not be verified: the org answered no environment id (RetrieveCurrentOrganization, Detail.EnvironmentId).");return n}J.readEnvironmentName=N4});var qE=v(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.ConnectivityApi=hr.CONNECTIVITY_UNAUTHORIZED_CODE=hr.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE=hr.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE=hr.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE=hr.CONNECTIVITY_NOT_CONFIGURED_CODE=void 0;var Ut=Q(),_4=ye(),Fc=Al(),_l=qo(),Tl=qo();Object.defineProperty(hr,"CONNECTIVITY_NOT_CONFIGURED_CODE",{enumerable:!0,get:function(){return Tl.CONNECTIVITY_NOT_CONFIGURED_CODE}});Object.defineProperty(hr,"CONNECTIVITY_CLOUD_UNSUPPORTED_CODE",{enumerable:!0,get:function(){return Tl.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE}});Object.defineProperty(hr,"CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE",{enumerable:!0,get:function(){return Tl.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE}});Object.defineProperty(hr,"CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE",{enumerable:!0,get:function(){return Tl.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE}});Object.defineProperty(hr,"CONNECTIVITY_UNAUTHORIZED_CODE",{enumerable:!0,get:function(){return Tl.CONNECTIVITY_UNAUTHORIZED_CODE}});var xE="2016-11-01",T4="2021-04-01",D4="https://api.bap.microsoft.com",I4="https://test.api.bap.microsoft.com",O4=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,P4=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,$E="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'",gi="/providers/Microsoft.PowerApps/apis/",R4=/^[A-Za-z0-9_.-]{1,128}$/,L4=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]),k4="ServiceDecommissioned";function st(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Zi(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function Un(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}function Nl(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}function FE(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}function x4(e){return/^[a-z0-9][a-z0-9.-]*$/.test(e)&&(e==="api.powerapps.com"||e.endsWith(".api.powerapps.com"))}function Qr(e,t){return new Ut.SdkError(Fc.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}function $c(e){return new Ut.SdkError(_l.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: ${e}. The Power Apps service was not asked about it.`)}function ME(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}function UE(e){if(typeof e=="string"&&e.length>0)return Un(e,500);if(st(e)){let t=st(e.error)?e.error.message:void 0;for(let r of[t,e.Message,e.message])if(typeof r=="string")return Un(r,500)}return"request failed"}function $4(e){return st(e)&&st(e.error)?e.error.code:void 0}function BE(e){if(typeof e=="string"){let r=e.slice(0,gi.length).toLowerCase()===gi.toLowerCase()?e.slice(gi.length):e;if(R4.test(r)&&!/^\.{1,2}$/.test(r))return r}throw new Ut.InvalidArgumentError(`connector must be a connector's short name ('shared_office365users') or its full API id ('${gi}shared_office365users'); got ${typeof e=="string"?`'${Un(e,80)}'`:Zi(e)}.`)}function F4(e,t,r){let n=`Connection row ${t}`;if(!st(e))throw Qr(n,`it is ${Zi(e)}, not an object`);let i=e.properties;if(!st(i))throw Qr(n,`its properties are ${Zi(i)}, not an object`);let o=i.apiId;if(typeof o!="string"||o.slice(0,gi.length).toLowerCase()!==gi.toLowerCase())throw Qr(n,`its apiId is not '${gi}<connector>'`);let a=o.slice(gi.length);if(a===""||a.includes("/"))throw Qr(n,"its apiId names no single connector");if(L4.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw Qr(n,"it has no name");let l=i.environment,u=st(l)?l.name:void 0;if(typeof u!="string"||u.toLowerCase()!==r.toLowerCase())throw Qr(n,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw Qr(n,`its displayName is ${Zi(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw Qr(n,`its statuses are ${Zi(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let p=st(f)?f.status:void 0;if(typeof p!="string")throw Qr(n,"one of its statuses has no string status");return p})}}var Km=class{constructor(t,r,n){this.org=t,this.instanceUrl=r,this.service=n,this.swaggers=new Map}async listConnections(){let t=this.requireService(),r=await this.resolveEnvironment(t),n=[],i=new Set,o=`${r.origin}/providers/Microsoft.PowerApps/connections?api-version=${xE}&$filter=${ME(r.id)}`,a=await this.send(t,o,!0),s=1,l=0;for(;;){let u=`Page ${s} of the connections`,c=a.body,d=c?.value;if(!Array.isArray(d))throw Qr(u,`its value is ${Zi(d)}, not an array`);for(let p of d){let m=F4(p,l,r.id);l+=1,m&&n.push(m)}let f=c?.nextLink;if(f==null)return n;if(typeof f!="string"||f.length===0)throw Qr(u,`its nextLink is ${f===""?"an empty string":Zi(f)}, not a non-empty string`);if(i.has(f))throw new Ut.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${Un(f)}'), which would loop indefinitely.`);i.add(f),this.assertSameOrigin(f,r.parsed),a=await this.send(t,f,!0),s+=1}}async listConnectorOperations(t){let r=this.requireService(),n=BE(t);return(0,Fc.projectConnectorOperations)(await this.swagger(r,n))}async getConnectorOperationSchema(t,r){let n=this.requireService(),i=BE(t);if(typeof r!="string"||r==="")throw new Ut.InvalidArgumentError("operationId must be a non-empty string.");return(0,Fc.projectConnectorOperationSchema)(await this.swagger(n,i),r)}requireService(){if(!this.service)throw new Ut.SdkError(_l.CONNECTIVITY_NOT_CONFIGURED_CODE,"This SDK was created without a powerAppsServiceClient (MakerSdkOptions), so it cannot read connections or connectors: it needs an HttpClient that authenticates for https://service.powerapps.com/ and does not follow redirects. Nothing was requested.");return this.service}resolveEnvironment(t){if(!this.environment){let r=this.verifyEnvironment(t);this.environment=r,r.catch(()=>{this.environment===r&&(this.environment=void 0)})}return this.environment}async verifyEnvironment(t){let r=this.candidateBapOrigin(),n=await this.readEnvironmentId(),i=`${r}/providers/Microsoft.BusinessAppPlatform/environments/${encodeURIComponent(n)}?api-version=${T4}`,o=(await this.send(t,i,!1)).body,a=st(o)?o.properties:void 0,s=st(o)?o.name:void 0;if(typeof s!="string"||s.toLowerCase()!==n.toLowerCase())throw $c(`BAP's environment row is not the one named '${Un(n,80)}' (its name)`);let l=st(a)&&st(a.linkedEnvironmentMetadata)?a.linkedEnvironmentMetadata.instanceUrl:void 0,u=typeof l=="string"?Nl(l):void 0,c=Nl(this.instanceUrl);if(!u||!c||!FE(u,c))throw $c("BAP's row is not linked to this org (its linkedEnvironmentMetadata.instanceUrl is another origin)");let d=st(a)?a.runtimeEndpoints:void 0,f=st(d)?d["microsoft.PowerApps"]:void 0,p=typeof f=="string"?Nl(f):void 0;if(!p||p.protocol!=="https:"||!x4(p.host.toLowerCase()))throw $c("BAP's Power Apps runtime endpoint is not an https host of api.powerapps.com (runtimeEndpoints['microsoft.PowerApps'])");return{id:n,origin:p.origin.toLowerCase(),parsed:p}}candidateBapOrigin(){let t=Nl(this.instanceUrl),r=t?t.host.toLowerCase():"",n=O4.exec(r);if(n&&n[1]!=="9")return D4;if(P4.test(r))return I4;throw new Ut.SdkError(_l.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The org's host is not one of the clouds this reads in (${t?`'${Un(t.host,80)}'`:`'${Un(this.instanceUrl,80)}', which is not a URL`}): a Public org is <name>.crm[N].dynamics.com (N other than 9) and a Test org <name>.crmtest.dynamics.com. GCC (crm9), GCC High, DoD, China, ports and custom domains are not supported. Nothing was requested.`)}async readEnvironmentId(){let t=(0,_4.ensureSuccess)(await this.org.get($E),this.org.apiUrl($E)).body,r=st(t)?t.Detail:void 0,n=st(r)?r.EnvironmentId:void 0;if(typeof n!="string"||n==="")throw $c("the org answered no environment id (RetrieveCurrentOrganization, Detail.EnvironmentId)");return n}swagger(t,r){let n=r.toLowerCase(),i=this.swaggers.get(n);if(!i){let o=this.readSwagger(t,r);i=o,this.swaggers.set(n,o),o.catch(()=>{this.swaggers.get(n)===o&&this.swaggers.delete(n)})}return i}async readSwagger(t,r){let n=await this.resolveEnvironment(t),i=encodeURIComponent(r),o=`${n.origin}${gi}${i}?api-version=${xE}&$filter=${ME(n.id)}`,a=(await this.send(t,o,!0)).body,s=st(a)?a.properties:void 0,l=st(s)?s.swagger:void 0;if(!st(l))throw Qr(`The connector '${Un(r,80)}'`,`its properties.swagger is ${Zi(l)}, not an object`);return(0,Fc.validateConnectorSwagger)(l),l}assertSameOrigin(t,r){let n=Nl(t);if(!n)throw new Ut.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${Un(t)}'`);if(!FE(n,r))throw new Ut.InvalidArgumentError(`Refusing to follow a cross-origin link ('${Un(n.origin,120)}' is not the environment's Power Apps endpoint '${r.origin}'); server-driven pagination must stay on that origin.`)}async send(t,r,n){let i;try{i=await t.get(r)}catch(o){throw o instanceof Ut.ConnectionError&&typeof o.statusCode=="number"&&o.statusCode>0?this.mapNon2xx(r,o.statusCode,void 0,n,o):o instanceof Ut.SdkError?o:new Ut.ConnectionError(r,0,o instanceof Error?o.message:String(o),o)}if(!i||typeof i.status!="number")throw new Ut.ConnectionError(r,0,"the transport returned no HTTP response");if(i.status>=200&&i.status<300)return i;throw this.mapNon2xx(r,i.status,i.body,n)}mapNon2xx(t,r,n,i,o){let a=o??new Ut.ConnectionError(t,r,UE(n),n);return i&&r===410&&$4(n)===k4?(0,Ut.attachCause)(new Ut.SdkError(_l.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE,`The Power Apps API this reads through is decommissioned for this environment: ${UE(n)} Fall back to pac, or to the Power Platform API when the host has a client for it; the SDK does not fall back.`),a):r===401||r===403?(0,_l.connectivityUnauthorized)(r,n,a):a}};hr.ConnectivityApi=Km});var Zm=v(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.projectConnectorTableSchema=Me.projectConnectorTables=Me.tableSchemaSuffix=Me.tablesSuffix=Me.encodeTable=Me.encodeDataset=Me.checkTabularConnection=Me.runtimeAuthority=Me.tabularRevision=Me.checkTableSchemaArguments=Me.checkListTablesArguments=void 0;var Vo=Q(),M=qo(),M4=/^[A-Za-z0-9_.-]{1,128}$/,Go=/^\.{1,2}$/,U4="shared_sharepointonline",B4=/^[0-9]{1,9}$/,q4=/^[A-Za-z0-9._~-]+$/,V4=/^\/apim\/([A-Za-z0-9._-]+)\/?$/,G4=/^\/connectors\/runtime\/invoke\/scalegroups\/([A-Za-z0-9._-]+)\/(scaleunits|shards)\/([A-Za-z0-9._-]+)\/apis\/([A-Za-z0-9._-]+)\/connections\/?$/,W4=/^[A-Za-z0-9._~!'()*-]$/,z4=/^[0-9A-Fa-f]{2}$/;function yi(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Dl(e){return typeof e=="string"?`'${(0,M.bounded)(e,80)}'`:(0,M.kindOf)(e)}function Jm(e,t){return new Vo.SdkError(M.CONNECTOR_NOT_TABULAR_CODE,`The connector '${(0,M.bounded)(e,80)}' has no tables: ${t}.`)}function Mc(e,t){return new Vo.SdkError(M.CONNECTOR_RUNTIME_UNSUPPORTED_CODE,`The connector '${(0,M.bounded)(e,80)}' runs where this SDK does not send a token: ${t}. Nothing was sent to it.`)}function j4(e){if(typeof e=="string"&&M4.test(e)&&!Go.test(e))return e;throw new Vo.InvalidArgumentError(`connectionId must be a connection's name (letters, digits, '_', '.', '-'; at most 128; not '.' or '..'); got ${Dl(e)}.`)}function H4(e){if(e!=null){if(typeof e=="string"&&e!==""&&e.split(",").find(r=>r===""||Go.test(r))===void 0)return e;throw new Vo.InvalidArgumentError(`dataset must be a non-empty string (a SharePoint site URL, a SQL 'server,database', \u2026) none of whose ','-separated parts is empty, '.' or '..', or absent for a connector without datasets; got ${Dl(e)}.`)}}function K4(e){if(typeof e=="string"&&e!==""&&!Go.test(e))return e;throw new Vo.InvalidArgumentError(`table must be a non-empty string other than '.' and '..'; got ${Dl(e)}.`)}function GE(e,t,r){return{short:(0,M.connectorShortName)(e),connectionId:j4(t),dataset:H4(r)}}Me.checkListTablesArguments=GE;function J4(e,t,r,n){return{...GE(e,t,r),table:K4(n)}}Me.checkTableSchemaArguments=J4;function Y4(e,t){let r=`The connector '${(0,M.bounded)(t,80)}'`,n=e.properties;if(!(0,M.isObject)(n))throw(0,M.unreadable)(r,`its properties are ${(0,M.kindOf)(n)}, not an object`);if(!yi(n,"interfaces"))throw Jm(t,"it declares no interfaces");let i=n.interfaces;if(!(0,M.isObject)(i))throw(0,M.unreadable)(r,`its properties.interfaces are ${(0,M.kindOf)(i)}, not an object`);if(!yi(i,"CDPTabular1"))throw Jm(t,"it declares no CDPTabular1 interface");let o=i.CDPTabular1;if(!(0,M.isObject)(o))throw(0,M.unreadable)(r,`its CDPTabular1 interface is ${(0,M.kindOf)(o)}, not an object`);let a=o.revisions;if(!(0,M.isObject)(a))throw(0,M.unreadable)(r,`its CDPTabular1 revisions are ${(0,M.kindOf)(a)}, not an object`);let s,l=new Map;for(let u of Object.keys(a)){let c=a[u],d=`its CDPTabular1 revision '${(0,M.bounded)(u,40)}'`;if(!(0,M.isObject)(c)||typeof c.status!="string")throw(0,M.unreadable)(r,`${d} is not an object with a string status`);if(c.status!=="Production")continue;if(!B4.test(u))throw(0,M.unreadable)(r,`${d} is a Production revision whose key is not a decimal integer of 1\u20139 digits`);let f=Q4(c.baseUrl);if(f===void 0)throw(0,M.unreadable)(r,`${d} has a baseUrl that is not '/' or '/'-separated [A-Za-z0-9._~-] segments`);let p=Number(u),m=l.get(p);if(m!==void 0)throw(0,M.unreadable)(r,`its Production revisions '${m}' and '${(0,M.bounded)(u,40)}' have the same number`);l.set(p,u),(!s||p>s.revisionNumber)&&(s={revisionNumber:p,revision:f})}if(!s)throw Jm(t,"its CDPTabular1 interface has no Production revision");return s.revision}Me.tabularRevision=Y4;function Q4(e){if(typeof e!="string")return;let t=e.replace(/^\/+/,"").replace(/\/+$/,"");return t===""?"":t.split("/").every(i=>q4.test(i)&&!Go.test(i))?t:void 0}function X4(e,t,r){let n=(0,M.isObject)(e.properties)?e.properties:void 0,i=n?n.primaryRuntimeUrl:void 0;if(typeof i!="string")throw Mc(r,`its primaryRuntimeUrl is ${(0,M.kindOf)(i)}, not a string`);let o=t.cloud==="Test",a=(o?`https://${t.name}.tip2-001.tip2.azure-apihub.net`:t.origin).toLowerCase(),s=(0,M.parseUrl)(i);if(!s||s.protocol!=="https:"||s.origin.toLowerCase()!==a)throw Mc(r,`its runtime ('${(0,M.bounded)(i,120)}') is not ${o?"this environment's measured API Hub host (<environment name>.tip2-001.tip2.azure-apihub.net)":"under this environment's own Power Platform API origin"} over https`);let l=i.slice(0,a.length).toLowerCase()===a?i.slice(a.length):void 0;if(o){let c=l===void 0?null:V4.exec(l);if(!c||Go.test(c[1]))throw Mc(r,`its runtime ('${(0,M.bounded)(i,120)}') is not <host>/apim/<connector>`);return{transport:"invoke",origin:a,path:`/apim/${c[1]}`}}let u=l===void 0?null:G4.exec(l);if(!u||[u[1],u[3],u[4]].some(c=>Go.test(c)))throw Mc(r,`its runtime ('${(0,M.bounded)(i,120)}') is not <origin>/connectors/runtime/invoke/scalegroups/<group>/(scaleunits|shards)/<unit>/apis/<api>/connections`);return{transport:"direct",origin:a,path:`/connectors/runtime/invoke/scalegroups/${u[1]}/${u[2]}/${u[3]}/apis/${u[4]}/connections`}}Me.runtimeAuthority=X4;function Z4(e,t,r,n){let i=`The connection '${(0,M.bounded)(t,128)}'`;if(!(0,M.isObject)(e))throw(0,M.unreadable)(i,`it is ${(0,M.kindOf)(e)}, not an object`);if(e.name!==t)throw(0,M.unreadable)(i,`its name is ${Dl(e.name)}, not the requested connection`);let o=e.properties;if(!(0,M.isObject)(o))throw(0,M.unreadable)(i,`its properties are ${(0,M.kindOf)(o)}, not an object`);let a=o.apiId;if(typeof a!="string"||a.toLowerCase()!==`${M.CONNECTOR_PREFIX}${r}`.toLowerCase())throw(0,M.unreadable)(i,`its apiId is ${Dl(a)}, not the connector '${(0,M.bounded)(r,80)}'`);let s=o.environment,l=(0,M.isObject)(s)?s.name:void 0;if(typeof l!="string"||l.toLowerCase()!==n.toLowerCase())throw(0,M.unreadable)(i,"it is not a connection of this environment (properties.environment.name)");return t}Me.checkTabularConnection=Z4;function VE(e){return encodeURIComponent(e).replace(/[!'()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`)}function eV(e){if(e==="")return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="%"){if(!z4.test(e.slice(t+1,t+3)))return!1;t+=2}else if(!W4.test(e[t]))return!1;return!0}function WE(e,t){let r,n,i;try{r=VE(e),n=VE(r),i=decodeURIComponent(n)}catch{throw new Vo.InvalidArgumentError(`${t} is not well-formed Unicode (it has a lone surrogate), so it cannot be sent.`)}if(!eV(n)||Go.test(n)||i!==r)throw new Vo.InvalidArgumentError(`${t} cannot be sent as one path segment.`);return n}function Xm(e){return e.split(",").map((t,r)=>WE(t,`dataset part ${r}`)).join(",")}Me.encodeDataset=Xm;function zE(e){return WE(e,"table")}Me.encodeTable=zE;function tV(e,t){if(t===void 0)return"/tables";let r=e.toLowerCase()===U4?"allTables":"tables";return`/datasets/${Xm(t)}/${r}`}Me.tablesSuffix=tV;function rV(e,t){return`/$metadata.json${e===void 0?"":`/datasets/${Xm(e)}`}/tables/${zE(t)}`}Me.tableSchemaSuffix=rV;function Wa(e,t){let r=t.toLowerCase();for(let n of Object.keys(e))if(n.toLowerCase()===r)return{found:!0,value:e[n]};return{found:!1}}function nV(e){let t="The table list",r;if(Array.isArray(e))r=e;else if((0,M.isObject)(e)){for(let o of["nextLink","@odata.nextLink"])if(Wa(e,o).found)throw(0,M.unreadable)(t,`it carries a ${o} \u2014 a paged answer is refused, never read as a partial list`);let n=Wa(e,"value"),i=n.found?n:Wa(e,"tables");if(!i.found)throw(0,M.unreadable)(t,"it is an object with neither a value nor a tables member");if(!Array.isArray(i.value))throw(0,M.unreadable)(t,`its ${n.found?"value":"tables"} is ${(0,M.kindOf)(i.value)}, not an array`);r=i.value}else throw(0,M.unreadable)(t,`it is ${(0,M.kindOf)(e)}, not an array or an object`);return{tables:r.map((n,i)=>iV(n,i))}}Me.projectConnectorTables=nV;function iV(e,t){let r=`Table row ${t}`;if(!(0,M.isObject)(e))throw(0,M.unreadable)(r,`it is ${(0,M.kindOf)(e)}, not an object`);let n=Wa(e,"name");if(!n.found||typeof n.value!="string"||n.value==="")throw(0,M.unreadable)(r,"it has no non-empty string name");let i=Wa(e,"displayName");if(i.found&&typeof i.value!="string")throw(0,M.unreadable)(r,`its displayName is ${(0,M.kindOf)(i.value)}, not a string`);let o=Wa(e,"id");if(o.found&&(typeof o.value!="string"||o.value===""))throw(0,M.unreadable)(r,`its id is ${o.value===""?"an empty string":(0,M.kindOf)(o.value)}, not a non-empty string`);return{name:n.value,displayName:i.found?i.value:null,id:o.found?o.value:n.value}}function Ym(e,t,r){if(!yi(e,t))return;let n=e[t];if(!(0,M.isObject)(n))throw(0,M.unreadable)("The table schema",`its ${r} is ${(0,M.kindOf)(n)}, not an object`);return n}function Qm(e,t,r){if(!yi(e,t))return;let n=e[t];if(typeof n!="string")throw(0,M.unreadable)(r,`its ${t} is ${(0,M.kindOf)(n)}, not a string`);return n}function oV(e,t){var r,n;if(yi(e,"$ref"))throw(0,M.unreadable)(t,"it is a $ref, whose type is not guessed");let i=Qm(e,"type",t),o=Qm(e,"format",t),a=(r=i??o)!==null&&r!==void 0?r:"object";if(!yi(e,"items"))return a;let s=e.items;if(!(0,M.isObject)(s))throw(0,M.unreadable)(t,`its items are ${(0,M.kindOf)(s)}, not an object`);if(yi(s,"$ref"))throw(0,M.unreadable)(t,"its items are a $ref, whose type is not guessed");return`${a}<${(n=Qm(s,"type",`${t} items`))!==null&&n!==void 0?n:"object"}>`}function aV(e,t){let r="The table schema";if(!(0,M.isObject)(e))throw(0,M.unreadable)(r,`it is ${(0,M.kindOf)(e)}, not an object`);let n=Ym(e,"items","items"),i=Ym(e,"schema","schema"),o=i?Ym(i,"items","schema.items"):void 0,a=[[e,"the answer"],[n,"items"],[i,"schema"],[o,"schema.items"]],s=new Set;for(let[c,d]of a)if(c&&yi(c,"required")){let f=c.required;if(!Array.isArray(f))throw(0,M.unreadable)(r,`the required of ${d} is ${(0,M.kindOf)(f)}, not an array`);f.forEach(p=>{if(typeof p!="string")throw(0,M.unreadable)(r,`the required of ${d} has an entry that is ${(0,M.kindOf)(p)}, not a string`);s.add(p.toLowerCase())})}let l;for(let[c,d]of a)if(c&&yi(c,"properties")){if(!(0,M.isObject)(c.properties))throw(0,M.unreadable)(r,`the properties of ${d} are ${(0,M.kindOf)(c.properties)}, not an object`);l=c.properties;break}if(!l)throw(0,M.unreadable)(r,"it has no properties, items.properties, schema.properties or schema.items.properties");let u=Object.keys(l).map(c=>{let d=`Column '${(0,M.bounded)(c,80)}'`,f=l[c];if(!(0,M.isObject)(f))throw(0,M.unreadable)(d,`it is ${(0,M.kindOf)(f)}, not an object`);return{name:c,type:oV(f,d),required:s.has(c.toLowerCase())}});return{table:t,columns:u}}Me.projectConnectorTableSchema=aV});var jE=v(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});Uc.PowerPlatformApiDiscovery=void 0;var eh=class{constructor(t){this.clusterCategory=t}getTokenAudience(){return`https://${this._getEnvironmentApiHostNameSuffix()}`}getTokenEndpointHost(){return this._getEnvironmentApiHostNameSuffix()}getTenantEndpoint(t){return this._generatePowerPlatformApiDomain(t,"tenant")}getTenantIslandClusterEndpoint(t){return this._generatePowerPlatformApiDomain(t,"tenant","il-")}getEnvironmentEndpoint(t){return this._generatePowerPlatformApiDomain(t,"environment")}_generatePowerPlatformApiDomain(t,r,n=""){if(!/^[a-zA-Z0-9\-]+$/g.test(t))throw new Error(`Cannot generate Power Platform API endpoint because the ${r} identifier contains invalid host name characters, only alphanumeric and dash characters are expected: ${t}`);let i=this._getHexApiSuffixLength(),o=t.toLowerCase().replace(/-/g,"");if(i>=o.length)throw new Error(`Cannot generate Power Platform API endpoint because the normalized ${r} identifier must be at least ${i+1} characters in length: ${o}`);let a=o.substring(o.length-i),s=o.substring(0,o.length-i),l=this._getEnvironmentApiHostNameSuffix();return`${n}${s}.${a}.${r}.${l}`}_getHexApiSuffixLength(){switch(this.clusterCategory){case"firstrelease":case"prod":return 2;default:return 1}}_getEnvironmentApiHostNameSuffix(){switch(this.clusterCategory){case"local":return"api.powerplatform.localhost";case"dev":return"api.dev.powerplatform.com";case"test":return"api.test.powerplatform.com";case"preprod":return"api.preprod.powerplatform.com";case"firstrelease":case"prod":return"api.powerplatform.com";case"gov":return"api.gov.powerplatform.microsoft.us";case"high":return"api.high.powerplatform.microsoft.us";case"dod":return"api.appsplatform.us";case"mooncake":return"api.powerplatform.partner.microsoftonline.cn";case"ex":return"api.powerplatform.eaglex.ic.gov";case"rx":return"api.powerplatform.microsoft.scloud";default:throw new Error(`Invalid ClusterCategory value: ${this.clusterCategory}`)}}};Uc.PowerPlatformApiDiscovery=eh});var HE=v(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});Bc.PowerPlatformApiDiscovery=void 0;var sV=jE();Object.defineProperty(Bc,"PowerPlatformApiDiscovery",{enumerable:!0,get:function(){return sV.PowerPlatformApiDiscovery}})});var QE=v(eo=>{"use strict";Object.defineProperty(eo,"__esModule",{value:!0});eo.platformTokenAudience=eo.platformEnvironment=eo.platformClusterOf=void 0;var KE=HE(),JE=Q(),YE=qo(),lV=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,uV=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,cV=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,dV=/^default-/i;function th(e,t=80){return e.length>t?`${e.slice(0,t)}\u2026`:e}function fV(e){try{return new URL(e).host.toLowerCase()}catch{return}}function pV(e){let t=fV(e);if(t){if(uV.test(t))return{cloud:"Test",category:"test"};let r=lV.exec(t);if(r&&r[1]!=="9")return{cloud:"Public",category:"prod"}}throw new JE.SdkError(YE.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The Power Platform API route is built for the Test and Public clouds; this org (${t?`'${th(t)}'`:`'${th(e)}', which is not a URL`}) is another cloud. A Public org is <name>.crm[N].dynamics.com (N other than 9) and a Test org <name>.crmtest.dynamics.com. GCC (crm9), GCC High, DoD, China, ports and custom domains are pending or out of scope. Nothing was requested.`)}eo.platformClusterOf=pV;function mV(e,t){let r=dV.test(e)?e.slice(8):e;if(!cV.test(r))throw new JE.SdkError(YE.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: its name ('${th(e)}') is neither a GUID nor 'Default-<GUID>', the forms this route is measured for. The Power Platform API was not asked about it.`);return{origin:`https://${new KE.PowerPlatformApiDiscovery(t).getEnvironmentEndpoint(e)}`,guid:r.toLowerCase()}}eo.platformEnvironment=mV;function hV(e){return new KE.PowerPlatformApiDiscovery(e).getTokenAudience()}eo.platformTokenAudience=hV});var ZE=v(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.PlatformConnectivityApi=za.assertTabularCloud=void 0;var bn=Q(),rh=Al(),de=qo(),XE=QE(),bi=Zm(),nh="1";function ih(e){let t=(0,de.connectivityCloudOf)(e);if(t!=="Test"&&t!=="Public")throw new bn.SdkError(de.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,"Connector tables are read in the Test and Public clouds; this org's cloud is neither (GCC, GCC High and DoD are pending). Nothing was requested.")}za.assertTabularCloud=ih;var oh=class{constructor(t,r,n,i){this.org=t,this.instanceUrl=r,this.client=n,this.runtime=i,this.records=new Map,this.swaggers=new Map}async listConnections(){let t=await this.resolveEnvironment(),r=[],n=new Set,i=await this.send(this.client,"GET",`${t.origin}/connectivity/connections?api-version=${nh}`,[401,403]),o=1,a=0;for(;;){let s=`Page ${o} of the connections`,l=i.body,u=l?.value;if(!Array.isArray(u))throw(0,de.unreadable)(s,`its value is ${(0,de.kindOf)(u)}, not an array`);for(let d of u){let f=(0,de.readConnection)(d,a,t.name);a+=1,f&&r.push(f)}let c=l?.nextLink;if(c==null)return r;if(typeof c!="string"||c.length===0)throw(0,de.unreadable)(s,`its nextLink is ${c===""?"an empty string":(0,de.kindOf)(c)}, not a non-empty string`);if(n.has(c))throw new bn.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${(0,de.bounded)(c)}'), which would loop indefinitely.`);n.add(c),this.assertSameOrigin(c,t.parsed),i=await this.send(this.client,"GET",c,[401,403]),o+=1}}async listConnectorOperations(t){let r=(0,de.connectorShortName)(t);return(0,rh.projectConnectorOperations)(await this.swagger(r))}async getConnectorOperationSchema(t,r){let n=(0,de.connectorShortName)(t);if(typeof r!="string"||r==="")throw new bn.InvalidArgumentError("operationId must be a non-empty string.");return(0,rh.projectConnectorOperationSchema)(await this.swagger(n),r)}async listConnectorTables(t,r,n){ih(this.instanceUrl);let i=(0,bi.checkListTablesArguments)(t,r,n),o=(0,bi.tablesSuffix)(i.short,i.dataset);return(0,bi.projectConnectorTables)(await this.invokeTabular(i,o))}async getConnectorTableSchema(t,r,n,i){ih(this.instanceUrl);let o=(0,bi.checkTableSchemaArguments)(t,r,n,i),a=(0,bi.tableSchemaSuffix)(o.dataset,o.table);return(0,bi.projectConnectorTableSchema)(await this.invokeTabular(o,a),o.table)}async invokeTabular(t,r){let n=this.requireRuntime(),i=await this.resolveEnvironment(),o=await this.record(t.short),a=(0,bi.tabularRevision)(o,t.short),s=(0,bi.runtimeAuthority)(o,{cloud:i.cloud,name:i.name,origin:i.origin},t.short),l=`${i.origin}/connectivity/connectors/${encodeURIComponent(t.short)}/connections/${encodeURIComponent(t.connectionId)}?$filter=${(0,de.environmentFilter)(i.name)}&api-version=${nh}`,u=(await this.send(this.client,"GET",l,[401,403])).body,c=(0,bi.checkTabularConnection)(u,t.connectionId,t.short,i.name),d=`${s.path}/${c}${a===""?"":`/${a}`}${r}`;return(s.transport==="invoke"?await this.send(n,"POST",`${s.origin}/invoke`,[401],{"X-Ms-Request-Url":d,"X-Ms-Request-Method":"GET"}):await this.send(n,"GET",`${s.origin}${d}`,[401])).body}requireRuntime(){if(!this.runtime)throw new bn.SdkError(de.CONNECTIVITY_NOT_CONFIGURED_CODE,"This SDK was created without a connectorRuntimeClient (MakerSdkOptions), so it cannot read connector tables: it needs an HttpClient that authenticates for API Hub (https://apihub.azure.com) and does not follow redirects. Nothing was requested.");return this.runtime}resolveEnvironment(){if(!this.environment){let t=this.readEnvironment();this.environment=t,t.catch(()=>{this.environment===t&&(this.environment=void 0)})}return this.environment}async readEnvironment(){let{cloud:t,category:r}=(0,XE.platformClusterOf)(this.instanceUrl),n=await(0,de.readEnvironmentName)(this.org),{origin:i,guid:o}=(0,XE.platformEnvironment)(n,r),a=(0,de.parseUrl)(i);if(!a)throw(0,de.unreadable)("The Power Platform API origin",`'${(0,de.bounded)(i)}' is not a URL`);return{cloud:t,origin:i,parsed:a,name:n,guid:o}}cached(t,r,n){let i=t.get(r);if(!i){let o=n();i=o,t.set(r,o),o.catch(()=>{t.get(r)===o&&t.delete(r)})}return i}record(t){return this.cached(this.records,t.toLowerCase(),()=>this.readRecord(t))}async readRecord(t){let r=await this.resolveEnvironment(),n=`${r.origin}/connectivity/connectors/${encodeURIComponent(t)}?$filter=${(0,de.environmentFilter)(r.name)}&api-version=${nh}`,i=(await this.send(this.client,"GET",n,[401,403])).body,o=(0,de.isObject)(i)?i.name:void 0;if(!(0,de.isObject)(i)||typeof o!="string"||o.toLowerCase()!==t.toLowerCase())throw(0,de.unreadable)(`The connector '${(0,de.bounded)(t,80)}'`,`the record's name is ${typeof o=="string"?`'${(0,de.bounded)(o,80)}'`:(0,de.kindOf)(o)}, not the requested connector`);return i}swagger(t){return this.cached(this.swaggers,t.toLowerCase(),async()=>{let n=(await this.record(t)).properties,i=(0,de.isObject)(n)?n.swagger:void 0;if(!(0,de.isObject)(i))throw(0,de.unreadable)(`The connector '${(0,de.bounded)(t,80)}'`,`its properties.swagger is ${(0,de.kindOf)(i)}, not an object`);return(0,rh.validateConnectorSwagger)(i),i})}assertSameOrigin(t,r){let n=(0,de.parseUrl)(t);if(!n)throw new bn.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${(0,de.bounded)(t)}'`);if(!(0,de.sameOrigin)(n,r))throw new bn.InvalidArgumentError(`Refusing to follow a cross-origin link ('${(0,de.bounded)(n.origin,120)}' is not the environment's Power Platform API origin '${r.origin}'); server-driven pagination must stay on that origin.`)}async send(t,r,n,i,o){let a;try{a=r==="GET"?await t.get(n):await t.post(n,void 0,{headers:o})}catch(s){throw s instanceof bn.ConnectionError&&typeof s.statusCode=="number"&&s.statusCode>0?this.non2xx(n,s.statusCode,void 0,i,s):s instanceof bn.SdkError?s:new bn.ConnectionError(n,0,s instanceof Error?s.message:String(s),s)}if(!a||typeof a.status!="number")throw new bn.ConnectionError(n,0,"the transport returned no HTTP response");if(a.status>=200&&a.status<300)return a;throw this.non2xx(n,a.status,a.body,i)}non2xx(t,r,n,i,o){let a=o??new bn.ConnectionError(t,r,(0,de.messageOf)(n),n);return i.includes(r)?(0,de.connectivityUnauthorized)(r,n,a):a}};za.PlatformConnectivityApi=oh});var tA=v(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});Vc.ConnectivityRouter=void 0;var ah=Q(),gV=qE(),qc=qo(),eA=Zm(),sh=ZE(),lh=class{constructor(t,r,n){this.org=t,this.instanceUrl=r,this.clients=n}async listConnections(){return this.route().listConnections()}async listConnectorOperations(t){return this.route().listConnectorOperations(t)}async getConnectorOperationSchema(t,r){return this.route().getConnectorOperationSchema(t,r)}async listConnectorTables(t,r,n){return(0,sh.assertTabularCloud)(this.instanceUrl),(0,eA.checkListTablesArguments)(t,r,n),this.tabularRoute().listConnectorTables(t,r,n)}async getConnectorTableSchema(t,r,n,i){return(0,sh.assertTabularCloud)(this.instanceUrl),(0,eA.checkTableSchemaArguments)(t,r,n,i),this.tabularRoute().getConnectorTableSchema(t,r,n,i)}route(){return this.delegate||(this.delegate=this.select()),this.delegate}platformRoute(t){return this.platform||(this.platform=new sh.PlatformConnectivityApi(this.org,this.instanceUrl,t,this.clients.connectorRuntimeClient)),this.platform}tabularRoute(){let{powerPlatformApiClient:t,connectorRuntimeClient:r}=this.clients,n=[t?void 0:"powerPlatformApiClient (the Power Platform API)",r?void 0:"connectorRuntimeClient (API Hub, https://apihub.azure.com)"].filter(i=>i!==void 0);if(n.length>0||!t)throw new ah.SdkError(qc.CONNECTIVITY_NOT_CONFIGURED_CODE,`Connector tables are read through the Power Platform API and the connector runtime: this SDK was created without MakerSdkOptions.${n.join(" or MakerSdkOptions.")}, an HttpClient that does not follow redirects. Nothing was requested.`);return this.platformRoute(t)}select(){let t=(0,qc.connectivityCloudOf)(this.instanceUrl),{powerAppsServiceClient:r,powerPlatformApiClient:n}=this.clients;if(t==="Unsupported")throw new ah.SdkError(qc.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,"This org's cloud has no connection/connector route: the Test and Public clouds are served (through the Power Platform API, or the classic route for Public); GCC, GCC High and DoD are pending. Nothing was requested.");if(n)return this.platformRoute(n);if(t==="Public"&&r)return new gV.ConnectivityApi(this.org,this.instanceUrl,r);throw new ah.SdkError(qc.CONNECTIVITY_NOT_CONFIGURED_CODE,t==="Test"?"This org is in the Test cloud, whose connection and connector reads go through the Power Platform API: supply MakerSdkOptions.powerPlatformApiClient (an HttpClient that authenticates for the Power Platform API and does not follow redirects). Nothing was requested.":"This org is in the Public cloud: supply MakerSdkOptions.powerPlatformApiClient (the Power Platform API route) or powerAppsServiceClient (the classic route). Neither was given, so nothing was requested.")}};Vc.ConnectivityRouter=lh});var ja=v(vi=>{"use strict";function yV(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 ch(e,t){return t===void 0&&(t=Object),t&&typeof t.freeze=="function"?t.freeze(e):e}function bV(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 rA=ch({HTML:"text/html",isHTML:function(e){return e===rA.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),nA=ch({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(e){return e===nA.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"}),Gc=/[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]/,uh=new RegExp("[\\-\\.0-9"+Gc.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),vV=new RegExp("^"+Gc.source+uh.source+"*(?::"+Gc.source+uh.source+"*)?$");vi.assign=bV;vi.find=yV;vi.freeze=ch;vi.MIME_TYPE=rA;vi.NAMESPACE=nA;vi.nameStartChar=Gc;vi.nameChar=uh;vi.tagNamePattern=vV});var Eh=v(Ai=>{var dh=ja(),Bn=dh.find,Ol=dh.NAMESPACE,Ha=dh.tagNamePattern;function wV(e){return e!==""}function CV(e){return e?e.split(/[\t\n\f\r ]+/).filter(wV):[]}function EV(e,t){return e.hasOwnProperty(t)||(e[t]=!0),e}function iA(e){if(!e)return[];var t=CV(e);return Object.keys(t.reduce(EV,{}))}function AV(e){return function(t){return e&&e.indexOf(t)!==-1}}function Rl(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function yr(e,t){var r=e.prototype;if(!(r instanceof t)){let i=function(){};var n=i;i.prototype=t.prototype,i=new i,Rl(r,i),e.prototype=r=i}r.constructor!=e&&(typeof e!="function"&&console.error("unknown Class:"+e),r.constructor=e)}var br={},Xr=br.ELEMENT_NODE=1,Ka=br.ATTRIBUTE_NODE=2,Il=br.TEXT_NODE=3,fA=br.CDATA_SECTION_NODE=4,pA=br.ENTITY_REFERENCE_NODE=5,SV=br.ENTITY_NODE=6,fh=br.PROCESSING_INSTRUCTION_NODE=7,ph=br.COMMENT_NODE=8,mA=br.DOCUMENT_NODE=9,hA=br.DOCUMENT_TYPE_NODE=10,wi=br.DOCUMENT_FRAGMENT_NODE=11,NV=br.NOTATION_NODE=12,Bt={},wt={},rse=Bt.INDEX_SIZE_ERR=(wt[1]="Index size error",1),nse=Bt.DOMSTRING_SIZE_ERR=(wt[2]="DOMString size error",2),gr=Bt.HIERARCHY_REQUEST_ERR=(wt[3]="Hierarchy request error",3),ise=Bt.WRONG_DOCUMENT_ERR=(wt[4]="Wrong document",4),oA=Bt.INVALID_CHARACTER_ERR=(wt[5]="Invalid character",5),ose=Bt.NO_DATA_ALLOWED_ERR=(wt[6]="No data allowed",6),ase=Bt.NO_MODIFICATION_ALLOWED_ERR=(wt[7]="No modification allowed",7),gA=Bt.NOT_FOUND_ERR=(wt[8]="Not found",8),sse=Bt.NOT_SUPPORTED_ERR=(wt[9]="Not supported",9),aA=Bt.INUSE_ATTRIBUTE_ERR=(wt[10]="Attribute in use",10),vn=Bt.INVALID_STATE_ERR=(wt[11]="Invalid state",11),lse=Bt.SYNTAX_ERR=(wt[12]="Syntax error",12),use=Bt.INVALID_MODIFICATION_ERR=(wt[13]="Invalid modification",13),cse=Bt.NAMESPACE_ERR=(wt[14]="Invalid namespace",14),dse=Bt.INVALID_ACCESS_ERR=(wt[15]="Invalid access",15);function fe(e,t){if(t instanceof Error)var r=t;else r=this,Error.call(this,wt[e]),this.message=wt[e],Error.captureStackTrace&&Error.captureStackTrace(this,fe);return r.code=e,t&&(this.message=this.message+": "+t),r}fe.prototype=Error.prototype;Rl(Bt,fe);function Ci(){}Ci.prototype={length:0,item:function(e){return e>=0&&e<this.length?this[e]:null},toString:function(e,t,r){for(var n=!!r&&!!r.requireWellFormed,i=[],o=0;o<this.length;o++)Ch(this[o],i,e,t,null,n);return i.join("")},filter:function(e){return Array.prototype.filter.call(this,e)},indexOf:function(e){return Array.prototype.indexOf.call(this,e)}};function Ja(e,t){this._node=e,this._refresh=t,mh(this)}function mh(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!==t){var r=e._refresh(e._node);if(IA(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];Rl(r,e),e._inc=t}}Ja.prototype.item=function(e){return mh(this),this[e]||null};yr(Ja,Ci);function zc(){this._nameIndex=Object.create(null)}function yA(e,t){for(var r=e.length;r--;)if(e[r]===t)return r}function _V(e,t){e._nameIndex[t.nodeName]=t}function bA(e,t){e._nameIndex[t.nodeName]===t&&delete e._nameIndex[t.nodeName]}function sA(e,t,r,n){if(n?(t[yA(t,n)]=r,bA(t,n)):t[t.length++]=r,_V(t,r),e){r.ownerElement=e;var i=e.ownerDocument;i&&(n&&CA(i,e,n),TV(i,e,r))}}function lA(e,t,r){var n=yA(t,r);if(n>=0){for(var i=t.length-1;n<i;)t[n]=t[++n];if(t.length=i,bA(t,r),e){var o=e.ownerDocument;o&&(CA(o,e,r),r.ownerElement=null)}}else throw new fe(gA,new Error(e.tagName+"@"+r))}zc.prototype={length:0,item:Ci.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 fe(aA);var r=this._nameIndex[e.nodeName];return sA(this._ownerElement,this,e,r),r},setNamedItemNS:function(e){var t=e.ownerElement,r;if(t&&t!=this._ownerElement)throw new fe(aA);return r=this.getNamedItemNS(e.namespaceURI,e.localName),sA(this._ownerElement,this,e,r),r},removeNamedItem:function(e){var t=this.getNamedItem(e);return lA(this._ownerElement,this,t),t},removeNamedItemNS:function(e,t){var r=this.getNamedItemNS(e,t);return lA(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 vA(){}vA.prototype={hasFeature:function(e,t){return!0},createDocument:function(e,t,r){var n=new Ll;if(n.implementation=this,n.childNodes=new Ci,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 Yc;return n.name=e,n.nodeName=e,n.publicId=t||"",n.systemId=r||"",n}};function Ne(){}Ne.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 Hc(this,e,t)},replaceChild:function(e,t){Hc(this,e,t,AA),t&&this.removeChild(t)},removeChild:function(e){return EA(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return DA(this.ownerDocument||this,this,e)},normalize:function(){vt(this,null,{enter:function(e){for(var t=e.firstChild;t;){var r=t.nextSibling;if(r!==null&&r.nodeType===Il&&t.nodeType===Il){for(var n=[],i=r;i!==null&&i.nodeType===Il;)n.push(i.data),i=i.nextSibling;for(var o=t.nextSibling;o!==i;){var a=o.nextSibling;o.parentNode=null,o.previousSibling=null,o.nextSibling=null,o=a}t.nextSibling=i,i!==null?i.previousSibling=t:e.lastChild=t,t.appendData(n.join("")),Jc(e.ownerDocument,e),t=i}else t=r}return!0}})},isSupported:function(e,t){return this.ownerDocument.implementation.hasFeature(e,t)},hasAttributes:function(){return this.attributes.length>0},lookupPrefix:function(e){for(var t=this;t;){var r=t._nsMap;if(r){for(var n in r)if(Object.prototype.hasOwnProperty.call(r,n)&&r[n]===e)return n}t=t.nodeType==Ka?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==Ka?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){var t=this.lookupPrefix(e);return t==null}};function wA(e){return e=="<"&&"<"||e==">"&&">"||e=="&"&&"&"||e=='"'&&"""||"&#"+e.charCodeAt()+";"}Rl(br,Ne);Rl(br,Ne.prototype);function jc(e,t){return vt(e,null,{enter:function(r){return t(r)?vt.STOP:!0}})===vt.STOP}function vt(e,t,r){for(var n=[{node:e,context:t,phase:vt.ENTER}];n.length>0;){var i=n.pop();if(i.phase===vt.ENTER){var o=r.enter(i.node,i.context);if(o===vt.STOP)return vt.STOP;if(n.push({node:i.node,context:o,phase:vt.EXIT}),o==null)continue;for(var a=i.node.lastChild;a;)n.push({node:a,context:o,phase:vt.ENTER}),a=a.previousSibling}else r.exit&&r.exit(i.node,i.context)}}vt.STOP=Symbol("walkDOM.STOP");vt.ENTER=0;vt.EXIT=1;function Ll(){this.ownerDocument=this}function TV(e,t,r){e&&e._inc++;var n=r.namespaceURI;n===Ol.XMLNS&&(t._nsMap[r.prefix?r.localName:""]=r.value)}function CA(e,t,r,n){e&&e._inc++;var i=r.namespaceURI;i===Ol.XMLNS&&delete t._nsMap[r.prefix?r.localName:""]}function Jc(e,t,r){if(e&&e._inc){e._inc++;var n=t.childNodes;if(r)n[n.length++]=r;else{for(var i=t.firstChild,o=0;i;)n[o++]=i,i=i.nextSibling;n.length=o,delete n[n.length]}}}function EA(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,Jc(e.ownerDocument,e),t}function DV(e){return e&&(e.nodeType===Ne.DOCUMENT_NODE||e.nodeType===Ne.DOCUMENT_FRAGMENT_NODE||e.nodeType===Ne.ELEMENT_NODE)}function IV(e){return e&&(qn(e)||hh(e)||Ei(e)||e.nodeType===Ne.DOCUMENT_FRAGMENT_NODE||e.nodeType===Ne.COMMENT_NODE||e.nodeType===Ne.PROCESSING_INSTRUCTION_NODE)}function Ei(e){return e&&e.nodeType===Ne.DOCUMENT_TYPE_NODE}function qn(e){return e&&e.nodeType===Ne.ELEMENT_NODE}function hh(e){return e&&e.nodeType===Ne.TEXT_NODE}function uA(e,t){var r=e.childNodes||[];if(Bn(r,qn)||Ei(t))return!1;var n=Bn(r,Ei);return!(t&&n&&r.indexOf(n)>r.indexOf(t))}function cA(e,t){var r=e.childNodes||[];function n(o){return qn(o)&&o!==t}if(Bn(r,n))return!1;var i=Bn(r,Ei);return!(t&&i&&r.indexOf(i)>r.indexOf(t))}function OV(e,t,r){if(!DV(e))throw new fe(gr,"Unexpected parent node type "+e.nodeType);if(r&&r.parentNode!==e)throw new fe(gA,"child not in parent");if(!IV(t)||Ei(t)&&e.nodeType!==Ne.DOCUMENT_NODE)throw new fe(gr,"Unexpected node type "+t.nodeType+" for parent node type "+e.nodeType)}function PV(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===Ne.DOCUMENT_FRAGMENT_NODE){var o=i.filter(qn);if(o.length>1||Bn(i,hh))throw new fe(gr,"More than one element or text in fragment");if(o.length===1&&!uA(e,r))throw new fe(gr,"Element in fragment can not be inserted before doctype")}if(qn(t)&&!uA(e,r))throw new fe(gr,"Only one element can be added and only after doctype");if(Ei(t)){if(Bn(n,Ei))throw new fe(gr,"Only one doctype is allowed");var a=Bn(n,qn);if(r&&n.indexOf(a)<n.indexOf(r))throw new fe(gr,"Doctype can only be inserted before an element");if(!r&&a)throw new fe(gr,"Doctype can not be appended since element is present")}}function AA(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===Ne.DOCUMENT_FRAGMENT_NODE){var o=i.filter(qn);if(o.length>1||Bn(i,hh))throw new fe(gr,"More than one element or text in fragment");if(o.length===1&&!cA(e,r))throw new fe(gr,"Element in fragment can not be inserted before doctype")}if(qn(t)&&!cA(e,r))throw new fe(gr,"Only one element can be added and only after doctype");if(Ei(t)){let l=function(u){return Ei(u)&&u!==r};var s=l;if(Bn(n,l))throw new fe(gr,"Only one doctype is allowed");var a=Bn(n,qn);if(r&&n.indexOf(a)<n.indexOf(r))throw new fe(gr,"Doctype can only be inserted before an element")}}function Hc(e,t,r,n){OV(e,t,r),e.nodeType===Ne.DOCUMENT_NODE&&(n||PV)(e,t,r);var i=t.parentNode;if(i&&i.removeChild(t),t.nodeType===wi){var o=t.firstChild;if(o==null)return t;var a=t.lastChild}else o=a=t;var s=r?r.previousSibling:e.lastChild;o.previousSibling=s,a.nextSibling=r,s?s.nextSibling=o:e.firstChild=o,r==null?e.lastChild=a:r.previousSibling=a;do{o.parentNode=e;var l=e.ownerDocument||e;Pl(o,l)}while(o!==a&&(o=o.nextSibling));return Jc(e.ownerDocument||e,e),t.nodeType==wi&&(t.firstChild=t.lastChild=null),t}function Pl(e,t){if(e.ownerDocument!==t){if(e.ownerDocument=t,e.nodeType===Xr&&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;)Pl(i,t),i=i.nextSibling}}function RV(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,Jc(e.ownerDocument,e,t);var r=e.ownerDocument||e;return Pl(t,r),t}Ll.prototype={nodeName:"#document",nodeType:mA,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==wi){for(var r=e.firstChild;r;){var n=r.nextSibling;this.insertBefore(r,t),r=n}return e}return Hc(this,e,t),Pl(e,this),this.documentElement===null&&e.nodeType===Xr&&(this.documentElement=e),e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),EA(this,e)},replaceChild:function(e,t){Hc(this,e,t,AA),Pl(e,this),t&&this.removeChild(t),qn(e)&&(this.documentElement=e)},importNode:function(e,t){return LV(this,e,t)},getElementById:function(e){var t=null;return jc(this.documentElement,function(r){if(r.nodeType==Xr&&r.getAttribute("id")==e)return t=r,!0}),t},getElementsByClassName:function(e){var t=iA(e);return new Ja(this,function(r){var n=[];return t.length>0&&jc(r.documentElement,function(i){if(i!==r&&i.nodeType===Xr){var o=i.getAttribute("class");if(o){var a=e===o;if(!a){var s=iA(o);a=t.every(AV(s))}a&&n.push(i)}}}),n})},createElement:function(e){var t=new Wo;t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.localName=e,t.childNodes=new Ci;var r=t.attributes=new zc;return r._ownerElement=t,t},createDocumentFragment:function(){var e=new Qc;return e.ownerDocument=this,e.childNodes=new Ci,e},createTextNode:function(e){var t=new gh;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new yh;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){if(e.indexOf("]]>")!==-1)throw new fe(oA,'data contains "]]>"');var t=new bh;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var r=new wh;return r.ownerDocument=this,r.tagName=r.nodeName=r.target=e,r.nodeValue=r.data=t,r},createAttribute:function(e){var t=new Kc;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){if(!Ha.test(e))throw new fe(oA,'not a valid xml name "'+e+'"');var t=new vh;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var r=new Wo,n=t.split(":"),i=r.attributes=new zc;return r.childNodes=new Ci,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 Kc,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}};yr(Ll,Ne);function Wo(){this._nsMap={}}Wo.prototype={nodeType:Xr,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===wi?this.insertBefore(e,null):RV(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 Ja(this,function(t){var r=[];return jc(t,function(n){n!==t&&n.nodeType==Xr&&(e==="*"||n.tagName==e)&&r.push(n)}),r})},getElementsByTagNameNS:function(e,t){return new Ja(this,function(r){var n=[];return jc(r,function(i){i!==r&&i.nodeType===Xr&&(e==="*"||i.namespaceURI===e)&&(t==="*"||i.localName==t)&&n.push(i)}),n})}};Ll.prototype.getElementsByTagName=Wo.prototype.getElementsByTagName;Ll.prototype.getElementsByTagNameNS=Wo.prototype.getElementsByTagNameNS;yr(Wo,Ne);function Kc(){}Kc.prototype.nodeType=Ka;yr(Kc,Ne);function kl(){}kl.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(wt[gr])},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}};yr(kl,Ne);function gh(){}gh.prototype={nodeName:"#text",nodeType:Il,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}};yr(gh,kl);function yh(){}yh.prototype={nodeName:"#comment",nodeType:ph};yr(yh,kl);function bh(){}bh.prototype={nodeName:"#cdata-section",nodeType:fA};yr(bh,kl);function Yc(){}Yc.prototype.nodeType=hA;yr(Yc,Ne);function SA(){}SA.prototype.nodeType=NV;yr(SA,Ne);function NA(){}NA.prototype.nodeType=SV;yr(NA,Ne);function vh(){}vh.prototype.nodeType=pA;yr(vh,Ne);function Qc(){}Qc.prototype.nodeName="#document-fragment";Qc.prototype.nodeType=wi;yr(Qc,Ne);function wh(){}wh.prototype.nodeType=fh;yr(wh,Ne);function _A(){}_A.prototype.serializeToString=function(e,t,r,n){return TA.call(e,t,r,n)};Ne.prototype.toString=TA;function TA(e,t,r){var n=!!r&&!!r.requireWellFormed,i=[],o=this.nodeType==9&&this.documentElement||this,a=o.prefix,s=o.namespaceURI;if(s&&a==null){var a=o.lookupPrefix(s);if(a==null)var l=[{namespace:s,prefix:null}]}return Ch(this,i,e,t,l,n),i.join("")}function dA(e,t,r){var n=e.prefix||"",i=e.namespaceURI;if(!i||n==="xml"&&i===Ol.XML||i===Ol.XMLNS)return!1;for(var o=r.length;o--;){var a=r[o];if(a.prefix===n)return a.namespace!==i}return!0}function Wc(e,t,r,n){if(n&&!Ha.test(t))throw new fe(vn,'The attribute name "'+t+'" is not a valid XML QName');e.push(" ",t,'="',r.replace(/[<>&"\t\n\r]/g,wA),'"')}function Ch(e,t,r,n,i,o){i||(i=[]),vt(e,{ns:i,isHTML:r},{enter:function(a,s){var l=s.ns,u=s.isHTML;if(n)if(a=n(a),a){if(typeof a=="string")return t.push(a),null}else return null;switch(a.nodeType){case Xr:var c=a.attributes,d=c.length,f=a.tagName;u=Ol.isHTML(a.namespaceURI)||u;var p=f;if(!u&&!a.prefix&&a.namespaceURI){for(var m,h=0;h<c.length;h++)if(c.item(h).name==="xmlns"){m=c.item(h).value;break}if(!m)for(var g=l.length-1;g>=0;g--){var b=l[g];if(b.prefix===""&&b.namespace===a.namespaceURI){m=b.namespace;break}}if(m!==a.namespaceURI)for(var g=l.length-1;g>=0;g--){var b=l[g];if(b.namespace===a.namespaceURI){b.prefix&&(p=b.prefix+":"+f);break}}}if(o&&!Ha.test(p))throw new fe(vn,'The element name "'+p+'" is not a valid XML QName');t.push("<",p);for(var w=l.slice(),E=0;E<d;E++){var A=c.item(E);A.prefix=="xmlns"?w.push({prefix:A.localName,namespace:A.value}):A.nodeName=="xmlns"&&w.push({prefix:"",namespace:A.value})}for(var E=0;E<d;E++){var A=c.item(E);if(dA(A,u,w)){var L=A.prefix||"",R=A.namespaceURI;Wc(t,L?"xmlns:"+L:"xmlns",R,o),w.push({prefix:L,namespace:R})}var I=n?n(A):A;I&&(typeof I=="string"?t.push(I):Wc(t,I.name,I.value,o))}if(f===p&&dA(a,u,w)){var D=a.prefix||"",R=a.namespaceURI;Wc(t,D?"xmlns:"+D:"xmlns",R,o),w.push({prefix:D,namespace:R})}var O=a.firstChild;if(O||u&&!/^(?:meta|link|img|br|hr|input)$/i.test(f)){if(t.push(">"),u&&/^script$/i.test(f)){for(;O;)O.data?t.push(O.data):Ch(O,t,u,n,w.slice(),o),O=O.nextSibling;return t.push("</",f,">"),null}return{ns:w,isHTML:u,tag:p}}else return t.push("/>"),null;case mA:case wi:return{ns:l.slice(),isHTML:u,tag:null};case Ka:return Wc(t,a.name,a.value,o),null;case Il:return t.push(a.data.replace(/[<&>]/g,wA)),null;case fA:if(o&&a.data.indexOf("]]>")!==-1)throw new fe(vn,'The CDATASection data contains "]]>"');return t.push("<![CDATA[",a.data.replace(/]]>/g,"]]]]><![CDATA[>"),"]]>"),null;case ph:if(o&&a.data.indexOf("-->")!==-1)throw new fe(vn,'The comment node data contains "-->"');return t.push("<!--",a.data,"-->"),null;case hA:if(o){if(!Ha.test(a.name))throw new fe(vn,'The doctype name "'+a.name+'" is not a valid XML Name');if(a.publicId&&!/^("[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%']*"|'[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%'"]*')$/.test(a.publicId))throw new fe(vn,"DocumentType publicId is not a valid PubidLiteral");if(a.systemId&&!/^("[^"]*"|'[^']*')$/.test(a.systemId))throw new fe(vn,"DocumentType systemId is not a valid SystemLiteral");if(a.internalSubset&&a.internalSubset.indexOf("]>")!==-1)throw new fe(vn,'DocumentType internalSubset contains "]>"')}var $=a.publicId,K=a.systemId;if(t.push("<!DOCTYPE ",a.name),$)t.push(" PUBLIC ",$),K&&K!="."&&t.push(" ",K),t.push(">");else if(K&&K!=".")t.push(" SYSTEM ",K,">");else{var Re=a.internalSubset;Re&&t.push(" [",Re,"]"),t.push(">")}return null;case fh:if(o){if(!Ha.test(a.target)||a.target.indexOf(":")!==-1||a.target.toLowerCase()==="xml")throw new fe(vn,'The processing instruction target "'+a.target+'" is not a valid XML NCName or is reserved');if(a.data.indexOf("?>")!==-1)throw new fe(vn,'The ProcessingInstruction data contains "?>"')}return t.push("<?",a.target," ",a.data,"?>"),null;case pA:if(o&&!Ha.test(a.nodeName))throw new fe(vn,'The entity reference name "'+a.nodeName+'" is not a valid XML Name');return t.push("&",a.nodeName,";"),null;default:return t.push("??",a.nodeName),null}},exit:function(a,s){s&&s.tag&&t.push("</",s.tag,">")}})}function LV(e,t,r){var n;return vt(t,null,{enter:function(i,o){var a=i.cloneNode(!1);a.ownerDocument=e,a.parentNode=null,o===null?n=a:o.appendChild(a);var s=i.nodeType===Ka||r;return s?a:null}}),n}function DA(e,t,r){var n;return vt(t,null,{enter:function(i,o){var a=new i.constructor;for(var s in i)if(Object.prototype.hasOwnProperty.call(i,s)){var l=i[s];typeof l!="object"&&l!=a[s]&&(a[s]=l)}i.childNodes&&(a.childNodes=new Ci),a.ownerDocument=e;var u=r;switch(a.nodeType){case Xr:var c=i.attributes,d=a.attributes=new zc,f=c.length;d._ownerElement=a;for(var p=0;p<f;p++)a.setAttributeNode(DA(e,c.item(p),!0));break;case Ka:u=!0}return o!==null?o.appendChild(a):n=a,u?a:null}}),n}function IA(e,t,r){e[t]=r}try{Object.defineProperty&&(Object.defineProperty(Ja.prototype,"length",{get:function(){return mh(this),this.$$length}}),Object.defineProperty(Ne.prototype,"textContent",{get:function(){if(this.nodeType===Xr||this.nodeType===wi){var e=[];return vt(this,null,{enter:function(t){if(t.nodeType===Xr||t.nodeType===wi)return!0;if(t.nodeType===fh||t.nodeType===ph)return null;e.push(t.nodeValue)}}),e.join("")}return this.nodeValue},set:function(e){switch(this.nodeType){case Xr:case wi: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}}}),IA=function(e,t,r){e["$$"+t]=r})}catch{}Ai.DocumentType=Yc;Ai.DOMException=fe;Ai.DOMImplementation=vA;Ai.Element=Wo;Ai.Node=Ne;Ai.NodeList=Ci;Ai.walkDOM=vt;Ai.XMLSerializer=_A});var PA=v(xl=>{"use strict";var OA=ja().freeze;xl.XML_ENTITIES=OA({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});xl.HTML_ENTITIES=OA({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"});xl.entityMap=xl.HTML_ENTITIES});var $A=v(Sh=>{var Ml=ja().NAMESPACE,Ah=ja().tagNamePattern,Ya=0,to=1,Qa=2,$l=3,Xa=4,Za=5,Fl=6,Xc=7;function es(e,t){this.message=e,this.locator=t,Error.captureStackTrace&&Error.captureStackTrace(this,es)}es.prototype=new Error;es.prototype.name=es.name;function kA(){}kA.prototype={parse:function(e,t,r){var n=this.domBuilder;n.startDocument(),MV(t,t={}),kV(e,t,r,n,this.errorHandler),n.endDocument()}};function kV(e,t,r,n,i){function o(ge){if(ge>65535){ge-=65536;var ht=55296+(ge>>10),Ro=56320+(ge&1023);return String.fromCharCode(ht,Ro)}else return String.fromCharCode(ge)}function a(ge){var ht=ge.slice(1,-1);return Object.hasOwnProperty.call(r,ht)?r[ht]:ht.charAt(0)==="#"?o(parseInt(ht.substr(1).replace("x","0x"))):(i.error("entity not found:"+ge),ge)}function s(ge){if(ge>h){var ht=e.substring(h,ge).replace(/&#?\w+;/g,a);f&&l(h),n.characters(ht,0,ge-h),h=ge}}function l(ge,ht){for(;ge>=c&&(ht=d.exec(e));)u=ht.index,c=u+ht[0].length,f.lineNumber++;f.columnNumber=ge-u+1}for(var u=0,c=0,d=/.*(?:\r\n?|\n)|.*$/g,f=n.locator,p=[{currentNSMap:t}],m={},h=0;;){try{var g=e.indexOf("<",h);if(g<0){if(!e.substr(h).match(/^\s*$/)){var b=n.doc,w=b.createTextNode(e.substr(h));b.appendChild(w),n.currentElement=w}return}switch(g>h&&s(g),e.charAt(g+1)){case"/":var K=e.indexOf(">",g+3),E=e.substring(g+2,K).replace(/^([\s\S]*?[^ \t\n\r])?[ \t\n\r]*$/,"$1"),A=p.pop();K<0?(E=e.substring(g+2).replace(/[\s<].*/,""),i.error("end tag name: "+E+" is not complete:"+A.tagName),K=g+1+E.length):E.match(/\s</)?(E=E.replace(/[\s<].*/,""),i.error("end tag name: "+E+" maybe not complete"),K=g+1+E.length):/[ \t\n\r]/.test(E)&&Ah.test(E.split(/[ \t\n\r]/)[0])&&i.error('end tag name is followed by whitespace and trailing content: "'+E+'"');var L=A.localNSMap,R=A.tagName==E,I=R||A.tagName&&A.tagName.toLowerCase()==E.toLowerCase();if(I){if(n.endElement(A.uri,A.localName,E),L)for(var D in L)Object.prototype.hasOwnProperty.call(L,D)&&n.endPrefixMapping(D);R||i.fatalError("end tag name: "+E+" is not match the current start tagName:"+A.tagName)}else p.push(A);K++;break;case"?":f&&l(g),K=BV(e,g,n);break;case"!":f&&l(g),K=UV(e,g,n,i);break;default:f&&l(g);var O=new xA,$=p[p.length-1].currentNSMap,K=xV(e,g,O,$,a,i),Re=O.length;if(!O.closed&&FV(e,K,O.tagName,m)&&(O.closed=!0,r.nbsp||i.warning("unclosed xml attribute")),f&&Re){for(var It=RA(f,{}),Le=0;Le<Re;Le++){var at=O[Le];l(at.offset),at.locator=RA(f,{})}n.locator=It,LA(O,n,$)&&p.push(O),n.locator=f}else LA(O,n,$)&&p.push(O);Ml.isHTML(O.uri)&&!O.closed?K=$V(e,K,O.tagName,a,n):K++}}catch(ge){if(ge instanceof es)throw ge;i.error("element parse error: "+ge),K=-1}K>h?h=K:s(Math.max(g,h)+1)}}function RA(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function xV(e,t,r,n,i,o){function a(p,m,h){r.attributeNames.hasOwnProperty(p)&&o.fatalError("Attribute "+p+" redefined"),r.addValue(p,m.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,i),h)}for(var s,l,u=++t,c=Ya;;){var d=e.charAt(u);if(c===Ya&&d==="<")throw new Error("unexpected < in tag name: "+e.slice(t,u));switch(d){case"=":if(c===to)s=e.slice(t,u),c=$l;else if(c===Qa)c=$l;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(c===$l||c===to)if(c===to&&(o.warning('attribute value must after "="'),s=e.slice(t,u)),t=u+1,u=e.indexOf(d,t),u>0)l=e.slice(t,u),a(s,l,t-1),c=Za;else throw new Error("attribute value no end '"+d+"' match");else if(c==Xa)l=e.slice(t,u),a(s,l,t),o.warning('attribute "'+s+'" missed start quot('+d+")!!"),t=u+1,c=Za;else throw new Error('attribute value must after "="');break;case"/":switch(c){case Ya:r.setTagName(e.slice(t,u));case Za:case Fl:case Xc:c=Xc,r.closed=!0;case Xa:case to:break;case Qa:r.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return o.error("unexpected end of input"),c==Ya&&r.setTagName(e.slice(t,u)),u;case">":switch(c){case Ya:r.setTagName(e.slice(t,u));case Za:case Fl:case Xc:break;case Xa:case to:l=e.slice(t,u),l.slice(-1)==="/"&&(r.closed=!0,l=l.slice(0,-1));case Qa:c===Qa&&(l=s),c==Xa?(o.warning('attribute "'+l+'" missed quot(")!'),a(s,l,t)):((!Ml.isHTML(n[""])||!l.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+l+'" missed value!! "'+l+'" instead!!'),a(l,l,t));break;case $l:throw new Error("attribute value missed!!")}return u;case"\x80":d=" ";default:if(d<=" ")switch(c){case Ya:r.setTagName(e.slice(t,u)),c=Fl;break;case to:s=e.slice(t,u),c=Qa;break;case Xa:var l=e.slice(t,u);o.warning('attribute "'+l+'" missed quot(")!!'),a(s,l,t);case Za:c=Fl;break}else switch(c){case Qa:var f=r.tagName;(!Ml.isHTML(n[""])||!s.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+s+'" missed value!! "'+s+'" instead2!!'),a(s,s,t),t=u,c=to;break;case Za:o.warning('attribute space is required"'+s+'"!!');case Fl:c=to,t=u;break;case $l:c=Xa,t=u;break;case Xc:throw new Error("elements closed character '/' and '>' must be connected to")}}u++}}function LA(e,t,r){for(var n=e.tagName,i=null,d=e.length;d--;){var o=e[d],a=o.qName,s=o.value,f=a.indexOf(":");if(f>0)var l=o.prefix=a.slice(0,f),u=a.slice(f+1),c=l==="xmlns"&&u;else u=a,l=null,c=a==="xmlns"&&"";o.localName=u,c!==!1&&(i==null&&(i={},r=Object.create(r)),r[c]=i[c]=s,o.uri=Ml.XMLNS,t.startPrefixMapping(c,s))}for(var d=e.length;d--;){o=e[d];var l=o.prefix;l&&(l==="xml"&&(o.uri=Ml.XML),l!=="xmlns"&&(o.uri=r[l||""]))}var f=n.indexOf(":");f>0?(l=e.prefix=n.slice(0,f),u=e.localName=n.slice(f+1)):(l=null,u=e.localName=n);var p=e.uri=r[l||""];if(t.startElement(p,u,n,e),e.closed){if(t.endElement(p,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 $V(e,t,r,n,i){if(/^(?:script|textarea)$/i.test(r)){var o=e.indexOf("</"+r+">",t),a=e.substring(t+1,o);if(/[&<]/.test(a))return/^script$/i.test(r)?(i.characters(a,0,a.length),o):(a=a.replace(/&#?\w+;/g,n),i.characters(a,0,a.length),o)}return t+1}function FV(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 MV(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function UV(e,t,r,n){var i=e.charAt(t+2);switch(i){case"-":if(e.charAt(t+3)==="-"){var o=e.indexOf("-->",t+4);return o>t?(r.comment(e,t+4,o-t-4),o+3):(n.error("Unclosed comment"),-1)}else return-1;default:if(e.substr(t+3,6)=="CDATA["){var o=e.indexOf("]]>",t+9);return r.startCDATA(),r.characters(e,t+9,o-t-9),r.endCDATA(),o+3}var a=qV(e,t),s=a.length;if(s>1&&/!doctype/i.test(a[0][0])){var l=a[1][0],u=!1,c=!1;s>3&&(/^public$/i.test(a[2][0])?(u=a[3][0],c=s>4&&a[4][0]):/^system$/i.test(a[2][0])&&(c=a[3][0]));var d=a[s-1];return r.startDTD(l,u,c),r.endDTD(),d.index+d[0].length}}return-1}function BV(e,t,r){var n=e.indexOf("?>",t);if(n){var i=e.substring(t,n).match(/^<\?(\S*)\s*([\s\S]*?)$/);if(i){var o=i[0].length;return r.processingInstruction(i[1],i[2]),n+2}else return-1}return-1}function xA(){this.attributeNames={}}xA.prototype={setTagName:function(e){if(!Ah.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},addValue:function(e,t,r){if(!Ah.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 qV(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}Sh.XMLReader=kA;Sh.ParseError=es});var GA=v(ed=>{var VV=ja(),GV=Eh(),FA=PA(),BA=$A(),WV=GV.DOMImplementation,MA=VV.NAMESPACE,zV=BA.ParseError,jV=BA.XMLReader;function qA(e){return e.replace(/\r[\n\u0085]/g,`+`}});var bA=v(ld=>{"use strict";Object.defineProperty(ld,"__esModule",{value:!0});ld.generateGenPageRuntimeTypes=void 0;var yA=Oh(),Qo=Q(),gA=new Set(["None","ColorsDefaultsConstraints","ColorsDefaultsConstraintsDescriptions"]),Xo="generateGenPageRuntimeTypes";async function ZV(e,t,r){let n=eG(t),i=tG(r),o=[];for(let a of n){let s=await e(a);if(s.columnDetailComplete!==!0)throw new Qo.SdkError("GENPAGE_DATA_SOURCE_INCOMPLETE",`${Xo}: the column metadata of data source '${a}' could not be read completely (a choice or lookup read failed, or returned options with no label), so its RuntimeTypes would lack enums a page can use. Retry.`);o.push(s)}return(0,yA.renderGenPageAuthoringTypes)(o,i)}ld.generateGenPageRuntimeTypes=ZV;function eG(e){if(!Array.isArray(e))throw new Qo.InvalidArgumentError(`${Xo}: dataSources must be an array of table logical names`);let t=new Set;for(let r of e){if(typeof r!="string"||!yA.TABLE_LOGICAL_NAME.test(r))throw new Qo.InvalidArgumentError(`${Xo}: a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(r)}'`);if(t.has(r))throw new Qo.InvalidArgumentError(`${Xo}: data source '${r}' is listed twice; a page's dataSources hold each table once`);t.add(r)}return[...t]}function tG(e){if(e===void 0)return"None";if(e===null||typeof e!="object"||Array.isArray(e))throw new Qo.InvalidArgumentError(`${Xo}: options must be an object`);let t=Object.keys(e).filter(n=>n!=="detail");if(t.length>0)throw new Qo.InvalidArgumentError(`${Xo}: unknown option '${t[0]}' (the only option is 'detail')`);let r=e.detail===void 0?"None":e.detail;if(typeof r!="string"||!gA.has(r))throw new Qo.InvalidArgumentError(`${Xo}: detail must be one of ${[...gA].map(n=>`'${n}'`).join(", ")}, got '${String(r)}'`);return r}});var SA=v(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});Zo.getEnvironmentLanguages=Zo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE=void 0;var rG=Q(),CA=fe();Zo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE="ENVIRONMENT_LANGUAGES_UNREADABLE";var vA="/organizations?$select=languagecode",nG="/RetrieveProvisionedLanguages()",iG="/RetrieveAvailableLanguages()";function EA(e,t){return new rG.SdkError(Zo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE,`The org's languages could not be read: ${e} ${t}. Nothing is assumed in its place \u2014 retry, or check the caller's access to the org.`)}function AA(e){return typeof e=="number"&&Number.isInteger(e)&&e>0}async function wA(e,t,r,n){let i=(0,CA.ensureSuccess)(await e.get(t),e.apiUrl(t)).body,o=i?.[r];if(!Array.isArray(o)||o.length===0||!o.every(AA))throw EA(n,`answered no list of language codes in '${r}'`);return[...new Set(o)]}async function oG(e){var t;let r=(0,CA.ensureSuccess)(await e.get(vA),e.apiUrl(vA)).body,n=r?.value,i=Array.isArray(n)&&n.length===1?(t=n[0])===null||t===void 0?void 0:t.languagecode:void 0;if(!AA(i))throw EA("the organization read","did not answer one row with a language code");let o=await wA(e,nG,"RetrieveProvisionedLanguages","RetrieveProvisionedLanguages"),a=await wA(e,iG,"LocaleIds","RetrieveAvailableLanguages");return{baseLanguage:i,available:a,provisioned:o}}Zo.getEnvironmentLanguages=oG});var Wl=v(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.projectConnectorOperationSchema=lt.projectConnectorOperations=lt.validateConnectorSwagger=lt.CONNECTOR_SCHEMA_TOO_LARGE_CODE=lt.CONNECTOR_OPERATION_NOT_FOUND_CODE=lt.CONNECTOR_SWAGGER_UNSUPPORTED_CODE=lt.CONNECTIVITY_RESPONSE_UNREADABLE_CODE=void 0;var Gl=Q();lt.CONNECTIVITY_RESPONSE_UNREADABLE_CODE="CONNECTIVITY_RESPONSE_UNREADABLE";lt.CONNECTOR_SWAGGER_UNSUPPORTED_CODE="CONNECTOR_SWAGGER_UNSUPPORTED";lt.CONNECTOR_OPERATION_NOT_FOUND_CODE="CONNECTOR_OPERATION_NOT_FOUND";lt.CONNECTOR_SCHEMA_TOO_LARGE_CODE="CONNECTOR_SCHEMA_TOO_LARGE";var NA=64,_A=128,TA=2e5,DA=4e6,aG=new Set(["get","put","post","delete","patch","head","options"]),sG=new Set(["query","header","path","formData","body"]);function sn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Tn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Dt(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function et(e){return e.length>80?`'${e.slice(0,80)}\u2026'`:`'${e}'`}function ke(e,t){return new Gl.SdkError(lt.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`The connector's swagger could not be read: ${e} ${t}. Nothing was skipped or assumed in its place.`)}function fo(e,t){return new Gl.SdkError(lt.CONNECTOR_SWAGGER_UNSUPPORTED_CODE,`The connector's swagger is outside the supported contract (Swagger 2.0 as the Power Apps API serves it): ${e} ${t}.`)}function lG(e,t){let r=e;for(let n of t.slice(2).split("/")){let i=n.replace(/~1/g,"/").replace(/~0/g,"~");if(typeof r!="object"||r===null||!Tn(r,i))return{found:!1};r=r[i]}return{found:!0,value:r}}function Lh(e,t,r){if(!t.startsWith("#/"))throw fo(r,`has a $ref that is not a local '#/\u2026' pointer (${et(t)})`);if(t.includes("%"))throw fo(r,`has a $ref with a percent-encoded character (${et(t)}), which is not decoded`);if(/~(?![01])/.test(t))throw ke(r,`has a $ref with a malformed escape (${et(t)}): a '~' not followed by 0 or 1`);let n=lG(e,t);if(!n.found)throw ke(r,`has a $ref that does not resolve (${et(t)})`);return n.value}function ud(e,t){if(Tn(e,"$ref")){if(typeof e.$ref!="string")throw ke(t,`has a $ref that is ${Dt(e.$ref)}, not a string`);return e.$ref}}function uG(e,t,r){if(!sn(t))throw ke(r,`is ${Dt(t)}, not a parameter object`);let n=t,i=ud(t,r);if(i!==void 0){let s=Lh(e,i,r);if(!sn(s))throw ke(r,`has a $ref (${et(i)}) that resolves to ${Dt(s)}, not a parameter object`);if(ud(s,`${r} \u2192 ${et(i)}`)!==void 0)throw fo(r,`has a $ref (${et(i)}) to a parameter that is itself a $ref`);n=s}if(typeof n.name!="string")throw ke(r,"has no string name");let o=n.in;if(typeof o!="string"||!sG.has(o))throw ke(r,`has an in that is ${typeof o=="string"?et(o):Dt(o)}, not one of query, header, path, formData or body`);if(Tn(n,"required")&&typeof n.required!="boolean")throw ke(r,`has a required that is ${Dt(n.required)}, not a boolean`);let a=n["x-ms-visibility"];if(Tn(n,"x-ms-visibility")&&typeof a!="string")throw ke(r,`has an x-ms-visibility that is ${Dt(a)}, not a string`);return{name:n.name,in:o,required:n.required===!0,internal:a==="internal"}}function Ph(e){return`${e.in}:${e.name}`}function OA(e,t,r){if(!Tn(t,"parameters"))return[];let n=t.parameters;if(!Array.isArray(n))throw ke(r,`has parameters that are ${Dt(n)}, not an array`);let i=new Set;return n.map((o,a)=>{let s=`${r} parameters[${a}]`,l=uG(e,o,s),u=Ph(l);if(i.has(u))throw ke(s,`repeats the parameter ${et(l.name)} in ${et(l.in)}, which must be unique in its list`);return i.add(u),l})}function PA(e,t,r){let n=t.responses;if(!Tn(n,"200"))return;let i=`${r} response 200`,o=n[200];if(!sn(o))throw ke(i,`is ${Dt(o)}, not a response object`);let a=o,s=ud(o,i);if(s!==void 0){if(s.startsWith("#/")&&!/^#\/responses\/[^/]+$/.test(s))throw ke(i,`has a $ref (${et(s)}) that does not name a response ('#/responses/<name>')`);let l=Lh(e,s,i);if(!sn(l))throw ke(i,`has a $ref (${et(s)}) that resolves to ${Dt(l)}, not a response object`);if(ud(l,`${i} \u2192 ${et(s)}`)!==void 0)throw fo(i,`has a $ref (${et(s)}) to a response that is itself a $ref`);a=l}if(Tn(a,"content"))throw fo(i,"is an OpenAPI 3 response (it has content), not a Swagger 2.0 one");if(Tn(a,"schema")){if(!sn(a.schema))throw ke(i,`has a schema that is ${Dt(a.schema)}, not an object`);return a.schema}}function IA(e,t,r){if(!Tn(e,t))return;let n=e[t];if(typeof n!="string")throw ke(r,`has a ${t} that is ${Dt(n)}, not a string`);return n}function cG(e,t,r,n,i){if(!sn(t))throw ke(r,`is ${Dt(t)}, not an operation object`);let o=t.operationId;if(typeof o!="string")throw ke(r,`has no string operationId (${Dt(o)})`);if(n.has(o))throw ke(r,`repeats the operationId ${et(o)}, which must be unique in the document`);n.add(o);let a=IA(t,"summary",r),s=IA(t,"description",r),l=OA(e,t,r);if(!sn(t.responses))throw ke(r,`has no responses object (${Dt(t.responses)})`);return PA(e,t,r),{id:o,summary:a,description:s,node:t,where:r,parameters:l,pathParameters:i}}function kh(e){if(!sn(e))throw ke("the document",`is ${Dt(e)}, not an object`);if(Tn(e,"openapi"))throw fo("the document","is OpenAPI 3 (it has an openapi member), not Swagger 2.0");if(!Tn(e,"swagger"))throw ke("the document","names no Swagger version");if(e.swagger!=="2.0")throw fo("the document",`declares swagger ${et(String(e.swagger))}, not 2.0`);let t=e.paths;if(!sn(t))throw ke("the document",`has paths that are ${Dt(t)}, not an object`);let r=[],n=new Set;for(let i of Object.keys(t)){let o=t[i],a=`paths[${et(i)}]`;if(!sn(o))throw ke(a,`is ${Dt(o)}, not a path item object`);let s=[];for(let l of Object.keys(o))if(aG.has(l.toLowerCase()))r.push(cG(e,o[l],`${a}.${l}`,n,s));else if(l==="parameters")for(let u of OA(e,o,a))s.push(u);else if(!l.startsWith("x-"))throw fo(a,`has a ${et(l)} member; a path item may hold only HTTP methods, parameters and x- extensions`)}return{document:e,operations:r}}function dG(e){kh(e)}lt.validateConnectorSwagger=dG;var Rh=class{constructor(t,r){this.root=t,this.where=r,this.nodes=0,this.characters=0,this.path=[]}run(t){return this.visit(t,0)}tooLarge(t){return new Gl.SdkError(lt.CONNECTOR_SCHEMA_TOO_LARGE_CODE,`The response schema of ${this.where} is too large to return: it has ${t}. That is far above any connector measured, so this one is not read.`)}node(){if(this.nodes+=1,this.nodes>TA)throw this.tooLarge(`more than ${TA} nodes`)}text(t){if(this.characters+=t,this.characters>DA)throw this.tooLarge(`more than ${DA} characters of strings and keys`)}checkDepth(t){if(t>_A)throw this.tooLarge(`nesting deeper than ${_A} levels`)}visit(t,r){if(this.checkDepth(r),Array.isArray(t)){this.node();let n=[];for(let i of t)n.push(this.visit(i,r+1));return n}if(sn(t)){if(typeof t.$ref=="string")return this.reference(t.$ref,r);this.node();let n={};for(let i of Object.keys(t))this.text(i.length),Object.defineProperty(n,i,{value:this.visit(t[i],r+1),enumerable:!0,writable:!0,configurable:!0});return n}return this.node(),typeof t=="string"&&this.text(t.length),t}reference(t,r){if(this.path.includes(t)){this.checkDepth(r+1);let o=t.slice(t.lastIndexOf("/")+1);return this.node(),this.text(4),this.node(),this.text(o.length),{$ref:o}}if(this.path.length>=NA)throw this.tooLarge(`a $ref chain of more than ${NA} references`);let n=Lh(this.root,t,this.where);if(!sn(n))throw ke(this.where,`has a schema $ref (${et(t)}) that resolves to ${Dt(n)}, not a schema object`);this.path.push(t);let i=this.visit(n,r);return this.path.pop(),i}};function fG(e){let{operations:t}=kh(e);return{operations:t.map(r=>{var n,i;return{name:r.id,summary:(i=(n=r.summary)!==null&&n!==void 0?n:r.description)!==null&&i!==void 0?i:null}})}}lt.projectConnectorOperations=fG;function pG(e,t){if(typeof t!="string"||t==="")throw new Gl.InvalidArgumentError("operationId must be a non-empty string.");let{document:r,operations:n}=kh(e),i=n.find(u=>u.id===t);if(!i)throw new Gl.SdkError(lt.CONNECTOR_OPERATION_NOT_FOUND_CODE,`The connector has no operation with the id ${et(t)} (ids are matched exactly, case included). List the connector\u2019s operations to see its ids.`);let o=new Set(i.parameters.map(Ph)),a=[...i.parameters,...i.pathParameters.filter(u=>!o.has(Ph(u)))].filter(u=>!u.internal).map(({name:u,required:c})=>({name:u,required:c})),s=PA(r,i.node,i.where),l=s===void 0?{}:new Rh(r,`${i.where} (${et(i.id)})`).run(s);return{operation:i.id,parameters:a,response:l}}lt.projectConnectorOperationSchema=pG});var ea=v(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.readEnvironmentName=J.readConnection=J.connectorShortName=J.CONNECTOR_PREFIX=J.connectivityUnauthorized=J.errorCodeOf=J.messageOf=J.environmentFilter=J.unreadable=J.connectivityCloudOf=J.sameOrigin=J.parseUrl=J.bounded=J.kindOf=J.isObject=J.CONNECTOR_RUNTIME_UNSUPPORTED_CODE=J.CONNECTOR_NOT_TABULAR_CODE=J.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE=J.CONNECTIVITY_UNAUTHORIZED_CODE=J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE=J.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE=J.CONNECTIVITY_NOT_CONFIGURED_CODE=void 0;var zl=Q(),mG=fe(),hG=Wl();J.CONNECTIVITY_NOT_CONFIGURED_CODE="CONNECTIVITY_NOT_CONFIGURED";J.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE="CONNECTIVITY_CLOUD_UNSUPPORTED";J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE="CONNECTIVITY_ENVIRONMENT_UNVERIFIED";J.CONNECTIVITY_UNAUTHORIZED_CODE="CONNECTIVITY_UNAUTHORIZED";J.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE="CONNECTIVITY_ROUTE_DECOMMISSIONED";J.CONNECTOR_NOT_TABULAR_CODE="CONNECTOR_NOT_TABULAR";J.CONNECTOR_RUNTIME_UNSUPPORTED_CODE="CONNECTOR_RUNTIME_UNSUPPORTED";function Nr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}J.isObject=Nr;function ns(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}J.kindOf=ns;function is(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}J.bounded=is;function LA(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}J.parseUrl=LA;function gG(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}J.sameOrigin=gG;var yG=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,bG=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/;function vG(e){let t=LA(e),r=t?t.host.toLowerCase():"";if(bG.test(r))return"Test";let n=yG.exec(r);return n&&n[1]!=="9"?"Public":"Unsupported"}J.connectivityCloudOf=vG;function Yn(e,t){return new zl.SdkError(hG.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}J.unreadable=Yn;function wG(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}J.environmentFilter=wG;function CG(e){if(typeof e=="string"&&e.length>0)return is(e,500);if(Nr(e)){let t=Nr(e.error)?e.error.message:void 0;for(let r of[t,e.Message,e.message])if(typeof r=="string")return is(r,500)}return"request failed"}J.messageOf=CG;function kA(e){return Nr(e)&&Nr(e.error)?e.error.code:void 0}J.errorCodeOf=kA;function EG(e){if(Nr(e)&&Nr(e.error)&&Nr(e.error.innererror))return e.error.innererror.code}function AG(e,t,r){let n=[],i=kA(t);typeof i=="string"&&i.length>0&&n.push(is(i,80));let o=EG(t);typeof o=="string"&&o.length>0&&n.push(is(o,80));let a=n.length>0?` (${n.join("; ")})`:"";return(0,zl.attachCause)(new zl.SdkError(J.CONNECTIVITY_UNAUTHORIZED_CODE,`A connectivity request was refused with HTTP ${e}${a}: the token's audience, scopes, expiry, or access was rejected. Supply a valid token for this route, or fall back to pac.`),r)}J.connectivityUnauthorized=AG;J.CONNECTOR_PREFIX="/providers/Microsoft.PowerApps/apis/";var SG=/^[A-Za-z0-9_.-]{1,128}$/,NG=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]);function _G(e){if(typeof e=="string"){let r=e.slice(0,J.CONNECTOR_PREFIX.length).toLowerCase()===J.CONNECTOR_PREFIX.toLowerCase()?e.slice(J.CONNECTOR_PREFIX.length):e;if(SG.test(r)&&!/^\.{1,2}$/.test(r))return r}throw new zl.InvalidArgumentError(`connector must be a connector's short name ('shared_office365users') or its full API id ('${J.CONNECTOR_PREFIX}shared_office365users'); got ${typeof e=="string"?`'${is(e,80)}'`:ns(e)}.`)}J.connectorShortName=_G;function TG(e,t,r){let n=`Connection row ${t}`;if(!Nr(e))throw Yn(n,`it is ${ns(e)}, not an object`);let i=e.properties;if(!Nr(i))throw Yn(n,`its properties are ${ns(i)}, not an object`);let o=i.apiId;if(typeof o!="string"||o.slice(0,J.CONNECTOR_PREFIX.length).toLowerCase()!==J.CONNECTOR_PREFIX.toLowerCase())throw Yn(n,`its apiId is not '${J.CONNECTOR_PREFIX}<connector>'`);let a=o.slice(J.CONNECTOR_PREFIX.length);if(a===""||a.includes("/"))throw Yn(n,"its apiId names no single connector");if(NG.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw Yn(n,"it has no name");let l=i.environment,u=Nr(l)?l.name:void 0;if(typeof u!="string"||u.toLowerCase()!==r.toLowerCase())throw Yn(n,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw Yn(n,`its displayName is ${ns(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw Yn(n,`its statuses are ${ns(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let m=Nr(f)?f.status:void 0;if(typeof m!="string")throw Yn(n,"one of its statuses has no string status");return m})}}J.readConnection=TG;var RA="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'";async function DG(e){let t=(0,mG.ensureSuccess)(await e.get(RA),e.apiUrl(RA)).body,r=Nr(t)?t.Detail:void 0,n=Nr(r)?r.EnvironmentId:void 0;if(typeof n!="string"||n==="")throw new zl.SdkError(J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,"The environment of this org could not be verified: the org answered no environment id (RetrieveCurrentOrganization, Detail.EnvironmentId).");return n}J.readEnvironmentName=DG});var qA=v(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.ConnectivityApi=_r.CONNECTIVITY_UNAUTHORIZED_CODE=_r.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE=_r.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE=_r.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE=_r.CONNECTIVITY_NOT_CONFIGURED_CODE=void 0;var Yt=Q(),IG=fe(),dd=Wl(),Hl=ea(),Kl=ea();Object.defineProperty(_r,"CONNECTIVITY_NOT_CONFIGURED_CODE",{enumerable:!0,get:function(){return Kl.CONNECTIVITY_NOT_CONFIGURED_CODE}});Object.defineProperty(_r,"CONNECTIVITY_CLOUD_UNSUPPORTED_CODE",{enumerable:!0,get:function(){return Kl.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE}});Object.defineProperty(_r,"CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE",{enumerable:!0,get:function(){return Kl.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE}});Object.defineProperty(_r,"CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE",{enumerable:!0,get:function(){return Kl.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE}});Object.defineProperty(_r,"CONNECTIVITY_UNAUTHORIZED_CODE",{enumerable:!0,get:function(){return Kl.CONNECTIVITY_UNAUTHORIZED_CODE}});var $A="2016-11-01",OG="2021-04-01",PG="https://api.bap.microsoft.com",RG="https://test.api.bap.microsoft.com",LG=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,kG=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,xA="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'",Oi="/providers/Microsoft.PowerApps/apis/",$G=/^[A-Za-z0-9_.-]{1,128}$/,xG=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]),FG="ServiceDecommissioned";function gt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function po(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function Qn(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}function jl(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}function FA(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}function MG(e){return/^[a-z0-9][a-z0-9.-]*$/.test(e)&&(e==="api.powerapps.com"||e.endsWith(".api.powerapps.com"))}function ln(e,t){return new Yt.SdkError(dd.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}function cd(e){return new Yt.SdkError(Hl.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: ${e}. The Power Apps service was not asked about it.`)}function MA(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}function UA(e){if(typeof e=="string"&&e.length>0)return Qn(e,500);if(gt(e)){let t=gt(e.error)?e.error.message:void 0;for(let r of[t,e.Message,e.message])if(typeof r=="string")return Qn(r,500)}return"request failed"}function UG(e){return gt(e)&>(e.error)?e.error.code:void 0}function BA(e){if(typeof e=="string"){let r=e.slice(0,Oi.length).toLowerCase()===Oi.toLowerCase()?e.slice(Oi.length):e;if($G.test(r)&&!/^\.{1,2}$/.test(r))return r}throw new Yt.InvalidArgumentError(`connector must be a connector's short name ('shared_office365users') or its full API id ('${Oi}shared_office365users'); got ${typeof e=="string"?`'${Qn(e,80)}'`:po(e)}.`)}function BG(e,t,r){let n=`Connection row ${t}`;if(!gt(e))throw ln(n,`it is ${po(e)}, not an object`);let i=e.properties;if(!gt(i))throw ln(n,`its properties are ${po(i)}, not an object`);let o=i.apiId;if(typeof o!="string"||o.slice(0,Oi.length).toLowerCase()!==Oi.toLowerCase())throw ln(n,`its apiId is not '${Oi}<connector>'`);let a=o.slice(Oi.length);if(a===""||a.includes("/"))throw ln(n,"its apiId names no single connector");if(xG.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw ln(n,"it has no name");let l=i.environment,u=gt(l)?l.name:void 0;if(typeof u!="string"||u.toLowerCase()!==r.toLowerCase())throw ln(n,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw ln(n,`its displayName is ${po(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw ln(n,`its statuses are ${po(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let m=gt(f)?f.status:void 0;if(typeof m!="string")throw ln(n,"one of its statuses has no string status");return m})}}var $h=class{constructor(t,r,n){this.org=t,this.instanceUrl=r,this.service=n,this.swaggers=new Map}async listConnections(){let t=this.requireService(),r=await this.resolveEnvironment(t),n=[],i=new Set,o=`${r.origin}/providers/Microsoft.PowerApps/connections?api-version=${$A}&$filter=${MA(r.id)}`,a=await this.send(t,o,!0),s=1,l=0;for(;;){let u=`Page ${s} of the connections`,c=a.body,d=c?.value;if(!Array.isArray(d))throw ln(u,`its value is ${po(d)}, not an array`);for(let m of d){let p=BG(m,l,r.id);l+=1,p&&n.push(p)}let f=c?.nextLink;if(f==null)return n;if(typeof f!="string"||f.length===0)throw ln(u,`its nextLink is ${f===""?"an empty string":po(f)}, not a non-empty string`);if(i.has(f))throw new Yt.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${Qn(f)}'), which would loop indefinitely.`);i.add(f),this.assertSameOrigin(f,r.parsed),a=await this.send(t,f,!0),s+=1}}async listConnectorOperations(t){let r=this.requireService(),n=BA(t);return(0,dd.projectConnectorOperations)(await this.swagger(r,n))}async getConnectorOperationSchema(t,r){let n=this.requireService(),i=BA(t);if(typeof r!="string"||r==="")throw new Yt.InvalidArgumentError("operationId must be a non-empty string.");return(0,dd.projectConnectorOperationSchema)(await this.swagger(n,i),r)}requireService(){if(!this.service)throw new Yt.SdkError(Hl.CONNECTIVITY_NOT_CONFIGURED_CODE,"This SDK was created without a powerAppsServiceClient (MakerSdkOptions), so it cannot read connections or connectors: it needs an HttpClient that authenticates for https://service.powerapps.com/ and does not follow redirects. Nothing was requested.");return this.service}resolveEnvironment(t){if(!this.environment){let r=this.verifyEnvironment(t);this.environment=r,r.catch(()=>{this.environment===r&&(this.environment=void 0)})}return this.environment}async verifyEnvironment(t){let r=this.candidateBapOrigin(),n=await this.readEnvironmentId(),i=`${r}/providers/Microsoft.BusinessAppPlatform/environments/${encodeURIComponent(n)}?api-version=${OG}`,o=(await this.send(t,i,!1)).body,a=gt(o)?o.properties:void 0,s=gt(o)?o.name:void 0;if(typeof s!="string"||s.toLowerCase()!==n.toLowerCase())throw cd(`BAP's environment row is not the one named '${Qn(n,80)}' (its name)`);let l=gt(a)&>(a.linkedEnvironmentMetadata)?a.linkedEnvironmentMetadata.instanceUrl:void 0,u=typeof l=="string"?jl(l):void 0,c=jl(this.instanceUrl);if(!u||!c||!FA(u,c))throw cd("BAP's row is not linked to this org (its linkedEnvironmentMetadata.instanceUrl is another origin)");let d=gt(a)?a.runtimeEndpoints:void 0,f=gt(d)?d["microsoft.PowerApps"]:void 0,m=typeof f=="string"?jl(f):void 0;if(!m||m.protocol!=="https:"||!MG(m.host.toLowerCase()))throw cd("BAP's Power Apps runtime endpoint is not an https host of api.powerapps.com (runtimeEndpoints['microsoft.PowerApps'])");return{id:n,origin:m.origin.toLowerCase(),parsed:m}}candidateBapOrigin(){let t=jl(this.instanceUrl),r=t?t.host.toLowerCase():"",n=LG.exec(r);if(n&&n[1]!=="9")return PG;if(kG.test(r))return RG;throw new Yt.SdkError(Hl.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The org's host is not one of the clouds this reads in (${t?`'${Qn(t.host,80)}'`:`'${Qn(this.instanceUrl,80)}', which is not a URL`}): a Public org is <name>.crm[N].dynamics.com (N other than 9) and a Test org <name>.crmtest.dynamics.com. GCC (crm9), GCC High, DoD, China, ports and custom domains are not supported. Nothing was requested.`)}async readEnvironmentId(){let t=(0,IG.ensureSuccess)(await this.org.get(xA),this.org.apiUrl(xA)).body,r=gt(t)?t.Detail:void 0,n=gt(r)?r.EnvironmentId:void 0;if(typeof n!="string"||n==="")throw cd("the org answered no environment id (RetrieveCurrentOrganization, Detail.EnvironmentId)");return n}swagger(t,r){let n=r.toLowerCase(),i=this.swaggers.get(n);if(!i){let o=this.readSwagger(t,r);i=o,this.swaggers.set(n,o),o.catch(()=>{this.swaggers.get(n)===o&&this.swaggers.delete(n)})}return i}async readSwagger(t,r){let n=await this.resolveEnvironment(t),i=encodeURIComponent(r),o=`${n.origin}${Oi}${i}?api-version=${$A}&$filter=${MA(n.id)}`,a=(await this.send(t,o,!0)).body,s=gt(a)?a.properties:void 0,l=gt(s)?s.swagger:void 0;if(!gt(l))throw ln(`The connector '${Qn(r,80)}'`,`its properties.swagger is ${po(l)}, not an object`);return(0,dd.validateConnectorSwagger)(l),l}assertSameOrigin(t,r){let n=jl(t);if(!n)throw new Yt.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${Qn(t)}'`);if(!FA(n,r))throw new Yt.InvalidArgumentError(`Refusing to follow a cross-origin link ('${Qn(n.origin,120)}' is not the environment's Power Apps endpoint '${r.origin}'); server-driven pagination must stay on that origin.`)}async send(t,r,n){let i;try{i=await t.get(r)}catch(o){throw o instanceof Yt.ConnectionError&&typeof o.statusCode=="number"&&o.statusCode>0?this.mapNon2xx(r,o.statusCode,void 0,n,o):o instanceof Yt.SdkError?o:new Yt.ConnectionError(r,0,o instanceof Error?o.message:String(o),o)}if(!i||typeof i.status!="number")throw new Yt.ConnectionError(r,0,"the transport returned no HTTP response");if(i.status>=200&&i.status<300)return i;throw this.mapNon2xx(r,i.status,i.body,n)}mapNon2xx(t,r,n,i,o){let a=o??new Yt.ConnectionError(t,r,UA(n),n);return i&&r===410&&UG(n)===FG?(0,Yt.attachCause)(new Yt.SdkError(Hl.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE,`The Power Apps API this reads through is decommissioned for this environment: ${UA(n)} Fall back to pac, or to the Power Platform API when the host has a client for it; the SDK does not fall back.`),a):r===401||r===403?(0,Hl.connectivityUnauthorized)(r,n,a):a}};_r.ConnectivityApi=$h});var Bh=v(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.projectConnectorTableSchema=Be.projectConnectorTables=Be.tableSchemaSuffix=Be.tablesSuffix=Be.encodeTable=Be.encodeDataset=Be.checkTabularConnection=Be.runtimeAuthority=Be.tabularRevision=Be.checkTableSchemaArguments=Be.checkListTablesArguments=void 0;var ta=Q(),M=ea(),qG=/^[A-Za-z0-9_.-]{1,128}$/,ra=/^\.{1,2}$/,VG="shared_sharepointonline",GG=/^[0-9]{1,9}$/,WG=/^[A-Za-z0-9._~-]+$/,zG=/^\/apim\/([A-Za-z0-9._-]+)\/?$/,jG=/^\/connectors\/runtime\/invoke\/scalegroups\/([A-Za-z0-9._-]+)\/(scaleunits|shards)\/([A-Za-z0-9._-]+)\/apis\/([A-Za-z0-9._-]+)\/connections\/?$/,HG=/^[A-Za-z0-9._~!'()*-]$/,KG=/^[0-9A-Fa-f]{2}$/;function Pi(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Jl(e){return typeof e=="string"?`'${(0,M.bounded)(e,80)}'`:(0,M.kindOf)(e)}function xh(e,t){return new ta.SdkError(M.CONNECTOR_NOT_TABULAR_CODE,`The connector '${(0,M.bounded)(e,80)}' has no tables: ${t}.`)}function fd(e,t){return new ta.SdkError(M.CONNECTOR_RUNTIME_UNSUPPORTED_CODE,`The connector '${(0,M.bounded)(e,80)}' runs where this SDK does not send a token: ${t}. Nothing was sent to it.`)}function JG(e){if(typeof e=="string"&&qG.test(e)&&!ra.test(e))return e;throw new ta.InvalidArgumentError(`connectionId must be a connection's name (letters, digits, '_', '.', '-'; at most 128; not '.' or '..'); got ${Jl(e)}.`)}function YG(e){if(e!=null){if(typeof e=="string"&&e!==""&&e.split(",").find(r=>r===""||ra.test(r))===void 0)return e;throw new ta.InvalidArgumentError(`dataset must be a non-empty string (a SharePoint site URL, a SQL 'server,database', \u2026) none of whose ','-separated parts is empty, '.' or '..', or absent for a connector without datasets; got ${Jl(e)}.`)}}function QG(e){if(typeof e=="string"&&e!==""&&!ra.test(e))return e;throw new ta.InvalidArgumentError(`table must be a non-empty string other than '.' and '..'; got ${Jl(e)}.`)}function GA(e,t,r){return{short:(0,M.connectorShortName)(e),connectionId:JG(t),dataset:YG(r)}}Be.checkListTablesArguments=GA;function XG(e,t,r,n){return{...GA(e,t,r),table:QG(n)}}Be.checkTableSchemaArguments=XG;function ZG(e,t){let r=`The connector '${(0,M.bounded)(t,80)}'`,n=e.properties;if(!(0,M.isObject)(n))throw(0,M.unreadable)(r,`its properties are ${(0,M.kindOf)(n)}, not an object`);if(!Pi(n,"interfaces"))throw xh(t,"it declares no interfaces");let i=n.interfaces;if(!(0,M.isObject)(i))throw(0,M.unreadable)(r,`its properties.interfaces are ${(0,M.kindOf)(i)}, not an object`);if(!Pi(i,"CDPTabular1"))throw xh(t,"it declares no CDPTabular1 interface");let o=i.CDPTabular1;if(!(0,M.isObject)(o))throw(0,M.unreadable)(r,`its CDPTabular1 interface is ${(0,M.kindOf)(o)}, not an object`);let a=o.revisions;if(!(0,M.isObject)(a))throw(0,M.unreadable)(r,`its CDPTabular1 revisions are ${(0,M.kindOf)(a)}, not an object`);let s,l=new Map;for(let u of Object.keys(a)){let c=a[u],d=`its CDPTabular1 revision '${(0,M.bounded)(u,40)}'`;if(!(0,M.isObject)(c)||typeof c.status!="string")throw(0,M.unreadable)(r,`${d} is not an object with a string status`);if(c.status!=="Production")continue;if(!GG.test(u))throw(0,M.unreadable)(r,`${d} is a Production revision whose key is not a decimal integer of 1\u20139 digits`);let f=e8(c.baseUrl);if(f===void 0)throw(0,M.unreadable)(r,`${d} has a baseUrl that is not '/' or '/'-separated [A-Za-z0-9._~-] segments`);let m=Number(u),p=l.get(m);if(p!==void 0)throw(0,M.unreadable)(r,`its Production revisions '${p}' and '${(0,M.bounded)(u,40)}' have the same number`);l.set(m,u),(!s||m>s.revisionNumber)&&(s={revisionNumber:m,revision:f})}if(!s)throw xh(t,"its CDPTabular1 interface has no Production revision");return s.revision}Be.tabularRevision=ZG;function e8(e){if(typeof e!="string")return;let t=e.replace(/^\/+/,"").replace(/\/+$/,"");return t===""?"":t.split("/").every(i=>WG.test(i)&&!ra.test(i))?t:void 0}function t8(e,t,r){let n=(0,M.isObject)(e.properties)?e.properties:void 0,i=n?n.primaryRuntimeUrl:void 0;if(typeof i!="string")throw fd(r,`its primaryRuntimeUrl is ${(0,M.kindOf)(i)}, not a string`);let o=t.cloud==="Test",a=(o?`https://${t.name}.tip2-001.tip2.azure-apihub.net`:t.origin).toLowerCase(),s=(0,M.parseUrl)(i);if(!s||s.protocol!=="https:"||s.origin.toLowerCase()!==a)throw fd(r,`its runtime ('${(0,M.bounded)(i,120)}') is not ${o?"this environment's measured API Hub host (<environment name>.tip2-001.tip2.azure-apihub.net)":"under this environment's own Power Platform API origin"} over https`);let l=i.slice(0,a.length).toLowerCase()===a?i.slice(a.length):void 0;if(o){let c=l===void 0?null:zG.exec(l);if(!c||ra.test(c[1]))throw fd(r,`its runtime ('${(0,M.bounded)(i,120)}') is not <host>/apim/<connector>`);return{transport:"invoke",origin:a,path:`/apim/${c[1]}`}}let u=l===void 0?null:jG.exec(l);if(!u||[u[1],u[3],u[4]].some(c=>ra.test(c)))throw fd(r,`its runtime ('${(0,M.bounded)(i,120)}') is not <origin>/connectors/runtime/invoke/scalegroups/<group>/(scaleunits|shards)/<unit>/apis/<api>/connections`);return{transport:"direct",origin:a,path:`/connectors/runtime/invoke/scalegroups/${u[1]}/${u[2]}/${u[3]}/apis/${u[4]}/connections`}}Be.runtimeAuthority=t8;function r8(e,t,r,n){let i=`The connection '${(0,M.bounded)(t,128)}'`;if(!(0,M.isObject)(e))throw(0,M.unreadable)(i,`it is ${(0,M.kindOf)(e)}, not an object`);if(e.name!==t)throw(0,M.unreadable)(i,`its name is ${Jl(e.name)}, not the requested connection`);let o=e.properties;if(!(0,M.isObject)(o))throw(0,M.unreadable)(i,`its properties are ${(0,M.kindOf)(o)}, not an object`);let a=o.apiId;if(typeof a!="string"||a.toLowerCase()!==`${M.CONNECTOR_PREFIX}${r}`.toLowerCase())throw(0,M.unreadable)(i,`its apiId is ${Jl(a)}, not the connector '${(0,M.bounded)(r,80)}'`);let s=o.environment,l=(0,M.isObject)(s)?s.name:void 0;if(typeof l!="string"||l.toLowerCase()!==n.toLowerCase())throw(0,M.unreadable)(i,"it is not a connection of this environment (properties.environment.name)");return t}Be.checkTabularConnection=r8;function VA(e){return encodeURIComponent(e).replace(/[!'()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`)}function n8(e){if(e==="")return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="%"){if(!KG.test(e.slice(t+1,t+3)))return!1;t+=2}else if(!HG.test(e[t]))return!1;return!0}function WA(e,t){let r,n,i;try{r=VA(e),n=VA(r),i=decodeURIComponent(n)}catch{throw new ta.InvalidArgumentError(`${t} is not well-formed Unicode (it has a lone surrogate), so it cannot be sent.`)}if(!n8(n)||ra.test(n)||i!==r)throw new ta.InvalidArgumentError(`${t} cannot be sent as one path segment.`);return n}function Uh(e){return e.split(",").map((t,r)=>WA(t,`dataset part ${r}`)).join(",")}Be.encodeDataset=Uh;function zA(e){return WA(e,"table")}Be.encodeTable=zA;function i8(e,t){if(t===void 0)return"/tables";let r=e.toLowerCase()===VG?"allTables":"tables";return`/datasets/${Uh(t)}/${r}`}Be.tablesSuffix=i8;function o8(e,t){return`/$metadata.json${e===void 0?"":`/datasets/${Uh(e)}`}/tables/${zA(t)}`}Be.tableSchemaSuffix=o8;function os(e,t){let r=t.toLowerCase();for(let n of Object.keys(e))if(n.toLowerCase()===r)return{found:!0,value:e[n]};return{found:!1}}function a8(e){let t="The table list",r;if(Array.isArray(e))r=e;else if((0,M.isObject)(e)){for(let o of["nextLink","@odata.nextLink"])if(os(e,o).found)throw(0,M.unreadable)(t,`it carries a ${o} \u2014 a paged answer is refused, never read as a partial list`);let n=os(e,"value"),i=n.found?n:os(e,"tables");if(!i.found)throw(0,M.unreadable)(t,"it is an object with neither a value nor a tables member");if(!Array.isArray(i.value))throw(0,M.unreadable)(t,`its ${n.found?"value":"tables"} is ${(0,M.kindOf)(i.value)}, not an array`);r=i.value}else throw(0,M.unreadable)(t,`it is ${(0,M.kindOf)(e)}, not an array or an object`);return{tables:r.map((n,i)=>s8(n,i))}}Be.projectConnectorTables=a8;function s8(e,t){let r=`Table row ${t}`;if(!(0,M.isObject)(e))throw(0,M.unreadable)(r,`it is ${(0,M.kindOf)(e)}, not an object`);let n=os(e,"name");if(!n.found||typeof n.value!="string"||n.value==="")throw(0,M.unreadable)(r,"it has no non-empty string name");let i=os(e,"displayName");if(i.found&&typeof i.value!="string")throw(0,M.unreadable)(r,`its displayName is ${(0,M.kindOf)(i.value)}, not a string`);let o=os(e,"id");if(o.found&&(typeof o.value!="string"||o.value===""))throw(0,M.unreadable)(r,`its id is ${o.value===""?"an empty string":(0,M.kindOf)(o.value)}, not a non-empty string`);return{name:n.value,displayName:i.found?i.value:null,id:o.found?o.value:n.value}}function Fh(e,t,r){if(!Pi(e,t))return;let n=e[t];if(!(0,M.isObject)(n))throw(0,M.unreadable)("The table schema",`its ${r} is ${(0,M.kindOf)(n)}, not an object`);return n}function Mh(e,t,r){if(!Pi(e,t))return;let n=e[t];if(typeof n!="string")throw(0,M.unreadable)(r,`its ${t} is ${(0,M.kindOf)(n)}, not a string`);return n}function l8(e,t){var r,n;if(Pi(e,"$ref"))throw(0,M.unreadable)(t,"it is a $ref, whose type is not guessed");let i=Mh(e,"type",t),o=Mh(e,"format",t),a=(r=i??o)!==null&&r!==void 0?r:"object";if(!Pi(e,"items"))return a;let s=e.items;if(!(0,M.isObject)(s))throw(0,M.unreadable)(t,`its items are ${(0,M.kindOf)(s)}, not an object`);if(Pi(s,"$ref"))throw(0,M.unreadable)(t,"its items are a $ref, whose type is not guessed");return`${a}<${(n=Mh(s,"type",`${t} items`))!==null&&n!==void 0?n:"object"}>`}function u8(e,t){let r="The table schema";if(!(0,M.isObject)(e))throw(0,M.unreadable)(r,`it is ${(0,M.kindOf)(e)}, not an object`);let n=Fh(e,"items","items"),i=Fh(e,"schema","schema"),o=i?Fh(i,"items","schema.items"):void 0,a=[[e,"the answer"],[n,"items"],[i,"schema"],[o,"schema.items"]],s=new Set;for(let[c,d]of a)if(c&&Pi(c,"required")){let f=c.required;if(!Array.isArray(f))throw(0,M.unreadable)(r,`the required of ${d} is ${(0,M.kindOf)(f)}, not an array`);f.forEach(m=>{if(typeof m!="string")throw(0,M.unreadable)(r,`the required of ${d} has an entry that is ${(0,M.kindOf)(m)}, not a string`);s.add(m.toLowerCase())})}let l;for(let[c,d]of a)if(c&&Pi(c,"properties")){if(!(0,M.isObject)(c.properties))throw(0,M.unreadable)(r,`the properties of ${d} are ${(0,M.kindOf)(c.properties)}, not an object`);l=c.properties;break}if(!l)throw(0,M.unreadable)(r,"it has no properties, items.properties, schema.properties or schema.items.properties");let u=Object.keys(l).map(c=>{let d=`Column '${(0,M.bounded)(c,80)}'`,f=l[c];if(!(0,M.isObject)(f))throw(0,M.unreadable)(d,`it is ${(0,M.kindOf)(f)}, not an object`);return{name:c,type:l8(f,d),required:s.has(c.toLowerCase())}});return{table:t,columns:u}}Be.projectConnectorTableSchema=u8});var jA=v(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});pd.PowerPlatformApiDiscovery=void 0;var qh=class{constructor(t){this.clusterCategory=t}getTokenAudience(){return`https://${this._getEnvironmentApiHostNameSuffix()}`}getTokenEndpointHost(){return this._getEnvironmentApiHostNameSuffix()}getTenantEndpoint(t){return this._generatePowerPlatformApiDomain(t,"tenant")}getTenantIslandClusterEndpoint(t){return this._generatePowerPlatformApiDomain(t,"tenant","il-")}getEnvironmentEndpoint(t){return this._generatePowerPlatformApiDomain(t,"environment")}_generatePowerPlatformApiDomain(t,r,n=""){if(!/^[a-zA-Z0-9\-]+$/g.test(t))throw new Error(`Cannot generate Power Platform API endpoint because the ${r} identifier contains invalid host name characters, only alphanumeric and dash characters are expected: ${t}`);let i=this._getHexApiSuffixLength(),o=t.toLowerCase().replace(/-/g,"");if(i>=o.length)throw new Error(`Cannot generate Power Platform API endpoint because the normalized ${r} identifier must be at least ${i+1} characters in length: ${o}`);let a=o.substring(o.length-i),s=o.substring(0,o.length-i),l=this._getEnvironmentApiHostNameSuffix();return`${n}${s}.${a}.${r}.${l}`}_getHexApiSuffixLength(){switch(this.clusterCategory){case"firstrelease":case"prod":return 2;default:return 1}}_getEnvironmentApiHostNameSuffix(){switch(this.clusterCategory){case"local":return"api.powerplatform.localhost";case"dev":return"api.dev.powerplatform.com";case"test":return"api.test.powerplatform.com";case"preprod":return"api.preprod.powerplatform.com";case"firstrelease":case"prod":return"api.powerplatform.com";case"gov":return"api.gov.powerplatform.microsoft.us";case"high":return"api.high.powerplatform.microsoft.us";case"dod":return"api.appsplatform.us";case"mooncake":return"api.powerplatform.partner.microsoftonline.cn";case"ex":return"api.powerplatform.eaglex.ic.gov";case"rx":return"api.powerplatform.microsoft.scloud";default:throw new Error(`Invalid ClusterCategory value: ${this.clusterCategory}`)}}};pd.PowerPlatformApiDiscovery=qh});var HA=v(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});md.PowerPlatformApiDiscovery=void 0;var c8=jA();Object.defineProperty(md,"PowerPlatformApiDiscovery",{enumerable:!0,get:function(){return c8.PowerPlatformApiDiscovery}})});var QA=v(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.platformTokenAudience=mo.platformEnvironment=mo.platformClusterOf=void 0;var KA=HA(),JA=Q(),YA=ea(),d8=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,f8=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,p8=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,m8=/^default-/i;function Vh(e,t=80){return e.length>t?`${e.slice(0,t)}\u2026`:e}function h8(e){try{return new URL(e).host.toLowerCase()}catch{return}}function g8(e){let t=h8(e);if(t){if(f8.test(t))return{cloud:"Test",category:"test"};let r=d8.exec(t);if(r&&r[1]!=="9")return{cloud:"Public",category:"prod"}}throw new JA.SdkError(YA.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The Power Platform API route is built for the Test and Public clouds; this org (${t?`'${Vh(t)}'`:`'${Vh(e)}', which is not a URL`}) is another cloud. A Public org is <name>.crm[N].dynamics.com (N other than 9) and a Test org <name>.crmtest.dynamics.com. GCC (crm9), GCC High, DoD, China, ports and custom domains are pending or out of scope. Nothing was requested.`)}mo.platformClusterOf=g8;function y8(e,t){let r=m8.test(e)?e.slice(8):e;if(!p8.test(r))throw new JA.SdkError(YA.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: its name ('${Vh(e)}') is neither a GUID nor 'Default-<GUID>', the forms this route is measured for. The Power Platform API was not asked about it.`);return{origin:`https://${new KA.PowerPlatformApiDiscovery(t).getEnvironmentEndpoint(e)}`,guid:r.toLowerCase()}}mo.platformEnvironment=y8;function b8(e){return new KA.PowerPlatformApiDiscovery(e).getTokenAudience()}mo.platformTokenAudience=b8});var ZA=v(as=>{"use strict";Object.defineProperty(as,"__esModule",{value:!0});as.PlatformConnectivityApi=as.assertTabularCloud=void 0;var Dn=Q(),Gh=Wl(),pe=ea(),XA=QA(),Ri=Bh(),Wh="1";function zh(e){let t=(0,pe.connectivityCloudOf)(e);if(t!=="Test"&&t!=="Public")throw new Dn.SdkError(pe.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,"Connector tables are read in the Test and Public clouds; this org's cloud is neither (GCC, GCC High and DoD are pending). Nothing was requested.")}as.assertTabularCloud=zh;var jh=class{constructor(t,r,n,i){this.org=t,this.instanceUrl=r,this.client=n,this.runtime=i,this.records=new Map,this.swaggers=new Map}async listConnections(){let t=await this.resolveEnvironment(),r=[],n=new Set,i=await this.send(this.client,"GET",`${t.origin}/connectivity/connections?api-version=${Wh}`,[401,403]),o=1,a=0;for(;;){let s=`Page ${o} of the connections`,l=i.body,u=l?.value;if(!Array.isArray(u))throw(0,pe.unreadable)(s,`its value is ${(0,pe.kindOf)(u)}, not an array`);for(let d of u){let f=(0,pe.readConnection)(d,a,t.name);a+=1,f&&r.push(f)}let c=l?.nextLink;if(c==null)return r;if(typeof c!="string"||c.length===0)throw(0,pe.unreadable)(s,`its nextLink is ${c===""?"an empty string":(0,pe.kindOf)(c)}, not a non-empty string`);if(n.has(c))throw new Dn.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${(0,pe.bounded)(c)}'), which would loop indefinitely.`);n.add(c),this.assertSameOrigin(c,t.parsed),i=await this.send(this.client,"GET",c,[401,403]),o+=1}}async listConnectorOperations(t){let r=(0,pe.connectorShortName)(t);return(0,Gh.projectConnectorOperations)(await this.swagger(r))}async getConnectorOperationSchema(t,r){let n=(0,pe.connectorShortName)(t);if(typeof r!="string"||r==="")throw new Dn.InvalidArgumentError("operationId must be a non-empty string.");return(0,Gh.projectConnectorOperationSchema)(await this.swagger(n),r)}async listConnectorTables(t,r,n){zh(this.instanceUrl);let i=(0,Ri.checkListTablesArguments)(t,r,n),o=(0,Ri.tablesSuffix)(i.short,i.dataset);return(0,Ri.projectConnectorTables)(await this.invokeTabular(i,o))}async getConnectorTableSchema(t,r,n,i){zh(this.instanceUrl);let o=(0,Ri.checkTableSchemaArguments)(t,r,n,i),a=(0,Ri.tableSchemaSuffix)(o.dataset,o.table);return(0,Ri.projectConnectorTableSchema)(await this.invokeTabular(o,a),o.table)}async invokeTabular(t,r){let n=this.requireRuntime(),i=await this.resolveEnvironment(),o=await this.record(t.short),a=(0,Ri.tabularRevision)(o,t.short),s=(0,Ri.runtimeAuthority)(o,{cloud:i.cloud,name:i.name,origin:i.origin},t.short),l=`${i.origin}/connectivity/connectors/${encodeURIComponent(t.short)}/connections/${encodeURIComponent(t.connectionId)}?$filter=${(0,pe.environmentFilter)(i.name)}&api-version=${Wh}`,u=(await this.send(this.client,"GET",l,[401,403])).body,c=(0,Ri.checkTabularConnection)(u,t.connectionId,t.short,i.name),d=`${s.path}/${c}${a===""?"":`/${a}`}${r}`;return(s.transport==="invoke"?await this.send(n,"POST",`${s.origin}/invoke`,[401],{"X-Ms-Request-Url":d,"X-Ms-Request-Method":"GET"}):await this.send(n,"GET",`${s.origin}${d}`,[401])).body}requireRuntime(){if(!this.runtime)throw new Dn.SdkError(pe.CONNECTIVITY_NOT_CONFIGURED_CODE,"This SDK was created without a connectorRuntimeClient (MakerSdkOptions), so it cannot read connector tables: it needs an HttpClient that authenticates for API Hub (https://apihub.azure.com) and does not follow redirects. Nothing was requested.");return this.runtime}resolveEnvironment(){if(!this.environment){let t=this.readEnvironment();this.environment=t,t.catch(()=>{this.environment===t&&(this.environment=void 0)})}return this.environment}async readEnvironment(){let{cloud:t,category:r}=(0,XA.platformClusterOf)(this.instanceUrl),n=await(0,pe.readEnvironmentName)(this.org),{origin:i,guid:o}=(0,XA.platformEnvironment)(n,r),a=(0,pe.parseUrl)(i);if(!a)throw(0,pe.unreadable)("The Power Platform API origin",`'${(0,pe.bounded)(i)}' is not a URL`);return{cloud:t,origin:i,parsed:a,name:n,guid:o}}cached(t,r,n){let i=t.get(r);if(!i){let o=n();i=o,t.set(r,o),o.catch(()=>{t.get(r)===o&&t.delete(r)})}return i}record(t){return this.cached(this.records,t.toLowerCase(),()=>this.readRecord(t))}async readRecord(t){let r=await this.resolveEnvironment(),n=`${r.origin}/connectivity/connectors/${encodeURIComponent(t)}?$filter=${(0,pe.environmentFilter)(r.name)}&api-version=${Wh}`,i=(await this.send(this.client,"GET",n,[401,403])).body,o=(0,pe.isObject)(i)?i.name:void 0;if(!(0,pe.isObject)(i)||typeof o!="string"||o.toLowerCase()!==t.toLowerCase())throw(0,pe.unreadable)(`The connector '${(0,pe.bounded)(t,80)}'`,`the record's name is ${typeof o=="string"?`'${(0,pe.bounded)(o,80)}'`:(0,pe.kindOf)(o)}, not the requested connector`);return i}swagger(t){return this.cached(this.swaggers,t.toLowerCase(),async()=>{let n=(await this.record(t)).properties,i=(0,pe.isObject)(n)?n.swagger:void 0;if(!(0,pe.isObject)(i))throw(0,pe.unreadable)(`The connector '${(0,pe.bounded)(t,80)}'`,`its properties.swagger is ${(0,pe.kindOf)(i)}, not an object`);return(0,Gh.validateConnectorSwagger)(i),i})}assertSameOrigin(t,r){let n=(0,pe.parseUrl)(t);if(!n)throw new Dn.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${(0,pe.bounded)(t)}'`);if(!(0,pe.sameOrigin)(n,r))throw new Dn.InvalidArgumentError(`Refusing to follow a cross-origin link ('${(0,pe.bounded)(n.origin,120)}' is not the environment's Power Platform API origin '${r.origin}'); server-driven pagination must stay on that origin.`)}async send(t,r,n,i,o){let a;try{a=r==="GET"?await t.get(n):await t.post(n,void 0,{headers:o})}catch(s){throw s instanceof Dn.ConnectionError&&typeof s.statusCode=="number"&&s.statusCode>0?this.non2xx(n,s.statusCode,void 0,i,s):s instanceof Dn.SdkError?s:new Dn.ConnectionError(n,0,s instanceof Error?s.message:String(s),s)}if(!a||typeof a.status!="number")throw new Dn.ConnectionError(n,0,"the transport returned no HTTP response");if(a.status>=200&&a.status<300)return a;throw this.non2xx(n,a.status,a.body,i)}non2xx(t,r,n,i,o){let a=o??new Dn.ConnectionError(t,r,(0,pe.messageOf)(n),n);return i.includes(r)?(0,pe.connectivityUnauthorized)(r,n,a):a}};as.PlatformConnectivityApi=jh});var tS=v(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});gd.ConnectivityRouter=void 0;var Hh=Q(),v8=qA(),hd=ea(),eS=Bh(),Kh=ZA(),Jh=class{constructor(t,r,n){this.org=t,this.instanceUrl=r,this.clients=n}async listConnections(){return this.route().listConnections()}async listConnectorOperations(t){return this.route().listConnectorOperations(t)}async getConnectorOperationSchema(t,r){return this.route().getConnectorOperationSchema(t,r)}async listConnectorTables(t,r,n){return(0,Kh.assertTabularCloud)(this.instanceUrl),(0,eS.checkListTablesArguments)(t,r,n),this.tabularRoute().listConnectorTables(t,r,n)}async getConnectorTableSchema(t,r,n,i){return(0,Kh.assertTabularCloud)(this.instanceUrl),(0,eS.checkTableSchemaArguments)(t,r,n,i),this.tabularRoute().getConnectorTableSchema(t,r,n,i)}route(){return this.delegate||(this.delegate=this.select()),this.delegate}platformRoute(t){return this.platform||(this.platform=new Kh.PlatformConnectivityApi(this.org,this.instanceUrl,t,this.clients.connectorRuntimeClient)),this.platform}tabularRoute(){let{powerPlatformApiClient:t,connectorRuntimeClient:r}=this.clients,n=[t?void 0:"powerPlatformApiClient (the Power Platform API)",r?void 0:"connectorRuntimeClient (API Hub, https://apihub.azure.com)"].filter(i=>i!==void 0);if(n.length>0||!t)throw new Hh.SdkError(hd.CONNECTIVITY_NOT_CONFIGURED_CODE,`Connector tables are read through the Power Platform API and the connector runtime: this SDK was created without MakerSdkOptions.${n.join(" or MakerSdkOptions.")}, an HttpClient that does not follow redirects. Nothing was requested.`);return this.platformRoute(t)}select(){let t=(0,hd.connectivityCloudOf)(this.instanceUrl),{powerAppsServiceClient:r,powerPlatformApiClient:n}=this.clients;if(t==="Unsupported")throw new Hh.SdkError(hd.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,"This org's cloud has no connection/connector route: the Test and Public clouds are served (through the Power Platform API, or the classic route for Public); GCC, GCC High and DoD are pending. Nothing was requested.");if(n)return this.platformRoute(n);if(t==="Public"&&r)return new v8.ConnectivityApi(this.org,this.instanceUrl,r);throw new Hh.SdkError(hd.CONNECTIVITY_NOT_CONFIGURED_CODE,t==="Test"?"This org is in the Test cloud, whose connection and connector reads go through the Power Platform API: supply MakerSdkOptions.powerPlatformApiClient (an HttpClient that authenticates for the Power Platform API and does not follow redirects). Nothing was requested.":"This org is in the Public cloud: supply MakerSdkOptions.powerPlatformApiClient (the Power Platform API route) or powerAppsServiceClient (the classic route). Neither was given, so nothing was requested.")}};gd.ConnectivityRouter=Jh});var ss=v(Li=>{"use strict";function w8(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 Qh(e,t){return t===void 0&&(t=Object),t&&typeof t.freeze=="function"?t.freeze(e):e}function C8(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 rS=Qh({HTML:"text/html",isHTML:function(e){return e===rS.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),nS=Qh({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(e){return e===nS.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"}),yd=/[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]/,Yh=new RegExp("[\\-\\.0-9"+yd.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),E8=new RegExp("^"+yd.source+Yh.source+"*(?::"+yd.source+Yh.source+"*)?$");Li.assign=C8;Li.find=w8;Li.freeze=Qh;Li.MIME_TYPE=rS;Li.NAMESPACE=nS;Li.nameStartChar=yd;Li.nameChar=Yh;Li.tagNamePattern=E8});var ug=v(Fi=>{var Xh=ss(),Xn=Xh.find,Ql=Xh.NAMESPACE,ls=Xh.tagNamePattern;function A8(e){return e!==""}function S8(e){return e?e.split(/[\t\n\f\r ]+/).filter(A8):[]}function N8(e,t){return e.hasOwnProperty(t)||(e[t]=!0),e}function iS(e){if(!e)return[];var t=S8(e);return Object.keys(t.reduce(N8,{}))}function _8(e){return function(t){return e&&e.indexOf(t)!==-1}}function Zl(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function Dr(e,t){var r=e.prototype;if(!(r instanceof t)){let i=function(){};var n=i;i.prototype=t.prototype,i=new i,Zl(r,i),e.prototype=r=i}r.constructor!=e&&(typeof e!="function"&&console.error("unknown Class:"+e),r.constructor=e)}var Ir={},un=Ir.ELEMENT_NODE=1,us=Ir.ATTRIBUTE_NODE=2,Yl=Ir.TEXT_NODE=3,fS=Ir.CDATA_SECTION_NODE=4,pS=Ir.ENTITY_REFERENCE_NODE=5,T8=Ir.ENTITY_NODE=6,Zh=Ir.PROCESSING_INSTRUCTION_NODE=7,eg=Ir.COMMENT_NODE=8,mS=Ir.DOCUMENT_NODE=9,hS=Ir.DOCUMENT_TYPE_NODE=10,ki=Ir.DOCUMENT_FRAGMENT_NODE=11,D8=Ir.NOTATION_NODE=12,Qt={},Ot={},vce=Qt.INDEX_SIZE_ERR=(Ot[1]="Index size error",1),wce=Qt.DOMSTRING_SIZE_ERR=(Ot[2]="DOMString size error",2),Tr=Qt.HIERARCHY_REQUEST_ERR=(Ot[3]="Hierarchy request error",3),Cce=Qt.WRONG_DOCUMENT_ERR=(Ot[4]="Wrong document",4),oS=Qt.INVALID_CHARACTER_ERR=(Ot[5]="Invalid character",5),Ece=Qt.NO_DATA_ALLOWED_ERR=(Ot[6]="No data allowed",6),Ace=Qt.NO_MODIFICATION_ALLOWED_ERR=(Ot[7]="No modification allowed",7),gS=Qt.NOT_FOUND_ERR=(Ot[8]="Not found",8),Sce=Qt.NOT_SUPPORTED_ERR=(Ot[9]="Not supported",9),aS=Qt.INUSE_ATTRIBUTE_ERR=(Ot[10]="Attribute in use",10),In=Qt.INVALID_STATE_ERR=(Ot[11]="Invalid state",11),Nce=Qt.SYNTAX_ERR=(Ot[12]="Syntax error",12),_ce=Qt.INVALID_MODIFICATION_ERR=(Ot[13]="Invalid modification",13),Tce=Qt.NAMESPACE_ERR=(Ot[14]="Invalid namespace",14),Dce=Qt.INVALID_ACCESS_ERR=(Ot[15]="Invalid access",15);function me(e,t){if(t instanceof Error)var r=t;else r=this,Error.call(this,Ot[e]),this.message=Ot[e],Error.captureStackTrace&&Error.captureStackTrace(this,me);return r.code=e,t&&(this.message=this.message+": "+t),r}me.prototype=Error.prototype;Zl(Qt,me);function $i(){}$i.prototype={length:0,item:function(e){return e>=0&&e<this.length?this[e]:null},toString:function(e,t,r){for(var n=!!r&&!!r.requireWellFormed,i=[],o=0;o<this.length;o++)lg(this[o],i,e,t,null,n);return i.join("")},filter:function(e){return Array.prototype.filter.call(this,e)},indexOf:function(e){return Array.prototype.indexOf.call(this,e)}};function cs(e,t){this._node=e,this._refresh=t,tg(this)}function tg(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!==t){var r=e._refresh(e._node);if(IS(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];Zl(r,e),e._inc=t}}cs.prototype.item=function(e){return tg(this),this[e]||null};Dr(cs,$i);function vd(){this._nameIndex=Object.create(null)}function yS(e,t){for(var r=e.length;r--;)if(e[r]===t)return r}function I8(e,t){e._nameIndex[t.nodeName]=t}function bS(e,t){e._nameIndex[t.nodeName]===t&&delete e._nameIndex[t.nodeName]}function sS(e,t,r,n){if(n?(t[yS(t,n)]=r,bS(t,n)):t[t.length++]=r,I8(t,r),e){r.ownerElement=e;var i=e.ownerDocument;i&&(n&&CS(i,e,n),O8(i,e,r))}}function lS(e,t,r){var n=yS(t,r);if(n>=0){for(var i=t.length-1;n<i;)t[n]=t[++n];if(t.length=i,bS(t,r),e){var o=e.ownerDocument;o&&(CS(o,e,r),r.ownerElement=null)}}else throw new me(gS,new Error(e.tagName+"@"+r))}vd.prototype={length:0,item:$i.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 me(aS);var r=this._nameIndex[e.nodeName];return sS(this._ownerElement,this,e,r),r},setNamedItemNS:function(e){var t=e.ownerElement,r;if(t&&t!=this._ownerElement)throw new me(aS);return r=this.getNamedItemNS(e.namespaceURI,e.localName),sS(this._ownerElement,this,e,r),r},removeNamedItem:function(e){var t=this.getNamedItem(e);return lS(this._ownerElement,this,t),t},removeNamedItemNS:function(e,t){var r=this.getNamedItemNS(e,t);return lS(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 vS(){}vS.prototype={hasFeature:function(e,t){return!0},createDocument:function(e,t,r){var n=new eu;if(n.implementation=this,n.childNodes=new $i,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 Sd;return n.name=e,n.nodeName=e,n.publicId=t||"",n.systemId=r||"",n}};function De(){}De.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 Cd(this,e,t)},replaceChild:function(e,t){Cd(this,e,t,AS),t&&this.removeChild(t)},removeChild:function(e){return ES(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return DS(this.ownerDocument||this,this,e)},normalize:function(){It(this,null,{enter:function(e){for(var t=e.firstChild;t;){var r=t.nextSibling;if(r!==null&&r.nodeType===Yl&&t.nodeType===Yl){for(var n=[],i=r;i!==null&&i.nodeType===Yl;)n.push(i.data),i=i.nextSibling;for(var o=t.nextSibling;o!==i;){var a=o.nextSibling;o.parentNode=null,o.previousSibling=null,o.nextSibling=null,o=a}t.nextSibling=i,i!==null?i.previousSibling=t:e.lastChild=t,t.appendData(n.join("")),Ad(e.ownerDocument,e),t=i}else t=r}return!0}})},isSupported:function(e,t){return this.ownerDocument.implementation.hasFeature(e,t)},hasAttributes:function(){return this.attributes.length>0},lookupPrefix:function(e){for(var t=this;t;){var r=t._nsMap;if(r){for(var n in r)if(Object.prototype.hasOwnProperty.call(r,n)&&r[n]===e)return n}t=t.nodeType==us?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==us?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){var t=this.lookupPrefix(e);return t==null}};function wS(e){return e=="<"&&"<"||e==">"&&">"||e=="&"&&"&"||e=='"'&&"""||"&#"+e.charCodeAt()+";"}Zl(Ir,De);Zl(Ir,De.prototype);function wd(e,t){return It(e,null,{enter:function(r){return t(r)?It.STOP:!0}})===It.STOP}function It(e,t,r){for(var n=[{node:e,context:t,phase:It.ENTER}];n.length>0;){var i=n.pop();if(i.phase===It.ENTER){var o=r.enter(i.node,i.context);if(o===It.STOP)return It.STOP;if(n.push({node:i.node,context:o,phase:It.EXIT}),o==null)continue;for(var a=i.node.lastChild;a;)n.push({node:a,context:o,phase:It.ENTER}),a=a.previousSibling}else r.exit&&r.exit(i.node,i.context)}}It.STOP=Symbol("walkDOM.STOP");It.ENTER=0;It.EXIT=1;function eu(){this.ownerDocument=this}function O8(e,t,r){e&&e._inc++;var n=r.namespaceURI;n===Ql.XMLNS&&(t._nsMap[r.prefix?r.localName:""]=r.value)}function CS(e,t,r,n){e&&e._inc++;var i=r.namespaceURI;i===Ql.XMLNS&&delete t._nsMap[r.prefix?r.localName:""]}function Ad(e,t,r){if(e&&e._inc){e._inc++;var n=t.childNodes;if(r)n[n.length++]=r;else{for(var i=t.firstChild,o=0;i;)n[o++]=i,i=i.nextSibling;n.length=o,delete n[n.length]}}}function ES(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,Ad(e.ownerDocument,e),t}function P8(e){return e&&(e.nodeType===De.DOCUMENT_NODE||e.nodeType===De.DOCUMENT_FRAGMENT_NODE||e.nodeType===De.ELEMENT_NODE)}function R8(e){return e&&(Zn(e)||rg(e)||xi(e)||e.nodeType===De.DOCUMENT_FRAGMENT_NODE||e.nodeType===De.COMMENT_NODE||e.nodeType===De.PROCESSING_INSTRUCTION_NODE)}function xi(e){return e&&e.nodeType===De.DOCUMENT_TYPE_NODE}function Zn(e){return e&&e.nodeType===De.ELEMENT_NODE}function rg(e){return e&&e.nodeType===De.TEXT_NODE}function uS(e,t){var r=e.childNodes||[];if(Xn(r,Zn)||xi(t))return!1;var n=Xn(r,xi);return!(t&&n&&r.indexOf(n)>r.indexOf(t))}function cS(e,t){var r=e.childNodes||[];function n(o){return Zn(o)&&o!==t}if(Xn(r,n))return!1;var i=Xn(r,xi);return!(t&&i&&r.indexOf(i)>r.indexOf(t))}function L8(e,t,r){if(!P8(e))throw new me(Tr,"Unexpected parent node type "+e.nodeType);if(r&&r.parentNode!==e)throw new me(gS,"child not in parent");if(!R8(t)||xi(t)&&e.nodeType!==De.DOCUMENT_NODE)throw new me(Tr,"Unexpected node type "+t.nodeType+" for parent node type "+e.nodeType)}function k8(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===De.DOCUMENT_FRAGMENT_NODE){var o=i.filter(Zn);if(o.length>1||Xn(i,rg))throw new me(Tr,"More than one element or text in fragment");if(o.length===1&&!uS(e,r))throw new me(Tr,"Element in fragment can not be inserted before doctype")}if(Zn(t)&&!uS(e,r))throw new me(Tr,"Only one element can be added and only after doctype");if(xi(t)){if(Xn(n,xi))throw new me(Tr,"Only one doctype is allowed");var a=Xn(n,Zn);if(r&&n.indexOf(a)<n.indexOf(r))throw new me(Tr,"Doctype can only be inserted before an element");if(!r&&a)throw new me(Tr,"Doctype can not be appended since element is present")}}function AS(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===De.DOCUMENT_FRAGMENT_NODE){var o=i.filter(Zn);if(o.length>1||Xn(i,rg))throw new me(Tr,"More than one element or text in fragment");if(o.length===1&&!cS(e,r))throw new me(Tr,"Element in fragment can not be inserted before doctype")}if(Zn(t)&&!cS(e,r))throw new me(Tr,"Only one element can be added and only after doctype");if(xi(t)){let l=function(u){return xi(u)&&u!==r};var s=l;if(Xn(n,l))throw new me(Tr,"Only one doctype is allowed");var a=Xn(n,Zn);if(r&&n.indexOf(a)<n.indexOf(r))throw new me(Tr,"Doctype can only be inserted before an element")}}function Cd(e,t,r,n){L8(e,t,r),e.nodeType===De.DOCUMENT_NODE&&(n||k8)(e,t,r);var i=t.parentNode;if(i&&i.removeChild(t),t.nodeType===ki){var o=t.firstChild;if(o==null)return t;var a=t.lastChild}else o=a=t;var s=r?r.previousSibling:e.lastChild;o.previousSibling=s,a.nextSibling=r,s?s.nextSibling=o:e.firstChild=o,r==null?e.lastChild=a:r.previousSibling=a;do{o.parentNode=e;var l=e.ownerDocument||e;Xl(o,l)}while(o!==a&&(o=o.nextSibling));return Ad(e.ownerDocument||e,e),t.nodeType==ki&&(t.firstChild=t.lastChild=null),t}function Xl(e,t){if(e.ownerDocument!==t){if(e.ownerDocument=t,e.nodeType===un&&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;)Xl(i,t),i=i.nextSibling}}function $8(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,Ad(e.ownerDocument,e,t);var r=e.ownerDocument||e;return Xl(t,r),t}eu.prototype={nodeName:"#document",nodeType:mS,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==ki){for(var r=e.firstChild;r;){var n=r.nextSibling;this.insertBefore(r,t),r=n}return e}return Cd(this,e,t),Xl(e,this),this.documentElement===null&&e.nodeType===un&&(this.documentElement=e),e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),ES(this,e)},replaceChild:function(e,t){Cd(this,e,t,AS),Xl(e,this),t&&this.removeChild(t),Zn(e)&&(this.documentElement=e)},importNode:function(e,t){return x8(this,e,t)},getElementById:function(e){var t=null;return wd(this.documentElement,function(r){if(r.nodeType==un&&r.getAttribute("id")==e)return t=r,!0}),t},getElementsByClassName:function(e){var t=iS(e);return new cs(this,function(r){var n=[];return t.length>0&&wd(r.documentElement,function(i){if(i!==r&&i.nodeType===un){var o=i.getAttribute("class");if(o){var a=e===o;if(!a){var s=iS(o);a=t.every(_8(s))}a&&n.push(i)}}}),n})},createElement:function(e){var t=new na;t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.localName=e,t.childNodes=new $i;var r=t.attributes=new vd;return r._ownerElement=t,t},createDocumentFragment:function(){var e=new Nd;return e.ownerDocument=this,e.childNodes=new $i,e},createTextNode:function(e){var t=new ng;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new ig;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){if(e.indexOf("]]>")!==-1)throw new me(oS,'data contains "]]>"');var t=new og;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var r=new sg;return r.ownerDocument=this,r.tagName=r.nodeName=r.target=e,r.nodeValue=r.data=t,r},createAttribute:function(e){var t=new Ed;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){if(!ls.test(e))throw new me(oS,'not a valid xml name "'+e+'"');var t=new ag;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var r=new na,n=t.split(":"),i=r.attributes=new vd;return r.childNodes=new $i,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 Ed,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}};Dr(eu,De);function na(){this._nsMap={}}na.prototype={nodeType:un,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===ki?this.insertBefore(e,null):$8(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 cs(this,function(t){var r=[];return wd(t,function(n){n!==t&&n.nodeType==un&&(e==="*"||n.tagName==e)&&r.push(n)}),r})},getElementsByTagNameNS:function(e,t){return new cs(this,function(r){var n=[];return wd(r,function(i){i!==r&&i.nodeType===un&&(e==="*"||i.namespaceURI===e)&&(t==="*"||i.localName==t)&&n.push(i)}),n})}};eu.prototype.getElementsByTagName=na.prototype.getElementsByTagName;eu.prototype.getElementsByTagNameNS=na.prototype.getElementsByTagNameNS;Dr(na,De);function Ed(){}Ed.prototype.nodeType=us;Dr(Ed,De);function tu(){}tu.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(Ot[Tr])},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}};Dr(tu,De);function ng(){}ng.prototype={nodeName:"#text",nodeType:Yl,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}};Dr(ng,tu);function ig(){}ig.prototype={nodeName:"#comment",nodeType:eg};Dr(ig,tu);function og(){}og.prototype={nodeName:"#cdata-section",nodeType:fS};Dr(og,tu);function Sd(){}Sd.prototype.nodeType=hS;Dr(Sd,De);function SS(){}SS.prototype.nodeType=D8;Dr(SS,De);function NS(){}NS.prototype.nodeType=T8;Dr(NS,De);function ag(){}ag.prototype.nodeType=pS;Dr(ag,De);function Nd(){}Nd.prototype.nodeName="#document-fragment";Nd.prototype.nodeType=ki;Dr(Nd,De);function sg(){}sg.prototype.nodeType=Zh;Dr(sg,De);function _S(){}_S.prototype.serializeToString=function(e,t,r,n){return TS.call(e,t,r,n)};De.prototype.toString=TS;function TS(e,t,r){var n=!!r&&!!r.requireWellFormed,i=[],o=this.nodeType==9&&this.documentElement||this,a=o.prefix,s=o.namespaceURI;if(s&&a==null){var a=o.lookupPrefix(s);if(a==null)var l=[{namespace:s,prefix:null}]}return lg(this,i,e,t,l,n),i.join("")}function dS(e,t,r){var n=e.prefix||"",i=e.namespaceURI;if(!i||n==="xml"&&i===Ql.XML||i===Ql.XMLNS)return!1;for(var o=r.length;o--;){var a=r[o];if(a.prefix===n)return a.namespace!==i}return!0}function bd(e,t,r,n){if(n&&!ls.test(t))throw new me(In,'The attribute name "'+t+'" is not a valid XML QName');e.push(" ",t,'="',r.replace(/[<>&"\t\n\r]/g,wS),'"')}function lg(e,t,r,n,i,o){i||(i=[]),It(e,{ns:i,isHTML:r},{enter:function(a,s){var l=s.ns,u=s.isHTML;if(n)if(a=n(a),a){if(typeof a=="string")return t.push(a),null}else return null;switch(a.nodeType){case un:var c=a.attributes,d=c.length,f=a.tagName;u=Ql.isHTML(a.namespaceURI)||u;var m=f;if(!u&&!a.prefix&&a.namespaceURI){for(var p,h=0;h<c.length;h++)if(c.item(h).name==="xmlns"){p=c.item(h).value;break}if(!p)for(var g=l.length-1;g>=0;g--){var b=l[g];if(b.prefix===""&&b.namespace===a.namespaceURI){p=b.namespace;break}}if(p!==a.namespaceURI)for(var g=l.length-1;g>=0;g--){var b=l[g];if(b.namespace===a.namespaceURI){b.prefix&&(m=b.prefix+":"+f);break}}}if(o&&!ls.test(m))throw new me(In,'The element name "'+m+'" is not a valid XML QName');t.push("<",m);for(var w=l.slice(),C=0;C<d;C++){var S=c.item(C);S.prefix=="xmlns"?w.push({prefix:S.localName,namespace:S.value}):S.nodeName=="xmlns"&&w.push({prefix:"",namespace:S.value})}for(var C=0;C<d;C++){var S=c.item(C);if(dS(S,u,w)){var O=S.prefix||"",L=S.namespaceURI;bd(t,O?"xmlns:"+O:"xmlns",L,o),w.push({prefix:O,namespace:L})}var I=n?n(S):S;I&&(typeof I=="string"?t.push(I):bd(t,I.name,I.value,o))}if(f===m&&dS(a,u,w)){var D=a.prefix||"",L=a.namespaceURI;bd(t,D?"xmlns:"+D:"xmlns",L,o),w.push({prefix:D,namespace:L})}var P=a.firstChild;if(P||u&&!/^(?:meta|link|img|br|hr|input)$/i.test(f)){if(t.push(">"),u&&/^script$/i.test(f)){for(;P;)P.data?t.push(P.data):lg(P,t,u,n,w.slice(),o),P=P.nextSibling;return t.push("</",f,">"),null}return{ns:w,isHTML:u,tag:m}}else return t.push("/>"),null;case mS:case ki:return{ns:l.slice(),isHTML:u,tag:null};case us:return bd(t,a.name,a.value,o),null;case Yl:return t.push(a.data.replace(/[<&>]/g,wS)),null;case fS:if(o&&a.data.indexOf("]]>")!==-1)throw new me(In,'The CDATASection data contains "]]>"');return t.push("<![CDATA[",a.data.replace(/]]>/g,"]]]]><![CDATA[>"),"]]>"),null;case eg:if(o&&a.data.indexOf("-->")!==-1)throw new me(In,'The comment node data contains "-->"');return t.push("<!--",a.data,"-->"),null;case hS:if(o){if(!ls.test(a.name))throw new me(In,'The doctype name "'+a.name+'" is not a valid XML Name');if(a.publicId&&!/^("[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%']*"|'[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%'"]*')$/.test(a.publicId))throw new me(In,"DocumentType publicId is not a valid PubidLiteral");if(a.systemId&&!/^("[^"]*"|'[^']*')$/.test(a.systemId))throw new me(In,"DocumentType systemId is not a valid SystemLiteral");if(a.internalSubset&&a.internalSubset.indexOf("]>")!==-1)throw new me(In,'DocumentType internalSubset contains "]>"')}var x=a.publicId,K=a.systemId;if(t.push("<!DOCTYPE ",a.name),x)t.push(" PUBLIC ",x),K&&K!="."&&t.push(" ",K),t.push(">");else if(K&&K!=".")t.push(" SYSTEM ",K,">");else{var Le=a.internalSubset;Le&&t.push(" [",Le,"]"),t.push(">")}return null;case Zh:if(o){if(!ls.test(a.target)||a.target.indexOf(":")!==-1||a.target.toLowerCase()==="xml")throw new me(In,'The processing instruction target "'+a.target+'" is not a valid XML NCName or is reserved');if(a.data.indexOf("?>")!==-1)throw new me(In,'The ProcessingInstruction data contains "?>"')}return t.push("<?",a.target," ",a.data,"?>"),null;case pS:if(o&&!ls.test(a.nodeName))throw new me(In,'The entity reference name "'+a.nodeName+'" is not a valid XML Name');return t.push("&",a.nodeName,";"),null;default:return t.push("??",a.nodeName),null}},exit:function(a,s){s&&s.tag&&t.push("</",s.tag,">")}})}function x8(e,t,r){var n;return It(t,null,{enter:function(i,o){var a=i.cloneNode(!1);a.ownerDocument=e,a.parentNode=null,o===null?n=a:o.appendChild(a);var s=i.nodeType===us||r;return s?a:null}}),n}function DS(e,t,r){var n;return It(t,null,{enter:function(i,o){var a=new i.constructor;for(var s in i)if(Object.prototype.hasOwnProperty.call(i,s)){var l=i[s];typeof l!="object"&&l!=a[s]&&(a[s]=l)}i.childNodes&&(a.childNodes=new $i),a.ownerDocument=e;var u=r;switch(a.nodeType){case un:var c=i.attributes,d=a.attributes=new vd,f=c.length;d._ownerElement=a;for(var m=0;m<f;m++)a.setAttributeNode(DS(e,c.item(m),!0));break;case us:u=!0}return o!==null?o.appendChild(a):n=a,u?a:null}}),n}function IS(e,t,r){e[t]=r}try{Object.defineProperty&&(Object.defineProperty(cs.prototype,"length",{get:function(){return tg(this),this.$$length}}),Object.defineProperty(De.prototype,"textContent",{get:function(){if(this.nodeType===un||this.nodeType===ki){var e=[];return It(this,null,{enter:function(t){if(t.nodeType===un||t.nodeType===ki)return!0;if(t.nodeType===Zh||t.nodeType===eg)return null;e.push(t.nodeValue)}}),e.join("")}return this.nodeValue},set:function(e){switch(this.nodeType){case un:case ki: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}}}),IS=function(e,t,r){e["$$"+t]=r})}catch{}Fi.DocumentType=Sd;Fi.DOMException=me;Fi.DOMImplementation=vS;Fi.Element=na;Fi.Node=De;Fi.NodeList=$i;Fi.walkDOM=It;Fi.XMLSerializer=_S});var PS=v(ru=>{"use strict";var OS=ss().freeze;ru.XML_ENTITIES=OS({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});ru.HTML_ENTITIES=OS({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"});ru.entityMap=ru.HTML_ENTITIES});var xS=v(dg=>{var ou=ss().NAMESPACE,cg=ss().tagNamePattern,ds=0,ho=1,fs=2,nu=3,ps=4,ms=5,iu=6,_d=7;function hs(e,t){this.message=e,this.locator=t,Error.captureStackTrace&&Error.captureStackTrace(this,hs)}hs.prototype=new Error;hs.prototype.name=hs.name;function kS(){}kS.prototype={parse:function(e,t,r){var n=this.domBuilder;n.startDocument(),q8(t,t={}),F8(e,t,r,n,this.errorHandler),n.endDocument()}};function F8(e,t,r,n,i){function o(de){if(de>65535){de-=65536;var Ke=55296+(de>>10),ur=56320+(de&1023);return String.fromCharCode(Ke,ur)}else return String.fromCharCode(de)}function a(de){var Ke=de.slice(1,-1);return Object.hasOwnProperty.call(r,Ke)?r[Ke]:Ke.charAt(0)==="#"?o(parseInt(Ke.substr(1).replace("x","0x"))):(i.error("entity not found:"+de),de)}function s(de){if(de>h){var Ke=e.substring(h,de).replace(/&#?\w+;/g,a);f&&l(h),n.characters(Ke,0,de-h),h=de}}function l(de,Ke){for(;de>=c&&(Ke=d.exec(e));)u=Ke.index,c=u+Ke[0].length,f.lineNumber++;f.columnNumber=de-u+1}for(var u=0,c=0,d=/.*(?:\r\n?|\n)|.*$/g,f=n.locator,m=[{currentNSMap:t}],p={},h=0;;){try{var g=e.indexOf("<",h);if(g<0){if(!e.substr(h).match(/^\s*$/)){var b=n.doc,w=b.createTextNode(e.substr(h));b.appendChild(w),n.currentElement=w}return}switch(g>h&&s(g),e.charAt(g+1)){case"/":var K=e.indexOf(">",g+3),C=e.substring(g+2,K).replace(/^([\s\S]*?[^ \t\n\r])?[ \t\n\r]*$/,"$1"),S=m.pop();K<0?(C=e.substring(g+2).replace(/[\s<].*/,""),i.error("end tag name: "+C+" is not complete:"+S.tagName),K=g+1+C.length):C.match(/\s</)?(C=C.replace(/[\s<].*/,""),i.error("end tag name: "+C+" maybe not complete"),K=g+1+C.length):/[ \t\n\r]/.test(C)&&cg.test(C.split(/[ \t\n\r]/)[0])&&i.error('end tag name is followed by whitespace and trailing content: "'+C+'"');var O=S.localNSMap,L=S.tagName==C,I=L||S.tagName&&S.tagName.toLowerCase()==C.toLowerCase();if(I){if(n.endElement(S.uri,S.localName,C),O)for(var D in O)Object.prototype.hasOwnProperty.call(O,D)&&n.endPrefixMapping(D);L||i.fatalError("end tag name: "+C+" is not match the current start tagName:"+S.tagName)}else m.push(S);K++;break;case"?":f&&l(g),K=G8(e,g,n);break;case"!":f&&l(g),K=V8(e,g,n,i);break;default:f&&l(g);var P=new $S,x=m[m.length-1].currentNSMap,K=M8(e,g,P,x,a,i),Le=P.length;if(!P.closed&&B8(e,K,P.tagName,p)&&(P.closed=!0,r.nbsp||i.warning("unclosed xml attribute")),f&&Le){for(var lr=RS(f,{}),Ge=0;Ge<Le;Ge++){var Ut=P[Ge];l(Ut.offset),Ut.locator=RS(f,{})}n.locator=lr,LS(P,n,x)&&m.push(P),n.locator=f}else LS(P,n,x)&&m.push(P);ou.isHTML(P.uri)&&!P.closed?K=U8(e,K,P.tagName,a,n):K++}}catch(de){if(de instanceof hs)throw de;i.error("element parse error: "+de),K=-1}K>h?h=K:s(Math.max(g,h)+1)}}function RS(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function M8(e,t,r,n,i,o){function a(m,p,h){r.attributeNames.hasOwnProperty(m)&&o.fatalError("Attribute "+m+" redefined"),r.addValue(m,p.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,i),h)}for(var s,l,u=++t,c=ds;;){var d=e.charAt(u);if(c===ds&&d==="<")throw new Error("unexpected < in tag name: "+e.slice(t,u));switch(d){case"=":if(c===ho)s=e.slice(t,u),c=nu;else if(c===fs)c=nu;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(c===nu||c===ho)if(c===ho&&(o.warning('attribute value must after "="'),s=e.slice(t,u)),t=u+1,u=e.indexOf(d,t),u>0)l=e.slice(t,u),a(s,l,t-1),c=ms;else throw new Error("attribute value no end '"+d+"' match");else if(c==ps)l=e.slice(t,u),a(s,l,t),o.warning('attribute "'+s+'" missed start quot('+d+")!!"),t=u+1,c=ms;else throw new Error('attribute value must after "="');break;case"/":switch(c){case ds:r.setTagName(e.slice(t,u));case ms:case iu:case _d:c=_d,r.closed=!0;case ps:case ho:break;case fs:r.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return o.error("unexpected end of input"),c==ds&&r.setTagName(e.slice(t,u)),u;case">":switch(c){case ds:r.setTagName(e.slice(t,u));case ms:case iu:case _d:break;case ps:case ho:l=e.slice(t,u),l.slice(-1)==="/"&&(r.closed=!0,l=l.slice(0,-1));case fs:c===fs&&(l=s),c==ps?(o.warning('attribute "'+l+'" missed quot(")!'),a(s,l,t)):((!ou.isHTML(n[""])||!l.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+l+'" missed value!! "'+l+'" instead!!'),a(l,l,t));break;case nu:throw new Error("attribute value missed!!")}return u;case"\x80":d=" ";default:if(d<=" ")switch(c){case ds:r.setTagName(e.slice(t,u)),c=iu;break;case ho:s=e.slice(t,u),c=fs;break;case ps:var l=e.slice(t,u);o.warning('attribute "'+l+'" missed quot(")!!'),a(s,l,t);case ms:c=iu;break}else switch(c){case fs:var f=r.tagName;(!ou.isHTML(n[""])||!s.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+s+'" missed value!! "'+s+'" instead2!!'),a(s,s,t),t=u,c=ho;break;case ms:o.warning('attribute space is required"'+s+'"!!');case iu:c=ho,t=u;break;case nu:c=ps,t=u;break;case _d:throw new Error("elements closed character '/' and '>' must be connected to")}}u++}}function LS(e,t,r){for(var n=e.tagName,i=null,d=e.length;d--;){var o=e[d],a=o.qName,s=o.value,f=a.indexOf(":");if(f>0)var l=o.prefix=a.slice(0,f),u=a.slice(f+1),c=l==="xmlns"&&u;else u=a,l=null,c=a==="xmlns"&&"";o.localName=u,c!==!1&&(i==null&&(i={},r=Object.create(r)),r[c]=i[c]=s,o.uri=ou.XMLNS,t.startPrefixMapping(c,s))}for(var d=e.length;d--;){o=e[d];var l=o.prefix;l&&(l==="xml"&&(o.uri=ou.XML),l!=="xmlns"&&(o.uri=r[l||""]))}var f=n.indexOf(":");f>0?(l=e.prefix=n.slice(0,f),u=e.localName=n.slice(f+1)):(l=null,u=e.localName=n);var 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 U8(e,t,r,n,i){if(/^(?:script|textarea)$/i.test(r)){var o=e.indexOf("</"+r+">",t),a=e.substring(t+1,o);if(/[&<]/.test(a))return/^script$/i.test(r)?(i.characters(a,0,a.length),o):(a=a.replace(/&#?\w+;/g,n),i.characters(a,0,a.length),o)}return t+1}function B8(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 q8(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function V8(e,t,r,n){var i=e.charAt(t+2);switch(i){case"-":if(e.charAt(t+3)==="-"){var o=e.indexOf("-->",t+4);return o>t?(r.comment(e,t+4,o-t-4),o+3):(n.error("Unclosed comment"),-1)}else return-1;default:if(e.substr(t+3,6)=="CDATA["){var o=e.indexOf("]]>",t+9);return r.startCDATA(),r.characters(e,t+9,o-t-9),r.endCDATA(),o+3}var a=W8(e,t),s=a.length;if(s>1&&/!doctype/i.test(a[0][0])){var l=a[1][0],u=!1,c=!1;s>3&&(/^public$/i.test(a[2][0])?(u=a[3][0],c=s>4&&a[4][0]):/^system$/i.test(a[2][0])&&(c=a[3][0]));var d=a[s-1];return r.startDTD(l,u,c),r.endDTD(),d.index+d[0].length}}return-1}function G8(e,t,r){var n=e.indexOf("?>",t);if(n){var i=e.substring(t,n).match(/^<\?(\S*)\s*([\s\S]*?)$/);if(i){var o=i[0].length;return r.processingInstruction(i[1],i[2]),n+2}else return-1}return-1}function $S(){this.attributeNames={}}$S.prototype={setTagName:function(e){if(!cg.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},addValue:function(e,t,r){if(!cg.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 W8(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}dg.XMLReader=kS;dg.ParseError=hs});var GS=v(Dd=>{var z8=ss(),j8=ug(),FS=PS(),BS=xS(),H8=j8.DOMImplementation,MS=z8.NAMESPACE,K8=BS.ParseError,J8=BS.XMLReader;function qS(e){return e.replace(/\r[\n\u0085]/g,``).replace(/[\r\u0085\u2028]/g,`-`)}function VA(e){this.options=e||{locator:{}}}VA.prototype.parseFromString=function(e,t){var r=this.options,n=new jV,i=r.domBuilder||new Ul,o=r.errorHandler,a=r.locator,s=r.xmlns||{},l=/\/x?html?$/.test(t),u=l?FA.HTML_ENTITIES:FA.XML_ENTITIES;a&&i.setDocumentLocator(a),n.errorHandler=HV(o,i,a),n.domBuilder=r.domBuilder||i,l&&(s[""]=MA.HTML),s.xml=s.xml||MA.XML;var c=r.normalizeLineEndings||qA;return e&&typeof e=="string"?n.parse(c(e),s,u):n.errorHandler.error("invalid doc source"),i.doc};function HV(e,t,r){if(!e){if(t instanceof Ul)return t;e=t}var n={},i=e instanceof Function;r=r||{};function o(a){var s=e[a];!s&&i&&(s=e.length==2?function(l){e(a,l)}:e),n[a]=s&&function(l){s("[xmldom "+a+"] "+l+Nh(r))}||function(){}}return o("warning"),o("error"),o("fatalError"),n}function Ul(){this.cdata=!1}function ts(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}Ul.prototype={startDocument:function(){this.doc=new WV().createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(e,t,r,n){var i=this.doc,o=i.createElementNS(e,r||t),a=n.length;Zc(this,o),this.currentElement=o,this.locator&&ts(this.locator,o);for(var s=0;s<a;s++){var e=n.getURI(s),l=n.getValue(s),r=n.getQName(s),u=i.createAttributeNS(e,r);this.locator&&ts(n.getLocator(s),u),u.value=u.nodeValue=l,o.setAttributeNode(u)}},endElement:function(e,t,r){var n=this.currentElement,i=n.tagName;this.currentElement=n.parentNode},startPrefixMapping:function(e,t){},endPrefixMapping:function(e){},processingInstruction:function(e,t){var r=this.doc.createProcessingInstruction(e,t);this.locator&&ts(this.locator,r),Zc(this,r)},ignorableWhitespace:function(e,t,r){},characters:function(e,t,r){if(e=UA.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&&ts(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=UA.apply(this,arguments);var n=this.doc.createComment(e);this.locator&&ts(this.locator,n),Zc(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&&ts(this.locator,i),Zc(this,i),this.doc.doctype=i}},warning:function(e){console.warn("[xmldom warning] "+e,Nh(this.locator))},error:function(e){console.error("[xmldom error] "+e,Nh(this.locator))},fatalError:function(e){throw new zV(e,this.locator)}};function Nh(e){if(e)return`-@`+(e.systemId||"")+"#[line:"+e.lineNumber+",col:"+e.columnNumber+"]"}function UA(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){Ul.prototype[e]=function(){return null}});function Zc(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}ed.__DOMHandler=Ul;ed.normalizeLineEndings=qA;ed.DOMParser=VA});var rs=v(td=>{var WA=Eh();td.DOMImplementation=WA.DOMImplementation;td.XMLSerializer=WA.XMLSerializer;td.DOMParser=GA().DOMParser});var jA={};jr(jA,{CCFControlConstants:()=>zA,CCFPropertyConstants:()=>Th,CustomControlDataType:()=>F,CustomControlNames:()=>Si,DefaultControlNameKeys:()=>_h,ICCModeEnum:()=>ro,JSONParametersConstants:()=>Dh,LookUpType:()=>rd,ManifestXMLConstants:()=>qt,NumberType:()=>nd,Usage:()=>zo});var zA,Th,Dh,qt,F,_h,Si,ro,zo,rd,nd,jo=k(()=>{"use strict";zA={CCID:"CustomControlId",CCName:"DisplayName",Properties:"Properties",Mode:"ControlMode",AvailableOn:"AvailableOn",CCDescription:"description-key",ImageURL:"preview-image",TypeGroup:"type-group",DataSets:"DataSets",EntityNameKey:"EntityNameKey",NameSpace:"Name",OfTypeKey:"OfType"},Th={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"},Dh={GroupDefinition:"GroupDefinition"},qt={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"})(F||(F={}));(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"})(_h||(_h={}));(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"})(Si||(Si={}));(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"})(ro||(ro={}));(function(e){e[e.Bound=0]="Bound",e[e.Input=1]="Input",e[e.Output=2]="Output"})(zo||(zo={}));rd=[F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.LookupSimple],nd=[F.WholeNone,F.WholeDuration,F.WholeLanguage,F.WholeTimeZone,F.FP,F.Decimal]});var ns,er,Bl=k(()=>{"use strict";ns=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}},er=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 HA={};jr(HA,{AttributeDataSourceType:()=>ql,AttributeDataSourceTypeMask:()=>id,AttributePrecisionSource:()=>Vl,EntityAttributeDataSourceType:()=>Ho,EntityAttributeDateTimeBehavior:()=>Ph,EntityAttributeImeMode:()=>Oh,EntityAttributePrecisionSource:()=>Rh,EntityAttributeRequiredLevel:()=>no,EntityAttributeType:()=>x,EntityAttributeTypeFormat:()=>W,EntityMetadataLookUpBase:()=>Ni,EntityResxKeyLookUp:()=>od,SourceTypeMask:()=>Ih});var Ni,x,W,no,Ho,Ih,ql,id,Oh,Ph,Rh,Vl,od,is=k(()=>{"use strict";Bl();Ni=class{name;constructor(t){this.name=t}toString(){return this.name}getName(){return this.name}getDisplayNameResourceKey(){return od.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"})(x||(x={}));(function(e){e.Email="Email",e.Text="Text",e.TextArea="TextArea",e.Url="Url",e.TickerSymbol="TickerSymbol",e.PhoneticGuide="PhoneticGuide",e.VersionNumber="VersionNumber",e.Phone="Phone",e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale",e.DateOnly="DateOnly",e.DateAndTime="DateAndTime",e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean",e.Regarding="Regarding"})(W||(W={}));no=class extends Ni{constructor(t){super(t)}static get None(){return"None"}static get SystemRequired(){return"SystemRequired"}static get ApplicationRequired(){return"ApplicationRequired"}static get Recommended(){return"Recommended"}},Ho=class e extends Ni{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?ql.Persistent:parseInt(ql[this.name])}},Ih=class e extends Ni{constructor(t){super(t),t||(this.name=e.Undefined)}static get Undefined(){return"Undefined"}static get Simple(){return"Simple"}static get Related(){return"Related"}static get Logical(){return"Logical"}static get Calculated(){return"Calculated"}static get Rollup(){return"Rollup"}static get Invalid(){return"Invalid"}GetValue(){return parseInt(id[this.name])}};(function(e){e[e.Persistent=0]="Persistent",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup"})(ql||(ql={}));(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"})(id||(id={}));Oh=class e extends Ni{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Auto(){return"Auto"}static get Inactive(){return"Inactive"}static get Active(){return"Active"}static get Disabled(){return"Disabled"}},Ph=class e extends Ni{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get UserLocal(){return"UserLocal"}static get DateOnly(){return"DateOnly"}static get TimeZoneIndependent(){return"TimeZoneIndependent"}},Rh=class e extends Ni{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Attribute(){return"Attribute"}static get Organization(){return"Organization"}static get Currency(){return"Currency"}GetValue(){return this.name===e.None?Vl.Currency:parseInt(Vl[this.name])}};(function(e){e[e.Attribute=0]="Attribute",e[e.Organization=1]="Organization",e[e.Currency=2]="Currency"})(Vl||(Vl={}));od=class e{static resourceKeyMap=e.initResourceKeyMap();static initResourceKeyMap(){let t=new ns;return t.add(x.TwoOptions,"SystemCustomization.type.bit.label"),t.add(x.Customer,"SystemCustomization.type.customer.label"),t.add(x.CustomerType,"SystemCustomization.type.customer.label"),t.add(x.DateTime,"SystemCustomization.type.datetime.label"),t.add(x.DecimalNumber,"SystemCustomization.type.decimal.label"),t.add(x.FloatingPointNumber,"SystemCustomization.type.float.label"),t.add(x.WholeNumber,"SystemCustomization.type.int.label"),t.add(x.LookupType,"SystemCustomization.type.lookup.label"),t.add(x.Lookup,"SystemCustomization.type.lookup.label"),t.add(x.MultipleLineofText,"SystemCustomization.type.ntext.label"),t.add(x.Currency,"SystemCustomization.type.money.label"),t.add(x.Owner,"SystemCustomization.type.owner.label"),t.add(x.OwnerType,"SystemCustomization.type.owner.label"),t.add(x.PartyList,"SystemCustomization.type.partylist.label"),t.add(x.PartyListType,"SystemCustomization.type.partylist.label"),t.add(x.OptionSet,"SystemCustomization.type.picklist.label"),t.add(x.State,"SystemCustomization.type.state.label"),t.add(x.Status,"SystemCustomization.type.status.label"),t.add(x.SingleLineofText,"SystemCustomization.type.nvarchar.label"),t.add(x.UniqueIdentifier,"SystemCustomization.type.uniqueidentifier.label"),t.add(x.UniqueIdentifierType,"SystemCustomization.type.uniqueidentifiertype.label"),t.add(x.CalendarRulesType,"SystemCustomization.type.calendarrules.label"),t.add(x.VirtualType,"SystemCustomization.type.virtual.label"),t.add(x.BigInt,"SystemCustomization.type.bigint.label"),t.add(x.ManagedPropertyType,"SystemCustomization.type.managedproperty.label"),t.add(x.EntityNameType,"SystemCustomization.type.entityname.label"),t.add(x.Image,"SystemCustomization.type.image.label"),t.add(x.MultiSelectOptionSet,"SystemCustomization.type.multiselectpicklist.label"),t.add(x.PrimaryNameAttributeType,"SystemCustomization.type.primaryname.label"),t.add(x.LookupType,"SystemCustomization.type.lookuptype.label"),t.add(x.Subject,"SystemCustomization.type.subject.label"),t.add(W.Email,"SystemCustomization.String.Format.email"),t.add(W.Text,"SystemCustomization.String.Format.text"),t.add(W.TextArea,"SystemCustomization.String.Format.textarea"),t.add(W.Url,"SystemCustomization.String.Format.url"),t.add(W.TickerSymbol,"SystemCustomization.String.Format.tickersymbol"),t.add(W.PhoneticGuide,"SystemCustomization.String.Format.phoneticguide"),t.add(W.VersionNumber,"SystemCustomization.String.Format.versionnumber"),t.add(W.Phone,"SystemCustomization.String.Format.phone"),t.add(W.None,"SystemCustomization.Integer.Format."),t.add(W.Duration,"SystemCustomization.Integer.Format.duration"),t.add(W.TimeZone,"SystemCustomization.Integer.Format.timezone"),t.add(W.Language,"SystemCustomization.Integer.Format.language"),t.add(W.Locale,"SystemCustomization.Integer.Format.language"),t.add(W.DateOnly,"SystemCustomization.DateTime.Format.date"),t.add(W.DateAndTime,"SystemCustomization.DateTime.Format.datetime"),t.add(W.Regarding,"SystemCustomization.Lookup.Format.regarding"),t.add(Ho.Persistent,"SystemCustomization.String.Source.persistent"),t.add(Ho.Calculated,"SystemCustomization.String.Source.calculated"),t.add(Ho.Rollup,"SystemCustomization.String.Source.rollup"),t.add(Ho.None,"SystemCustomization.String.Source.none"),t}static getDisplayNameResourceKey(t){return e.resourceKeyMap.getValue(t)}}});var Lh=v(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.parsePcfManifest=Gn.manifestTypesForColumn=Gn.DEFAULT_TYPE_GROUPS=void 0;var KV=rs(),H=(jo(),kr(jA)),be=(is(),kr(HA));Gn.DEFAULT_TYPE_GROUPS={numbers:[H.CustomControlDataType.WholeNone,H.CustomControlDataType.FP,H.CustomControlDataType.Decimal,H.CustomControlDataType.Currency],text:[H.CustomControlDataType.SingleLineText,H.CustomControlDataType.SingleLineTextArea,H.CustomControlDataType.Multiple],lookup:[H.CustomControlDataType.LookupSimple,H.CustomControlDataType.LookupCustomer,H.CustomControlDataType.LookupOwner,H.CustomControlDataType.LookupPartyList,H.CustomControlDataType.LookupRegarding],dates:[H.CustomControlDataType.DateAndTimeDateOnly,H.CustomControlDataType.DateAndTimeDateAndTime],allFields:[H.CustomControlDataType.TwoOptions,H.CustomControlDataType.DateAndTimeDateOnly,H.CustomControlDataType.DateAndTimeDateAndTime,H.CustomControlDataType.FP,H.CustomControlDataType.Decimal,H.CustomControlDataType.WholeNone,H.CustomControlDataType.WholeDuration,H.CustomControlDataType.WholeTimeZone,H.CustomControlDataType.WholeLanguage,H.CustomControlDataType.LookupSimple,H.CustomControlDataType.LookupCustomer,H.CustomControlDataType.LookupOwner,H.CustomControlDataType.LookupPartyList,H.CustomControlDataType.LookupRegarding,H.CustomControlDataType.Multiple,H.CustomControlDataType.OptionSet,H.CustomControlDataType.SingleLineText,H.CustomControlDataType.SingleLineTextArea,H.CustomControlDataType.SingleLineEmail,H.CustomControlDataType.SingleLineURL,H.CustomControlDataType.SingleLineTickerSymbol,H.CustomControlDataType.SingleLinePhone]};var JV="Phone";function YV(e,t,r){switch(e){case be.EntityAttributeType.TwoOptions:return[H.CustomControlDataType.TwoOptions,H.CustomControlDataType.Boolean];case be.EntityAttributeType.Customer:case be.EntityAttributeType.CustomerType:return[H.CustomControlDataType.LookupCustomer];case be.EntityAttributeType.DateTime:return t===be.EntityAttributeTypeFormat.DateAndTime?[H.CustomControlDataType.DateAndTimeDateAndTime]:[H.CustomControlDataType.DateAndTimeDateOnly];case be.EntityAttributeType.DecimalNumber:return[H.CustomControlDataType.Decimal];case be.EntityAttributeType.FloatingPointNumber:return[H.CustomControlDataType.FP];case be.EntityAttributeType.File:return[H.CustomControlDataType.File];case be.EntityAttributeType.Image:return[H.CustomControlDataType.Image];case be.EntityAttributeType.WholeNumber:return t===be.EntityAttributeTypeFormat.Duration?[H.CustomControlDataType.WholeDuration]:t===be.EntityAttributeTypeFormat.Language?[H.CustomControlDataType.WholeLanguage]:t===be.EntityAttributeTypeFormat.TimeZone?[H.CustomControlDataType.WholeTimeZone]:[H.CustomControlDataType.WholeNone];case be.EntityAttributeType.LookupType:case be.EntityAttributeType.Lookup:return t===be.EntityAttributeTypeFormat.Regarding?[H.CustomControlDataType.LookupRegarding]:[H.CustomControlDataType.LookupSimple];case be.EntityAttributeType.MultipleLineofText:return[H.CustomControlDataType.Multiple];case be.EntityAttributeType.Currency:return[H.CustomControlDataType.Currency];case be.EntityAttributeType.Owner:case be.EntityAttributeType.OwnerType:return[H.CustomControlDataType.LookupOwner];case be.EntityAttributeType.PartyList:case be.EntityAttributeType.PartyListType:return[H.CustomControlDataType.LookupPartyList];case be.EntityAttributeType.Status:case be.EntityAttributeType.OptionSet:return[H.CustomControlDataType.OptionSet];case be.EntityAttributeType.SingleLineofText:switch(t){case be.EntityAttributeTypeFormat.Email:return[H.CustomControlDataType.SingleLineEmail];case be.EntityAttributeTypeFormat.Phone:return[H.CustomControlDataType.SingleLinePhone];case be.EntityAttributeTypeFormat.Text:return r===JV?[H.CustomControlDataType.SingleLinePhone]:[H.CustomControlDataType.SingleLineText];case be.EntityAttributeTypeFormat.TextArea:return[H.CustomControlDataType.SingleLineTextArea];case be.EntityAttributeTypeFormat.TickerSymbol:return[H.CustomControlDataType.SingleLineTickerSymbol];case be.EntityAttributeTypeFormat.Url:return[H.CustomControlDataType.SingleLineURL];default:return[H.CustomControlDataType.SingleLineText]}case be.EntityAttributeType.MultiSelectOptionSet:return[H.CustomControlDataType.MultiSelectOptionSet];default:return null}}Gn.manifestTypesForColumn=YV;function KA(e){let t=[],r=e.childNodes;for(let n=0;n<r.length;n+=1)r[n].nodeType===1&&t.push(r[n]);return t}function Vn(e,t){return e.hasAttribute(t)?e.getAttribute(t):null}function _i(e,...t){return KA(e).filter(r=>t.includes(r.tagName))}function QV(e){let t=new Map;for(let r of _i(e,"type-group"))t.set(String(Vn(r,"name")),_i(r,"type").map(n=>String(n.textContent)));for(let[r,n]of t)t.set(r,n.sort());return t}function XV(e){let t=e.getElementsByTagName("AvailableOn")[0];if(!t)return{web:!0,phone:!0,tablet:!0};let r=new Set(KA(t).map(n=>n.tagName));return{web:r.has("web"),phone:r.has("phone"),tablet:r.has("tablet")}}var ZV={input:"input",bound:"bound",output:"output"};function eG(e,t,r){let n=Vn(e,"usage"),i=n!==null&&ZV[n]||"input",o=Vn(e,"default-value"),a=_i(e,"value").map(p=>{let m={name:Vn(p,"name"),value:String(p.textContent),isDefault:Vn(p,"default")==="true"};return m.isDefault&&(o=m.value),m}),s=Vn(e,"of-type-group"),l=s!==null?t.get(s):void 0,u=s!==null&&Object.prototype.hasOwnProperty.call(Gn.DEFAULT_TYPE_GROUPS,s)?Gn.DEFAULT_TYPE_GROUPS[s]:void 0,c=l?[...l]:u?[...u]:[],d=Vn(e,"of-type"),f=d!==null?d:c.length>0?c[0]:null;return{name:Vn(e,"name"),usage:i,ofType:d,typeGroupName:s,ofTypeGroup:c,defaultType:f||void 0,required:Vn(e,"required")==="true",hidden:Vn(e,"hidden")==="true",defaultValue:o,enumValues:a,isPrimary:r&&i==="bound"}}function tG(e){var t;let r=[],n=m=>h=>r.push(`${m}: ${h}`),i=new KV.DOMParser({errorHandler:{warning:n("warning"),error:n("error"),fatalError:n("fatalError")}}).parseFromString(e,"text/xml"),o=(t=i?.documentElement)!==null&&t!==void 0?t:null;if(!o||r.length>0)throw new Error(`the control manifest does not parse cleanly${r.length>0?` (${r[0]})`:""}`);let a=_i(o,"control")[0];if(!a)throw new Error("the control manifest has no <control> element");let s=QV(a),l=_i(a,"data-set"),u=_i(a,"property"),c=_i(a,"groups"),d=[],f=!1;for(let m of u){let h=eG(m,s,l.length===0&&!f);f=f||h.isPrimary,d.push(h)}let p=l.length>0||(d.length>0?d[0].usage==="bound":c.some(m=>_i(m,"group").some(h=>_i(h,"data-set","property").length>0)));return{properties:d,hasDataset:l.length>0,hasGroups:c.length>0,isBound:p,availableOn:XV(a)}}Gn.parsePcfManifest=tG});var YA=v(as=>{"use strict";Object.defineProperty(as,"__esModule",{value:!0});as.readPcfColumn=as.readControlManifest=void 0;var os=ue(),rG=Lh();function kh(e,t,r){var n;let i=(n=r?.error)===null||n===void 0?void 0:n.message;return new Error(`${e}: HTTP ${t}${typeof i=="string"?` ${i}`:""}`)}async function nG(e,t){var r,n;let i="/customcontrols"+(0,os.odataQuery)([["$select","name,manifest"],["$filter",`name eq '${(0,os.odataLiteral)(t)}'`]]);try{let o=await e.get(i);if(o.status<200||o.status>=300)return{kind:"unavailable",error:kh(`reading control "${t}"`,o.status,o.body)};let a=((n=(r=o.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]).filter(l=>l!==null&&typeof l=="object");if(a.length===0)return{kind:"missing"};if(a.length>1)return{kind:"ambiguous"};let s=a[0].manifest;return typeof s!="string"?{kind:"unavailable",error:new Error(`control "${t}" has no manifest`)}:{kind:"found",value:(0,rG.parsePcfManifest)(s)}}catch(o){return{kind:"unavailable",error:o instanceof Error?o:new Error(String(o))}}}as.readControlManifest=nG;var iG=new Map([["StringType",{cast:"StringAttributeMetadata",select:"Format,FormatName"}],["MemoType",{cast:"MemoAttributeMetadata",select:"Format"}],["IntegerType",{cast:"IntegerAttributeMetadata",select:"Format"}],["DateTimeType",{cast:"DateTimeAttributeMetadata",select:"Format"}],["LookupType",{cast:"LookupAttributeMetadata",select:"Format"}]]);function JA(e){let t=e?.Value;return typeof t=="string"?t:void 0}async function oG(e,t,r,n){var i,o;let a=`/EntityDefinitions(LogicalName='${(0,os.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,os.odataPathLiteral)(r)}')`,s=n?.requireCreateEligibility===!0;try{let l=await e.get(a+(0,os.odataQuery)([["$select",`LogicalName,AttributeType,AttributeTypeName,IsValidForForm,IsPrimaryId${s?",IsValidForCreate":""}`]]));if(l.status===404)return{kind:"missing"};if(l.status<200||l.status>=300)return{kind:"unavailable",error:kh(`reading column "${r}"`,l.status,l.body)};let u=(i=l.body)!==null&&i!==void 0?i:{},c=JA(u.AttributeTypeName);if(!c)return{kind:"unavailable",error:new Error(`column "${r}" has no AttributeTypeName`)};if(s&&typeof u.IsValidForCreate!="boolean")return{kind:"unavailable",error:new Error(`column "${r}" has no IsValidForCreate`)};let d={logicalName:typeof u.LogicalName=="string"?u.LogicalName:r,attributeTypeName:c,isValidForForm:u.IsValidForForm===!0,isPrimaryId:u.IsPrimaryId===!0,...s?{isValidForCreate:u.IsValidForCreate}:{}},f=iG.get(c);if(f){let p=await e.get(`${a}/Microsoft.Dynamics.CRM.${f.cast}`+(0,os.odataQuery)([["$select",f.select]]));if(p.status<200||p.status>=300)return{kind:"unavailable",error:kh(`reading the format of column "${r}"`,p.status,p.body)};let m=(o=p.body)!==null&&o!==void 0?o:{};typeof m.Format=="string"&&(d.format=m.Format);let h=JA(m.FormatName);h&&(d.formatName=h)}return{kind:"found",value:d}}catch(l){return{kind:"unavailable",error:l instanceof Error?l:new Error(String(l))}}}as.readPcfColumn=oG});var Ko=v(ad=>{"use strict";Object.defineProperty(ad,"__esModule",{value:!0});ad.DEFAULT_LCID=void 0;ad.DEFAULT_LCID=1033});var lt=v(Wn=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.assignMissingIds=Wn.pointerTouchesValueMap=Wn.isValueMapKey=Wn.newId=void 0;var aG=Fa();function QA(){return globalThis.crypto.randomUUID().toLowerCase()}Wn.newId=QA;function sG(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var $h=new Set(["parameters","bag","expression","rawExpression","lookupValue","stepLabels","genPage","inputData","customControl"]);function lG(e){return $h.has(e)}Wn.isValueMapKey=lG;function uG(e){return aG.JsonPointer.parse(e).some(t=>$h.has(t))}Wn.pointerTouchesValueMap=uG;function cG(e){return xh(e),e}Wn.assignMissingIds=cG;function xh(e){if(Array.isArray(e)){e.forEach(t=>xh(t));return}if(sG(e)){(typeof e.id!="string"||e.id.length===0)&&(e.id=QA());for(let t of Object.keys(e))t==="id"||$h.has(t)||xh(e[t])}}});var Wl=v(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});vr.sendChangeSet=vr.partResponse=vr.postChangeSet=vr.parseChangeSetParts=vr.parseChangeSetStatuses=vr.renderChangeSet=void 0;var io=Q(),Fh=ye(),XA=lt(),Gl=ue();function Mh(e,t){let r=`batch_${(0,XA.newId)()}`,n=`changeset_${(0,XA.newId)()}`,i=t.map((s,l)=>String(l+1)),o=t.map((s,l)=>{var u,c;if(s.rawBody!==void 0&&s.contentType===void 0)throw new io.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a raw body but no Content-Type`);let d=(u=s.rawBody)!==null&&u!==void 0?u:s.body===void 0?void 0:JSON.stringify(s.body);if(d!==void 0&&(d.includes(`--${n}`)||d.includes(`--${r}`)))throw new io.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a body containing the batch boundary`);(0,Gl.assertNoControlChars)(s.path,"batch operation path"),s.etag&&(0,Gl.assertNoControlChars)(s.etag,"batch operation etag");let f=Object.entries((c=s.headers)!==null&&c!==void 0?c:{});for(let[p,m]of f)if((0,Gl.assertNoControlChars)(p,"batch operation header name"),(0,Gl.assertNoControlChars)(m,"batch operation header value"),!/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(p))throw new io.InvalidArgumentError(`batch operation header name '${p}' is not a valid HTTP token`);return s.contentType!==void 0&&(0,Gl.assertNoControlChars)(s.contentType,"batch operation content type"),[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${i[l]}`,"",`${s.method} ${e.apiUrl(s.path)} HTTP/1.1`,...d===void 0?[]:[`Content-Type: ${s.rawBody!==void 0?s.contentType:"application/json;type=entry"}`],...e.solutionName?[`MSCRM.SolutionUniqueName: ${e.solutionName}`]:[],...s.etag?[`If-Match: ${s.etag}`]:[],...f.map(([p,m])=>`${p}: ${m}`),"",...d===void 0?[]:[d]].join(`\r+`)}function VS(e){this.options=e||{locator:{}}}VS.prototype.parseFromString=function(e,t){var r=this.options,n=new J8,i=r.domBuilder||new au,o=r.errorHandler,a=r.locator,s=r.xmlns||{},l=/\/x?html?$/.test(t),u=l?FS.HTML_ENTITIES:FS.XML_ENTITIES;a&&i.setDocumentLocator(a),n.errorHandler=Y8(o,i,a),n.domBuilder=r.domBuilder||i,l&&(s[""]=MS.HTML),s.xml=s.xml||MS.XML;var c=r.normalizeLineEndings||qS;return e&&typeof e=="string"?n.parse(c(e),s,u):n.errorHandler.error("invalid doc source"),i.doc};function Y8(e,t,r){if(!e){if(t instanceof au)return t;e=t}var n={},i=e instanceof Function;r=r||{};function o(a){var s=e[a];!s&&i&&(s=e.length==2?function(l){e(a,l)}:e),n[a]=s&&function(l){s("[xmldom "+a+"] "+l+fg(r))}||function(){}}return o("warning"),o("error"),o("fatalError"),n}function au(){this.cdata=!1}function gs(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}au.prototype={startDocument:function(){this.doc=new H8().createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(e,t,r,n){var i=this.doc,o=i.createElementNS(e,r||t),a=n.length;Td(this,o),this.currentElement=o,this.locator&&gs(this.locator,o);for(var s=0;s<a;s++){var e=n.getURI(s),l=n.getValue(s),r=n.getQName(s),u=i.createAttributeNS(e,r);this.locator&&gs(n.getLocator(s),u),u.value=u.nodeValue=l,o.setAttributeNode(u)}},endElement:function(e,t,r){var n=this.currentElement,i=n.tagName;this.currentElement=n.parentNode},startPrefixMapping:function(e,t){},endPrefixMapping:function(e){},processingInstruction:function(e,t){var r=this.doc.createProcessingInstruction(e,t);this.locator&&gs(this.locator,r),Td(this,r)},ignorableWhitespace:function(e,t,r){},characters:function(e,t,r){if(e=US.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&&gs(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=US.apply(this,arguments);var n=this.doc.createComment(e);this.locator&&gs(this.locator,n),Td(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&&gs(this.locator,i),Td(this,i),this.doc.doctype=i}},warning:function(e){console.warn("[xmldom warning] "+e,fg(this.locator))},error:function(e){console.error("[xmldom error] "+e,fg(this.locator))},fatalError:function(e){throw new K8(e,this.locator)}};function fg(e){if(e)return`+@`+(e.systemId||"")+"#[line:"+e.lineNumber+",col:"+e.columnNumber+"]"}function US(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){au.prototype[e]=function(){return null}});function Td(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}Dd.__DOMHandler=au;Dd.normalizeLineEndings=qS;Dd.DOMParser=VS});var ys=v(Id=>{var WS=ug();Id.DOMImplementation=WS.DOMImplementation;Id.XMLSerializer=WS.XMLSerializer;Id.DOMParser=GS().DOMParser});var jS={};nn(jS,{CCFControlConstants:()=>zS,CCFPropertyConstants:()=>mg,CustomControlDataType:()=>F,CustomControlNames:()=>Mi,DefaultControlNameKeys:()=>pg,ICCModeEnum:()=>go,JSONParametersConstants:()=>hg,LookUpType:()=>Od,ManifestXMLConstants:()=>Xt,NumberType:()=>Pd,Usage:()=>ia});var zS,mg,hg,Xt,F,pg,Mi,go,ia,Od,Pd,oa=k(()=>{"use strict";zS={CCID:"CustomControlId",CCName:"DisplayName",Properties:"Properties",Mode:"ControlMode",AvailableOn:"AvailableOn",CCDescription:"description-key",ImageURL:"preview-image",TypeGroup:"type-group",DataSets:"DataSets",EntityNameKey:"EntityNameKey",NameSpace:"Name",OfTypeKey:"OfType"},mg={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"},hg={GroupDefinition:"GroupDefinition"},Xt={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"})(F||(F={}));(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"})(pg||(pg={}));(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"})(Mi||(Mi={}));(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"})(go||(go={}));(function(e){e[e.Bound=0]="Bound",e[e.Input=1]="Input",e[e.Output=2]="Output"})(ia||(ia={}));Od=[F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.LookupSimple],Pd=[F.WholeNone,F.WholeDuration,F.WholeLanguage,F.WholeTimeZone,F.FP,F.Decimal]});var bs,dr,su=k(()=>{"use strict";bs=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}},dr=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 HS={};nn(HS,{AttributeDataSourceType:()=>lu,AttributeDataSourceTypeMask:()=>Rd,AttributePrecisionSource:()=>uu,EntityAttributeDataSourceType:()=>aa,EntityAttributeDateTimeBehavior:()=>bg,EntityAttributeImeMode:()=>yg,EntityAttributePrecisionSource:()=>vg,EntityAttributeRequiredLevel:()=>yo,EntityAttributeType:()=>$,EntityAttributeTypeFormat:()=>W,EntityMetadataLookUpBase:()=>Ui,EntityResxKeyLookUp:()=>Ld,SourceTypeMask:()=>gg});var Ui,$,W,yo,aa,gg,lu,Rd,yg,bg,vg,uu,Ld,vs=k(()=>{"use strict";su();Ui=class{name;constructor(t){this.name=t}toString(){return this.name}getName(){return this.name}getDisplayNameResourceKey(){return Ld.getDisplayNameResourceKey(this.name)}};(function(e){e.BigInt="BigIntType",e.CalendarRulesType="CalendarRulesType",e.Currency="MoneyType",e.Customer="Customer",e.CustomerType="CustomerType",e.DateTime="DateTimeType",e.DecimalNumber="DecimalType",e.EntityNameType="EntityNameType",e.FloatingPointNumber="DoubleType",e.Image="ImageType",e.File="FileType",e.Lookup="Lookup",e.LookupType="LookupType",e.ManagedPropertyType="ManagedPropertyType",e.MultipleLineofText="MemoType",e.MultiSelectOptionSet="MultiSelectPicklistType",e.OptionSet="PicklistType",e.Owner="Owner",e.OwnerType="OwnerType",e.PartyList="PartyList",e.PartyListType="PartyListType",e.PrimaryNameAttributeType="String",e.SingleLineofText="StringType",e.State="StateType",e.Status="StatusType",e.Subject="Subject",e.TimeStamp="TimeStampType",e.TwoOptions="BooleanType",e.UniqueIdentifier="Uniqueidentifier",e.UniqueIdentifierType="UniqueidentifierType",e.VirtualType="VirtualType",e.WholeNumber="IntegerType"})($||($={}));(function(e){e.Email="Email",e.Text="Text",e.TextArea="TextArea",e.Url="Url",e.TickerSymbol="TickerSymbol",e.PhoneticGuide="PhoneticGuide",e.VersionNumber="VersionNumber",e.Phone="Phone",e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale",e.DateOnly="DateOnly",e.DateAndTime="DateAndTime",e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean",e.Regarding="Regarding"})(W||(W={}));yo=class extends Ui{constructor(t){super(t)}static get None(){return"None"}static get SystemRequired(){return"SystemRequired"}static get ApplicationRequired(){return"ApplicationRequired"}static get Recommended(){return"Recommended"}},aa=class e extends Ui{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Persistent(){return"Persistent"}static get Calculated(){return"Calculated"}static get Rollup(){return"Rollup"}GetValue(){return this.name===e.None?lu.Persistent:parseInt(lu[this.name])}},gg=class e extends Ui{constructor(t){super(t),t||(this.name=e.Undefined)}static get Undefined(){return"Undefined"}static get Simple(){return"Simple"}static get Related(){return"Related"}static get Logical(){return"Logical"}static get Calculated(){return"Calculated"}static get Rollup(){return"Rollup"}static get Invalid(){return"Invalid"}GetValue(){return parseInt(Rd[this.name])}};(function(e){e[e.Persistent=0]="Persistent",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup"})(lu||(lu={}));(function(e){e[e.Undefined=0]="Undefined",e[e.Simple=1]="Simple",e[e.Related=2]="Related",e[e.Logical=4]="Logical",e[e.Calculated=8]="Calculated",e[e.Rollup=16]="Rollup",e[e.Invalid=32]="Invalid"})(Rd||(Rd={}));yg=class e extends Ui{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Auto(){return"Auto"}static get Inactive(){return"Inactive"}static get Active(){return"Active"}static get Disabled(){return"Disabled"}},bg=class e extends Ui{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get UserLocal(){return"UserLocal"}static get DateOnly(){return"DateOnly"}static get TimeZoneIndependent(){return"TimeZoneIndependent"}},vg=class e extends Ui{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Attribute(){return"Attribute"}static get Organization(){return"Organization"}static get Currency(){return"Currency"}GetValue(){return this.name===e.None?uu.Currency:parseInt(uu[this.name])}};(function(e){e[e.Attribute=0]="Attribute",e[e.Organization=1]="Organization",e[e.Currency=2]="Currency"})(uu||(uu={}));Ld=class e{static resourceKeyMap=e.initResourceKeyMap();static initResourceKeyMap(){let t=new bs;return t.add($.TwoOptions,"SystemCustomization.type.bit.label"),t.add($.Customer,"SystemCustomization.type.customer.label"),t.add($.CustomerType,"SystemCustomization.type.customer.label"),t.add($.DateTime,"SystemCustomization.type.datetime.label"),t.add($.DecimalNumber,"SystemCustomization.type.decimal.label"),t.add($.FloatingPointNumber,"SystemCustomization.type.float.label"),t.add($.WholeNumber,"SystemCustomization.type.int.label"),t.add($.LookupType,"SystemCustomization.type.lookup.label"),t.add($.Lookup,"SystemCustomization.type.lookup.label"),t.add($.MultipleLineofText,"SystemCustomization.type.ntext.label"),t.add($.Currency,"SystemCustomization.type.money.label"),t.add($.Owner,"SystemCustomization.type.owner.label"),t.add($.OwnerType,"SystemCustomization.type.owner.label"),t.add($.PartyList,"SystemCustomization.type.partylist.label"),t.add($.PartyListType,"SystemCustomization.type.partylist.label"),t.add($.OptionSet,"SystemCustomization.type.picklist.label"),t.add($.State,"SystemCustomization.type.state.label"),t.add($.Status,"SystemCustomization.type.status.label"),t.add($.SingleLineofText,"SystemCustomization.type.nvarchar.label"),t.add($.UniqueIdentifier,"SystemCustomization.type.uniqueidentifier.label"),t.add($.UniqueIdentifierType,"SystemCustomization.type.uniqueidentifiertype.label"),t.add($.CalendarRulesType,"SystemCustomization.type.calendarrules.label"),t.add($.VirtualType,"SystemCustomization.type.virtual.label"),t.add($.BigInt,"SystemCustomization.type.bigint.label"),t.add($.ManagedPropertyType,"SystemCustomization.type.managedproperty.label"),t.add($.EntityNameType,"SystemCustomization.type.entityname.label"),t.add($.Image,"SystemCustomization.type.image.label"),t.add($.MultiSelectOptionSet,"SystemCustomization.type.multiselectpicklist.label"),t.add($.PrimaryNameAttributeType,"SystemCustomization.type.primaryname.label"),t.add($.LookupType,"SystemCustomization.type.lookuptype.label"),t.add($.Subject,"SystemCustomization.type.subject.label"),t.add(W.Email,"SystemCustomization.String.Format.email"),t.add(W.Text,"SystemCustomization.String.Format.text"),t.add(W.TextArea,"SystemCustomization.String.Format.textarea"),t.add(W.Url,"SystemCustomization.String.Format.url"),t.add(W.TickerSymbol,"SystemCustomization.String.Format.tickersymbol"),t.add(W.PhoneticGuide,"SystemCustomization.String.Format.phoneticguide"),t.add(W.VersionNumber,"SystemCustomization.String.Format.versionnumber"),t.add(W.Phone,"SystemCustomization.String.Format.phone"),t.add(W.None,"SystemCustomization.Integer.Format."),t.add(W.Duration,"SystemCustomization.Integer.Format.duration"),t.add(W.TimeZone,"SystemCustomization.Integer.Format.timezone"),t.add(W.Language,"SystemCustomization.Integer.Format.language"),t.add(W.Locale,"SystemCustomization.Integer.Format.language"),t.add(W.DateOnly,"SystemCustomization.DateTime.Format.date"),t.add(W.DateAndTime,"SystemCustomization.DateTime.Format.datetime"),t.add(W.Regarding,"SystemCustomization.Lookup.Format.regarding"),t.add(aa.Persistent,"SystemCustomization.String.Source.persistent"),t.add(aa.Calculated,"SystemCustomization.String.Source.calculated"),t.add(aa.Rollup,"SystemCustomization.String.Source.rollup"),t.add(aa.None,"SystemCustomization.String.Source.none"),t}static getDisplayNameResourceKey(t){return e.resourceKeyMap.getValue(t)}}});var cu=v(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.parsePcfManifest=ut.parseControlElement=ut.parseManifestRoot=ut.firstLevel=ut.attr=ut.elementChildren=ut.manifestTypesForColumn=ut.DEFAULT_TYPE_GROUPS=void 0;var Q8=ys(),H=(oa(),zr(jS)),ve=(vs(),zr(HS));ut.DEFAULT_TYPE_GROUPS={numbers:[H.CustomControlDataType.WholeNone,H.CustomControlDataType.FP,H.CustomControlDataType.Decimal,H.CustomControlDataType.Currency],text:[H.CustomControlDataType.SingleLineText,H.CustomControlDataType.SingleLineTextArea,H.CustomControlDataType.Multiple],lookup:[H.CustomControlDataType.LookupSimple,H.CustomControlDataType.LookupCustomer,H.CustomControlDataType.LookupOwner,H.CustomControlDataType.LookupPartyList,H.CustomControlDataType.LookupRegarding],dates:[H.CustomControlDataType.DateAndTimeDateOnly,H.CustomControlDataType.DateAndTimeDateAndTime],allFields:[H.CustomControlDataType.TwoOptions,H.CustomControlDataType.DateAndTimeDateOnly,H.CustomControlDataType.DateAndTimeDateAndTime,H.CustomControlDataType.FP,H.CustomControlDataType.Decimal,H.CustomControlDataType.WholeNone,H.CustomControlDataType.WholeDuration,H.CustomControlDataType.WholeTimeZone,H.CustomControlDataType.WholeLanguage,H.CustomControlDataType.LookupSimple,H.CustomControlDataType.LookupCustomer,H.CustomControlDataType.LookupOwner,H.CustomControlDataType.LookupPartyList,H.CustomControlDataType.LookupRegarding,H.CustomControlDataType.Multiple,H.CustomControlDataType.OptionSet,H.CustomControlDataType.SingleLineText,H.CustomControlDataType.SingleLineTextArea,H.CustomControlDataType.SingleLineEmail,H.CustomControlDataType.SingleLineURL,H.CustomControlDataType.SingleLineTickerSymbol,H.CustomControlDataType.SingleLinePhone]};var X8="Phone";function Z8(e,t,r){switch(e){case ve.EntityAttributeType.TwoOptions:return[H.CustomControlDataType.TwoOptions,H.CustomControlDataType.Boolean];case ve.EntityAttributeType.Customer:case ve.EntityAttributeType.CustomerType:return[H.CustomControlDataType.LookupCustomer];case ve.EntityAttributeType.DateTime:return t===ve.EntityAttributeTypeFormat.DateAndTime?[H.CustomControlDataType.DateAndTimeDateAndTime]:[H.CustomControlDataType.DateAndTimeDateOnly];case ve.EntityAttributeType.DecimalNumber:return[H.CustomControlDataType.Decimal];case ve.EntityAttributeType.FloatingPointNumber:return[H.CustomControlDataType.FP];case ve.EntityAttributeType.File:return[H.CustomControlDataType.File];case ve.EntityAttributeType.Image:return[H.CustomControlDataType.Image];case ve.EntityAttributeType.WholeNumber:return t===ve.EntityAttributeTypeFormat.Duration?[H.CustomControlDataType.WholeDuration]:t===ve.EntityAttributeTypeFormat.Language?[H.CustomControlDataType.WholeLanguage]:t===ve.EntityAttributeTypeFormat.TimeZone?[H.CustomControlDataType.WholeTimeZone]:[H.CustomControlDataType.WholeNone];case ve.EntityAttributeType.LookupType:case ve.EntityAttributeType.Lookup:return t===ve.EntityAttributeTypeFormat.Regarding?[H.CustomControlDataType.LookupRegarding]:[H.CustomControlDataType.LookupSimple];case ve.EntityAttributeType.MultipleLineofText:return[H.CustomControlDataType.Multiple];case ve.EntityAttributeType.Currency:return[H.CustomControlDataType.Currency];case ve.EntityAttributeType.Owner:case ve.EntityAttributeType.OwnerType:return[H.CustomControlDataType.LookupOwner];case ve.EntityAttributeType.PartyList:case ve.EntityAttributeType.PartyListType:return[H.CustomControlDataType.LookupPartyList];case ve.EntityAttributeType.Status:case ve.EntityAttributeType.OptionSet:return[H.CustomControlDataType.OptionSet];case ve.EntityAttributeType.SingleLineofText:switch(t){case ve.EntityAttributeTypeFormat.Email:return[H.CustomControlDataType.SingleLineEmail];case ve.EntityAttributeTypeFormat.Phone:return[H.CustomControlDataType.SingleLinePhone];case ve.EntityAttributeTypeFormat.Text:return r===X8?[H.CustomControlDataType.SingleLinePhone]:[H.CustomControlDataType.SingleLineText];case ve.EntityAttributeTypeFormat.TextArea:return[H.CustomControlDataType.SingleLineTextArea];case ve.EntityAttributeTypeFormat.TickerSymbol:return[H.CustomControlDataType.SingleLineTickerSymbol];case ve.EntityAttributeTypeFormat.Url:return[H.CustomControlDataType.SingleLineURL];default:return[H.CustomControlDataType.SingleLineText]}case ve.EntityAttributeType.MultiSelectOptionSet:return[H.CustomControlDataType.MultiSelectOptionSet];default:return null}}ut.manifestTypesForColumn=Z8;function wg(e){let t=[],r=e.childNodes;for(let n=0;n<r.length;n+=1)r[n].nodeType===1&&t.push(r[n]);return t}ut.elementChildren=wg;function On(e,t){return e.hasAttribute(t)?e.getAttribute(t):null}ut.attr=On;function ei(e,...t){return wg(e).filter(r=>t.includes(r.tagName))}ut.firstLevel=ei;function e9(e){let t=new Map;for(let r of ei(e,"type-group"))t.set(String(On(r,"name")),ei(r,"type").map(n=>String(n.textContent)));for(let[r,n]of t)t.set(r,n.sort());return t}function t9(e){let t=e.getElementsByTagName("AvailableOn")[0];if(!t)return{web:!0,phone:!0,tablet:!0};let r=new Set(wg(t).map(n=>n.tagName));return{web:r.has("web"),phone:r.has("phone"),tablet:r.has("tablet")}}var r9={input:"input",bound:"bound",output:"output"};function n9(e,t,r){let n=On(e,"usage"),i=n!==null&&r9[n]||"input",o=On(e,"default-value"),a=ei(e,"value").map(m=>{let p={name:On(m,"name"),value:String(m.textContent),isDefault:On(m,"default")==="true"};return p.isDefault&&(o=p.value),p}),s=On(e,"of-type-group"),l=s!==null?t.get(s):void 0,u=s!==null&&Object.prototype.hasOwnProperty.call(ut.DEFAULT_TYPE_GROUPS,s)?ut.DEFAULT_TYPE_GROUPS[s]:void 0,c=l?[...l]:u?[...u]:[],d=On(e,"of-type"),f=d!==null?d:c.length>0?c[0]:null;return{name:On(e,"name"),usage:i,ofType:d,typeGroupName:s,ofTypeGroup:c,defaultType:f||void 0,required:On(e,"required")==="true",hidden:On(e,"hidden")==="true",defaultValue:o,enumValues:a,isPrimary:r&&i==="bound"}}function KS(e){var t;let r=[],n=a=>s=>r.push(`${a}: ${s}`),i=new Q8.DOMParser({errorHandler:{warning:n("warning"),error:n("error"),fatalError:n("fatalError")}}).parseFromString(e,"text/xml"),o=(t=i?.documentElement)!==null&&t!==void 0?t:null;if(!o||r.length>0)throw new Error(`the control manifest does not parse cleanly${r.length>0?` (${r[0]})`:""}`);return o}ut.parseManifestRoot=KS;function JS(e){let t=ei(KS(e),"control")[0];if(!t)throw new Error("the control manifest has no <control> element");return t}ut.parseControlElement=JS;function i9(e){let t=JS(e),r=e9(t),n=ei(t,"data-set"),i=ei(t,"property"),o=ei(t,"groups"),a=[],s=!1;for(let u of i){let c=n9(u,r,n.length===0&&!s);s=s||c.isPrimary,a.push(c)}let l=n.length>0||(a.length>0?a[0].usage==="bound":o.some(u=>ei(u,"group").some(c=>ei(c,"data-set","property").length>0)));return{properties:a,hasDataset:n.length>0,hasGroups:o.length>0,isBound:l,availableOn:t9(t)}}ut.parsePcfManifest=i9});var QS=v(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});Cs.readPcfColumn=Cs.readControlManifest=void 0;var ws=oe(),o9=cu();function Cg(e,t,r){var n;let i=(n=r?.error)===null||n===void 0?void 0:n.message;return new Error(`${e}: HTTP ${t}${typeof i=="string"?` ${i}`:""}`)}async function a9(e,t){var r;let n="/customcontrols"+(0,ws.odataQuery)([["$select","name,manifest"],["$filter",`name eq '${(0,ws.odataLiteral)(t)}'`]]);try{let i=await e.get(n);if(i.status<200||i.status>=300)return{kind:"unavailable",error:Cg(`reading control "${t}"`,i.status,i.body)};let o=(r=i.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(o)||o.some(l=>l===null||typeof l!="object"))return{kind:"unavailable",error:new Error(`reading control "${t}": the answer is unreadable \u2014 expected an OData 'value' array of rows`)};let a=o;if(a.length===0)return{kind:"missing"};if(a.length>1)return{kind:"ambiguous"};let s=a[0].manifest;return typeof s!="string"?{kind:"unavailable",error:new Error(`control "${t}" has no manifest`)}:{kind:"found",value:(0,o9.parsePcfManifest)(s)}}catch(i){return{kind:"unavailable",error:i instanceof Error?i:new Error(String(i))}}}Cs.readControlManifest=a9;var s9=new Map([["StringType",{cast:"StringAttributeMetadata",select:"Format,FormatName"}],["MemoType",{cast:"MemoAttributeMetadata",select:"Format"}],["IntegerType",{cast:"IntegerAttributeMetadata",select:"Format"}],["DateTimeType",{cast:"DateTimeAttributeMetadata",select:"Format"}],["LookupType",{cast:"LookupAttributeMetadata",select:"Format"}]]);function YS(e){let t=e?.Value;return typeof t=="string"?t:void 0}async function l9(e,t,r,n){var i;let o=`/EntityDefinitions(LogicalName='${(0,ws.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,ws.odataPathLiteral)(r)}')`,a=n?.requireCreateEligibility===!0;try{let s=await e.get(o+(0,ws.odataQuery)([["$select",`LogicalName,AttributeType,AttributeTypeName,IsValidForForm,IsPrimaryId${a?",IsValidForCreate":""}`]]));if(s.status===404)return{kind:"missing"};if(s.status<200||s.status>=300)return{kind:"unavailable",error:Cg(`reading column "${r}"`,s.status,s.body)};let l=(i=s.body)!==null&&i!==void 0?i:{},u=YS(l.AttributeTypeName);if(!u)return{kind:"unavailable",error:new Error(`column "${r}" has no AttributeTypeName`)};if(a&&typeof l.IsValidForCreate!="boolean")return{kind:"unavailable",error:new Error(`column "${r}" has no IsValidForCreate`)};let c={logicalName:typeof l.LogicalName=="string"?l.LogicalName:r,attributeTypeName:u,isValidForForm:l.IsValidForForm===!0,isPrimaryId:l.IsPrimaryId===!0,...a?{isValidForCreate:l.IsValidForCreate}:{}},d=s9.get(u);if(d){let f=await e.get(`${o}/Microsoft.Dynamics.CRM.${d.cast}`+(0,ws.odataQuery)([["$select",d.select]]));if(f.status<200||f.status>=300)return{kind:"unavailable",error:Cg(`reading the format of column "${r}"`,f.status,f.body)};let m=f.body;if(m===null||typeof m!="object"||m.Format!==null&&typeof m.Format!="string")return{kind:"unavailable",error:new Error(`reading the format of column "${r}": the answer is unreadable \u2014 expected its Format (a string or null)`)};typeof m.Format=="string"&&(c.format=m.Format);let p=YS(m.FormatName);p&&(c.formatName=p)}return{kind:"found",value:c}}catch(s){return{kind:"unavailable",error:s instanceof Error?s:new Error(String(s))}}}Cs.readPcfColumn=l9});var sa=v(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});kd.DEFAULT_LCID=void 0;kd.DEFAULT_LCID=1033});var ct=v(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});ti.assignMissingIds=ti.pointerTouchesValueMap=ti.isValueMapKey=ti.newId=void 0;var u9=Xa();function XS(){return globalThis.crypto.randomUUID().toLowerCase()}ti.newId=XS;function c9(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Ag=new Set(["parameters","bag","expression","rawExpression","lookupValue","stepLabels","genPage","inputData","customControl"]);function d9(e){return Ag.has(e)}ti.isValueMapKey=d9;function f9(e){return u9.JsonPointer.parse(e).some(t=>Ag.has(t))}ti.pointerTouchesValueMap=f9;function p9(e){return Eg(e),e}ti.assignMissingIds=p9;function Eg(e){if(Array.isArray(e)){e.forEach(t=>Eg(t));return}if(c9(e)){(typeof e.id!="string"||e.id.length===0)&&(e.id=XS());for(let t of Object.keys(e))t==="id"||Ag.has(t)||Eg(e[t])}}});var Es=v(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.sendChangeSet=Or.partResponse=Or.postChangeSet=Or.parseChangeSetParts=Or.parseChangeSetStatuses=Or.renderChangeSet=void 0;var bo=Q(),Sg=fe(),ZS=ct(),du=oe();function Ng(e,t){let r=`batch_${(0,ZS.newId)()}`,n=`changeset_${(0,ZS.newId)()}`,i=t.map((s,l)=>String(l+1)),o=t.map((s,l)=>{var u,c;if(s.rawBody!==void 0&&s.contentType===void 0)throw new bo.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a raw body but no Content-Type`);let d=(u=s.rawBody)!==null&&u!==void 0?u:s.body===void 0?void 0:JSON.stringify(s.body);if(d!==void 0&&(d.includes(`--${n}`)||d.includes(`--${r}`)))throw new bo.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a body containing the batch boundary`);(0,du.assertNoControlChars)(s.path,"batch operation path"),s.etag&&(0,du.assertNoControlChars)(s.etag,"batch operation etag");let f=Object.entries((c=s.headers)!==null&&c!==void 0?c:{});for(let[m,p]of f)if((0,du.assertNoControlChars)(m,"batch operation header name"),(0,du.assertNoControlChars)(p,"batch operation header value"),!/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(m))throw new bo.InvalidArgumentError(`batch operation header name '${m}' is not a valid HTTP token`);return s.contentType!==void 0&&(0,du.assertNoControlChars)(s.contentType,"batch operation content type"),[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${i[l]}`,"",`${s.method} ${e.apiUrl(s.path)} HTTP/1.1`,...d===void 0?[]:[`Content-Type: ${s.rawBody!==void 0?s.contentType:"application/json;type=entry"}`],...e.solutionName?[`MSCRM.SolutionUniqueName: ${e.solutionName}`]:[],...s.etag?[`If-Match: ${s.etag}`]:[],...f.map(([m,p])=>`${m}: ${p}`),"",...d===void 0?[]:[d]].join(`\r`)});return{body:[`--${r}`,`Content-Type: multipart/mixed;boundary=${n}`,"",...o,`--${n}--`,`--${r}--`,""].join(`\r-`),batchId:r,contentIds:i}}vr.renderChangeSet=Mh;function ZA(e,t){var r;return(r=Uh(e,t))===null||r===void 0?void 0:r.map(n=>n.status)}vr.parseChangeSetStatuses=ZA;function Uh(e,t){var r,n,i,o;if(typeof e!="string"||e.length===0)return;let a=(r=/^--(\S+)\r?\n/.exec(e))===null||r===void 0?void 0:r[1];if(a===void 0||!e.trimEnd().endsWith(`--${a}--`))return;let s=(n=/Content-Type:\s*multipart\/mixed;\s*boundary=(\S+)/i.exec(e))===null||n===void 0?void 0:n[1];if(s===void 0||s===a)return;let l=e.split(`--${s}`);if(l.length<2||!/^--(\r?\n|$)/.test(l[l.length-1]))return;let u=new Set(t),c=[],d=new Set;for(let f of l.slice(1)){if(f.startsWith("--"))break;let p=f.indexOf(`\r+`),batchId:r,contentIds:i}}Or.renderChangeSet=Ng;function eN(e,t){var r;return(r=_g(e,t))===null||r===void 0?void 0:r.map(n=>n.status)}Or.parseChangeSetStatuses=eN;function _g(e,t){var r,n,i,o;if(typeof e!="string"||e.length===0)return;let a=(r=/^--(\S+)\r?\n/.exec(e))===null||r===void 0?void 0:r[1];if(a===void 0||!e.trimEnd().endsWith(`--${a}--`))return;let s=(n=/Content-Type:\s*multipart\/mixed;\s*boundary=(\S+)/i.exec(e))===null||n===void 0?void 0:n[1];if(s===void 0||s===a)return;let l=e.split(`--${s}`);if(l.length<2||!/^--(\r?\n|$)/.test(l[l.length-1]))return;let u=new Set(t),c=[],d=new Set;for(let f of l.slice(1)){if(f.startsWith("--"))break;let m=f.indexOf(`\r\r-`);if(p===-1)return;let m=f.slice(0,p),h=f.slice(p+4);if(!/^Content-Type:\s*application\/http\b/im.test(m))return;let g=/^HTTP\/1\.[01] (\d{3})\b/.exec(h);if(!g||((i=h.match(/^HTTP\/1\.[01] \d{3}\b/gm))!==null&&i!==void 0?i:[]).length!==1)return;let b=(o=/^Content-ID:\s*(\S+)/im.exec(m))===null||o===void 0?void 0:o[1];if(b===void 0||d.has(b)||!u.has(b))return;d.add(b),c.push({status:Number(g[1]),text:h,contentId:b})}return c.length===0?void 0:c}vr.parseChangeSetParts=Uh;async function dG(e,t,r){if(t.length===0)return;let{body:n,batchId:i,contentIds:o}=Mh(e,t),a=await e.postBatch(n,i),s=e.apiUrl("/$batch");if((0,Fh.ensureSuccess)(a,s),typeof a.body!="string"||a.body.length===0)throw new io.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`);let l=ZA(a.body,o);if(l===void 0)throw new io.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`);if(l.length!==t.length)throw new io.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the change set reported ${l.length} result(s) for ${t.length} operation(s)`);let u=l.find(c=>c<200||c>=300);if(u!==void 0)throw new io.ConnectionError(s,u,`atomic write of ${r} was rolled back: the change set reported HTTP ${u}`)}vr.postChangeSet=dG;function eS(e){let t=e.text.replace(/\r\n/g,`+`);if(m===-1)return;let p=f.slice(0,m),h=f.slice(m+4);if(!/^Content-Type:\s*application\/http\b/im.test(p))return;let g=/^HTTP\/1\.[01] (\d{3})\b/.exec(h);if(!g||((i=h.match(/^HTTP\/1\.[01] \d{3}\b/gm))!==null&&i!==void 0?i:[]).length!==1)return;let b=(o=/^Content-ID:\s*(\S+)/im.exec(p))===null||o===void 0?void 0:o[1];if(b===void 0||d.has(b)||!u.has(b))return;d.add(b),c.push({status:Number(g[1]),text:h,contentId:b})}return c.length===0?void 0:c}Or.parseChangeSetParts=_g;async function m9(e,t,r){if(t.length===0)return;let{body:n,batchId:i,contentIds:o}=Ng(e,t),a=await e.postBatch(n,i),s=e.apiUrl("/$batch");if((0,Sg.ensureSuccess)(a,s),typeof a.body!="string"||a.body.length===0)throw new bo.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`);let l=eN(a.body,o);if(l===void 0)throw new bo.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`);if(l.length!==t.length)throw new bo.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the change set reported ${l.length} result(s) for ${t.length} operation(s)`);let u=l.find(c=>c<200||c>=300);if(u!==void 0)throw new bo.ConnectionError(s,u,`atomic write of ${r} was rolled back: the change set reported HTTP ${u}`)}Or.postChangeSet=m9;function tN(e){let t=e.text.replace(/\r\n/g,``),r=t.indexOf(``),n=r===-1?t:t.slice(0,r),i=(r===-1?"":t.slice(r+2)).trim(),o={};for(let s of n.split(`-`).slice(1)){let l=s.indexOf(":");l>0&&(o[s.slice(0,l).trim()]=s.slice(l+1).trim())}let a=i===""?void 0:i;if(i!=="")try{a=JSON.parse(i)}catch{}return{status:e.status,headers:o,body:a}}vr.partResponse=eS;async function fG(e,t,r){let{body:n,batchId:i,contentIds:o}=Mh(e,t),a=await e.postBatch(n,i),s=e.apiUrl("/$batch"),l=Uh(a.body,o),u=l?.find(c=>c.status<200||c.status>=300);if(u&&(0,Fh.ensureSuccess)(eS(u),e.apiUrl(t[o.indexOf(u.contentId)].path)),(0,Fh.ensureSuccess)(a,s),!l||l.length!==t.length)throw new io.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the $batch response ${l?`reported ${l.length} result(s) for ${t.length} operation(s)`:"could not be parsed"}, so the outcome is unknown`);return o.map(c=>l.find(d=>d.contentId===c))}vr.sendChangeSet=fG});var sd=v(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.updateTable=ie.deleteAlternateKey=ie.createAlternateKey=ie.deleteGlobalOptionSet=ie.createGlobalOptionSet=ie.deleteRelationship=ie.deleteColumn=ie.updateColumn=ie.deleteTable=ie.createRelationship=ie.insertStatusValue=ie.createCustomerColumn=ie.createColumns=ie.setColumnVisualization=ie.getColumnVisualization=ie.createColumn=ie.createTable=ie.resolveEntitySetName=ie.pluralFallback=void 0;var Ae=ye(),ne=ue(),zn=Ko(),Ie=Q(),pG=Wl(),mG={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 Je(e,t){return{"@odata.type":"Microsoft.Dynamics.CRM.Label",LocalizedLabels:hG(e,t)}}var tS=65535;function hG(e,t){let r=(o,a)=>({"@odata.type":"Microsoft.Dynamics.CRM.LocalizedLabel",Label:o,LanguageCode:a});if(typeof e=="string")return[r(e,t)];let n=Object.entries(e);if(!n.length)throw new Ie.InvalidArgumentError("a localized label must contain at least one language");let i=new Set;return n.map(([o,a])=>{if(!/^[1-9]\d*$/.test(o))throw new Ie.InvalidArgumentError(`localized label key '${o}' is not an LCID (expected a canonical positive integer, e.g. 1033)`);let s=Number(o);if(s>tS)throw new Ie.InvalidArgumentError(`localized label LCID ${s} is out of range (1-${tS})`);if(i.has(s))throw new Ie.InvalidArgumentError(`localized label LCID ${s} is specified more than once`);if(i.add(s),typeof a!="string")throw new Ie.InvalidArgumentError(`localized label for LCID ${s} must be a string`);return r(a,s)})}function oS(e){return typeof e=="string"?`${e}s`:Object.fromEntries(Object.entries(e).map(([t,r])=>{if(typeof r!="string")throw new Ie.InvalidArgumentError(`localized label for LCID ${t} must be a string`);return[t,`${r}s`]}))}ie.pluralFallback=oS;function zl(e){return{Value:e,CanBeChanged:!0,ManagedPropertyLogicalName:"canmodifyrequirementlevelsettings"}}function Vh(e){let t=e.indexOf("_");return t>0?e.slice(0,t):e}function rS(e,t,r){let n=e[t];n&&typeof n=="object"?n.Value=r:e[t]={Value:r}}function jl(e){let t=(0,Ae.readCreatedId)(e,"MetadataId");if(!t)throw new Ie.InvalidArgumentError("Dataverse did not return a MetadataId for the created metadata component");return t}function gG(e,t,r){var n,i,o,a,s,l,u,c,d,f,p,m,h,g,b,w,E,A,L,R,I,D,O,$;if(t.defaultValue!==void 0&&e!=="boolean")throw new Ie.InvalidArgumentError(`createColumn: 'defaultValue' applies to boolean columns, but '${t.schemaName}' is of type '${e}'.`);if(t.integerFormat!==void 0&&e!=="integer")throw new Ie.InvalidArgumentError(`createColumn: 'integerFormat' applies to integer columns, but '${t.schemaName}' is of type '${e}'.`);switch(e){case"string":return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},MaxLength:(n=t.maxLength)!==null&&n!==void 0?n:100,FormatName:{Value:(i=t.stringFormat)!==null&&i!==void 0?i:"Text"}};case"memo":return{"@odata.type":"Microsoft.Dynamics.CRM.MemoAttributeMetadata",AttributeType:"Memo",AttributeTypeName:{Value:"MemoType"},MaxLength:(o=t.maxLength)!==null&&o!==void 0?o:2e3,Format:"TextArea"};case"integer":return{"@odata.type":"Microsoft.Dynamics.CRM.IntegerAttributeMetadata",AttributeType:"Integer",AttributeTypeName:{Value:"IntegerType"},Format:(a=t.integerFormat)!==null&&a!==void 0?a:"None",MinValue:(s=t.minValue)!==null&&s!==void 0?s:-2147483648,MaxValue:(l=t.maxValue)!==null&&l!==void 0?l:2147483647};case"bigint":return{"@odata.type":"Microsoft.Dynamics.CRM.BigIntAttributeMetadata",AttributeType:"BigInt",AttributeTypeName:{Value:"BigIntType"}};case"double":return{"@odata.type":"Microsoft.Dynamics.CRM.DoubleAttributeMetadata",AttributeType:"Double",AttributeTypeName:{Value:"DoubleType"},Precision:(u=t.precision)!==null&&u!==void 0?u:2,MinValue:(c=t.minValue)!==null&&c!==void 0?c:-1e11,MaxValue:(d=t.maxValue)!==null&&d!==void 0?d:1e11};case"decimal":return{"@odata.type":"Microsoft.Dynamics.CRM.DecimalAttributeMetadata",AttributeType:"Decimal",AttributeTypeName:{Value:"DecimalType"},Precision:(f=t.precision)!==null&&f!==void 0?f:2,MinValue:(p=t.minValue)!==null&&p!==void 0?p:-1e11,MaxValue:(m=t.maxValue)!==null&&m!==void 0?m:1e11};case"money":return{"@odata.type":"Microsoft.Dynamics.CRM.MoneyAttributeMetadata",AttributeType:"Money",AttributeTypeName:{Value:"MoneyType"},Precision:(h=t.precision)!==null&&h!==void 0?h:2,PrecisionSource:2,MinValue:(g=t.minValue)!==null&&g!==void 0?g:0,MaxValue:(b=t.maxValue)!==null&&b!==void 0?b:1e9};case"boolean":return{"@odata.type":"Microsoft.Dynamics.CRM.BooleanAttributeMetadata",AttributeType:"Boolean",AttributeTypeName:{Value:"BooleanType"},DefaultValue:(w=t.defaultValue)!==null&&w!==void 0?w:!1,OptionSet:{"@odata.type":"Microsoft.Dynamics.CRM.BooleanOptionSetMetadata",TrueOption:{Value:1,Label:Je((E=t.trueLabel)!==null&&E!==void 0?E:"Yes",r)},FalseOption:{Value:0,Label:Je((A=t.falseLabel)!==null&&A!==void 0?A:"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 nS(t,r,!1);case"multiChoice":return nS(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:(I=t.isPrimaryImage)!==null&&I!==void 0?I:!1,MaxSizeInKB:(D=t.maxSizeKb)!==null&&D!==void 0?D:10240};case"autonumber":return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},FormatName:{Value:"Text"},MaxLength:(O=t.maxLength)!==null&&O!==void 0?O:100,AutoNumberFormat:($=t.autoNumberFormat)!==null&&$!==void 0?$:""};default:throw new Ie.InvalidArgumentError(`unsupported column type '${String(e)}'`)}}function nS(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,ne.normalizeGuid)(e.globalChoiceMetadataId,"globalChoiceMetadataId")})`,i;if(!e.options||e.options.length===0)throw new Ie.InvalidArgumentError(`choice column '${e.schemaName}' requires at least one option (or a globalChoiceMetadataId)`);return i.OptionSet={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",IsGlobal:!1,OptionSetType:"Picklist",Options:e.options.map(o=>({Value:o.value,Label:Je(o.label,t)}))},i}var Bh=new WeakMap;async function yG(e,t){var r,n;let i=(r=Bh.get(e))===null||r===void 0?void 0:r.get(t);if(i)return i;let o=`/EntityDefinitions(LogicalName='${(0,ne.odataPathLiteral)(t)}')${(0,ne.odataQuery)([["$select","EntitySetName"]])}`,s=(n=(0,Ae.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.EntitySetName;if(!s)throw new Ie.InvalidArgumentError(`could not resolve EntitySetName for '${t}'`);(0,ne.assertODataName)(s,`server-derived EntitySetName for '${t}'`);let l=Bh.get(e);return l||(l=new Map,Bh.set(e,l)),l.set(t,s),s}ie.resolveEntitySetName=yG;async function bG(e,t){var r,n,i,o,a,s,l,u,c,d,f,p,m,h,g;let b=(r=t.languageCode)!==null&&r!==void 0?r:zn.DEFAULT_LCID,w=Vh(t.schemaName),E=(n=t.primaryColumnSchemaName)!==null&&n!==void 0?n:`${w}_Name`,A={"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},SchemaName:E,RequiredLevel:zl("None"),MaxLength:(i=t.primaryColumnMaxLength)!==null&&i!==void 0?i:100,FormatName:{Value:"Text"},DisplayName:Je((o=t.primaryColumnDisplayName)!==null&&o!==void 0?o:"Name",b),IsPrimaryName:!0};t.primaryColumnAutoNumberFormat&&(A.AutoNumberFormat=t.primaryColumnAutoNumberFormat),t.columns&&lS(t.columns,"createTable");let L={"@odata.type":"Microsoft.Dynamics.CRM.EntityMetadata",SchemaName:t.schemaName,DisplayName:Je(t.displayName,b),DisplayCollectionName:Je((a=t.pluralName)!==null&&a!==void 0?a:oS(t.displayName),b),OwnershipType:(s=t.ownership)!==null&&s!==void 0?s:"UserOwned",IsActivity:!1,HasActivities:(l=t.hasActivities)!==null&&l!==void 0?l:!1,HasNotes:(u=t.hasNotes)!==null&&u!==void 0?u:!1,Attributes:[A,...((c=t.columns)!==null&&c!==void 0?c:[]).map(Le=>Gh(Le,b))]};t.description&&(L.Description=Je(t.description,b));let R="/EntityDefinitions",I=(0,Ae.ensureSuccess)(await e.post(R,L),e.apiUrl(R)),D=jl(I),O=`/EntityDefinitions(${D})`+(0,ne.odataQuery)([["$select","LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute"]]),$=Math.max(1,Math.trunc((d=t.readBackAttempts)!==null&&d!==void 0?d:6)),K=Math.max(0,(f=t.readBackDelayMs)!==null&&f!==void 0?f:1e3),Re;for(let Le=1;Le<=$;Le+=1){let at=await e.get(O);if(at.status>=200&&at.status<300){Re=at;break}at.status!==404&&(0,Ae.ensureSuccess)(at,e.apiUrl(O)),Le<$&&K>0&&await new Promise(ge=>setTimeout(ge,K))}if(!Re)throw new Ie.SdkError("TABLE_METADATA_NOT_VISIBLE",`Table '${t.schemaName}' WAS CREATED (MetadataId ${D}) but its metadata was still not readable after ${$} attempt(s). Do NOT re-run the create \u2014 it will collide on the schema name. Re-read /EntityDefinitions(${D}) once the environment catches up, or raise 'readBackAttempts'.`);let It=Re.body;return{logicalName:(p=It.LogicalName)!==null&&p!==void 0?p:t.schemaName.toLowerCase(),metadataId:D,entitySetName:(m=It.EntitySetName)!==null&&m!==void 0?m:"",primaryIdAttribute:(h=It.PrimaryIdAttribute)!==null&&h!==void 0?h:`${t.schemaName.toLowerCase()}id`,primaryNameAttribute:(g=It.PrimaryNameAttribute)!==null&&g!==void 0?g:E.toLowerCase()}}ie.createTable=bG;function Gh(e,t){var r,n;let i=(r=e.languageCode)!==null&&r!==void 0?r:t,o={...gG(e.type,e,i),SchemaName:e.schemaName,RequiredLevel:zl((n=e.required)!==null&&n!==void 0?n:"None"),DisplayName:Je(e.displayName,i)};return e.description&&(o.Description=Je(e.description,i)),e.sourceType&&e.sourceType!=="Simple"&&(o.SourceType=e.sourceType==="Rollup"?2:1,e.formulaDefinition&&(o.FormulaDefinition=e.formulaDefinition)),aS(o,e),o}function aS(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 vG(e,t,r){var n;let i=Gh(r,(n=r.languageCode)!==null&&n!==void 0?n:zn.DEFAULT_LCID),o=`/EntityDefinitions(LogicalName='${(0,ne.odataPathLiteral)(t)}')/Attributes`,a=(0,Ae.ensureSuccess)(await e.post(o,i),e.apiUrl(o)),s={logicalName:r.schemaName.toLowerCase(),metadataId:jl(a)};if(r.visualization&&r.visualization!=="None")try{await dS(e,t,s.logicalName,s.metadataId,r.visualization)}catch(l){let u=new Ie.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(0,Ie.attachCause)(u,l),u}return s}ie.createColumn=vG;var ss="/controlconfigurations",sS="CustomRenderersConfiguration",qh={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 lS(e,t){let r=e.find(n=>n.visualization&&n.visualization!=="None");if(r)throw new Ie.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 uS(e){return JSON.stringify({type:qh[e]})}function wG(e){if(!e)return"None";let t;try{t=JSON.parse(e)}catch{return"None"}let r=t?.type,n=Object.keys(qh).find(i=>qh[i]===r);return n??"None"}async function cS(e,t,r){var n,i;let o=`entitylogicalname eq '${(0,ne.odataLiteral)(t)}' and Attribute/logicalname eq '${(0,ne.odataLiteral)(r)}'`,a=`${ss}${(0,ne.odataQuery)([["$select","name,uniquename,metadatajson"],["$expand","Attribute($select=name,logicalname)"],["$filter",o]])}`,l=(i=(n=(0,Ae.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[],u=r.toLowerCase();return l.filter(c=>{var d,f;return((f=(d=c.Attribute)===null||d===void 0?void 0:d.logicalname)===null||f===void 0?void 0:f.toLowerCase())===u})}async function CG(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,ne.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,ne.odataPathLiteral)(r)}')${(0,ne.odataQuery)([["$select","MetadataId"]])}`,a=(n=(0,Ae.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||n===void 0?void 0:n.MetadataId;if(!a)throw new Ie.InvalidArgumentError(`cannot resolve column '${r}' on '${t}' to set its visualization`);return(0,ne.normalizeGuid)(a,"MetadataId")}async function dS(e,t,r,n,i){let o={name:sS,uniquename:`msdyn_${t}_${r}_customrenderers`,metadatajson:uS(i),"[email protected]":`/attributes(${(0,ne.normalizeGuid)(n,"MetadataId")})`,entitylogicalname:t};(0,Ae.ensureSuccess)(await e.post(ss,o),e.apiUrl(ss))}async function EG(e,t,r){var n;let i=await cS(e,t,r);return wG((n=i[0])===null||n===void 0?void 0:n.metadatajson)}ie.getColumnVisualization=EG;async function AG(e,t,r,n){let o=(await cS(e,t,r)).map(u=>u.controlconfigurationid).filter(u=>!!u);if(n==="None"){for(let u of o){let c=`${ss}(${(0,ne.normalizeGuid)(u,"controlconfigurationid")})`;(0,Ae.ensureSuccess)(await e.delete(c),e.apiUrl(c))}return}let[a,...s]=o,l=await CG(e,t,r);if(a){let u=`${ss}(${(0,ne.normalizeGuid)(a,"controlconfigurationid")})`,c={name:sS,metadatajson:uS(n),"[email protected]":`/attributes(${l})`,entitylogicalname:t};(0,Ae.ensureSuccess)(await e.patch(u,c),e.apiUrl(u))}else await dS(e,t,r,l,n);for(let u of s){let c=`${ss}(${(0,ne.normalizeGuid)(u,"controlconfigurationid")})`;(0,Ae.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}ie.setColumnVisualization=AG;async function SG(e,t,r){if(r.length===0)return;if(lS(r,"createColumns"),!e.supportsAtomicBatch)throw new Ie.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,ne.odataPathLiteral)(t)}')/Attributes`;await(0,pG.postChangeSet)(e,r.map(i=>{var o;return{method:"POST",path:n,body:Gh(i,(o=i.languageCode)!==null&&o!==void 0?o:zn.DEFAULT_LCID)}}),`${r.length} column(s) on '${t}'`)}ie.createColumns=SG;async function NG(e,t,r){var n,i,o,a;let s=(n=r.languageCode)!==null&&n!==void 0?n:zn.DEFAULT_LCID,l=Vh(r.schemaName),u=(i=r.accountRelationshipName)!==null&&i!==void 0?i:`${l}_${t}_account`,c=(o=r.contactRelationshipName)!==null&&o!==void 0?o:`${l}_${t}_contact`,d={Lookup:{"@odata.type":"Microsoft.Dynamics.CRM.ComplexLookupAttributeMetadata",SchemaName:r.schemaName,DisplayName:Je(r.displayName,s),RequiredLevel:zl((a=r.required)!==null&&a!==void 0?a:"None"),Targets:["account","contact"]},OneToManyRelationships:[{"@odata.type":"Microsoft.Dynamics.CRM.ComplexOneToManyRelationshipMetadata",SchemaName:u,ReferencedEntity:"account",ReferencingEntity:t},{"@odata.type":"Microsoft.Dynamics.CRM.ComplexOneToManyRelationshipMetadata",SchemaName:c,ReferencedEntity:"contact",ReferencingEntity:t}]};return(0,Ae.ensureSuccess)(await e.post("/CreateCustomerRelationships",d),e.apiUrl("/CreateCustomerRelationships")),{logicalName:r.schemaName.toLowerCase(),metadataId:""}}ie.createCustomerColumn=NG;async function _G(e,t,r){var n,i,o,a,s;let l=(n=r.languageCode)!==null&&n!==void 0?n:zn.DEFAULT_LCID,u={EntityLogicalName:t,AttributeLogicalName:"statuscode",Label:Je(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,Ae.ensureSuccess)(await e.post("/InsertStatusValue",u),e.apiUrl("/InsertStatusValue"));return Number((s=(a=(o=c.body)===null||o===void 0?void 0:o.NewOptionValue)!==null&&a!==void 0?a:r.value)!==null&&s!==void 0?s:0)}ie.insertStatusValue=_G;async function TG(e,t){var r,n,i,o,a;let s=(r=t.languageCode)!==null&&r!==void 0?r:zn.DEFAULT_LCID,l,u;if(t.type==="OneToMany"){if(!t.referencedEntity||!t.referencingEntity)throw new Ie.InvalidArgumentError("OneToMany relationship requires referencedEntity and referencingEntity");let f=(n=t.lookupSchemaName)!==null&&n!==void 0?n:`${Vh(t.schemaName)}_${t.referencedEntity}Id`;u=f.toLowerCase(),l={"@odata.type":"Microsoft.Dynamics.CRM.OneToManyRelationshipMetadata",SchemaName:t.schemaName,ReferencedEntity:t.referencedEntity,ReferencingEntity:t.referencingEntity,Lookup:{"@odata.type":"Microsoft.Dynamics.CRM.LookupAttributeMetadata",AttributeType:"Lookup",AttributeTypeName:{Value:"LookupType"},SchemaName:f,RequiredLevel:zl((i=t.lookupRequired)!==null&&i!==void 0?i:"None"),DisplayName:Je((o=t.lookupDisplayName)!==null&&o!==void 0?o:t.referencedEntity,s)}}}else{if(!t.entity1||!t.entity2)throw new Ie.InvalidArgumentError("ManyToMany relationship requires entity1 and entity2");l={"@odata.type":"Microsoft.Dynamics.CRM.ManyToManyRelationshipMetadata",SchemaName:t.schemaName,IntersectEntityName:(a=t.intersectEntityName)!==null&&a!==void 0?a:t.schemaName.toLowerCase(),Entity1LogicalName:t.entity1,Entity2LogicalName:t.entity2}}let c="/RelationshipDefinitions",d=(0,Ae.ensureSuccess)(await e.post(c,l),e.apiUrl(c));return{schemaName:t.schemaName,metadataId:jl(d),lookupLogicalName:u}}ie.createRelationship=TG;async function DG(e,t){let r=`/EntityDefinitions(LogicalName='${(0,ne.odataPathLiteral)(t)}')`;(0,Ae.ensureSuccess)(await e.delete(r),e.apiUrl(r))}ie.deleteTable=DG;async function IG(e,t,r,n){var i,o;let a=(i=n.languageCode)!==null&&i!==void 0?i:zn.DEFAULT_LCID,s=`/EntityDefinitions(LogicalName='${(0,ne.odataPathLiteral)(t)}')/Attributes`,l=`${s}(LogicalName='${(0,ne.odataPathLiteral)(r)}')${(0,ne.odataQuery)([["$select","MetadataId,AttributeType"]])}`,c=(0,Ae.ensureSuccess)(await e.get(l),e.apiUrl(l)).body,d=mG[(o=c.AttributeType)!==null&&o!==void 0?o:""];if(!c.MetadataId||!d)throw new Ie.InvalidArgumentError(`cannot update column '${r}' on '${t}' (type '${c.AttributeType}' not supported)`);let f=(0,ne.normalizeGuid)(c.MetadataId,"MetadataId"),p=`${s}(${f})/${d}`,m=(0,Ae.ensureSuccess)(await e.get(p),e.apiUrl(p)).body;for(let g of Object.keys(m))g.startsWith("@odata.")&&delete m[g];if(m["@odata.type"]=d,n.displayName!==void 0&&(m.DisplayName=Je(n.displayName,a)),n.description!==void 0&&(m.Description=Je(n.description,a)),n.required!==void 0&&(m.RequiredLevel=zl(n.required)),n.maxLength!==void 0&&(m.MaxLength=n.maxLength),n.autoNumberFormat!==void 0&&(m.AutoNumberFormat=n.autoNumberFormat),n.defaultValue!==void 0&&c.AttributeType!=="Boolean")throw new Ie.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 Ie.InvalidArgumentError(`updateColumn: 'integerFormat' applies to Integer columns, but '${r}' on '${t}' is of type '${c.AttributeType}'.`);n.defaultValue!==void 0&&(m.DefaultValue=n.defaultValue),n.integerFormat!==void 0&&(m.Format=n.integerFormat),aS(m,n);let h=`${s}(${f})`;(0,Ae.ensureSuccess)(await e.put(h,m,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(h))}ie.updateColumn=IG;async function OG(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,ne.odataPathLiteral)(t)}')/Attributes`,o=`${i}(LogicalName='${(0,ne.odataPathLiteral)(r)}')${(0,ne.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,Ae.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new Ie.InvalidArgumentError(`column '${r}' not found on '${t}'`);let l=`${i}(${(0,ne.normalizeGuid)(s,"MetadataId")})`;(0,Ae.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteColumn=OG;async function PG(e,t){var r,n,i;let o=`/RelationshipDefinitions${(0,ne.odataQuery)([["$filter",`SchemaName eq '${(0,ne.odataLiteral)(t)}'`],["$select","MetadataId"]])}`,s=(i=(n=(r=(0,Ae.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||r===void 0?void 0:r.value)===null||n===void 0?void 0:n[0])===null||i===void 0?void 0:i.MetadataId;if(!s)throw new Ie.InvalidArgumentError(`relationship '${t}' not found`);let l=`/RelationshipDefinitions(${(0,ne.normalizeGuid)(s,"MetadataId")})`;(0,Ae.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteRelationship=PG;async function iS(e,t){var r;let n=`/GlobalOptionSetDefinitions(Name='${(0,ne.odataPathLiteral)(t)}')${(0,ne.odataQuery)([["$select","MetadataId"]])}`,i=await e.get(n);if(i.status===404)return;let a=(r=(0,Ae.ensureSuccess)(i,e.apiUrl(n)).body)===null||r===void 0?void 0:r.MetadataId;return a?(0,ne.normalizeGuid)(a,"MetadataId"):void 0}async function RG(e,t){var r;let n=t.name.toLowerCase(),i=await iS(e,n);if(i)return{name:n,metadataId:i};let o=(r=t.languageCode)!==null&&r!==void 0?r:zn.DEFAULT_LCID,a={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",Name:n,DisplayName:Je(t.displayName,o),IsGlobal:!0,OptionSetType:"Picklist",Options:t.options.map(l=>({Value:l.value,Label:Je(l.label,o)}))};t.description&&(a.Description=Je(t.description,o));let s="/GlobalOptionSetDefinitions";try{let l=(0,Ae.ensureSuccess)(await e.post(s,a),e.apiUrl(s));return{name:n,metadataId:jl(l)}}catch(l){let u;try{u=await iS(e,n)}catch{u=void 0}if(u)return{name:n,metadataId:u};throw l}}ie.createGlobalOptionSet=RG;async function LG(e,t){let r=`/GlobalOptionSetDefinitions(Name='${(0,ne.odataPathLiteral)(t.toLowerCase())}')`;(0,Ae.ensureSuccess)(await e.delete(r),e.apiUrl(r))}ie.deleteGlobalOptionSet=LG;async function kG(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:zn.DEFAULT_LCID,o={"@odata.type":"Microsoft.Dynamics.CRM.EntityKeyMetadata",SchemaName:r.schemaName,DisplayName:Je(r.displayName,i),KeyAttributes:r.keyAttributes},a=`/EntityDefinitions(LogicalName='${(0,ne.odataPathLiteral)(t)}')/Keys`,s=(0,Ae.ensureSuccess)(await e.post(a,o),e.apiUrl(a));return{logicalName:r.schemaName.toLowerCase(),metadataId:jl(s)}}ie.createAlternateKey=kG;async function xG(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,ne.odataPathLiteral)(t)}')/Keys`,o=`${i}(LogicalName='${(0,ne.odataPathLiteral)(r.toLowerCase())}')${(0,ne.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,Ae.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new Ie.InvalidArgumentError(`alternate key '${r}' not found on '${t}'`);let l=`${i}(${(0,ne.normalizeGuid)(s,"MetadataId")})`;(0,Ae.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteAlternateKey=xG;async function $G(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:zn.DEFAULT_LCID,o=`/EntityDefinitions(LogicalName='${(0,ne.odataPathLiteral)(t)}')`,s=(0,Ae.ensureSuccess)(await e.get(o),e.apiUrl(o)).body,l=s.MetadataId;if(!l)throw new Ie.InvalidArgumentError(`table '${t}' not found`);let u=(0,ne.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=Je(r.displayName,i)),r.pluralName!==void 0&&(s.DisplayCollectionName=Je(r.pluralName,i)),r.description!==void 0&&(s.Description=Je(r.description,i)),r.auditEnabled!==void 0&&rS(s,"IsAuditEnabled",r.auditEnabled),r.duplicateDetectionEnabled!==void 0&&rS(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,Ae.ensureSuccess)(await e.put(c,s,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(c))}ie.updateTable=$G});var ao=v(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.rebuildRaw=wr.assembleChildren=wr.spliceChildren=wr.mergeAttrs=wr.rawFromNode=wr.emptyBag=void 0;var oo=Q(),fS=1e6,ud=512;function FG(){return{a:[],c:[]}}wr.emptyBag=FG;function pS(e,t=0){if(t>ud)throw new oo.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${ud}`);return{n:e.getNodeName(),a:e.getAllProperties().map(r=>[r.key,r.value]),c:e.getAllChildren().map(r=>pS(r,t+1))}}wr.rawFromNode=pS;function MG(e,t,r=[]){let n=new Map;for(let[s,l]of t)n.set(s,l);let i=new Set(r.filter(s=>!n.has(s))),o=new Set,a=[];for(let[s,l]of e)i.has(s)||(n.has(s)?a.push([s,n.get(s)]):a.push([s,l]),o.add(s));for(let[s,l]of t)o.has(s)||(a.push([s,l]),o.add(s));return a}wr.mergeAttrs=MG;function ld(e,t){let r=new Set;for(let s of e){let l=s.i;if(!Number.isInteger(l)||l<0||l>fS)throw new oo.InvalidArgumentError(`Bag child index must be an integer in [0, ${fS}] (got ${String(l)})`);if(r.has(l))throw new oo.InvalidArgumentError(`Duplicate bag child index ${l}`);r.add(l)}let n=[...e].sort((s,l)=>s.i-l.i),i=[],o=0,a=0;for(let s of n){for(;a<s.i&&o<t.length;)i.push(t[o]),o+=1,a+=1;a<s.i&&(a=s.i),i.push(s.node),a+=1}for(;o<t.length;)i.push(t[o]),o+=1;return i}wr.spliceChildren=ld;function UG(e,t){if(e.w){let r={n:e.w.n,a:e.w.a.map(n=>[n[0],n[1]]),c:ld(e.w.c,t)};return ld(e.c,[r])}return ld(e.c,t)}wr.assembleChildren=UG;function mS(e,t,r,n=0){if(n>ud)throw new oo.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${ud}`);BG(e,n);let i=t.make(e.n,r);for(let[o,a]of e.a)t.setProp(i,o,a);for(let o of e.c)t.addChild(i,mS(o,t,i,n+1));return i}wr.rebuildRaw=mS;function BG(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new oo.InvalidArgumentError(`Malformed hybrid node at depth ${t}: expected a JSON object`);let r=e;if(typeof r.n!="string")throw new oo.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 oo.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 oo.InvalidArgumentError(`Malformed hybrid node '${r.n}': each attribute must be a [string, string] pair`)}});var so=v(cd=>{"use strict";Object.defineProperty(cd,"__esModule",{value:!0});cd.installDomShim=void 0;var hS=rs(),gS=!1,qG={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 VG(){if(gS)return;let e=globalThis;typeof e.DOMParser>"u"&&(e.DOMParser=hS.DOMParser),typeof e.XMLSerializer>"u"&&(e.XMLSerializer=hS.XMLSerializer),typeof e.Node>"u"&&(e.Node=qG),gS=!0}cd.installDomShim=VG});var lo=v(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.projectElementBag=Ye.serializeNode=Ye.domEngine=Ye.nodeLikeFromDom=Ye.parseXmlRoot=Ye.EMPTY_FORM_SENTINEL=Ye.TEXT_SENTINEL=void 0;var GG=ao(),Hl=Q(),WG=so();Ye.TEXT_SENTINEL="#text";Ye.EMPTY_FORM_SENTINEL="#empty";var fd=new WeakSet;function zG(e,t){(0,WG.installDomShim)();let r=e&&e.trim()!==""?e:t,i=new DOMParser().parseFromString(r,"text/xml").documentElement;if(!i)throw new Hl.InvalidArgumentError("XML source has no root element (empty or malformed input)");return HG(i),KG(i),QG(i,r),i}Ye.parseXmlRoot=zG;var jG=new Set([1,3]);function HG(e){let t=[e];for(;t.length>0;){let n=t.pop().childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];if(!jG.has(o.nodeType))throw new Hl.InvalidArgumentError(`Unsupported XML node type ${o.nodeType} (CDATA / comment / processing-instruction) is outside the hybrid projection's lossless grammar and cannot be round-tripped`);o.nodeType===1&&t.push(o)}}}function KG(e){var t,r;let n=(t=e.ownerDocument)!==null&&t!==void 0?t:e.parentNode;if(!n)return;let i=n.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];if(a!==e&&!(a.nodeType===3&&((r=a.nodeValue)!==null&&r!==void 0?r:"").trim()===""))throw new Hl.InvalidArgumentError(`Unsupported document-level XML node (type ${a.nodeType}: declaration / comment / processing-instruction outside the root element) cannot be round-tripped`)}}function JG(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 YG(e){let t=[],r=[e];for(;r.length>0;){let n=r.pop();t.push(n);let i=n.childNodes;for(let o=i.length-1;o>=0;o-=1){let a=i[o];a.nodeType===1&&r.push(a)}}return t}function bS(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 QG(e,t){let r=JG(t),n=YG(e),i=Math.min(r.length,n.length);for(let o=0;o<i;o+=1){if(r[o])continue;let a=n[o];bS(a)||fd.add(a)}}function Wh(e){let t=e.nodeType===3;return{getNodeName:()=>t?Ye.TEXT_SENTINEL:e.tagName,getAllProperties:()=>{var r;if(t)return[{key:Ye.TEXT_SENTINEL,value:(r=e.nodeValue)!==null&&r!==void 0?r:""}];let n=e.attributes,i=[];for(let o=0;o<n.length;o+=1)i.push({key:n[o].name,value:n[o].value});return fd.has(e)&&!bS(e)&&i.push({key:Ye.EMPTY_FORM_SENTINEL,value:"1"}),i},getAllChildren:()=>{if(t)return[];let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];(o.nodeType===1||o.nodeType===3)&&r.push(Wh(o))}return r}}}Ye.nodeLikeFromDom=Wh;function XG(e){return{make:t=>t===Ye.TEXT_SENTINEL?e.createTextNode(""):e.createElement(t),setProp:(t,r,n)=>{t.nodeType===3?t.nodeValue=n:r===Ye.EMPTY_FORM_SENTINEL?fd.add(t):t.setAttribute(r,n)},addChild:(t,r)=>{t.appendChild(r)}}}Ye.domEngine=XG;function vS(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 dd(r);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))throw dd(r);t+=1;continue}if(r>=56320&&r<=57343)throw dd(r)}}function dd(e){let t=e.toString(16).toUpperCase().padStart(4,"0");return new Hl.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 ZG(e){return vS(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/\r/g,"
").replace(/\n/g,"
").replace(/\t/g,"	")}function e9(e){return vS(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function t9(e){return wS(e,0)}Ye.serializeNode=t9;var yS=512;function wS(e,t){var r;if(t>yS)throw new Hl.InvalidArgumentError(`XML nesting exceeds the maximum supported depth of ${yS}`);if(e.nodeType===3)return e9((r=e.nodeValue)!==null&&r!==void 0?r:"");let n=e,i="<"+n.tagName,o=n.attributes;for(let l=0;l<o.length;l+=1)i+=" "+o[l].name+'="'+ZG(o[l].value)+'"';let a=[],s=n.childNodes;for(let l=0;l<s.length;l+=1){let u=s[l];(u.nodeType===1||u.nodeType===3)&&a.push(u)}if(a.length===0)return fd.has(n)?i+"></"+n.tagName+">":i+" />";i+=">";for(let l of a)i+=wS(l,t+1);return i+"</"+n.tagName+">"}function r9(e){let t=Wh(e);return{a:t.getAllProperties().map(r=>[r.key,r.value]),c:t.getAllChildren().map((r,n)=>({i:n,node:(0,GG.rawFromNode)(r)}))}}Ye.projectElementBag=r9});var Zr=v(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.rejectUnknownKeys=Vt.childObjects=Vt.optionalGuidId=Vt.optionalEnum=Vt.eachObject=Vt.issue=Vt.isJsonObject=void 0;function CS(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}Vt.isJsonObject=CS;function ls(e,t,r,n){return n?{pointer:e,rule:t,message:r,fatal:n}:{pointer:e,rule:t,message:r}}Vt.issue=ls;function ES(e,t,r,n){if(!Array.isArray(e))return[];let i=[];return e.forEach((o,a)=>{CS(o)?i.push({node:o,index:a}):n.push(ls(`${t}/${a}`,`${r}-must-be-object`,`a ${r} must be a JSON object, got ${o===null?"null":typeof o}`))}),i}Vt.eachObject=ES;function n9(e,t,r,n,i,o){let a=e[t];a!==void 0&&(typeof a!="string"||!r.includes(a))&&o.push(ls(`${n}/${t}`,i,`${t} must be one of ${r.map(s=>`'${s}'`).join(", ")}, got ${JSON.stringify(a)}`))}Vt.optionalEnum=n9;var i9=/^(?:\{[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 o9(e,t,r,n,i){let o=e[t];typeof o=="string"&&o!==""&&!i9.test(o)&&i.push(ls(`${r}/${t}`,n,`${t} must be a GUID or empty, got '${o}'`))}Vt.optionalGuidId=o9;function a9(e,t,r,n,i){let o=e[t],a=`${r}/${t}`;return o===void 0?[]:Array.isArray(o)?ES(o,a,n,i):(i.push(ls(a,`${n}-list-must-be-array`,`${t} must be an array when present, got ${typeof o}`)),[])}Vt.childObjects=a9;function s9(e,t,r,n,i,o={}){var a,s;for(let l of Object.keys(e)){if(t.has(l))continue;let u=(a=o.elsewhere)===null||a===void 0?void 0:a[l],c=(s=o.unsupported)===null||s===void 0?void 0:s[l],d=u?` '${l}' is a ${u} key \u2014 set it on the ${u} instead.`:c?` ${c}`:` Put values the typed layer does not model in '${n}.bag', which round-trips them verbatim.`;i.push(ls(`${r}/${l}`,`${n}-unknown-key`,`'${l}' is not a ${n} property, and would be SILENTLY DROPPED at serialization.${d}`))}}Vt.rejectUnknownKeys=s9});var yd=v(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.genPageEmbedIssues=B.setUniqueId=B.mintEmbedIdentity=B.authoredUniqueId=B.hasGenPage=B.applyEmbedCellDefaults=B.applyEmbedControlDefaults=B.mayCommitEmbedState=B.commitEmbedState=B.reconcileEmbedDescriptions=B.embedAppendIndex=B.activeEmbedBindings=B.projectGenPageEmbeds=B.isRecognizedEmbed=B.isUnbound=B.effectiveClassId=B.effectiveFormType=B.inputDataFrom=B.classifyBinding=B.isStaticParameter=B.entryParameter=B.pageEntries=B.descriptionFor=B.descriptionsRegion=B.controlUniqueIds=B.controlUniqueId=B.typedCellSites=B.typedCells=B.rawText=B.rawAttr=B.normGuid=B.GENPAGE_FORM_FACTORS=B.GENPAGE_EMBED_ROWSPAN=B.GENPAGE_CONTROL_NAME=B.CUSTOM_CONTROL_CLASS_ID=void 0;var l9=rs(),u9=Fa(),zh=lt(),en=Zr();B.CUSTOM_CONTROL_CLASS_ID="F9A8A302-114E-466A-B582-6771B2AE0D92";B.GENPAGE_CONTROL_NAME="MscrmControls.UxAgentControl";B.GENPAGE_EMBED_ROWSPAN=6;B.GENPAGE_FORM_FACTORS=["2","0","1"];var c9=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Cr(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase();return t.startsWith("{")&&t.endsWith("}")&&(t=t.slice(1,-1)),c9.test(t)?t:""}B.normGuid=Cr;function uo(e,t){let r=Ce(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}B.rawAttr=uo;function Jl(e){return Ce(e?.c).filter(t=>typeof t?.n=="string"&&t.n.startsWith("<")).map(t=>t.n.slice(1)).join("")}B.rawText=Jl;function Ce(e){return Array.isArray(e)?e:[]}function Qh(e,t){let r=Ce(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}function NS(e){return typeof e=="string"?e.trim().replace(/^\{|\}$/g,"").toUpperCase():""}function _S(e){return wn(e).map(t=>t.cell)}B.typedCells=_S;function wn(e){let t=[];return Ce(e?.tabs).forEach((r,n)=>{Ce(De(r)?r.columns:void 0).forEach((i,o)=>{Ce(De(i)?i.sections:void 0).forEach((a,s)=>{Ce(De(a)?a.rows:void 0).forEach((l,u)=>{Ce(De(l)?l.cells:void 0).forEach((c,d)=>{De(c)&&t.push({cell:c,pointer:`/tabs/${n}/columns/${o}/sections/${s}/rows/${u}/cells/${d}`})})})})})}),t}B.typedCellSites=wn;function Ti(e){return De(e)?Cr(Qh(e.bag,"uniqueid")):""}B.controlUniqueId=Ti;function d9(e){let t=new Set;for(let{cell:r}of wn(e)){let n=Qo(r.control)?Ti(r.control):"";n&&t.add(n)}return t}function f9(e){let t=new Map;for(let{cell:r}of wn(e)){let n=De(r.control)?Ti(r.control):"";n&&!t.has(n)&&t.set(n,r.control)}return t}function p9(e){return e!==void 0&&e.genPage===void 0&&(eg(e)!==B.CUSTOM_CONTROL_CLASS_ID||!gd(e))}function jh(e,t){if(De(e)){t(e);for(let r of Ce(e.c))jh(r,t)}}function Jo(e,t){var r;if(De(e)){for(let n of Ce(e.c))jh(n?.node,t);for(let n of Ce((r=e.w)===null||r===void 0?void 0:r.c))jh(n?.node,t)}}function md(e){let t=new Map,r=i=>{var o;i&&t.set(i,((o=t.get(i))!==null&&o!==void 0?o:0)+1)},n=i=>{i.n==="control"&&r(Cr(uo(i,"uniqueid")))};return Jo(e?.bag,n),Ce(e?.tabs).forEach(i=>{De(i)&&(Jo(i.bag,n),Ce(i.columns).forEach(o=>{De(o)&&(Jo(o.bag,n),Ce(o.sections).forEach(a=>{De(a)&&(Jo(a.bag,n),Ce(a.rows).forEach(s=>{De(s)&&(Jo(s.bag,n),Ce(s.cells).forEach(l=>{De(l)&&(Jo(l.bag,n),De(l.control)&&(r(Ti(l.control)),Jo(l.control.bag,n)))}))}))}))}))}),t}B.controlUniqueIds=md;function us(e){return Ce(e?.c).find(t=>{var r;return((r=t?.node)===null||r===void 0?void 0:r.n)==="controlDescriptions"})}B.descriptionsRegion=us;function Yo(e,t){var r;let n=Cr(t);if(n)return Ce((r=us(e))===null||r===void 0?void 0:r.node.c).find(i=>i?.n==="controlDescription"&&Cr(uo(i,"forControl"))===n)}B.descriptionFor=Yo;function Yl(e){return Ce(e.c).filter(TS)}B.pageEntries=Yl;function TS(e){return e?.n==="customControl"&&uo(e,"name")===B.GENPAGE_CONTROL_NAME}function Hh(e,t){let r=Ce(e.c).find(n=>n?.n==="parameters");return Ce(r?.c).find(n=>n?.n===t)}B.entryParameter=Hh;function Kh(e){return uo(e,"static")==="true"}B.isStaticParameter=Kh;function Ql(e){let t=Yl(e);if(t.length===0)return{kind:"none"};let r,n;for(let i=0;i<t.length;i+=1){let o=Hh(t[i],"RefId");if(!o||!Kh(o))return{kind:"unsupported"};let a=Cr(Jl(o));if(!a)return{kind:"unsupported"};let s=Hh(t[i],"PageInput");if(s&&!Kh(s))return{kind:"unsupported"};let l=s?Jl(s):void 0;if(i===0)r=a,n=l;else if(a!==r||l!==n)return{kind:"unsupported"}}return n===void 0?{kind:"projectable",pageId:r}:{kind:"projectable",pageId:r,pageInputRaw:n}}B.classifyBinding=Ql;function De(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Xh(e){if(e===void 0)return;let t;try{t=JSON.parse(e)}catch{return}return De(t)&&De(t.data)?t.data:void 0}B.inputDataFrom=Xh;function Zh(e){var t;return(t=e.formType)!==null&&t!==void 0?t:"Main"}B.effectiveFormType=Zh;function eg(e){return NS(e.classId!==void 0?e.classId:Qh(e.bag,"classid"))}B.effectiveClassId=eg;function gd(e){return!e.fieldName}B.isUnbound=gd;function tg(e,t){if(Zh(e)!=="Main"||!gd(t)||eg(t)!==B.CUSTOM_CONTROL_CLASS_ID)return!1;let r=Ti(t),n=r?Yo(e.bag,r):void 0;return n!==void 0&&Ql(n).kind==="projectable"}B.isRecognizedEmbed=tg;function m9(e){for(let t of _S(e)){let r=t.control;if(!r||!tg(e,r))continue;let n=Ql(Yo(e.bag,Ti(r)));if(n.kind!=="projectable")continue;let i=Xh(n.pageInputRaw);r.genPage=i===void 0?{pageId:n.pageId}:{pageId:n.pageId,inputData:i}}}B.projectGenPageEmbeds=m9;var h9=new Set(["pageId","inputData"]);function Kl(e){let t=[];for(let r=0;r<e.childNodes.length;r+=1){let n=e.childNodes[r];n.nodeType===1&&t.push(n)}return t}function g9(e){let t=[],r=u=>c=>t.push(`${u}: ${c}`),i=new l9.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml").documentElement;if(!i||t.length>0)throw new Error(`the formxml does not parse cleanly${t.length>0?` (${t[0]})`:""}`);let o=new Set,a=i.getElementsByTagName("control");for(let u=0;u<a.length;u+=1){let c=Cr(a[u].getAttribute("uniqueid"));c&&o.add(c)}let s=Kl(i).find(u=>u.nodeName==="controlDescriptions"),l=new Map;for(let u of s?Kl(s):[]){let c=Cr(u.getAttribute("forControl"));if(!(u.nodeName!=="controlDescription"||!c||!o.has(c)))for(let d of Kl(u)){if(d.nodeName!=="customControl"||d.getAttribute("name")!==B.GENPAGE_CONTROL_NAME)continue;let f=Kl(d).find(h=>h.nodeName==="parameters"),p=f?Kl(f).find(h=>h.nodeName==="RefId"):void 0,m=p&&p.getAttribute("static")==="true"?Cr(p.textContent):"";m&&l.set(`${c}|${m}`,[c,m])}}return[...l.values()]}B.activeEmbedBindings=g9;function pd(e){return{n:`<${e}`,a:[],c:[]}}function Jh(e,t){return{n:e,a:[["type","SingleLine.Text"],["static","true"]],c:[pd(t)]}}function Yh(e,t){let r={};if(t!==void 0)try{let n=JSON.parse(t);De(n)&&(r=n)}catch{}return JSON.stringify({...r,data:e})}function y9(e,t,r){return{n:"controlDescription",a:[["forControl",e]],c:B.GENPAGE_FORM_FACTORS.map(n=>({n:"customControl",a:[["name",B.GENPAGE_CONTROL_NAME],["formFactor",n]],c:[{n:"parameters",a:[],c:[Jh("RefId",t),...r===void 0?[]:[Jh("PageInput",Yh(r))]]}]}))}}function hd(e,t){if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>hd(r,t[n]));if(De(e)&&De(t)){let r=Object.keys(e);return r.length===Object.keys(t).length&&r.every(n=>n in t&&hd(e[n],t[n]))}return e===t}function b9(e,t,r){let n=Ce(e.c).find(u=>u?.n==="parameters");if(!n||!Array.isArray(n.c))return;let i=n.c.find(u=>u?.n==="RefId");i&&Cr(Jl(i))!==t&&(i.c=[pd(t)]);let o=n.c.findIndex(u=>u?.n==="PageInput"),a=o>=0?n.c[o]:void 0,s=a?Jl(a):void 0;if(hd(Xh(s),r))return;if(r!==void 0){a?a.c=[pd(Yh(r,s))]:n.c.push(Jh("PageInput",Yh(r)));return}let l=JSON.parse(s);delete l.data,Object.keys(l).length===0?n.c.splice(o,1):a.c=[pd(JSON.stringify(l))]}function rg(e){let t=Ce(e?.c),r=t.reduce((n,i)=>i.i>n?i.i:n,-1);return Math.max(r,t.length)+1}B.embedAppendIndex=rg;function v9(e,t){var r;let n=e.bag,i=us(n);if(i&&t){let o=md(t),a=md(e),s=d9(t),l=f9(e),u=Ce(i.node.c),c=[];for(let d of u){let f=d?.n==="controlDescription"&&Yl(d).length>0?Cr(uo(d,"forControl")):"";if(!f||!o.has(f))c.push(d);else if(a.has(f))if(s.has(f)&&p9(l.get(f))&&hd(d,Yo(t.bag,f))){let p=Ce(d.c).filter(m=>!TS(m));p.length>0&&c.push({...d,c:p})}else c.push(d)}(c.length!==u.length||c.some((d,f)=>d!==u[f]))&&(i.node.c=c)}for(let{cell:o}of wn(e)){let a=o.control;if(!Qo(a)||!De(a.genPage))continue;let s=Cr(a.genPage.pageId),l=a.genPage.inputData,u=Ti(a);if(!u){if(Xl(a)!==void 0)continue;u=ng(a)}let c=Yo(n,u);if(c){for(let p of Yl(c))b9(p,s,l);continue}i||(i={i:rg(n),node:{n:"controlDescriptions",a:[],c:[]}},n.c.push(i));let d=((r=Qh(a.bag,"uniqueid"))!==null&&r!==void 0?r:"").trim(),f=d.startsWith("{")?d:`{${u}}`;i.node.c.push(y9(f,s,l))}}B.reconcileEmbedDescriptions=v9;function w9(e,t){let r=us(e.bag),n=t!==void 0&&(r===void 0||JSON.stringify(r.node)!==JSON.stringify(t)),i=wn(e).some(({cell:a})=>Qo(a.control)&&(a.rowspan===void 0||a.control.classId===void 0||a.control.showLabel===void 0||a.control.label===void 0||a.control.fieldName===void 0));if(!n&&!i)return e;let o=JSON.parse(JSON.stringify(e));if(n){let a=JSON.parse(JSON.stringify(t)),s=us(o.bag);s?s.node=a:(o.bag=De(o.bag)?o.bag:{a:[],c:[]},o.bag.c=Ce(o.bag.c),o.bag.c.push({i:rg(e.bag),node:a}))}for(let{cell:a}of wn(o))Qo(a.control)&&(DS(a.control),IS(a));return o}B.commitEmbedState=w9;function C9(e){if(wn(e).some(({cell:r})=>Qo(r.control)))return!0;let t=us(e.bag);return Ce(t?.node.c).some(r=>r?.n==="controlDescription"&&Yl(r).length>0)}B.mayCommitEmbedState=C9;function DS(e){e.classId===void 0&&(e.classId=B.CUSTOM_CONTROL_CLASS_ID),e.showLabel===void 0&&(e.showLabel=!1),e.label===void 0&&(e.label=""),e.fieldName===void 0&&(e.fieldName=null)}B.applyEmbedControlDefaults=DS;function IS(e){e.rowspan===void 0&&(e.rowspan=B.GENPAGE_EMBED_ROWSPAN)}B.applyEmbedCellDefaults=IS;function Qo(e){return De(e)&&e.genPage!==void 0}B.hasGenPage=Qo;function AS(e){return Qo(e.control)&&(!e.control.id||!e.id||Xl(e.control)===void 0)}function Xl(e){let t=Ce(De(e.bag)?e.bag.a:void 0).find(n=>Array.isArray(n)&&n[0]==="uniqueid");if(!t)return;let r=t[1];return typeof r=="string"&&r.trim()===""?void 0:r}B.authoredUniqueId=Xl;function E9(e){if(!wn(e).some(({cell:r})=>AS(r)))return e;let t=JSON.parse(JSON.stringify(e));for(let{cell:r}of wn(t)){if(!AS(r))continue;let n=r.control;n.id||(n.id=(0,zh.newId)()),r.id||(r.id=(0,zh.newId)()),Xl(n)===void 0&&ng(n)}return t}B.mintEmbedIdentity=E9;function ng(e){let t=(0,zh.newId)(),r=`{${t}}`;if(!De(e.bag))return e.bag={a:[["uniqueid",r]],c:[]},t;let n=Ce(e.bag.a),i=n.find(o=>Array.isArray(o)&&o[0]==="uniqueid");return i?i[1]=r:n.push(["uniqueid",r]),e.bag.a=n,e.bag.c=Ce(e.bag.c),t}B.setUniqueId=ng;function SS(e){return e===null?"null":Array.isArray(e)?"an array":typeof e}function A9(e){let t=Ce(e.c).filter(r=>r?.n==="customControl").map(r=>{var n,i;return(i=(n=uo(r,"name"))!==null&&n!==void 0?n:uo(r,"id"))!==null&&i!==void 0?i:"(unnamed)"});return[...new Set(t)].join(", ")||"(no custom control)"}function S9(e){let t=[],r;for(let{cell:n,pointer:i}of wn(e)){let o=n.control;if(!De(o))continue;let a=`${i}/control`;if(o.genPage===void 0){N9(e,o,a,t);continue}r=r??md(e),_9(e,o,a,r,t)}return t}B.genPageEmbedIssues=S9;function N9(e,t,r,n){if(!tg(e,t))return;let i=Ql(Yo(e.bag,Ti(t)));n.push((0,en.issue)(r,"genpage-embed-removed",`this control still embeds generative page ${i.pageId}: removing genPage alone would leave that binding on the form. To remove the embed, remove the cell (or set the cell's control to null); to change the page, edit genPage/pageId. A copy fetched by an older SDK (projection 3) shows no genPage at all \u2014 re-fetch the form.`))}function _9(e,t,r,n,i){var o;let a=`${r}/genPage`,s=t.genPage;if(!De(s))i.push((0,en.issue)(a,"genpage-embed-shape",`genPage must be an object { pageId, inputData? }, got ${SS(s)}.`+(s===null?" To remove an embed, remove the cell (or set the cell's control to null).":"")));else{(typeof s.pageId!="string"||!Cr(s.pageId))&&i.push((0,en.issue)(`${a}/pageId`,"genpage-embed-shape",`genPage.pageId must be the id (a GUID) of a generative page, got ${s.pageId===void 0?"nothing":JSON.stringify(s.pageId)}`)),s.inputData!==void 0&&!De(s.inputData)&&i.push((0,en.issue)(`${a}/inputData`,"genpage-embed-shape",`genPage.inputData must be a JSON object \u2014 the page reads it as pageInput.data \u2014 got ${SS(s.inputData)}`));for(let p of Object.keys(s))h9.has(p)||i.push((0,en.issue)(u9.JsonPointer.append(a,p),"genpage-embed-unknown-key",`'${p}' is not a genPage property (pageId, inputData), and would be SILENTLY DROPPED at serialization.`))}gd(t)||i.push((0,en.issue)(`${r}/fieldName`,"genpage-embed-bound",`a generative-page embed is an unbound control, but this one is bound to column '${t.fieldName}'. Set fieldName to null, or embed the page in a new cell.`)),t.classId!==void 0&&NS(t.classId)!==B.CUSTOM_CONTROL_CLASS_ID&&i.push((0,en.issue)(`${r}/classId`,"genpage-embed-class-id",`a generative-page embed is the custom control {${B.CUSTOM_CONTROL_CLASS_ID}}, but classId is ${JSON.stringify(t.classId)}. Omit classId (the SDK defaults it) or set it to that class.`));let l=Zh(e);l!=="Main"&&i.push((0,en.issue)(a,"genpage-embed-main-form-only",`a generative page can be embedded only in a Main form, as in the maker portal; this is a ${l} form.`));let u=Xl(t);u!==void 0&&!Cr(u)&&i.push((0,en.issue)(`${r}/bag`,"genpage-embed-unique-id",`this embed's uniqueid ${JSON.stringify(u)} is not a GUID, and its page binding is keyed by it. Remove it from the bag (the SDK mints one) or set a GUID.`));let c=Ti(t);if(!c)return;let d=Yo(e.bag,c),f=d?Ql(d):void 0;d&&f?.kind==="none"?i.push((0,en.issue)(a,"genpage-embed-other-control",`this control is already bound to another custom control (${A9(d)}). genPage would have to delete that binding to take its place, so embed the page in a new cell instead.`)):f?.kind==="unsupported"&&i.push((0,en.issue)(a,"genpage-embed-unsupported-binding","this control already embeds a page through a binding genPage cannot represent exactly \u2014 a RefId or PageInput bound to a column, a RefId that is not a page id, or form factors that disagree. Taking it over would silently turn it into a static binding, so embed the page in a new cell instead.")),((o=n.get(c))!==null&&o!==void 0?o:0)>1&&i.push((0,en.issue)(`${r}/bag`,"genpage-embed-duplicate-unique-id",`this embed's uniqueid {${c}} is also carried by another control on the form, so both would share one binding. Author the copy without its bag and the SDK mints a new identity for it.`))}});var og=v(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});co.findMissingGenPages=co.GENPAGE_LOOKUP_CHUNK=void 0;var T9=Xt(),ig=ue();co.GENPAGE_LOOKUP_CHUNK=50;async function D9(e,t,r){let n=[...new Set(t.map(o=>(0,ig.normalizeGuid)(o,"uxagentprojectid")))],i=new Set;for(let o=0;o<n.length;o+=co.GENPAGE_LOOKUP_CHUNK){let a=n.slice(o,o+co.GENPAGE_LOOKUP_CHUNK),s="/uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,ig.odataQuery)([["$select","uxagentprojectid"],["$filter",a.map(u=>`uxagentprojectid eq ${u}`).join(" or ")]]),l=await(0,T9.collectPages)(e,s,r);for(let u of l){let c=u.uxagentprojectid;typeof c=="string"&&c.trim()!==""&&i.add((0,ig.normalizeGuid)(c,"uxagentprojectid"))}}return n.filter(o=>!i.has(o))}co.findMissingGenPages=D9});var Zl=v(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.assertSystemFormKind=Ct.readSystemFormType=Ct.decodeCode=Ct.assertSystemFormRecordKind=Ct.describeSystemFormType=Ct.systemFormKindOf=Ct.SYSTEMFORM_KIND_MISMATCH_CODE=void 0;var PS=Q(),I9=ye(),OS=ue();Ct.SYSTEMFORM_KIND_MISMATCH_CODE="SYSTEMFORM_KIND_MISMATCH";var O9={0:"dashboard",10:"dashboard",2:"form",6:"form",7:"form",11:"form"},P9={0:"dashboard",1:"appointment book",2:"Main form",3:"mini campaign form",4:"preview form",5:"mobile express form",6:"Quick View form",7:"Quick Create form",8:"dialog",9:"task flow form",10:"interactive dashboard",11:"card form",12:"interactive Main form",13:"contextual dashboard",100:"other form",101:"Main form backup",102:"appointment book backup",103:"Power BI dashboard"};function bd(e){return Number.isInteger(e)?O9[e]:void 0}Ct.systemFormKindOf=bd;function RS(e){var t;return Number.isFinite(e)?`a ${(t=P9[e])!==null&&t!==void 0?t:"systemform"} (type ${e})`:"a systemform whose type could not be read"}Ct.describeSystemFormType=RS;function LS(e,t,r,n){let i=RS(r),o=bd(r);switch(n){case"fetch":return`Refusing to fetch systemform '${e}' as a ${t}: it is ${i}. Nothing was read into the workspace. `+(o?`Fetch it as a ${o}.`:Number.isFinite(r)?"The SDK does not model that kind: check the id.":"Check the id.");case"write":return`Refusing to write systemform '${e}' as a ${t}: it is ${i}. Nothing was written. Check the id: a local copy fetched by an SDK that did not check the kind can name a row of another kind \u2014 discard it with deleteArtifact('${t}', '${e}').`;case"delete":return`Refusing to delete systemform '${e}' as a ${t}: it is ${i}. Nothing was changed. Check the id.`;default:return`Refusing to ${n} systemform '${e}': it is ${i}, not a ${t}.`+(n==="set the security roles of"?" Nothing was written.":"")+" Check the id."}}function R9(e,t,r,n){let i=ag(e?.type);if(bd(i)!==r)throw new PS.SdkError(Ct.SYSTEMFORM_KIND_MISMATCH_CODE,LS(t,r,i,n));return i}Ct.assertSystemFormRecordKind=R9;function ag(e){if(typeof e=="number")return Number.isInteger(e)?e:NaN;if(typeof e!="string"||!/^\s*-?\d+\s*$/.test(e))return NaN;let t=Number(e);return Number.isInteger(t)?t:NaN}Ct.decodeCode=ag;async function L9(e,t){return await kS(e,t,!1)}Ct.readSystemFormType=L9;async function k9(e,t){return kS(e,t,!0)}async function kS(e,t,r){var n;let o=`/systemforms(${(0,OS.normalizeGuid)(t,"formId")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,OS.odataQuery)([["$select","type"]]),a=await e.get(o);if(!(r&&a.status===404))return(0,I9.ensureSuccess)(a,e.apiUrl(o)),ag((n=a.body)===null||n===void 0?void 0:n.type)}async function x9(e,t,r){let n=await k9(e,t);if(!(n===void 0||bd(n)===r))throw new PS.SdkError(Ct.SYSTEMFORM_KIND_MISMATCH_CODE,LS(t,r,n,"delete"))}Ct.assertSystemFormKind=x9});var lg=v(Mr=>{"use strict";Object.defineProperty(Mr,"__esModule",{value:!0});Mr.patchSystemForm=Mr.assertSystemFormContentUnchanged=Mr.readSystemFormRowEtag=Mr.unpublishedSystemFormPath=Mr.FORM_TYPE_IMMUTABLE_CODE=void 0;var tn=ye(),$9=ue(),vd=Q(),fo=Zl();Mr.FORM_TYPE_IMMUTABLE_CODE="FORM_TYPE_IMMUTABLE";function sg(e,t="formid"){return`/systemforms(${e})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,$9.odataQuery)([["$select",t]])}Mr.unpublishedSystemFormPath=sg;function xS(e,t){return(0,tn.readRowEtag)(e,"systemforms","formid",t)}Mr.readSystemFormRowEtag=xS;async function $S(e,t,r,n,i){(0,tn.requireEtag)(i,r,t);let o=(0,tn.ensureSuccess)(await e.get(n),e.apiUrl(n)),a=(0,fo.assertSystemFormRecordKind)(o.body,t,r,"write"),s=(0,tn.readEtag)(o);if(s===null)throw new vd.SdkError(tn.VERSION_CONFLICT_CODE,`Refusing to write ${r} '${t}': its current version could not be read, so the write could not be verified as conditional and would risk silently overwriting a concurrent edit.`);if(s!==i)throw new vd.SdkError(tn.VERSION_CONFLICT_CODE,`Version conflict writing ${r} '${t}': its formxml changed on the server since it was read (held ${i}, server ${s}). Re-fetch the ${r} and re-apply the change.`);return a}Mr.assertSystemFormContentUnchanged=$S;async function F9(e,t,r,n,i,o){(0,tn.requireEtag)(i,r,t);let a=await xS(e,t);if(a===null)throw new vd.SdkError(tn.VERSION_CONFLICT_CODE,`Refusing to write ${r} '${t}': its row version could not be read, so the write could not be made conditional and would risk silently overwriting a concurrent edit.`);let s=await $S(e,t,r,sg(t,"formid,type"),i);if(n.type!==void 0&&(0,fo.decodeCode)(n.type)!==s)throw new vd.SdkError(Mr.FORM_TYPE_IMMUTABLE_CODE,`Refusing to push ${r} '${t}': it would change it from ${(0,fo.describeSystemFormType)(s)} to ${(0,fo.describeSystemFormType)((0,fo.decodeCode)(n.type))}. The platform ignores a type change on an existing ${r}, so the push would report a change that did not happen. Nothing was written. Create a new ${r} of that type instead.`);let l=(0,tn.echoWrite)("formid",{"If-Match":a}),u=`/systemforms(${t})${l.query}`;return(0,tn.ensureSuccess)(await e.patch(u,n,l.options),e.apiUrl(u)),M9(e,t,r,o)}Mr.patchSystemForm=F9;async function M9(e,t,r,n){let i;try{let o=sg(t,n.select),a=(0,tn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=a.body,l=(0,tn.readEtag)(a),u=typeof s?.formid=="string"&&s.formid.replace(/[{}]/g,"").toLowerCase()===t,c=typeof s?.formxml=="string"&&s.formxml.trim()!=="",d=n.required.filter(m=>s?.[m]===void 0||s?.[m]===null),f=(0,fo.decodeCode)(s?.type),p=(0,fo.systemFormKindOf)(f)===r;if(l&&u&&c&&d.length===0&&p)return{id:t,etag:l,readBack:s};i=l?!u||!c?`the read did not return this ${r}'s document`:d.length>0?`the read did not return its ${d.join(", ")}`:`the read returned ${(0,fo.describeSystemFormType)(f)}, not a ${r}`:"the read returned no version"}catch(o){i=o instanceof Error?o.message:String(o)}return{id:t,etag:null,warnings:[`The ${r} was saved, but its new version could not be read (${i}). The SDK holds no version for it now, so the next push is refused: re-fetch the ${r} before editing it again.`]}}});var pg=v(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.getFormSecurityRoles=Pt.setFormSecurityRoles=Pt.formApi=Pt.readPrimaryCreateRefusal=Pt.FORM_GENPAGE_TARGET_UNVERIFIABLE=Pt.FORM_GENPAGE_TARGET_NOT_FOUND=void 0;var U9=Xt(),Et=ye(),rn=ue(),Xo=Q(),ug=lo(),MS=yd(),B9=og(),cg=lg(),eu=Zl();Pt.FORM_GENPAGE_TARGET_NOT_FOUND="FORM_GENPAGE_TARGET_NOT_FOUND";Pt.FORM_GENPAGE_TARGET_UNVERIFIABLE="FORM_GENPAGE_TARGET_UNVERIFIABLE";var US="formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber",q9={select:US,required:["name","type","objecttypecode"]},V9="formid,name,type,objecttypecode",G9=2,W9={Main:G9,QuickView:6,QuickCreate:7,Card:11},BS=new WeakMap;function z9(e){return typeof e=="object"&&e!==null?BS.get(e):void 0}Pt.readPrimaryCreateRefusal=z9;Pt.formApi={async get(e,t){let r=(0,rn.normalizeGuid)(t,"id"),n=`/systemforms(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,rn.odataQuery)([["$select",US]]),i=(0,Et.ensureSuccess)(await e.get(n),e.apiUrl(n));return(0,eu.assertSystemFormRecordKind)(i.body,r,"form","fetch"),{raw:i.body,etag:(0,Et.readEtag)(i)}},async list(e,t){var r;let n=!((r=t?.formTypes)===null||r===void 0)&&r.length?t.formTypes:["Main"],i=[...new Set(n.map(u=>W9[u]))],a=[i.length===1?`type eq ${i[0]}`:`(${i.map(u=>`type eq ${u}`).join(" or ")})`];t?.entityLogicalName&&a.push(`objecttypecode eq '${(0,rn.odataLiteral)(t.entityLogicalName)}'`);let s=`/systemforms${(0,rn.odataQuery)([["$select",V9],["$filter",a.join(" and ")]])}`;return(await(0,U9.collectPages)(e,s,"listArtifacts('form')")).map(u=>{var c,d;return{type:"form",id:(c=u.formid)!==null&&c!==void 0?c:"",name:(d=u.name)!==null&&d!==void 0?d:"",entityLogicalName:u.objecttypecode,isDirty:!1}})},async create(e,t,r){let n=FS(t);n!==void 0&&await qS(e,fg(n,"payload"),[]);let i=(0,Et.echoWrite)("formid"),o=`/systemforms${i.query}`,a=(0,Et.withClientMintedId)(t,"formid",r),s=Object.freeze({...a}),l=await(0,Et.resendDeadlockVictim)(()=>e.post(o,{...s},i.options));try{(0,Et.ensureSuccess)(l,e.apiUrl(o))}catch(u){throw typeof u=="object"&&u!==null&&BS.set(u,{status:l.status,sent:s,desiredId:r}),u}return{id:(0,Et.resolveCreatedId)(l,"formid","form",r),etag:(0,Et.readEtag)(l)}},async update(e,t,r,n){let i=(0,rn.normalizeGuid)(t,"id"),o=FS(r);return o!==void 0&&await H9(e,i,o,n),(0,cg.patchSystemForm)(e,i,"form",r,n,q9)},readContentThenToken(e,t){return Pt.formApi.get(e,t)},async delete(e,t){let r=(0,rn.normalizeGuid)(t,"id");return await(0,eu.assertSystemFormKind)(e,r,"form"),(0,Et.deleteRecord)(e,"systemforms",r)}};var dg="DisplayConditions";async function j9(e,t,r){var n,i,o,a;if(r.everyone&&r.roleIds&&r.roleIds.length>0)throw new Xo.InvalidArgumentError("setFormSecurityRoles: `everyone` and `roleIds` are mutually exclusive \u2014 the platform models <Everyone /> as a replacement for the <Role> list, not an addition to it.");let s=(0,rn.normalizeGuid)(t,"formId"),l=`/systemforms(${s})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,rn.odataQuery)([["$select","formid,formxml,type"]]),u=(0,Et.ensureSuccess)(await e.get(l),e.apiUrl(l));(0,eu.assertSystemFormRecordKind)(u.body,s,"form","set the security roles of");let c=(0,Et.readEtag)(u),d=u.body,f=d?.formxml;if(!f)throw new Xo.InvalidArgumentError(`form '${s}' returned no formxml, so its roles cannot be set`);let p=(0,ug.parseXmlRoot)(f,"<form/>"),m=p.ownerDocument;if(!m)throw new Xo.InvalidArgumentError(`form '${s}' produced no owner document`);let h=VS(p,dg),g=h?.hasAttribute("Order")&&(n=h.getAttribute("Order"))!==null&&n!==void 0?n:void 0,b=h?.getAttribute("FallbackForm")||void 0;h&&p.removeChild(h);let w=!!r.everyone||((o=(i=r.roleIds)===null||i===void 0?void 0:i.length)!==null&&o!==void 0?o:0)>0;if(!w&&(r.order!==void 0||r.fallbackForm!==void 0)){if(!h)throw new Xo.InvalidArgumentError("setFormSecurityRoles: `order`/`fallbackForm` were supplied without `roleIds` or `everyone`, but this form has no <DisplayConditions> to attach them to. Pass the roles as well.");r.order!==void 0&&h.setAttribute("Order",String(r.order)),r.fallbackForm!==void 0&&h.setAttribute("FallbackForm",String(r.fallbackForm)),p.appendChild(h)}else if(w){let I=m.createElement(dg),D=r.order!==void 0?String(r.order):g;D!==void 0&&I.setAttribute("Order",D);let O=r.fallbackForm!==void 0?String(r.fallbackForm):b??"false";if(I.setAttribute("FallbackForm",O),r.everyone)I.appendChild(m.createElement("Everyone"));else for(let $ of(a=r.roleIds)!==null&&a!==void 0?a:[]){let K=m.createElement("Role");K.setAttribute("Id",`{${(0,rn.normalizeGuid)($,"roleId")}}`),I.appendChild(K)}p.appendChild(I)}let A=(0,ug.serializeNode)(p);await(0,cg.assertSystemFormContentUnchanged)(e,s,"form",l,c);let L=await(0,cg.readSystemFormRowEtag)(e,s),R=`/systemforms(${s})`;(0,Et.ensureSuccess)(await e.patch(R,{formxml:A},{headers:{"Content-Type":"application/json","If-Match":(0,Et.requireEtag)(L,"form",s)}}),e.apiUrl(R))}Pt.setFormSecurityRoles=j9;function FS(e){let t=e?.formxml;return typeof t=="string"&&t.includes(MS.GENPAGE_CONTROL_NAME)?t:void 0}function fg(e,t){try{return(0,MS.activeEmbedBindings)(e)}catch(r){throw new Xo.SdkError(Pt.FORM_GENPAGE_TARGET_UNVERIFIABLE,`Refusing to push the form: the ${t} formxml could not be parsed, so the generative pages it embeds cannot be verified (${r instanceof Error?r.message:String(r)}).`)}}async function qS(e,t,r){let n=new Set(r.map(([a,s])=>`${a}|${s}`)),i=t.filter(([a,s])=>!n.has(`${a}|${s}`)).map(([,a])=>a);if(i.length===0)return;let o=await(0,B9.findMissingGenPages)(e,i,"form generative-page preflight");if(o.length>0)throw new Xo.SdkError(Pt.FORM_GENPAGE_TARGET_NOT_FOUND,`Refusing to push the form: it embeds generative page(s) ${o.map(a=>`'${a}'`).join(", ")} that do not exist in this environment. Push the page before the form that embeds it.`)}async function H9(e,t,r,n){var i;(0,Et.requireEtag)(n,"form",t);let o=`/systemforms(${t})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,rn.odataQuery)([["$select","formid,formxml,type"]]),a=(0,Et.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,eu.assertSystemFormRecordKind)(a.body,t,"form","write");let s=(0,Et.readEtag)(a);if(s===null||s!==n)throw new Xo.SdkError(Et.VERSION_CONFLICT_CODE,`Version conflict writing form '${t}': its formxml changed on the server since it was read (held ${n}, server ${s??"(unreadable)"}). Re-fetch the form and re-apply the change.`);let l=(i=a.body)===null||i===void 0?void 0:i.formxml,u=typeof l=="string"&&l!==""?fg(l,"server"):[];await qS(e,fg(r,"payload"),u)}function VS(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 K9(e,t){var r,n;let i=(0,rn.normalizeGuid)(t,"formId"),o=`/systemforms(${i})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,rn.odataQuery)([["$select","formid,formxml,type"]]),a=(0,Et.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,eu.assertSystemFormRecordKind)(a.body,i,"form","read the security roles of");let s=(r=a.body)===null||r===void 0?void 0:r.formxml;if(!s)return;let l=(0,ug.parseXmlRoot)(s,"<form/>"),u=VS(l,dg);if(!u)return;let c=[],d=!1,f=u.childNodes;for(let m=0;m<f.length;m+=1){let h=f[m];if(h.nodeType!==1)continue;let g=h;if(g.tagName==="Everyone")d=!0;else if(g.tagName==="Role"){let b=(n=g.getAttribute("Id"))!==null&&n!==void 0?n:"";b&&c.push(b.replace(/[{}]/g,"").toLowerCase())}}let p=u.getAttribute("Order");return{...d?{everyone:!0}:{},...c.length>0?{roleIds:c}:{},fallbackForm:u.getAttribute("FallbackForm")==="true",...p!==null&&p!==""?{order:Number(p)}:{}}}Pt.getFormSecurityRoles=K9});var mg=v(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.deleteSolution=me.getDeploymentSettingsTemplate=me.importSolution=me.exportSolution=me.removeSolutionComponent=me.addSolutionComponent=me.setSolutionVersion=me.createSolution=me.createPublisher=me.getSolution=me.fetchSolutionComponents=me.resolveGenPageComponentType=me.SolutionComponentType=void 0;var J9=Xt(),Lt=ye(),nr=ue(),Y9=lt(),Gt=Q();me.SolutionComponentType={SavedQuery:26,Workflow:29,SavedQueryVisualization:59,SystemForm:60,AppModule:80};var Q9=[me.SolutionComponentType.SavedQuery,me.SolutionComponentType.Workflow,me.SolutionComponentType.SavedQueryVisualization,me.SolutionComponentType.SystemForm,me.SolutionComponentType.AppModule],GS="uxagentproject",WS=new WeakMap;async function YS(e){var t;let r=WS.get(e);if(r!==void 0)return r;let n=`/EntityDefinitions(LogicalName='${GS}')${(0,nr.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status===404)return;(0,Lt.ensureSuccess)(i,e.apiUrl(n));let o=(t=i.body)===null||t===void 0?void 0:t.ObjectTypeCode;if(typeof o!="number"||!Number.isInteger(o)||o<=0)throw new Gt.SdkError("GENPAGE_COMPONENT_TYPE_UNRESOLVED",`A generative page's solution component type \u2014 the ObjectTypeCode of '${GS}' \u2014 could not be read: its metadata answered without a usable value (${JSON.stringify(o)}). Without it a solution's generative pages cannot be told apart from other components. Retry.`);return WS.set(e,o),o}me.resolveGenPageComponentType=YS;var zS=1,jS=0;async function X9(e,t){let r=(0,nr.normalizeGuid)(t,"solutionId"),n=await YS(e),o=[zS,...Q9,...n===void 0?[]:[n]].map(c=>`componenttype eq ${c}`).join(" or "),a=`/solutioncomponents${(0,nr.odataQuery)([["$select","objectid,componenttype,rootcomponentbehavior"],["$filter",`_solutionid_value eq ${r} and (${o})`]])}`,s=await(0,J9.collectPages)(e,a,"fetchSolutionComponents"),l=[];for(let c of s){if(typeof c.objectid!="string")continue;let d=Number(c.componenttype);if(d===zS){let f=c.rootcomponentbehavior;(f===jS||f===String(jS))&&l.push({objectId:c.objectid,componentType:d,includesAllSubcomponents:!0});continue}l.push({objectId:c.objectid,componentType:d,...n!==void 0&&d===n?{genPage:!0}:{}})}let u=c=>c.objectId.toLowerCase().replace(/^\{|\}$/g,"");return l.sort((c,d)=>c.componentType-d.componentType||(u(c)<u(d)?-1:u(c)>u(d)?1:0))}me.fetchSolutionComponents=X9;function Z9(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 e5(e,t){var r,n,i,o,a,s,l,u,c,d;let f=String(t??"").trim();if(!f)throw new Gt.InvalidArgumentError("getSolution: a solution unique name or id is required.");let p=Z9(f)?`solutionid eq ${(0,nr.normalizeGuid)(f,"solutionId")}`:`uniquename eq '${(0,nr.odataLiteral)(f)}'`,m=`/solutions${(0,nr.odataQuery)([["$select","solutionid,uniquename,friendlyname,version,ismanaged"],["$expand","publisherid($select=publisherid,uniquename,customizationprefix,customizationoptionvalueprefix)"],["$filter",p]])}`,b=((n=(r=(0,Lt.ensureSuccess)(await e.get(m),e.apiUrl(m)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0];if(!b?.solutionid)throw new Gt.InvalidArgumentError(`No solution found for '${t}'.`);let w=b.publisherid;if(!w?.publisherid)throw new Gt.InvalidArgumentError(`Solution '${(i=b.uniquename)!==null&&i!==void 0?i:t}' returned no owning publisher, so its customization prefix cannot be determined; refusing to report an empty prefix that could be mistaken for "no prefix".`);if(!("customizationprefix"in w))throw new Gt.InvalidArgumentError(`Solution '${(o=b.uniquename)!==null&&o!==void 0?o:t}' returned a publisher without a customizationprefix property (partial expansion), so its prefix cannot be determined.`);return{solutionId:(0,nr.normalizeGuid)(b.solutionid,"solutionId"),uniqueName:(a=b.uniquename)!==null&&a!==void 0?a:"",friendlyName:(s=b.friendlyname)!==null&&s!==void 0?s:"",version:(l=b.version)!==null&&l!==void 0?l:"",isManaged:!!b.ismanaged,publisherId:(0,nr.normalizeGuid)(w.publisherid,"publisherId"),publisherUniqueName:(u=w.uniquename)!==null&&u!==void 0?u:"",publisherPrefix:(c=w.customizationprefix)!==null&&c!==void 0?c:"",publisherOptionValuePrefix:(d=w.customizationoptionvalueprefix)!==null&&d!==void 0?d:0}}me.getSolution=e5;async function t5(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,Lt.ensureSuccess)(await(0,Lt.resendDeadlockVictim)(()=>e.post("/publishers",{...n})),e.apiUrl("/publishers")),o=(0,Lt.readCreatedId)(i,"publisherid");if(!o)throw new Gt.InvalidArgumentError(`Dataverse did not return an id for publisher '${t.uniqueName}'`);return{id:o,uniqueName:t.uniqueName}}me.createPublisher=t5;async function r5(e,t){var r;let n=(0,nr.normalizeGuid)(t.publisherId,"publisherId"),i={uniquename:t.uniqueName,friendlyname:t.friendlyName,version:(r=t.version)!==null&&r!==void 0?r:"1.0.0.0","[email protected]":`/publishers(${n})`};t.description&&(i.description=t.description);let o=(0,Lt.ensureSuccess)(await e.post("/solutions",i),e.apiUrl("/solutions")),a=(0,Lt.readCreatedId)(o,"solutionid");if(!a)throw new Gt.InvalidArgumentError(`Dataverse did not return an id for solution '${t.uniqueName}'`);return{id:a,uniqueName:t.uniqueName}}me.createSolution=r5;async function n5(e,t,r){let i=`/solutions(${(0,nr.normalizeGuid)(t,"solutionId")})`;(0,Lt.ensureSuccess)(await e.patch(i,{version:r}),e.apiUrl(i))}me.setSolutionVersion=n5;async function i5(e,t){var r;let i={ComponentId:(0,nr.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,Lt.ensureSuccess)(await e.post("/AddSolutionComponent",i),e.apiUrl("/AddSolutionComponent"))}me.addSolutionComponent=i5;async function o5(e,t,r,n){let o={SolutionComponent:{"@odata.type":"Microsoft.Dynamics.CRM.solutioncomponent",solutioncomponentid:(0,nr.normalizeGuid)(t,"componentId")},ComponentType:r,SolutionUniqueName:n};(0,Lt.ensureSuccess)(await e.post("/RemoveSolutionComponent",o),e.apiUrl("/RemoveSolutionComponent"))}me.removeSolutionComponent=o5;async function a5(e,t){var r,n;let i={SolutionName:t.solutionName,Managed:(r=t.managed)!==null&&r!==void 0?r:!1},a=(n=(0,Lt.ensureSuccess)(await e.post("/ExportSolution",i),e.apiUrl("/ExportSolution")).body)===null||n===void 0?void 0:n.ExportSolutionFile;if(!a)throw new Gt.InvalidArgumentError(`ExportSolution returned no file for '${t.solutionName}'`);return{base64:a}}me.exportSolution=a5;async function s5(e,t){let r=[["overwriteUnmanagedCustomizations","overwrote unmanaged customizations made over the solution's components"],["publishWorkflows","activated the solution's workflows"]];for(let[a,s]of r)if(typeof t?.[a]!="boolean")throw new Gt.InvalidArgumentError(`importSolution: '${a}' is required and must be true or false (it was ${String(t?.[a])}). It used to default to true, which ${s} unless the caller said otherwise. Nothing was imported.`);let n=t.deploymentSettings===void 0?void 0:b5(t.deploymentSettings),i={OverwriteUnmanagedCustomizations:t.overwriteUnmanagedCustomizations,PublishWorkflows:t.publishWorkflows,CustomizationFile:t.base64,ImportJobId:t.importJobId?(0,nr.normalizeGuid)(t.importJobId,"importJobId"):(0,Y9.newId)()};if(!n)return(0,Lt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{};if(n.variables.length===0&&n.references.length===0)return(0,Lt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:{environmentVariables:[],connectionReferences:[]}};let o=[];try{let a=await QS(e,t.base64,tu,o),{parameters:s,applied:l}=v5(a,n);return i.ComponentParameters=s,(0,Lt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:l,...o.length>0?{warnings:o}:{}}}catch(a){throw(0,Gt.withCleanupWarnings)(a,o)}}me.importSolution=s5;var tu="importSolution",HS="getDeploymentSettingsTemplate";async function l5(e,t){var r;let n=t?.base64;if(typeof n!="string"||n.length===0)throw new Gt.InvalidArgumentError(`${HS}: 'base64' must be the solution package \u2014 a non-empty base64 string, e.g. exportSolution's result (it was ${(r=JSON.stringify(n))!==null&&r!==void 0?r:String(n)})`);let i=[];try{let o=await QS(e,n,HS,i),a=wd(o.variables,l=>l.SchemaName).map(({SchemaName:l,DefaultValue:u,TypeId:c,IsRequired:d})=>({SchemaName:l,Value:"",...u!==void 0?{DefaultValue:u}:{},...c!==void 0?{TypeId:c}:{},...d!==void 0?{IsRequired:d}:{}})),s=wd(o.references,l=>l.LogicalName).map(({LogicalName:l,ConnectorId:u})=>({LogicalName:l,ConnectionId:"",...u!==void 0?{ConnectorId:u}:{}}));return{settings:{EnvironmentVariables:a,ConnectionReferences:s},...i.length>0?{warnings:i}:{}}}catch(o){throw(0,Gt.withCleanupWarnings)(o,i)}}me.getDeploymentSettingsTemplate=l5;function wd(e,t){return[...e].sort((r,n)=>{let i=t(r).toLowerCase(),o=t(n).toLowerCase();return i<o?-1:i>o?1:0})}function Zo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Rt(e,t=120){var r;let n=(r=JSON.stringify(e))!==null&&r!==void 0?r:String(e);return n.length>t?`${n.slice(0,t)}\u2026`:n}async function QS(e,t,r,n){var i;let a=(i=(0,Lt.ensureSuccess)(await e.post("/StageSolution",{CustomizationFile:t}),e.apiUrl("/StageSolution")).body)===null||i===void 0?void 0:i.StageSolutionResults;try{return c5(a,r)}finally{await u5(e,Zo(a)?a.StageSolutionUploadId:void 0,n)}}async function u5(e,t,r){let n;try{n=(0,nr.normalizeGuid)(t,"StageSolutionUploadId")}catch{r.push(`StageSolution's reply named no usable staging upload id (${Rt(t,60)}), so the staged copy of the package it may have stored (a stagesolutionupload row of yours) could not be deleted.`);return}let i=`/stagesolutionuploads(${n})`;try{let o=await e.delete(i);o.status!==404&&(0,Lt.ensureSuccess)(o,e.apiUrl(i))}catch(o){r.push(`The staged copy of the package (stagesolutionupload ${n}) could not be deleted: ${o instanceof Error?o.message:String(o)}. It stays until it is deleted (DELETE ${i}).`)}}function rr(e,t){return new Gt.SdkError("SOLUTION_STAGING_UNREADABLE",`${e}: StageSolution's reply could not be read \u2014 ${t}.${e===tu?" Nothing was imported.":""}`)}function KS(e){return!Array.isArray(e)||e.length===0?"none":`${e.slice(0,5).map(r=>Zo(r)&&typeof r.Message=="string"?r.Message:Rt(r,200)).join("; ")}${e.length>5?` (+${e.length-5} more)`:""}`}function c5(e,t){if(!Zo(e))throw rr(t,`it holds no StageSolutionResults (${Rt(e,60)})`);let r=e.StageSolutionStatus;if(r==="Failed"||r===0)throw new Gt.SdkError("SOLUTION_STAGING_FAILED",`${t}: the package did not pass StageSolution in this environment (status ${Rt(r)}). Missing dependencies: ${KS(e.MissingDependencies)}. Validation: ${KS(e.SolutionValidationResults)}.${t===tu?" Its components cannot be checked against deploymentSettings. Nothing was imported.":" Stage it in the environment it was exported from."}`);if(r!=="Passed"&&r!==1)throw rr(t,`StageSolutionStatus is ${Rt(r)}, neither "Passed" nor "Failed"`);let n=e.SolutionComponentsDetails;if(!Array.isArray(n))throw rr(t,`SolutionComponentsDetails is not a list (${Rt(n,60)})`);let i=[],o=[],a=new Set,s=new Set;return n.forEach((l,u)=>{let c=`SolutionComponentsDetails[${u}]`;if(!Zo(l))throw rr(t,`${c} is not an object`);if(typeof l.ComponentTypeName!="string")throw rr(t,`${c}.ComponentTypeName is not a string`);let d=l.ComponentTypeName.toLowerCase();if(d!=="environmentvariabledefinition"&&d!=="connectionreference")return;let f=d5(l.Attributes,`${c}.Attributes`,t),p=(m,h)=>{let g=f.get(m);if(g==null){if(h)throw rr(t,`${c}.${m} is missing`);return}if(typeof g!="string"||h&&g.length===0)throw rr(t,`${c}.${m} is not ${h?"a non-empty string":"a string"}`);return g};if(d==="environmentvariabledefinition"){let m=p("schemaname",!0);if(a.has(m.toLowerCase()))throw rr(t,`${c}.schemaname '${m}' is listed twice`);a.add(m.toLowerCase());let h=p("defaultvalue",!1),g=f5(f.get("type"),`${c}.type`,t),b=p5(f.get("isrequired"),`${c}.isrequired`,t);i.push({SchemaName:m,...h!==void 0?{DefaultValue:h}:{},...g!==void 0?{TypeId:g}:{},...b!==void 0?{IsRequired:b}:{}})}else{let m=p("connectionreferencelogicalname",!0);if(s.has(m.toLowerCase()))throw rr(t,`${c}.connectionreferencelogicalname '${m}' is listed twice`);s.add(m.toLowerCase());let h=p("connectorid",!1);o.push({LogicalName:m,...h!==void 0?{ConnectorId:h}:{}})}}),{variables:i,references:o}}function d5(e,t,r){if(!Zo(e)||!Array.isArray(e.Keys)||!Array.isArray(e.Values))throw rr(r,`${t} is not { Keys: [...], Values: [...] }`);let{Keys:n,Values:i}=e;if(n.length!==i.length)throw rr(r,`${t} has ${n.length} keys but ${i.length} values`);let o=new Map;return n.forEach((a,s)=>{if(typeof a!="string")throw rr(r,`${t}.Keys[${s}] is not a string`);if(o.has(a))throw rr(r,`${t}.Keys lists '${a}' twice`);o.set(a,i[s])}),o}function f5(e,t,r){if(e!=null){if(typeof e=="number"&&Number.isSafeInteger(e))return e;if(typeof e=="string"&&/^\d{1,15}$/.test(e))return Number(e);throw rr(r,`${t} is not a whole number (${Rt(e,40)})`)}}function p5(e,t,r){if(e!=null){if(typeof e=="boolean")return e;if(typeof e=="string"&&/^(true|false)$/i.test(e))return e.toLowerCase()==="true";throw rr(r,`${t} is not true or false (${Rt(e,40)})`)}}var m5=new Set(["EnvironmentVariables","ConnectionReferences","Workflows","CanvasApps","CopilotAgents","$schema"]),h5=["Workflows","CanvasApps","CopilotAgents"],g5=new Set(["SchemaName","Value","DefaultValue","TypeId","IsRequired","Name"]),y5=new Set(["LogicalName","ConnectionId","ConnectorId"]);function tr(e,t){return new Gt.InvalidArgumentError(`${tu}: deploymentSettings is not a deployment-settings file this SDK applies \u2014 ${e} ${t}. Nothing was imported.`)}function b5(e){let t="deploymentSettings";if(!Zo(e))throw tr(t,`must be an object \u2014 the settings file, parsed (it was ${Rt(e,40)})`);for(let l of Object.keys(e))if(!m5.has(l))throw tr(`${t}.${l}`,"is not part of the format (EnvironmentVariables, ConnectionReferences; Workflows, CanvasApps and CopilotAgents only empty; $schema)");for(let l of h5){let u=e[l];if(u!==void 0&&!(Array.isArray(u)&&u.length===0))throw tr(`${t}.${l}`,"is a pac feature this SDK does not apply: only an empty list is accepted")}if(e.$schema!==void 0&&typeof e.$schema!="string")throw tr(`${t}.$schema`,"must be a string");let r=l=>{let u=e[l];if(u===void 0)return[];if(!Array.isArray(u))throw tr(`${t}.${l}`,`must be a list (it was ${Rt(u,40)})`);return u.map((c,d)=>{if(!Zo(c))throw tr(`${t}.${l}[${d}]`,`must be an object (it was ${Rt(c,40)})`);return c})},n=(l,u,c)=>{let d=l[u];if(typeof d!="string"||d.length===0)throw tr(c,`must be a non-empty string (it was ${Rt(d,40)})`);if(d.trim()!==d)throw tr(c,`must not begin or end with whitespace (it was ${Rt(d,60)})`);return d},i=(l,u,c)=>{if(l.has(u.toLowerCase()))throw tr(c,`names '${u}' a second time (names are case-insensitive)`);l.add(u.toLowerCase())},o={variables:[],references:[]},a=new Set;r("EnvironmentVariables").forEach((l,u)=>{let c=`${t}.EnvironmentVariables[${u}]`;for(let f of Object.keys(l))if(!g5.has(f))throw tr(`${c}.${f}`,"is not part of a variable (SchemaName, Value; DefaultValue, TypeId, IsRequired, Name)");let d=n(l,"SchemaName",`${c}.SchemaName`);if(i(a,d,`${c}.SchemaName`),typeof l.Value!="string")throw tr(`${c}.Value`,`must be a string \u2014 empty to override nothing (it was ${Rt(l.Value,40)})`);l.Value.length>0&&o.variables.push({name:d,value:l.Value})});let s=new Set;return r("ConnectionReferences").forEach((l,u)=>{let c=`${t}.ConnectionReferences[${u}]`;for(let p of Object.keys(l))if(!y5.has(p))throw tr(`${c}.${p}`,p==="ConnectionInstance"?"is pac's connection-instance feature, which this SDK does not apply":"is not part of a connection reference (LogicalName, ConnectionId, ConnectorId)");let d=n(l,"LogicalName",`${c}.LogicalName`);i(s,d,`${c}.LogicalName`);let f=l.ConnectionId;if(typeof f!="string")throw tr(`${c}.ConnectionId`,`must be a string \u2014 empty to bind nothing (it was ${Rt(f,40)})`);if(f.trim()!==f)throw tr(`${c}.ConnectionId`,`must not begin or end with whitespace (it was ${Rt(f,60)})`);if(l.ConnectorId!==void 0&&typeof l.ConnectorId!="string")throw tr(`${c}.ConnectorId`,`must be a string (it was ${Rt(l.ConnectorId,40)})`);f.length>0&&o.references.push({name:d,connectionId:f,...l.ConnectorId?{connectorId:l.ConnectorId}:{}})}),o}function JS(e,t=20){return e.length===0?"none":`${e.slice(0,t).join(", ")}${e.length>t?` (+${e.length-t} more)`:""}`}function v5(e,t){var r;let n=new Map(e.variables.map(l=>[l.SchemaName.toLowerCase(),l])),i=new Map(e.references.map(l=>[l.LogicalName.toLowerCase(),l])),o=[],a=[],s={environmentVariables:[],connectionReferences:[]};for(let l of t.variables){let u=n.get(l.name.toLowerCase());if(!u){o.push(`EnvironmentVariables: '${l.name}' is not a variable of the package`);continue}a.push({"@odata.type":"Microsoft.Dynamics.CRM.environmentvariablevalue",schemaname:u.SchemaName,value:l.value}),s.environmentVariables.push(u.SchemaName)}for(let l of t.references){let u=i.get(l.name.toLowerCase());if(!u){o.push(`ConnectionReferences: '${l.name}' is not a connection reference of the package`);continue}if(l.connectorId!==void 0&&l.connectorId.toLowerCase()!==((r=u.ConnectorId)===null||r===void 0?void 0:r.toLowerCase())){o.push(`ConnectionReferences: '${l.name}' names connector '${l.connectorId}', but the package's reference is for ${u.ConnectorId?`'${u.ConnectorId}'`:"no connector"}`);continue}a.push({"@odata.type":"Microsoft.Dynamics.CRM.connectionreference",connectionreferencelogicalname:u.LogicalName,connectionid:l.connectionId,...u.ConnectorId!==void 0?{connectorid:u.ConnectorId}:{}}),s.connectionReferences.push(u.LogicalName)}if(o.length>0){let l=o.join("; "),u=JS(wd(e.variables,d=>d.SchemaName).map(d=>d.SchemaName)),c=JS(wd(e.references,d=>d.LogicalName).map(d=>d.LogicalName));throw new Gt.InvalidArgumentError(`${tu}: deploymentSettings does not match the package \u2014 ${l}. The package's variables: ${u}; its connection references: ${c}. Nothing was imported.`)}return{parameters:a,applied:s}}async function w5(e,t){let n=`/solutions(${(0,nr.normalizeGuid)(t,"solutionId")})`;(0,Lt.ensureSuccess)(await e.delete(n),e.apiUrl(n))}me.deleteSolution=w5});var nN=v(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.recoverFormCreate=ut.solutionMembershipProblem=ut.formWriteMismatches=ut.validateExistingForm=ut.formExistsAtId=ut.isFormRecordAt=ut.MAIN_FORM_TYPE=void 0;var cs=ue(),XS=Xt(),ZS=mg();ut.MAIN_FORM_TYPE=2;function Cd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ed(e){return e instanceof Error?e.message:String(e)}function hg(e,t){if(typeof e!="string"||typeof t!="string")return!1;try{return(0,cs.normalizeGuid)(e,"a GUID")===(0,cs.normalizeGuid)(t,"a GUID")}catch{return!1}}function gg(e,t){return Cd(e)&&hg(e.formid,t)}ut.isFormRecordAt=gg;async function C5(e,t){try{return gg((await e()).raw,t)}catch{return!1}}ut.formExistsAtId=C5;function eN(e,t){let r=e.raw;if(!Cd(r))return{problem:"it is not a record"};if(!gg(r,t))return{problem:"its formid is not the id this create sent"};if(r.type!==ut.MAIN_FORM_TYPE)return{problem:`its type is not ${ut.MAIN_FORM_TYPE} (a Main form)`};if(typeof r.objecttypecode!="string")return{problem:"its objecttypecode is not a string"};if(typeof r.name!="string")return{problem:"its name is not a string"};if(typeof r.formxml!="string"||r.formxml.length===0)return{problem:"its formxml is not a non-empty string"};if(typeof r.formpresentation!="number")return{problem:"its formpresentation is not a number"};if(typeof r.formactivationstate!="number")return{problem:"its formactivationstate is not a number"};for(let o of["uniquename","description"]){let a=r[o];if(a!=null&&typeof a!="string")return{problem:`its ${o} is neither a string nor null`}}let n=r["@odata.etag"];if(n!==void 0&&typeof n!="string")return{problem:"its @odata.etag is not a string"};if(n!==void 0&&e.etag!==null&&e.etag!==n)return{problem:"the ETag header and the @odata.etag of the body disagree"};let i=e.etag;return i===null?{problem:"the read carries no concurrency token"}:i.trim()===""||i.trim()==="*"?{problem:"its concurrency token is blank or a wildcard"}:{record:r,etag:i}}ut.validateExistingForm=eN;function tN(e,t){let r=[];for(let i of["formxml","name","objecttypecode","type"])e[i]!==t[i]&&r.push(i);let n=t.description;if(n!==void 0){let i=e.description;typeof n=="string"&&(n===""?i==null||i==="":i===n)||r.push("description")}return r}ut.formWriteMismatches=tN;async function rN(e,t){let r=e.solutionName;if(r)try{let n=await(0,XS.collectPages)(e,`/solutions${(0,cs.odataQuery)([["$select","solutionid,uniquename"],["$filter",`uniquename eq '${(0,cs.odataLiteral)(r)}'`]])}`,"createRecovery solution lookup");if(n.length!==1)return`the configured solution '${r}' resolves to ${n.length} solutions, not exactly one`;let[i]=n,o;return Cd(i)&&typeof i.uniquename=="string"&&typeof i.solutionid=="string"&&i.uniquename.toLowerCase()===r.toLowerCase()&&(o=(0,cs.normalizeGuid)(i.solutionid,"solutionid")),o===void 0?`the configured solution '${r}' did not resolve to a valid solution of that name`:(await(0,XS.collectPages)(e,`/solutioncomponents${(0,cs.odataQuery)([["$select","objectid,componenttype,_solutionid_value"],["$filter",`_solutionid_value eq ${o} and componenttype eq ${ZS.SolutionComponentType.SystemForm} and objectid eq ${t}`]])}`,"createRecovery solution membership")).some(l=>Cd(l)&&l.componenttype===ZS.SolutionComponentType.SystemForm&&hg(l.objectid,t)&&hg(l._solutionid_value,o))?void 0:`the form is not a component of the configured solution '${r}'`}catch(n){return`membership in the configured solution '${r}' could not be established (${Ed(n)})`}}ut.solutionMembershipProblem=rN;async function E5(e){try{return await A5(e)}catch(t){return{refused:`the recovery could not be completed (${Ed(t)})`}}}ut.recoverFormCreate=E5;async function A5(e){let{client:t,read:r,sent:n,authoredFormType:i,project:o}=e;if(i!=="Main"||n.type!==ut.MAIN_FORM_TYPE)return{refused:`only a Main form is adopted (this one is authored as ${String(i)})`};let a=n.formid;if(typeof a!="string")return{refused:"the create sent no formid to look for"};let s;try{s=await r()}catch(f){return{refused:`the existing row could not be read (${Ed(f)})`}}let l=eN(s,a);if("problem"in l)return{refused:`the existing row cannot be trusted: ${l.problem}`};let u=tN(l.record,n);if(u.length>0)return{refused:`the existing row is not what this create wrote (it differs in ${u.join(", ")})`};let c;try{c=o(l.record)}catch(f){return{refused:`the existing row could not be read into a form (${Ed(f)})`}}let d=await rN(t,a);return d!==void 0?{refused:d}:{adopted:{artifact:c,etag:l.etag}}}});var Nd=v(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.disassociateRecords=je.associateRecords=je.createRecordsBulk=je.upsertRecord=je.queryAllRecords=je.queryRecords=je.getRecord=je.deleteRecord=je.updateRecord=je.createRecord=void 0;var S5=Xt(),Cn=ye(),Wt=ue(),Ad=Q(),jn=sd();function Sd(e){let t=e,r=!1,n={};for(let i of Object.keys(t)){let o=t[i];Array.isArray(o)&&o.every(a=>typeof a=="number")?(n[i]=o.join(","),r=!0):n[i]=o}return r?n:e}async function N5(e,t,r){let i=`/${await(0,jn.resolveEntitySetName)(e,t)}`,o=(0,Cn.ensureSuccess)(await e.post(i,Sd(r)),e.apiUrl(i)),a=(0,Cn.readCreatedId)(o,`${t}id`);if(!a)throw new Ad.InvalidArgumentError(`Dataverse did not return an id for the created '${t}' row`);return{id:a,entityType:t}}je.createRecord=N5;async function _5(e,t,r,n){let i=(0,Wt.normalizeGuid)(r,"id"),a=`/${await(0,jn.resolveEntitySetName)(e,t)}(${i})`;(0,Cn.ensureSuccess)(await e.patch(a,Sd(n)),e.apiUrl(a))}je.updateRecord=_5;async function T5(e,t,r){let n=(0,Wt.normalizeGuid)(r,"id"),o=`/${await(0,jn.resolveEntitySetName)(e,t)}(${n})`;(0,Cn.ensureSuccess)(await e.delete(o),e.apiUrl(o))}je.deleteRecord=T5;async function D5(e,t,r,n){var i;let o=(0,Wt.normalizeGuid)(r,"id"),a=await(0,jn.resolveEntitySetName)(e,t),s=(0,Wt.odataQuery)([["$select",n&&n.length>0?n.join(","):void 0]]),l=`/${a}(${o})${s}`;return(i=(0,Cn.ensureSuccess)(await e.get(l),e.apiUrl(l)).body)!==null&&i!==void 0?i:{}}je.getRecord=D5;function I5(e){return e?.fetchXml?(0,Wt.odataQuery)([["fetchXml",e.fetchXml]]):(0,Wt.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 iN(e,t,r){var n,i;if(r?.paginate){if(r.top!==void 0)throw new Ad.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 Ad.InvalidArgumentError("queryRecords: `paginate` is not supported with `fetchXml` \u2014 FetchXML paging uses a paging cookie (page / fetchxmlpagingcookie), not @odata.nextLink. Page the FetchXML manually, or use an OData query.")}let a=`/${await(0,jn.resolveEntitySetName)(e,t)}${I5(r)}`;return r?.paginate?(0,S5.collectPages)(e,a,"queryRecords"):(i=(n=(0,Cn.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]}je.queryRecords=iN;async function O5(e,t,r){return iN(e,t,{...r,paginate:!0})}je.queryAllRecords=O5;function P5(e){if("id"in e)return`(${(0,Wt.normalizeGuid)(e.id,"id")})`;let t=typeof e.value=="string"?`'${(0,Wt.odataPathLiteral)(e.value)}'`:e.value;return`(${(0,Wt.assertODataName)(e.key,"alternate key name")}=${t})`}async function R5(e,t,r,n){let i=P5(r),a=`/${await(0,jn.resolveEntitySetName)(e,t)}${i}`,s=(0,Cn.ensureSuccess)(await e.patch(a,Sd(n)),e.apiUrl(a)),l=s.status===201,u=(0,Cn.readCreatedId)(s,`${t}id`);return{id:u??("id"in r?(0,Wt.normalizeGuid)(r.id,"id"):""),created:l}}je.upsertRecord=R5;async function L5(e,t,r){var n,i;if(r.length===0)return[];let o=await(0,jn.resolveEntitySetName)(e,t),a=r.map(c=>({"@odata.type":`Microsoft.Dynamics.CRM.${t}`,...Sd(c)})),s=`/${o}/Microsoft.Dynamics.CRM.CreateMultiple`,u=(i=(n=(0,Cn.ensureSuccess)(await e.post(s,{Targets:a}),e.apiUrl(s)).body)===null||n===void 0?void 0:n.Ids)!==null&&i!==void 0?i:[];if(u.length!==r.length)throw new Ad.InvalidArgumentError(`CreateMultiple on '${t}' returned ${u.length} id(s) for ${r.length} row(s)`);return u}je.createRecordsBulk=L5;async function k5(e,t,r,n){let i=(0,Wt.normalizeGuid)(r,"id"),o=(0,Wt.normalizeGuid)(n.targetId,"targetId"),a=await(0,jn.resolveEntitySetName)(e,t),s=await(0,jn.resolveEntitySetName)(e,n.targetEntity),l=(0,Wt.assertODataName)(n.relationshipName,"relationshipName"),u=`/${a}(${i})/${l}/$ref`,c={"@odata.id":e.apiUrl(`/${s}(${o})`)};(0,Cn.ensureSuccess)(await e.post(u,c),e.apiUrl(u))}je.associateRecords=k5;async function x5(e,t,r,n,i){let o=(0,Wt.normalizeGuid)(r,"id"),a=(0,Wt.normalizeGuid)(i,"targetId"),s=await(0,jn.resolveEntitySetName)(e,t),l=(0,Wt.assertODataName)(n,"relationshipName"),u=`/${s}(${o})/${l}(${a})/$ref`;(0,Cn.ensureSuccess)(await e.delete(u),e.apiUrl(u))}je.disassociateRecords=x5});var Td=v(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.base64ToUtf8=Hn.base64ToBytes=Hn.bytesToBase64=Hn.utf8ToBase64=void 0;var yg=32768,Er="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function _d(){return globalThis}function $5(e){let t=[];for(let r=0;r<e.length;r+=1){let n=e.charCodeAt(r);if(n>=55296&&n<=56319){let i=r+1<e.length?e.charCodeAt(r+1):0;i>=56320&&i<=57343?(n=(n-55296<<10)+(i-56320)+65536,r+=1):n=65533}else n>=56320&&n<=57343&&(n=65533);n<128?t.push(n):n<2048?t.push(192|n>>6,128|n&63):n<65536?t.push(224|n>>12,128|n>>6&63,128|n&63):t.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|n&63)}return Uint8Array.from(t)}function F5(e){let t="";for(let r=0;r<e.length;r+=yg)t+=String.fromCharCode(...e.subarray(r,r+yg));return t}function M5(e){let t="";for(let r=0;r<e.length;r+=1){let n=String.fromCharCode(e.charCodeAt(r)&255);if(n==="=")break;n==="-"?t+="+":n==="_"?t+="/":Er.indexOf(n)>=0&&(t+=n)}for(t.length%4===1&&(t=t.slice(0,-1));t.length%4!==0;)t+="=";return t}function U5(e){let t="",r=0;for(;r+2<e.length;r+=3){let i=e[r]<<16|e[r+1]<<8|e[r+2];t+=Er[i>>18&63]+Er[i>>12&63]+Er[i>>6&63]+Er[i&63]}let n=e.length-r;if(n===1){let i=e[r]<<16;t+=`${Er[i>>18&63]}${Er[i>>12&63]}==`}else if(n===2){let i=e[r]<<16|e[r+1]<<8,o=Er[i>>18&63],a=Er[i>>12&63],s=Er[i>>6&63];t+=`${o}${a}${s}=`}return t}function B5(e){let t=e.endsWith("==")?2:e.endsWith("=")?1:0,r=e.length/4*3-t,n=new Uint8Array(r>0?r:0),i=0;for(let o=0;o<e.length;o+=4){let a=Er.indexOf(e[o])<<18|Er.indexOf(e[o+1])<<12|(e[o+2]==="="?0:Er.indexOf(e[o+2]))<<6|(e[o+3]==="="?0:Er.indexOf(e[o+3]));i<r&&(n[i++]=a>>16&255),i<r&&(n[i++]=a>>8&255),i<r&&(n[i++]=a&255)}return n}function q5(e){let t=_d();if(t.Buffer)return t.Buffer.from(e,"utf8").toString("base64");let r=t.TextEncoder;return oN(r?new r().encode(e):$5(e))}Hn.utf8ToBase64=q5;function oN(e){let t=_d();return t.Buffer?t.Buffer.from(e).toString("base64"):t.btoa?t.btoa(F5(e)):U5(e)}Hn.bytesToBase64=oN;function aN(e){let t=_d();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"base64"));let r=M5(e);if(t.atob){let n=t.atob(r);return Uint8Array.from(n,i=>i.charCodeAt(0))}return B5(r)}Hn.base64ToBytes=aN;function V5(e){let t=[],r="",n=()=>{r+=String.fromCharCode(...t),t.length=0},i=a=>{if(a>65535){let s=a-65536;t.push(55296+(s>>10),56320+(s&1023))}else t.push(a);t.length>=yg&&n()},o=0;for(;o<e.length;){let a=e[o],s=0,l=0,u=128,c=191;if(a<128){i(a),o+=1;continue}else if(a>=194&&a<=223)s=1,l=a&31;else if(a>=224&&a<=239)s=2,l=a&15,u=a===224?160:128,c=a===237?159:191;else if(a>=240&&a<=244)s=3,l=a&7,u=a===240?144:128,c=a===244?143:191;else{i(65533),o+=1;continue}let d=o+1,f=!0;for(let p=0;p<s;p+=1,d+=1){let m=d<e.length?e[d]:-1;if(m<u||m>c){f=!1;break}u=128,c=191,l=l<<6|m&63}f?(i(l),o=d):(i(65533),o=d)}return n(),r}function G5(e){let t=_d();return t.Buffer?t.Buffer.from(e,"base64").toString("utf8"):V5(aN(e))}Hn.base64ToUtf8=G5});var cN=v(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.deleteWebResource=Kn.getWebResource=Kn.updateWebResource=Kn.createWebResource=void 0;var W5=Kr(),ru=ye(),Dd=ue(),z5=Td(),sN=Q(),j5={html:1,css:2,js:3,xml:4,png:5,jpg:6,gif:7,xsl:9,ico:10,svg:11,resx:12};function lN(e){if(e.contentBase64!==void 0)return e.contentBase64;if(e.content!==void 0)return(0,z5.utf8ToBase64)(e.content)}async function uN(e,t){return(0,W5.publishWebResourceById)(e,t)}async function H5(e,t){var r;let n=lN(t);if(n===void 0)throw new sN.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:j5[t.type],content:n};t.description&&(i.description=t.description);let o=(0,ru.ensureSuccess)(await e.post("/webresourceset",i),e.apiUrl("/webresourceset")),a=(0,ru.readCreatedId)(o,"webresourceid");if(!a)throw new sN.InvalidArgumentError(`Dataverse did not return an id for web resource '${t.name}'`);return t.publish!==!1&&await uN(e,a),{id:a,name:t.name}}Kn.createWebResource=H5;async function K5(e,t,r){let n=(0,Dd.normalizeGuid)(t,"id"),i={},o=lN(r);o!==void 0&&(i.content=o),r.displayName!==void 0&&(i.displayname=r.displayName),r.description!==void 0&&(i.description=r.description);let a=`/webresourceset(${n})`;(0,ru.ensureSuccess)(await e.patch(a,i),e.apiUrl(a)),r.publish!==!1&&await uN(e,n)}Kn.updateWebResource=K5;async function J5(e,t){var r;let i=`/webresourceset(${(0,Dd.normalizeGuid)(t,"id")})${(0,Dd.odataQuery)([["$select","name,displayname,webresourcetype,content,description"]])}`;return(r=(0,ru.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)!==null&&r!==void 0?r:{}}Kn.getWebResource=J5;async function Y5(e,t){let n=`/webresourceset(${(0,Dd.normalizeGuid)(t,"id")})`;(0,ru.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Kn.deleteWebResource=Y5});var Id=v(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.applyAppSettings=At.setAppSetting=At.readAppSettings=At.resolveSettingDefinitions=At.APP_SETTING_UNSET=At.APP_SETTING_OFF=At.APP_SETTING_ON=At.HEADER_AND_NAVIGATION_REFRESH=void 0;var ds=ye(),Di=ue();At.HEADER_AND_NAVIGATION_REFRESH="HeaderAndNavigationRefresh";At.APP_SETTING_ON="2";At.APP_SETTING_OFF="1";At.APP_SETTING_UNSET="0";function pN(e,t){return"/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Di.odataQuery)([["$select",e],["$filter",t]])}async function mN(e,t){var r,n;let i=[...new Set(t.filter(Boolean))],o=new Map;if(i.length===0)return o;let a=i.map(c=>`uniquename eq '${(0,Di.odataLiteral)(c)}'`).join(" or "),s=`/settingdefinitions${(0,Di.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",a]])}`,u=((n=(r=(0,ds.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]).filter(Boolean);for(let c of u)c.uniquename&&o.set(c.uniquename,c);return o}At.resolveSettingDefinitions=mN;async function Q5(e,t){var r,n,i,o;let a=(0,Di.normalizeGuid)(t,"App id"),s=pN("appsettingid,value,_settingdefinitionid_value",`_parentappmoduleid_value eq ${a}`),u=((n=(r=(0,ds.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(f=>f._settingdefinitionid_value).filter(Boolean))],d=new Map;if(c.length>0){let f=c.map(h=>`settingdefinitionid eq ${(0,Di.normalizeGuid)(h,"Setting definition id")}`).join(" or "),p=`/settingdefinitions${(0,Di.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",f]])}`,m=(0,ds.ensureSuccess)(await e.get(p),e.apiUrl(p));for(let h of((o=(i=m.body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[]).filter(Boolean))h.settingdefinitionid&&d.set(h.settingdefinitionid.toLowerCase(),h)}return u.map(f=>{var p,m,h,g,b;let w=d.get(((p=f._settingdefinitionid_value)!==null&&p!==void 0?p:"").toLowerCase());return{id:(m=f.appsettingid)!==null&&m!==void 0?m:"",name:(g=(h=w?.uniquename)!==null&&h!==void 0?h:f._settingdefinitionid_value)!==null&&g!==void 0?g:"",value:(b=f.value)!==null&&b!==void 0?b:"",...w?.displayname?{displayName:w.displayname}:{}}})}At.readAppSettings=Q5;async function dN(e,t,r){var n,i,o;let a=pN("appsettingid,value",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${r}`),l=((i=(n=(0,ds.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]).filter(Boolean)[0];return l?.appsettingid?{id:l.appsettingid,value:(o=l.value)!==null&&o!==void 0?o:""}:void 0}async function hN(e,t,r,n){let i=(0,Di.normalizeGuid)(t,"App id"),a=(await mN(e,[r])).get(r),s=a?.settingdefinitionid;if(!s)throw new Error(`App setting '${r}' is not available in this environment: no settingdefinition row has that uniquename. The feature may be version-gated or its solution may not be installed.`);let l=(0,Di.normalizeGuid)(s,"Setting definition id"),u=await dN(e,i,l);if(u)return fN(e,u,n);let c="/appsettings",d={"[email protected]":`/appmodules(${i})`,"[email protected]":`/settingdefinitions(${l})`,value:n},f,p;try{if(f=await e.post(c,d),f.status>=200&&f.status<300)return"created"}catch(h){p=h}let m;try{m=await dN(e,i,l)}catch{m=void 0}if(m)return fN(e,m,n);throw f&&(0,ds.ensureSuccess)(f,e.apiUrl(c)),p}At.setAppSetting=hN;async function fN(e,t,r){if(t.value===r)return"unchanged";let n=`/appsettings(${(0,Di.normalizeGuid)(t.id,"App setting id")})`;return(0,ds.ensureSuccess)(await e.patch(n,{value:r}),e.apiUrl(n)),"updated"}async function X5(e,t,r){var n;let i=[];for(let[o,a]of Object.entries(r??{}))try{await hN(e,t,o,a)}catch(s){i.push(`App setting '${o}' was not applied: ${(n=s?.message)!==null&&n!==void 0?n:String(s)} The app was created; set it later with setAppSetting().`)}return i}At.applyAppSettings=X5});var Pd=v(Od=>{"use strict";Object.defineProperty(Od,"__esModule",{value:!0});Od.HEADER_NAV_BOOLEAN_RULE=void 0;Od.HEADER_NAV_BOOLEAN_RULE="headerAndNavigationRefresh-must-be-boolean"});var Cg=v(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.compileGenPage=Oe.legacyEnumsNeeded=Oe.createGenPageTypeScriptLoader=Oe.acceptGenPageTypeScript=Oe.isLoadableGenPageOutput=Oe.runtimeTypesImportSpans=Oe.GENPAGE_RUNTIME_TYPES_END=Oe.GENPAGE_RUNTIME_TYPES_BEGIN=Oe.GENPAGE_TYPESCRIPT_VERSION=void 0;var fs=Q();Oe.GENPAGE_TYPESCRIPT_VERSION="5.8.3";Oe.GENPAGE_RUNTIME_TYPES_BEGIN="// --- BEGIN GENERATED RUNTIME TYPES ---";Oe.GENPAGE_RUNTIME_TYPES_END="// --- END GENERATED RUNTIME TYPES ---";var En="./RuntimeTypes",Z5="'\"`",gN=/\s/;function e8(e){return e===10||e===13||e===8232||e===8233}function t8(e,t){let r=[];e.lastIndex=0;for(let n=e.exec(t);n!==null;n=e.exec(t))r.push(n.index);return r}function wN(e){let t=[],r=En.length;for(let l=e.indexOf(En);l!==-1;l=e.indexOf(En,l+1)){let u=l-1;u>=0&&Z5.includes(e[u])&&e[u+1+r]===e[u]&&t.push(u)}let n=[];if(t.length===0)return n;let i=-1,o=l=>{if(i<l)for(i=l;i<e.length&&e[i]!=="'"&&e[i]!=='"';)i+=1;return i},a=-1,s=l=>{for(;a+1<t.length&&t[a+1]<=l;)a+=1;return a>=0?t[a]:-1/0};for(let l=e.indexOf("import");l!==-1;){let u=l+1;if(l+6<e.length&&gN.test(e[l+6])){let c=s(o(l+6));if(c>=l+8){let d=c+2+r;for(e[d]===";"&&(d+=1);d<e.length&&gN.test(e[d]);)d+=1;n.push({start:l,end:d}),u=d}}l=e.indexOf("import",u)}return n}Oe.runtimeTypesImportSpans=wN;var r8=/\b(?:import\s*['"]|export\s)/;function n8(e){let t=t8(/from\s+['"]/g,e);if(t.length===0)return!1;let r=/\bimport\s/g,n=-1,i=0;for(let o=r.exec(e);o!==null;o=r.exec(e)){let a=o.index+7;if(a>n)for(n=a;n<e.length&&!e8(e.charCodeAt(n));)n+=1;for(;i<t.length&&t[i]<a+1;)i+=1;if(i<t.length&&t[i]<n)return!0}return!1}function i8(e){return e!==void 0&&e!==""&&(r8.test(e)||n8(e))}Oe.isLoadableGenPageOutput=i8;var yN=["transpileModule","createSourceFile","createProgram","getParseTreeNode","flattenDiagnosticMessageText","forEachChild","getModifiers","canHaveModifiers","isImportDeclaration","isExportDeclaration","isExportAssignment","isStringLiteral"];function CN(e){var t;let r=s=>s!==null&&(typeof s=="object"||typeof s=="function")?s:void 0,n=r(e);n&&typeof n.transpileModule!="function"&&(n=(t=r(n.default))!==null&&t!==void 0?t:n);let i=n?yN.filter(s=>typeof n?.[s]!="function"):[...yN];if(!n||i.length>0)throw new fs.SdkError("GENPAGE_COMPILER_INVALID",`The TypeScript compiler supplied as MakerSdkOptions.typescript is not the typescript module (missing ${i.join(", ")}). Pass the 'typescript' package's module object, loadNodeTypeScript from '@maker-studio/cds-maker-sdk/node', or \u2014 in a bare engine \u2014 globalThis.ts after evaluating typescript@${Oe.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js.`);let o=typeof n.version=="string"?n.version:"",a=Oe.GENPAGE_TYPESCRIPT_VERSION.split(".").slice(0,2).join(".");if(o.split(".").slice(0,2).join(".")!==a)throw new fs.SdkError("GENPAGE_COMPILER_VERSION",`The TypeScript compiler supplied as MakerSdkOptions.typescript is version '${o||"unknown"}', but generative pages are compiled with ${a}.x \u2014 the version the maker portal itself uses (${Oe.GENPAGE_TYPESCRIPT_VERSION}). Another version can emit different JavaScript for the same page. Supply typescript@${Oe.GENPAGE_TYPESCRIPT_VERSION}.`);return n}Oe.acceptGenPageTypeScript=CN;function o8(e){let t;return()=>{if(!t){if(e===void 0)return Promise.reject(new fs.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`This push must compile a generative page, but no TypeScript compiler was supplied. Pass MakerSdkOptions.typescript \u2014 in Node, loadNodeTypeScript from '@maker-studio/cds-maker-sdk/node'; in a bare engine, globalThis.ts after evaluating typescript@${Oe.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js. Nothing was written.`));t=Promise.resolve().then(()=>typeof e=="function"?e():e).then(CN).catch(r=>{throw t=void 0,r instanceof fs.SdkError?r:new fs.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`The TypeScript compiler could not be loaded, so a generative page cannot be compiled (${r instanceof Error?r.message:String(r)}). Nothing was written.`)})}return t}}Oe.createGenPageTypeScriptLoader=o8;var EN=e=>`${e.kind}:${e.pos}:${e.end}`;function a8(e,t){return()=>r=>{let n=i=>{let o=e.getParseTreeNode(i);o&&t.add(EN(o)),e.forEachChild(i,n)};return n(r),r}}function wg(e){return{target:e.ScriptTarget.ES5,module:e.ModuleKind.ES2020,jsx:e.JsxEmit.React}}var s8=2301;function bN(e,t,r){var n;let i=e.transpileModule(t,{compilerOptions:wg(e),reportDiagnostics:!0,...r?{transformers:{after:[a8(e,r)]}}:{}}),o=((n=i.diagnostics)!==null&&n!==void 0?n:[]).filter(a=>a.category===e.DiagnosticCategory.Error).map(a=>{let s=a.file&&typeof a.start=="number"?a.file.getLineAndCharacterOfPosition(a.start):{line:0,character:0};return{line:s.line+1,column:s.character+1,rule:"genpage-source-syntax",code:a.code,message:e.flattenDiagnosticMessageText(a.messageText,`-`)}});return{code:i.outputText,diagnostics:o}}var vN=e=>e.startsWith(".")||e.startsWith("/"),bg={line:1,column:1};function vg(e,t){let r=o=>{let a=t.getLineAndCharacterOfPosition(o.getStart(t));return{line:a.line+1,column:a.character+1}},n=o=>(e.isImportDeclaration(o)||e.isExportDeclaration(o))&&o.moduleSpecifier&&e.isStringLiteral(o.moduleSpecifier)?o.moduleSpecifier.text:void 0,i=o=>t.statements.filter(a=>e.isImportDeclaration(a)&&n(a)===o);return{statement(o,a){let s=t.statements.find(l=>n(l)===o&&(a==="import"?e.isImportDeclaration(l):e.isExportDeclaration(l)));return s?r(s):bg},element(o,a){var s;for(let l of i(o)){let u=(s=l.importClause)===null||s===void 0?void 0:s.namedBindings,c=u&&e.isNamedImports(u)?u.elements.find(d=>d.name.text===a):void 0;if(c)return r(c)}return this.statement(o,"import")},binding(o){var a,s;for(let l of t.statements)if(e.isImportDeclaration(l)&&l.importClause){let u=l.importClause,c=u.namedBindings,d=((a=u.name)===null||a===void 0?void 0:a.text)===o?u.name:c&&e.isNamespaceImport(c)&&c.name.text===o?c.name:c&&e.isNamedImports(c)?c.elements.find(f=>f.name.text===o):void 0;if(d)return r(d)}else{if((e.isFunctionDeclaration(l)||e.isClassDeclaration(l))&&((s=l.name)===null||s===void 0?void 0:s.text)===o)return r(l.name);if(e.isVariableStatement(l)){let u=l.declarationList.declarations.find(c=>e.isIdentifier(c.name)&&c.name.text===o);if(u)return r(u.name)}}return bg}}}function l8(e,t,r,n){var i,o;let a=[],s=vg(e,r),l=(m,h,g)=>{a.push({...m,rule:h,code:0,message:g})},u=(m,h)=>{var g;return(e.canHaveModifiers(m)?(g=e.getModifiers(m))!==null&&g!==void 0?g:[]:[]).some(b=>b.kind===h)},c=(m,h)=>l(m,"genpage-relative-import",`'${h}' cannot resolve at runtime: the page is loaded as a single module from a blob URL, so the only relative import it may have is './RuntimeTypes'`),d="genpage-runtime-types-import-form",f=!1,p=new Set;for(let m of t.statements){if(e.isExportAssignment(m)){f=f||!m.isExportEquals;continue}if(e.isFunctionDeclaration(m)||e.isClassDeclaration(m)){u(m,e.SyntaxKind.ExportKeyword)&&u(m,e.SyntaxKind.DefaultKeyword)&&(f=!0),m.name&&p.add(m.name.text);continue}if(e.isExportDeclaration(m)){let w=m.exportClause;w&&e.isNamedExports(w)&&w.elements.some(A=>A.name.text==="default")&&(f=!0);let E=m.moduleSpecifier&&e.isStringLiteral(m.moduleSpecifier)?m.moduleSpecifier.text:void 0;E===En?l(s.statement(E,"export"),d,"a page cannot re-export from './RuntimeTypes': that module does not exist at runtime"):E!==void 0&&vN(E)&&c(s.statement(E,"export"),E);continue}if(!e.isImportDeclaration(m)||!e.isStringLiteral(m.moduleSpecifier))continue;let h=m.moduleSpecifier.text,g=m.importClause;if(h!==En){vN(h)&&c(s.statement(h,"import"),h),g?.name&&p.add(g.name.text);let w=g?.namedBindings;w&&e.isNamespaceImport(w)?p.add(w.name.text):w&&e.isNamedImports(w)&&w.elements.forEach(E=>p.add(E.name.text));continue}if(!g){l(s.statement(h,"import"),d,"a side-effect import of './RuntimeTypes' cannot resolve at runtime; import the names it declares");continue}g.name&&l(s.binding(g.name.text),d,"'./RuntimeTypes' has no default export at runtime; import its names");let b=g.namedBindings;if(b&&e.isNamespaceImport(b))l(s.binding(b.name.text),d,"a namespace import of './RuntimeTypes' is undefined at runtime \u2014 its enums are inlined under their own names; import the names instead");else if(b&&e.isNamedImports(b))for(let w of b.elements){let E=w.name.text,A=(o=(i=w.propertyName)===null||i===void 0?void 0:i.text)!==null&&o!==void 0?o:E,L=s.element(h,E);A!==E?l(L,d,`'${A} as ${E}' would be undefined at runtime: the enum is inlined as '${A}', so import it under its own name`):n?.text?n.enums.has(E)||l(L,"genpage-runtime-types-unresolved",`'${E}' is imported from './RuntimeTypes' as a VALUE, but the runtime types define no value of that name \u2014 only the choice enums of the page's data sources are values. Import a type with 'import type'.`):l(L,"genpage-runtime-types-unresolved",`'${E}' is imported from './RuntimeTypes' as a VALUE, but the page has no data sources, so no runtime types are inlined and the import reaches the runtime, which cannot load it. Import it with 'import type', or add the table it belongs to to dataSources.`)}}if(f||l(bg,"genpage-no-default-export","the page has no default export \u2014 the runtime renders the module's default export as the page component"),n?.text)for(let m of p)n.enums.has(m)&&l(s.binding(m),"genpage-runtime-types-collision",`'${m}' is declared at the page's module scope and is also one of its inlined choice enums, so the compiled page would declare it twice and fail to load. Rename the page's binding, or import the enum from './RuntimeTypes'.`);return a}function AN(e,t,r){let n,i=()=>{if(!n){let m={getSourceFile:g=>g===t.fileName?t:void 0,getDefaultLibFileName:()=>"lib.d.ts",writeFile:()=>{},getCurrentDirectory:()=>"",getCanonicalFileName:g=>g,useCaseSensitiveFileNames:()=>!0,getNewLine:()=>`-`,fileExists:g=>g===t.fileName,readFile:()=>{},directoryExists:()=>!0,getDirectories:()=>[]},h={...r,noLib:!0,noResolve:!0,allowJs:!0,types:[],alwaysStrict:!0,moduleDetection:e.ModuleDetectionKind.Force};n=e.createProgram({rootNames:[t.fileName],options:h,host:m})}return n},o,a=()=>(o||(o=i().getTypeChecker()),o),s,l=()=>{if(!s){s=new Map;try{for(let m of i().getSemanticDiagnostics(t))m.code===s8&&typeof m.start=="number"&&s.set(m.start,e.flattenDiagnosticMessageText(m.messageText," "))}catch{}}return s},u=m=>e.isImportSpecifier(m)?m.parent.parent.parent:e.isImportClause(m)?m.parent:e.isNamespaceImport(m)?m.parent.parent:void 0,c=m=>{let h=u(m);return h!==void 0&&e.isImportDeclaration(h)&&e.isStringLiteral(h.moduleSpecifier)&&h.moduleSpecifier.text===En},d=m=>{var h;for(let g=m;g;g=g.parent)if(e.canHaveModifiers(g)&&((h=e.getModifiers(g))!==null&&h!==void 0?h:[]).some(b=>b.kind===e.SyntaxKind.DeclareKeyword))return!0;return!1},f=m=>d(m)||e.isImportEqualsDeclaration(m)&&(m.isTypeOnly||e.isExternalModuleReference(m.moduleReference))||e.isImportClause(m)&&m.isTypeOnly||e.isNamespaceImport(m)&&m.parent.isTypeOnly||e.isImportSpecifier(m)&&(m.isTypeOnly||m.parent.parent.isTypeOnly),p=m=>{var h;return((h=m?.declarations)!==null&&h!==void 0?h:[]).some(g=>!c(g)&&!f(g))};return{pageOwns:m=>{let h=m.parent;return p(e.isShorthandPropertyAssignment(h)&&h.name===m?a().getShorthandAssignmentValueSymbol(h):a().getSymbolAtLocation(m))},pageOwnsLocalExport:m=>p(a().getExportSpecifierLocalTargetSymbol(m)),initializerShadow:m=>l().get(m.getStart(t))}}function u8(e,t,r,n){let i=[],o=r?.enums;if(!o||o.size===0)return i;let a=(u,c,d)=>{let f=t.getLineAndCharacterOfPosition(u.getStart(t));i.push({line:f.line+1,column:f.character+1,rule:c,code:0,message:d})},s=AN(e,t,wg(e)),l=u=>{let c,d;if(e.isPropertyAccessExpression(u)&&e.isIdentifier(u.expression))c=u.expression,d=u.name.text;else if(e.isElementAccessExpression(u)&&e.isIdentifier(u.expression)){let p=u.argumentExpression;e.isStringLiteral(p)||e.isNoSubstitutionTemplateLiteral(p)?(c=u.expression,d=p.text):e.isNumericLiteral(p)&&(c=u.expression,d=String(Number(p.text)))}let f=c&&o.has(c.text)&&n.has(EN(u))&&!s.pageOwns(c)?o.get(c.text):void 0;if(c&&f&&d!==void 0){let p=e.isPropertyAccessExpression(u)?`${f.name}.${d}`:`${f.name}[${JSON.stringify(d)}]`,m=Object.prototype.hasOwnProperty.call(f.runtime,d)?f.runtime[d]:void 0,h=f.labels.get(d),g;m===void 0?g={rule:"genpage-enum-member-unknown",message:`${p} is undefined at runtime: '${f.name}' has no member '${d}' in this environment's metadata \u2014 members are the column's choice labels, so a renamed or differently localized label no longer matches. Known: ${[...f.labels.keys()].map(w=>`'${w}'`).join(", ")}`}:h&&typeof m!="number"?g={rule:"genpage-enum-member-clobbered",message:`${p} is the string '${String(m)}' at runtime, not a choice value: the label '${d}' looks like a number, and another option's reverse mapping overwrites it. Use the choice's numeric value instead.`}:h&&h.length>1&&(g={rule:"genpage-enum-member-ambiguous",message:`${p} labels more than one choice (${h.join(", ")}); the compiled value is whichever option comes last. Use the choice's numeric value instead.`});let b=g?s.initializerShadow(c):void 0;g&&b!==void 0?a(u,"genpage-enum-initializer-shadowed",`${p} does not read the choice enum at runtime. ${b} (TS2301): the ES5 emit moves an instance field's initializer into the constructor, where that parameter or local shadows '${c.text}'. If you meant the constructor's '${c.text}', move the assignment into the constructor body, or make it a parameter property and read \`this.${c.text}\`. If you meant the choice enum, rename the constructor's parameter or local.`):g&&a(u,g.rule,g.message)}e.forEachChild(u,l)};return l(t),i}function c8(e,t){return e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!1,e.ScriptKind.JS).statements.some(n=>(e.isImportDeclaration(n)||e.isExportDeclaration(n))&&n.moduleSpecifier!==void 0&&e.isStringLiteral(n.moduleSpecifier)&&n.moduleSpecifier.text===En)}function d8(e,t){let r=e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),n=new Set(r.statements.filter(s=>e.isImportDeclaration(s)&&e.isStringLiteral(s.moduleSpecifier)&&s.moduleSpecifier.text===En).map(s=>s.getStart(r))),i=!0,o="",a=0;for(let s of wN(t))n.has(s.start)||(i=!1),o+=t.slice(a,s.start),a=s.end;return o+=t.slice(a),{code:o,exact:i}}function SN(e,t,r){if(!r||r.size===0)return[];let n=AN(e,t,{...wg(e),target:e.ScriptTarget.ESNext}),i=new Set,o=s=>{var l,u;let c=s.parent;if(e.isImportSpecifier(c)){let d=c.parent.parent.parent;e.isImportDeclaration(d)&&e.isStringLiteral(d.moduleSpecifier)&&d.moduleSpecifier.text===En&&((l=c.propertyName)!==null&&l!==void 0?l:c.name)===s&&i.add(s.text);return}if(e.isExportSpecifier(c)){!(c.parent.parent.moduleSpecifier!==void 0)&&((u=c.propertyName)!==null&&u!==void 0?u:c.name)===s&&!n.pageOwnsLocalExport(c)&&i.add(s.text);return}e.isPropertyAccessExpression(c)&&c.name===s||e.isBindingElement(c)&&c.propertyName===s||e.isLabeledStatement(c)||e.isBreakOrContinueStatement(c)||n.pageOwns(s)||i.add(s.text)},a=s=>{e.isIdentifier(s)&&r.has(s.text)&&o(s),e.forEachChild(s,a)};return a(t),[...r.keys()].filter(s=>i.has(s))}Oe.legacyEnumsNeeded=SN;function f8(e,t,r){if(!e?.text||!t||r.length===0)return e;let n=new Map(e.enums),i=e.text;for(let o of r){let a=t.get(o);a&&(i+=a.declaration,n.set(o,a.model))}return{text:i,enums:n}}function p8(e,t,r,n){let i=new Set,o=bN(e,t,i);if(o.diagnostics.length>0)return o;let a=e.createSourceFile("page.tsx",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.TSX),s=e.createSourceFile("page.js",o.code,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),l=f8(r,n,SN(e,s,n)),u=[...l8(e,s,a,l),...u8(e,a,l,i)];if(!l?.text)return{code:o.code,diagnostics:u};let c=bN(e,l.text);if(c.diagnostics.length>0)throw new fs.SdkError("GENPAGE_RUNTIME_TYPES_INVALID",`The generated runtime types do not compile (${c.diagnostics.map(m=>`${m.line}:${m.column} ${m.message}`).join("; ")}). This is an SDK defect: the page was not written.`);let d=d8(e,o.code),f=d.code;return u.length===0&&!d.exact?u.push({...vg(e,a).statement(En,"import"),rule:"genpage-runtime-types-import-form",code:0,message:"the maker portal's patch would remove more than this './RuntimeTypes' import: a comment or other text before it contains the word 'import', and the pattern would delete from there \u2014 taking the code in between with it. Reword or move that text."}):u.length===0&&c8(e,f)&&u.push({...vg(e,a).statement(En,"import"),rule:"genpage-runtime-types-import-form",code:0,message:"this './RuntimeTypes' import is not one the maker portal's patch can remove (a comment holding a quote inside it stops the pattern), so it would reach the runtime, which cannot load it. Write it on one line, as 'import { name } from './RuntimeTypes';'."}),{code:[Oe.GENPAGE_RUNTIME_TYPES_BEGIN,c.code,Oe.GENPAGE_RUNTIME_TYPES_END,f].join(`+`).slice(1)){let l=s.indexOf(":");l>0&&(o[s.slice(0,l).trim()]=s.slice(l+1).trim())}let a=i===""?void 0:i;if(i!=="")try{a=JSON.parse(i)}catch{}return{status:e.status,headers:o,body:a}}Or.partResponse=tN;async function h9(e,t,r){let{body:n,batchId:i,contentIds:o}=Ng(e,t),a=await e.postBatch(n,i),s=e.apiUrl("/$batch"),l=_g(a.body,o),u=l?.find(c=>c.status<200||c.status>=300);if(u&&(0,Sg.ensureSuccess)(tN(u),e.apiUrl(t[o.indexOf(u.contentId)].path)),(0,Sg.ensureSuccess)(a,s),!l||l.length!==t.length)throw new bo.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the $batch response ${l?`reported ${l.length} result(s) for ${t.length} operation(s)`:"could not be parsed"}, so the outcome is unknown`);return o.map(c=>l.find(d=>d.contentId===c))}Or.sendChangeSet=h9});var $d=v(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.updateTable=ie.deleteAlternateKey=ie.createAlternateKey=ie.deleteGlobalOptionSet=ie.createGlobalOptionSet=ie.deleteRelationship=ie.deleteColumn=ie.updateColumn=ie.deleteTable=ie.createRelationship=ie.insertStatusValue=ie.createCustomerColumn=ie.createColumns=ie.setColumnVisualization=ie.getColumnVisualization=ie.createColumn=ie.createTable=ie.resolveEntitySetName=ie.pluralFallback=void 0;var Se=fe(),te=oe(),ri=sa(),he=Q(),g9=Es(),y9={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 tt(e,t){return{"@odata.type":"Microsoft.Dynamics.CRM.Label",LocalizedLabels:b9(e,t)}}var rN=65535;function b9(e,t){let r=(o,a)=>({"@odata.type":"Microsoft.Dynamics.CRM.LocalizedLabel",Label:o,LanguageCode:a});if(typeof e=="string")return[r(e,t)];let n=Object.entries(e);if(!n.length)throw new he.InvalidArgumentError("a localized label must contain at least one language");let i=new Set;return n.map(([o,a])=>{if(!/^[1-9]\d*$/.test(o))throw new he.InvalidArgumentError(`localized label key '${o}' is not an LCID (expected a canonical positive integer, e.g. 1033)`);let s=Number(o);if(s>rN)throw new he.InvalidArgumentError(`localized label LCID ${s} is out of range (1-${rN})`);if(i.has(s))throw new he.InvalidArgumentError(`localized label LCID ${s} is specified more than once`);if(i.add(s),typeof a!="string")throw new he.InvalidArgumentError(`localized label for LCID ${s} must be a string`);return r(a,s)})}function sN(e){return typeof e=="string"?`${e}s`:Object.fromEntries(Object.entries(e).map(([t,r])=>{if(typeof r!="string")throw new he.InvalidArgumentError(`localized label for LCID ${t} must be a string`);return[t,`${r}s`]}))}ie.pluralFallback=sN;function fu(e){return{Value:e,CanBeChanged:!0,ManagedPropertyLogicalName:"canmodifyrequirementlevelsettings"}}var nN=["None","ApplicationRequired","Recommended"];function Ig(e){let t=e.indexOf("_");return t>0?e.slice(0,t):e}function iN(e,t,r){let n=e[t];n&&typeof n=="object"?n.Value=r:e[t]={Value:r}}function pu(e){let t=(0,Se.readCreatedId)(e,"MetadataId");if(!t)throw new he.InvalidArgumentError("Dataverse did not return a MetadataId for the created metadata component");return t}function v9(e,t,r){var n,i,o,a,s,l,u,c,d,f,m,p,h,g,b,w,C,S,O,L,I,D,P,x;if(t.defaultValue!==void 0&&e!=="boolean")throw new he.InvalidArgumentError(`createColumn: 'defaultValue' applies to boolean columns, but '${t.schemaName}' is of type '${e}'.`);if(t.integerFormat!==void 0&&e!=="integer")throw new he.InvalidArgumentError(`createColumn: 'integerFormat' applies to integer columns, but '${t.schemaName}' is of type '${e}'.`);switch(e){case"string":return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},MaxLength:(n=t.maxLength)!==null&&n!==void 0?n:100,FormatName:{Value:(i=t.stringFormat)!==null&&i!==void 0?i:"Text"}};case"memo":return{"@odata.type":"Microsoft.Dynamics.CRM.MemoAttributeMetadata",AttributeType:"Memo",AttributeTypeName:{Value:"MemoType"},MaxLength:(o=t.maxLength)!==null&&o!==void 0?o:2e3,Format:"TextArea"};case"integer":return{"@odata.type":"Microsoft.Dynamics.CRM.IntegerAttributeMetadata",AttributeType:"Integer",AttributeTypeName:{Value:"IntegerType"},Format:(a=t.integerFormat)!==null&&a!==void 0?a:"None",MinValue:(s=t.minValue)!==null&&s!==void 0?s:-2147483648,MaxValue:(l=t.maxValue)!==null&&l!==void 0?l:2147483647};case"bigint":return{"@odata.type":"Microsoft.Dynamics.CRM.BigIntAttributeMetadata",AttributeType:"BigInt",AttributeTypeName:{Value:"BigIntType"}};case"double":return{"@odata.type":"Microsoft.Dynamics.CRM.DoubleAttributeMetadata",AttributeType:"Double",AttributeTypeName:{Value:"DoubleType"},Precision:(u=t.precision)!==null&&u!==void 0?u:2,MinValue:(c=t.minValue)!==null&&c!==void 0?c:-1e11,MaxValue:(d=t.maxValue)!==null&&d!==void 0?d:1e11};case"decimal":return{"@odata.type":"Microsoft.Dynamics.CRM.DecimalAttributeMetadata",AttributeType:"Decimal",AttributeTypeName:{Value:"DecimalType"},Precision:(f=t.precision)!==null&&f!==void 0?f:2,MinValue:(m=t.minValue)!==null&&m!==void 0?m:-1e11,MaxValue:(p=t.maxValue)!==null&&p!==void 0?p:1e11};case"money":return{"@odata.type":"Microsoft.Dynamics.CRM.MoneyAttributeMetadata",AttributeType:"Money",AttributeTypeName:{Value:"MoneyType"},Precision:(h=t.precision)!==null&&h!==void 0?h:2,PrecisionSource:2,MinValue:(g=t.minValue)!==null&&g!==void 0?g:0,MaxValue:(b=t.maxValue)!==null&&b!==void 0?b:1e9};case"boolean":return{"@odata.type":"Microsoft.Dynamics.CRM.BooleanAttributeMetadata",AttributeType:"Boolean",AttributeTypeName:{Value:"BooleanType"},DefaultValue:(w=t.defaultValue)!==null&&w!==void 0?w:!1,OptionSet:{"@odata.type":"Microsoft.Dynamics.CRM.BooleanOptionSetMetadata",TrueOption:{Value:1,Label:tt((C=t.trueLabel)!==null&&C!==void 0?C:"Yes",r)},FalseOption:{Value:0,Label:tt((S=t.falseLabel)!==null&&S!==void 0?S:"No",r)}}};case"dateTime":return{"@odata.type":"Microsoft.Dynamics.CRM.DateTimeAttributeMetadata",AttributeType:"DateTime",AttributeTypeName:{Value:"DateTimeType"},Format:(O=t.dateFormat)!==null&&O!==void 0?O:"DateAndTime"};case"choice":return oN(t,r,!1);case"multiChoice":return oN(t,r,!0);case"file":return{"@odata.type":"Microsoft.Dynamics.CRM.FileAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"FileType"},MaxSizeInKB:(L=t.maxSizeKb)!==null&&L!==void 0?L:10240};case"image":return{"@odata.type":"Microsoft.Dynamics.CRM.ImageAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"ImageType"},IsPrimaryImage:(I=t.isPrimaryImage)!==null&&I!==void 0?I:!1,MaxSizeInKB:(D=t.maxSizeKb)!==null&&D!==void 0?D:10240};case"autonumber":if(!(!((P=t.autoNumberFormat)===null||P===void 0)&&P.trim()))throw new he.InvalidArgumentError(`createColumn: an 'autonumber' column needs an 'autoNumberFormat' (e.g. 'CDS-{SEQNUM:5}'), but '${t.schemaName}' has none \u2014 without one Dataverse would create a plain text column.`);return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},FormatName:{Value:"Text"},MaxLength:(x=t.maxLength)!==null&&x!==void 0?x:100,AutoNumberFormat:t.autoNumberFormat};default:throw new he.InvalidArgumentError(`unsupported column type '${String(e)}'`)}}function oN(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,te.normalizeGuid)(e.globalChoiceMetadataId,"globalChoiceMetadataId")})`,i;if(!e.options||e.options.length===0)throw new he.InvalidArgumentError(`choice column '${e.schemaName}' requires at least one option (or a globalChoiceMetadataId)`);return i.OptionSet={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",IsGlobal:!1,OptionSetType:"Picklist",Options:e.options.map(o=>({Value:o.value,Label:tt(o.label,t)}))},i}var Tg=new WeakMap;async function w9(e,t){var r,n;let i=(r=Tg.get(e))===null||r===void 0?void 0:r.get(t);if(i)return i;let o=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')${(0,te.odataQuery)([["$select","EntitySetName"]])}`,s=(n=(0,Se.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.EntitySetName;if(!s)throw new he.InvalidArgumentError(`could not resolve EntitySetName for '${t}'`);(0,te.assertODataName)(s,`server-derived EntitySetName for '${t}'`);let l=Tg.get(e);return l||(l=new Map,Tg.set(e,l)),l.set(t,s),s}ie.resolveEntitySetName=w9;async function C9(e,t){var r,n,i,o,a,s,l,u,c,d,f,m,p,h,g;let b=t.primaryColumnRequired;if(b!==void 0&&!nN.includes(b))throw new he.InvalidArgumentError(`createTable: 'primaryColumnRequired' must be one of ${nN.join(", ")}; got '${String(b)}'.`);let w=b!==void 0&&b!=="None";if(w&&!t.primaryColumnAutoNumberFormat&&!e.supportsPut)throw new he.InvalidArgumentError(`createTable: 'primaryColumnRequired: ${b}' on a plain text primary column needs an HttpClient that implements put(): the platform ignores the level in the create, so the SDK sets it with an update.`);let C=(r=t.languageCode)!==null&&r!==void 0?r:ri.DEFAULT_LCID,S=Ig(t.schemaName),O=(n=t.primaryColumnSchemaName)!==null&&n!==void 0?n:`${S}_Name`,L={"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},SchemaName:O,RequiredLevel:fu(b??"None"),MaxLength:(i=t.primaryColumnMaxLength)!==null&&i!==void 0?i:100,FormatName:{Value:"Text"},DisplayName:tt((o=t.primaryColumnDisplayName)!==null&&o!==void 0?o:"Name",C),IsPrimaryName:!0};t.primaryColumnAutoNumberFormat&&(L.AutoNumberFormat=t.primaryColumnAutoNumberFormat),t.columns&&dN(t.columns,"createTable");let I={"@odata.type":"Microsoft.Dynamics.CRM.EntityMetadata",SchemaName:t.schemaName,DisplayName:tt(t.displayName,C),DisplayCollectionName:tt((a=t.pluralName)!==null&&a!==void 0?a:sN(t.displayName),C),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:[L,...((c=t.columns)!==null&&c!==void 0?c:[]).map(ur=>Og(ur,C))]};t.description&&(I.Description=tt(t.description,C));let D="/EntityDefinitions",P=(0,Se.ensureSuccess)(await e.post(D,I),e.apiUrl(D)),x=pu(P),K=`/EntityDefinitions(${x})`+(0,te.odataQuery)([["$select","LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute"]]),Le=Math.max(1,Math.trunc((d=t.readBackAttempts)!==null&&d!==void 0?d:6)),lr=Math.max(0,(f=t.readBackDelayMs)!==null&&f!==void 0?f:1e3),Ge=w?` Its primary column's requirement level '${b}' was NOT applied or checked: once the table is readable, set it with updateColumn('${t.schemaName.toLowerCase()}', '${O.toLowerCase()}', { required: '${b}' }).`:"",Ut;try{Ut=await lN(e,K,Le,lr)}catch(ur){throw w?(0,he.attachCause)(new he.SdkError("PRIMARY_COLUMN_REQUIRED_NOT_APPLIED",`Table '${t.schemaName}' WAS CREATED (MetadataId ${x}), but reading it back failed (${ur instanceof Error?ur.message:String(ur)}).${Ge} Do NOT re-run the create \u2014 it will collide on the schema name.`),ur):ur}if(!Ut)throw new he.SdkError("TABLE_METADATA_NOT_VISIBLE",`Table '${t.schemaName}' WAS CREATED (MetadataId ${x}) but its metadata was still not readable after ${Le} attempt(s). Do NOT re-run the create \u2014 it will collide on the schema name. Re-read /EntityDefinitions(${x}) once the environment catches up, or raise 'readBackAttempts'.${Ge}`);let de=Ut.body,Ke={logicalName:(m=de.LogicalName)!==null&&m!==void 0?m:t.schemaName.toLowerCase(),metadataId:x,entitySetName:(p=de.EntitySetName)!==null&&p!==void 0?p:"",primaryIdAttribute:(h=de.PrimaryIdAttribute)!==null&&h!==void 0?h:`${t.schemaName.toLowerCase()}id`,primaryNameAttribute:(g=de.PrimaryNameAttribute)!==null&&g!==void 0?g:O.toLowerCase()};return w&&(Ke.primaryColumnRequired=await E9(e,t.schemaName,Ke,b,Le,lr)),Ke}ie.createTable=C9;async function lN(e,t,r,n){for(let i=1;i<=r;i+=1){let o=await e.get(t);if(o.status>=200&&o.status<300)return o;o.status!==404&&(0,Se.ensureSuccess)(o,e.apiUrl(t)),i<r&&n>0&&await new Promise(a=>setTimeout(a,n))}}async function E9(e,t,r,n,i,o){let a=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(r.logicalName)}')/Attributes(LogicalName='${(0,te.odataPathLiteral)(r.primaryNameAttribute)}')`+(0,te.odataQuery)([["$select","RequiredLevel"]]),s=async()=>{var d,f;let m=await lN(e,a,i,o),p=(f=(d=m?.body)===null||d===void 0?void 0:d.RequiredLevel)===null||f===void 0?void 0:f.Value;return typeof p=="string"?p:void 0},l="read",u,c=d=>{let f=`its primary column '${r.primaryNameAttribute}'`,m=l==="read"?`${f} could not be read back`:l==="update"?`${f} read '${u??"(unreadable)"}' and the update to '${n}' failed, so it may or may not carry it`:u===void 0?`${f} was updated to '${n}' but could not be read back`:`${f} is still '${u}' after the update to '${n}'`;return new he.SdkError("PRIMARY_COLUMN_REQUIRED_NOT_APPLIED",`Table '${t}' WAS CREATED (MetadataId ${r.metadataId}), but ${m}${d?` (${d})`:""}. Do NOT re-run the create \u2014 it will collide on the schema name. Check the level, and set it with updateColumn('${r.logicalName}', '${r.primaryNameAttribute}', { required: '${n}' }).`)};try{u=await s(),u!==n&&(l="update",await hN(e,r.logicalName,r.primaryNameAttribute,{required:n}),l="verify",u=await s())}catch(d){throw l==="verify"&&(u=void 0),(0,he.attachCause)(c(d instanceof Error?d.message:String(d)),d)}if(u!==n)throw c(u===void 0?"the answer had no RequiredLevel":void 0);return n}function Og(e,t){var r,n;let i=(r=e.languageCode)!==null&&r!==void 0?r:t,o={...v9(e.type,e,i),SchemaName:e.schemaName,RequiredLevel:fu((n=e.required)!==null&&n!==void 0?n:"None"),DisplayName:tt(e.displayName,i)};return e.description&&(o.Description=tt(e.description,i)),e.sourceType&&e.sourceType!=="Simple"&&(o.SourceType=e.sourceType==="Rollup"?2:1,e.formulaDefinition&&(o.FormulaDefinition=e.formulaDefinition)),uN(o,e),o}function uN(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 A9(e,t,r){var n;let i=Og(r,(n=r.languageCode)!==null&&n!==void 0?n:ri.DEFAULT_LCID),o=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes`,a=(0,Se.ensureSuccess)(await e.post(o,i),e.apiUrl(o)),s={logicalName:r.schemaName.toLowerCase(),metadataId:pu(a)};if(r.visualization&&r.visualization!=="None")try{await mN(e,t,s.logicalName,s.metadataId,r.visualization)}catch(l){let u=new he.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(0,he.attachCause)(u,l),u}return s}ie.createColumn=A9;var As="/controlconfigurations",cN="CustomRenderersConfiguration",Dg={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 dN(e,t){let r=e.find(n=>n.visualization&&n.visualization!=="None");if(r)throw new he.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 fN(e){return JSON.stringify({type:Dg[e]})}function S9(e){if(!e)return"None";let t;try{t=JSON.parse(e)}catch{return"None"}let r=t?.type,n=Object.keys(Dg).find(i=>Dg[i]===r);return n??"None"}async function pN(e,t,r){var n,i;let o=`entitylogicalname eq '${(0,te.odataLiteral)(t)}' and Attribute/logicalname eq '${(0,te.odataLiteral)(r)}'`,a=`${As}${(0,te.odataQuery)([["$select","name,uniquename,metadatajson"],["$expand","Attribute($select=name,logicalname)"],["$filter",o]])}`,l=(i=(n=(0,Se.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[],u=r.toLowerCase();return l.filter(c=>{var d,f;return((f=(d=c.Attribute)===null||d===void 0?void 0:d.logicalname)===null||f===void 0?void 0:f.toLowerCase())===u})}async function N9(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,te.odataPathLiteral)(r)}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,a=(n=(0,Se.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||n===void 0?void 0:n.MetadataId;if(!a)throw new he.InvalidArgumentError(`cannot resolve column '${r}' on '${t}' to set its visualization`);return(0,te.normalizeGuid)(a,"MetadataId")}async function mN(e,t,r,n,i){let o={name:cN,uniquename:`msdyn_${t}_${r}_customrenderers`,metadatajson:fN(i),"[email protected]":`/attributes(${(0,te.normalizeGuid)(n,"MetadataId")})`,entitylogicalname:t};(0,Se.ensureSuccess)(await e.post(As,o),e.apiUrl(As))}async function _9(e,t,r){var n;let i=await pN(e,t,r);return S9((n=i[0])===null||n===void 0?void 0:n.metadatajson)}ie.getColumnVisualization=_9;async function T9(e,t,r,n){let o=(await pN(e,t,r)).map(u=>u.controlconfigurationid).filter(u=>!!u);if(n==="None"){for(let u of o){let c=`${As}(${(0,te.normalizeGuid)(u,"controlconfigurationid")})`;(0,Se.ensureSuccess)(await e.delete(c),e.apiUrl(c))}return}let[a,...s]=o,l=await N9(e,t,r);if(a){let u=`${As}(${(0,te.normalizeGuid)(a,"controlconfigurationid")})`,c={name:cN,metadatajson:fN(n),"[email protected]":`/attributes(${l})`,entitylogicalname:t};(0,Se.ensureSuccess)(await e.patch(u,c),e.apiUrl(u))}else await mN(e,t,r,l,n);for(let u of s){let c=`${As}(${(0,te.normalizeGuid)(u,"controlconfigurationid")})`;(0,Se.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}ie.setColumnVisualization=T9;async function D9(e,t,r){if(r.length===0)return;if(dN(r,"createColumns"),!e.supportsAtomicBatch)throw new he.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,te.odataPathLiteral)(t)}')/Attributes`;await(0,g9.postChangeSet)(e,r.map(i=>{var o;return{method:"POST",path:n,body:Og(i,(o=i.languageCode)!==null&&o!==void 0?o:ri.DEFAULT_LCID)}}),`${r.length} column(s) on '${t}'`)}ie.createColumns=D9;async function I9(e,t,r){var n,i,o,a;let s=(n=r.languageCode)!==null&&n!==void 0?n:ri.DEFAULT_LCID,l=Ig(r.schemaName),u=(i=r.accountRelationshipName)!==null&&i!==void 0?i:`${l}_${t}_account`,c=(o=r.contactRelationshipName)!==null&&o!==void 0?o:`${l}_${t}_contact`,d={Lookup:{"@odata.type":"Microsoft.Dynamics.CRM.ComplexLookupAttributeMetadata",SchemaName:r.schemaName,DisplayName:tt(r.displayName,s),RequiredLevel:fu((a=r.required)!==null&&a!==void 0?a:"None"),Targets:["account","contact"]},OneToManyRelationships:[{"@odata.type":"Microsoft.Dynamics.CRM.ComplexOneToManyRelationshipMetadata",SchemaName:u,ReferencedEntity:"account",ReferencingEntity:t},{"@odata.type":"Microsoft.Dynamics.CRM.ComplexOneToManyRelationshipMetadata",SchemaName:c,ReferencedEntity:"contact",ReferencingEntity:t}]};return(0,Se.ensureSuccess)(await e.post("/CreateCustomerRelationships",d),e.apiUrl("/CreateCustomerRelationships")),{logicalName:r.schemaName.toLowerCase(),metadataId:""}}ie.createCustomerColumn=I9;async function O9(e,t,r){var n,i,o,a,s;let l=(n=r.languageCode)!==null&&n!==void 0?n:ri.DEFAULT_LCID,u={EntityLogicalName:t,AttributeLogicalName:"statuscode",Label:tt(r.label,l),StateCode:(i=r.stateCode)!==null&&i!==void 0?i:0};typeof r.value=="number"&&(u.Value=r.value),r.color&&(u.Color=r.color);let c=(0,Se.ensureSuccess)(await e.post("/InsertStatusValue",u),e.apiUrl("/InsertStatusValue"));return Number((s=(a=(o=c.body)===null||o===void 0?void 0:o.NewOptionValue)!==null&&a!==void 0?a:r.value)!==null&&s!==void 0?s:0)}ie.insertStatusValue=O9;async function P9(e,t){var r,n,i,o,a;let s=(r=t.languageCode)!==null&&r!==void 0?r:ri.DEFAULT_LCID,l,u;if(t.type==="OneToMany"){if(!t.referencedEntity||!t.referencingEntity)throw new he.InvalidArgumentError("OneToMany relationship requires referencedEntity and referencingEntity");let f=(n=t.lookupSchemaName)!==null&&n!==void 0?n:`${Ig(t.schemaName)}_${t.referencedEntity}Id`;u=f.toLowerCase(),l={"@odata.type":"Microsoft.Dynamics.CRM.OneToManyRelationshipMetadata",SchemaName:t.schemaName,ReferencedEntity:t.referencedEntity,ReferencingEntity:t.referencingEntity,Lookup:{"@odata.type":"Microsoft.Dynamics.CRM.LookupAttributeMetadata",AttributeType:"Lookup",AttributeTypeName:{Value:"LookupType"},SchemaName:f,RequiredLevel:fu((i=t.lookupRequired)!==null&&i!==void 0?i:"None"),DisplayName:tt((o=t.lookupDisplayName)!==null&&o!==void 0?o:t.referencedEntity,s)}}}else{if(!t.entity1||!t.entity2)throw new he.InvalidArgumentError("ManyToMany relationship requires entity1 and entity2");l={"@odata.type":"Microsoft.Dynamics.CRM.ManyToManyRelationshipMetadata",SchemaName:t.schemaName,IntersectEntityName:(a=t.intersectEntityName)!==null&&a!==void 0?a:t.schemaName.toLowerCase(),Entity1LogicalName:t.entity1,Entity2LogicalName:t.entity2}}let c="/RelationshipDefinitions",d=(0,Se.ensureSuccess)(await e.post(c,l),e.apiUrl(c));return{schemaName:t.schemaName,metadataId:pu(d),lookupLogicalName:u}}ie.createRelationship=P9;async function R9(e,t){let r=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')`;(0,Se.ensureSuccess)(await e.delete(r),e.apiUrl(r))}ie.deleteTable=R9;async function hN(e,t,r,n){var i,o;let a=(i=n.languageCode)!==null&&i!==void 0?i:ri.DEFAULT_LCID,s=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes`,l=`${s}(LogicalName='${(0,te.odataPathLiteral)(r)}')${(0,te.odataQuery)([["$select","MetadataId,AttributeType"]])}`,c=(0,Se.ensureSuccess)(await e.get(l),e.apiUrl(l)).body,d=y9[(o=c.AttributeType)!==null&&o!==void 0?o:""];if(!c.MetadataId||!d){let g=c.MetadataId?c.AttributeType?`type '${c.AttributeType}' not supported`:"the attribute read returned no AttributeType":"the attribute read returned no MetadataId";throw new he.InvalidArgumentError(`cannot update column '${r}' on '${t}' (${g})`)}let f=(0,te.normalizeGuid)(c.MetadataId,"MetadataId"),m=`${s}(${f})/${d}`,p=(0,Se.ensureSuccess)(await e.get(m),e.apiUrl(m)).body;for(let g of Object.keys(p))g.startsWith("@odata.")&&delete p[g];if(p["@odata.type"]=d,n.displayName!==void 0&&(p.DisplayName=tt(n.displayName,a)),n.description!==void 0&&(p.Description=tt(n.description,a)),n.required!==void 0&&(p.RequiredLevel=fu(n.required)),n.maxLength!==void 0&&(p.MaxLength=n.maxLength),n.autoNumberFormat!==void 0&&(p.AutoNumberFormat=n.autoNumberFormat),n.defaultValue!==void 0&&c.AttributeType!=="Boolean")throw new he.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 he.InvalidArgumentError(`updateColumn: 'integerFormat' applies to Integer columns, but '${r}' on '${t}' is of type '${c.AttributeType}'.`);n.defaultValue!==void 0&&(p.DefaultValue=n.defaultValue),n.integerFormat!==void 0&&(p.Format=n.integerFormat),uN(p,n);let h=`${s}(${f})`;(0,Se.ensureSuccess)(await e.put(h,p,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(h))}ie.updateColumn=hN;async function L9(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes`,o=`${i}(LogicalName='${(0,te.odataPathLiteral)(r)}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,Se.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new he.InvalidArgumentError(`column '${r}' not found on '${t}'`);let l=`${i}(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,Se.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteColumn=L9;async function k9(e,t){var r,n,i;let o=`/RelationshipDefinitions${(0,te.odataQuery)([["$filter",`SchemaName eq '${(0,te.odataLiteral)(t)}'`],["$select","MetadataId"]])}`,s=(i=(n=(r=(0,Se.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||r===void 0?void 0:r.value)===null||n===void 0?void 0:n[0])===null||i===void 0?void 0:i.MetadataId;if(!s)throw new he.InvalidArgumentError(`relationship '${t}' not found`);let l=`/RelationshipDefinitions(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,Se.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteRelationship=k9;async function aN(e,t){var r;let n=`/GlobalOptionSetDefinitions(Name='${(0,te.odataPathLiteral)(t)}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,i=await e.get(n);if(i.status===404)return;let a=(r=(0,Se.ensureSuccess)(i,e.apiUrl(n)).body)===null||r===void 0?void 0:r.MetadataId;return a?(0,te.normalizeGuid)(a,"MetadataId"):void 0}async function $9(e,t){var r;let n=t.name.toLowerCase(),i=await aN(e,n);if(i)return{name:n,metadataId:i};let o=(r=t.languageCode)!==null&&r!==void 0?r:ri.DEFAULT_LCID,a={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",Name:n,DisplayName:tt(t.displayName,o),IsGlobal:!0,OptionSetType:"Picklist",Options:t.options.map(l=>({Value:l.value,Label:tt(l.label,o)}))};t.description&&(a.Description=tt(t.description,o));let s="/GlobalOptionSetDefinitions";try{let l=(0,Se.ensureSuccess)(await e.post(s,a),e.apiUrl(s));return{name:n,metadataId:pu(l)}}catch(l){let u;try{u=await aN(e,n)}catch{u=void 0}if(u)return{name:n,metadataId:u};throw l}}ie.createGlobalOptionSet=$9;async function x9(e,t){let r=`/GlobalOptionSetDefinitions(Name='${(0,te.odataPathLiteral)(t.toLowerCase())}')`;(0,Se.ensureSuccess)(await e.delete(r),e.apiUrl(r))}ie.deleteGlobalOptionSet=x9;async function F9(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:ri.DEFAULT_LCID,o={"@odata.type":"Microsoft.Dynamics.CRM.EntityKeyMetadata",SchemaName:r.schemaName,DisplayName:tt(r.displayName,i),KeyAttributes:r.keyAttributes},a=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Keys`,s=(0,Se.ensureSuccess)(await e.post(a,o),e.apiUrl(a));return{logicalName:r.schemaName.toLowerCase(),metadataId:pu(s)}}ie.createAlternateKey=F9;async function M9(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Keys`,o=`${i}(LogicalName='${(0,te.odataPathLiteral)(r.toLowerCase())}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,Se.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new he.InvalidArgumentError(`alternate key '${r}' not found on '${t}'`);let l=`${i}(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,Se.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteAlternateKey=M9;async function U9(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:ri.DEFAULT_LCID,o=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')`,s=(0,Se.ensureSuccess)(await e.get(o),e.apiUrl(o)).body,l=s.MetadataId;if(!l)throw new he.InvalidArgumentError(`table '${t}' not found`);let u=(0,te.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=tt(r.displayName,i)),r.pluralName!==void 0&&(s.DisplayCollectionName=tt(r.pluralName,i)),r.description!==void 0&&(s.Description=tt(r.description,i)),r.auditEnabled!==void 0&&iN(s,"IsAuditEnabled",r.auditEnabled),r.duplicateDetectionEnabled!==void 0&&iN(s,"IsDuplicateDetectionEnabled",r.duplicateDetectionEnabled),r.changeTrackingEnabled!==void 0&&(s.ChangeTrackingEnabled=r.changeTrackingEnabled),r.quickCreateEnabled!==void 0&&(s.IsQuickCreateEnabled=r.quickCreateEnabled),r.iconVectorName!==void 0&&(s.IconVectorName=r.iconVectorName),r.iconSmallName!==void 0&&(s.IconSmallName=r.iconSmallName),r.iconMediumName!==void 0&&(s.IconMediumName=r.iconMediumName),r.iconLargeName!==void 0&&(s.IconLargeName=r.iconLargeName);let c=`/EntityDefinitions(${u})`;(0,Se.ensureSuccess)(await e.put(c,s,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(c))}ie.updateTable=U9});var wo=v(Pr=>{"use strict";Object.defineProperty(Pr,"__esModule",{value:!0});Pr.rebuildRaw=Pr.assembleChildren=Pr.spliceChildren=Pr.mergeAttrs=Pr.rawFromNode=Pr.emptyBag=void 0;var vo=Q(),gN=1e6,Fd=512;function B9(){return{a:[],c:[]}}Pr.emptyBag=B9;function yN(e,t=0){if(t>Fd)throw new vo.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${Fd}`);return{n:e.getNodeName(),a:e.getAllProperties().map(r=>[r.key,r.value]),c:e.getAllChildren().map(r=>yN(r,t+1))}}Pr.rawFromNode=yN;function q9(e,t,r=[]){let n=new Map;for(let[s,l]of t)n.set(s,l);let i=new Set(r.filter(s=>!n.has(s))),o=new Set,a=[];for(let[s,l]of e)i.has(s)||(n.has(s)?a.push([s,n.get(s)]):a.push([s,l]),o.add(s));for(let[s,l]of t)o.has(s)||(a.push([s,l]),o.add(s));return a}Pr.mergeAttrs=q9;function xd(e,t){let r=new Set;for(let s of e){let l=s.i;if(!Number.isInteger(l)||l<0||l>gN)throw new vo.InvalidArgumentError(`Bag child index must be an integer in [0, ${gN}] (got ${String(l)})`);if(r.has(l))throw new vo.InvalidArgumentError(`Duplicate bag child index ${l}`);r.add(l)}let n=[...e].sort((s,l)=>s.i-l.i),i=[],o=0,a=0;for(let s of n){for(;a<s.i&&o<t.length;)i.push(t[o]),o+=1,a+=1;a<s.i&&(a=s.i),i.push(s.node),a+=1}for(;o<t.length;)i.push(t[o]),o+=1;return i}Pr.spliceChildren=xd;function V9(e,t){if(e.w){let r={n:e.w.n,a:e.w.a.map(n=>[n[0],n[1]]),c:xd(e.w.c,t)};return xd(e.c,[r])}return xd(e.c,t)}Pr.assembleChildren=V9;function bN(e,t,r,n=0){if(n>Fd)throw new vo.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${Fd}`);G9(e,n);let i=t.make(e.n,r);for(let[o,a]of e.a)t.setProp(i,o,a);for(let o of e.c)t.addChild(i,bN(o,t,i,n+1));return i}Pr.rebuildRaw=bN;function G9(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new vo.InvalidArgumentError(`Malformed hybrid node at depth ${t}: expected a JSON object`);let r=e;if(typeof r.n!="string")throw new vo.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 vo.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 vo.InvalidArgumentError(`Malformed hybrid node '${r.n}': each attribute must be a [string, string] pair`)}});var Co=v(Md=>{"use strict";Object.defineProperty(Md,"__esModule",{value:!0});Md.installDomShim=void 0;var vN=ys(),wN=!1,W9={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 z9(){if(wN)return;let e=globalThis;typeof e.DOMParser>"u"&&(e.DOMParser=vN.DOMParser),typeof e.XMLSerializer>"u"&&(e.XMLSerializer=vN.XMLSerializer),typeof e.Node>"u"&&(e.Node=W9),wN=!0}Md.installDomShim=z9});var Eo=v(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.projectElementBag=rt.serializeNode=rt.domEngine=rt.nodeLikeFromDom=rt.parseXmlRoot=rt.EMPTY_FORM_SENTINEL=rt.TEXT_SENTINEL=void 0;var j9=wo(),Ss=Q(),H9=Co();rt.TEXT_SENTINEL="#text";rt.EMPTY_FORM_SENTINEL="#empty";var Bd=new WeakSet;function K9(e,t){(0,H9.installDomShim)();let r=e&&e.trim()!==""?e:t,n=new DOMParser().parseFromString(r,"text/xml"),i=n.documentElement;if(!i)throw new Ss.InvalidArgumentError("XML source has no root element (empty or malformed input)");return J9(r),Q9(n),Z9(i),e5(i),n5(i,r),i}rt.parseXmlRoot=K9;function J9(e){let t=e.search(/\S/);if(t!==-1&&e[t]!=="<")throw EN(3)}var Y9=["http://www.mozilla.org/newlayout/xml/parsererror.xml","http://www.w3.org/1999/xhtml"];function Q9(e){var t;for(let r of Y9){let n=e.getElementsByTagNameNS(r,"parsererror")[0];if(n){let i=((t=n.textContent)!==null&&t!==void 0?t:"").replace(/\s+/g," ").trim().slice(0,200);throw new Ss.InvalidArgumentError(`XML source is not well-formed (${i||"the XML parser reported an error"}), so it cannot be round-tripped`)}}}var X9=new Set([1,3]);function Z9(e){let t=[e];for(;t.length>0;){let n=t.pop().childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];if(!X9.has(o.nodeType))throw new Ss.InvalidArgumentError(`Unsupported XML node type ${o.nodeType} (CDATA / comment / processing-instruction) is outside the hybrid projection's lossless grammar and cannot be round-tripped`);o.nodeType===1&&t.push(o)}}}function e5(e){var t,r;let n=(t=e.ownerDocument)!==null&&t!==void 0?t:e.parentNode;if(!n)return;let i=n.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];if(a!==e&&!(a.nodeType===3&&((r=a.nodeValue)!==null&&r!==void 0?r:"").trim()===""))throw EN(a.nodeType)}}function EN(e){return new Ss.InvalidArgumentError(`Unsupported document-level XML node (type ${e}: declaration / comment / processing-instruction outside the root element) cannot be round-tripped`)}function t5(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 r5(e){let t=[],r=[e];for(;r.length>0;){let n=r.pop();t.push(n);let i=n.childNodes;for(let o=i.length-1;o>=0;o-=1){let a=i[o];a.nodeType===1&&r.push(a)}}return t}function AN(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 n5(e,t){let r=t5(t),n=r5(e),i=Math.min(r.length,n.length);for(let o=0;o<i;o+=1){if(r[o])continue;let a=n[o];AN(a)||Bd.add(a)}}function Pg(e){let t=e.nodeType===3;return{getNodeName:()=>t?rt.TEXT_SENTINEL:e.tagName,getAllProperties:()=>{var r;if(t)return[{key:rt.TEXT_SENTINEL,value:(r=e.nodeValue)!==null&&r!==void 0?r:""}];let n=e.attributes,i=[];for(let o=0;o<n.length;o+=1)i.push({key:n[o].name,value:n[o].value});return Bd.has(e)&&!AN(e)&&i.push({key:rt.EMPTY_FORM_SENTINEL,value:"1"}),i},getAllChildren:()=>{if(t)return[];let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];(o.nodeType===1||o.nodeType===3)&&r.push(Pg(o))}return r}}}rt.nodeLikeFromDom=Pg;function i5(e){return{make:t=>t===rt.TEXT_SENTINEL?e.createTextNode(""):e.createElement(t),setProp:(t,r,n)=>{t.nodeType===3?t.nodeValue=n:r===rt.EMPTY_FORM_SENTINEL?Bd.add(t):t.setAttribute(r,n)},addChild:(t,r)=>{t.appendChild(r)}}}rt.domEngine=i5;function SN(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 Ud(r);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))throw Ud(r);t+=1;continue}if(r>=56320&&r<=57343)throw Ud(r)}}function Ud(e){let t=e.toString(16).toUpperCase().padStart(4,"0");return new Ss.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 o5(e){return SN(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/\r/g,"
").replace(/\n/g,"
").replace(/\t/g,"	")}function a5(e){return SN(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function s5(e){return NN(e,0)}rt.serializeNode=s5;var CN=512;function NN(e,t){var r;if(t>CN)throw new Ss.InvalidArgumentError(`XML nesting exceeds the maximum supported depth of ${CN}`);if(e.nodeType===3)return a5((r=e.nodeValue)!==null&&r!==void 0?r:"");let n=e,i="<"+n.tagName,o=n.attributes;for(let l=0;l<o.length;l+=1)i+=" "+o[l].name+'="'+o5(o[l].value)+'"';let a=[],s=n.childNodes;for(let l=0;l<s.length;l+=1){let u=s[l];(u.nodeType===1||u.nodeType===3)&&a.push(u)}if(a.length===0)return Bd.has(n)?i+"></"+n.tagName+">":i+" />";i+=">";for(let l of a)i+=NN(l,t+1);return i+"</"+n.tagName+">"}function l5(e){let t=Pg(e);return{a:t.getAllProperties().map(r=>[r.key,r.value]),c:t.getAllChildren().map((r,n)=>({i:n,node:(0,j9.rawFromNode)(r)}))}}rt.projectElementBag=l5});var cn=v(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.rejectUnknownKeys=Zt.childObjects=Zt.optionalGuidId=Zt.optionalEnum=Zt.eachObject=Zt.issue=Zt.isJsonObject=void 0;function _N(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}Zt.isJsonObject=_N;function Ns(e,t,r,n){return n?{pointer:e,rule:t,message:r,fatal:n}:{pointer:e,rule:t,message:r}}Zt.issue=Ns;function TN(e,t,r,n){if(!Array.isArray(e))return[];let i=[];return e.forEach((o,a)=>{_N(o)?i.push({node:o,index:a}):n.push(Ns(`${t}/${a}`,`${r}-must-be-object`,`a ${r} must be a JSON object, got ${o===null?"null":typeof o}`))}),i}Zt.eachObject=TN;function u5(e,t,r,n,i,o){let a=e[t];a!==void 0&&(typeof a!="string"||!r.includes(a))&&o.push(Ns(`${n}/${t}`,i,`${t} must be one of ${r.map(s=>`'${s}'`).join(", ")}, got ${JSON.stringify(a)}`))}Zt.optionalEnum=u5;var c5=/^(?:\{[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 o=e[t];typeof o=="string"&&o!==""&&!c5.test(o)&&i.push(Ns(`${r}/${t}`,n,`${t} must be a GUID or empty, got '${o}'`))}Zt.optionalGuidId=d5;function f5(e,t,r,n,i){let o=e[t],a=`${r}/${t}`;return o===void 0?[]:Array.isArray(o)?TN(o,a,n,i):(i.push(Ns(a,`${n}-list-must-be-array`,`${t} must be an array when present, got ${typeof o}`)),[])}Zt.childObjects=f5;function p5(e,t,r,n,i,o={}){var a,s;for(let l of Object.keys(e)){if(t.has(l))continue;let u=(a=o.elsewhere)===null||a===void 0?void 0:a[l],c=(s=o.unsupported)===null||s===void 0?void 0:s[l],d=u?` '${l}' is a ${u} key \u2014 set it on the ${u} instead.`:c?` ${c}`:` Put values the typed layer does not model in '${n}.bag', which round-trips them verbatim.`;i.push(Ns(`${r}/${l}`,`${n}-unknown-key`,`'${l}' is not a ${n} property, and would be SILENTLY DROPPED at serialization.${d}`))}}Zt.rejectUnknownKeys=p5});var zd=v(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.genPageEmbedIssues=B.setUniqueId=B.mintEmbedIdentity=B.authoredUniqueId=B.hasGenPage=B.applyEmbedCellDefaults=B.applyEmbedControlDefaults=B.mayCommitEmbedState=B.commitEmbedState=B.reconcileEmbedDescriptions=B.embedAppendIndex=B.activeEmbedBindings=B.projectGenPageEmbeds=B.isRecognizedEmbed=B.isUnbound=B.effectiveClassId=B.effectiveFormType=B.inputDataFrom=B.classifyBinding=B.isStaticParameter=B.entryParameter=B.pageEntries=B.descriptionFor=B.descriptionsRegion=B.controlUniqueIds=B.controlUniqueId=B.typedCellSites=B.typedCells=B.rawText=B.rawAttr=B.normGuid=B.GENPAGE_FORM_FACTORS=B.GENPAGE_EMBED_ROWSPAN=B.GENPAGE_CONTROL_NAME=B.CUSTOM_CONTROL_CLASS_ID=void 0;var m5=ys(),h5=Xa(),Rg=ct(),dn=cn();B.CUSTOM_CONTROL_CLASS_ID="F9A8A302-114E-466A-B582-6771B2AE0D92";B.GENPAGE_CONTROL_NAME="MscrmControls.UxAgentControl";B.GENPAGE_EMBED_ROWSPAN=6;B.GENPAGE_FORM_FACTORS=["2","0","1"];var g5=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Rr(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase();return t.startsWith("{")&&t.endsWith("}")&&(t=t.slice(1,-1)),g5.test(t)?t:""}B.normGuid=Rr;function Ao(e,t){let r=Ee(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}B.rawAttr=Ao;function hu(e){return Ee(e?.c).filter(t=>typeof t?.n=="string"&&t.n.startsWith("<")).map(t=>t.n.slice(1)).join("")}B.rawText=hu;function Ee(e){return Array.isArray(e)?e:[]}function Mg(e,t){let r=Ee(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}function ON(e){return typeof e=="string"?e.trim().replace(/^\{|\}$/g,"").toUpperCase():""}function PN(e){return Pn(e).map(t=>t.cell)}B.typedCells=PN;function Pn(e){let t=[];return Ee(e?.tabs).forEach((r,n)=>{Ee(Pe(r)?r.columns:void 0).forEach((i,o)=>{Ee(Pe(i)?i.sections:void 0).forEach((a,s)=>{Ee(Pe(a)?a.rows:void 0).forEach((l,u)=>{Ee(Pe(l)?l.cells:void 0).forEach((c,d)=>{Pe(c)&&t.push({cell:c,pointer:`/tabs/${n}/columns/${o}/sections/${s}/rows/${u}/cells/${d}`})})})})})}),t}B.typedCellSites=Pn;function Bi(e){return Pe(e)?Rr(Mg(e.bag,"uniqueid")):""}B.controlUniqueId=Bi;function y5(e){let t=new Set;for(let{cell:r}of Pn(e)){let n=ca(r.control)?Bi(r.control):"";n&&t.add(n)}return t}function b5(e){let t=new Map;for(let{cell:r}of Pn(e)){let n=Pe(r.control)?Bi(r.control):"";n&&!t.has(n)&&t.set(n,r.control)}return t}function v5(e){return e!==void 0&&e.genPage===void 0&&(qg(e)!==B.CUSTOM_CONTROL_CLASS_ID||!Wd(e))}function Lg(e,t){if(Pe(e)){t(e);for(let r of Ee(e.c))Lg(r,t)}}function la(e,t){var r;if(Pe(e)){for(let n of Ee(e.c))Lg(n?.node,t);for(let n of Ee((r=e.w)===null||r===void 0?void 0:r.c))Lg(n?.node,t)}}function Vd(e){let t=new Map,r=i=>{var o;i&&t.set(i,((o=t.get(i))!==null&&o!==void 0?o:0)+1)},n=i=>{i.n==="control"&&r(Rr(Ao(i,"uniqueid")))};return la(e?.bag,n),Ee(e?.tabs).forEach(i=>{Pe(i)&&(la(i.bag,n),Ee(i.columns).forEach(o=>{Pe(o)&&(la(o.bag,n),Ee(o.sections).forEach(a=>{Pe(a)&&(la(a.bag,n),Ee(a.rows).forEach(s=>{Pe(s)&&(la(s.bag,n),Ee(s.cells).forEach(l=>{Pe(l)&&(la(l.bag,n),Pe(l.control)&&(r(Bi(l.control)),la(l.control.bag,n)))}))}))}))}))}),t}B.controlUniqueIds=Vd;function _s(e){return Ee(e?.c).find(t=>{var r;return((r=t?.node)===null||r===void 0?void 0:r.n)==="controlDescriptions"})}B.descriptionsRegion=_s;function ua(e,t){var r;let n=Rr(t);if(n)return Ee((r=_s(e))===null||r===void 0?void 0:r.node.c).find(i=>i?.n==="controlDescription"&&Rr(Ao(i,"forControl"))===n)}B.descriptionFor=ua;function gu(e){return Ee(e.c).filter(RN)}B.pageEntries=gu;function RN(e){return e?.n==="customControl"&&Ao(e,"name")===B.GENPAGE_CONTROL_NAME}function kg(e,t){let r=Ee(e.c).find(n=>n?.n==="parameters");return Ee(r?.c).find(n=>n?.n===t)}B.entryParameter=kg;function $g(e){return Ao(e,"static")==="true"}B.isStaticParameter=$g;function yu(e){let t=gu(e);if(t.length===0)return{kind:"none"};let r,n;for(let i=0;i<t.length;i+=1){let o=kg(t[i],"RefId");if(!o||!$g(o))return{kind:"unsupported"};let a=Rr(hu(o));if(!a)return{kind:"unsupported"};let s=kg(t[i],"PageInput");if(s&&!$g(s))return{kind:"unsupported"};let l=s?hu(s):void 0;if(i===0)r=a,n=l;else if(a!==r||l!==n)return{kind:"unsupported"}}return n===void 0?{kind:"projectable",pageId:r}:{kind:"projectable",pageId:r,pageInputRaw:n}}B.classifyBinding=yu;function Pe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ug(e){if(e===void 0)return;let t;try{t=JSON.parse(e)}catch{return}return Pe(t)&&Pe(t.data)?t.data:void 0}B.inputDataFrom=Ug;function Bg(e){var t;return(t=e.formType)!==null&&t!==void 0?t:"Main"}B.effectiveFormType=Bg;function qg(e){return ON(e.classId!==void 0?e.classId:Mg(e.bag,"classid"))}B.effectiveClassId=qg;function Wd(e){return!e.fieldName}B.isUnbound=Wd;function Vg(e,t){if(Bg(e)!=="Main"||!Wd(t)||qg(t)!==B.CUSTOM_CONTROL_CLASS_ID)return!1;let r=Bi(t),n=r?ua(e.bag,r):void 0;return n!==void 0&&yu(n).kind==="projectable"}B.isRecognizedEmbed=Vg;function w5(e){for(let t of PN(e)){let r=t.control;if(!r||!Vg(e,r))continue;let n=yu(ua(e.bag,Bi(r)));if(n.kind!=="projectable")continue;let i=Ug(n.pageInputRaw);r.genPage=i===void 0?{pageId:n.pageId}:{pageId:n.pageId,inputData:i}}}B.projectGenPageEmbeds=w5;var C5=new Set(["pageId","inputData"]);function mu(e){let t=[];for(let r=0;r<e.childNodes.length;r+=1){let n=e.childNodes[r];n.nodeType===1&&t.push(n)}return t}function E5(e){var t;let r=[],n=c=>d=>r.push(`${c}: ${d}`),i=new m5.DOMParser({errorHandler:{warning:n("warning"),error:n("error"),fatalError:n("fatalError")}}).parseFromString(e,"text/xml"),o=(t=i?.documentElement)!==null&&t!==void 0?t:null;if(!o||r.length>0)throw new Error(`the formxml does not parse cleanly${r.length>0?` (${r[0]})`:""}`);let a=new Set,s=o.getElementsByTagName("control");for(let c=0;c<s.length;c+=1){let d=Rr(s[c].getAttribute("uniqueid"));d&&a.add(d)}let l=mu(o).find(c=>c.nodeName==="controlDescriptions"),u=new Map;for(let c of l?mu(l):[]){let d=Rr(c.getAttribute("forControl"));if(!(c.nodeName!=="controlDescription"||!d||!a.has(d)))for(let f of mu(c)){if(f.nodeName!=="customControl"||f.getAttribute("name")!==B.GENPAGE_CONTROL_NAME)continue;let m=mu(f).find(g=>g.nodeName==="parameters"),p=m?mu(m).find(g=>g.nodeName==="RefId"):void 0,h=p&&p.getAttribute("static")==="true"?Rr(p.textContent):"";h&&u.set(`${d}|${h}`,[d,h])}}return[...u.values()]}B.activeEmbedBindings=E5;function qd(e){return{n:`<${e}`,a:[],c:[]}}function xg(e,t){return{n:e,a:[["type","SingleLine.Text"],["static","true"]],c:[qd(t)]}}function Fg(e,t){let r={};if(t!==void 0)try{let n=JSON.parse(t);Pe(n)&&(r=n)}catch{}return JSON.stringify({...r,data:e})}function A5(e,t,r){return{n:"controlDescription",a:[["forControl",e]],c:B.GENPAGE_FORM_FACTORS.map(n=>({n:"customControl",a:[["name",B.GENPAGE_CONTROL_NAME],["formFactor",n]],c:[{n:"parameters",a:[],c:[xg("RefId",t),...r===void 0?[]:[xg("PageInput",Fg(r))]]}]}))}}function Gd(e,t){if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>Gd(r,t[n]));if(Pe(e)&&Pe(t)){let r=Object.keys(e);return r.length===Object.keys(t).length&&r.every(n=>n in t&&Gd(e[n],t[n]))}return e===t}function S5(e,t,r){let n=Ee(e.c).find(u=>u?.n==="parameters");if(!n||!Array.isArray(n.c))return;let i=n.c.find(u=>u?.n==="RefId");i&&Rr(hu(i))!==t&&(i.c=[qd(t)]);let o=n.c.findIndex(u=>u?.n==="PageInput"),a=o>=0?n.c[o]:void 0,s=a?hu(a):void 0;if(Gd(Ug(s),r))return;if(r!==void 0){a?a.c=[qd(Fg(r,s))]:n.c.push(xg("PageInput",Fg(r)));return}let l=JSON.parse(s);delete l.data,Object.keys(l).length===0?n.c.splice(o,1):a.c=[qd(JSON.stringify(l))]}function Gg(e){let t=Ee(e?.c),r=t.reduce((n,i)=>i.i>n?i.i:n,-1);return Math.max(r,t.length)+1}B.embedAppendIndex=Gg;function N5(e,t){var r;let n=e.bag,i=_s(n);if(i&&t){let o=Vd(t),a=Vd(e),s=y5(t),l=b5(e),u=Ee(i.node.c),c=[];for(let d of u){let f=d?.n==="controlDescription"&&gu(d).length>0?Rr(Ao(d,"forControl")):"";if(!f||!o.has(f))c.push(d);else if(a.has(f))if(s.has(f)&&v5(l.get(f))&&Gd(d,ua(t.bag,f))){let m=Ee(d.c).filter(p=>!RN(p));m.length>0&&c.push({...d,c:m})}else c.push(d)}(c.length!==u.length||c.some((d,f)=>d!==u[f]))&&(i.node.c=c)}for(let{cell:o}of Pn(e)){let a=o.control;if(!ca(a)||!Pe(a.genPage))continue;let s=Rr(a.genPage.pageId),l=a.genPage.inputData,u=Bi(a);if(!u){if(bu(a)!==void 0)continue;u=Wg(a)}let c=ua(n,u);if(c){for(let m of gu(c))S5(m,s,l);continue}i||(i={i:Gg(n),node:{n:"controlDescriptions",a:[],c:[]}},n.c.push(i));let d=((r=Mg(a.bag,"uniqueid"))!==null&&r!==void 0?r:"").trim(),f=d.startsWith("{")?d:`{${u}}`;i.node.c.push(A5(f,s,l))}}B.reconcileEmbedDescriptions=N5;function _5(e,t){let r=_s(e.bag),n=t!==void 0&&(r===void 0||JSON.stringify(r.node)!==JSON.stringify(t)),i=Pn(e).some(({cell:a})=>ca(a.control)&&(a.rowspan===void 0||a.control.classId===void 0||a.control.showLabel===void 0||a.control.label===void 0||a.control.fieldName===void 0));if(!n&&!i)return e;let o=JSON.parse(JSON.stringify(e));if(n){let a=JSON.parse(JSON.stringify(t)),s=_s(o.bag);s?s.node=a:(o.bag=Pe(o.bag)?o.bag:{a:[],c:[]},o.bag.c=Ee(o.bag.c),o.bag.c.push({i:Gg(e.bag),node:a}))}for(let{cell:a}of Pn(o))ca(a.control)&&(LN(a.control),kN(a));return o}B.commitEmbedState=_5;function T5(e){if(Pn(e).some(({cell:r})=>ca(r.control)))return!0;let t=_s(e.bag);return Ee(t?.node.c).some(r=>r?.n==="controlDescription"&&gu(r).length>0)}B.mayCommitEmbedState=T5;function LN(e){e.classId===void 0&&(e.classId=B.CUSTOM_CONTROL_CLASS_ID),e.showLabel===void 0&&(e.showLabel=!1),e.label===void 0&&(e.label=""),e.fieldName===void 0&&(e.fieldName=null)}B.applyEmbedControlDefaults=LN;function kN(e){e.rowspan===void 0&&(e.rowspan=B.GENPAGE_EMBED_ROWSPAN)}B.applyEmbedCellDefaults=kN;function ca(e){return Pe(e)&&e.genPage!==void 0}B.hasGenPage=ca;function DN(e){return ca(e.control)&&(!e.control.id||!e.id||bu(e.control)===void 0)}function bu(e){let t=Ee(Pe(e.bag)?e.bag.a:void 0).find(n=>Array.isArray(n)&&n[0]==="uniqueid");if(!t)return;let r=t[1];return typeof r=="string"&&r.trim()===""?void 0:r}B.authoredUniqueId=bu;function D5(e){if(!Pn(e).some(({cell:r})=>DN(r)))return e;let t=JSON.parse(JSON.stringify(e));for(let{cell:r}of Pn(t)){if(!DN(r))continue;let n=r.control;n.id||(n.id=(0,Rg.newId)()),r.id||(r.id=(0,Rg.newId)()),bu(n)===void 0&&Wg(n)}return t}B.mintEmbedIdentity=D5;function Wg(e){let t=(0,Rg.newId)(),r=`{${t}}`;if(!Pe(e.bag))return e.bag={a:[["uniqueid",r]],c:[]},t;let n=Ee(e.bag.a),i=n.find(o=>Array.isArray(o)&&o[0]==="uniqueid");return i?i[1]=r:n.push(["uniqueid",r]),e.bag.a=n,e.bag.c=Ee(e.bag.c),t}B.setUniqueId=Wg;function IN(e){return e===null?"null":Array.isArray(e)?"an array":typeof e}function I5(e){let t=Ee(e.c).filter(r=>r?.n==="customControl").map(r=>{var n,i;return(i=(n=Ao(r,"name"))!==null&&n!==void 0?n:Ao(r,"id"))!==null&&i!==void 0?i:"unnamed"});return[...new Set(t)].join(", ")||"no custom control"}function O5(e){let t=[],r;for(let{cell:n,pointer:i}of Pn(e)){let o=n.control;if(!Pe(o))continue;let a=`${i}/control`;if(o.genPage===void 0){P5(e,o,a,t);continue}r=r??Vd(e),R5(e,o,a,r,t)}return t}B.genPageEmbedIssues=O5;function P5(e,t,r,n){if(!Vg(e,t))return;let i=yu(ua(e.bag,Bi(t)));n.push((0,dn.issue)(r,"genpage-embed-removed",`this control still embeds generative page ${i.pageId}: removing genPage alone would leave that binding on the form. To remove the embed, remove the cell (or set the cell's control to null); to change the page, edit genPage/pageId. A copy fetched by an older SDK (projection 3) shows no genPage at all \u2014 re-fetch the form.`))}function R5(e,t,r,n,i){var o;let a=`${r}/genPage`,s=t.genPage;if(!Pe(s))i.push((0,dn.issue)(a,"genpage-embed-shape",`genPage must be an object { pageId, inputData? }, got ${IN(s)}.`+(s===null?" To remove an embed, remove the cell (or set the cell's control to null).":"")));else{(typeof s.pageId!="string"||!Rr(s.pageId))&&i.push((0,dn.issue)(`${a}/pageId`,"genpage-embed-shape",`genPage.pageId must be the id (a GUID) of a generative page, got ${s.pageId===void 0?"nothing":JSON.stringify(s.pageId)}`)),s.inputData!==void 0&&!Pe(s.inputData)&&i.push((0,dn.issue)(`${a}/inputData`,"genpage-embed-shape",`genPage.inputData must be a JSON object \u2014 the page reads it as pageInput.data \u2014 got ${IN(s.inputData)}`));for(let m of Object.keys(s))C5.has(m)||i.push((0,dn.issue)(h5.JsonPointer.append(a,m),"genpage-embed-unknown-key",`'${m}' is not a genPage property (pageId, inputData), and would be SILENTLY DROPPED at serialization.`))}Wd(t)||i.push((0,dn.issue)(`${r}/fieldName`,"genpage-embed-bound",`a generative-page embed is an unbound control, but this one is bound to column '${t.fieldName}'. Set fieldName to null, or embed the page in a new cell.`)),t.classId!==void 0&&ON(t.classId)!==B.CUSTOM_CONTROL_CLASS_ID&&i.push((0,dn.issue)(`${r}/classId`,"genpage-embed-class-id",`a generative-page embed is the custom control {${B.CUSTOM_CONTROL_CLASS_ID}}, but classId is ${JSON.stringify(t.classId)}. Omit classId (the SDK defaults it) or set it to that class.`));let l=Bg(e);l!=="Main"&&i.push((0,dn.issue)(a,"genpage-embed-main-form-only",`a generative page can be embedded only in a Main form, as in the maker portal; this is a ${l} form.`));let u=bu(t);u!==void 0&&!Rr(u)&&i.push((0,dn.issue)(`${r}/bag`,"genpage-embed-unique-id",`this embed's uniqueid ${JSON.stringify(u)} is not a GUID, and its page binding is keyed by it. Remove it from the bag (the SDK mints one) or set a GUID.`));let c=Bi(t);if(!c)return;let d=ua(e.bag,c),f=d?yu(d):void 0;d&&f?.kind==="none"?i.push((0,dn.issue)(a,"genpage-embed-other-control",`this control is already bound to another custom control (${I5(d)}). genPage would have to delete that binding to take its place, so embed the page in a new cell instead.`)):f?.kind==="unsupported"&&i.push((0,dn.issue)(a,"genpage-embed-unsupported-binding","this control already embeds a page through a binding genPage cannot represent exactly \u2014 a RefId or PageInput bound to a column, a RefId that is not a page id, or form factors that disagree. Taking it over would silently turn it into a static binding, so embed the page in a new cell instead.")),((o=n.get(c))!==null&&o!==void 0?o:0)>1&&i.push((0,dn.issue)(`${r}/bag`,"genpage-embed-duplicate-unique-id",`this embed's uniqueid {${c}} is also carried by another control on the form, so both would share one binding. Author the copy without its bag and the SDK mints a new identity for it.`))}});var jg=v(So=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});So.findMissingGenPages=So.GENPAGE_LOOKUP_CHUNK=void 0;var L5=Tt(),zg=oe();So.GENPAGE_LOOKUP_CHUNK=50;async function k5(e,t,r){let n=[...new Set(t.map(o=>(0,zg.normalizeGuid)(o,"uxagentprojectid")))],i=new Set;for(let o=0;o<n.length;o+=So.GENPAGE_LOOKUP_CHUNK){let a=n.slice(o,o+So.GENPAGE_LOOKUP_CHUNK),s="/uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,zg.odataQuery)([["$select","uxagentprojectid"],["$filter",a.map(u=>`uxagentprojectid eq ${u}`).join(" or ")]]),l=await(0,L5.collectPages)(e,s,r);for(let u of l){let c=u.uxagentprojectid;typeof c=="string"&&c.trim()!==""&&i.add((0,zg.normalizeGuid)(c,"uxagentprojectid"))}}return n.filter(o=>!i.has(o))}So.findMissingGenPages=k5});var vu=v(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.assertSystemFormKind=Pt.readSystemFormType=Pt.decodeCode=Pt.assertSystemFormRecordKind=Pt.describeSystemFormType=Pt.systemFormKindOf=Pt.SYSTEMFORM_KIND_MISMATCH_CODE=void 0;var xN=Q(),$5=fe(),$N=oe();Pt.SYSTEMFORM_KIND_MISMATCH_CODE="SYSTEMFORM_KIND_MISMATCH";var x5={0:"dashboard",10:"dashboard",2:"form",6:"form",7:"form",11:"form"},F5={0:"dashboard",1:"appointment book",2:"Main form",3:"mini campaign form",4:"preview form",5:"mobile express form",6:"Quick View form",7:"Quick Create form",8:"dialog",9:"task flow form",10:"interactive dashboard",11:"card form",12:"interactive Main form",13:"contextual dashboard",100:"other form",101:"Main form backup",102:"appointment book backup",103:"Power BI dashboard"};function jd(e){return Number.isInteger(e)?x5[e]:void 0}Pt.systemFormKindOf=jd;function FN(e){var t;return Number.isFinite(e)?`a ${(t=F5[e])!==null&&t!==void 0?t:"systemform"} (type ${e})`:"a systemform whose type could not be read"}Pt.describeSystemFormType=FN;function MN(e,t,r,n){let i=FN(r),o=jd(r);switch(n){case"fetch":return`Refusing to fetch systemform '${e}' as a ${t}: it is ${i}. Nothing was read into the workspace. `+(o?`Fetch it as a ${o}.`:Number.isFinite(r)?"The SDK does not model that kind: check the id.":"Check the id.");case"write":return`Refusing to write systemform '${e}' as a ${t}: it is ${i}. Nothing was written. Check the id: a local copy fetched by an SDK that did not check the kind can name a row of another kind \u2014 discard it with deleteArtifact('${t}', '${e}').`;case"delete":return`Refusing to delete systemform '${e}' as a ${t}: it is ${i}. Nothing was changed. Check the id.`;default:return`Refusing to ${n} systemform '${e}': it is ${i}, not a ${t}.`+(n==="set the security roles of"?" Nothing was written.":"")+" Check the id."}}function M5(e,t,r,n){let i=Hg(e?.type);if(jd(i)!==r)throw new xN.SdkError(Pt.SYSTEMFORM_KIND_MISMATCH_CODE,MN(t,r,i,n));return i}Pt.assertSystemFormRecordKind=M5;function Hg(e){if(typeof e=="number")return Number.isInteger(e)?e:NaN;if(typeof e!="string"||!/^\s*-?\d+\s*$/.test(e))return NaN;let t=Number(e);return Number.isInteger(t)?t:NaN}Pt.decodeCode=Hg;async function U5(e,t){return await UN(e,t,!1)}Pt.readSystemFormType=U5;async function B5(e,t){return UN(e,t,!0)}async function UN(e,t,r){var n;let o=`/systemforms(${(0,$N.normalizeGuid)(t,"formId")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,$N.odataQuery)([["$select","type"]]),a=await e.get(o);if(!(r&&a.status===404))return(0,$5.ensureSuccess)(a,e.apiUrl(o)),Hg((n=a.body)===null||n===void 0?void 0:n.type)}async function q5(e,t,r){let n=await B5(e,t);if(!(n===void 0||jd(n)===r))throw new xN.SdkError(Pt.SYSTEMFORM_KIND_MISMATCH_CODE,MN(t,r,n,"delete"))}Pt.assertSystemFormKind=q5});var Jg=v(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.patchSystemForm=Yr.assertSystemFormContentUnchanged=Yr.readSystemFormRowEtag=Yr.unpublishedSystemFormPath=Yr.FORM_TYPE_IMMUTABLE_CODE=void 0;var fn=fe(),V5=oe(),Hd=Q(),No=vu();Yr.FORM_TYPE_IMMUTABLE_CODE="FORM_TYPE_IMMUTABLE";function Kg(e,t="formid"){return`/systemforms(${e})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,V5.odataQuery)([["$select",t]])}Yr.unpublishedSystemFormPath=Kg;function BN(e,t){return(0,fn.readRowEtag)(e,"systemforms","formid",t)}Yr.readSystemFormRowEtag=BN;async function qN(e,t,r,n,i){(0,fn.requireEtag)(i,r,t);let o=(0,fn.ensureSuccess)(await e.get(n),e.apiUrl(n)),a=(0,No.assertSystemFormRecordKind)(o.body,t,r,"write"),s=(0,fn.readEtag)(o);if(s===null)throw new Hd.SdkError(fn.VERSION_CONFLICT_CODE,`Refusing to write ${r} '${t}': its current version could not be read, so the write could not be verified as conditional and would risk silently overwriting a concurrent edit.`);if(s!==i)throw new Hd.SdkError(fn.VERSION_CONFLICT_CODE,`Version conflict writing ${r} '${t}': its formxml changed on the server since it was read (held ${i}, server ${s}). Re-fetch the ${r} and re-apply the change.`);return a}Yr.assertSystemFormContentUnchanged=qN;async function G5(e,t,r,n,i,o){(0,fn.requireEtag)(i,r,t);let a=await BN(e,t);if(a===null)throw new Hd.SdkError(fn.VERSION_CONFLICT_CODE,`Refusing to write ${r} '${t}': its row version could not be read, so the write could not be made conditional and would risk silently overwriting a concurrent edit.`);let s=await qN(e,t,r,Kg(t,"formid,type"),i);if(n.type!==void 0&&(0,No.decodeCode)(n.type)!==s)throw new Hd.SdkError(Yr.FORM_TYPE_IMMUTABLE_CODE,`Refusing to push ${r} '${t}': it would change it from ${(0,No.describeSystemFormType)(s)} to ${(0,No.describeSystemFormType)((0,No.decodeCode)(n.type))}. The platform ignores a type change on an existing ${r}, so the push would report a change that did not happen. Nothing was written. Create a new ${r} of that type instead.`);let l=(0,fn.echoWrite)("formid",{"If-Match":a}),u=`/systemforms(${t})${l.query}`;return(0,fn.ensureSuccess)(await e.patch(u,n,l.options),e.apiUrl(u)),W5(e,t,r,o)}Yr.patchSystemForm=G5;async function W5(e,t,r,n){let i;try{let o=Kg(t,n.select),a=(0,fn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=a.body,l=(0,fn.readEtag)(a),u=typeof s?.formid=="string"&&s.formid.replace(/[{}]/g,"").toLowerCase()===t,c=typeof s?.formxml=="string"&&s.formxml.trim()!=="",d=n.required.filter(p=>s?.[p]===void 0||s?.[p]===null),f=(0,No.decodeCode)(s?.type),m=(0,No.systemFormKindOf)(f)===r;if(l&&u&&c&&d.length===0&&m)return{id:t,etag:l,readBack:s};i=l?!u||!c?`the read did not return this ${r}'s document`:d.length>0?`the read did not return its ${d.join(", ")}`:`the read returned ${(0,No.describeSystemFormType)(f)}, not a ${r}`:"the read returned no version"}catch(o){i=o instanceof Error?o.message:String(o)}return{id:t,etag:null,warnings:[`The ${r} was saved, but its new version could not be read (${i}). The SDK holds no version for it now, so the next push is refused: re-fetch the ${r} before editing it again.`]}}});var e0=v(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.getFormSecurityRoles=qt.setFormSecurityRoles=qt.formApi=qt.readPrimaryCreateRefusal=qt.FORM_GENPAGE_TARGET_UNVERIFIABLE=qt.FORM_GENPAGE_TARGET_NOT_FOUND=void 0;var z5=Tt(),Rt=fe(),pn=oe(),da=Q(),Yg=Eo(),GN=zd(),j5=jg(),Qg=Jg(),wu=vu();qt.FORM_GENPAGE_TARGET_NOT_FOUND="FORM_GENPAGE_TARGET_NOT_FOUND";qt.FORM_GENPAGE_TARGET_UNVERIFIABLE="FORM_GENPAGE_TARGET_UNVERIFIABLE";var WN="formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber",H5={select:WN,required:["name","type","objecttypecode"]},K5="formid,name,type,objecttypecode",J5=2,Y5={Main:J5,QuickView:6,QuickCreate:7,Card:11},zN=new WeakMap;function Q5(e){return typeof e=="object"&&e!==null?zN.get(e):void 0}qt.readPrimaryCreateRefusal=Q5;qt.formApi={async get(e,t){let r=(0,pn.normalizeGuid)(t,"id"),n=`/systemforms(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,pn.odataQuery)([["$select",WN]]),i=(0,Rt.ensureSuccess)(await e.get(n),e.apiUrl(n));return(0,wu.assertSystemFormRecordKind)(i.body,r,"form","fetch"),{raw:i.body,etag:(0,Rt.readEtag)(i)}},async list(e,t){var r;let n=!((r=t?.formTypes)===null||r===void 0)&&r.length?t.formTypes:["Main"],i=[...new Set(n.map(u=>Y5[u]))],a=[i.length===1?`type eq ${i[0]}`:`(${i.map(u=>`type eq ${u}`).join(" or ")})`];t?.entityLogicalName&&a.push(`objecttypecode eq '${(0,pn.odataLiteral)(t.entityLogicalName)}'`);let s=`/systemforms${(0,pn.odataQuery)([["$select",K5],["$filter",a.join(" and ")]])}`;return(await(0,z5.collectPages)(e,s,"listArtifacts('form')")).map(u=>{var c,d;return{type:"form",id:(c=u.formid)!==null&&c!==void 0?c:"",name:(d=u.name)!==null&&d!==void 0?d:"",entityLogicalName:u.objecttypecode,isDirty:!1}})},async create(e,t,r){let n=VN(t);n!==void 0&&await jN(e,Zg(n,"payload"),[]);let i=(0,Rt.echoWrite)("formid"),o=`/systemforms${i.query}`,a=(0,Rt.withClientMintedId)(t,"formid",r),s=Object.freeze({...a}),l=await(0,Rt.resendDeadlockVictim)(()=>e.post(o,{...s},i.options));try{(0,Rt.ensureSuccess)(l,e.apiUrl(o))}catch(u){throw typeof u=="object"&&u!==null&&zN.set(u,{status:l.status,sent:s,desiredId:r}),u}return{id:(0,Rt.resolveCreatedId)(l,"formid","form",r),etag:(0,Rt.readEtag)(l)}},async update(e,t,r,n){let i=(0,pn.normalizeGuid)(t,"id"),o=VN(r);return o!==void 0&&await Z5(e,i,o,n),(0,Qg.patchSystemForm)(e,i,"form",r,n,H5)},readContentThenToken(e,t){return qt.formApi.get(e,t)},async delete(e,t){let r=(0,pn.normalizeGuid)(t,"id");return await(0,wu.assertSystemFormKind)(e,r,"form"),(0,Rt.deleteRecord)(e,"systemforms",r)}};var Xg="DisplayConditions";async function X5(e,t,r){var n,i,o,a;if(r.everyone&&r.roleIds&&r.roleIds.length>0)throw new da.InvalidArgumentError("setFormSecurityRoles: `everyone` and `roleIds` are mutually exclusive \u2014 the platform models <Everyone /> as a replacement for the <Role> list, not an addition to it.");let s=(0,pn.normalizeGuid)(t,"formId"),l=`/systemforms(${s})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,pn.odataQuery)([["$select","formid,formxml,type"]]),u=(0,Rt.ensureSuccess)(await e.get(l),e.apiUrl(l));(0,wu.assertSystemFormRecordKind)(u.body,s,"form","set the security roles of");let c=(0,Rt.readEtag)(u),d=u.body,f=d?.formxml;if(!f)throw new da.InvalidArgumentError(`form '${s}' returned no formxml, so its roles cannot be set`);let m=(0,Yg.parseXmlRoot)(f,"<form/>"),p=m.ownerDocument;if(!p)throw new da.InvalidArgumentError(`form '${s}' produced no owner document`);let h=HN(m,Xg),g=h?.hasAttribute("Order")&&(n=h.getAttribute("Order"))!==null&&n!==void 0?n:void 0,b=h?.getAttribute("FallbackForm")||void 0;h&&m.removeChild(h);let w=!!r.everyone||((o=(i=r.roleIds)===null||i===void 0?void 0:i.length)!==null&&o!==void 0?o:0)>0;if(!w&&(r.order!==void 0||r.fallbackForm!==void 0)){if(!h)throw new da.InvalidArgumentError("setFormSecurityRoles: `order`/`fallbackForm` were supplied without `roleIds` or `everyone`, but this form has no <DisplayConditions> to attach them to. Pass the roles as well.");r.order!==void 0&&h.setAttribute("Order",String(r.order)),r.fallbackForm!==void 0&&h.setAttribute("FallbackForm",String(r.fallbackForm)),m.appendChild(h)}else if(w){let I=p.createElement(Xg),D=r.order!==void 0?String(r.order):g;D!==void 0&&I.setAttribute("Order",D);let P=r.fallbackForm!==void 0?String(r.fallbackForm):b??"false";if(I.setAttribute("FallbackForm",P),r.everyone)I.appendChild(p.createElement("Everyone"));else for(let x of(a=r.roleIds)!==null&&a!==void 0?a:[]){let K=p.createElement("Role");K.setAttribute("Id",`{${(0,pn.normalizeGuid)(x,"roleId")}}`),I.appendChild(K)}m.appendChild(I)}let S=(0,Yg.serializeNode)(m);await(0,Qg.assertSystemFormContentUnchanged)(e,s,"form",l,c);let O=await(0,Qg.readSystemFormRowEtag)(e,s),L=`/systemforms(${s})`;(0,Rt.ensureSuccess)(await e.patch(L,{formxml:S},{headers:{"Content-Type":"application/json","If-Match":(0,Rt.requireEtag)(O,"form",s)}}),e.apiUrl(L))}qt.setFormSecurityRoles=X5;function VN(e){let t=e?.formxml;return typeof t=="string"&&t.includes(GN.GENPAGE_CONTROL_NAME)?t:void 0}function Zg(e,t){try{return(0,GN.activeEmbedBindings)(e)}catch(r){throw new da.SdkError(qt.FORM_GENPAGE_TARGET_UNVERIFIABLE,`Refusing to push the form: the ${t} formxml could not be parsed, so the generative pages it embeds cannot be verified (${r instanceof Error?r.message:String(r)}).`)}}async function jN(e,t,r){let n=new Set(r.map(([a,s])=>`${a}|${s}`)),i=t.filter(([a,s])=>!n.has(`${a}|${s}`)).map(([,a])=>a);if(i.length===0)return;let o=await(0,j5.findMissingGenPages)(e,i,"form generative-page preflight");if(o.length>0)throw new da.SdkError(qt.FORM_GENPAGE_TARGET_NOT_FOUND,`Refusing to push the form: it embeds generative page(s) ${o.map(a=>`'${a}'`).join(", ")} that do not exist in this environment. Push the page before the form that embeds it.`)}async function Z5(e,t,r,n){var i;(0,Rt.requireEtag)(n,"form",t);let o=`/systemforms(${t})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,pn.odataQuery)([["$select","formid,formxml,type"]]),a=(0,Rt.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,wu.assertSystemFormRecordKind)(a.body,t,"form","write");let s=(0,Rt.readEtag)(a);if(s===null||s!==n)throw new da.SdkError(Rt.VERSION_CONFLICT_CODE,`Version conflict writing form '${t}': its formxml changed on the server since it was read (held ${n}, server ${s??"(unreadable)"}). Re-fetch the form and re-apply the change.`);let l=(i=a.body)===null||i===void 0?void 0:i.formxml,u=typeof l=="string"&&l!==""?Zg(l,"server"):[];await jN(e,Zg(r,"payload"),u)}function HN(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 eW(e,t){var r,n;let i=(0,pn.normalizeGuid)(t,"formId"),o=`/systemforms(${i})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,pn.odataQuery)([["$select","formid,formxml,type"]]),a=(0,Rt.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,wu.assertSystemFormRecordKind)(a.body,i,"form","read the security roles of");let s=(r=a.body)===null||r===void 0?void 0:r.formxml;if(!s)return;let l=(0,Yg.parseXmlRoot)(s,"<form/>"),u=HN(l,Xg);if(!u)return;let c=[],d=!1,f=u.childNodes;for(let p=0;p<f.length;p+=1){let h=f[p];if(h.nodeType!==1)continue;let g=h;if(g.tagName==="Everyone")d=!0;else if(g.tagName==="Role"){let b=(n=g.getAttribute("Id"))!==null&&n!==void 0?n:"";b&&c.push(b.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)}:{}}}qt.getFormSecurityRoles=eW});var Jd=v(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.deleteSolution=ye.getDeploymentSettingsTemplate=ye.importSolution=ye.exportSolution=ye.removeSolutionComponent=ye.addSolutionComponent=ye.setSolutionVersion=ye.createSolution=ye.createPublisher=ye.getSolution=ye.fetchSolutionComponents=ye.resolveGenPageComponentType=ye.SolutionComponentType=void 0;var tW=Tt(),Gt=fe(),mr=oe(),rW=ct(),er=Q();ye.SolutionComponentType={SavedQuery:26,Workflow:29,SavedQueryVisualization:59,SystemForm:60,AppModule:80};var nW=[ye.SolutionComponentType.SavedQuery,ye.SolutionComponentType.Workflow,ye.SolutionComponentType.SavedQueryVisualization,ye.SolutionComponentType.SystemForm,ye.SolutionComponentType.AppModule],KN="uxagentproject",JN=new WeakMap;async function t_(e){var t;let r=JN.get(e);if(r!==void 0)return r;let n=`/EntityDefinitions(LogicalName='${KN}')${(0,mr.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status===404)return;(0,Gt.ensureSuccess)(i,e.apiUrl(n));let o=(t=i.body)===null||t===void 0?void 0:t.ObjectTypeCode;if(typeof o!="number"||!Number.isInteger(o)||o<=0)throw new er.SdkError("GENPAGE_COMPONENT_TYPE_UNRESOLVED",`A generative page's solution component type \u2014 the ObjectTypeCode of '${KN}' \u2014 could not be read: its metadata answered without a usable value (${JSON.stringify(o)}). Without it a solution's generative pages cannot be told apart from other components. Retry.`);return JN.set(e,o),o}ye.resolveGenPageComponentType=t_;var YN=1,QN=0;async function iW(e,t){let r=(0,mr.normalizeGuid)(t,"solutionId"),n=await t_(e),o=[YN,...nW,...n===void 0?[]:[n]].map(c=>`componenttype eq ${c}`).join(" or "),a=`/solutioncomponents${(0,mr.odataQuery)([["$select","objectid,componenttype,rootcomponentbehavior"],["$filter",`_solutionid_value eq ${r} and (${o})`]])}`,s=await(0,tW.collectPages)(e,a,"fetchSolutionComponents"),l=[];for(let c of s){if(typeof c.objectid!="string")continue;let d=Number(c.componenttype);if(d===YN){let f=c.rootcomponentbehavior;(f===QN||f===String(QN))&&l.push({objectId:c.objectid,componentType:d,includesAllSubcomponents:!0});continue}l.push({objectId:c.objectid,componentType:d,...n!==void 0&&d===n?{genPage:!0}:{}})}let u=c=>c.objectId.toLowerCase().replace(/^\{|\}$/g,"");return l.sort((c,d)=>c.componentType-d.componentType||(u(c)<u(d)?-1:u(c)>u(d)?1:0))}ye.fetchSolutionComponents=iW;function oW(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 aW(e,t){var r,n,i,o,a,s,l,u,c,d;let f=String(t??"").trim();if(!f)throw new er.InvalidArgumentError("getSolution: a solution unique name or id is required.");let m=oW(f)?`solutionid eq ${(0,mr.normalizeGuid)(f,"solutionId")}`:`uniquename eq '${(0,mr.odataLiteral)(f)}'`,p=`/solutions${(0,mr.odataQuery)([["$select","solutionid,uniquename,friendlyname,version,ismanaged"],["$expand","publisherid($select=publisherid,uniquename,customizationprefix,customizationoptionvalueprefix)"],["$filter",m]])}`,b=((n=(r=(0,Gt.ensureSuccess)(await e.get(p),e.apiUrl(p)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0];if(!b?.solutionid)throw new er.InvalidArgumentError(`No solution found for '${t}'.`);let w=b.publisherid;if(!w?.publisherid)throw new er.InvalidArgumentError(`Solution '${(i=b.uniquename)!==null&&i!==void 0?i:t}' returned no owning publisher, so its customization prefix cannot be determined; refusing to report an empty prefix that could be mistaken for "no prefix".`);if(!("customizationprefix"in w))throw new er.InvalidArgumentError(`Solution '${(o=b.uniquename)!==null&&o!==void 0?o:t}' returned a publisher without a customizationprefix property (partial expansion), so its prefix cannot be determined.`);return{solutionId:(0,mr.normalizeGuid)(b.solutionid,"solutionId"),uniqueName:(a=b.uniquename)!==null&&a!==void 0?a:"",friendlyName:(s=b.friendlyname)!==null&&s!==void 0?s:"",version:(l=b.version)!==null&&l!==void 0?l:"",isManaged:!!b.ismanaged,publisherId:(0,mr.normalizeGuid)(w.publisherid,"publisherId"),publisherUniqueName:(u=w.uniquename)!==null&&u!==void 0?u:"",publisherPrefix:(c=w.customizationprefix)!==null&&c!==void 0?c:"",publisherOptionValuePrefix:(d=w.customizationoptionvalueprefix)!==null&&d!==void 0?d:0}}ye.getSolution=aW;async function sW(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,Gt.ensureSuccess)(await(0,Gt.resendDeadlockVictim)(()=>e.post("/publishers",{...n})),e.apiUrl("/publishers")),o=(0,Gt.readCreatedId)(i,"publisherid");if(!o)throw new er.InvalidArgumentError(`Dataverse did not return an id for publisher '${t.uniqueName}'`);return{id:o,uniqueName:t.uniqueName}}ye.createPublisher=sW;async function lW(e,t){var r;let n=(0,mr.normalizeGuid)(t.publisherId,"publisherId"),i={uniquename:t.uniqueName,friendlyname:t.friendlyName,version:(r=t.version)!==null&&r!==void 0?r:"1.0.0.0","[email protected]":`/publishers(${n})`};t.description&&(i.description=t.description);let o=(0,Gt.ensureSuccess)(await e.post("/solutions",i),e.apiUrl("/solutions")),a=(0,Gt.readCreatedId)(o,"solutionid");if(!a)throw new er.InvalidArgumentError(`Dataverse did not return an id for solution '${t.uniqueName}'`);return{id:a,uniqueName:t.uniqueName}}ye.createSolution=lW;async function uW(e,t,r){let i=`/solutions(${(0,mr.normalizeGuid)(t,"solutionId")})`;(0,Gt.ensureSuccess)(await e.patch(i,{version:r}),e.apiUrl(i))}ye.setSolutionVersion=uW;async function cW(e,t){var r;let i={ComponentId:(0,mr.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,Gt.ensureSuccess)(await e.post("/AddSolutionComponent",i),e.apiUrl("/AddSolutionComponent"))}ye.addSolutionComponent=cW;async function dW(e,t,r,n){let o={SolutionComponent:{"@odata.type":"Microsoft.Dynamics.CRM.solutioncomponent",solutioncomponentid:(0,mr.normalizeGuid)(t,"componentId")},ComponentType:r,SolutionUniqueName:n};(0,Gt.ensureSuccess)(await e.post("/RemoveSolutionComponent",o),e.apiUrl("/RemoveSolutionComponent"))}ye.removeSolutionComponent=dW;async function fW(e,t){var r,n;let i={SolutionName:t.solutionName,Managed:(r=t.managed)!==null&&r!==void 0?r:!1},a=(n=(0,Gt.ensureSuccess)(await e.post("/ExportSolution",i),e.apiUrl("/ExportSolution")).body)===null||n===void 0?void 0:n.ExportSolutionFile;if(!a)throw new er.InvalidArgumentError(`ExportSolution returned no file for '${t.solutionName}'`);return{base64:a}}ye.exportSolution=fW;async function pW(e,t){let r=[["overwriteUnmanagedCustomizations","overwrote unmanaged customizations made over the solution's components"],["publishWorkflows","activated the solution's workflows"]];for(let[a,s]of r)if(typeof t?.[a]!="boolean")throw new er.InvalidArgumentError(`importSolution: '${a}' is required and must be true or false (it was ${String(t?.[a])}). It used to default to true, which ${s} unless the caller said otherwise. Nothing was imported.`);let n=t.deploymentSettings===void 0?void 0:SW(t.deploymentSettings),i={OverwriteUnmanagedCustomizations:t.overwriteUnmanagedCustomizations,PublishWorkflows:t.publishWorkflows,CustomizationFile:t.base64,ImportJobId:t.importJobId?(0,mr.normalizeGuid)(t.importJobId,"importJobId"):(0,rW.newId)()};if(!n)return(0,Gt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{};if(n.variables.length===0&&n.references.length===0)return(0,Gt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:{environmentVariables:[],connectionReferences:[]}};let o=[];try{let a=await r_(e,t.base64,Cu,o),{parameters:s,applied:l}=NW(a,n);return i.ComponentParameters=s,(0,Gt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:l,...o.length>0?{warnings:o}:{}}}catch(a){throw(0,er.withCleanupWarnings)(a,o)}}ye.importSolution=pW;var Cu="importSolution",XN="getDeploymentSettingsTemplate";async function mW(e,t){var r;let n=t?.base64;if(typeof n!="string"||n.length===0)throw new er.InvalidArgumentError(`${XN}: 'base64' must be the solution package \u2014 a non-empty base64 string, e.g. exportSolution's result (it was ${(r=JSON.stringify(n))!==null&&r!==void 0?r:String(n)})`);let i=[];try{let o=await r_(e,n,XN,i),a=Kd(o.variables,l=>l.SchemaName).map(({SchemaName:l,DefaultValue:u,TypeId:c,IsRequired:d})=>({SchemaName:l,Value:"",...u!==void 0?{DefaultValue:u}:{},...c!==void 0?{TypeId:c}:{},...d!==void 0?{IsRequired:d}:{}})),s=Kd(o.references,l=>l.LogicalName).map(({LogicalName:l,ConnectorId:u})=>({LogicalName:l,ConnectionId:"",...u!==void 0?{ConnectorId:u}:{}}));return{settings:{EnvironmentVariables:a,ConnectionReferences:s},...i.length>0?{warnings:i}:{}}}catch(o){throw(0,er.withCleanupWarnings)(o,i)}}ye.getDeploymentSettingsTemplate=mW;function Kd(e,t){return[...e].sort((r,n)=>{let i=t(r).toLowerCase(),o=t(n).toLowerCase();return i<o?-1:i>o?1:0})}function fa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Vt(e,t=120){var r;let n=(r=JSON.stringify(e))!==null&&r!==void 0?r:String(e);return n.length>t?`${n.slice(0,t)}\u2026`:n}async function r_(e,t,r,n){var i;let a=(i=(0,Gt.ensureSuccess)(await e.post("/StageSolution",{CustomizationFile:t}),e.apiUrl("/StageSolution")).body)===null||i===void 0?void 0:i.StageSolutionResults;try{return gW(a,r)}finally{await hW(e,fa(a)?a.StageSolutionUploadId:void 0,n)}}async function hW(e,t,r){let n;try{n=(0,mr.normalizeGuid)(t,"StageSolutionUploadId")}catch{r.push(`StageSolution's reply named no usable staging upload id (${Vt(t,60)}), so the staged copy of the package it may have stored (a stagesolutionupload row of yours) could not be deleted.`);return}let i=`/stagesolutionuploads(${n})`;try{let o=await e.delete(i);o.status!==404&&(0,Gt.ensureSuccess)(o,e.apiUrl(i))}catch(o){r.push(`The staged copy of the package (stagesolutionupload ${n}) could not be deleted: ${o instanceof Error?o.message:String(o)}. It stays until it is deleted (DELETE ${i}).`)}}function pr(e,t){return new er.SdkError("SOLUTION_STAGING_UNREADABLE",`${e}: StageSolution's reply could not be read \u2014 ${t}.${e===Cu?" Nothing was imported.":""}`)}function ZN(e){return!Array.isArray(e)||e.length===0?"none":`${e.slice(0,5).map(r=>fa(r)&&typeof r.Message=="string"?r.Message:Vt(r,200)).join("; ")}${e.length>5?` (+${e.length-5} more)`:""}`}function gW(e,t){if(!fa(e))throw pr(t,`it holds no StageSolutionResults (${Vt(e,60)})`);let r=e.StageSolutionStatus;if(r==="Failed"||r===0)throw new er.SdkError("SOLUTION_STAGING_FAILED",`${t}: the package did not pass StageSolution in this environment (status ${Vt(r)}). Missing dependencies: ${ZN(e.MissingDependencies)}. Validation: ${ZN(e.SolutionValidationResults)}.${t===Cu?" Its components cannot be checked against deploymentSettings. Nothing was imported.":" Stage it in the environment it was exported from."}`);if(r!=="Passed"&&r!==1)throw pr(t,`StageSolutionStatus is ${Vt(r)}, neither "Passed" nor "Failed"`);let n=e.SolutionComponentsDetails;if(!Array.isArray(n))throw pr(t,`SolutionComponentsDetails is not a list (${Vt(n,60)})`);let i=[],o=[],a=new Set,s=new Set;return n.forEach((l,u)=>{let c=`SolutionComponentsDetails[${u}]`;if(!fa(l))throw pr(t,`${c} is not an object`);if(typeof l.ComponentTypeName!="string")throw pr(t,`${c}.ComponentTypeName is not a string`);let d=l.ComponentTypeName.toLowerCase();if(d!=="environmentvariabledefinition"&&d!=="connectionreference")return;let f=yW(l.Attributes,`${c}.Attributes`,t),m=(p,h)=>{let g=f.get(p);if(g==null){if(h)throw pr(t,`${c}.${p} is missing`);return}if(typeof g!="string"||h&&g.length===0)throw pr(t,`${c}.${p} is not ${h?"a non-empty string":"a string"}`);return g};if(d==="environmentvariabledefinition"){let p=m("schemaname",!0);if(a.has(p.toLowerCase()))throw pr(t,`${c}.schemaname '${p}' is listed twice`);a.add(p.toLowerCase());let h=m("defaultvalue",!1),g=bW(f.get("type"),`${c}.type`,t),b=vW(f.get("isrequired"),`${c}.isrequired`,t);i.push({SchemaName:p,...h!==void 0?{DefaultValue:h}:{},...g!==void 0?{TypeId:g}:{},...b!==void 0?{IsRequired:b}:{}})}else{let p=m("connectionreferencelogicalname",!0);if(s.has(p.toLowerCase()))throw pr(t,`${c}.connectionreferencelogicalname '${p}' is listed twice`);s.add(p.toLowerCase());let h=m("connectorid",!1);o.push({LogicalName:p,...h!==void 0?{ConnectorId:h}:{}})}}),{variables:i,references:o}}function yW(e,t,r){if(!fa(e)||!Array.isArray(e.Keys)||!Array.isArray(e.Values))throw pr(r,`${t} is not { Keys: [...], Values: [...] }`);let{Keys:n,Values:i}=e;if(n.length!==i.length)throw pr(r,`${t} has ${n.length} keys but ${i.length} values`);let o=new Map;return n.forEach((a,s)=>{if(typeof a!="string")throw pr(r,`${t}.Keys[${s}] is not a string`);if(o.has(a))throw pr(r,`${t}.Keys lists '${a}' twice`);o.set(a,i[s])}),o}function bW(e,t,r){if(e!=null){if(typeof e=="number"&&Number.isSafeInteger(e))return e;if(typeof e=="string"&&/^\d{1,15}$/.test(e))return Number(e);throw pr(r,`${t} is not a whole number (${Vt(e,40)})`)}}function vW(e,t,r){if(e!=null){if(typeof e=="boolean")return e;if(typeof e=="string"&&/^(true|false)$/i.test(e))return e.toLowerCase()==="true";throw pr(r,`${t} is not true or false (${Vt(e,40)})`)}}var wW=new Set(["EnvironmentVariables","ConnectionReferences","Workflows","CanvasApps","CopilotAgents","$schema"]),CW=["Workflows","CanvasApps","CopilotAgents"],EW=new Set(["SchemaName","Value","DefaultValue","TypeId","IsRequired","Name"]),AW=new Set(["LogicalName","ConnectionId","ConnectorId"]);function fr(e,t){return new er.InvalidArgumentError(`${Cu}: deploymentSettings is not a deployment-settings file this SDK applies \u2014 ${e} ${t}. Nothing was imported.`)}function SW(e){let t="deploymentSettings";if(!fa(e))throw fr(t,`must be an object \u2014 the settings file, parsed (it was ${Vt(e,40)})`);for(let l of Object.keys(e))if(!wW.has(l))throw fr(`${t}.${l}`,"is not part of the format (EnvironmentVariables, ConnectionReferences; Workflows, CanvasApps and CopilotAgents only empty; $schema)");for(let l of CW){let u=e[l];if(u!==void 0&&!(Array.isArray(u)&&u.length===0))throw fr(`${t}.${l}`,"is a pac feature this SDK does not apply: only an empty list is accepted")}if(e.$schema!==void 0&&typeof e.$schema!="string")throw fr(`${t}.$schema`,"must be a string");let r=l=>{let u=e[l];if(u===void 0)return[];if(!Array.isArray(u))throw fr(`${t}.${l}`,`must be a list (it was ${Vt(u,40)})`);return u.map((c,d)=>{if(!fa(c))throw fr(`${t}.${l}[${d}]`,`must be an object (it was ${Vt(c,40)})`);return c})},n=(l,u,c)=>{let d=l[u];if(typeof d!="string"||d.length===0)throw fr(c,`must be a non-empty string (it was ${Vt(d,40)})`);if(d.trim()!==d)throw fr(c,`must not begin or end with whitespace (it was ${Vt(d,60)})`);return d},i=(l,u,c)=>{if(l.has(u.toLowerCase()))throw fr(c,`names '${u}' a second time (names are case-insensitive)`);l.add(u.toLowerCase())},o={variables:[],references:[]},a=new Set;r("EnvironmentVariables").forEach((l,u)=>{let c=`${t}.EnvironmentVariables[${u}]`;for(let f of Object.keys(l))if(!EW.has(f))throw fr(`${c}.${f}`,"is not part of a variable (SchemaName, Value; DefaultValue, TypeId, IsRequired, Name)");let d=n(l,"SchemaName",`${c}.SchemaName`);if(i(a,d,`${c}.SchemaName`),typeof l.Value!="string")throw fr(`${c}.Value`,`must be a string \u2014 empty to override nothing (it was ${Vt(l.Value,40)})`);l.Value.length>0&&o.variables.push({name:d,value:l.Value})});let s=new Set;return r("ConnectionReferences").forEach((l,u)=>{let c=`${t}.ConnectionReferences[${u}]`;for(let m of Object.keys(l))if(!AW.has(m))throw fr(`${c}.${m}`,m==="ConnectionInstance"?"is pac's connection-instance feature, which this SDK does not apply":"is not part of a connection reference (LogicalName, ConnectionId, ConnectorId)");let d=n(l,"LogicalName",`${c}.LogicalName`);i(s,d,`${c}.LogicalName`);let f=l.ConnectionId;if(typeof f!="string")throw fr(`${c}.ConnectionId`,`must be a string \u2014 empty to bind nothing (it was ${Vt(f,40)})`);if(f.trim()!==f)throw fr(`${c}.ConnectionId`,`must not begin or end with whitespace (it was ${Vt(f,60)})`);if(l.ConnectorId!==void 0&&typeof l.ConnectorId!="string")throw fr(`${c}.ConnectorId`,`must be a string (it was ${Vt(l.ConnectorId,40)})`);f.length>0&&o.references.push({name:d,connectionId:f,...l.ConnectorId?{connectorId:l.ConnectorId}:{}})}),o}function e_(e,t=20){return e.length===0?"none":`${e.slice(0,t).join(", ")}${e.length>t?` (+${e.length-t} more)`:""}`}function NW(e,t){var r;let n=new Map(e.variables.map(l=>[l.SchemaName.toLowerCase(),l])),i=new Map(e.references.map(l=>[l.LogicalName.toLowerCase(),l])),o=[],a=[],s={environmentVariables:[],connectionReferences:[]};for(let l of t.variables){let u=n.get(l.name.toLowerCase());if(!u){o.push(`EnvironmentVariables: '${l.name}' is not a variable of the package`);continue}a.push({"@odata.type":"Microsoft.Dynamics.CRM.environmentvariablevalue",schemaname:u.SchemaName,value:l.value}),s.environmentVariables.push(u.SchemaName)}for(let l of t.references){let u=i.get(l.name.toLowerCase());if(!u){o.push(`ConnectionReferences: '${l.name}' is not a connection reference of the package`);continue}if(l.connectorId!==void 0&&l.connectorId.toLowerCase()!==((r=u.ConnectorId)===null||r===void 0?void 0:r.toLowerCase())){o.push(`ConnectionReferences: '${l.name}' names connector '${l.connectorId}', but the package's reference is for ${u.ConnectorId?`'${u.ConnectorId}'`:"no connector"}`);continue}a.push({"@odata.type":"Microsoft.Dynamics.CRM.connectionreference",connectionreferencelogicalname:u.LogicalName,connectionid:l.connectionId,...u.ConnectorId!==void 0?{connectorid:u.ConnectorId}:{}}),s.connectionReferences.push(u.LogicalName)}if(o.length>0){let l=o.join("; "),u=e_(Kd(e.variables,d=>d.SchemaName).map(d=>d.SchemaName)),c=e_(Kd(e.references,d=>d.LogicalName).map(d=>d.LogicalName));throw new er.InvalidArgumentError(`${Cu}: deploymentSettings does not match the package \u2014 ${l}. The package's variables: ${u}; its connection references: ${c}. Nothing was imported.`)}return{parameters:a,applied:s}}async function _W(e,t){let n=`/solutions(${(0,mr.normalizeGuid)(t,"solutionId")})`;(0,Gt.ensureSuccess)(await e.delete(n),e.apiUrl(n))}ye.deleteSolution=_W});var l_=v(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.recoverFormCreate=yt.solutionMembershipProblem=yt.formWriteMismatches=yt.validateExistingForm=yt.formExistsAtId=yt.isFormRecordAt=yt.MAIN_FORM_TYPE=void 0;var Ts=oe(),n_=Tt(),i_=Jd();yt.MAIN_FORM_TYPE=2;function Yd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Qd(e){return e instanceof Error?e.message:String(e)}function t0(e,t){if(typeof e!="string"||typeof t!="string")return!1;try{return(0,Ts.normalizeGuid)(e,"a GUID")===(0,Ts.normalizeGuid)(t,"a GUID")}catch{return!1}}function r0(e,t){return Yd(e)&&t0(e.formid,t)}yt.isFormRecordAt=r0;async function TW(e,t){try{return r0((await e()).raw,t)}catch{return!1}}yt.formExistsAtId=TW;function o_(e,t){let r=e.raw;if(!Yd(r))return{problem:"it is not a record"};if(!r0(r,t))return{problem:"its formid is not the id this create sent"};if(r.type!==yt.MAIN_FORM_TYPE)return{problem:`its type is not ${yt.MAIN_FORM_TYPE} (a Main form)`};if(typeof r.objecttypecode!="string")return{problem:"its objecttypecode is not a string"};if(typeof r.name!="string")return{problem:"its name is not a string"};if(typeof r.formxml!="string"||r.formxml.length===0)return{problem:"its formxml is not a non-empty string"};if(typeof r.formpresentation!="number")return{problem:"its formpresentation is not a number"};if(typeof r.formactivationstate!="number")return{problem:"its formactivationstate is not a number"};for(let o of["uniquename","description"]){let a=r[o];if(a!=null&&typeof a!="string")return{problem:`its ${o} is neither a string nor null`}}let n=r["@odata.etag"];if(n!==void 0&&typeof n!="string")return{problem:"its @odata.etag is not a string"};if(n!==void 0&&e.etag!==null&&e.etag!==n)return{problem:"the ETag header and the @odata.etag of the body disagree"};let i=e.etag;return i===null?{problem:"the read carries no concurrency token"}:i.trim()===""||i.trim()==="*"?{problem:"its concurrency token is blank or a wildcard"}:{record:r,etag:i}}yt.validateExistingForm=o_;function a_(e,t){let r=[];for(let i of["formxml","name","objecttypecode","type"])e[i]!==t[i]&&r.push(i);let n=t.description;if(n!==void 0){let i=e.description;typeof n=="string"&&(n===""?i==null||i==="":i===n)||r.push("description")}return r}yt.formWriteMismatches=a_;async function s_(e,t){let r=e.solutionName;if(r)try{let n=await(0,n_.collectPages)(e,`/solutions${(0,Ts.odataQuery)([["$select","solutionid,uniquename"],["$filter",`uniquename eq '${(0,Ts.odataLiteral)(r)}'`]])}`,"createRecovery solution lookup");if(n.length!==1)return`the configured solution '${r}' resolves to ${n.length} solutions, not exactly one`;let[i]=n,o;return Yd(i)&&typeof i.uniquename=="string"&&typeof i.solutionid=="string"&&i.uniquename.toLowerCase()===r.toLowerCase()&&(o=(0,Ts.normalizeGuid)(i.solutionid,"solutionid")),o===void 0?`the configured solution '${r}' did not resolve to a valid solution of that name`:(await(0,n_.collectPages)(e,`/solutioncomponents${(0,Ts.odataQuery)([["$select","objectid,componenttype,_solutionid_value"],["$filter",`_solutionid_value eq ${o} and componenttype eq ${i_.SolutionComponentType.SystemForm} and objectid eq ${t}`]])}`,"createRecovery solution membership")).some(l=>Yd(l)&&l.componenttype===i_.SolutionComponentType.SystemForm&&t0(l.objectid,t)&&t0(l._solutionid_value,o))?void 0:`the form is not a component of the configured solution '${r}'`}catch(n){return`membership in the configured solution '${r}' could not be established (${Qd(n)})`}}yt.solutionMembershipProblem=s_;async function DW(e){try{return await IW(e)}catch(t){return{refused:`the recovery could not be completed (${Qd(t)})`}}}yt.recoverFormCreate=DW;async function IW(e){let{client:t,read:r,sent:n,authoredFormType:i,project:o}=e;if(i!=="Main"||n.type!==yt.MAIN_FORM_TYPE)return{refused:`only a Main form is adopted (this one is authored as ${String(i)})`};let a=n.formid;if(typeof a!="string")return{refused:"the create sent no formid to look for"};let s;try{s=await r()}catch(f){return{refused:`the existing row could not be read (${Qd(f)})`}}let l=o_(s,a);if("problem"in l)return{refused:`the existing row cannot be trusted: ${l.problem}`};let u=a_(l.record,n);if(u.length>0)return{refused:`the existing row is not what this create wrote (it differs in ${u.join(", ")})`};let c;try{c=o(l.record)}catch(f){return{refused:`the existing row could not be read into a form (${Qd(f)})`}}let d=await s_(t,a);return d!==void 0?{refused:d}:{adopted:{artifact:c,etag:l.etag}}}});var Zd=v(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.disassociateRecords=Ye.associateRecords=Ye.createRecordsBulk=Ye.upsertRecord=Ye.queryAllRecords=Ye.queryRecords=Ye.getRecord=Ye.deleteRecord=Ye.updateRecord=Ye.createRecord=void 0;var n0=Tt(),Rn=fe(),tr=oe(),Ds=Q(),ni=$d();function Xd(e){let t=e,r=!1,n={};for(let i of Object.keys(t)){let o=t[i];Array.isArray(o)&&o.every(a=>typeof a=="number")?(n[i]=o.join(","),r=!0):n[i]=o}return r?n:e}async function OW(e,t,r){let i=`/${await(0,ni.resolveEntitySetName)(e,t)}`,o=(0,Rn.ensureSuccess)(await e.post(i,Xd(r)),e.apiUrl(i)),a=(0,Rn.readCreatedId)(o,`${t}id`);if(!a)throw new Ds.InvalidArgumentError(`Dataverse did not return an id for the created '${t}' row`);return{id:a,entityType:t}}Ye.createRecord=OW;async function PW(e,t,r,n){let i=(0,tr.normalizeGuid)(r,"id"),a=`/${await(0,ni.resolveEntitySetName)(e,t)}(${i})`;(0,Rn.ensureSuccess)(await e.patch(a,Xd(n)),e.apiUrl(a))}Ye.updateRecord=PW;async function RW(e,t,r){let n=(0,tr.normalizeGuid)(r,"id"),o=`/${await(0,ni.resolveEntitySetName)(e,t)}(${n})`;(0,Rn.ensureSuccess)(await e.delete(o),e.apiUrl(o))}Ye.deleteRecord=RW;async function LW(e,t,r,n){let i=(0,tr.normalizeGuid)(r,"id"),o=await(0,ni.resolveEntitySetName)(e,t),a=(0,tr.odataQuery)([["$select",n&&n.length>0?n.join(","):void 0]]),s=`/${o}(${i})${a}`,l=(0,Rn.ensureSuccess)(await e.get(s),e.apiUrl(s)),u=l.body;if(u===null||typeof u!="object"||Array.isArray(u))throw new Ds.ConnectionError(e.apiUrl(s),l.status,`getRecord: read returned a malformed row \u2014 expected an OData entity object but got ${Array.isArray(u)?"an array":(0,n0.describeMalformedValue)(u)}; refusing to read it as a row.`);return u}Ye.getRecord=LW;function kW(e){return e?.fetchXml?(0,tr.odataQuery)([["fetchXml",e.fetchXml]]):(0,tr.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 u_(e,t,r){var n;if(r?.paginate){if(r.top!==void 0)throw new Ds.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 Ds.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,ni.resolveEntitySetName)(e,t)}${kW(r)}`;if(r?.paginate)return(0,n0.collectPages)(e,o,"queryRecords");let a=(0,Rn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(n=a.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(s))throw new Ds.ConnectionError(e.apiUrl(o),a.status,`queryRecords: read returned a malformed page \u2014 expected an OData 'value' array but got ${(0,n0.describeMalformedValue)(s)}; refusing to read it as rows.`);return s}Ye.queryRecords=u_;async function $W(e,t,r){return u_(e,t,{...r,paginate:!0})}Ye.queryAllRecords=$W;function xW(e){if("id"in e)return`(${(0,tr.normalizeGuid)(e.id,"id")})`;let t=typeof e.value=="string"?`'${(0,tr.odataPathLiteral)(e.value)}'`:e.value;return`(${(0,tr.assertODataName)(e.key,"alternate key name")}=${t})`}async function FW(e,t,r,n){let i=xW(r),a=`/${await(0,ni.resolveEntitySetName)(e,t)}${i}`,s=(0,Rn.ensureSuccess)(await e.patch(a,Xd(n)),e.apiUrl(a)),l=s.status===201,u=(0,Rn.readCreatedId)(s,`${t}id`);return{id:u??("id"in r?(0,tr.normalizeGuid)(r.id,"id"):""),created:l}}Ye.upsertRecord=FW;async function MW(e,t,r){var n,i;if(r.length===0)return[];let o=await(0,ni.resolveEntitySetName)(e,t),a=r.map(c=>({"@odata.type":`Microsoft.Dynamics.CRM.${t}`,...Xd(c)})),s=`/${o}/Microsoft.Dynamics.CRM.CreateMultiple`,u=(i=(n=(0,Rn.ensureSuccess)(await e.post(s,{Targets:a}),e.apiUrl(s)).body)===null||n===void 0?void 0:n.Ids)!==null&&i!==void 0?i:[];if(u.length!==r.length)throw new Ds.InvalidArgumentError(`CreateMultiple on '${t}' returned ${u.length} id(s) for ${r.length} row(s)`);return u}Ye.createRecordsBulk=MW;async function UW(e,t,r,n){let i=(0,tr.normalizeGuid)(r,"id"),o=(0,tr.normalizeGuid)(n.targetId,"targetId"),a=await(0,ni.resolveEntitySetName)(e,t),s=await(0,ni.resolveEntitySetName)(e,n.targetEntity),l=(0,tr.assertODataName)(n.relationshipName,"relationshipName"),u=`/${a}(${i})/${l}/$ref`,c={"@odata.id":e.apiUrl(`/${s}(${o})`)};(0,Rn.ensureSuccess)(await e.post(u,c),e.apiUrl(u))}Ye.associateRecords=UW;async function BW(e,t,r,n,i){let o=(0,tr.normalizeGuid)(r,"id"),a=(0,tr.normalizeGuid)(i,"targetId"),s=await(0,ni.resolveEntitySetName)(e,t),l=(0,tr.assertODataName)(n,"relationshipName"),u=`/${s}(${o})/${l}(${a})/$ref`;(0,Rn.ensureSuccess)(await e.delete(u),e.apiUrl(u))}Ye.disassociateRecords=BW});var pa=v(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.base64ToUtf8=mn.base64ToBytes=mn.bytesToBase64=mn.utf8ToBase64=mn.utf8ToBytes=void 0;var i0=32768,Lr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Eu(){return globalThis}function c_(e){let t=[];for(let r=0;r<e.length;r+=1){let n=e.charCodeAt(r);if(n>=55296&&n<=56319){let i=r+1<e.length?e.charCodeAt(r+1):0;i>=56320&&i<=57343?(n=(n-55296<<10)+(i-56320)+65536,r+=1):n=65533}else n>=56320&&n<=57343&&(n=65533);n<128?t.push(n):n<2048?t.push(192|n>>6,128|n&63):n<65536?t.push(224|n>>12,128|n>>6&63,128|n&63):t.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|n&63)}return Uint8Array.from(t)}function qW(e){let t="";for(let r=0;r<e.length;r+=i0)t+=String.fromCharCode(...e.subarray(r,r+i0));return t}function VW(e){let t="";for(let r=0;r<e.length;r+=1){let n=String.fromCharCode(e.charCodeAt(r)&255);if(n==="=")break;n==="-"?t+="+":n==="_"?t+="/":Lr.indexOf(n)>=0&&(t+=n)}for(t.length%4===1&&(t=t.slice(0,-1));t.length%4!==0;)t+="=";return t}function GW(e){let t="",r=0;for(;r+2<e.length;r+=3){let i=e[r]<<16|e[r+1]<<8|e[r+2];t+=Lr[i>>18&63]+Lr[i>>12&63]+Lr[i>>6&63]+Lr[i&63]}let n=e.length-r;if(n===1){let i=e[r]<<16;t+=`${Lr[i>>18&63]}${Lr[i>>12&63]}==`}else if(n===2){let i=e[r]<<16|e[r+1]<<8,o=Lr[i>>18&63],a=Lr[i>>12&63],s=Lr[i>>6&63];t+=`${o}${a}${s}=`}return t}function WW(e){let t=e.endsWith("==")?2:e.endsWith("=")?1:0,r=e.length/4*3-t,n=new Uint8Array(r>0?r:0),i=0;for(let o=0;o<e.length;o+=4){let a=Lr.indexOf(e[o])<<18|Lr.indexOf(e[o+1])<<12|(e[o+2]==="="?0:Lr.indexOf(e[o+2]))<<6|(e[o+3]==="="?0:Lr.indexOf(e[o+3]));i<r&&(n[i++]=a>>16&255),i<r&&(n[i++]=a>>8&255),i<r&&(n[i++]=a&255)}return n}function zW(e){let t=Eu();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"utf8"));let r=t.TextEncoder;return r?new r().encode(e):c_(e)}mn.utf8ToBytes=zW;function jW(e){let t=Eu();if(t.Buffer)return t.Buffer.from(e,"utf8").toString("base64");let r=t.TextEncoder;return d_(r?new r().encode(e):c_(e))}mn.utf8ToBase64=jW;function d_(e){let t=Eu();return t.Buffer?t.Buffer.from(e).toString("base64"):t.btoa?t.btoa(qW(e)):GW(e)}mn.bytesToBase64=d_;function f_(e){let t=Eu();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"base64"));let r=VW(e);if(t.atob){let n=t.atob(r);return Uint8Array.from(n,i=>i.charCodeAt(0))}return WW(r)}mn.base64ToBytes=f_;function HW(e){let t=[],r="",n=()=>{r+=String.fromCharCode(...t),t.length=0},i=a=>{if(a>65535){let s=a-65536;t.push(55296+(s>>10),56320+(s&1023))}else t.push(a);t.length>=i0&&n()},o=0;for(;o<e.length;){let a=e[o],s=0,l=0,u=128,c=191;if(a<128){i(a),o+=1;continue}else if(a>=194&&a<=223)s=1,l=a&31;else if(a>=224&&a<=239)s=2,l=a&15,u=a===224?160:128,c=a===237?159:191;else if(a>=240&&a<=244)s=3,l=a&7,u=a===240?144:128,c=a===244?143:191;else{i(65533),o+=1;continue}let d=o+1,f=!0;for(let m=0;m<s;m+=1,d+=1){let p=d<e.length?e[d]:-1;if(p<u||p>c){f=!1;break}u=128,c=191,l=l<<6|p&63}f?(i(l),o=d):(i(65533),o=d)}return n(),r}function KW(e){let t=Eu();return t.Buffer?t.Buffer.from(e,"base64").toString("utf8"):HW(f_(e))}mn.base64ToUtf8=KW});var g_=v(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.deleteWebResource=ii.getWebResource=ii.updateWebResource=ii.createWebResource=void 0;var JW=jr(),Au=fe(),ef=oe(),YW=pa(),p_=Q(),QW={html:1,css:2,js:3,xml:4,png:5,jpg:6,gif:7,xsl:9,ico:10,svg:11,resx:12};function m_(e){if(e.contentBase64!==void 0)return e.contentBase64;if(e.content!==void 0)return(0,YW.utf8ToBase64)(e.content)}async function h_(e,t){return(0,JW.publishWebResourceById)(e,t)}async function XW(e,t){var r;let n=m_(t);if(n===void 0)throw new p_.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:QW[t.type],content:n};t.description&&(i.description=t.description);let o=(0,Au.ensureSuccess)(await e.post("/webresourceset",i),e.apiUrl("/webresourceset")),a=(0,Au.readCreatedId)(o,"webresourceid");if(!a)throw new p_.InvalidArgumentError(`Dataverse did not return an id for web resource '${t.name}'`);return t.publish!==!1&&await h_(e,a),{id:a,name:t.name}}ii.createWebResource=XW;async function ZW(e,t,r){let n=(0,ef.normalizeGuid)(t,"id"),i={},o=m_(r);o!==void 0&&(i.content=o),r.displayName!==void 0&&(i.displayname=r.displayName),r.description!==void 0&&(i.description=r.description);let a=`/webresourceset(${n})`;(0,Au.ensureSuccess)(await e.patch(a,i),e.apiUrl(a)),r.publish!==!1&&await h_(e,n)}ii.updateWebResource=ZW;async function e6(e,t){var r;let i=`/webresourceset(${(0,ef.normalizeGuid)(t,"id")})${(0,ef.odataQuery)([["$select","name,displayname,webresourcetype,content,description"]])}`;return(r=(0,Au.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)!==null&&r!==void 0?r:{}}ii.getWebResource=e6;async function t6(e,t){let n=`/webresourceset(${(0,ef.normalizeGuid)(t,"id")})`;(0,Au.ensureSuccess)(await e.delete(n),e.apiUrl(n))}ii.deleteWebResource=t6});var tf=v(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.applyAppSettings=Lt.setAppSetting=Lt.readAppSettings=Lt.resolveSettingDefinitions=Lt.APP_SETTING_UNSET=Lt.APP_SETTING_OFF=Lt.APP_SETTING_ON=Lt.HEADER_AND_NAVIGATION_REFRESH=void 0;var Is=fe(),qi=oe();Lt.HEADER_AND_NAVIGATION_REFRESH="HeaderAndNavigationRefresh";Lt.APP_SETTING_ON="2";Lt.APP_SETTING_OFF="1";Lt.APP_SETTING_UNSET="0";function v_(e,t){return"/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,qi.odataQuery)([["$select",e],["$filter",t]])}async function w_(e,t){var r,n;let i=[...new Set(t.filter(Boolean))],o=new Map;if(i.length===0)return o;let a=i.map(c=>`uniquename eq '${(0,qi.odataLiteral)(c)}'`).join(" or "),s=`/settingdefinitions${(0,qi.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",a]])}`,u=((n=(r=(0,Is.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]).filter(Boolean);for(let c of u)c.uniquename&&o.set(c.uniquename,c);return o}Lt.resolveSettingDefinitions=w_;async function r6(e,t){var r,n,i,o;let a=(0,qi.normalizeGuid)(t,"App id"),s=v_("appsettingid,value,_settingdefinitionid_value",`_parentappmoduleid_value eq ${a}`),u=((n=(r=(0,Is.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(f=>f._settingdefinitionid_value).filter(Boolean))],d=new Map;if(c.length>0){let f=c.map(h=>`settingdefinitionid eq ${(0,qi.normalizeGuid)(h,"Setting definition id")}`).join(" or "),m=`/settingdefinitions${(0,qi.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",f]])}`,p=(0,Is.ensureSuccess)(await e.get(m),e.apiUrl(m));for(let h of((o=(i=p.body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[]).filter(Boolean))h.settingdefinitionid&&d.set(h.settingdefinitionid.toLowerCase(),h)}return u.map(f=>{var m,p,h,g,b;let w=d.get(((m=f._settingdefinitionid_value)!==null&&m!==void 0?m:"").toLowerCase());return{id:(p=f.appsettingid)!==null&&p!==void 0?p:"",name:(g=(h=w?.uniquename)!==null&&h!==void 0?h:f._settingdefinitionid_value)!==null&&g!==void 0?g:"",value:(b=f.value)!==null&&b!==void 0?b:"",...w?.displayname?{displayName:w.displayname}:{}}})}Lt.readAppSettings=r6;async function y_(e,t,r){var n,i,o;let a=v_("appsettingid,value",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${r}`),l=((i=(n=(0,Is.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]).filter(Boolean)[0];return l?.appsettingid?{id:l.appsettingid,value:(o=l.value)!==null&&o!==void 0?o:""}:void 0}async function C_(e,t,r,n){let i=(0,qi.normalizeGuid)(t,"App id"),a=(await w_(e,[r])).get(r),s=a?.settingdefinitionid;if(!s)throw new Error(`App setting '${r}' is not available in this environment: no settingdefinition row has that uniquename. The feature may be version-gated or its solution may not be installed.`);let l=(0,qi.normalizeGuid)(s,"Setting definition id"),u=await y_(e,i,l);if(u)return b_(e,u,n);let c="/appsettings",d={"[email protected]":`/appmodules(${i})`,"[email protected]":`/settingdefinitions(${l})`,value:n},f,m;try{if(f=await e.post(c,d),f.status>=200&&f.status<300)return"created"}catch(h){m=h}let p;try{p=await y_(e,i,l)}catch{p=void 0}if(p)return b_(e,p,n);throw f&&(0,Is.ensureSuccess)(f,e.apiUrl(c)),m}Lt.setAppSetting=C_;async function b_(e,t,r){if(t.value===r)return"unchanged";let n=`/appsettings(${(0,qi.normalizeGuid)(t.id,"App setting id")})`;return(0,Is.ensureSuccess)(await e.patch(n,{value:r}),e.apiUrl(n)),"updated"}async function n6(e,t,r){var n;let i=[];for(let[o,a]of Object.entries(r??{}))try{await C_(e,t,o,a)}catch(s){i.push(`App setting '${o}' was not applied: ${(n=s?.message)!==null&&n!==void 0?n:String(s)} The app was created; set it later with setAppSetting().`)}return i}Lt.applyAppSettings=n6});var nf=v(rf=>{"use strict";Object.defineProperty(rf,"__esModule",{value:!0});rf.HEADER_NAV_BOOLEAN_RULE=void 0;rf.HEADER_NAV_BOOLEAN_RULE="headerAndNavigationRefresh-must-be-boolean"});var o0=v(af=>{"use strict";Object.defineProperty(af,"__esModule",{value:!0});af.asUint8Array=void 0;var i6=Object.getPrototypeOf(Uint8Array.prototype);function of(e){let t=Object.getOwnPropertyDescriptor(i6,e);if(!t?.get)throw new Error(`this JavaScript engine has no %TypedArray%.prototype getter for ${String(e)}`);return t.get}var o6=of(Symbol.toStringTag),a6=of("buffer"),s6=of("byteOffset"),l6=of("byteLength");function u6(e){if(o6.call(e)==="Uint8Array")return new Uint8Array(a6.call(e),s6.call(e),l6.call(e))}af.asUint8Array=u6});var I_=v(Os=>{"use strict";Object.defineProperty(Os,"__esModule",{value:!0});Os.zipStored=Os.crc32=void 0;var c6=Q(),d6=pa(),f6=o0(),p6=67324752,m6=33639248,h6=101010256,sf=30,a0=46,g6=22,E_=10,y6=20,A_=2048,S_=0,N_=0,__=33,b6=65535,v6=65535,T_=4294967295,w6=3988292384,lf;function C6(){if(!lf){lf=new Uint32Array(256);for(let e=0;e<256;e+=1){let t=e;for(let r=0;r<8;r+=1)t=t&1?w6^t>>>1:t>>>1;lf[e]=t}}return lf}function D_(e){let t=C6(),r=4294967295;for(let n=0;n<e.length;n+=1)r=t[(r^e[n])&255]^r>>>8;return(r^4294967295)>>>0}Os.crc32=D_;function oi(e){return new c6.InvalidArgumentError(`zip: ${e}`)}function E6(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))return!1;t+=1}else if(r>=56320&&r<=57343)return!1}return!0}function A6(e){if(typeof e!="string"||e.length===0)throw oi("every entry needs a non-empty name.");if(e.includes("\\"))throw oi(`'${e}' contains a backslash; ZIP paths use '/'.`);if(/^[A-Za-z]:/.test(e))throw oi(`'${e}' starts with a drive letter; ZIP paths are relative.`);if(e.split("/").some(t=>t===""||t==="."||t===".."))throw oi(`'${e}' is not a relative path of named segments (no leading, trailing or doubled '/', no '.' or '..').`);if(!E6(e))throw oi(`'${e}' contains an unpaired surrogate, which has no UTF-8 form.`);return e}function S6(e,t=T_){if(e.length>b6)throw oi(`${e.length} entries is more than the 65,535 a ZIP can count without ZIP64.`);let r=Math.min(t,T_),n=new Set,i=[],o=g6;for(let f of e){let m=A6(f.name);if(n.has(m))throw oi(`'${m}' appears twice.`);n.add(m);let p=(0,f6.asUint8Array)(f.data);if(!p)throw oi(`the data for '${m}' must be a Uint8Array.`);let h=(0,d6.utf8ToBytes)(m);if(h.length>v6)throw oi(`a name of ${h.length} UTF-8 bytes is more than the 65,535 a header can record.`);o+=sf+a0+2*h.length+p.byteLength,i.push({nameBytes:h,data:p})}if(o>r)throw oi(`the archive would be ${o} bytes, more than the ${r} allowed.`);let a=new Uint8Array(o),s=new DataView(a.buffer),l=[],u=[],c=0;for(let{nameBytes:f,data:m}of i){let p=D_(m);l.push(c),u.push(p),s.setUint32(c,p6,!0),s.setUint16(c+4,E_,!0),s.setUint16(c+6,A_,!0),s.setUint16(c+8,S_,!0),s.setUint16(c+10,N_,!0),s.setUint16(c+12,__,!0),s.setUint32(c+14,p,!0),s.setUint32(c+18,m.byteLength,!0),s.setUint32(c+22,m.byteLength,!0),s.setUint16(c+26,f.length,!0),a.set(f,c+sf),a.set(m,c+sf+f.length),c+=sf+f.length+m.byteLength}let d=c;return i.forEach(({nameBytes:f,data:m},p)=>{s.setUint32(c,m6,!0),s.setUint16(c+4,y6,!0),s.setUint16(c+6,E_,!0),s.setUint16(c+8,A_,!0),s.setUint16(c+10,S_,!0),s.setUint16(c+12,N_,!0),s.setUint16(c+14,__,!0),s.setUint32(c+16,u[p],!0),s.setUint32(c+20,m.byteLength,!0),s.setUint32(c+24,m.byteLength,!0),s.setUint16(c+28,f.length,!0),s.setUint32(c+42,l[p],!0),a.set(f,c+a0),c+=a0+f.length}),s.setUint32(c,h6,!0),s.setUint16(c+8,i.length,!0),s.setUint16(c+10,i.length,!0),s.setUint32(c+12,c-d,!0),s.setUint32(c+16,d,!0),a}Os.zipStored=S6});var W_=v($e=>{"use strict";Object.defineProperty($e,"__esModule",{value:!0});$e.pcfManifestsEquivalent=$e.buildPcfSolutionZip=$e.pcfContentTypesXml=$e.pcfCustomizationsXml=$e.pcfSolutionXml=$e.pcfWebResourceName=$e.pcfControlName=$e.checkPcfControlPackage=$e.unboundPrefixes=$e.PCF_WEB_RESOURCE_TYPES=void 0;var N6=Q(),Qr=cu(),uf=pa(),_6=o0(),T6=I_();$e.PCF_WEB_RESOURCE_TYPES={html:1,htm:1,css:2,js:3,xml:4,png:5,jpg:6,jpeg:6,gif:7,xsl:9,xslt:9,ico:10,svg:11,resx:12};var D6=["code","css","resx","img","html"],O_=/^[A-Za-z_][A-Za-z0-9_]*$/,I6=/^\d+\.\d+\.\d+$/,O6=/^[A-Za-z0-9_.-]+$/;function bt(e){return new N6.InvalidArgumentError(`registerPcfControl: ${e}`)}function x_(e){return(0,Qr.elementChildren)(e).filter(t=>t.localName==="control"&&!t.namespaceURI)}function F_(e){let t=[],r=n=>{n.prefix&&!n.namespaceURI&&t.push(`<${n.tagName}>`);for(let i=0;i<n.attributes.length;i+=1){let o=n.attributes.item(i);o.prefix&&!o.namespaceURI&&t.push(`${o.name}="\u2026" on <${n.tagName}>`)}(0,Qr.elementChildren)(n).forEach(r)};return r(e),t}$e.unboundPrefixes=F_;function s0(e){let t=(0,Qr.parseManifestRoot)(e),r=F_(t);if(r.length>0)throw new Error(`the manifest uses a prefix no namespace declaration binds: ${r.join(", ")}.`);if(t.localName!=="manifest")throw new Error(`the manifest's root element is <${t.tagName}>, not <manifest>.`);if(t.namespaceURI)throw new Error(`the manifest's root element is <manifest> in the namespace '${t.namespaceURI}', not in no namespace.`);let n=x_(t)[0];if(!n)throw new Error("the control manifest has no <control> element");return{root:t,control:n}}function P6(e){let t=e.split("/");if(!t.every(a=>O6.test(a)&&a!=="."&&a!==".."))throw bt(`the resource path '${e}' is not a web resource name: use letters, digits, '_', '.' and '-' in '/'-separated segments, with no '.' or '..' segment.`);let r=t[t.length-1],n=r.lastIndexOf("."),i=n>0?r.slice(n+1).toLowerCase():"",o=Object.prototype.hasOwnProperty.call($e.PCF_WEB_RESOURCE_TYPES,i)?$e.PCF_WEB_RESOURCE_TYPES[i]:void 0;if(o===void 0)throw bt(`the resource path '${e}' has no web resource type; the extensions are ${Object.keys($e.PCF_WEB_RESOURCE_TYPES).join(", ")}.`);return o}function R6(e){var t,r,n;if(typeof e!="object"||e===null)throw bt("the control package must be an object with a manifest and files.");let{manifest:i,files:o}=e;if(typeof i!="string"||i.length===0)throw bt("the manifest must be the built ControlManifest.xml, as a string.");if(typeof o!="object"||o===null||Array.isArray(o))throw bt("files must be an object mapping each resource path to its bytes.");let a,s;try{({root:a,control:s}=s0(i))}catch(b){throw bt(b.message)}if(x_(a).length!==1)throw bt("the manifest must hold exactly one <control>.");let l=(t=(0,Qr.attr)(s,"namespace"))!==null&&t!==void 0?t:"",u=(r=(0,Qr.attr)(s,"constructor"))!==null&&r!==void 0?r:"",c=(n=(0,Qr.attr)(s,"version"))!==null&&n!==void 0?n:"";if(!l.split(".").every(b=>O_.test(b)))throw bt(`the control's namespace '${l}' is not a dotted identifier.`);if(!O_.test(u))throw bt(`the control's constructor '${u}' is not an identifier.`);if(!I6.test(c))throw bt(`the control's version '${c}' is not major.minor.patch.`);let d=(0,Qr.firstLevel)(s,"resources");if(d.length!==1)throw bt("the manifest must hold exactly one <resources> element.");let f=[],m=0;for(let b of(0,Qr.elementChildren)(d[0])){let w=(0,Qr.attr)(b,"path");if(!D6.includes(b.tagName)){if(w!==null)throw bt(`<${b.tagName} path="${w}"> is not a resource kind the SDK registers.`);continue}if(!w)throw bt(`a <${b.tagName}> resource has no path.`);m+=b.tagName==="code"?1:0,f.push(w)}if(m!==1)throw bt(`the manifest must name exactly one <code> resource; it names ${m}.`);let p=new Map,h=[];for(let b of f){let w=P6(b),C=b.toLowerCase();if(C==="controlmanifest.xml")throw bt(`the resource path '${b}' is where the package puts the manifest itself.`);let S=p.get(C);if(S!==void 0)throw bt(`the manifest names '${b}' and '${S}', which are the same web resource.`);if(p.set(C,b),!Object.prototype.hasOwnProperty.call(o,b))throw bt(`the manifest names '${b}', but files has no such key.`);let O=(0,_6.asUint8Array)(o[b]);if(!O)throw bt(`files['${b}'] must be a Uint8Array.`);h.push({path:b,data:O,webResourceType:w})}let g=Object.keys(o).filter(b=>!f.includes(b));if(g.length>0)throw bt(`files holds ${g.map(b=>`'${b}'`).join(", ")}, which the manifest does not name.`);return{namespace:l,constructorName:u,version:c,manifest:i,files:h}}$e.checkPcfControlPackage=R6;function L6(e,t){return`${e}_${t.namespace}.${t.constructorName}`}$e.pcfControlName=L6;function k6(e,t){return`cc_${e.namespace}.${e.constructorName}/${t}`}$e.pcfWebResourceName=k6;function Ps(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}var $6=["City","County","Country","Fax","FreightTermsCode","ImportSequenceNumber","Latitude","Line1","Line2","Line3","Longitude","Name","PostalCode","PostOfficeBox","PrimaryContactName"],x6=["StateOrProvince","Telephone1","Telephone2","Telephone3","TimeZoneRuleVersionNumber","UPSZone","UTCOffset","UTCConversionTimeZoneCode"];function P_(e){let t=r=>r.map(n=>`<${n} xsi:nil="true"></${n}>`).join("");return`<Address><AddressNumber>${e}</AddressNumber><AddressTypeCode>1</AddressTypeCode>${t($6)}<ShippingMethodCode>1</ShippingMethodCode>${t(x6)}</Address>`}function M_(e){let t=Ps(e.solutionUniqueName),r=Ps(e.publisherUniqueName);return`<ImportExportXml version="9.1.0.643" SolutionPackageVersion="9.1" languagecode="1033" generatedBy="CrmLive" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><SolutionManifest><UniqueName>${t}</UniqueName><LocalizedNames><LocalizedName description="${t}" languagecode="1033" /></LocalizedNames><Descriptions /><Version>1.0</Version><Managed>0</Managed><Publisher><UniqueName>${r}</UniqueName><LocalizedNames><LocalizedName description="${r}" languagecode="1033" /></LocalizedNames><Descriptions><Description description="${r}" languagecode="1033" /></Descriptions><EMailAddress xsi:nil="true"></EMailAddress><SupportingWebsiteUrl xsi:nil="true"></SupportingWebsiteUrl><CustomizationPrefix>${Ps(e.prefix)}</CustomizationPrefix><CustomizationOptionValuePrefix>${e.optionValuePrefix}</CustomizationOptionValuePrefix><Addresses>${P_(1)}${P_(2)}</Addresses></Publisher><RootComponents><RootComponent type="66" schemaName="${Ps(e.controlName)}" behavior="0" /></RootComponents><MissingDependencies /></SolutionManifest></ImportExportXml>`}$e.pcfSolutionXml=M_;function U_(e){let t=Ps(e);return`<ImportExportXml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><Entities></Entities><Roles></Roles><Workflows></Workflows><FieldSecurityProfiles></FieldSecurityProfiles><Templates /><EntityMaps /><EntityRelationships /><OrganizationSettings /><optionsets /><CustomControls><CustomControl><Name>${t}</Name><FileName>/Controls/${t}/ControlManifest.xml</FileName><ForceUpdate>true</ForceUpdate></CustomControl></CustomControls><EntityDataProviders /><Languages><Language>1033</Language></Languages></ImportExportXml>`}$e.pcfCustomizationsXml=U_;function B_(e){let t=["xml"];for(let n of e){let i=n.slice(n.lastIndexOf(".")+1).toLowerCase();t.includes(i)||t.push(i)}return`<?xml version="1.0" encoding="utf-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">${t.map(n=>`<Default Extension="${Ps(n)}" ContentType="application/octet-stream" />`).join("")}</Types>`}$e.pcfContentTypesXml=B_;function F6(e){let t=`Controls/${e.controlName}`,r=[{name:"customizations.xml",data:(0,uf.utf8ToBytes)(U_(e.controlName))},{name:"solution.xml",data:(0,uf.utf8ToBytes)(M_(e))},...e.control.files.map(n=>({name:`${t}/${n.path}`,data:n.data})),{name:`${t}/ControlManifest.xml`,data:(0,uf.utf8ToBytes)(e.control.manifest)},{name:"[Content_Types].xml",data:(0,uf.utf8ToBytes)(B_(e.control.files.map(n=>n.path)))}];return(0,T6.zipStored)(r)}$e.buildPcfSolutionZip=F6;var M6=/^[ \t\r\n]*$/,q_=1,c0=3,U6=4,V_=7;function cf(e,t){let r=(0,Qr.attr)(e,"xml:space");return r==="preserve"?!0:r==="default"?!1:t}function R_(e,t){var r;let n=[],i=e.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];(a.nodeType===q_||a.nodeType===U6||a.nodeType===V_||a.nodeType===c0&&(t||!M6.test((r=a.nodeValue)!==null&&r!==void 0?r:"")))&&n.push(a)}return n}function L_(e){return e.length>0&&e.every(t=>t.nodeType===c0)?e.map(t=>{var r;return(r=t.nodeValue)!==null&&r!==void 0?r:""}).join(""):void 0}function k_(e,t){var r;let n="",i=t;for(;i<e.length&&e[i].nodeType===c0;)n+=(r=e[i].nodeValue)!==null&&r!==void 0?r:"",i+=1;return{text:n,next:i}}function l0(e,t){return(e.namespaceURI||null)===(t.namespaceURI||null)&&e.localName===t.localName}function B6(e,t,r,n){if(e.nodeType!==t.nodeType)return!1;if(e.nodeType===q_)return G_(e,t,r,n);if(e.nodeType===V_){let i=e,o=t;return i.target===o.target&&i.data===o.data}return e.nodeValue===t.nodeValue}function q6(e,t,r,n){let i=L_(e);if(i!==void 0)return i===L_(t);if(e.length===0)return t.length===0;let o=0,a=0;for(;;){let s=k_(e,o),l=k_(t,a);if(s.text!==l.text)return!1;if(o=s.next,a=l.next,o>=e.length&&a>=t.length)return!0;if(o>=e.length||a>=t.length||!B6(e[o],t[a],r,n))return!1;o+=1,a+=1}}function G_(e,t,r,n){if(!l0(e,t)||e.attributes.length!==t.attributes.length)return!1;for(let a=0;a<e.attributes.length;a+=1){let s=e.attributes.item(a),l=t.attributes.item(a);if(!l0(s,l)||s.value!==l.value)return!1}let i=cf(e,r),o=cf(t,n);return q6(R_(e,i),R_(t,o),i,o)}function u0(e){return(0,Qr.elementChildren)(e).reduce((t,r)=>t+1+u0(r),0)}function $_(e){return cf(e,cf(e.parentNode,!1))}function V6(e,t){let r,n;try{r=s0(t).control,n=s0(e).control}catch{return!1}if(r.attributes.length!==n.attributes.length)return!1;for(let u=0;u<r.attributes.length;u+=1){let c=r.attributes.item(u),d;for(let m=0;m<n.attributes.length&&!d;m+=1){let p=n.attributes.item(m);d=l0(c,p)?p:void 0}if(!d||!(c.localName==="version"&&!c.namespaceURI)&&c.value!==d.value)return!1}if(u0(r)!==u0(n))return!1;let i=(0,Qr.elementChildren)(r),o=(0,Qr.elementChildren)(n),a=$_(r),s=$_(n),l=Math.min(i.length,o.length);for(let u=0;u<l;u+=1)if(!G_(i[u],o[u],a,s))return!1;return!0}$e.pcfManifestsEquivalent=V6});var z_=v(df=>{"use strict";Object.defineProperty(df,"__esModule",{value:!0});df.sha256Hex=void 0;var G6=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ai=(e,t)=>e>>>t|e<<32-t;function W6(e){let t=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),r=new Uint8Array(Math.ceil((e.length+9)/64)*64);r.set(e),r[e.length]=128;let n=new DataView(r.buffer);n.setUint32(r.length-8,Math.floor(e.length/536870912)),n.setUint32(r.length-4,e.length%536870912*8);let i=new Uint32Array(64);for(let o=0;o<r.length;o+=64){for(let p=0;p<16;p+=1)i[p]=n.getUint32(o+p*4);for(let p=16;p<64;p+=1){let h=ai(i[p-15],7)^ai(i[p-15],18)^i[p-15]>>>3,g=ai(i[p-2],17)^ai(i[p-2],19)^i[p-2]>>>10;i[p]=i[p-16]+h+i[p-7]+g>>>0}let[a,s,l,u,c,d,f,m]=t;for(let p=0;p<64;p+=1){let h=m+(ai(c,6)^ai(c,11)^ai(c,25))+(c&d^~c&f)+G6[p]+i[p]>>>0,g=(ai(a,2)^ai(a,13)^ai(a,22))+(a&s^a&l^s&l)>>>0;m=f,f=d,d=c,c=u+h>>>0,u=l,l=s,s=a,a=h+g>>>0}t[0]+=a,t[1]+=s,t[2]+=l,t[3]+=u,t[4]+=c,t[5]+=d,t[6]+=f,t[7]+=m}return Array.from(t,o=>o.toString(16).padStart(8,"0")).join("")}df.sha256Hex=W6});var aT=v(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.registerPcfControl=Ne.readJobVerdict=Ne.PCF_REGISTRATION_UNVERIFIED_CODE=Ne.PCF_MANIFEST_CHANGE_NEEDS_PUBLISH_ALL_CODE=Ne.PCF_RESOURCE_NAME_TAKEN_CODE=Ne.PCF_CONTROL_MANAGED_CODE=Ne.PCF_CONTROL_AMBIGUOUS_CODE=Ne.PCF_CONTROL_NAME_TAKEN_CODE=Ne.PCF_TARGET_SOLUTION_MANAGED_CODE=void 0;var z6=Es(),_o=Tt(),Vi=W_(),X_=jr(),d0=Jd(),We=Q(),j6=cu(),Su=pa(),To=fe(),Z_=ct(),nt=oe(),H6=z_();Ne.PCF_TARGET_SOLUTION_MANAGED_CODE="PCF_TARGET_SOLUTION_MANAGED";Ne.PCF_CONTROL_NAME_TAKEN_CODE="PCF_CONTROL_NAME_TAKEN";Ne.PCF_CONTROL_AMBIGUOUS_CODE="PCF_CONTROL_AMBIGUOUS";Ne.PCF_CONTROL_MANAGED_CODE="PCF_CONTROL_MANAGED";Ne.PCF_RESOURCE_NAME_TAKEN_CODE="PCF_RESOURCE_NAME_TAKEN";Ne.PCF_MANIFEST_CHANGE_NEEDS_PUBLISH_ALL_CODE="PCF_MANIFEST_CHANGE_NEEDS_PUBLISH_ALL";Ne.PCF_REGISTRATION_UNVERIFIED_CODE="PCF_REGISTRATION_UNVERIFIED";var it="registerPcfControl",f0=66,K6=5e3,j_=300*1e3,J6={hash:"webresourceid,name,ismanaged,webresourcetype,contenthash",tokens:"webresourceid,name,ismanaged,webresourcetype",content:"webresourceid,name,ismanaged,webresourcetype,content"},ff=new WeakMap;function pf(e){return new We.InvalidArgumentError(`${it}: ${e}`)}function Rs(e,t){return e.toLowerCase()===t.toLowerCase()}function si(e){return e.map(t=>`'${t}'`).join(", ")}function Y6(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function Nu(e){return e instanceof We.ConnectionError&&(e.statusCode===0||To.AMBIGUOUS_WRITE_STATUSES.has(e.statusCode))}function Q6(e,t){var r;if(e!==void 0&&(typeof e!="object"||e===null))throw pf("options must be an object.");let{solutionUniqueName:n,publishAll:i}=e??{};if(i!==void 0&&i!==!0)throw pf(`publishAll must be absent or the literal true (it was ${String(i)}): it consents to PublishAllXml, which publishes every pending customization in the org. Nothing was sent.`);if(n!==void 0&&(typeof n!="string"||!n.trim()))throw pf("solutionUniqueName must be a non-empty string. Nothing was sent.");let o=(r=n)!==null&&r!==void 0?r:t;if(!o)throw pf("name the solution the control joins \u2014 options.solutionUniqueName or MakerSdkOptions.solutionUniqueName: its publisher's prefix names the control, and the SDK never guesses one. Nothing was sent.");return{target:o,publishAll:i===!0}}function eT(e,t,r){let n=e?.["@odata.etag"];if(!(0,To.isVersionToken)(n))throw new We.ConnectionError(r,200,`${it}: ${t} came back without a version token (@odata.etag ${n===void 0?"missing":JSON.stringify(n)}), so a change since it was read could not be detected`);return n}function tT(e,t){var r,n,i,o;let a=e,s=String((r=a?.name)!==null&&r!==void 0?r:"");return{id:(0,nt.normalizeGuid)(String((n=a?.customcontrolid)!==null&&n!==void 0?n:""),"customcontrolid"),name:s,version:String((i=a?.version)!==null&&i!==void 0?i:""),manifest:String((o=a?.manifest)!==null&&o!==void 0?o:""),managed:a?.ismanaged===!0,etag:eT(e,`the control '${s}'`,t)}}function X6(e,t){var r,n;let i=e,o=String((r=i?.name)!==null&&r!==void 0?r:"");return{id:(0,nt.normalizeGuid)(String((n=i?.webresourceid)!==null&&n!==void 0?n:""),"webresourceid"),name:o,managed:i?.ismanaged===!0,type:Number(i?.webresourcetype),content:typeof i?.content=="string"?i.content:"",contentHash:typeof i?.contenthash=="string"?i.contenthash.toLowerCase():"",etag:eT(e,`the web resource '${o}'`,t)}}async function p0(e){let t=(0,nt.odataLiteral)(e.key),r=`/customcontrols${(0,nt.odataQuery)([["$select","customcontrolid,name,version,manifest,ismanaged"],["$filter",`endswith(name,'_${t}') or name eq '${t}'`]])}`,n=e.client.apiUrl(r),i=e.key.toLowerCase();return(await(0,_o.collectPages)(e.client,r,it)).filter(o=>{let a=typeof o.name=="string"?o.name.toLowerCase():"";return a===i||a.slice(a.indexOf("_")+1)===i}).map(o=>tT(o,n))}async function mf(e,t){let r=`cc_${e.key}/`,n=`/webresourceset${(0,nt.odataQuery)([["$select",J6[t]],["$filter",`startswith(name,'${(0,nt.odataLiteral)(r)}')`]])}`,i=e.client.apiUrl(n);return(await(0,_o.collectPages)(e.client,n,it)).filter(o=>typeof o.name=="string"&&o.name.toLowerCase().startsWith(r.toLowerCase())).map(o=>X6(o,i))}function Z6(e){let t=ff.get(e.sdkClient);if(t)return t;let r=`/EntityDefinitions(LogicalName='webresource')/Attributes${(0,nt.odataQuery)([["$select","LogicalName"],["$filter","LogicalName eq 'contenthash'"]])}`,n=e.client.apiUrl(r),i=e.client.get(r).then(o=>{var a;let s=(a=(0,To.ensureSuccess)(o,n).body)===null||a===void 0?void 0:a.value;if(!Array.isArray(s))throw new We.ConnectionError(n,o.status,`${it}: the columns of webresource came back unreadable`);return s.some(l=>l?.LogicalName==="contenthash")}).catch(o=>{throw ff.get(e.sdkClient)===i&&ff.delete(e.sdkClient),o});return ff.set(e.sdkClient,i),i}async function rT(e,t){let r=await(0,_o.collectPages)(e.client,`/customcontrols(${t})/customcontrol_resource_id${(0,nt.odataQuery)([["$select","webresourceid,name"]])}`,it);return new Set(r.map(n=>n.webresourceid).filter(n=>typeof n=="string"&&n!=="").map(n=>n.toLowerCase()))}async function m0(e,t){let r=`/customcontrols(${t})${(0,nt.odataQuery)([["$select","customcontrolid,name,version,manifest,ismanaged"]])}`,n=await e.client.get(r);if(n.status!==404)return(0,To.ensureSuccess)(n,e.client.apiUrl(r)),tT(n.body,e.client.apiUrl(r))}function H_(e,t,r){return new We.SdkError(Ne.PCF_RESOURCE_NAME_TAKEN_CODE,`${it}: ${si(t.map(n=>n.name))} ${t.length===1?"is":"are"} named as a file of ${e.name} but ${r}. An import would create a second web resource of the same name (the runtime loads by name); rename or delete ${t.length===1?"it":"them"} first. Nothing was written.`)}async function ez(e){let t=await p0(e),r=t.filter(u=>!Rs(u.name,e.name));if(r.length>0)throw new We.SdkError(Ne.PCF_CONTROL_NAME_TAKEN_CODE,`${it}: the control ${e.key} is registered as ${si(r.map(u=>u.name))}, under another publisher prefix \u2014 the platform keeps one control per namespace and constructor. Target a solution whose publisher has that prefix, or remove that control. Nothing was written.`);if(t.length>1)throw new We.SdkError(Ne.PCF_CONTROL_AMBIGUOUS_CODE,`${it}: ${t.length} control rows are named ${e.name}; the SDK cannot tell which one to update. Nothing was written.`);let n=t[0];if(n?.managed)throw new We.SdkError(Ne.PCF_CONTROL_MANAGED_CODE,`${it}: ${n.name} is managed; a managed control is changed by its solution's upgrade, not in place. Nothing was written.`);let i=await mf(e,await Z6(e)?"hash":"tokens");if(!n){if(i.length>0)throw H_(e,i,"no control of that name exists");return}e.progress.customControlId=n.id;let o=await rT(e,n.id),a=i.filter(u=>!o.has(u.id));if(a.length>0)throw H_(e,a,`${n.name} does not reference ${a.length===1?"it":"them"}`);let s=i.filter(u=>u.managed);if(s.length>0)throw new We.SdkError(Ne.PCF_CONTROL_MANAGED_CODE,`${it}: ${si(s.map(u=>u.name))} of ${n.name} ${s.length===1?"is":"are"} managed. Nothing was written.`);let l=new Map;for(let u of e.checked.files){let c=(0,Vi.pcfWebResourceName)(e.checked,u.path),d=i.filter(f=>Rs(f.name,c));if(d.length>1)throw new We.SdkError(Ne.PCF_CONTROL_AMBIGUOUS_CODE,`${it}: ${n.name} references ${d.length} web resources named '${c}'; the SDK cannot tell which one the runtime loads. Nothing was written.`);d.length===1&&l.set(u.path,d[0])}return{control:n,folder:i,files:l}}function tz(e){return(0,H6.sha256Hex)((0,Su.utf8ToBytes)((0,Su.bytesToBase64)(e.data)))}function rz(e,t){if(!t)return{mode:"created"};let{control:r}=t,n=(0,Vi.pcfManifestsEquivalent)(r.manifest,e.checked.manifest),i=e.checked.files.filter(s=>!t.files.has(s.path)).map(s=>s.path),o=e.checked.files.map(s=>({file:s,row:t.files.get(s.path)})).filter(({file:s,row:l})=>l!==void 0&&l.type!==s.webResourceType).map(({file:s,row:l})=>`'${l.name}' (type ${l.type}, not ${s.webResourceType})`);if(!n||i.length>0||o.length>0){if(!e.publishAll){let s=n?i.length>0?`${r.name} lacks ${si(i)}, which only a re-import restores`:`${r.name}'s ${o.join(", ")} cannot be repaired by a files-only write \u2014 only a re-import may`:`the manifest of ${r.name} changed`;throw new We.SdkError(Ne.PCF_MANIFEST_CHANGE_NEEDS_PUBLISH_ALL_CODE,`${it}: ${s}, and a re-imported control is applied only by PublishAllXml \u2014 which publishes EVERY pending customization in the org. Pass publishAll: true to consent. Nothing was written.`)}return{mode:"reimported",snapshot:t}}if(r.version!==e.checked.version){if(e.publishAll)return{mode:"reimported",snapshot:t};e.warnings.push(`${r.name} keeps version ${r.version}: a files-only update does not change it (pac's --incremental neither); applying ${e.checked.version} needs publishAll: true.`)}let a=e.checked.files.map(s=>({file:s,row:t.files.get(s.path)})).filter(({file:s,row:l})=>l.contentHash!==tz(s));return a.length>0?{mode:"updated",snapshot:t,changed:a}:{mode:"unchanged",snapshot:t}}async function hf(e,t){var r;if(!t){let s=await p0(e),l=await mf(e,"tokens");if(s.length>0||l.length>0)throw new We.VersionConflictError("customcontrol",e.name,null,null,`Since this registration first read the org, ${si([...s.map(u=>u.name),...l.map(u=>u.name)])} appeared. Nothing was written; retry the registration.`);return}let n=[],i=await m0(e,t.control.id);i?i.etag!==t.control.etag&&n.push(i.name):n.push(`${t.control.name} (deleted)`);let o=await mf(e,"tokens"),a=new Map(t.folder.map(s=>[s.id,s.etag]));for(let s of o)a.has(s.id)?a.get(s.id)!==s.etag&&n.push(s.name):n.push(`${s.name} (new)`);for(let s of t.folder)o.some(l=>l.id===s.id)||n.push(`${s.name} (deleted)`);if(n.length>0)throw new We.VersionConflictError("customcontrol",e.name,t.control.etag,(r=i?.etag)!==null&&r!==void 0?r:null,`Changed since this registration read it: ${si(n)} \u2014 by another writer, or by the platform touching them (an import or publish elsewhere in the org can move these tokens with no change). Nothing was written; retry the registration.`)}function nT(e){let t;try{t=(0,j6.parseManifestRoot)(typeof e=="string"?e:"")}catch{return{state:"unknown",reason:"settled, but its data log does not parse"}}if(t.tagName!=="importexportxml"||t.namespaceURI)return{state:"unknown",reason:`settled, but its data log's root is <${t.tagName}>`};let r=(0,Vi.unboundPrefixes)(t);if(r.length>0)return{state:"unknown",reason:`settled, but its data log uses a prefix no declaration binds (${r.join(", ")})`};let n=t.getAttribute("succeeded");return n==="success"||n==="warning"?{state:"success"}:n==="failure"?{state:"failure",message:t.getAttribute("status")||"the import failed"}:{state:"unknown",reason:"settled without a success, warning or failure verdict"}}Ne.readJobVerdict=nT;function nz(e,t){return new Promise(r=>{let n=setTimeout(()=>r("late"),t);e.then(i=>{clearTimeout(n),r({value:i})},i=>{clearTimeout(n),r({error:i})})})}async function iz(e,t){let r=`/importjobs(${t})${(0,nt.odataQuery)([["$select","completedon,data"]])}`,n=Date.now()+j_,i={state:"unknown",reason:`had not settled after ${j_/6e4} minutes`};for(;;){let o=Math.min(K6,n-Date.now());if(o<=0)return i;await new Promise(c=>setTimeout(c,o));let a=n-Date.now();if(a<=0)return i;let s=await nz(e.client.get(r),a);if(s==="late")return i;if("error"in s){if(Nu(s.error))continue;return{state:"unknown",reason:`could not be read (${s.error.message})`}}let l=s.value;if(l.status===404)continue;if(l.status<200||l.status>=300)return{state:"unknown",reason:`could not be read (HTTP ${l.status})`};let u=l.body;if(u?.completedon)return nT(u.data)}}async function oz(e,t,r){let n=(0,Z_.newId)(),i=e.checked.files.map(s=>s.path),o=r?i.filter(s=>!r.files.has(s)):i;e.progress.phase="import",e.progress.importJobId=n,e.started=!0;let a;try{await(0,d0.importSolution)(e.client,{base64:(0,Su.bytesToBase64)(t),overwriteUnmanagedCustomizations:!1,publishWorkflows:!1,importJobId:n})}catch(s){if(!Nu(s))throw s;a=s}if(a){let s=await iz(e,n);if(s.state==="failure")throw new We.ConnectionError(a.url,a.statusCode,`the import's answer was lost, and its job ${n} reports that it FAILED: ${s.message}`,a);if(s.state==="unknown")throw e.progress.imported="unknown",e.progress.unconfirmed=[...i],e.progress.publishedUnknown=[...o],new We.ConnectionError(a.url,a.statusCode,`the import's answer was lost, and its job ${n} ${s.reason}: whether it committed is unknown. Read importjobs(${n}), then retry the registration.`,a)}e.progress.imported="yes",e.progress.written=[...i],e.progress.published=[...o]}async function az(e){e.progress.phase="publish-all";let t=e.checked.files.map(r=>r.path).filter(r=>!e.progress.published.includes(r));try{await(0,X_.publishAllXml)(e.client)}catch(r){throw Nu(r)?(e.progress.publishAll="unknown",e.progress.publishedUnknown=[...e.progress.publishedUnknown,...t]):e.progress.publishAll="failed",r}e.progress.publishAll="succeeded",e.progress.published=[...e.progress.published,...t]}async function K_(e,t){var r,n;if(e.progress.imported==="unknown")return e.progress.temporaries.push(t.solution,t.publisher),[`The temporary solution '${t.solution}' and publisher '${t.publisher}' were left in place: the import's outcome is unknown, and an import still running may be using them. Delete them once importjobs(${e.progress.importJobId}) has settled.`];let i=(o,a)=>(e.progress.temporaries.push(...a),[`${si(a)} ${a.length===1?"was":"were"} left in place: ${o}. Delete ${a.length===1?"it":"them"} when convenient.`]);try{let o=await(0,_o.collectPages)(e.client,`/solutions${(0,nt.odataQuery)([["$select","solutionid"],["$filter",`uniquename eq '${(0,nt.odataLiteral)(t.solution)}'`]])}`,it);for(let a of o){let s=(0,nt.normalizeGuid)(String((r=a.solutionid)!==null&&r!==void 0?r:""),"solutionid");if(!await sz(e,s))return i(`the temporary solution holds components other than ${e.name}`,[t.solution,t.publisher]);let l=`/solutions(${s})`;(0,To.ensureSuccess)(await e.client.delete(l),e.client.apiUrl(l))}}catch(o){return i(`the temporary solution could not be removed (${o.message})`,[t.solution,t.publisher])}try{let o=await(0,_o.collectPages)(e.client,`/publishers${(0,nt.odataQuery)([["$select","publisherid"],["$filter",`uniquename eq '${(0,nt.odataLiteral)(t.publisher)}'`]])}`,it);for(let a of o){let s=(0,nt.normalizeGuid)(String((n=a.publisherid)!==null&&n!==void 0?n:""),"publisherid");if((await(0,_o.collectPages)(e.client,`/solutions${(0,nt.odataQuery)([["$select","solutionid"],["$filter",`_publisherid_value eq ${s}`]])}`,it)).length>0)return i("a solution uses the temporary publisher",[t.publisher]);let u=`/publishers(${s})`;(0,To.ensureSuccess)(await e.client.delete(u),e.client.apiUrl(u))}}catch(o){return i(`the temporary publisher could not be removed (${o.message})`,[t.publisher])}return[]}async function sz(e,t){var r,n;let i=await(0,_o.collectPages)(e.client,`/solutioncomponents${(0,nt.odataQuery)([["$select","objectid,componenttype"],["$filter",`_solutionid_value eq ${t}`]])}`,it);for(let o of i){if(o.componenttype!==f0||typeof o.objectid!="string")return!1;let a=(0,nt.normalizeGuid)(o.objectid,"objectid");if(a!==e.progress.customControlId&&!Rs((n=(r=await m0(e,a))===null||r===void 0?void 0:r.name)!==null&&n!==void 0?n:"",e.name))return!1}return!0}async function J_(e,t,r){let n=(0,Z_.newId)().replace(/-/g,"").slice(0,12),i={solution:`CdsMakerSdkPcf${n}`,publisher:`CdsMakerSdkPcfPub${n}`},o=(0,Vi.buildPcfSolutionZip)({controlName:e.name,solutionUniqueName:i.solution,publisherUniqueName:i.publisher,prefix:e.solution.publisherPrefix,optionValuePrefix:e.solution.publisherOptionValuePrefix,control:e.checked});await hf(e,r);let a;try{await oz(e,o,r),t==="reimported"&&await az(e);let s=await fz(e,r),l=await h0(e,s.id);a=g0(e,t,s,l,e.checked.files.map(u=>u.path),[])}catch(s){throw(0,We.withCleanupWarnings)(s,await K_(e,i))}return a.warnings.push(...await K_(e,i)),a}async function Y_(e,t,r){try{return await r()}catch(n){throw Nu(n)&&e.progress.unconfirmed.push(...t),n}}function lz(e){return e instanceof We.SdkError&&e.code===To.VERSION_CONFLICT_CODE&&!(e instanceof We.VersionConflictError)}async function uz(e,t,r){let n=({file:a})=>({content:(0,Su.bytesToBase64)(a.data)}),i=r.map(({file:a})=>a.path);if(e.client.supportsAtomicBatch){let a=s=>Y_(e,i,()=>(0,z6.sendChangeSet)(e.client,r.map(l=>({method:"PATCH",path:`/webresourceset(${l.row.id})`,body:n(l),etag:s?l.row.etag:"*"})),`the files of ${e.name}`));try{await a(!0)}catch(s){if(!lz(s))throw s;await hf(e,t),await a(!1)}e.progress.written.push(...i);return}let o;for(let a of r){let s=`/webresourceset(${a.row.id})`,l=c=>Y_(e,[a.file.path],async()=>{let d=await e.client.patch(s,n(a),{headers:{"If-Match":c}});return d.status===412?d:(0,To.ensureSuccess)(d,e.client.apiUrl(s))}),u=await l(o===!1?"*":a.row.etag);if(u.status===412&&o===void 0&&(await hf(e,t),o=!1,u=await l("*")),u.status===412)throw new We.VersionConflictError("webresource",a.row.id,a.row.etag,null,`'${a.row.name}' changed after this registration read it${e.progress.written.length>0?`; ${si(e.progress.written)} had been written before it`:""}. Retry the registration once the other writer is done.`);o=o??!0,e.progress.written.push(a.file.path)}}async function cz(e,t){e.progress.phase="publish";let r=t.map(({file:i})=>i.path),n=t.map(({row:i})=>`<webresource>${(0,nt.xmlText)(i.id)}</webresource>`).join("");try{await(0,X_.publishXml)(e.client,`<importexportxml><webresources>${n}</webresources></importexportxml>`)}catch(i){throw Nu(i)&&e.progress.publishedUnknown.push(...r),i}e.progress.published.push(...r)}async function dz(e,t,r){await hf(e,t),e.progress.phase="write",e.started=!0,await uz(e,t,r),await cz(e,r),e.progress.phase="verify";let n=await m0(e,t.control.id);if(!n)throw gf(e,"updated",["the control was deleted"]);let i=[];if((n.version!==t.control.version||n.manifest!==t.control.manifest)&&i.push("its control row changed since it was read \u2014 another registration re-imported it"),i.push(...await oT(e,n.id)),i.length>0)throw gf(e,"updated",i);let o=await h0(e,n.id);return g0(e,"updated",n,o,[...e.progress.written],[...e.progress.published])}function gf(e,t,r){return new We.SdkError(Ne.PCF_REGISTRATION_UNVERIFIED_CODE,`${it}: ${e.name} did not verify after it was ${t}: ${r.join("; ")}. Retrying the registration is safe.`)}function iT(e,t){let r=new Set(e.checked.files.map(n=>(0,Vi.pcfWebResourceName)(e.checked,n.path).toLowerCase()));for(let n of t){let i=`'${n.name}' is a file of ${e.name} that its manifest no longer names; the platform keeps it after a re-import, and the SDK does not delete it.`;!r.has(n.name.toLowerCase())&&!e.warnings.includes(i)&&e.warnings.push(i)}}async function oT(e,t){let r=await rT(e,t),n=await mf(e,"content"),i=[],o=n.filter(s=>!r.has(s.id));o.length>0&&i.push(`${si(o.map(s=>s.name))} in its folder ${o.length===1?"is":"are"} not its own`);let a=n.filter(s=>r.has(s.id));for(let s of e.checked.files){let l=(0,Vi.pcfWebResourceName)(e.checked,s.path),u=a.filter(d=>Rs(d.name,l));if(u.length!==1){i.push(`it references ${u.length} web resources named '${l}'`);continue}let[c]=u;c.type!==s.webResourceType&&i.push(`'${c.name}' has the web resource type ${c.type}, not ${s.webResourceType}`),c.managed&&i.push(`'${c.name}' is managed`),Y6((0,Su.base64ToBytes)(c.content),s.data)||i.push(`the published content of '${c.name}' is not the file sent`)}return iT(e,a),i}async function fz(e,t){e.progress.phase="verify";let r=t?"reimported":"created",n=await p0(e),i=n.filter(l=>Rs(l.name,e.name)),o=[],a=n.filter(l=>!Rs(l.name,e.name));if(a.length>0&&o.push(`${si(a.map(l=>l.name))} also ${a.length===1?"holds":"hold"} ${e.key}`),i.length!==1)throw gf(e,r,[...o,`${i.length} control rows are named ${e.name}`]);let[s]=i;if(e.progress.customControlId=s.id,t&&s.id!==t.control.id&&o.push(`its row is ${s.id}, not the re-imported ${t.control.id}`),s.managed&&o.push("it is managed"),s.version!==e.checked.version&&o.push(`its version is ${s.version}, not ${e.checked.version}`),(0,Vi.pcfManifestsEquivalent)(s.manifest,e.checked.manifest)||o.push("its stored manifest is not equivalent to the one sent"),o.push(...await oT(e,s.id)),o.length>0)throw gf(e,r,o);return s}async function Q_(e,t){return(await(0,_o.collectPages)(e.client,`/solutioncomponents${(0,nt.odataQuery)([["$select","solutioncomponentid"],["$filter",`_solutionid_value eq ${e.solution.solutionId} and objectid eq ${t} and componenttype eq ${f0}`]])}`,it)).length>0}async function h0(e,t){if(e.progress.phase="membership",await Q_(e,t))return"present";if(e.started=!0,await(0,d0.addSolutionComponent)(e.client,{componentId:t,componentType:f0,solutionUniqueName:e.solution.uniqueName,addRequiredComponents:!1}),!await Q_(e,t))throw new We.SdkError(Ne.PCF_REGISTRATION_UNVERIFIED_CODE,`${it}: ${e.name} is not in the solution '${e.solution.uniqueName}' after AddSolutionComponent. Retrying the registration is safe.`);return"added"}function g0(e,t,r,n,i,o){return{name:r.name,customControlId:r.id,mode:t,written:i,published:o,publishedAll:t==="reimported",storedVersion:r.version,membership:n,warnings:[...e.warnings]}}async function pz(e,t,r){let n=(0,Vi.checkPcfControlPackage)(t),{target:i,publishAll:o}=Q6(r,e.solutionName),a=e.withSolutionScope(void 0),s=await(0,d0.getSolution)(a,i);if(s.isManaged||!s.publisherPrefix)throw new We.SdkError(Ne.PCF_TARGET_SOLUTION_MANAGED_CODE,`${it}: the solution '${s.uniqueName}' ${s.isManaged?"is managed; a control joins an unmanaged solution":"has a publisher without a customization prefix, which would leave the control's name unprefixed"}. Nothing was written.`);let l=(0,Vi.pcfControlName)(s.publisherPrefix,n),u={client:a,sdkClient:e,checked:n,key:`${n.namespace}.${n.constructorName}`,name:l,solution:s,publishAll:o,progress:{phase:"import",name:l,imported:"no",written:[],unconfirmed:[],published:[],publishedUnknown:[],publishAll:"not-sent",temporaries:[]},warnings:[],started:!1};try{let c=rz(u,await ez(u));switch(c.mode){case"created":return await J_(u,"created",void 0);case"reimported":return await J_(u,"reimported",c.snapshot);case"updated":return await dz(u,c.snapshot,c.changed);default:{iT(u,c.snapshot.folder);let d=await h0(u,c.snapshot.control.id);return g0(u,"unchanged",c.snapshot.control,d,[],[])}}}catch(c){throw u.started?(0,We.withPcfRegistrationProgress)(c,u.progress):c}}Ne.registerPcfControl=pz});var v0=v(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.compileGenPage=Re.legacyEnumsNeeded=Re.createGenPageTypeScriptLoader=Re.acceptGenPageTypeScript=Re.isLoadableGenPageOutput=Re.runtimeTypesImportSpans=Re.GENPAGE_RUNTIME_TYPES_END=Re.GENPAGE_RUNTIME_TYPES_BEGIN=Re.GENPAGE_TYPESCRIPT_VERSION=void 0;var Ls=Q();Re.GENPAGE_TYPESCRIPT_VERSION="5.8.3";Re.GENPAGE_RUNTIME_TYPES_BEGIN="// --- BEGIN GENERATED RUNTIME TYPES ---";Re.GENPAGE_RUNTIME_TYPES_END="// --- END GENERATED RUNTIME TYPES ---";var Ln="./RuntimeTypes",mz="'\"`",sT=/\s/;function hz(e){return e===10||e===13||e===8232||e===8233}function gz(e,t){let r=[];e.lastIndex=0;for(let n=e.exec(t);n!==null;n=e.exec(t))r.push(n.index);return r}function dT(e){let t=[],r=Ln.length;for(let l=e.indexOf(Ln);l!==-1;l=e.indexOf(Ln,l+1)){let u=l-1;u>=0&&mz.includes(e[u])&&e[u+1+r]===e[u]&&t.push(u)}let n=[];if(t.length===0)return n;let i=-1,o=l=>{if(i<l)for(i=l;i<e.length&&e[i]!=="'"&&e[i]!=='"';)i+=1;return i},a=-1,s=l=>{for(;a+1<t.length&&t[a+1]<=l;)a+=1;return a>=0?t[a]:-1/0};for(let l=e.indexOf("import");l!==-1;){let u=l+1;if(l+6<e.length&&sT.test(e[l+6])){let c=s(o(l+6));if(c>=l+8){let d=c+2+r;for(e[d]===";"&&(d+=1);d<e.length&&sT.test(e[d]);)d+=1;n.push({start:l,end:d}),u=d}}l=e.indexOf("import",u)}return n}Re.runtimeTypesImportSpans=dT;var yz=/\b(?:import\s*['"]|export\s)/;function bz(e){let t=gz(/from\s+['"]/g,e);if(t.length===0)return!1;let r=/\bimport\s/g,n=-1,i=0;for(let o=r.exec(e);o!==null;o=r.exec(e)){let a=o.index+7;if(a>n)for(n=a;n<e.length&&!hz(e.charCodeAt(n));)n+=1;for(;i<t.length&&t[i]<a+1;)i+=1;if(i<t.length&&t[i]<n)return!0}return!1}function vz(e){return e!==void 0&&e!==""&&(yz.test(e)||bz(e))}Re.isLoadableGenPageOutput=vz;var lT=["transpileModule","createSourceFile","createProgram","getParseTreeNode","flattenDiagnosticMessageText","forEachChild","getModifiers","canHaveModifiers","isImportDeclaration","isExportDeclaration","isExportAssignment","isStringLiteral"];function fT(e){var t;let r=s=>s!==null&&(typeof s=="object"||typeof s=="function")?s:void 0,n=r(e);n&&typeof n.transpileModule!="function"&&(n=(t=r(n.default))!==null&&t!==void 0?t:n);let i=n?lT.filter(s=>typeof n?.[s]!="function"):[...lT];if(!n||i.length>0)throw new Ls.SdkError("GENPAGE_COMPILER_INVALID",`The TypeScript compiler supplied as MakerSdkOptions.typescript is not the typescript module (missing ${i.join(", ")}). Pass the 'typescript' package's module object, loadNodeTypeScript from '@maker-studio/cds-maker-sdk/node', or \u2014 in a bare engine \u2014 globalThis.ts after evaluating typescript@${Re.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js.`);let o=typeof n.version=="string"?n.version:"",a=Re.GENPAGE_TYPESCRIPT_VERSION.split(".").slice(0,2).join(".");if(o.split(".").slice(0,2).join(".")!==a)throw new Ls.SdkError("GENPAGE_COMPILER_VERSION",`The TypeScript compiler supplied as MakerSdkOptions.typescript is version '${o||"unknown"}', but generative pages are compiled with ${a}.x \u2014 the version the maker portal itself uses (${Re.GENPAGE_TYPESCRIPT_VERSION}). Another version can emit different JavaScript for the same page. Supply typescript@${Re.GENPAGE_TYPESCRIPT_VERSION}.`);return n}Re.acceptGenPageTypeScript=fT;function wz(e){let t;return()=>{if(!t){if(e===void 0)return Promise.reject(new Ls.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`This push must compile a generative page, but no TypeScript compiler was supplied. Pass MakerSdkOptions.typescript \u2014 in Node, loadNodeTypeScript from '@maker-studio/cds-maker-sdk/node'; in a bare engine, globalThis.ts after evaluating typescript@${Re.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js. Nothing was written.`));t=Promise.resolve().then(()=>typeof e=="function"?e():e).then(fT).catch(r=>{throw t=void 0,r instanceof Ls.SdkError?r:new Ls.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`The TypeScript compiler could not be loaded, so a generative page cannot be compiled (${r instanceof Error?r.message:String(r)}). Nothing was written.`)})}return t}}Re.createGenPageTypeScriptLoader=wz;var pT=e=>`${e.kind}:${e.pos}:${e.end}`;function Cz(e,t){return()=>r=>{let n=i=>{let o=e.getParseTreeNode(i);o&&t.add(pT(o)),e.forEachChild(i,n)};return n(r),r}}function b0(e){return{target:e.ScriptTarget.ES5,module:e.ModuleKind.ES2020,jsx:e.JsxEmit.React}}var Ez=2301;function uT(e,t,r){var n;let i=e.transpileModule(t,{compilerOptions:b0(e),reportDiagnostics:!0,...r?{transformers:{after:[Cz(e,r)]}}:{}}),o=((n=i.diagnostics)!==null&&n!==void 0?n:[]).filter(a=>a.category===e.DiagnosticCategory.Error).map(a=>{let s=a.file&&typeof a.start=="number"?a.file.getLineAndCharacterOfPosition(a.start):{line:0,character:0};return{line:s.line+1,column:s.character+1,rule:"genpage-source-syntax",code:a.code,message:e.flattenDiagnosticMessageText(a.messageText,`+`)}});return{code:i.outputText,diagnostics:o}}var cT=e=>e.startsWith(".")||e.startsWith("/"),yf={line:1,column:1};function y0(e,t){let r=o=>{let a=t.getLineAndCharacterOfPosition(o.getStart(t));return{line:a.line+1,column:a.character+1}},n=o=>(e.isImportDeclaration(o)||e.isExportDeclaration(o))&&o.moduleSpecifier&&e.isStringLiteral(o.moduleSpecifier)?o.moduleSpecifier.text:void 0,i=o=>t.statements.filter(a=>e.isImportDeclaration(a)&&n(a)===o);return{statement(o,a){let s=t.statements.find(l=>n(l)===o&&(a==="import"?e.isImportDeclaration(l):e.isExportDeclaration(l)));return s?r(s):yf},element(o,a){var s;for(let l of i(o)){let u=(s=l.importClause)===null||s===void 0?void 0:s.namedBindings,c=u&&e.isNamedImports(u)?u.elements.find(d=>d.name.text===a):void 0;if(c)return r(c)}return this.statement(o,"import")},binding(o){var a,s;for(let l of t.statements)if(e.isImportDeclaration(l)&&l.importClause){let u=l.importClause,c=u.namedBindings,d=((a=u.name)===null||a===void 0?void 0:a.text)===o?u.name:c&&e.isNamespaceImport(c)&&c.name.text===o?c.name:c&&e.isNamedImports(c)?c.elements.find(f=>f.name.text===o):void 0;if(d)return r(d)}else{if((e.isFunctionDeclaration(l)||e.isClassDeclaration(l))&&((s=l.name)===null||s===void 0?void 0:s.text)===o)return r(l.name);if(e.isVariableStatement(l)){let u=l.declarationList.declarations.find(c=>e.isIdentifier(c.name)&&c.name.text===o);if(u)return r(u.name)}}return yf}}}function Az(e,t,r,n){var i,o;let a=[],s=y0(e,r),l=(p,h,g)=>{a.push({...p,rule:h,code:0,message:g})},u=(p,h)=>{var g;return(e.canHaveModifiers(p)?(g=e.getModifiers(p))!==null&&g!==void 0?g:[]:[]).some(b=>b.kind===h)},c=(p,h)=>l(p,"genpage-relative-import",`'${h}' cannot resolve at runtime: the page is loaded as a single module from a blob URL, so the only relative import it may have is './RuntimeTypes'`),d="genpage-runtime-types-import-form",f=!1,m=new Set;for(let p of t.statements){if(e.isExportAssignment(p)){f=f||!p.isExportEquals;continue}if(e.isFunctionDeclaration(p)||e.isClassDeclaration(p)){u(p,e.SyntaxKind.ExportKeyword)&&u(p,e.SyntaxKind.DefaultKeyword)&&(f=!0),p.name&&m.add(p.name.text);continue}if(e.isExportDeclaration(p)){let w=p.exportClause;w&&e.isNamedExports(w)&&w.elements.some(S=>S.name.text==="default")&&(f=!0);let C=p.moduleSpecifier&&e.isStringLiteral(p.moduleSpecifier)?p.moduleSpecifier.text:void 0;C===Ln?l(s.statement(C,"export"),d,"a page cannot re-export from './RuntimeTypes': that module does not exist at runtime"):C!==void 0&&cT(C)&&c(s.statement(C,"export"),C);continue}if(!e.isImportDeclaration(p)||!e.isStringLiteral(p.moduleSpecifier))continue;let h=p.moduleSpecifier.text,g=p.importClause;if(h!==Ln){cT(h)&&c(s.statement(h,"import"),h),g?.name&&m.add(g.name.text);let w=g?.namedBindings;w&&e.isNamespaceImport(w)?m.add(w.name.text):w&&e.isNamedImports(w)&&w.elements.forEach(C=>m.add(C.name.text));continue}if(!g){l(s.statement(h,"import"),d,"a side-effect import of './RuntimeTypes' cannot resolve at runtime; import the names it declares");continue}g.name&&l(s.binding(g.name.text),d,"'./RuntimeTypes' has no default export at runtime; import its names");let b=g.namedBindings;if(b&&e.isNamespaceImport(b))l(s.binding(b.name.text),d,"a namespace import of './RuntimeTypes' is undefined at runtime \u2014 its enums are inlined under their own names; import the names instead");else if(b&&e.isNamedImports(b))for(let w of b.elements){let C=w.name.text,S=(o=(i=w.propertyName)===null||i===void 0?void 0:i.text)!==null&&o!==void 0?o:C,O=s.element(h,C);S!==C?l(O,d,`'${S} as ${C}' would be undefined at runtime: the enum is inlined as '${S}', so import it under its own name`):n?.text?n.enums.has(C)||l(O,"genpage-runtime-types-unresolved",`'${C}' is imported from './RuntimeTypes' as a VALUE, but the runtime types define no value of that name \u2014 only the choice enums of the page's data sources are values. Import a type with 'import type'.`):l(O,"genpage-runtime-types-unresolved",`'${C}' is imported from './RuntimeTypes' as a VALUE, but the page has no data sources, so no runtime types are inlined and the import reaches the runtime, which cannot load it. Import it with 'import type', or add the table it belongs to to dataSources.`)}}if(f||l(yf,"genpage-no-default-export","the page has no default export \u2014 the runtime renders the module's default export as the page component"),n?.text)for(let p of m)n.enums.has(p)&&l(s.binding(p),"genpage-runtime-types-collision",`'${p}' is declared at the page's module scope and is also one of its inlined choice enums, so the compiled page would declare it twice and fail to load. Rename the page's binding, or import the enum from './RuntimeTypes'.`);return a}function mT(e,t,r){let n,i=()=>{if(!n){let p={getSourceFile:g=>g===t.fileName?t:void 0,getDefaultLibFileName:()=>"lib.d.ts",writeFile:()=>{},getCurrentDirectory:()=>"",getCanonicalFileName:g=>g,useCaseSensitiveFileNames:()=>!0,getNewLine:()=>`+`,fileExists:g=>g===t.fileName,readFile:()=>{},directoryExists:()=>!0,getDirectories:()=>[]},h={...r,noLib:!0,noResolve:!0,allowJs:!0,types:[],alwaysStrict:!0,moduleDetection:e.ModuleDetectionKind.Force};n=e.createProgram({rootNames:[t.fileName],options:h,host:p})}return n},o,a=()=>(o||(o=i().getTypeChecker()),o),s,l=()=>{if(!s){s=new Map;try{for(let p of i().getSemanticDiagnostics(t))p.code===Ez&&typeof p.start=="number"&&s.set(p.start,e.flattenDiagnosticMessageText(p.messageText," "))}catch{}}return s},u=p=>e.isImportSpecifier(p)?p.parent.parent.parent:e.isImportClause(p)?p.parent:e.isNamespaceImport(p)?p.parent.parent:void 0,c=p=>{let h=u(p);return h!==void 0&&e.isImportDeclaration(h)&&e.isStringLiteral(h.moduleSpecifier)&&h.moduleSpecifier.text===Ln},d=p=>{var h;for(let g=p;g;g=g.parent)if(e.canHaveModifiers(g)&&((h=e.getModifiers(g))!==null&&h!==void 0?h:[]).some(b=>b.kind===e.SyntaxKind.DeclareKeyword))return!0;return!1},f=p=>d(p)||e.isImportEqualsDeclaration(p)&&(p.isTypeOnly||e.isExternalModuleReference(p.moduleReference))||e.isImportClause(p)&&p.isTypeOnly||e.isNamespaceImport(p)&&p.parent.isTypeOnly||e.isImportSpecifier(p)&&(p.isTypeOnly||p.parent.parent.isTypeOnly),m=p=>{var h;return((h=p?.declarations)!==null&&h!==void 0?h:[]).some(g=>!c(g)&&!f(g))};return{pageOwns:p=>{let h=p.parent;return m(e.isShorthandPropertyAssignment(h)&&h.name===p?a().getShorthandAssignmentValueSymbol(h):a().getSymbolAtLocation(p))},pageOwnsLocalExport:p=>m(a().getExportSpecifierLocalTargetSymbol(p)),initializerShadow:p=>l().get(p.getStart(t))}}function Sz(e,t,r,n){let i=[],o=r?.enums;if(!o||o.size===0)return i;let a=(u,c,d)=>{let f=t.getLineAndCharacterOfPosition(u.getStart(t));i.push({line:f.line+1,column:f.character+1,rule:c,code:0,message:d})},s=mT(e,t,b0(e)),l=u=>{let c,d;if(e.isPropertyAccessExpression(u)&&e.isIdentifier(u.expression))c=u.expression,d=u.name.text;else if(e.isElementAccessExpression(u)&&e.isIdentifier(u.expression)){let m=u.argumentExpression;e.isStringLiteral(m)||e.isNoSubstitutionTemplateLiteral(m)?(c=u.expression,d=m.text):e.isNumericLiteral(m)&&(c=u.expression,d=String(Number(m.text)))}let f=c&&o.has(c.text)&&n.has(pT(u))&&!s.pageOwns(c)?o.get(c.text):void 0;if(c&&f&&d!==void 0){let m=e.isPropertyAccessExpression(u)?`${f.name}.${d}`:`${f.name}[${JSON.stringify(d)}]`,p=Object.prototype.hasOwnProperty.call(f.runtime,d)?f.runtime[d]:void 0,h=f.labels.get(d),g;p===void 0?g={rule:"genpage-enum-member-unknown",message:`${m} is undefined at runtime: '${f.name}' has no member '${d}' in this environment's metadata \u2014 members are the column's choice labels, so a renamed or differently localized label no longer matches. Known: ${[...f.labels.keys()].map(w=>`'${w}'`).join(", ")}`}:h&&typeof p!="number"?g={rule:"genpage-enum-member-clobbered",message:`${m} is the string '${String(p)}' at runtime, not a choice value: the label '${d}' looks like a number, and another option's reverse mapping overwrites it. Use the choice's numeric value instead.`}:h&&h.length>1&&(g={rule:"genpage-enum-member-ambiguous",message:`${m} labels more than one choice (${h.join(", ")}); the compiled value is whichever option comes last. Use the choice's numeric value instead.`});let b=g?s.initializerShadow(c):void 0;g&&b!==void 0?a(u,"genpage-enum-initializer-shadowed",`${m} does not read the choice enum at runtime. ${b} (TS2301): the ES5 emit moves an instance field's initializer into the constructor, where that parameter or local shadows '${c.text}'. If you meant the constructor's '${c.text}', move the assignment into the constructor body, or make it a parameter property and read \`this.${c.text}\`. If you meant the choice enum, rename the constructor's parameter or local.`):g&&a(u,g.rule,g.message)}e.forEachChild(u,l)};return l(t),i}function Nz(e,t){return e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!1,e.ScriptKind.JS).statements.some(n=>(e.isImportDeclaration(n)||e.isExportDeclaration(n))&&n.moduleSpecifier!==void 0&&e.isStringLiteral(n.moduleSpecifier)&&n.moduleSpecifier.text===Ln)}function hT(e,t){return t.statements.filter(r=>e.isImportDeclaration(r)&&e.isStringLiteral(r.moduleSpecifier)&&r.moduleSpecifier.text===Ln).map(r=>r.getStart(t))}function _z(e,t){let r=e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),n=hT(e,r),i=new Set(n),o,a="",s=0;for(let l of dT(t))!o&&!i.has(l.start)&&(o={swallows:n.some(u=>u>l.start&&u<l.end),text:t.slice(l.start,l.end).trimEnd()}),a+=t.slice(s,l.start),s=l.end;return a+=t.slice(s),{code:a,inexact:o}}function Tz(e,t,r){let n=new Set(hT(e,t));for(let i=t.text.indexOf(r);i!==-1;i=t.text.indexOf(r,i+1))if(!n.has(i)){let o=t.getLineAndCharacterOfPosition(i);return{line:o.line+1,column:o.character+1}}return yf}function gT(e,t,r){if(!r||r.size===0)return[];let n=mT(e,t,{...b0(e),target:e.ScriptTarget.ESNext}),i=new Set,o=s=>{var l,u;let c=s.parent;if(e.isImportSpecifier(c)){let d=c.parent.parent.parent;e.isImportDeclaration(d)&&e.isStringLiteral(d.moduleSpecifier)&&d.moduleSpecifier.text===Ln&&((l=c.propertyName)!==null&&l!==void 0?l:c.name)===s&&i.add(s.text);return}if(e.isExportSpecifier(c)){!(c.parent.parent.moduleSpecifier!==void 0)&&((u=c.propertyName)!==null&&u!==void 0?u:c.name)===s&&!n.pageOwnsLocalExport(c)&&i.add(s.text);return}e.isPropertyAccessExpression(c)&&c.name===s||e.isBindingElement(c)&&c.propertyName===s||e.isLabeledStatement(c)||e.isBreakOrContinueStatement(c)||n.pageOwns(s)||i.add(s.text)},a=s=>{e.isIdentifier(s)&&r.has(s.text)&&o(s),e.forEachChild(s,a)};return a(t),[...r.keys()].filter(s=>i.has(s))}Re.legacyEnumsNeeded=gT;function Dz(e,t,r){if(!e?.text||!t||r.length===0)return e;let n=new Map(e.enums),i=e.text;for(let o of r){let a=t.get(o);a&&(i+=a.declaration,n.set(o,a.model))}return{text:i,enums:n}}function Iz(e,t,r,n){var i;let o=new Set,a=uT(e,t,o);if(a.diagnostics.length>0)return a;let s=e.createSourceFile("page.tsx",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.TSX),l=e.createSourceFile("page.js",a.code,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),u=Dz(r,n,gT(e,l,n)),c=[...Az(e,l,s,u),...Sz(e,s,u,o)];if(!u?.text)return{code:a.code,diagnostics:c};let d=uT(e,u.text);if(d.diagnostics.length>0)throw new Ls.SdkError("GENPAGE_RUNTIME_TYPES_INVALID",`The generated runtime types do not compile (${d.diagnostics.map(h=>`${h.line}:${h.column} ${h.message}`).join("; ")}). This is an SDK defect: the page was not written.`);let f=_z(e,a.code),m=f.code;if(c.length===0&&(!((i=f.inexact)===null||i===void 0)&&i.swallows))c.push({...y0(e,s).statement(Ln,"import"),rule:"genpage-runtime-types-import-form",code:0,message:"the maker portal's patch would remove more than this './RuntimeTypes' import: a comment or other text before it contains the word 'import', and the pattern would delete from there \u2014 taking the code in between with it. Reword or move that text."});else if(c.length===0&&f.inexact){let{text:h}=f.inexact;c.push({...Tz(e,s,h),rule:"genpage-runtime-types-import-form",code:0,message:`the maker portal's patch would delete \`${h.length>80?`${h.slice(0,79)}\u2026`:h}\` from text that only looks like an import of './RuntimeTypes' \u2014 in a string, a template or a comment \u2014 so the page it ships would differ from this source. Reword that text so it no longer reads as such an import.`})}else c.length===0&&Nz(e,m)&&c.push({...y0(e,s).statement(Ln,"import"),rule:"genpage-runtime-types-import-form",code:0,message:"this './RuntimeTypes' import is not one the maker portal's patch can remove (a comment holding a quote inside it stops the pattern), so it would reach the runtime, which cannot load it. Write it on one line, as 'import { name } from './RuntimeTypes';'."});return{code:[Re.GENPAGE_RUNTIME_TYPES_BEGIN,d.code,Re.GENPAGE_RUNTIME_TYPES_END,m].join(`-`),diagnostics:u}}Oe.compileGenPage=p8});var Eg=v(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});ps.isFailureAfterPrimaryWrite=ps.failedAfterPrimaryWrite=void 0;var NN=Symbol.for("cds-maker-sdk.createFailedAfterPrimaryWrite");function m8(e){return typeof e=="object"&&e!==null&&(e[NN]=!0),e}ps.failedAfterPrimaryWrite=m8;function h8(e){return typeof e=="object"&&e!==null&&e[NN]===!0}ps.isFailureAfterPrimaryWrite=h8});var Fd=v(Jn=>{"use strict";Object.defineProperty(Jn,"__esModule",{value:!0});Jn.appApi=Jn.deleteAppResolvingOnce=Jn.mainFormSetShapeIssues=Jn.unpublishedAppModulesQuery=void 0;var ms=Xt(),g8=Ig(),y8=og(),_N=Kr(),b8=Id(),v8=Eg(),pe=ye(),Ee=ue(),Sg=lt(),UN=Wl(),Se=Q(),w8=(0,Ee.odataQuery)([["$select","appmoduleid,name,uniquename,description,aiappdescription"]]),Ng="appmoduleid,name,uniquename,description,aiappdescription";function kd(e,t,r){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ee.odataQuery)([["$select",e],["$filter",t],["$top",r]])}Jn.unpublishedAppModulesQuery=kd;function _g(e,t){return kd(e,t?`appmoduleid eq ${t}`:void 0,t?1:void 0)}function xd(e,t){return"/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ee.odataQuery)([["$select",t],["$filter",`sitemapid eq ${e}`],["$top",1]])}function nu(e){var t;let r=(t=e.body)===null||t===void 0?void 0:t.value;if(Array.isArray(r))return r[0]}function C8(e){let t=e?.["@odata.etag"];return typeof t=="string"?t:null}function $d(e,t){if(typeof e!="string")return!1;try{return(0,Ee.normalizeGuid)(e,"sitemapid")===t}catch{return!1}}function ea(e){let t=new Set,r=[];for(let n of e??[])n&&!t.has(n)&&(t.add(n),r.push(n));return r}function E8(e){return`cdsapp_${(e||"").replace(/[^a-zA-Z0-9]/g,"")||"app"}`}async function BN(e,t){var r,n;let i=u=>{throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`The sitemap lookup for app uniquename '${t??""}' ${u}, so it cannot be determined whether this app has a sitemap. Retry; if the app is newly created, publish it first (an unpublished app is not readable).`)};if(!t)return i("cannot run because the app record carried no uniquename");let o=`/sitemaps${(0,Ee.odataQuery)([["$select","sitemapid"],["$filter",`sitemapnameunique eq '${(0,Ee.odataLiteral)(t)}'`],["$top",1]])}`,a;try{a=await e.get(o)}catch(u){return i(`failed (${u.message})`)}if(a.status<200||a.status>=300)return i(`returned HTTP ${a.status}`);let s=(r=a.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(s))return i("returned a malformed body");let l=(n=s[0])===null||n===void 0?void 0:n.sitemapid;return s.length>0&&!l?i("returned a row with no sitemapid"):l}async function A8(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,Ee.odataQuery)([["$select","webresourceid"],["$top",1],["$filter",s]])}`,n="(webresourcetype eq 5 or webresourcetype eq 6 or webresourcetype eq 7 or webresourcetype eq 10 or webresourcetype eq 11)",i=t(await e.get(r("webresourcetype eq 5 and ismanaged eq false and contains(name,'icon')")));if(i)return{id:i,managed:!1};let o=t(await e.get(r(`${n} and ismanaged eq false`)));if(o)return{id:o,managed:!1};let a=t(await e.get(r(n)));return a?{id:a,managed:!0}:void 0}var TN="627090ff-40a3-4053-8790-584edc5be201";function Ii(e){return e instanceof Error?e.message:String(e)}async function S8(e,t){var r;try{let n=`/roles${(0,Ee.odataQuery)([["$select","roleid,_parentrootroleid_value"],["$filter",`_roletemplateid_value eq ${TN}`]])}`,i=await(0,ms.collectPages)(e,n,"the System Administrator role"),o=i.find(l=>typeof l.roleid=="string"&&typeof l._parentrootroleid_value=="string"&&l.roleid.toLowerCase()===l._parentrootroleid_value.toLowerCase()),a=(r=o??i.find(l=>typeof l.roleid=="string"))===null||r===void 0?void 0:r.roleid;if(!a)return`App roles: no 'System Administrator' role (template ${TN}) was found in this environment, so the SDK did not associate one with the app \u2014 it may not be visible or playable until a role is granted access to it.`;let s=`/appmodules(${t})/appmoduleroles_association/$ref`;return(0,pe.ensureSuccess)(await e.post(s,{"@odata.id":e.apiUrl(`/roles(${a})`)}),e.apiUrl(s)),null}catch(n){return`App roles: could not associate the 'System Administrator' role with the app (${Ii(n)}); it will not be visible or playable until a role is granted access to it.`}}async function N8(e,t,r=!0){let n=[];async function i(l,u,c){try{return(await(0,ms.collectPages)(e,l,`app assets (${c} for '${t}')`)).map(f=>String(f[u])).filter(f=>f&&f!=="undefined")}catch(d){return n.push(`App components: could not enumerate ${c} for table '${t}' (${Ii(d)}); they were NOT added to the app.`),[]}}let[o,a,s]=await Promise.all([r?i(`/systemforms${(0,Ee.odataQuery)([["$select","formid"],["$filter",`objecttypecode eq '${(0,Ee.odataLiteral)(t)}' and type eq 2 and formactivationstate eq 1`]])}`,"formid","forms"):Promise.resolve([]),i(`/savedqueries${(0,Ee.odataQuery)([["$select","savedqueryid"],["$filter",`returnedtypecode eq '${(0,Ee.odataLiteral)(t)}' and querytype eq 0 and statecode eq 0`]])}`,"savedqueryid","views"),i(`/savedqueryvisualizations${(0,Ee.odataQuery)([["$select","savedqueryvisualizationid"],["$filter",`primaryentitytypecode eq '${(0,Ee.odataLiteral)(t)}'`]])}`,"savedqueryvisualizationid","charts")]);return{forms:o,views:a,charts:s,warnings:n}}var DN=new WeakMap;async function _8(e,t){let r=DN.get(e);r||(r=new Map,DN.set(e,r));let n=r.get(t);if(n!==void 0)return n;let i=await T8(e,t);return i&&r.set(t,i),i}async function IN(e,t,r){let n=new Array(e.length),i=0;async function o(){for(let a=i;a<e.length;a=i)i=a+1,n[a]=await r(e[a])}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>o())),n}async function T8(e,t){let r=`/EntityDefinitions(LogicalName='${(0,Ee.odataPathLiteral)(t)}')${(0,Ee.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 ON(e,t,r){let n=[],i=ea(t.entities),o=4,a=await IN(i,o,g=>_8(e,g)),s=i.filter((g,b)=>!a[b]);if(s.length>0)throw new Se.SdkError("APP_ENTITY_COMPONENT_UNRESOLVED",`Refusing to build app components: table(s) ${s.map(g=>`'${g}'`).join(", ")} could not be resolved to an EntityDefinitions MetadataId + EntitySetName. Pinning the rest would produce an app whose navigation references a table the app does not contain. Verify the table name(s) exist in this environment and retry.`);let l=a.filter(g=>!!g);for(let g of l)n.push({"@odata.id":`${g.entitySetName}(${g.metadataId})`});for(let g of ea(t.components.forms))n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});for(let g of ea(t.components.views))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:g});for(let g of ea(t.components.charts))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:g});for(let g of ea(t.components.dashboards))n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});let u=new Set(t.components.forms),c=new Set(t.components.views),d=new Set(t.components.charts),f=new Map((r??[]).map(g=>[g.table,g])),p=await IN(i,o,g=>N8(e,g,!f.has(g.toLowerCase()))),m=p.flatMap(g=>g.warnings),h=new Set([...ea(t.components.forms),...ea(t.components.dashboards)].map(Ur));return p.forEach((g,b)=>{let w=f.get(i[b].toLowerCase());if(w)for(let E of w.allowed)h.has(E)||(h.add(E),u.add(E),n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:E}));else for(let E of g.forms)u.has(E)||(u.add(E),n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:E}));for(let E of g.views)c.has(E)||(c.add(E),n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:E}));for(let E of g.charts)d.has(E)||(d.add(E),n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:E}))}),{components:n,tables:l,warnings:m}}function Ur(e){let t=String(e).trim();return(t.startsWith("{")&&t.endsWith("}")?t.slice(1,-1):t).toLowerCase()}var Dg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Tg="/components/mainFormsByTable",PN=50;function qN(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function VN(e,t){if(e===void 0)return[];if(e===null||typeof e!="object"||Array.isArray(e))return[{pointer:Tg,rule:"app-main-form-set-shape",message:"must be an object mapping a table logical name to its Main form ids"}];let r=[],n=new Set(t.map(o=>o.toLowerCase())),i=new Set;for(let[o,a]of Object.entries(e)){let s=o.toLowerCase(),l=`${Tg}/${qN(o)}`;if(i.has(s)){r.push({pointer:l,rule:"app-main-form-set-shape",message:`table '${o}' is listed twice (logical names compare case-insensitively)`});continue}if(i.add(s),n.has(s)||r.push({pointer:l,rule:"app-main-form-set-table",message:`'${o}' is not a table this app's sitemap navigates to (Entity subareas: ${[...n].join(", ")||"none"})`}),!Array.isArray(a)){r.push({pointer:l,rule:"app-main-form-set-shape",message:"must be an array of Main form ids"});continue}if(a.length===0){r.push({pointer:l,rule:"app-main-form-set-empty",message:`an empty list is refused: an app with no Main form of '${o}' offers every form of the table`});continue}let u=new Set;a.forEach((c,d)=>{let f=`${l}/${d}`;typeof c!="string"||!Dg.test(Ur(c))?r.push({pointer:f,rule:"app-main-form-set-shape",message:`'${String(c)}' is not a form id`}):u.has(Ur(c))?r.push({pointer:f,rule:"app-main-form-set-shape",message:`form '${c}' is listed twice`}):u.add(Ur(c))})}return r}Jn.mainFormSetShapeIssues=VN;async function RN(e,t,r){let n=t.components.mainFormsByTable;if(n===void 0)return;let i=VN(n,t.entities);if(i.length>0)throw new Se.ValidationError("app",r,i);if(Object.keys(n).length===0)return;let o=[],a=[];for(let[l,u]of Object.entries(n)){let c=l.toLowerCase(),d=await(0,ms.collectPages)(e,`/systemforms${(0,Ee.odataQuery)([["$select","formid,formactivationstate"],["$filter",`objecttypecode eq '${(0,Ee.odataLiteral)(c)}' and type eq 2`]])}`,`app Main-form allow-list ('${c}')`),f=new Set,p=new Set;for(let h of d)typeof h.formid=="string"&&(f.add(Ur(h.formid)),Number(h.formactivationstate)===1&&p.add(Ur(h.formid)));let m=u.map(Ur);m.forEach((h,g)=>{let b=`${Tg}/${qN(l)}/${g}`;f.has(h)?p.has(h)||o.push({pointer:b,rule:"app-main-form-set-inactive",message:`Main form '${u[g]}' of '${c}' is inactive, so no app can offer it`}):o.push({pointer:b,rule:"app-main-form-set-not-main-form",message:`'${u[g]}' is not a Main form of '${c}'`})}),a.push({table:c,allowed:m,catalog:f})}let s=[...t.components.forms.map((l,u)=>({id:l,pointer:`/components/forms/${u}`})),...t.components.dashboards.map((l,u)=>({id:l,pointer:`/components/dashboards/${u}`}))];for(let l of s){let u=Ur(l.id);for(let c of a)c.catalog.has(u)&&!c.allowed.includes(u)&&o.push({pointer:l.pointer,rule:"app-main-form-set-conflict",message:`'${l.id}' is a Main form of '${c.table}' outside its allow-list, and this pin (an explicit form or dashboard, or a sitemap DashBoard subarea) would add it. Remove the pin, or list the form.`})}if(o.length>0)throw new Se.ValidationError("app",r,o);return a}async function D8(e,t){var r,n;let i=u=>({kind:"inconclusive",reason:u}),o=await e.get(kd("appmoduleid,appmoduleidunique,componentstate",`appmoduleid eq ${t}`));if(o.status<200||o.status>=300)return i(`reading the app returned HTTP ${o.status}`);let a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a)||a.length===0)return i("reading the app returned no row");let s=a.length===1?a:a.filter(u=>Number(u?.componentstate)===1),l=s.length===1?(n=s[0])===null||n===void 0?void 0:n.appmoduleidunique:"";return typeof l!="string"||!Dg.test(Ur(l))?i(`no single current layer among ${a.length} app row(s)`):{kind:"read",unique:Ur(l)}}function Rd(e,t){let r;return()=>r??(r=D8(e,t))}async function GN(e,t,r,n=Rd(e,t)){let i=p=>({kind:"inconclusive",reason:p}),o=await n();if(o.kind==="inconclusive")return o;let a=o.unique,s;try{let p=await(0,ms.collectPages)(e,`/appmodulecomponents${(0,Ee.odataQuery)([["$select","objectid"],["$filter",`_appmoduleidunique_value eq ${Ur(a)} and componenttype eq 60`]])}`,`app Main-form membership ('${t}')`);if(p.some(m=>typeof m.objectid!="string"))return i("a form component carries no object id");s=p.map(m=>Ur(String(m.objectid)))}catch(p){return i(`reading its form components failed (${Ii(p)})`)}let l=new Map,u=[];for(let p of new Set(s)){let m=r.find(h=>h.catalog.has(p));m?l.set(p,m.table):u.push(p)}if(u.some(p=>!Dg.test(p)))return i("a form component carries an object id that is not a GUID");let c=new Set(r.map(p=>p.table)),d=new Set;for(let p=0;p<u.length;p+=PN){let m=u.slice(p,p+PN);try{let h=await(0,ms.collectPages)(e,`/systemforms${(0,Ee.odataQuery)([["$select","formid,type,objecttypecode"],["$filter",m.map(g=>`formid eq ${g}`).join(" or ")]])}`,`app Main-form membership ('${t}': classifying components)`);for(let g of h){if(typeof g.formid!="string"||typeof g.type!="number"||g.type===2&&(typeof g.objecttypecode!="string"||g.objecttypecode===""))continue;let b=Ur(g.formid);d.add(b);let w=g.type===2?String(g.objecttypecode).toLowerCase():"";c.has(w)&&l.set(b,w)}}catch(h){return i(`classifying its form components failed (${Ii(h)})`)}}let f=u.filter(p=>!d.has(p));return f.length>0?i(`form component(s) ${f.join(", ")} could not be classified`):{kind:"read",tables:r.map(p=>{let m=[...l].filter(([,h])=>h===p.table).map(([h])=>h);return{table:p.table,members:m,extras:m.filter(h=>!p.allowed.includes(h)),missing:p.allowed.filter(h=>!m.includes(h))}})}}async function I8(e,t,r,n){let i=await GN(e,t,r,n);if(i.kind==="inconclusive")throw new Se.SdkError("APP_MAIN_FORM_SET_UNVERIFIED",`App '${t}': its Main-form allow-list was written but could not be verified \u2014 ${i.reason}.`);let o=i.tables.filter(a=>a.extras.length>0||a.missing.length>0);if(o.length>0)throw new Se.SdkError("APP_MAIN_FORM_SET_NOT_APPLIED",`App '${t}': its Main forms do not match the allow-list after the write \u2014 ${o.map(a=>`'${a.table}': unexpected [${a.extras.join(", ")}], missing [${a.missing.join(", ")}]`).join("; ")}.`)}async function O8(e,t,r,n){let i;try{i=await GN(e,t,r,n)}catch(a){i={kind:"inconclusive",reason:Ii(a)}}if(i.kind==="inconclusive")return[`Main-form membership of app '${t}' could not be verified (${i.reason}).`];let o=[];for(let a of i.tables)a.extras.length>0&&o.push(`Main-form components outside the allow-list remain for table '${a.table}': [${a.extras.join(", ")}]. This option controls additions only; it does not remove existing components. Runtime form availability has not been verified.`),a.missing.length>0&&o.push(`Allow-listed Main forms are not in app '${t}' after the push for table '${a.table}': [${a.missing.join(", ")}]; re-push to retry.`);return o}async function LN(e,t,r){if(r.length===0)return;let n="/AddAppComponents";(0,pe.ensureSuccess)(await e.post(n,{AppId:t,Components:r}),e.apiUrl(n))}async function kN(e,t,r,n=Rd(e,t)){var i;if(r.length===0)return;let o=await n();if(o.kind==="inconclusive")throw new Se.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its components were written but could not be verified \u2014 ${o.reason}. Re-push to retry.`);let a=`/appmodulecomponents${(0,Ee.odataQuery)([["$select","objectid,componenttype"],["$filter",`_appmoduleidunique_value eq ${o.unique} and componenttype eq 1`]])}`,s=await e.get(a);if(s.status<200||s.status>=300)throw new Se.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 reading them back returned HTTP ${s.status}. Re-push to retry.`);let l=(i=s.body)===null||i===void 0?void 0:i.value;if(!Array.isArray(l))throw new Se.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 the read-back returned no readable result set. Re-push to retry.`);let u=new Set(l.map(d=>d.objectid).filter(d=>typeof d=="string").map(d=>d.toLowerCase())),c=r.filter(d=>!u.has(d.metadataId.toLowerCase()));if(c.length>0)throw new Se.SdkError("APP_COMPONENTS_NOT_PERSISTED",`App '${t}': ${c.length} declared table(s) are NOT components of the app after AddAppComponents reported success \u2014 ${c.map(d=>`'${d.logicalName}' (expected objectid ${d.metadataId})`).join(", ")}. The app's navigation would reference content the app does not contain.`)}async function P8(e,t,r){let n=`/appmodules(${t})`,i=`/sitemaps(${r.sitemapId})`,o;try{o=await L8(e,r.sitemapId,r.sitemapNameUnique)}catch(l){return{outcome:"kept",reason:`whether its sitemap row exists could not be determined (${Ii(l)})`}}let a=o==="foreign",s=l=>l.kind==="deleted"?{outcome:"removed",foreignSitemap:a}:l.kind==="refused"?{outcome:"kept",foreignSitemap:a,reason:`its delete was refused (${Ii(l.error)})`}:{outcome:"unconfirmed",foreignSitemap:a,reason:`its delete was sent but its outcome is unknown (${Ii(l.error)})`};try{if(o==="absent"||o==="foreign"){if(!r.serverRefusedSitemap)return{outcome:"kept",foreignSitemap:a,reason:"the sitemap write's outcome was never observed, so its row may still appear"};let l=await(0,pe.resendAppSearchIndexRace)(()=>e.delete(n));return s(l.status===404?{kind:"deleted"}:zN(l,e.apiUrl(n)))}return e.supportsAtomicBatch?r.sitemapWriteToken?s(await jN(e,[{path:n},{path:i,etag:r.sitemapWriteToken}])):{outcome:"kept",reason:"the sitemap write returned no token of its own, and deleting the row without one could destroy another writer's change"}:{outcome:"kept",reason:"the HttpClient cannot send an atomic change set (no `postRaw`), and deleting the two rows one at a time could strand the sitemap"}}catch(l){return s({kind:"unknown",error:l})}}function R8(e,t,r){if(!(e instanceof Error))return e;let n=t.foreignSitemap?` Sitemap id '${r.sitemapId}' already belongs to ANOTHER app's sitemap, which was left untouched and must not be deleted: supply a sitemapId no other app uses, or omit it so one is minted.`:"";if(t.outcome==="removed")return e.message+=` The partial app this create wrote was removed.${n}`,e;let i=t.foreignSitemap?`appmodule '${r.appId}' (unique name '${r.uniqueName}')`:`appmodule '${r.appId}' (unique name '${r.uniqueName}') and, if it was written, sitemap '${r.sitemapId}'`,a=`a create with that unique name is refused \u2014 remove it in the maker portal, or, once you have confirmed the rows are this create's own, with ${t.foreignSitemap?`deleteRecord('appmodule', '${r.appId}')`:`deleteRecord('appmodule', '${r.appId}') and deleteRecord('sitemap', '${r.sitemapId}')`}.`;return e.message+=t.outcome==="kept"?` The partial app this create wrote was KEPT, because ${t.reason}: ${i}. While it exists, ${a}`:` Whether the partial app this create wrote was removed could not be confirmed, because ${t.reason}. Check for ${i}: while any of it exists, ${a}`,e.message+=n,e}async function L8(e,t,r){var n,i,o;let a=xd(t,"sitemapid,sitemapnameunique"),s=await e.get(a);if(s.status<200||s.status>=300)throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned HTTP ${s.status}, so it cannot be determined whether the row exists.`);let l=(n=s.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(l))throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned no readable result set, so it cannot be determined whether the row exists.`);return l.length===0?"absent":String((o=(i=l[0])===null||i===void 0?void 0:i.sitemapnameunique)!==null&&o!==void 0?o:"")===r?"ours":"foreign"}async function k8(e,t){var r;let n;try{n=await e.get(kd("appmoduleid,uniquename,componentstate",`appmoduleid eq ${t}`))}catch(s){return{kind:"unsettled",why:`its unpublished read failed (${s.message})`}}if(n.status<200||n.status>=300)return{kind:"unsettled",why:`its unpublished read returned HTTP ${n.status}`};let i=(r=n.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(i)||i.length!==1)return{kind:"unsettled",why:`its unpublished read returned ${Array.isArray(i)?i.length:"no"} row(s), not exactly one`};let o=i[0],a=o?.uniquename;return!$d(o?.appmoduleid,t)||o?.componentstate!==1||typeof a!="string"||!a?{kind:"unsettled",why:"its unpublished row is not this app as a never-published draft"}:{kind:"draft",uniquename:a}}async function WN(e,t){var r;let n=(0,Ee.normalizeGuid)(t,"id"),i=b=>{throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${n}': ${b} Deleting the app would destroy the only pointer to its sitemap, stranding that row and reserving its unique name forever. Retry.`)},o=`/appmodules(${n})${w8}`,a;try{a=await e.get(o)}catch(b){return i(`reading the app failed (${b.message}).`)}let s,l=!1;if(a.status===404){let b=await k8(e,n);if(b.kind!=="draft")return i(`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; ${b.why}.`);s=b.uniquename,l=!0}else{if(a.status<200||a.status>=300)return i(`reading the app returned HTTP ${a.status}.`);s=(r=a.body)===null||r===void 0?void 0:r.uniquename}if(!s)return i("the app record carried no uniquename, so its sitemap cannot be located.");let u=l?{draft:!0}:{appEtag:(0,pe.readEtag)(a)},c=await BN(e,s);if(!c)return{uniquename:s,...u};let d=(0,Ee.normalizeGuid)(c,"sitemapId"),f=await Ld(e,d),p=xd(d,"sitemapid,sitemapnameunique,sitemapxml"),m;try{m=await e.get(p)}catch(b){return i(`reading sitemap '${d}' failed (${b.message}).`)}if(m.status<200||m.status>=300)return i(`reading sitemap '${d}' returned HTTP ${m.status}.`);let h=nu(m);if(!h)return i(`sitemap '${d}' was not returned by the unpublished-aware read.`);if(h.sitemapnameunique!==s)return i(`sitemap '${d}' now carries sitemapnameunique '${String(h.sitemapnameunique)}', not '${s}', so it is no longer this app's sitemap.`);if(!$d(h.sitemapid,d))return i(`sitemap '${d}' was read back as a row carrying sitemapid '${String(h.sitemapid)}'.`);let g=h.sitemapxml;return typeof g!="string"?i(`sitemap '${d}' returned no sitemapxml.`):{sitemapId:d,uniquename:s,sitemapXml:g,...u,sitemapEtag:f}}async function x8(e,t,r){let n=(0,Ee.normalizeGuid)(t,"id"),i=await WN(e,n);await r?.(i.sitemapXml),await KN(e,n,i)}Jn.deleteAppResolvingOnce=x8;async function $8(e,t){let r=await jN(e,t);if(r.kind!=="deleted")throw r.error}function zN(e,t){try{return(0,pe.ensureSuccess)(e,t),{kind:"deleted"}}catch(r){return HN(e.status)?{kind:"refused",error:r}:{kind:"unknown",error:r}}}function F8(e,t){var r;if(e.status!==400&&(e.status<200||e.status>=300))return!1;let n=(r=(0,UN.parseChangeSetParts)(e.body,t))===null||r===void 0?void 0:r.filter(i=>i.status<200||i.status>=300);return n!==void 0&&n.length>0&&n.every(i=>i.status===400&&(0,pe.namesAppSearchIndexRace)(i.text))}async function jN(e,t){let r=`batch_${(0,Sg.newId)()}`,n=`changeset_${(0,Sg.newId)()}`,i=t.map((p,m)=>[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${m+1}`,"",`DELETE ${e.apiUrl(p.path)} HTTP/1.1`,...p.etag?[`If-Match: ${p.etag}`]:[],""].join(`\r+`),diagnostics:c}}Re.compileGenPage=Iz});var w0=v(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});ks.isFailureAfterPrimaryWrite=ks.failedAfterPrimaryWrite=void 0;var yT=Symbol.for("cds-maker-sdk.createFailedAfterPrimaryWrite");function Oz(e){return typeof e=="object"&&e!==null&&(e[yT]=!0),e}ks.failedAfterPrimaryWrite=Oz;function Pz(e){return typeof e=="object"&&e!==null&&e[yT]===!0}ks.isFailureAfterPrimaryWrite=Pz});var Af=v(li=>{"use strict";Object.defineProperty(li,"__esModule",{value:!0});li.appApi=li.deleteAppResolvingOnce=li.mainFormSetShapeIssues=li.unpublishedAppModulesQuery=void 0;var $s=Tt(),Rz=T0(),Lz=jg(),bT=jr(),kz=tf(),$z=w0(),ge=fe(),Ae=oe(),E0=ct(),PT=Es(),_e=Q(),xz=(0,Ae.odataQuery)([["$select","appmoduleid,name,uniquename,description,aiappdescription"]]),A0="appmoduleid,name,uniquename,description,aiappdescription";function wf(e,t,r){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ae.odataQuery)([["$select",e],["$filter",t],["$top",r]])}li.unpublishedAppModulesQuery=wf;function S0(e,t){return wf(e,t?`appmoduleid eq ${t}`:void 0,t?1:void 0)}function Cf(e,t){return"/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ae.odataQuery)([["$select",t],["$filter",`sitemapid eq ${e}`],["$top",1]])}function _u(e){var t;let r=(t=e.body)===null||t===void 0?void 0:t.value;if(Array.isArray(r))return r[0]}function Fz(e){let t=e?.["@odata.etag"];return typeof t=="string"?t:null}function Ef(e,t){if(typeof e!="string")return!1;try{return(0,Ae.normalizeGuid)(e,"sitemapid")===t}catch{return!1}}function ma(e){let t=new Set,r=[];for(let n of e??[])n&&!t.has(n)&&(t.add(n),r.push(n));return r}function Mz(e){return`cdsapp_${(e||"").replace(/[^a-zA-Z0-9]/g,"")||"app"}`}async function RT(e,t){var r,n;let i=u=>{throw new _e.SdkError("APP_SITEMAP_UNRESOLVED",`The sitemap lookup for app uniquename '${t??""}' ${u}, so it cannot be determined whether this app has a sitemap. Retry; if the app is newly created, publish it first (an unpublished app is not readable).`)};if(!t)return i("cannot run because the app record carried no uniquename");let o=`/sitemaps${(0,Ae.odataQuery)([["$select","sitemapid"],["$filter",`sitemapnameunique eq '${(0,Ae.odataLiteral)(t)}'`],["$top",1]])}`,a;try{a=await e.get(o)}catch(u){return i(`failed (${u.message})`)}if(a.status<200||a.status>=300)return i(`returned HTTP ${a.status}`);let s=(r=a.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(s))return i("returned a malformed body");let l=(n=s[0])===null||n===void 0?void 0:n.sitemapid;return s.length>0&&!l?i("returned a row with no sitemapid"):l}async function Uz(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,Ae.odataQuery)([["$select","webresourceid"],["$top",1],["$filter",s]])}`,n="(webresourcetype eq 5 or webresourcetype eq 6 or webresourcetype eq 7 or webresourcetype eq 10 or webresourcetype eq 11)",i=t(await e.get(r("webresourcetype eq 5 and ismanaged eq false and contains(name,'icon')")));if(i)return{id:i,managed:!1};let o=t(await e.get(r(`${n} and ismanaged eq false`)));if(o)return{id:o,managed:!1};let a=t(await e.get(r(n)));return a?{id:a,managed:!0}:void 0}var vT="627090ff-40a3-4053-8790-584edc5be201";function Gi(e){return e instanceof Error?e.message:String(e)}async function Bz(e,t){var r;try{let n=`/roles${(0,Ae.odataQuery)([["$select","roleid,_parentrootroleid_value"],["$filter",`_roletemplateid_value eq ${vT}`]])}`,i=await(0,$s.collectPages)(e,n,"the System Administrator role"),o=i.find(l=>typeof l.roleid=="string"&&typeof l._parentrootroleid_value=="string"&&l.roleid.toLowerCase()===l._parentrootroleid_value.toLowerCase()),a=(r=o??i.find(l=>typeof l.roleid=="string"))===null||r===void 0?void 0:r.roleid;if(!a)return`App roles: no 'System Administrator' role (template ${vT}) was found in this environment, so the SDK did not associate one with the app \u2014 it may not be visible or playable until a role is granted access to it.`;let s=`/appmodules(${t})/appmoduleroles_association/$ref`;return(0,ge.ensureSuccess)(await e.post(s,{"@odata.id":e.apiUrl(`/roles(${a})`)}),e.apiUrl(s)),null}catch(n){return`App roles: could not associate the 'System Administrator' role with the app (${Gi(n)}); it will not be visible or playable until a role is granted access to it.`}}async function qz(e,t,r=!0){let n=[];async function i(l,u,c){try{return(await(0,$s.collectPages)(e,l,`app assets (${c} for '${t}')`)).map(f=>String(f[u])).filter(f=>f&&f!=="undefined")}catch(d){return n.push(`App components: could not enumerate ${c} for table '${t}' (${Gi(d)}); they were NOT added to the app.`),[]}}let[o,a,s]=await Promise.all([r?i(`/systemforms${(0,Ae.odataQuery)([["$select","formid"],["$filter",`objecttypecode eq '${(0,Ae.odataLiteral)(t)}' and type eq 2 and formactivationstate eq 1`]])}`,"formid","forms"):Promise.resolve([]),i(`/savedqueries${(0,Ae.odataQuery)([["$select","savedqueryid"],["$filter",`returnedtypecode eq '${(0,Ae.odataLiteral)(t)}' and querytype eq 0 and statecode eq 0`]])}`,"savedqueryid","views"),i(`/savedqueryvisualizations${(0,Ae.odataQuery)([["$select","savedqueryvisualizationid"],["$filter",`primaryentitytypecode eq '${(0,Ae.odataLiteral)(t)}'`]])}`,"savedqueryvisualizationid","charts")]);return{forms:o,views:a,charts:s,warnings:n}}var wT=new WeakMap;async function Vz(e,t){let r=wT.get(e);r||(r=new Map,wT.set(e,r));let n=r.get(t);if(n!==void 0)return n;let i=await Gz(e,t);return i&&r.set(t,i),i}async function CT(e,t,r){let n=new Array(e.length),i=0;async function o(){for(let a=i;a<e.length;a=i)i=a+1,n[a]=await r(e[a])}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>o())),n}async function Gz(e,t){let r=`/EntityDefinitions(LogicalName='${(0,Ae.odataPathLiteral)(t)}')${(0,Ae.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 ET(e,t,r){let n=[],i=ma(t.entities),o=4,a=await CT(i,o,g=>Vz(e,g)),s=i.filter((g,b)=>!a[b]);if(s.length>0)throw new _e.SdkError("APP_ENTITY_COMPONENT_UNRESOLVED",`Refusing to build app components: table(s) ${s.map(g=>`'${g}'`).join(", ")} could not be resolved to an EntityDefinitions MetadataId + EntitySetName. Pinning the rest would produce an app whose navigation references a table the app does not contain. Verify the table name(s) exist in this environment and retry.`);let l=a.filter(g=>!!g);for(let g of l)n.push({"@odata.id":`${g.entitySetName}(${g.metadataId})`});for(let g of ma(t.components.forms))n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});for(let g of ma(t.components.views))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:g});for(let g of ma(t.components.charts))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:g});for(let g of ma(t.components.dashboards))n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});let u=new Set(t.components.forms),c=new Set(t.components.views),d=new Set(t.components.charts),f=new Map((r??[]).map(g=>[g.table,g])),m=await CT(i,o,g=>qz(e,g,!f.has(g.toLowerCase()))),p=m.flatMap(g=>g.warnings),h=new Set([...ma(t.components.forms),...ma(t.components.dashboards)].map(Xr));return m.forEach((g,b)=>{let w=f.get(i[b].toLowerCase());if(w)for(let C of w.allowed)h.has(C)||(h.add(C),u.add(C),n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:C}));else for(let C of g.forms)u.has(C)||(u.add(C),n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:C}));for(let C of g.views)c.has(C)||(c.add(C),n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:C}));for(let C of g.charts)d.has(C)||(d.add(C),n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:C}))}),{components:n,tables:l,warnings:p}}function Xr(e){let t=String(e).trim();return(t.startsWith("{")&&t.endsWith("}")?t.slice(1,-1):t).toLowerCase()}var _0=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,N0="/components/mainFormsByTable",AT=50;function LT(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function kT(e,t){if(e===void 0)return[];if(e===null||typeof e!="object"||Array.isArray(e))return[{pointer:N0,rule:"app-main-form-set-shape",message:"must be an object mapping a table logical name to its Main form ids"}];let r=[],n=new Set(t.map(o=>o.toLowerCase())),i=new Set;for(let[o,a]of Object.entries(e)){let s=o.toLowerCase(),l=`${N0}/${LT(o)}`;if(i.has(s)){r.push({pointer:l,rule:"app-main-form-set-shape",message:`table '${o}' is listed twice (logical names compare case-insensitively)`});continue}if(i.add(s),n.has(s)||r.push({pointer:l,rule:"app-main-form-set-table",message:`'${o}' is not a table this app's sitemap navigates to (Entity subareas: ${[...n].join(", ")||"none"})`}),!Array.isArray(a)){r.push({pointer:l,rule:"app-main-form-set-shape",message:"must be an array of Main form ids"});continue}if(a.length===0){r.push({pointer:l,rule:"app-main-form-set-empty",message:`an empty list is refused: an app with no Main form of '${o}' offers every form of the table`});continue}let u=new Set;a.forEach((c,d)=>{let f=`${l}/${d}`;typeof c!="string"||!_0.test(Xr(c))?r.push({pointer:f,rule:"app-main-form-set-shape",message:`'${String(c)}' is not a form id`}):u.has(Xr(c))?r.push({pointer:f,rule:"app-main-form-set-shape",message:`form '${c}' is listed twice`}):u.add(Xr(c))})}return r}li.mainFormSetShapeIssues=kT;async function ST(e,t,r){let n=t.components.mainFormsByTable;if(n===void 0)return;let i=kT(n,t.entities);if(i.length>0)throw new _e.ValidationError("app",r,i);if(Object.keys(n).length===0)return;let o=[],a=[];for(let[l,u]of Object.entries(n)){let c=l.toLowerCase(),d=await(0,$s.collectPages)(e,`/systemforms${(0,Ae.odataQuery)([["$select","formid,formactivationstate"],["$filter",`objecttypecode eq '${(0,Ae.odataLiteral)(c)}' and type eq 2`]])}`,`app Main-form allow-list ('${c}')`),f=new Set,m=new Set;for(let h of d)typeof h.formid=="string"&&(f.add(Xr(h.formid)),Number(h.formactivationstate)===1&&m.add(Xr(h.formid)));let p=u.map(Xr);p.forEach((h,g)=>{let b=`${N0}/${LT(l)}/${g}`;f.has(h)?m.has(h)||o.push({pointer:b,rule:"app-main-form-set-inactive",message:`Main form '${u[g]}' of '${c}' is inactive, so no app can offer it`}):o.push({pointer:b,rule:"app-main-form-set-not-main-form",message:`'${u[g]}' is not a Main form of '${c}'`})}),a.push({table:c,allowed:p,catalog:f})}let s=[...t.components.forms.map((l,u)=>({id:l,pointer:`/components/forms/${u}`})),...t.components.dashboards.map((l,u)=>({id:l,pointer:`/components/dashboards/${u}`}))];for(let l of s){let u=Xr(l.id);for(let c of a)c.catalog.has(u)&&!c.allowed.includes(u)&&o.push({pointer:l.pointer,rule:"app-main-form-set-conflict",message:`'${l.id}' is a Main form of '${c.table}' outside its allow-list, and this pin (an explicit form or dashboard, or a sitemap DashBoard subarea) would add it. Remove the pin, or list the form.`})}if(o.length>0)throw new _e.ValidationError("app",r,o);return a}async function Wz(e,t){var r,n;let i=u=>({kind:"inconclusive",reason:u}),o=await e.get(wf("appmoduleid,appmoduleidunique,componentstate",`appmoduleid eq ${t}`));if(o.status<200||o.status>=300)return i(`reading the app returned HTTP ${o.status}`);let a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a)||a.length===0)return i("reading the app returned no row");let s=a.length===1?a:a.filter(u=>Number(u?.componentstate)===1),l=s.length===1?(n=s[0])===null||n===void 0?void 0:n.appmoduleidunique:"";return typeof l!="string"||!_0.test(Xr(l))?i(`no single current layer among ${a.length} app row(s)`):{kind:"read",unique:Xr(l)}}function bf(e,t){let r;return()=>r??(r=Wz(e,t))}async function $T(e,t,r,n=bf(e,t)){let i=m=>({kind:"inconclusive",reason:m}),o=await n();if(o.kind==="inconclusive")return o;let a=o.unique,s;try{let m=await(0,$s.collectPages)(e,`/appmodulecomponents${(0,Ae.odataQuery)([["$select","objectid"],["$filter",`_appmoduleidunique_value eq ${Xr(a)} and componenttype eq 60`]])}`,`app Main-form membership ('${t}')`);if(m.some(p=>typeof p.objectid!="string"))return i("a form component carries no object id");s=m.map(p=>Xr(String(p.objectid)))}catch(m){return i(`reading its form components failed (${Gi(m)})`)}let l=new Map,u=[];for(let m of new Set(s)){let p=r.find(h=>h.catalog.has(m));p?l.set(m,p.table):u.push(m)}if(u.some(m=>!_0.test(m)))return i("a form component carries an object id that is not a GUID");let c=new Set(r.map(m=>m.table)),d=new Set;for(let m=0;m<u.length;m+=AT){let p=u.slice(m,m+AT);try{let h=await(0,$s.collectPages)(e,`/systemforms${(0,Ae.odataQuery)([["$select","formid,type,objecttypecode"],["$filter",p.map(g=>`formid eq ${g}`).join(" or ")]])}`,`app Main-form membership ('${t}': classifying components)`);for(let g of h){if(typeof g.formid!="string"||typeof g.type!="number"||g.type===2&&(typeof g.objecttypecode!="string"||g.objecttypecode===""))continue;let b=Xr(g.formid);d.add(b);let w=g.type===2?String(g.objecttypecode).toLowerCase():"";c.has(w)&&l.set(b,w)}}catch(h){return i(`classifying its form components failed (${Gi(h)})`)}}let f=u.filter(m=>!d.has(m));return f.length>0?i(`form component(s) ${f.join(", ")} could not be classified`):{kind:"read",tables:r.map(m=>{let p=[...l].filter(([,h])=>h===m.table).map(([h])=>h);return{table:m.table,members:p,extras:p.filter(h=>!m.allowed.includes(h)),missing:m.allowed.filter(h=>!p.includes(h))}})}}async function zz(e,t,r,n){let i=await $T(e,t,r,n);if(i.kind==="inconclusive")throw new _e.SdkError("APP_MAIN_FORM_SET_UNVERIFIED",`App '${t}': its Main-form allow-list was written but could not be verified \u2014 ${i.reason}.`);let o=i.tables.filter(a=>a.extras.length>0||a.missing.length>0);if(o.length>0)throw new _e.SdkError("APP_MAIN_FORM_SET_NOT_APPLIED",`App '${t}': its Main forms do not match the allow-list after the write \u2014 ${o.map(a=>`'${a.table}': unexpected [${a.extras.join(", ")}], missing [${a.missing.join(", ")}]`).join("; ")}.`)}async function jz(e,t,r,n){let i;try{i=await $T(e,t,r,n)}catch(a){i={kind:"inconclusive",reason:Gi(a)}}if(i.kind==="inconclusive")return[`Main-form membership of app '${t}' could not be verified (${i.reason}).`];let o=[];for(let a of i.tables)a.extras.length>0&&o.push(`Main-form components outside the allow-list remain for table '${a.table}': [${a.extras.join(", ")}]. This option controls additions only; it does not remove existing components. Runtime form availability has not been verified.`),a.missing.length>0&&o.push(`Allow-listed Main forms are not in app '${t}' after the push for table '${a.table}': [${a.missing.join(", ")}]; re-push to retry.`);return o}async function NT(e,t,r){if(r.length===0)return;let n="/AddAppComponents";(0,ge.ensureSuccess)(await e.post(n,{AppId:t,Components:r}),e.apiUrl(n))}async function _T(e,t,r,n=bf(e,t)){var i;if(r.length===0)return;let o=await n();if(o.kind==="inconclusive")throw new _e.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its components were written but could not be verified \u2014 ${o.reason}. Re-push to retry.`);let a=`/appmodulecomponents${(0,Ae.odataQuery)([["$select","objectid,componenttype"],["$filter",`_appmoduleidunique_value eq ${o.unique} and componenttype eq 1`]])}`,s=await e.get(a);if(s.status<200||s.status>=300)throw new _e.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 reading them back returned HTTP ${s.status}. Re-push to retry.`);let l=(i=s.body)===null||i===void 0?void 0:i.value;if(!Array.isArray(l))throw new _e.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 u=new Set(l.map(d=>d.objectid).filter(d=>typeof d=="string").map(d=>d.toLowerCase())),c=r.filter(d=>!u.has(d.metadataId.toLowerCase()));if(c.length>0)throw new _e.SdkError("APP_COMPONENTS_NOT_PERSISTED",`App '${t}': ${c.length} declared table(s) are NOT components of the app after AddAppComponents reported success \u2014 ${c.map(d=>`'${d.logicalName}' (expected objectid ${d.metadataId})`).join(", ")}. The app's navigation would reference content the app does not contain.`)}async function Hz(e,t,r){let n=`/appmodules(${t})`,i=`/sitemaps(${r.sitemapId})`,o;try{o=await Jz(e,r.sitemapId,r.sitemapNameUnique)}catch(l){return{outcome:"kept",reason:`whether its sitemap row exists could not be determined (${Gi(l)})`}}let a=o==="foreign",s=l=>l.kind==="deleted"?{outcome:"removed",foreignSitemap:a}:l.kind==="refused"?{outcome:"kept",foreignSitemap:a,reason:`its delete was refused (${Gi(l.error)})`}:{outcome:"unconfirmed",foreignSitemap:a,reason:`its delete was sent but its outcome is unknown (${Gi(l.error)})`};try{if(o==="absent"||o==="foreign"){if(!r.serverRefusedSitemap)return{outcome:"kept",foreignSitemap:a,reason:"the sitemap write's outcome was never observed, so its row may still appear"};let l=await(0,ge.resendAppSearchIndexRace)(()=>e.delete(n));return s(l.status===404?{kind:"deleted"}:FT(l,e.apiUrl(n)))}return e.supportsAtomicBatch?r.sitemapWriteToken?s(await MT(e,[{path:n},{path:i,etag:r.sitemapWriteToken}])):{outcome:"kept",reason:"the sitemap write returned no token of its own, and deleting the row without one could destroy another writer's change"}:{outcome:"kept",reason:"the HttpClient cannot send an atomic change set (no `postRaw`), and deleting the two rows one at a time could strand the sitemap"}}catch(l){return s({kind:"unknown",error:l})}}function Kz(e,t,r){if(!(e instanceof Error))return e;let n=t.foreignSitemap?` Sitemap id '${r.sitemapId}' already belongs to ANOTHER app's sitemap, which was left untouched and must not be deleted: supply a sitemapId no other app uses, or omit it so one is minted.`:"";if(t.outcome==="removed")return e.message+=` The partial app this create wrote was removed.${n}`,e;let i=t.foreignSitemap?`appmodule '${r.appId}' (unique name '${r.uniqueName}')`:`appmodule '${r.appId}' (unique name '${r.uniqueName}') and, if it was written, sitemap '${r.sitemapId}'`,a=`a create with that unique name is refused \u2014 remove it in the maker portal, or, once you have confirmed the rows are this create's own, with ${t.foreignSitemap?`deleteRecord('appmodule', '${r.appId}')`:`deleteRecord('appmodule', '${r.appId}') and deleteRecord('sitemap', '${r.sitemapId}')`}.`;return e.message+=t.outcome==="kept"?` The partial app this create wrote was KEPT, because ${t.reason}: ${i}. While it exists, ${a}`:` Whether the partial app this create wrote was removed could not be confirmed, because ${t.reason}. Check for ${i}: while any of it exists, ${a}`,e.message+=n,e}async function Jz(e,t,r){var n,i,o;let a=Cf(t,"sitemapid,sitemapnameunique"),s=await e.get(a);if(s.status<200||s.status>=300)throw new _e.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned HTTP ${s.status}, so it cannot be determined whether the row exists.`);let l=(n=s.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(l))throw new _e.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned no readable result set, so it cannot be determined whether the row exists.`);return l.length===0?"absent":String((o=(i=l[0])===null||i===void 0?void 0:i.sitemapnameunique)!==null&&o!==void 0?o:"")===r?"ours":"foreign"}async function Yz(e,t){var r;let n;try{n=await e.get(wf("appmoduleid,uniquename,componentstate",`appmoduleid eq ${t}`))}catch(s){return{kind:"unsettled",why:`its unpublished read failed (${s.message})`}}if(n.status<200||n.status>=300)return{kind:"unsettled",why:`its unpublished read returned HTTP ${n.status}`};let i=(r=n.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(i)||i.length!==1)return{kind:"unsettled",why:`its unpublished read returned ${Array.isArray(i)?i.length:"no"} row(s), not exactly one`};let o=i[0],a=o?.uniquename;return!Ef(o?.appmoduleid,t)||o?.componentstate!==1||typeof a!="string"||!a?{kind:"unsettled",why:"its unpublished row is not this app as a never-published draft"}:{kind:"draft",uniquename:a}}async function xT(e,t){var r;let n=(0,Ae.normalizeGuid)(t,"id"),i=b=>{throw new _e.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${n}': ${b} Deleting the app would destroy the only pointer to its sitemap, stranding that row and reserving its unique name forever. Retry.`)},o=`/appmodules(${n})${xz}`,a;try{a=await e.get(o)}catch(b){return i(`reading the app failed (${b.message}).`)}let s,l=!1;if(a.status===404){let b=await Yz(e,n);if(b.kind!=="draft")return i(`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; ${b.why}.`);s=b.uniquename,l=!0}else{if(a.status<200||a.status>=300)return i(`reading the app returned HTTP ${a.status}.`);s=(r=a.body)===null||r===void 0?void 0:r.uniquename}if(!s)return i("the app record carried no uniquename, so its sitemap cannot be located.");let u=l?{draft:!0}:{appEtag:(0,ge.readEtag)(a)},c=await RT(e,s);if(!c)return{uniquename:s,...u};let d=(0,Ae.normalizeGuid)(c,"sitemapId"),f=await vf(e,d),m=Cf(d,"sitemapid,sitemapnameunique,sitemapxml"),p;try{p=await e.get(m)}catch(b){return i(`reading sitemap '${d}' failed (${b.message}).`)}if(p.status<200||p.status>=300)return i(`reading sitemap '${d}' returned HTTP ${p.status}.`);let h=_u(p);if(!h)return i(`sitemap '${d}' was not returned by the unpublished-aware read.`);if(h.sitemapnameunique!==s)return i(`sitemap '${d}' now carries sitemapnameunique '${String(h.sitemapnameunique)}', not '${s}', so it is no longer this app's sitemap.`);if(!Ef(h.sitemapid,d))return i(`sitemap '${d}' was read back as a row carrying sitemapid '${String(h.sitemapid)}'.`);let g=h.sitemapxml;return typeof g!="string"?i(`sitemap '${d}' returned no sitemapxml.`):{sitemapId:d,uniquename:s,sitemapXml:g,...u,sitemapEtag:f}}async function Qz(e,t,r){let n=(0,Ae.normalizeGuid)(t,"id"),i=await xT(e,n);await r?.(i.sitemapXml),await BT(e,n,i)}li.deleteAppResolvingOnce=Qz;async function Xz(e,t){let r=await MT(e,t);if(r.kind!=="deleted")throw r.error}function FT(e,t){try{return(0,ge.ensureSuccess)(e,t),{kind:"deleted"}}catch(r){return UT(e.status)?{kind:"refused",error:r}:{kind:"unknown",error:r}}}function Zz(e,t){var r;if(e.status!==400&&(e.status<200||e.status>=300))return!1;let n=(r=(0,PT.parseChangeSetParts)(e.body,t))===null||r===void 0?void 0:r.filter(i=>i.status<200||i.status>=300);return n!==void 0&&n.length>0&&n.every(i=>i.status===400&&(0,ge.namesAppSearchIndexRace)(i.text))}async function MT(e,t){let r=`batch_${(0,E0.newId)()}`,n=`changeset_${(0,E0.newId)()}`,i=t.map((m,p)=>[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${p+1}`,"",`DELETE ${e.apiUrl(m.path)} HTTP/1.1`,...m.etag?[`If-Match: ${m.etag}`]:[],""].join(`\r`)),o=[`--${r}`,`Content-Type: multipart/mixed;boundary=${n}`,"",...i,`--${n}--`,`--${r}--`,""].join(`\r-`),a=e.apiUrl("/$batch"),s=i.map((p,m)=>String(m+1)),l;try{l=await(0,pe.resendWhile)(p=>F8(p,s),()=>e.postBatch(o,r),pe.DEADLOCK_BACKOFF_MS)}catch(p){return{kind:"unknown",error:p}}let u=zN(l,a);if(u.kind!=="deleted")return u;let c=`app '${t[0].path}'`;if(typeof l.body!="string"||l.body.length===0)return{kind:"unknown",error:new Se.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`)};let d=(0,UN.parseChangeSetStatuses)(l.body,s);if(d===void 0)return{kind:"unknown",error:new Se.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`)};let f=d.find(p=>p<200||p>=300);return f!==void 0?{kind:"refused",error:new Se.ConnectionError(a,f,`atomic delete of ${c} was rolled back: the change set reported HTTP ${f}`)}:d.length!==i.length?{kind:"unknown",error:new Se.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response reported ${d.length} operation result(s), expected exactly ${i.length}`)}:{kind:"deleted"}}async function Ld(e,t){try{let r=await e.get(`/sitemaps(${t})?$select=sitemapid`);return r.status<200||r.status>=300?null:(0,pe.readEtag)(r)}catch{return null}}async function xN(e,t){let r=`/appmodules(${t})?$select=appmoduleid`,n=await e.get(r);if(n.status!==404)return(0,pe.ensureSuccess)(n,e.apiUrl(r)),(0,pe.readEtag)(n)}async function Ag(e,t,r,n){if(!n)return null;let i=await Ld(e,t);if(!i)return null;try{let o=await e.get(xd(t,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"));if(o.status<200||o.status>=300)return null;let a=nu(o);return!a||!$d(a.sitemapid,t)||a.sitemapnameunique!==n||a.sitemapxml!==r.sitemapxml||a.sitemapname!==r.sitemapname?null:i}catch{return null}}function HN(e){return e>=400&&e<500&&e!==408&&e!==429}function $N(e,t,r){if(!e)throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${t}': the ${r} read returned no ETag, so the delete cannot be made conditional on the row that was actually inspected. Without that condition a row renamed or re-pointed between the read and the delete would be destroyed. Retry.`);return e}async function KN(e,t,r){let n=`/appmodules(${t})`,i=r.draft?void 0:$N(r.appEtag,t,"app");if(!r.sitemapId){if(r.draft){(0,pe.ensureSuccess)(await(0,pe.resendAppSearchIndexRace)(()=>e.delete(n)),e.apiUrl(n));return}await M8(e,n,i);return}if(!e.supportsAtomicBatch)throw new Se.SdkError("APP_DELETE_NOT_ATOMIC",`Refusing to delete app '${t}': it owns a sitemap, and the injected HttpClient cannot send a raw body, so the two rows would have to be deleted as separate requests. A failure between them strands the sitemap and permanently reserves the app's unique name. Implement HttpClient.postRaw so the SDK can delete them atomically.`);await $8(e,[{path:n,etag:i},{path:`/sitemaps(${r.sitemapId})`,etag:$N(r.sitemapEtag,t,"sitemap")}])}async function M8(e,t,r){(0,pe.ensureSuccess)(await(0,pe.resendAppSearchIndexRace)(()=>e.delete(t,{headers:{"If-Match":r}})),e.apiUrl(t))}async function FN(e,t){if(!/GenPageId/i.test(t))return;let r;try{r=[...new Set((0,g8.collectGenPageIds)(t))]}catch(i){throw new Se.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 (${Ii(i)}).`)}if(r.length===0)return;let n=await(0,y8.findMissingGenPages)(e,r,"sitemap generative-page preflight");if(n.length>0)throw new Se.SdkError("SITEMAP_TARGET_NOT_FOUND",`Refusing to push the app: its sitemap navigates to generative page(s) ${n.map(i=>`'${i}'`).join(", ")} that do not exist in this environment. Push the page before the app that links to it.`)}function U8(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")}async function MN(e,t,r){var n;let i=(0,Ee.normalizeGuid)(t,"id"),o=r==="tokens-first",a=o?await xN(e,i):null,s=_g(Ng,i),l=(0,pe.ensureSuccess)(await e.get(s),e.apiUrl(s)),u=(n=nu(l))!==null&&n!==void 0?n:{};if(!u.appmoduleid)throw new Se.SdkError("APP_NOT_FOUND",`App '${i}' was not found (checked the unpublished-aware projection, which includes drafts).`);let c=await BN(e,u.uniquename),d=c?(0,Ee.normalizeGuid)(c,"sitemapId"):void 0,f=null;if(d){o&&(f=await Ld(e,d));let m=xd(d,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"),h=(0,pe.ensureSuccess)(await e.get(m),e.apiUrl(m)),g=nu(h),b=w=>{throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': its sitemap '${d}' was located by unique name, but ${w}, so the sitemap cannot be read. Persisting the app without it would misreport it as having no sitemap, or write an empty one over its navigation. Retry.`)};if(!g)return b("the by-id read returned no row");if(g.sitemapnameunique!==u.uniquename)throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': sitemap '${d}' now carries sitemapnameunique '${String(g.sitemapnameunique)}', not '${String(u.uniquename)}', so it is no longer this app's sitemap. Retry.`);if(!$d(g.sitemapid,d))return b(`the by-id read returned a row carrying sitemapid '${String(g.sitemapid)}'`);if(typeof g.sitemapxml!="string")return b("the by-id read returned no sitemapxml");u.$sitemap=g,o||(f=await Ld(e,d))}o||(a=await xN(e,i));let p=a??C8(u);return{raw:u,etag:f,...u.appmoduleid?{siblingEtags:{[(0,Ee.normalizeGuid)(u.appmoduleid,"appmoduleid")]:p}}:{}}}Jn.appApi={get(e,t){return MN(e,t,"tokens-first")},readContentThenToken(e,t){return MN(e,t,"content-first")},async list(e,t){let r=_g(Ng);return(await(0,ms.collectPages)(e,r,"listArtifacts('app')")).map(i=>{var o,a;return{type:"app",id:(o=i.appmoduleid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",isDirty:!1}})},async create(e,t,r){let n=t;await FN(e,n.sitemapxml);let i=await RN(e,n,n.appModuleId),o=n.iconWebResourceId?void 0:await A8(e),a=n.iconWebResourceId||o?.id;if(!a)throw new Se.SdkError("APP_ICON_UNRESOLVED",`Cannot create app '${n.appModuleName}': its icon (\`appmodule.webresourceid\`) is a REQUIRED attribute and this environment has no image web resource to use. Pass \`iconWebResourceId\` explicitly, or add an image (PNG/JPG/GIF/ICO/SVG) web resource to the environment.`);let s=null;o?.managed&&(s=`No unmanaged image web resource was available, so the app icon resolved to a MANAGED one (${o.id}). That creates a cross-solution dependency which can fail to import into an environment without the owning managed solution. Pass \`iconWebResourceId\` with an in-solution image to avoid it.`);let l=n.appModuleUniqueName||E8(n.appModuleId),u={name:n.appModuleName,uniquename:l,clienttype:4,formfactor:1,navigationtype:0};n.appModuleDescription&&(u.description=n.appModuleDescription),n.appModuleAiDescription&&(u.aiappdescription=n.appModuleAiDescription),a&&(u.webresourceid=a);let c="/appmodules",d=(0,pe.ensureSuccess)(await(0,pe.resendDeadlockVictim)(()=>e.post(c,(0,pe.withClientMintedId)(u,"appmoduleid",r))),e.apiUrl(c)),f=(0,pe.resolveCreatedId)(d,"appmoduleid","app module",r),p=null,m=null,h=[];s&&h.push(s);let g={kind:"notRequested"},b=n.sitemapId?(0,Ee.normalizeGuid)(n.sitemapId,"sitemapId"):(0,Sg.newId)(),w=!1,E={sitemapxml:n.sitemapxml,sitemapname:n.sitemapname};try{let L="/sitemaps",R=(0,pe.echoWrite)("sitemapid"),I=await e.post(`${L}${R.query}`,{sitemapid:b,sitemapnameunique:l,...E},R.options);w=HN(I.status);let D=(0,pe.ensureSuccess)(I,e.apiUrl(L));m=(0,pe.readEtag)(D),p=m??await Ag(e,b,E,l);let O=await ON(e,n,i);h.push(...O.warnings);let $=O.components;$.unshift({"@odata.type":"Microsoft.Dynamics.CRM.sitemap",sitemapid:b}),await LN(e,f,$);let K=Rd(e,f);await kN(e,f,O.tables,K),i&&await I8(e,f,i,K);let Re=await S8(e,f);Re&&h.push(Re),n.appSettings&&Object.keys(n.appSettings).length>0&&h.push(...await(0,b8.applyAppSettings)(e,f,n.appSettings)),n.published!==!1&&(await(0,_N.publishAppModule)(e,f),g={kind:"submitted"})}catch(L){let R=await P8(e,f,{sitemapId:b,sitemapNameUnique:l,serverRefusedSitemap:w,sitemapWriteToken:m});throw(0,v8.failedAfterPrimaryWrite)(R8(L,R,{appId:f,sitemapId:b,uniqueName:l}))}let A=null;if(g.kind==="submitted")try{let L=await e.get(`/appmodules(${f})?$select=appmoduleid`);L.status>=200&&L.status<300&&(A=(0,pe.readEtag)(L))}catch{}return{id:f,etag:p,serverIdentity:{sitemapId:b},siblingEtags:{[f]:A},publish:g,...h.length>0?{warnings:h}:{}}},async update(e,t,r,n,i,o){var a,s,l,u,c,d,f,p,m;let h=r,g=(0,Ee.normalizeGuid)(t,"id");if(await FN(e,h.sitemapxml),!h.sitemapId)throw new Se.ValidationError("app",g,[{pointer:"/sitemapId",rule:"app-sitemap-identity-missing",message:`missing sitemap identity \u2014 re-fetch the app before pushing edits: fetchArtifact('app', '${g}', { overwrite: true }) (it REPLACES the local copy \u2014 keep outstanding changes aside), push that refreshed copy UNTOUCHED, then re-apply your changes and push again. If the untouched push is refused with this same rule, the app has NO sitemap on the server \u2014 an earlier create committed its appmodule but not its sitemap \u2014 and it can be neither updated, published nor removed with deleteRemoteArtifact (an unpublished app reads back 404). Only for an app you have confirmed is your own abandoned partial create, with nothing else provisioning it: remove its appmodule row with deleteRecord('appmodule', '${g}'), clear the local copy with deleteArtifact('app', '${g}'), then author the app again and push.`}]);let b=(0,Ee.normalizeGuid)(h.sitemapId,"sitemapId");if(!(0,pe.isVersionToken)(n))throw new Se.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${g}': ${n?`the concurrency token held for its sitemap row ('${n}') is not a version`:"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 RN(e,h,g),E=await ON(e,h,w),A=`/appmodules(${g})`,L=(a=o?.[g])!==null&&a!==void 0?a:null,R=!0,I;try{let Ot=_g(Ng,g),di=await e.get(Ot);if(di.status>=200&&di.status<300){let Ra=(s=nu(di))!==null&&s!==void 0?s:{};I=typeof Ra.uniquename=="string"&&Ra.uniquename?Ra.uniquename:void 0,R=String((l=Ra.name)!==null&&l!==void 0?l:"")!==String((u=h.appModuleName)!==null&&u!==void 0?u:"")||String((c=Ra.description)!==null&&c!==void 0?c:"")!==String((d=h.appModuleDescription)!==null&&d!==void 0?d:"")||h.appModuleAiDescription!==void 0&&String((f=Ra.aiappdescription)!==null&&f!==void 0?f:"")!==String(h.appModuleAiDescription)}}catch{}let D=L;if(R){if(!(0,pe.isVersionToken)(L))throw new Se.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${g}': ${L?`the concurrency token held for its appmodule header ('${L}') is not a version`:"no concurrency token is held for its appmodule header"}, so its header edit could not be made conditional and would silently overwrite a concurrent edit. Nothing was modified. Re-fetch the app (fetchArtifact('app', '${g}', { overwrite: true })) and re-apply the change.`);let Ot=(0,pe.echoWrite)("appmoduleid",{"If-Match":L}),di=await e.patch(`${A}${Ot.query}`,{name:h.appModuleName,description:h.appModuleDescription,...h.appModuleAiDescription!==void 0?{aiappdescription:h.appModuleAiDescription}:{}},Ot.options);if(U8(di))throw new Se.SdkError("APP_DRAFT_HEADER_NOT_WRITABLE",`Refusing to update app '${g}': its appmodule row is UNPUBLISHED, and Dataverse cannot resolve version numbers for a draft appmodule (HTTP 400). A draft header cannot be PATCHed at all \u2014 a plain retry fails too, as an upsert-create ("webresourceid cannot be NULL"). Publish the app first, then push the header edit. Nothing was modified by this call.`);(0,pe.ensureSuccess)(di,e.apiUrl(A)),D=(0,pe.readEtag)(di)}let O={sitemapxml:h.sitemapxml,sitemapname:h.sitemapname},$=I||h.appModuleUniqueName||void 0,K=(0,pe.echoWrite)("sitemapid",{"If-Match":n}),Re=`/sitemaps(${b})`,It;try{It=(0,pe.ensureSuccess)(await e.patch(`${Re}${K.query}`,{...O},K.options),e.apiUrl(Re))}catch(Ot){throw(0,Se.withPartialTokens)(Ot,{siblingEtags:{[g]:D}})}let Le=[...E.warnings],at=Rd(e,g);try{await LN(e,g,E.components),await kN(e,g,E.tables,at)}catch(Ot){Le.push(`App '${g}': one or more components were not pinned (${Ot.message}). Navigation may reference content not included in the app; re-push to retry.`)}w&&Le.push(...await O8(e,g,w,at));let ge={kind:"notRequested"},ht=D,Ro=(p=(0,pe.readEtag)(It))!==null&&p!==void 0?p:await Ag(e,b,O,$);if(h.published===!0){try{await(0,_N.publishAppModule)(e,g),ge={kind:"submitted"}}catch(Ot){ge={kind:"failed",error:Ot},Le.push(`App '${g}': saved, but publishing failed (${Ot.message}). The app remains unpublished; re-push to retry.`)}if(ge.kind==="submitted"){ht=null;try{let Ot=await e.get(`/appmodules(${g})?$select=appmoduleid`);Ot.status>=200&&Ot.status<300&&(ht=(0,pe.readEtag)(Ot)),Ro=(m=await Ag(e,b,O,$))!==null&&m!==void 0?m:Ro}catch{}}}return{id:g,etag:Ro,siblingEtags:{[g]:ht},publish:ge,...Le.length>0?{warnings:Le}:{}}},async delete(e,t){let r=(0,Ee.normalizeGuid)(t,"id");await KN(e,r,await WN(e,r))}}});var Ig=v(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.deleteAppCascade=hs.collectGenPageIds=void 0;var B8=Fd(),q8=Q(),Og=ue(),V8=rs();function JN(e){let t=[],r=s=>l=>t.push(`${s}: ${l}`),i=new V8.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml").documentElement;if(!i||t.length>0)throw new q8.InvalidArgumentError(`The app sitemap xml could not be parsed cleanly, so its generative-page children cannot be determined${t.length>0?` (${t[0]})`:""}`);let o=[],a=s=>{if(s.nodeName==="SubArea"){let u=s.getAttribute("GenPageId");u&&o.push((0,Og.normalizeGuid)(u,"GenPageId"))}let l=s.childNodes;for(let u=0;u<l.length;u+=1){let c=l[u];c.nodeType===1&&a(c)}};return a(i),o}hs.collectGenPageIds=JN;async function G8(e,t,r){let n=(0,Og.normalizeGuid)(t,"appModuleId");(0,Og.normalizeGuid)(r,"appModuleIdUnique");let i=[],o=[],a=[];await(0,B8.deleteAppResolvingOnce)(e,n,l=>{l!==void 0&&a.push(...JN(l))}),i.push({type:"app",id:n});let s=[...new Set(a)].map(l=>({type:"genPage",id:l}));return{success:o.length===0,deleted:i,failures:o,retained:s}}hs.deleteAppCascade=G8});var YN={};jr(YN,{Guid:()=>U});var U,ct=k(()=>{"use strict";U=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 q,zt=k(()=>{"use strict";et();q=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(!P.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 P.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 QN={};jr(QN,{ScriptUtilities:()=>P});var P,et=k(()=>{"use strict";ct();zt();P=class e{static IsNullOrUndefined(t){return t==null||t===void 0}static IsMacMachine(){return navigator.platform.indexOf("Mac")!==-1}static IsNullOrEmptyGuid(t){return q.IsNullOrEmpty(t.ToString())?!0:U.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:q.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 Md,Ud,ta,Bd,Pg,qd,Rg=k(()=>{"use strict";(function(e){e[e.FormElementNodeChange=0]="FormElementNodeChange",e[e.FormElementAttributeChange=1]="FormElementAttributeChange"})(Md||(Md={}));Ud=class{type;targetNode;constructor(t,r){this.type=t,this.targetNode=r}},ta=class extends Ud{key;oldValue;newValue;constructor(t,r,n,i){super(Md.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)}},Bd=class extends Ud{property;oldValue;newValue;constructor(t,r,n,i){super(Md.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)}},Pg=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()})}},qd=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 Pg(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 XN={};jr(XN,{ChartGridMode:()=>nn,ColumnLayoutWidths:()=>K8,ComponentCategory:()=>Gd,ComponentType:()=>Lg,ControlLayoutTypes:()=>Bg,DisplayConditionsInfo:()=>j8,ElementNames:()=>C,ElementProperties:()=>y,ElementType:()=>xg,EntityAttributeProperty:()=>$g,EventType:()=>iu,FormActivationState:()=>Ug,FormCanvasServiceScope:()=>aW,FormDesignerSideBarTab:()=>kg,FormPresentation:()=>Fg,FormState:()=>Vd,FormType:()=>dt,HeaderDensityType:()=>po,LookUpTable:()=>Yn,MORE_TAB_PREFIX:()=>Y8,NavBarChildElementType:()=>Mg,PREVIEW_ID_HEADER_FLYOUT:()=>eW,PREVIEW_ID_HEADER_OVERFLOW_BUTTON:()=>rW,PREVIEW_ID_NAVIGATION_AREA:()=>X8,PREVIEW_ID_QUICKCREATE_ROOT:()=>iW,PREVIEW_ID_TAB:()=>nW,PREVIEW_ID_TAB_LIST:()=>tW,PREVIEW_ID_TAB_PANEL:()=>Z8,PropertyModelKeys:()=>Gg,PropertyModelSectionKeys:()=>J8,RELATED_TAB_ID:()=>Wg,RELATED_TAB_PREFIX:()=>Q8,SectionDefaultProperties:()=>H8,SectionLayoutTypes:()=>Ge,TabContentType:()=>qg,TabDefaultProperties:()=>mo,TabLayoutTypes:()=>Ve,TelemetryPropertyNames:()=>oW,UnboundControlPropertyKeys:()=>Vg,compositeAddressFields:()=>z8,compositeFieldNames:()=>Br,compositeFields:()=>W8});var dt,Lg,kg,C,y,xg,Br,W8,z8,$g,Yn,Vd,po,Fg,j8,Mg,Ug,Ve,H8,mo,Ge,Bg,qg,K8,Vg,Gg,J8,iu,nn,Wg,Y8,Q8,X8,Z8,eW,tW,rW,nW,iW,oW,Gd,aW,se=k(()=>{"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"})(dt||(dt={}));(function(e){e[e.Form=0]="Form",e[e.Dialog=1]="Dialog"})(Lg||(Lg={}));(function(e){e[e.Components=0]="Components",e[e.Properties=1]="Properties",e[e.Relationship=2]="Relationship",e[e.BusinessRules=3]="BusinessRules"})(kg||(kg={}));(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"})(C||(C={}));y={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"})(xg||(xg={}));Br={fullname:"fullname",yomifullname:"yomifullname",address1_composite:"address1_composite",address2_composite:"address2_composite",address3_composite:"address3_composite",billto:"billto_composite",shipto:"shipto_composite"},W8=[Br.fullname,Br.yomifullname,Br.address1_composite,Br.address2_composite,Br.address3_composite,Br.billto,Br.shipto],z8=[Br.address1_composite,Br.address2_composite,Br.address3_composite,Br.billto,Br.shipto];(function(e){e[e.IsValidForForm=0]="IsValidForForm",e[e.IsValidForCreate=1]="IsValidForCreate"})($g||($g={}));(function(e){e[e.DependencyFieldTable=0]="DependencyFieldTable",e[e.LockedFieldTable=1]="LockedFieldTable"})(Yn||(Yn={}));(function(e){e[e.Published=0]="Published",e[e.Draft=1]="Draft",e[e.New=2]="New",e[e.SaveAs=3]="SaveAs"})(Vd||(Vd={}));(function(e){e.Low="Low",e.HighReadOnlyValues="HighReadOnlyValues",e.HighWithControls="HighWithControls"})(po||(po={}));(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(Fg||(Fg={}));j8={TopOrderFormId:"topOrderFormId",NextDisplayOrder:"nextDisplayOrder"};(function(e){e[e.NavBarRelationShipItem=0]="NavBarRelationShipItem",e[e.NavBarItem=1]="NavBarItem"})(Mg||(Mg={}));(function(e){e[e.InActive=0]="InActive",e[e.Active=1]="Active"})(Ug||(Ug={}));(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"})(Ve||(Ve={}));H8={ShowLabel:"false",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_"},mo={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"})(Ge||(Ge={}));(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"})(Bg||(Bg={}));(function(e){e.cardSections="cardSections",e.singleComponent="singleComponent",e.default="default",e.expandAvailableSpace="expandAvailableSpace"})(qg||(qg={}));K8={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"})(Vg||(Vg={}));(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"})(Gg||(Gg={}));J8={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"})(iu||(iu={}));(function(e){e.All="All",e.Chart="Chart",e.Grid="Grid"})(nn||(nn={}));Wg="tab_related3b554255-7717-4d17-bb7f-9936fb1e75ca",Y8="more_tab_",Q8="related_tab_",X8="preview_id_navigation_area",Z8="tab-section",eW="headerFieldsFlyout",tW="tablist",rW="header_overflowButton",nW="tab",iW="quickCreateRoot",oW={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"})(Gd||(Gd={}));aW="CellCanvasServiceScope"});var ZN={};jr(ZN,{Attribute:()=>Wd,FormElementNode:()=>te});var Wd,te,St=k(()=>{"use strict";et();zt();Rg();se();ct();Wd=class{key;value;constructor(t,r){this.key=t,this.value=r}},te=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-${U.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(C.form);r&&r.raiseMetadataChange(t)}trackPropertyAddition(t,r){this.trackPropertyCollectionChange(()=>{this.properties.push(new Wd(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 ta(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 ta(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 ta(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 Bd(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 ta(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){P.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(P.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:q.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=P.IsNullOrUndefined(r)?this.childrenNodes.length:r,this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(t,r)})}deleteGrandChildren(t,r,n){this.getChildren(t)[0].deleteChildren(r,n)}addGrandChild(t,r){let n=this.getChildren(t),i=null;n.length===0?(i=new e(t,this),this.addChild(i)):i=n[0],i.addChild(r)}addGrandChildAtIndex(t,r,n){let i=this.getChildren(t),o=null;i.length===0?(o=new e(t,this),this.addChild(o)):o=i[0],o.insertChildAtIndex(r,n)}GetPropertyByParameter(t){return this.getProperty(t)}getSemanticParent(){switch(this.getNodeName()){case C.formCell:let t=this.getAncestor(C.formSection);return t||(t=this.getAncestor(C.formHeader),t)||(t=this.getAncestor(C.formFooter),t)?t:null;case C.formSection:return this.getAncestor(C.formTab);case C.formTab:return this.getAncestor(C.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(C.form);return t?t.changeTracker():null}}});var e_={};jr(e_,{ControlClassId:()=>N,ControlNamePrefixes:()=>zd,getControlDisplayNames:()=>sW});function sW(e){return{[N.AccessPrivilegeControl]:e("controls.controlNames.accessPrivilege"),[N.AccessTeamTablePickerControl]:e("controls.controlNames.accessTeamTablePicker"),[N.ACIControl]:e("controls.controlNames.aci"),[N.ActivitiesContainerControl]:e("controls.controlNames.activitiesContainer"),[N.ActivitiesWallControl]:e("controls.controlNames.activitiesWall"),[N.AppliedFiltersControl]:e("controls.controlNames.appliedFilters"),[N.ArticleContentControl]:e("controls.controlNames.articleContent"),[N.BooleanControl]:e("controls.controlNames.twoOption"),[N.ButtonControl]:e("controls.controlNames.button"),[N.CheckboxControl]:e("controls.controlNames.checkbox"),[N.CompositionLinkControl]:e("controls.controlNames.compositionLink"),[N.ConnectionControl]:e("controls.controlNames.connection"),[N.ConnectionRoleObjectTypeListControl]:e("controls.controlNames.connectionRoleObjectTypeList"),[N.CoverageChoiceControl]:e("controls.controlNames.coverageChoice"),[N.DashboardControl]:e("controls.controlNames.dashboard"),[N.DynamicPropertyListControl]:e("controls.controlNames.dynamicPropertyList"),[N.EditFilterControl]:e("controls.controlNames.editFilter"),[N.ErrorStatusControl]:e("controls.controlNames.errorStatus"),[N.GlobalFilterControl]:e("controls.controlNames.globalFilter"),[N.HiddenInputControl]:e("controls.controlNames.hiddenInput"),[N.KBViewerControl]:e("controls.controlNames.kbViewer"),[N.LabelControl]:e("controls.controlNames.label"),[N.MailMergeLanguagePickerControl]:e("controls.controlNames.mailMergeLanguagePicker"),[N.MapLinkControl]:e("controls.controlNames.mapLink"),[N.OrgInsightsControl]:e("controls.controlNames.orgInsights"),[N.ChoiceLookupControl]:e("controls.controlNames.choiceLookup"),[N.PowerBIControl]:e("controls.controlNames.powerBI"),[N.ProcessControl]:e("controls.controlNames.process"),[N.RelatedInformationControl]:e("controls.controlNames.relatedInformation"),[N.RelationshipRoleChoiceControl]:e("controls.controlNames.relationshipRoleChoice"),[N.ReportControl]:e("controls.controlNames.report"),[N.StreamsControl]:e("controls.controlNames.streams"),[N.WebResourceSilverlightControl]:e("controls.controlNames.webResourceSilverlight"),[N.CurrencyControl]:e("controls.controlNames.currency"),[N.DateTimeControl]:e("controls.controlNames.dateAndTime"),[N.DecimalControl]:e("controls.controlNames.decimal"),[N.DurationControl]:e("controls.controlNames.duration"),[N.EmailAddressControl]:e("controls.controlNames.email"),[N.FileControl]:e("controls.controlNames.file"),[N.FloatingNumberControl]:e("controls.controlNames.floatingNumber"),[N.IframeControl]:e("controls.controlNames.iframe"),[N.ImageControl]:e("controls.controlNames.image"),[N.LookupControl]:e("controls.controlNames.lookup"),[N.MapsControl]:e("controls.controlNames.maps"),[N.PhoneNumberControl]:e("controls.controlNames.phoneNumber"),[N.ChoiceControl]:e("controls.controlNames.choice"),[N.QuickViewControl]:e("controls.controlNames.quickView"),[N.QuickFormControl]:e("controls.controlNames.quickForm"),[N.CustomControl]:e("controls.controlNames.customControl"),[N.SearchWidgetControl]:e("controls.controlNames.searchWidget"),[N.SocialInsightsControl]:e("controls.controlNames.socialInsights"),[N.SubgridControl]:e("controls.controlNames.subgrid"),[N.TextAreaControl]:e("controls.controlNames.textArea"),[N.TextboxControl]:e("controls.controlNames.textBox"),[N.TickerControl]:e("controls.controlNames.ticker"),[N.UrlControl]:e("controls.controlNames.url"),[N.WebResourceHTMLControl]:e("controls.controlNames.webResourceHTML"),[N.WebResourceImageControl]:e("controls.controlNames.webResourceImage"),[N.IntegerControl]:e("controls.controlNames.integer"),[N.TimerControl]:e("controls.controlNames.timer"),[N.TimelineControl]:e("controls.controlNames.timeline"),[N.EmailBodyControl]:e("controls.controlNames.emailBody"),[N.PartyListControl]:e("controls.controlNames.partyList"),[N.TimezoneControl]:e("controls.controlNames.timezone"),[N.LanguageControl]:e("controls.controlNames.language"),[N.ChoiceStatusControl]:e("controls.controlNames.choiceStatus"),[N.ChoicesControl]:e("controls.controlNames.choices"),[N.RegardingControl]:e("controls.controlNames.regarding"),[N.EmailEngagementActionsControl]:e("controls.controlNames.emailEngagementActions"),[N.EmailRecipientActivityControl]:e("controls.controlNames.emailRecipientActivity"),[N.ReferencePanelSearchWidgetControl]:e("controls.controlNames.referencePanelSearchWidget"),[N.ReferencePanelQuickViewControl]:e("controls.controlNames.referencePanelQuickView"),[N.ReferencePanelSubgridControl]:e("controls.controlNames.referencePanelSubgrid"),[N.KBEditorControl]:e("controls.controlNames.KBEditor"),[N.LinkControl]:e("controls.controlNames.link")}}var N,zd,ra=k(()=>{"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"})(N||(N={}));zd={[N.WebResourceHTMLControl]:"WebResource",[N.WebResourceImageControl]:"WebResource",[N.IframeControl]:"IFRAME",[N.SearchWidgetControl]:"Search widget",[N.SubgridControl]:"Subgrid",[N.TimelineControl]:"Timeline",[N.QuickViewControl]:"QuickviewControl"}});var na=v((tle,r_)=>{var ou=new Proxy(function(){return ou},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:ou},apply:function(){return ou},construct:function(){return{}}}),t_=function(){return ou};Object.setPrototypeOf(t_,ou);r_.exports=t_});var ir,Oi,n_,i_,gs=k(()=>{"use strict";ir="cds-designer-models",Oi="FormCustomControl",n_="FormCell",i_="Form"});var ia,zg=k(()=>{"use strict";Bl();se();ia=class e{static lockedFieldCount=new er;static dependencyFieldCount=new er;static getNecessaryLookUpTable(t){switch(t){case Yn.DependencyFieldTable:return e.dependencyFieldCount;case Yn.LockedFieldTable:return e.lockedFieldCount}}static initCanvasLockedFieldLookUp(t){switch(t){case Yn.DependencyFieldTable:e.dependencyFieldCount=new er;case Yn.LockedFieldTable:e.lockedFieldCount=new er}}}});var jd,o_=k(()=>{"use strict";ct();et();se();St();jd=class extends te{constructor(t){super(C.controlDescription,t)}get forControl(){let t=this.getProperty(y.ForControl);return P.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t))}set forControl(t){this.setProperty(y.ForControl,`{${t.ToString()}}`)}get customControls(){return this.getChildren(C.customControl)}set customControls(t){this.deleteAllChildren();for(let r of t)this.addChild(r)}get DefaultControlClassId(){for(let t of this.customControls)if(!P.IsNullOrUndefined(t.id))return t.id;return null}get DefaultCustomControl(){for(let t of this.customControls)if(!P.IsNullOrUndefined(t.id))return t;return null}get DefaultCustomControls(){let t=[];for(let r of this.customControls)P.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}}});function Pi(){return Qn||(Qn=window._makerConfig,Qn&&window?.location?.search?.indexOf("useProductionConfig")>-1&&(Qn={...Qn,region:"prod",graphQLEndpoint:"https://graph.make.powerapps.com/"}),Qn?.region==="prod"&&(Qn={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/"}}},...Qn}),Qn||{aadClientId:"a8f7a65c-f5ba-4859-b2d6-df772c264e9d",location:"cus",region:"test",publicPath:"/",graphQLEndpoint:"https://graph.make.test.powerapps.com/"})}var Qn,Hd=k(()=>{"use strict";});function a_(e,t,r){if(!e)return Kd.has(e)||(window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoIsEmpty"}),Kd.add("")),!1;if(e){if(e=e.toLowerCase(),Kd.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}}),Kd.add(e),!1}return!0}function lW(e){return a_(e,jg,"Location dictionary")?jg[e.toLowerCase()]:"us"}function uW(){let e=Pi().location.toLowerCase();return a_(e,jg,"Current location dictionary")?e:"us"}var Kd,jg,mle,s_=k(()=>{"use strict";Hd();Kd=new Set,jg={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"};mle=lW(uW())});var Y,gle,l_=k(()=>{"use strict";Y={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"},gle={[Y.USWest]:{geoName:"us",regionShortName:"wus"},[Y.USCentral]:{geoName:"us",regionShortName:"cus"},[Y.USEast]:{geoName:"us",regionShortName:"eus"},[Y.USEast2]:{geoName:"us",regionShortName:"eus2"},[Y.USWestCentral]:{geoName:"us",regionShortName:"wcus"},[Y.USWest2]:{geoName:"us",regionShortName:"wus2"},[Y.USSouthCentral]:{geoName:"br",regionShortName:"scus"},[Y.BrazilSouth]:{geoName:"br",regionShortName:"sbr"},[Y.UKSouth]:{geoName:"uk",regionShortName:"suk"},[Y.UKWest]:{geoName:"uk",regionShortName:"wuk"},[Y.JapanEast]:{geoName:"jp",regionShortName:"ejp"},[Y.JapanWest]:{geoName:"jp",regionShortName:"wjp"},[Y.IndiaCentral]:{geoName:"in",regionShortName:"cin"},[Y.IndiaSouth]:{geoName:"in",regionShortName:"sin"},[Y.ItalyNorth]:{geoName:"it",regionShortName:"nit"},[Y.GermanyWestCentral]:{geoName:"de",regionShortName:"wcde"},[Y.GermanyNorth]:{geoName:"de",regionShortName:"nde"},[Y.EuropeNorth]:{geoName:"eu",regionShortName:"neu"},[Y.EuropeWest]:{geoName:"eu",regionShortName:"weu"},[Y.AustraliaEast]:{geoName:"au",regionShortName:"eau"},[Y.AustraliaSouthEast]:{geoName:"au",regionShortName:"seau"},[Y.AsiaSouthEast]:{geoName:"as",regionShortName:"seas"},[Y.AsiaEast]:{geoName:"as",regionShortName:"eas"},[Y.CanadaCentral]:{geoName:"ca",regionShortName:"cca"},[Y.CanadaEast]:{geoName:"ca",regionShortName:"eca"},[Y.SouthAfricaNorth]:{geoName:"za",regionShortName:"nza"},[Y.SouthAfricaWest]:{geoName:"za",regionShortName:"wza"},[Y.FranceCentral]:{geoName:"fr",regionShortName:"cfr"},[Y.FranceSouth]:{geoName:"fr",regionShortName:"sfr"},[Y.UAENorth]:{geoName:"ae",regionShortName:"nae"},[Y.UAECentral]:{geoName:"ae",regionShortName:"cae"},[Y.SwedenCentral]:{geoName:"se",regionShortName:"cse"},[Y.SwitzerlandNorth]:{geoName:"ch",regionShortName:"nch"},[Y.SwitzerlandWest]:{geoName:"ch",regionShortName:"wch"},[Y.NorwayEast]:{geoName:"no",regionShortName:"eno"},[Y.NorwayWest]:{geoName:"no",regionShortName:"wno"},[Y.KoreaCentral]:{geoName:"kr",regionShortName:"ckr"},[Y.KoreaSouth]:{geoName:"kr",regionShortName:"skr"},[Y.SingaporeSouthEast]:{geoName:"sg",regionShortName:"seas"},[Y.PolandCentral]:{geoName:"pl",regionShortName:"cpl"},[Y.QatarCentral]:{geoName:"qa",regionShortName:"cqa"},[Y.NewZealandNorth]:{geoName:"nz",regionShortName:"nnz"},[Y.GovernmentUSTexas]:{geoName:"us",regionShortName:"ugtx"},[Y.GovernmentUSVirginia]:{geoName:"us",regionShortName:"ugva"},[Y.GovernmentUSDodCentral]:{regionShortName:"udc"},[Y.GovernmentUSDodEast]:{regionShortName:"ude"},[Y.ChinaEast]:{regionShortName:"cne"},[Y.ChinaEast2]:{regionShortName:"cne2"},[Y.ChinaEast3]:{regionShortName:"cne3"},[Y.ChinaNorth]:{regionShortName:"cnn"},[Y.ChinaNorth2]:{regionShortName:"cnn2"},[Y.ChinaNorth3]:{regionShortName:"cnn3"},[Y.UssecEast]:{geoName:"us",regionShortName:"erx"},[Y.UssecWest]:{geoName:"us",regionShortName:"wrx"},[Y.UsnatEast]:{geoName:"us",regionShortName:"eex"},[Y.UsnatWest]:{geoName:"us",regionShortName:"wex"}}});var u_=k(()=>{"use strict";Hd();});var au=k(()=>{"use strict";Hd();s_();l_();u_();});function su(e,t){return c_?c_.isOverridden(e,t):{overridden:!1}}var c_,lu=k(()=>{"use strict";});var Hg=k(()=>{"use strict";au();lu();});function cW(e,t){let{region:r}=Pi();return()=>{let n=e.settings[t];if(n.allowOverrides){let s=su(e.packageName,t);if(s.overridden)return typeof s.value=="string"?dW(s.value):s.value}let o=n.values,a=process.env.SETTINGS_FALLBACK_REGION?.[r];return o[r]!==void 0?o[r]:a&&o[a]!==void 0?o[a]:o.default}}function dW(e){return isNaN(Number(e))?e==="true"?!0:e==="false"?!1:e:Number(e)}function fW(e){let t=e.packageName;if(Jd.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=>Jg(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=>!Qd(i))){let i=`error parsing settings config for package ${t}, setting ${r} has invalid region`;throw console.error(i),new Error(i)}})}function uu(e){fW(e);let t={};return Object.keys(e.settings).forEach(r=>{t[r]={enumerable:!0,get:cW(e,r)}}),Jd.set(e.packageName,e),Object.defineProperties({},t)}function Kg(e,t){return Jd.has(e)?!!Jd.get(e).settings[t]:!1}var Jd,Yd=k(()=>{"use strict";au();lu();Yg();cu();Jd=new Map});function d_(e,t){let{region:r}=Pi();return()=>{let n=su(e.packageName,t);if(n.overridden)return n.value.toString()==="true";let i=e.features[t].enabledFor,o=process.env.SETTINGS_FALLBACK_REGION?.[r];return i[r]!==void 0?!!i[r]:o&&i[o]!==void 0?!!i[o]:!1}}function pW(e){let t=e.packageName;if(Xd.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=>Kg(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=>!Qd(i))){let i=`error parsing feature gates config for package ${t}, feature ${r} has invalid region`;throw console.error(i),new Error(i)}})}function Qg(e){pW(e);let t={};Object.keys(e.features).forEach(i=>{t[i]={enumerable:!0,configurable:!0,get:d_(e,i)}});let r={},n=new Set;return t.dangerouslySet={enumerable:!1,value:(i,o)=>{n.add(i),Object.defineProperty(r,i,{enumerable:!0,configurable:!0,value:o})}},t.dangerouslyReset={enumerable:!1,value:()=>{let i={};n.forEach(o=>{i[o.toString()]={enumerable:!0,configurable:!0,get:d_(e,o.toString())}}),Object.defineProperties(r,i),n.clear()}},Xd.set(e.packageName,e),Object.defineProperties(r,t)}function Jg(e,t){return Xd.has(e)?!!Xd.get(e).features[t]:!1}var Xd,Yg=k(()=>{"use strict";au();cu();lu();Yd();Xd=new Map});var p_=v((qle,f_)=>{"use strict";f_.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 g_=v(Xg=>{"use strict";var mW=Object.prototype.hasOwnProperty,hW;function m_(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch{return null}}function h_(e){try{return encodeURIComponent(e)}catch{return null}}function gW(e){for(var t=/([^=?#&]+)=?([^&]*)/g,r={},n;n=t.exec(e);){var i=m_(n[1]),o=m_(n[2]);i===null||o===null||i in r||(r[i]=o)}return r}function yW(e,t){t=t||"";var r=[],n,i;typeof t!="string"&&(t="?");for(i in e)if(mW.call(e,i)){if(n=e[i],!n&&(n===null||n===hW||isNaN(n))&&(n=""),i=h_(i),n=h_(n),i===null||n===null)continue;r.push(i+"="+n)}return r.length?t+r.join("&"):""}Xg.stringify=yW;Xg.parse=gW});var t0=v((Gle,E_)=>{"use strict";var b_=p_(),Zd=g_(),v_=/[\n\r\t]/g,bW=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,vW=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,wW=/^[a-zA-Z]:/,CW=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;function e0(e){return(e||"").toString().replace(CW,"")}var Zg=[["#","hash"],["?","query"],function(t,r){return Xn(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]],y_={hash:1,query:1};function w_(e){var t;typeof window<"u"?t=window:typeof global<"u"?t=global:typeof self<"u"?t=self:t={};var r=t.location||{};e=e||r;var n={},i=typeof e,o;if(e.protocol==="blob:")n=new Zn(unescape(e.pathname),{});else if(i==="string"){n=new Zn(e,{});for(o in y_)delete n[o]}else if(i==="object"){for(o in e)o in y_||(n[o]=e[o]);n.slashes===void 0&&(n.slashes=bW.test(e.href))}return n}function Xn(e){return e==="file:"||e==="ftp:"||e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function C_(e,t){e=e0(e),e=e.replace(v_,""),t=t||{};var r=vW.exec(e),n=r[1]?r[1].toLowerCase():"",i=!!r[2],o=!!r[3],a=0,s;return i?o?(s=r[2]+r[3]+r[4],a=r[2].length+r[3].length):(s=r[2]+r[4],a=r[2].length):o?(s=r[3]+r[4],a=r[3].length):s=r[4],n==="file:"?a>=2&&(s=s.slice(2)):Xn(n)?s=r[4]:n?i&&(s=s.slice(2)):a>=2&&Xn(t.protocol)&&(s=r[4]),{protocol:n,slashes:i||Xn(n),slashesCount:a,rest:s}}function EW(e,t){if(e==="")return t;for(var r=(t||"/").split("/").slice(0,-1).concat(e.split("/")),n=r.length,i=r[n-1],o=!1,a=0;n--;)r[n]==="."?r.splice(n,1):r[n]===".."?(r.splice(n,1),a++):a&&(n===0&&(o=!0),r.splice(n,1),a--);return o&&r.unshift(""),(i==="."||i==="..")&&r.push(""),r.join("/")}function Zn(e,t,r){if(e=e0(e),e=e.replace(v_,""),!(this instanceof Zn))return new Zn(e,t,r);var n,i,o,a,s,l,u=Zg.slice(),c=typeof t,d=this,f=0;for(c!=="object"&&c!=="string"&&(r=t,t=null),r&&typeof r!="function"&&(r=Zd.parse),t=w_(t),i=C_(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||wW.test(e))||!i.slashes&&(i.protocol||i.slashesCount<2||!Xn(d.protocol)))&&(u[3]=[/(.*)/,"pathname"]);f<u.length;f++){if(a=u[f],typeof a=="function"){e=a(e,d);continue}o=a[0],l=a[1],o!==o?d[l]=e:typeof o=="string"?(s=o==="@"?e.lastIndexOf(o):e.indexOf(o),~s&&(typeof a[2]=="number"?(d[l]=e.slice(0,s),e=e.slice(s+a[2])):(d[l]=e.slice(s),e=e.slice(0,s)))):(s=o.exec(e))&&(d[l]=s[1],e=e.slice(0,s.index)),d[l]=d[l]||n&&a[3]&&t[l]||"",a[4]&&(d[l]=d[l].toLowerCase())}r&&(d.query=r(d.query)),n&&t.slashes&&d.pathname.charAt(0)!=="/"&&(d.pathname!==""||t.pathname!=="")&&(d.pathname=EW(d.pathname,t.pathname)),d.pathname.charAt(0)!=="/"&&Xn(d.protocol)&&(d.pathname="/"+d.pathname),b_(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:"&&Xn(d.protocol)&&d.host?d.protocol+"//"+d.host:"null",d.href=d.toString()}function AW(e,t,r){var n=this;switch(e){case"query":typeof t=="string"&&t.length&&(t=(r||Zd.parse)(t)),n[e]=t;break;case"port":n[e]=t,b_(t,n.protocol)?t&&(n.host=n.hostname+":"+t):(n.host=n.hostname,n[e]="");break;case"hostname":n[e]=t,n.port&&(t+=":"+n.port),n.host=t;break;case"host":n[e]=t,/:\d+$/.test(t)?(t=t.split(":"),n.port=t.pop(),n.hostname=t.join(":")):(n.hostname=t,n.port="");break;case"protocol":n.protocol=t.toLowerCase(),n.slashes=!r;break;case"pathname":case"hash":if(t){var i=e==="pathname"?"/":"#";n[e]=t.charAt(0)!==i?i+t:t}else n[e]=t;break;case"username":case"password":n[e]=encodeURIComponent(t);break;case"auth":var o=t.indexOf(":");~o?(n.username=t.slice(0,o),n.username=encodeURIComponent(decodeURIComponent(n.username)),n.password=t.slice(o+1),n.password=encodeURIComponent(decodeURIComponent(n.password))):n.username=encodeURIComponent(decodeURIComponent(t))}for(var a=0;a<Zg.length;a++){var s=Zg[a];s[4]&&(n[s[1]]=n[s[1]].toLowerCase())}return n.auth=n.password?n.username+":"+n.password:n.username,n.origin=n.protocol!=="file:"&&Xn(n.protocol)&&n.host?n.protocol+"//"+n.host:"null",n.href=n.toString(),n}function SW(e){(!e||typeof e!="function")&&(e=Zd.stringify);var t,r=this,n=r.host,i=r.protocol;i&&i.charAt(i.length-1)!==":"&&(i+=":");var o=i+(r.protocol&&r.slashes||Xn(r.protocol)?"//":"");return r.username?(o+=r.username,r.password&&(o+=":"+r.password),o+="@"):r.password?(o+=":"+r.password,o+="@"):r.protocol!=="file:"&&Xn(r.protocol)&&!n&&r.pathname!=="/"&&(o+="@"),n[n.length-1]===":"&&(n+=":"),o+=n+r.pathname,t=typeof r.query=="object"?e(r.query):r.query,t&&(o+=t.charAt(0)!=="?"?"?"+t:t),r.hash&&(o+=r.hash),o}Zn.prototype={set:AW,toString:SW};Zn.extractProtocol=C_;Zn.location=w_;Zn.trimLeft=e0;Zn.qs=Zd;E_.exports=Zn});var NW,A_=k(()=>{"use strict";NW=we(t0());});function r0(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 ef=k(()=>{"use strict";});var n0,i0,o0=k(()=>{"use strict";ef();n0=class{features=new Map;register(t,r){let n=r0(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()}},i0=new n0});var a0=k(()=>{"use strict";});function Qd(e){return _W.has(e)}var _W,cu=k(()=>{"use strict";Hg();Yg();Yd();lu();Hg();A_();o0();ef();a0();_W=new Set(["tie","test","prod","preview","preprod","gov","high","dod","mooncake","ex","rx"])});var TW,S_=k(()=>{"use strict";cu();TW=uu({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 D_,l0,ys,oa,s0,tf,bs,Ri,Ue,N_,__,T_,An=k(()=>{"use strict";D_={ThreeEqColumn_FirstColumn:34,ThreeEqColumn_SecondColumn:33,ThreeEqColumn_ThirdColumn:33,FiveEqColumn:20},l0={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"})(ys||(ys={}));(function(e){e.Left="Left",e.Right="Right",e.Center="Center"})(oa||(oa={}));(function(e){e[e.Mobile=0]="Mobile",e[e.Tablet=1]="Tablet",e[e.Web=2]="Web"})(s0||(s0={}));tf=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"})(bs||(bs={}));Ri=class{static StartTag="<"},Ue={ShowLabel:"true",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_",labelAlignment:oa.Left,labelPosition:bs.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"})(N_||(N_={}));(function(e){e.TabWithLockedFieldRemoval="TabWithLockedFieldRemoval",e.SectionWithLockedFieldRemoval="SectionWithLockedFieldRemoval",e.LockedSectionRemoval="LockedSectionRemoval",e.LockedFieldRemoval="LockedFieldRemoval",e.RequiredFieldRemoval="RequiredFieldRemoval",e.LastRemainingTab="LastRemainingTab",e.UnknownRemoval="UnknownRemoval"})(__||(__={}));(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"})(T_||(T_={}))});var u0,I_=k(()=>{"use strict";(function(e){e.DefaultValue="defaultValue",e.Loaded="loaded"})(u0||(u0={}))});var R_,DW,O_,Mue,Uue,du,P_,Bue,que,L_=k(()=>{"use strict";R_=we(na());et();gs();S_();is();An();jo();se();DW=we(Ji());I_();(function(e){e.Model="Model",e.Canvas="Canvas",e.CustomPages="CustomPages"})(O_||(O_={}));Mue={Read:ro.Read,Edit:ro.Edit,Both:ro.Both,Container:ro.Container},Uue={input:zo.Input,bound:zo.Bound,output:zo.Output};(function(e){e[e.dataset=0]="dataset",e[e.property=1]="property",e[e.groups=2]="groups",e[e.group=3]="group"})(du||(du={}));(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"})(P_||(P_={}));Bue=new Set([F.Currency,F.Decimal,F.FP,F.Multiple,F.SingleLineEmail,F.SingleLinePhone,F.SingleLineText,F.SingleLineTextArea,F.SingleLineURL,F.SingleLineTickerSymbol,F.WholeNone,F.WholeDuration,F.WholeLanguage,F.WholeTimeZone,F.Enum,F.LookupSimple,F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.TwoOptions,F.Boolean,F.PowerBIReport,F.DateAndTimeDateAndTime,F.DateAndTimeDateOnly,F.OptionSet,F.MultiSelectOptionSet,F.CardForm]),que={numbers:[F.WholeNone,F.FP,F.Decimal,F.Currency],text:[F.SingleLineText,F.SingleLineTextArea,F.Multiple],lookup:[F.LookupSimple,F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding],dates:[F.DateAndTimeDateOnly,F.DateAndTimeDateAndTime],allFields:[F.TwoOptions,F.DateAndTimeDateOnly,F.DateAndTimeDateAndTime,F.FP,F.Decimal,F.WholeNone,F.WholeDuration,F.WholeTimeZone,F.WholeLanguage,F.LookupSimple,F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.Multiple,F.OptionSet,F.SingleLineText,F.SingleLineTextArea,F.SingleLineEmail,F.SingleLineURL,F.SingleLineTickerSymbol,F.SingleLinePhone]}});var Sn,rf,k_=k(()=>{"use strict";Sn=we(na());ct();et();zt();gs();jo();L_();is();se();St();An();rf=class extends te{constructor(t){super(C.customControl,t)}customControlId;get id(){let t=this.getProperty(y.id);return P.IsNullOrUndefined(t)?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new U(t.substr(1,t.length-2)):new U(t)}getParameters(){let t=new Map,r=this.getAllChildren();if(r&&r.length!==0&&r[0]){let n=r[0].getAllChildren();if(n!=null){for(let i of n)if(i&&i.getAllChildren().length>0){let o=i.getNodeName();t.get(o)?t.get(o).push(i):t.set(o,[i])}}}return t}getFormComponentValueByParameterName(t){let r=this.getParameters()?.get(qt.value);if(r?.length>0){let n=r[0],i=n?.getAllChildren()?.length>0?n.getAllChildren().find(a=>a.getNodeName()===t):null,o=i?.getAllChildren()?.length>0?i.getAllChildren()[0].getNodeName():"";return this.normalizePropertyValue(o)}}getParameterValue(t){let r=this.getParameterNodeChild(t);return r&&this.normalizePropertyValue(r.getNodeName())}getParameterNodeChild(t){let r=this.getParameters().get(t);return r?.length>0&&r[0].getAllChildren()?.length>0?r[0].getAllChildren()[0]:null}getDatasetName(t){return t.getAllProperties().find(r=>r.key===qt.name)?.value}getParameterChildrenValues(t,r,n){if(this.isDataSet(t)){let i=r.find(u=>u.key===qt.name)?.value,o={Name:i,Type:F.Grid,Columns:[]},l=this.getParameters().get(qt.dataset).find(u=>this.getDatasetName(u)===i).getAllChildren();for(let u of l){let c=u.getNodeName();if(u&&u.getAllChildren().length>0){let d=this.normalizePropertyValue(u.getAllChildren()[0].getNodeName());o[c]=d}}return o}}getParameterIsStatic(t){let r=!1,n=this.getParameters().get(t)[0],i=n&&n.getAllProperties();if(i){for(let o of i)if(o.key===y.static&&o.value==="true"){r=!0;break}}return r}get name(){return this.getProperty(y.Name)}get formFactor(){return this.getProperty(y.formFactor)}set formFactor(t){this.setProperty(y.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(Ri.StartTag)&&(t=t.substring(1)),t}async parametersToJSON(t){let r=[];if(!this.name)return r;try{let n=await t.formModelService.customControlDiscoveryService.getCustomControlMetadata(this.name);if(n)if(n.configurations){let i=n.configurations,o=this.getParameters();for(let[a,s]of o)if(this.isDataSet(a))for(let l of o.get(a)){let u=l.getAllProperties(),c=this.getDatasetName(l),d=i.get(c),f=await this.parameterJSON(a,u,d,t);r.push({Name:c,Value:f})}else if(this.isGroups(s))r.push({Name:a,Value:{Type:Dh.GroupDefinition,Value:this.normalizePropertyValue(this.getParameterNodeChild(s[0].NodeName).NodeName)}}),i.get(a).groupSet?.forEach(u=>{u.groupConfigurableProperties.forEach(async c=>{let d=c.name;c.propertyType===du.dataset?o.get(qt.dataset)?.some(p=>this.getDatasetName(p)===d)||r.push({Name:d,Value:{Name:d,Columns:[],Type:F.Grid}}):c.propertyType===du.property&&(o.has(d)||r.push({Name:d,Value:{Usage:c.usage}}))})});else{let l=s[0].getAllProperties(),u=i.get(a),c=await this.parameterJSON(a,l,u,t);if(c)r.push({Name:a,Value:c});else{(0,Sn.trackInfoTrace)(ir,{eventName:`${Oi}/parametersToJSON`,eventData:{message:`Configuration metadata for custom control parameter ${a} is not available for custom control : ${this.name}.`}}),r=[];break}}}else(0,Sn.trackErrorTrace)(ir,{eventName:`${Oi}/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,Sn.trackErrorTrace)(ir,{eventName:`${Oi}/parametersToJSON`,eventData:{message:"Custom Control Manifest not found"}},new Error(`No custom control manifest found for ${this.name}`))}catch(n){(0,Sn.trackErrorTrace)(ir,{eventName:`${Oi}/parametersToJSON`,eventData:{message:"parameters to json failed"}},n)}return r}async parameterJSON(t,r,n,i){if(this.isDataSet(t)){let o=n,a=r.find(s=>s.key===qt.name)?.value;if(o)return this.getParameterChildrenValues(t,r);{let s=new Error(`No dataset manifest info for ${a}`);(0,Sn.trackErrorTrace)(ir,{eventName:`${Oi}/parameterJSON`,eventData:{message:"Missing custom control manifest dataset info"}},s)}}else{let o=n,a=r&&r.find(l=>l.key===y.Type),s=o&&!o.ofTypeGroup.every(l=>!rd.includes(l));if(this.isLookupType(a?.value)||this.isLookupType(o?.ofType)||s)if(o){let l=o.usage,u=this.getParameterIsStatic(t),c=o.isPrimary;if(this.name===Si.FormComponent){let d=this.getFormComponentValueByParameterName(y.bindAttribute),f=await i.formModelService.loadLookupModel(d),p=f.lookupColumn,m=this.getLookupDataTypeFromAttributeMetadata(p);return{Name:t,Type:m,Usage:l,Static:u,Primary:c,EntityName:f.primaryTableName,Value:d,ViewId:this.getFormComponentValueByParameterName(Th.DefaultViewId),TargetEntityType:p.targets[0],FilterRelationshipName:this.getFormComponentValueByParameterName(y.FilterRelationshipName),AvailableViewIds:this.getFormComponentValueByParameterName(y.AvailableViewIds),DependentAttributeName:this.getFormComponentValueByParameterName(y.DependentAttributeName),DependentAttributeType:this.getFormComponentValueByParameterName(y.DependentAttributeType),AllowFilterOff:q.IsStrictTrue(this.getFormComponentValueByParameterName(y.AllowFilterOff)),DisableQuickFind:q.IsStrictTrue(this.getFormComponentValueByParameterName(y.DisableQuickFind)),EnableViewPicker:!q.IsStrictTrue(this.getFormComponentValueByParameterName(y.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,Sn.trackErrorTrace)(ir,{eventName:`${Oi}/parameterJSON`,eventData:{message:"Missing custom control manifest lookup property info"}},l)}if(o){let l=o.usage,u=this.getParameterIsStatic(t),c=this.getParameterValue(t),d=o.isPrimary;if(a){let p=a.value;return{Type:p,Static:u,Usage:l,Value:this.isNumberTypeProperty(o,p)&&Number(c)?Number(c):c,Primary:d}}if(o.ofType)return{Type:o.ofType,Static:u,Usage:l,Value:c,Primary:!0};if(o.ofTypeGroup)return{Static:u,Usage:l,Value:c,Primary:!0};let f=new Error(`No property type info for ${t}`);(0,Sn.trackErrorTrace)(ir,{eventName:`${Oi}/parameterJSON`,eventData:{message:"Missing property type info"}},f)}else{let l=new Error(`No property manifest info for ${t}`);(0,Sn.trackWarningTrace)(ir,{eventName:`${Oi}/parameterJSON`,eventData:{message:"Missing custom control manifest property info"}},l)}}return null}getLookupDataTypeFromAttributeMetadata(t){let{attributeType:r,format:n}=t;switch(r){case x.Customer:return F.LookupCustomer;case x.Owner:return F.LookupOwner;case x.PartyList:return F.LookupPartyList;default:return n===W.Regarding?F.LookupRegarding:F.LookupSimple}}isLookupType(t){return rd.includes(t)}isNumberTypeProperty(t,r){return nd.includes(r)||t.ofTypeGroup.some(n=>nd.includes(n))}isDataSet(t){return qt.dataset===t}isGroups(t){return!!t[0].getAllProperties().find(n=>n.key==="isGroup"&&n.value==="true")}}});var ee,c0=k(()=>{"use strict";ee=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_={};jr(x_,{CustomControlUniqueId:()=>aa,DeprecatedControlClassIds:()=>G,FieldControlTypes:()=>tt,mapFieldTypeToControl:()=>IW});function IW(e,t){switch(e){case x.TwoOptions:return N.BooleanControl;case x.Customer:case x.CustomerType:return N.LookupControl;case x.DateTime:return t===W.DateAndTime?N.DateTimeControl:N.DateTimeControl;case x.DecimalNumber:return N.DecimalControl;case x.FloatingPointNumber:return N.FloatingNumberControl;case x.WholeNumber:return t===W.Duration?N.DurationControl:t===W.Language?N.LanguageControl:t===W.TimeZone?N.TimezoneControl:N.IntegerControl;case x.CustomerType:case x.Lookup:case x.LookupType:return t===W.Regarding?N.RegardingControl:N.LookupControl;case x.MultipleLineofText:return t===W.Email?N.EmailBodyControl:N.TextAreaControl;case x.Currency:return N.CurrencyControl;case x.Owner:case x.OwnerType:return N.LookupControl;case x.PartyList:case x.PartyListType:return N.PartyListControl;case x.Status:case x.OptionSet:return N.ChoiceControl;case x.SingleLineofText:return t===W.Email?N.EmailAddressControl:t===W.Phone?N.PhoneNumberControl:t===W.Text?N.TextboxControl:t===W.TextArea?N.TextAreaControl:t===W.TickerSymbol?N.TickerControl:t===W.Url?N.UrlControl:t===W.PhoneticGuide?N.TextboxControl:N.TextboxControl;case x.MultiSelectOptionSet:return N.ChoicesControl;case x.Image:return N.ImageControl;case x.File:return N.FileControl;case x.State:return N.ChoiceControl;case x.Status:return N.ChoiceStatusControl;default:throw new Error(`Cannot get base control for ${e} field type`)}}var G,aa,tt,fu=k(()=>{"use strict";ct();Bl();et();zt();is();ra();c0();An();G=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"}};aa=class{static get RelationshipAssistant(){return"3ff9a528-dd50-4aca-8f10-2e5ed73513ad"}static get PredictiveLeadScoring(){return"6f503f2a-d033-4106-b62c-f8f2e5f01a57"}},tt=class e{static FieldControlIds=e.initializeFieldControls();static UnboundControlIds=e.initializeUnboundControls();static ControlsAllowedForReferencePanel=e.initializeReferencePanelControls();static ControlsAllowedForFooter=e.initializeFooterControls();static CustomControlIdMap=new er;static initializeFieldControls(){let t=new er,r=e.getControlName(x.SingleLineofText,W.Phone);t.add(r,new U(G.PhoneNumberControl));let n=e.getControlName(x.SingleLineofText,W.TextArea);t.add(n,new U(G.TextAreaControl));let i=e.getControlName(x.SingleLineofText,W.Text);t.add(i,new U(G.TextBoxControl));let o=e.getControlName(x.SingleLineofText,W.Email);t.add(o,new U(G.EmailAddressControl));let a=e.getControlName(x.SingleLineofText,W.Url);t.add(a,new U(G.UrlControl));let s=e.getControlName(x.SingleLineofText,W.TickerSymbol);t.add(s,new U(G.TickerControl));let l=e.getControlName(x.SingleLineofText,W.PhoneticGuide);t.add(l,new U(G.TextBoxControl));let u=e.getControlName(x.WholeNumber,W.Duration);t.add(u,new U(G.DurationControl));let c=e.getControlName(x.WholeNumber,W.Language);t.add(c,new U(G.LanguagePickerControl));let d=e.getControlName(x.WholeNumber,W.TimeZone);t.add(d,new U(G.TimeZonePicklistControl));let f=e.getControlName(x.WholeNumber,W.None);t.add(f,new U(G.IntegerControl));let p=e.getControlName(x.DateTime,W.DateOnly);t.add(p,new U(G.DateTimeControl));let m=e.getControlName(x.DateTime,W.DateAndTime);t.add(m,new U(G.DateTimeControl));let h=e.getControlName(x.LookupType,W.None);t.add(h,new U(G.LookupControl));let g=e.getControlName(x.CustomerType,W.None);t.add(g,new U(G.LookupControl));let b=e.getControlName(x.FloatingPointNumber,W.None);t.add(b,new U(G.FloatControl));let w=e.getControlName(x.DecimalNumber,W.None);t.add(w,new U(G.DecimalControl));let E=e.getControlName(x.Currency,W.None);t.add(E,new U(G.MoneyControl));let A=e.getControlName(x.MultipleLineofText,W.None);t.add(A,new U(G.TextAreaControl));let L=e.getControlName(x.MultipleLineofText,W.Text);t.add(L,new U(G.TextAreaControl));let R=e.getControlName(x.MultipleLineofText,W.TextArea);t.add(R,new U(G.TextAreaControl));let I=e.getControlName(x.MultipleLineofText,W.Email);t.add(I,new U(G.EmailBodyControl));let D=e.getControlName(x.OptionSet,W.None);t.add(D,new U(G.PicklistControl));let O=e.getControlName(x.TwoOptions,W.None);t.add(O,new U(G.RadioControl));let $=e.getControlName(x.Image,W.None);t.add($,new U(G.WebResourceImageControl));let K=e.getControlName(x.Image,W.None);t.add(K,new U(G.WebResourceHtmlControl));let Re=e.getControlName(x.TwoOptions,"Radio");t.add(Re,new U(G.RadioControl));let It=e.getControlName(x.TwoOptions,"CheckBox");t.add(It,new U(G.CheckBoxControl));let Le=e.getControlName(x.TwoOptions,"List");t.add(Le,new U(G.PicklistControl));let at=e.getControlName(x.State,W.None);t.add(at,new U(G.PicklistControl));let ge=e.getControlName(x.Status,W.None);t.add(ge,new U(G.PicklistStatusControl));let ht=e.getControlName(x.OwnerType,W.None);t.add(ht,new U(G.LookupControl));let Ro=e.getControlName(x.PartyListType,W.None);t.add(Ro,new U(G.PartyListControl));let Ot=e.getControlName(x.LookupType,W.Regarding);t.add(Ot,new U(G.RegardingControl));let di=e.getControlName(x.MultiSelectOptionSet,W.None);return t.add(di,new U(G.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(!P.IsNullOrEmptyGuid(t)){let r=e.getTypeAndFormatByControlOrUniqueId(t.guidString.toLowerCase());return r=P.IsNullOrUndefined(r)?e.getUnboundControlNameFromIdentifier(t):r.substring(0,r.indexOf("_")),r}return null}static isCustomControl(t){return P.IsNullOrUndefined(t.control)||P.IsNullOrUndefined(t.control.ClassId)||t.control.ClassId.guidString===G.CustomControl}static initializeUnboundControls(){let t=new er;return t.add(G.ACIControl,ee.ACIControl),t.add(G.IframeControl,ee.IframeControl),t.add(G.SearchWidgetControl,ee.SearchWidgetControl),t.add(G.MapsControl,ee.MapsControl),t.add(G.QuickFormCollectionControl,ee.QuickFormCollectionControl),t.add(G.GridControl,ee.SubGridControl),t.add(G.WebResourceImageControl,ee.WebResourceImageControl),t.add(G.WebResourceHtmlControl,ee.WebResourceHtmlControl),t.add(G.ReferencePanelSearchWidget,ee.SearchWidgetControl),t.add(G.ReferencePanelQuickFormCollectionControl,ee.QuickFormCollectionControl),t.add(G.ReferencePanelSubgridControl,ee.SubGridControl),t.add(G.TimerControl,ee.TimerControl),t.add(G.TimeLineControl,ee.NotesControl),t.add(G.TimeLineControlUC,ee.NotesControl),t.add(G.SocialInsightControl,ee.SocialInsightControl),t.add(aa.RelationshipAssistant,ee.CustomControl),t}static initializeReferencePanelControls(){let t=new er;return t.add(G.IframeControl,ee.IframeControl),t.add(G.ReferencePanelSearchWidget,ee.SearchWidgetControl),t.add(G.ReferencePanelQuickFormCollectionControl,ee.QuickFormCollectionControl),t.add(G.ReferencePanelSubgridControl,ee.SubGridControl),t.add(G.WebResourceHtmlControl,ee.WebResourceHtmlControl),t.add(G.WebResourceImageControl,ee.WebResourceHtmlControl),t}static initializeFooterControls(){let t=new ns;return t.add(ys.IFRAME,!0),t.add(ys.SPACER,!0),t.add(ys.WEB_RESOURCE_HTML,!0),t}static isUnboundFormControl(t){if(P.IsNullOrUndefined(t)||P.IsNullOrUndefined(t.control)||P.IsNullOrUndefined(t.control.ClassId))return!1;let r=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.containsKey(r.guidString)}static isReferencePanelSection(t){return!P.IsNullOrUndefined(t)&&!P.IsNullOrUndefined(t.Name)&&t.Name.indexOf(Ue.referencePanelNamePrefix)===0}static isUnboundFormControlByIdentifier(t){return P.IsNullOrUndefined(t)||P.IsNullOrUndefined(t.guidString)?!1:e.UnboundControlIds.containsKey(t.guidString)}static getUnboundFormControlName(t){let r=q.EmptyString;if(P.IsNullOrUndefined(t)||P.IsNullOrUndefined(t.control)||P.IsNullOrUndefined(t.control.ClassId))return r;let n=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.getValue(n.guidString).toString()}static getUnboundControlNameFromIdentifier(t){return P.IsNullOrUndefined(t)||P.IsNullOrUndefined(t.guidString)?q.EmptyString:e.UnboundControlIds.getValue(t.guidString).toString()}static isSpacerControl(t){return t===G.SpacerControl}static GetRowSpan(t){let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===G.CustomControl&&!P.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}switch(e.UnboundControlIds.getValue(r.guidString)){case ee.IframeControl:case ee.ACIControl:case ee.SocialInsightControl:return 6;case ee.SubGridControl:case ee.CustomControl:return 4;case ee.WebResourceImageControl:return 15;case ee.WebResourceHtmlControl:return 15;case ee.MapsControl:return 8;case ee.SearchWidgetControl:return 10;case ee.NotesControl:case ee.TimeLineControl:return 15;case ee.TimerControl:return 2;default:}}static isLookUpControl(t){return!P.IsNullOrUndefined(t)&&t.ClassId.guidString===G.LookupControl}static isRelationshipAssistantOrLeadScoringControl(t){return!P.IsNullOrUndefined(t)&&e.isRelationshipAssistantOrLeadScoring(t.UniqueId)}static isRelationshipAssistantOrLeadScoring(t){return!P.IsNullOrUndefined(t)&&(t.guidString===aa.RelationshipAssistant||t.guidString===aa.PredictiveLeadScoring)}static isRelationshipAssistantControl(t){return!P.IsNullOrUndefined(t)&&e.isRelationshipAssistant(t.UniqueId)}static isRelationshipAssistant(t){return!P.IsNullOrUndefined(t)&&t.guidString===aa.RelationshipAssistant}static getUniqueIdentifierForControl(t){if(P.IsNullOrUndefined(t))return null;let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===G.CustomControl&&!P.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}return r}}});var nf,$_=k(()=>{"use strict";nf=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 sa,vs,F_,M_,ho,U_,B_,d0=k(()=>{"use strict";(function(e){e[e.Center=0]="Center",e[e.Left=1]="Left",e[e.Right=2]="Right"})(sa||(sa={}));(function(e){e[e.Left=0]="Left",e[e.Top=1]="Top"})(vs||(vs={}));(function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle"})(F_||(F_={}));(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"})(M_||(M_={}));(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"})(ho||(ho={}));(function(e){e[e.None=0]="None",e[e.SystemRequired=1]="SystemRequired",e[e.ApplicationRequired=2]="ApplicationRequired",e[e.Recommended=3]="Recommended"})(U_||(U_={}));(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"})(B_||(B_={}))});var ws,q_=k(()=>{"use strict";cu();ws=Qg({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 V_(e){return{...e,extractConfig:t=>OW(t,Object.keys(e.fallback))}}function OW(e,t){let r={};for(let n of t)typeof e[n]<"u"&&(r[n]=e[n]);return r}var f0=k(()=>{"use strict";});var p0=v((mce,W_)=>{var pu=new Proxy(function(){return pu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:pu},apply:function(){return pu},construct:function(){return{}}}),G_=function(){return pu};Object.setPrototypeOf(G_,pu);W_.exports=G_});var H_=v((hce,j_)=>{var mu=new Proxy(function(){return mu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:mu},apply:function(){return mu},construct:function(){return{}}}),z_=function(){return mu};Object.setPrototypeOf(z_,mu);j_.exports=z_});var m0=v((gce,J_)=>{var hu=new Proxy(function(){return hu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:hu},apply:function(){return hu},construct:function(){return{}}}),K_=function(){return hu};Object.setPrototypeOf(K_,hu);J_.exports=K_});var Q_=v((yce,Y_)=>{function PW(){this.__data__=[],this.size=0}Y_.exports=PW});var Cs=v((bce,X_)=>{function RW(e,t){return e===t||e!==e&&t!==t}X_.exports=RW});var gu=v((vce,Z_)=>{var LW=Cs();function kW(e,t){for(var r=e.length;r--;)if(LW(e[r][0],t))return r;return-1}Z_.exports=kW});var tT=v((wce,eT)=>{var xW=gu(),$W=Array.prototype,FW=$W.splice;function MW(e){var t=this.__data__,r=xW(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():FW.call(t,r,1),--this.size,!0}eT.exports=MW});var nT=v((Cce,rT)=>{var UW=gu();function BW(e){var t=this.__data__,r=UW(t,e);return r<0?void 0:t[r][1]}rT.exports=BW});var oT=v((Ece,iT)=>{var qW=gu();function VW(e){return qW(this.__data__,e)>-1}iT.exports=VW});var sT=v((Ace,aT)=>{var GW=gu();function WW(e,t){var r=this.__data__,n=GW(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}aT.exports=WW});var yu=v((Sce,lT)=>{var zW=Q_(),jW=tT(),HW=nT(),KW=oT(),JW=sT();function Es(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])}}Es.prototype.clear=zW;Es.prototype.delete=jW;Es.prototype.get=HW;Es.prototype.has=KW;Es.prototype.set=JW;lT.exports=Es});var cT=v((Nce,uT)=>{var YW=yu();function QW(){this.__data__=new YW,this.size=0}uT.exports=QW});var fT=v((_ce,dT)=>{function XW(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}dT.exports=XW});var mT=v((Tce,pT)=>{function ZW(e){return this.__data__.get(e)}pT.exports=ZW});var gT=v((Dce,hT)=>{function e6(e){return this.__data__.has(e)}hT.exports=e6});var h0=v((Ice,yT)=>{var t6=typeof global=="object"&&global&&global.Object===Object&&global;yT.exports=t6});var Nn=v((Oce,bT)=>{var r6=h0(),n6=typeof self=="object"&&self&&self.Object===Object&&self,i6=r6||n6||Function("return this")();bT.exports=i6});var bu=v((Pce,vT)=>{var o6=Nn(),a6=o6.Symbol;vT.exports=a6});var AT=v((Rce,ET)=>{var wT=bu(),CT=Object.prototype,s6=CT.hasOwnProperty,l6=CT.toString,vu=wT?wT.toStringTag:void 0;function u6(e){var t=s6.call(e,vu),r=e[vu];try{e[vu]=void 0;var n=!0}catch{}var i=l6.call(e);return n&&(t?e[vu]=r:delete e[vu]),i}ET.exports=u6});var NT=v((Lce,ST)=>{var c6=Object.prototype,d6=c6.toString;function f6(e){return d6.call(e)}ST.exports=f6});var la=v((kce,DT)=>{var _T=bu(),p6=AT(),m6=NT(),h6="[object Null]",g6="[object Undefined]",TT=_T?_T.toStringTag:void 0;function y6(e){return e==null?e===void 0?g6:h6:TT&&TT in Object(e)?p6(e):m6(e)}DT.exports=y6});var Li=v((xce,IT)=>{function b6(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}IT.exports=b6});var of=v(($ce,OT)=>{var v6=la(),w6=Li(),C6="[object AsyncFunction]",E6="[object Function]",A6="[object GeneratorFunction]",S6="[object Proxy]";function N6(e){if(!w6(e))return!1;var t=v6(e);return t==E6||t==A6||t==C6||t==S6}OT.exports=N6});var RT=v((Fce,PT)=>{var _6=Nn(),T6=_6["__core-js_shared__"];PT.exports=T6});var xT=v((Mce,kT)=>{var g0=RT(),LT=(function(){var e=/[^.]+$/.exec(g0&&g0.keys&&g0.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function D6(e){return!!LT&< in e}kT.exports=D6});var y0=v((Uce,$T)=>{var I6=Function.prototype,O6=I6.toString;function P6(e){if(e!=null){try{return O6.call(e)}catch{}try{return e+""}catch{}}return""}$T.exports=P6});var MT=v((Bce,FT)=>{var R6=of(),L6=xT(),k6=Li(),x6=y0(),$6=/[\\^$.*+?()[\]{}|]/g,F6=/^\[object .+?Constructor\]$/,M6=Function.prototype,U6=Object.prototype,B6=M6.toString,q6=U6.hasOwnProperty,V6=RegExp("^"+B6.call(q6).replace($6,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function G6(e){if(!k6(e)||L6(e))return!1;var t=R6(e)?V6:F6;return t.test(x6(e))}FT.exports=G6});var BT=v((qce,UT)=>{function W6(e,t){return e?.[t]}UT.exports=W6});var go=v((Vce,qT)=>{var z6=MT(),j6=BT();function H6(e,t){var r=j6(e,t);return z6(r)?r:void 0}qT.exports=H6});var af=v((Gce,VT)=>{var K6=go(),J6=Nn(),Y6=K6(J6,"Map");VT.exports=Y6});var wu=v((Wce,GT)=>{var Q6=go(),X6=Q6(Object,"create");GT.exports=X6});var jT=v((zce,zT)=>{var WT=wu();function Z6(){this.__data__=WT?WT(null):{},this.size=0}zT.exports=Z6});var KT=v((jce,HT)=>{function ez(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}HT.exports=ez});var YT=v((Hce,JT)=>{var tz=wu(),rz="__lodash_hash_undefined__",nz=Object.prototype,iz=nz.hasOwnProperty;function oz(e){var t=this.__data__;if(tz){var r=t[e];return r===rz?void 0:r}return iz.call(t,e)?t[e]:void 0}JT.exports=oz});var XT=v((Kce,QT)=>{var az=wu(),sz=Object.prototype,lz=sz.hasOwnProperty;function uz(e){var t=this.__data__;return az?t[e]!==void 0:lz.call(t,e)}QT.exports=uz});var eD=v((Jce,ZT)=>{var cz=wu(),dz="__lodash_hash_undefined__";function fz(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=cz&&t===void 0?dz:t,this}ZT.exports=fz});var rD=v((Yce,tD)=>{var pz=jT(),mz=KT(),hz=YT(),gz=XT(),yz=eD();function As(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])}}As.prototype.clear=pz;As.prototype.delete=mz;As.prototype.get=hz;As.prototype.has=gz;As.prototype.set=yz;tD.exports=As});var oD=v((Qce,iD)=>{var nD=rD(),bz=yu(),vz=af();function wz(){this.size=0,this.__data__={hash:new nD,map:new(vz||bz),string:new nD}}iD.exports=wz});var sD=v((Xce,aD)=>{function Cz(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}aD.exports=Cz});var Cu=v((Zce,lD)=>{var Ez=sD();function Az(e,t){var r=e.__data__;return Ez(t)?r[typeof t=="string"?"string":"hash"]:r.map}lD.exports=Az});var cD=v((ede,uD)=>{var Sz=Cu();function Nz(e){var t=Sz(this,e).delete(e);return this.size-=t?1:0,t}uD.exports=Nz});var fD=v((tde,dD)=>{var _z=Cu();function Tz(e){return _z(this,e).get(e)}dD.exports=Tz});var mD=v((rde,pD)=>{var Dz=Cu();function Iz(e){return Dz(this,e).has(e)}pD.exports=Iz});var gD=v((nde,hD)=>{var Oz=Cu();function Pz(e,t){var r=Oz(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}hD.exports=Pz});var sf=v((ide,yD)=>{var Rz=oD(),Lz=cD(),kz=fD(),xz=mD(),$z=gD();function Ss(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])}}Ss.prototype.clear=Rz;Ss.prototype.delete=Lz;Ss.prototype.get=kz;Ss.prototype.has=xz;Ss.prototype.set=$z;yD.exports=Ss});var vD=v((ode,bD)=>{var Fz=yu(),Mz=af(),Uz=sf(),Bz=200;function qz(e,t){var r=this.__data__;if(r instanceof Fz){var n=r.__data__;if(!Mz||n.length<Bz-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new Uz(n)}return r.set(e,t),this.size=r.size,this}bD.exports=qz});var b0=v((ade,wD)=>{var Vz=yu(),Gz=cT(),Wz=fT(),zz=mT(),jz=gT(),Hz=vD();function Ns(e){var t=this.__data__=new Vz(e);this.size=t.size}Ns.prototype.clear=Gz;Ns.prototype.delete=Wz;Ns.prototype.get=zz;Ns.prototype.has=jz;Ns.prototype.set=Hz;wD.exports=Ns});var ED=v((sde,CD)=>{var Kz="__lodash_hash_undefined__";function Jz(e){return this.__data__.set(e,Kz),this}CD.exports=Jz});var SD=v((lde,AD)=>{function Yz(e){return this.__data__.has(e)}AD.exports=Yz});var _D=v((ude,ND)=>{var Qz=sf(),Xz=ED(),Zz=SD();function lf(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new Qz;++t<r;)this.add(e[t])}lf.prototype.add=lf.prototype.push=Xz;lf.prototype.has=Zz;ND.exports=lf});var DD=v((cde,TD)=>{function ej(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}TD.exports=ej});var OD=v((dde,ID)=>{function tj(e,t){return e.has(t)}ID.exports=tj});var v0=v((fde,PD)=>{var rj=_D(),nj=DD(),ij=OD(),oj=1,aj=2;function sj(e,t,r,n,i,o){var a=r&oj,s=e.length,l=t.length;if(s!=l&&!(a&&l>s))return!1;var u=o.get(e),c=o.get(t);if(u&&c)return u==t&&c==e;var d=-1,f=!0,p=r&aj?new rj:void 0;for(o.set(e,t),o.set(t,e);++d<s;){var m=e[d],h=t[d];if(n)var g=a?n(h,m,d,t,e,o):n(m,h,d,e,t,o);if(g!==void 0){if(g)continue;f=!1;break}if(p){if(!nj(t,function(b,w){if(!ij(p,w)&&(m===b||i(m,b,r,n,o)))return p.push(w)})){f=!1;break}}else if(!(m===h||i(m,h,r,n,o))){f=!1;break}}return o.delete(e),o.delete(t),f}PD.exports=sj});var w0=v((pde,RD)=>{var lj=Nn(),uj=lj.Uint8Array;RD.exports=uj});var kD=v((mde,LD)=>{function cj(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}LD.exports=cj});var $D=v((hde,xD)=>{function dj(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}xD.exports=dj});var qD=v((gde,BD)=>{var FD=bu(),MD=w0(),fj=Cs(),pj=v0(),mj=kD(),hj=$D(),gj=1,yj=2,bj="[object Boolean]",vj="[object Date]",wj="[object Error]",Cj="[object Map]",Ej="[object Number]",Aj="[object RegExp]",Sj="[object Set]",Nj="[object String]",_j="[object Symbol]",Tj="[object ArrayBuffer]",Dj="[object DataView]",UD=FD?FD.prototype:void 0,C0=UD?UD.valueOf:void 0;function Ij(e,t,r,n,i,o,a){switch(r){case Dj:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case Tj:return!(e.byteLength!=t.byteLength||!o(new MD(e),new MD(t)));case bj:case vj:case Ej:return fj(+e,+t);case wj:return e.name==t.name&&e.message==t.message;case Aj:case Nj:return e==t+"";case Cj:var s=mj;case Sj:var l=n&gj;if(s||(s=hj),e.size!=t.size&&!l)return!1;var u=a.get(e);if(u)return u==t;n|=yj,a.set(e,t);var c=pj(s(e),s(t),n,i,o,a);return a.delete(e),c;case _j:if(C0)return C0.call(e)==C0.call(t)}return!1}BD.exports=Ij});var GD=v((yde,VD)=>{function Oj(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}VD.exports=Oj});var yo=v((bde,WD)=>{var Pj=Array.isArray;WD.exports=Pj});var jD=v((vde,zD)=>{var Rj=GD(),Lj=yo();function kj(e,t,r){var n=t(e);return Lj(e)?n:Rj(n,r(e))}zD.exports=kj});var KD=v((wde,HD)=>{function xj(e,t){for(var r=-1,n=e==null?0:e.length,i=0,o=[];++r<n;){var a=e[r];t(a,r,e)&&(o[i++]=a)}return o}HD.exports=xj});var YD=v((Cde,JD)=>{function $j(){return[]}JD.exports=$j});var ZD=v((Ede,XD)=>{var Fj=KD(),Mj=YD(),Uj=Object.prototype,Bj=Uj.propertyIsEnumerable,QD=Object.getOwnPropertySymbols,qj=QD?function(e){return e==null?[]:(e=Object(e),Fj(QD(e),function(t){return Bj.call(e,t)}))}:Mj;XD.exports=qj});var tI=v((Ade,eI)=>{function Vj(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}eI.exports=Vj});var bo=v((Sde,rI)=>{function Gj(e){return e!=null&&typeof e=="object"}rI.exports=Gj});var iI=v((Nde,nI)=>{var Wj=la(),zj=bo(),jj="[object Arguments]";function Hj(e){return zj(e)&&Wj(e)==jj}nI.exports=Hj});var E0=v((_de,sI)=>{var oI=iI(),Kj=bo(),aI=Object.prototype,Jj=aI.hasOwnProperty,Yj=aI.propertyIsEnumerable,Qj=oI((function(){return arguments})())?oI:function(e){return Kj(e)&&Jj.call(e,"callee")&&!Yj.call(e,"callee")};sI.exports=Qj});var uI=v((Tde,lI)=>{function Xj(){return!1}lI.exports=Xj});var uf=v((Eu,_s)=>{var Zj=Nn(),e7=uI(),fI=typeof Eu=="object"&&Eu&&!Eu.nodeType&&Eu,cI=fI&&typeof _s=="object"&&_s&&!_s.nodeType&&_s,t7=cI&&cI.exports===fI,dI=t7?Zj.Buffer:void 0,r7=dI?dI.isBuffer:void 0,n7=r7||e7;_s.exports=n7});var cf=v((Dde,pI)=>{var i7=9007199254740991,o7=/^(?:0|[1-9]\d*)$/;function a7(e,t){var r=typeof e;return t=t??i7,!!t&&(r=="number"||r!="symbol"&&o7.test(e))&&e>-1&&e%1==0&&e<t}pI.exports=a7});var A0=v((Ide,mI)=>{var s7=9007199254740991;function l7(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=s7}mI.exports=l7});var gI=v((Ode,hI)=>{var u7=la(),c7=A0(),d7=bo(),f7="[object Arguments]",p7="[object Array]",m7="[object Boolean]",h7="[object Date]",g7="[object Error]",y7="[object Function]",b7="[object Map]",v7="[object Number]",w7="[object Object]",C7="[object RegExp]",E7="[object Set]",A7="[object String]",S7="[object WeakMap]",N7="[object ArrayBuffer]",_7="[object DataView]",T7="[object Float32Array]",D7="[object Float64Array]",I7="[object Int8Array]",O7="[object Int16Array]",P7="[object Int32Array]",R7="[object Uint8Array]",L7="[object Uint8ClampedArray]",k7="[object Uint16Array]",x7="[object Uint32Array]",xe={};xe[T7]=xe[D7]=xe[I7]=xe[O7]=xe[P7]=xe[R7]=xe[L7]=xe[k7]=xe[x7]=!0;xe[f7]=xe[p7]=xe[N7]=xe[m7]=xe[_7]=xe[h7]=xe[g7]=xe[y7]=xe[b7]=xe[v7]=xe[w7]=xe[C7]=xe[E7]=xe[A7]=xe[S7]=!1;function $7(e){return d7(e)&&c7(e.length)&&!!xe[u7(e)]}hI.exports=$7});var bI=v((Pde,yI)=>{function F7(e){return function(t){return e(t)}}yI.exports=F7});var wI=v((Au,Ts)=>{var M7=h0(),vI=typeof Au=="object"&&Au&&!Au.nodeType&&Au,Su=vI&&typeof Ts=="object"&&Ts&&!Ts.nodeType&&Ts,U7=Su&&Su.exports===vI,S0=U7&&M7.process,B7=(function(){try{var e=Su&&Su.require&&Su.require("util").types;return e||S0&&S0.binding&&S0.binding("util")}catch{}})();Ts.exports=B7});var df=v((Rde,AI)=>{var q7=gI(),V7=bI(),CI=wI(),EI=CI&&CI.isTypedArray,G7=EI?V7(EI):q7;AI.exports=G7});var N0=v((Lde,SI)=>{var W7=tI(),z7=E0(),j7=yo(),H7=uf(),K7=cf(),J7=df(),Y7=Object.prototype,Q7=Y7.hasOwnProperty;function X7(e,t){var r=j7(e),n=!r&&z7(e),i=!r&&!n&&H7(e),o=!r&&!n&&!i&&J7(e),a=r||n||i||o,s=a?W7(e.length,String):[],l=s.length;for(var u in e)(t||Q7.call(e,u))&&!(a&&(u=="length"||i&&(u=="offset"||u=="parent")||o&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||K7(u,l)))&&s.push(u);return s}SI.exports=X7});var ff=v((kde,NI)=>{var Z7=Object.prototype;function eH(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||Z7;return e===r}NI.exports=eH});var _0=v((xde,_I)=>{function tH(e,t){return function(r){return e(t(r))}}_I.exports=tH});var DI=v(($de,TI)=>{var rH=_0(),nH=rH(Object.keys,Object);TI.exports=nH});var OI=v((Fde,II)=>{var iH=ff(),oH=DI(),aH=Object.prototype,sH=aH.hasOwnProperty;function lH(e){if(!iH(e))return oH(e);var t=[];for(var r in Object(e))sH.call(e,r)&&r!="constructor"&&t.push(r);return t}II.exports=lH});var Nu=v((Mde,PI)=>{var uH=of(),cH=A0();function dH(e){return e!=null&&cH(e.length)&&!uH(e)}PI.exports=dH});var LI=v((Ude,RI)=>{var fH=N0(),pH=OI(),mH=Nu();function hH(e){return mH(e)?fH(e):pH(e)}RI.exports=hH});var xI=v((Bde,kI)=>{var gH=jD(),yH=ZD(),bH=LI();function vH(e){return gH(e,bH,yH)}kI.exports=vH});var MI=v((qde,FI)=>{var $I=xI(),wH=1,CH=Object.prototype,EH=CH.hasOwnProperty;function AH(e,t,r,n,i,o){var a=r&wH,s=$I(e),l=s.length,u=$I(t),c=u.length;if(l!=c&&!a)return!1;for(var d=l;d--;){var f=s[d];if(!(a?f in t:EH.call(t,f)))return!1}var p=o.get(e),m=o.get(t);if(p&&m)return p==t&&m==e;var h=!0;o.set(e,t),o.set(t,e);for(var g=a;++d<l;){f=s[d];var b=e[f],w=t[f];if(n)var E=a?n(w,b,f,t,e,o):n(b,w,f,e,t,o);if(!(E===void 0?b===w||i(b,w,r,n,o):E)){h=!1;break}g||(g=f=="constructor")}if(h&&!g){var A=e.constructor,L=t.constructor;A!=L&&"constructor"in e&&"constructor"in t&&!(typeof A=="function"&&A instanceof A&&typeof L=="function"&&L instanceof L)&&(h=!1)}return o.delete(e),o.delete(t),h}FI.exports=AH});var BI=v((Vde,UI)=>{var SH=go(),NH=Nn(),_H=SH(NH,"DataView");UI.exports=_H});var VI=v((Gde,qI)=>{var TH=go(),DH=Nn(),IH=TH(DH,"Promise");qI.exports=IH});var WI=v((Wde,GI)=>{var OH=go(),PH=Nn(),RH=OH(PH,"Set");GI.exports=RH});var jI=v((zde,zI)=>{var LH=go(),kH=Nn(),xH=LH(kH,"WeakMap");zI.exports=xH});var eO=v((jde,ZI)=>{var T0=BI(),D0=af(),I0=VI(),O0=WI(),P0=jI(),XI=la(),Ds=y0(),HI="[object Map]",$H="[object Object]",KI="[object Promise]",JI="[object Set]",YI="[object WeakMap]",QI="[object DataView]",FH=Ds(T0),MH=Ds(D0),UH=Ds(I0),BH=Ds(O0),qH=Ds(P0),ua=XI;(T0&&ua(new T0(new ArrayBuffer(1)))!=QI||D0&&ua(new D0)!=HI||I0&&ua(I0.resolve())!=KI||O0&&ua(new O0)!=JI||P0&&ua(new P0)!=YI)&&(ua=function(e){var t=XI(e),r=t==$H?e.constructor:void 0,n=r?Ds(r):"";if(n)switch(n){case FH:return QI;case MH:return HI;case UH:return KI;case BH:return JI;case qH:return YI}return t});ZI.exports=ua});var lO=v((Hde,sO)=>{var R0=b0(),VH=v0(),GH=qD(),WH=MI(),tO=eO(),rO=yo(),nO=uf(),zH=df(),jH=1,iO="[object Arguments]",oO="[object Array]",pf="[object Object]",HH=Object.prototype,aO=HH.hasOwnProperty;function KH(e,t,r,n,i,o){var a=rO(e),s=rO(t),l=a?oO:tO(e),u=s?oO:tO(t);l=l==iO?pf:l,u=u==iO?pf:u;var c=l==pf,d=u==pf,f=l==u;if(f&&nO(e)){if(!nO(t))return!1;a=!0,c=!1}if(f&&!c)return o||(o=new R0),a||zH(e)?VH(e,t,r,n,i,o):GH(e,t,l,r,n,i,o);if(!(r&jH)){var p=c&&aO.call(e,"__wrapped__"),m=d&&aO.call(t,"__wrapped__");if(p||m){var h=p?e.value():e,g=m?t.value():t;return o||(o=new R0),i(h,g,r,n,o)}}return f?(o||(o=new R0),WH(e,t,r,n,i,o)):!1}sO.exports=KH});var fO=v((Kde,dO)=>{var JH=lO(),uO=bo();function cO(e,t,r,n,i){return e===t?!0:e==null||t==null||!uO(e)&&!uO(t)?e!==e&&t!==t:JH(e,t,r,n,cO,i)}dO.exports=cO});var mO=v((Jde,pO)=>{var YH=fO();function QH(e,t){return YH(e,t)}pO.exports=QH});var L0=v((Yde,hO)=>{var XH=go(),ZH=(function(){try{var e=XH(Object,"defineProperty");return e({},"",{}),e}catch{}})();hO.exports=ZH});var mf=v((Qde,yO)=>{var gO=L0();function eK(e,t,r){t=="__proto__"&&gO?gO(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}yO.exports=eK});var k0=v((Xde,bO)=>{var tK=mf(),rK=Cs();function nK(e,t,r){(r!==void 0&&!rK(e[t],r)||r===void 0&&!(t in e))&&tK(e,t,r)}bO.exports=nK});var wO=v((Zde,vO)=>{function iK(e){return function(t,r,n){for(var i=-1,o=Object(t),a=n(t),s=a.length;s--;){var l=a[e?s:++i];if(r(o[l],l,o)===!1)break}return t}}vO.exports=iK});var EO=v((efe,CO)=>{var oK=wO(),aK=oK();CO.exports=aK});var TO=v((_u,Is)=>{var sK=Nn(),_O=typeof _u=="object"&&_u&&!_u.nodeType&&_u,AO=_O&&typeof Is=="object"&&Is&&!Is.nodeType&&Is,lK=AO&&AO.exports===_O,SO=lK?sK.Buffer:void 0,NO=SO?SO.allocUnsafe:void 0;function uK(e,t){if(t)return e.slice();var r=e.length,n=NO?NO(r):new e.constructor(r);return e.copy(n),n}Is.exports=uK});var OO=v((tfe,IO)=>{var DO=w0();function cK(e){var t=new e.constructor(e.byteLength);return new DO(t).set(new DO(e)),t}IO.exports=cK});var RO=v((rfe,PO)=>{var dK=OO();function fK(e,t){var r=t?dK(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}PO.exports=fK});var kO=v((nfe,LO)=>{function pK(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}LO.exports=pK});var FO=v((ife,$O)=>{var mK=Li(),xO=Object.create,hK=(function(){function e(){}return function(t){if(!mK(t))return{};if(xO)return xO(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})();$O.exports=hK});var x0=v((ofe,MO)=>{var gK=_0(),yK=gK(Object.getPrototypeOf,Object);MO.exports=yK});var BO=v((afe,UO)=>{var bK=FO(),vK=x0(),wK=ff();function CK(e){return typeof e.constructor=="function"&&!wK(e)?bK(vK(e)):{}}UO.exports=CK});var VO=v((sfe,qO)=>{var EK=Nu(),AK=bo();function SK(e){return AK(e)&&EK(e)}qO.exports=SK});var zO=v((lfe,WO)=>{var NK=la(),_K=x0(),TK=bo(),DK="[object Object]",IK=Function.prototype,OK=Object.prototype,GO=IK.toString,PK=OK.hasOwnProperty,RK=GO.call(Object);function LK(e){if(!TK(e)||NK(e)!=DK)return!1;var t=_K(e);if(t===null)return!0;var r=PK.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&GO.call(r)==RK}WO.exports=LK});var $0=v((ufe,jO)=>{function kK(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}jO.exports=kK});var F0=v((cfe,HO)=>{var xK=mf(),$K=Cs(),FK=Object.prototype,MK=FK.hasOwnProperty;function UK(e,t,r){var n=e[t];(!(MK.call(e,t)&&$K(n,r))||r===void 0&&!(t in e))&&xK(e,t,r)}HO.exports=UK});var JO=v((dfe,KO)=>{var BK=F0(),qK=mf();function VK(e,t,r,n){var i=!r;r||(r={});for(var o=-1,a=t.length;++o<a;){var s=t[o],l=n?n(r[s],e[s],s,r,e):void 0;l===void 0&&(l=e[s]),i?qK(r,s,l):BK(r,s,l)}return r}KO.exports=VK});var QO=v((ffe,YO)=>{function GK(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}YO.exports=GK});var ZO=v((pfe,XO)=>{var WK=Li(),zK=ff(),jK=QO(),HK=Object.prototype,KK=HK.hasOwnProperty;function JK(e){if(!WK(e))return jK(e);var t=zK(e),r=[];for(var n in e)n=="constructor"&&(t||!KK.call(e,n))||r.push(n);return r}XO.exports=JK});var M0=v((mfe,eP)=>{var YK=N0(),QK=ZO(),XK=Nu();function ZK(e){return XK(e)?YK(e,!0):QK(e)}eP.exports=ZK});var rP=v((hfe,tP)=>{var eJ=JO(),tJ=M0();function rJ(e){return eJ(e,tJ(e))}tP.exports=rJ});var lP=v((gfe,sP)=>{var nP=k0(),nJ=TO(),iJ=RO(),oJ=kO(),aJ=BO(),iP=E0(),oP=yo(),sJ=VO(),lJ=uf(),uJ=of(),cJ=Li(),dJ=zO(),fJ=df(),aP=$0(),pJ=rP();function mJ(e,t,r,n,i,o,a){var s=aP(e,r),l=aP(t,r),u=a.get(l);if(u){nP(e,r,u);return}var c=o?o(s,l,r+"",e,t,a):void 0,d=c===void 0;if(d){var f=oP(l),p=!f&&lJ(l),m=!f&&!p&&fJ(l);c=l,f||p||m?oP(s)?c=s:sJ(s)?c=oJ(s):p?(d=!1,c=nJ(l,!0)):m?(d=!1,c=iJ(l,!0)):c=[]:dJ(l)||iP(l)?(c=s,iP(s)?c=pJ(s):(!cJ(s)||uJ(s))&&(c=aJ(l))):d=!1}d&&(a.set(l,c),i(c,l,n,o,a),a.delete(l)),nP(e,r,c)}sP.exports=mJ});var U0=v((yfe,cP)=>{var hJ=b0(),gJ=k0(),yJ=EO(),bJ=lP(),vJ=Li(),wJ=M0(),CJ=$0();function uP(e,t,r,n,i){e!==t&&yJ(t,function(o,a){if(i||(i=new hJ),vJ(o))bJ(e,t,a,r,uP,n,i);else{var s=n?n(CJ(e,a),o,a+"",e,t,i):void 0;s===void 0&&(s=o),gJ(e,a,s)}},wJ)}cP.exports=uP});var B0=v((bfe,dP)=>{function EJ(e){return e}dP.exports=EJ});var pP=v((vfe,fP)=>{function AJ(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)}fP.exports=AJ});var gP=v((wfe,hP)=>{var SJ=pP(),mP=Math.max;function NJ(e,t,r){return t=mP(t===void 0?e.length-1:t,0),function(){for(var n=arguments,i=-1,o=mP(n.length-t,0),a=Array(o);++i<o;)a[i]=n[t+i];i=-1;for(var s=Array(t+1);++i<t;)s[i]=n[i];return s[t]=r(a),SJ(e,this,s)}}hP.exports=NJ});var bP=v((Cfe,yP)=>{function _J(e){return function(){return e}}yP.exports=_J});var CP=v((Efe,wP)=>{var TJ=bP(),vP=L0(),DJ=B0(),IJ=vP?function(e,t){return vP(e,"toString",{configurable:!0,enumerable:!1,value:TJ(t),writable:!0})}:DJ;wP.exports=IJ});var AP=v((Afe,EP)=>{var OJ=800,PJ=16,RJ=Date.now;function LJ(e){var t=0,r=0;return function(){var n=RJ(),i=PJ-(n-r);if(r=n,i>0){if(++t>=OJ)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}EP.exports=LJ});var NP=v((Sfe,SP)=>{var kJ=CP(),xJ=AP(),$J=xJ(kJ);SP.exports=$J});var TP=v((Nfe,_P)=>{var FJ=B0(),MJ=gP(),UJ=NP();function BJ(e,t){return UJ(MJ(e,t,FJ),e+"")}_P.exports=BJ});var IP=v((_fe,DP)=>{var qJ=Cs(),VJ=Nu(),GJ=cf(),WJ=Li();function zJ(e,t,r){if(!WJ(r))return!1;var n=typeof t;return(n=="number"?VJ(r)&&GJ(t,r.length):n=="string"&&t in r)?qJ(r[t],e):!1}DP.exports=zJ});var q0=v((Tfe,OP)=>{var jJ=TP(),HJ=IP();function KJ(e){return jJ(function(t,r){var n=-1,i=r.length,o=i>1?r[i-1]:void 0,a=i>2?r[2]:void 0;for(o=e.length>3&&typeof o=="function"?(i--,o):void 0,a&&HJ(r[0],r[1],a)&&(o=i<3?void 0:o,i=1),t=Object(t);++n<i;){var s=r[n];s&&e(t,s,n,o)}return t})}OP.exports=KJ});var RP=v((Dfe,PP)=>{var JJ=U0(),YJ=q0(),QJ=YJ(function(e,t,r,n){JJ(e,t,r,n)});PP.exports=QJ});var on,Tu=k(()=>{"use strict";(function(e){e[e.NotLoaded=0]="NotLoaded",e[e.Initialized=1]="Initialized",e[e.ConfigsLoaded=2]="ConfigsLoaded",e[e.Error=3]="Error"})(on||(on={}))});function kP(e,t,r="PROD"){let n=i=>`ShellSettings_ECS_ClientCache_${e}_${LP.EcsConfigType[i]}_${r}`;return{getData:i=>{let o=t.getItem(n(i));return Promise.resolve(o?JSON.parse(o):void 0)},putData:(i,o)=>(t.setItem(n(i),JSON.stringify(o)),Promise.resolve())}}var LP,XJ,xP=k(()=>{"use strict";LP=we(m0()),XJ=we(p0());});var V0,$P=k(()=>{"use strict";Yd();V0=uu({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 MP,UP,BP,qP,G0,ZJ,hf,FP,W0=k(()=>{"use strict";MP=we(p0()),UP=we(H_()),BP=we(m0()),qP=we(mO()),G0=we(RP());Tu();xP();$P();ZJ=60*1e3,hf=class{clientName;logger;ecsEndpoint;resolveLoadingPromise;loadingPromise=new Promise(t=>this.resolveLoadingPromise=t);_status=on.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"?V0.prodEcsEndpoint:V0.integrationEcsEndpoint}client=new UP.default;init=async({clientVersion:t,getFilters:r,cacheStorage:n=MP.StorageHelper.transientWithGlobalFallback,updateIntervalInMinutes:i,overrideEcsInitParams:o})=>{this.client.telemetryEventAdded.subscribe(this.logger.logEvent),this.client.configUpdated.subscribe(this.handleConfigUpdated);let a=(async()=>{let s=await r();return this.logEvent("FeaturesClient/configRequested",{ecsClientName:this.clientName,filters:s}),s});try{await this.client.initialize({clientName:this.clientName,clientVersion:t??"1.0.0.0",configsToFetch:[BP.EcsConfigType.Default],hosts:[this.ecsEndpoint],initialAppActiveState:!0,getEcsParameters:a,databaseInterface:kP(this.clientName,n,this.endpointType),...o}),this.client.requestUpdate(),this._status===on.NotLoaded&&(this._status=on.Initialized)}catch(s){this._status=on.Error,this.resolveLoadingPromise(),this.logEvent("FeaturesClient/initializationFailed",{ecsClientName:this.clientName,error:s},"Error")}i&&window.setInterval(()=>this.client.requestUpdate(),i*ZJ)};getConfig=t=>{let r=this.getMergedClientConfigByTeamName(t.teamName),n=r?t.extractConfig(r):{};return(0,G0.default)({},t.fallback,n,t.override,FP)};getAllConfigs=()=>this.getMergedClientConfig();getAllConfigsByTeamName=t=>this.getMergedClientConfigByTeamName(t);requestConfigUpdate=()=>{this.client.requestUpdate()};subscribe=(t,r)=>{let n=this.getConfig(t),i=this.client.configUpdated.subscribe(()=>{let o=this.getConfig(t);(0,qP.default)(o,n)||(n={...o},r(o))});return{unsubscribe:()=>i.unsubscribe()}};waitUntilLoaded=async t=>{if(t!==void 0){let r,n=new Promise((i,o)=>{r=window.setTimeout(()=>{o(new Error("Timed out waiting for configuration to load"))},t)});await Promise.race([this.loadingPromise,n]),clearTimeout(r)}else await this.loadingPromise};overrideClientConfig(t){this.logger.logEvent("FeaturesClient/overrideClientConfig",{clientConfigOverride:t}),this.clientConfigOverride=t}undoClientConfigOverride(){this.clientConfigOverride=void 0,this.logger.logEvent("FeaturesClient/undoClientConfigOverride")}getMergedClientConfig=()=>(0,G0.default)({},this.client.getConfig()?.config,this.clientConfigOverride,FP);getMergedClientConfigByTeamName=t=>this.getMergedClientConfig()?.[t];handleConfigUpdated=()=>{let t=this.client.getConfig();if(t===void 0)return;this.resolveLoadingPromise(),this._status=on.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})}},FP=(e,t)=>{if(Array.isArray(t))return t}});var GP=v((Ffe,VP)=>{"use strict";var eY=()=>{let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e};VP.exports=eY});var z0=v((Mfe,zP)=>{var Du=new Proxy(function(){return Du},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Du},apply:function(){return Du},construct:function(){return{}}}),WP=function(){return Du};Object.setPrototypeOf(WP,Du);zP.exports=WP});var KP=v((Ufe,HP)=>{var Iu=new Proxy(function(){return Iu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Iu},apply:function(){return Iu},construct:function(){return{}}}),jP=function(){return Iu};Object.setPrototypeOf(jP,Iu);HP.exports=jP});var tR=v((Bfe,eR)=>{"use strict";var j0=KP(),tY={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},rY={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},nY={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},XP={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},H0={};H0[j0.ForwardRef]=nY;H0[j0.Memo]=XP;function JP(e){return j0.isMemo(e)?XP:H0[e.$$typeof]||tY}var iY=Object.defineProperty,oY=Object.getOwnPropertyNames,YP=Object.getOwnPropertySymbols,aY=Object.getOwnPropertyDescriptor,sY=Object.getPrototypeOf,QP=Object.prototype;function ZP(e,t,r){if(typeof t!="string"){if(QP){var n=sY(t);n&&n!==QP&&ZP(e,n,r)}var i=oY(t);YP&&(i=i.concat(YP(t)));for(var o=JP(e),a=JP(t),s=0;s<i.length;++s){var l=i[s];if(!rY[l]&&!(r&&r[l])&&!(a&&a[l])&&!(o&&o[l])){var u=aY(t,l);try{iY(e,l,u)}catch{}}}}return e}eR.exports=ZP});function nR(e,t,r){let[n,i]=(0,Os.useState)(e.getConfig(t));return(0,Os.useEffect)(()=>{if(!r?.subscribe&&e.status===on.ConfigsLoaded)return;let o=e.subscribe(t,a=>{i(a),r?.subscribe||o.unsubscribe()});return o?.unsubscribe},[]),n}function iR(e){return function(t,r){return nR(e,t,r)}}function oR(e,t,r,n){let i=o=>{let a=nR(e,t,n),s={...o,...a};return Os.default.createElement(r,{...s})};return(0,rR.default)(i,r),i.displayName=`WithFeature(${r.name})`,i}function aR(e,t,r,n){return t.reduce((i,o)=>oR(e,o,i,n),r)}function sR(e){return function(t,r,n){return oR(e,t,r,n)}}var rR,Os,K0=k(()=>{"use strict";rR=we(tR()),Os=we(z0());Tu();});var uR=v((Gfe,lR)=>{var lY=U0(),uY=q0(),cY=uY(function(e,t,r){lY(e,t,r)});lR.exports=cY});var gf=v((Wfe,cR)=>{var dY=la(),fY=bo(),pY="[object Symbol]";function mY(e){return typeof e=="symbol"||fY(e)&&dY(e)==pY}cR.exports=mY});var fR=v((zfe,dR)=>{var hY=yo(),gY=gf(),yY=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,bY=/^\w*$/;function vY(e,t){if(hY(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||gY(e)?!0:bY.test(e)||!yY.test(e)||t!=null&&e in Object(t)}dR.exports=vY});var hR=v((jfe,mR)=>{var pR=sf(),wY="Expected a function";function J0(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(wY);var r=function(){var n=arguments,i=t?t.apply(this,n):n[0],o=r.cache;if(o.has(i))return o.get(i);var a=e.apply(this,n);return r.cache=o.set(i,a)||o,a};return r.cache=new(J0.Cache||pR),r}J0.Cache=pR;mR.exports=J0});var yR=v((Hfe,gR)=>{var CY=hR(),EY=500;function AY(e){var t=CY(e,function(n){return r.size===EY&&r.clear(),n}),r=t.cache;return t}gR.exports=AY});var vR=v((Kfe,bR)=>{var SY=yR(),NY=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,_Y=/\\(\\)?/g,TY=SY(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(NY,function(r,n,i,o){t.push(i?o.replace(_Y,"$1"):n||r)}),t});bR.exports=TY});var CR=v((Jfe,wR)=>{function DY(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}wR.exports=DY});var TR=v((Yfe,_R)=>{var ER=bu(),IY=CR(),OY=yo(),PY=gf(),RY=1/0,AR=ER?ER.prototype:void 0,SR=AR?AR.toString:void 0;function NR(e){if(typeof e=="string")return e;if(OY(e))return IY(e,NR)+"";if(PY(e))return SR?SR.call(e):"";var t=e+"";return t=="0"&&1/e==-RY?"-0":t}_R.exports=NR});var IR=v((Qfe,DR)=>{var LY=TR();function kY(e){return e==null?"":LY(e)}DR.exports=kY});var PR=v((Xfe,OR)=>{var xY=yo(),$Y=fR(),FY=vR(),MY=IR();function UY(e,t){return xY(e)?e:$Y(e,t)?[e]:FY(MY(e))}OR.exports=UY});var LR=v((Zfe,RR)=>{var BY=gf(),qY=1/0;function VY(e){if(typeof e=="string"||BY(e))return e;var t=e+"";return t=="0"&&1/e==-qY?"-0":t}RR.exports=VY});var $R=v((epe,xR)=>{var GY=F0(),WY=PR(),zY=cf(),kR=Li(),jY=LR();function HY(e,t,r,n){if(!kR(e))return e;t=WY(t,e);for(var i=-1,o=t.length,a=o-1,s=e;s!=null&&++i<o;){var l=jY(t[i]),u=r;if(l==="__proto__"||l==="constructor"||l==="prototype")return e;if(i!=a){var c=s[l];u=n?n(c,l,s):void 0,u===void 0&&(u=kR(c)?c:zY(t[i+1])?[]:{})}GY(s,l,u),s=s[l]}return e}xR.exports=HY});var MR=v((tpe,FR)=>{var KY=$R();function JY(e,t,r){return e==null?e:KY(e,t,r)}FR.exports=JY});function VR(e){let{query:t}=(0,qR.default)(window.location.href,!0);return QY(e,t),e}function QY(e,t){let r=YY+e.clientName,n=Object.keys(t).filter(o=>o.startsWith(r));if(!n)return;let i={};n.forEach(o=>{let a=t[o];if(a)try{let s=JSON.parse(a),l=r+GR,u={};if(o===r)u=s;else if(o.startsWith(l)){let c=o.substring(l.length);(0,BR.default)(u,c,s)}(0,UR.default)(i,u)}catch{}}),Object.keys(i).length>0&&e.overrideClientConfig(i)}var UR,BR,qR,GR,YY,WR=k(()=>{"use strict";UR=we(uR()),BR=we(MR()),qR=we(t0());GR=".",YY="ecs"+GR});function bf(e,t,r){let n=VR(new hf(e,t,r));function i(o){(0,yf.useEffect)(()=>{n.init(o)},[])}return{featuresClient:n,createFeature:ZY(n),useFeaturesClientInitParams:i,withFeatures:(o,a,s)=>aR(n,o,a,s)}}function ZY(e){let t=iR(e),r=sR(e);return function(i){let o=V_(i);return o.getConfig=()=>e.getConfig(o),o.isLoaded=()=>e.status===on.ConfigsLoaded,i0.register(o,e.clientName),{useFeature:a=>t(o,a),withFeature:(a,s)=>r(o,a,s),feature:o}}}var XY,yf,Y0=k(()=>{"use strict";XY=we(GP()),yf=we(z0());f0();W0();Tu();K0();WR();o0();});var zR=k(()=>{"use strict";f0();W0();Y0();Tu();K0();ef();a0();});function vf(e){return{logEvent:(t,r,n)=>{switch(n){case"Error":(0,Ps.trackErrorTrace)(e,{eventName:t,eventData:r});break;case"Warning":(0,Ps.trackWarningTrace)(e,{eventName:t,eventData:r});break;default:(0,Ps.trackInfoTrace)(e,{eventName:t,eventData:r});break}}}}var Ps,Q0=k(()=>{"use strict";Ps=we(na());});var Cpe,Epe,Ape,jR=k(()=>{"use strict";zR();Q0();({featuresClient:Cpe,createFeature:Epe,useFeaturesClientInitParams:Ape}=bf("PowerApps-Shell-Test",vf("shell-features")))});var JR=v((Npe,KR)=>{var Ou=new Proxy(function(){return Ou},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Ou},apply:function(){return Ou},construct:function(){return{}}}),HR=function(){return Ou};Object.setPrototypeOf(HR,Ou);KR.exports=HR});var eQ,tQ,YR=k(()=>{"use strict";au();eQ=we(JR()),tQ=we(na());});var QR=k(()=>{"use strict";jR();Q0();YR();});var kpe,Rs,xpe,XR=k(()=>{"use strict";QR();Y0();({featuresClient:kpe,createFeature:Rs,useFeaturesClientInitParams:xpe}=bf("PowerApps-MakerPortal",vf("powerapps-features")))});var ZR,e2,Upe,Bpe,qpe,Vpe,X0=k(()=>{"use strict";q_();XR();({feature:ZR}=Rs({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:ws.enableAutoInsertionOfCellInRow}})),{feature:e2}=Rs({teamName:"MakerPortal",owners:["aansu"],description:"Enable the one grid events for form designer",createdOn:"08/21/2024",fallback:{enableOneGridEventsForFormDesigner:ws.enableOneGridEvents}}),{feature:Upe}=Rs({teamName:"MakerPortal",owners:["adekulkarni"],description:"Disables PBI components and cleans them up from the form",createdOn:"01/03/2023",fallback:{enableFallbackFormTemplate:ws.disablePBIComponents}}),{feature:Bpe}=Rs({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:ws.enableAgentResponse}}),{feature:qpe,useFeature:Vpe}=Rs({teamName:"MakerPortal",owners:["aansu"],description:"Enables delayed localization of custom control",createdOn:"06/08/2025",fallback:{enableDelayedLocalizationForCustomControls:ws.enableDelayedLocalizationForCustomControls}})});var n2=v((Wpe,r2)=>{var Pu=new Proxy(function(){return Pu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Pu},apply:function(){return Pu},construct:function(){return{}}}),t2=function(){return Pu};Object.setPrototypeOf(t2,Pu);r2.exports=t2});var jt,vo=k(()=>{"use strict";ct();et();zt();fu();se();St();jt=class extends te{static HighestUsedIndexByClass=new Map;get colspan(){let t=this.getProperty(y.colspan);return P.IsNullOrUndefined(t)?null:parseInt(t,10)}set colspan(t){P.IsNullOrUndefined(t)||this.setProperty(y.colspan,String(t))}constructor(t,r){super(t,r)}get id(){let t=this.getProperty(y.id);return t==null?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new U(t.substr(1,t.length-2)):new U(t)}set id(t){this.setProperty(y.id,`{${t.ToString()}}`)}set labelId(t){this.setProperty(y.labelId,`{${t.ToString()}}`)}get labelId(){let t=this.getProperty(y.labelId);return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new U(t.substr(1,t.length-2)):new U(t)}get Name(){return this.getProperty(y.Name)}set Name(t){this.setProperty(y.Name,t)}setDisplayName(t,r){for(let i of this.getAllLabels())if(+i.getProperty(y.languagecode)===r){i.setProperty(y.description,t);return}let n=new te(C.formLabel,null);n.setProperty(y.description,t),n.setProperty(y.languagecode,String(r)),this.addGrandChild("labels",n)}getDisplayName(t){for(let r of this.getAllLabels())if(+r.getProperty(y.languagecode)===t)return r.getProperty(y.description)}getAllLabels(){let t=this.getChildren("labels");return t.length!==1?[]:t[0].getChildren("label")}get isLocked(){return+this.getProperty(y.locklevel)==1}set isLocked(t){!this.IsUnboundControl&&this.setProperty(y.locklevel,t?"1":"0")}get availableforphone(){return this.getProcessedValue(y.availableforphone)}set availableforphone(t){P.IsNullOrUndefined(t)||!this.IsAllowedUBCForAvailableOnPhone()||this.setProperty(y.availableforphone,String(t))}get visible(){return this.getProcessedValue(y.visible)}set visible(t){P.IsNullOrUndefined(t)||!this.IsAllowedUBCForVisibleByDefault()||this.setProperty(y.visible,String(t))}isLockLevelSettable(){return!this.IsUnboundControl}get showlabel(){return this.getProcessedValue(y.showlabel)}set showlabel(t){P.IsNullOrUndefined(t)||this.setProperty(y.showlabel,String(t))}isAvailableForPhoneSettable(){return this.IsAllowedUBCForAvailableOnPhone()}isVisibleSettable(){return this.IsAllowedUBCForVisibleByDefault()}getProcessedValue(t){let r=this.getProperty(t);return P.IsNullOrUndefined(r)||this.getProperty(t)==="true"}get readonly(){let t=this.getFirstChild(C.formControl);return t?t.disabled:!1}set readonly(t){let r=this.getFirstChild(C.formControl);r&&(r.disabled=t)}get allowfilteroff(){let t=this.getFirstChild(C.formControl);if(t)return t.getParam(y.AllowFilterOff)==="true"}set allowfilteroff(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AllowFilterOff,t)}get autoresolve(){let t=this.getFirstChild(C.formControl);if(t)return t.getParam(y.AutoResolve)==="true"}set autoresolve(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AutoResolve,t)}get defaultviewid(){let t=this.getFirstChild(C.formControl);return t?t.getParam(y.DefaultViewId):q.EmptyString}set defaultviewid(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DefaultViewId,t)}get dependentattributename(){let t=this.getFirstChild(C.formControl);return t?t.getParam(y.DependentAttributeName):q.EmptyString}set dependentattributename(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DependentAttributeName,t)}get dependentattributetype(){let t=this.getFirstChild(C.formControl);return t?t.getParam(y.DependentAttributeType):q.EmptyString}set dependentattributetype(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DependentAttributeType,t)}get disablequickfind(){let t=this.getFirstChild(C.formControl);if(t)return t.getParam(y.DisableQuickFind)==="true"}set disablequickfind(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DisableQuickFind,t)}get disableviewpicker(){let t=this.getFirstChild(C.formControl);if(t)return t.getParam(y.DisableViewPicker)==="true"}set disableviewpicker(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DisableViewPicker,t)}get filterrelationshipname(){let t=this.getFirstChild(C.formControl);return t?t.getParam(y.FilterRelationshipName):q.EmptyString}set filterrelationshipname(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.FilterRelationshipName,t)}get availableviewids(){let t=this.getFirstChild(C.formControl);return t?t.getParam(y.AvailableViewIds):q.EmptyString}set availableviewids(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AvailableViewIds,t)}get IsUnboundControl(){let t=this.getFirstChild(C.formControl);if(t&&t.ClassId){let r=tt.getUniqueIdentifierForControl(t);return!P.IsNullOrUndefined(r)&&tt.isUnboundFormControlByIdentifier(r)}else return!1}IsAllowedUBCForAvailableOnPhone(){let t=this.getFirstChild(C.formControl);if(t){let n=tt.getUniqueIdentifierForControl(t).guidString,i=n===G.GridControl||n===G.TimeLineControl||n===G.TimeLineControlUC;return this.IsUnboundControl?i:!0}return this.NodeName===C.formSection||this.NodeName===C.formTab}IsAllowedUBCForVisibleByDefault(){let t=this.getFirstChild(C.formControl);if(t){let n=tt.getUniqueIdentifierForControl(t).guidString,i=n===G.MapsControl||n===G.WebResourceHtmlControl||n===G.WebResourceImageControl||n===G.IframeControl||n===G.SocialInsightControl;return this.IsUnboundControl?i:!0}else return!0}get events(){let t=this.getChildren(C.formEvents);return t.length===1?t[0].getAllChildren():[]}addEvent(t){this.addGrandChild(C.formEvents,t)}getUsedNodeNameSet(t){return null}getHighestIndexById(t,r){return null}}});var Ls,Z0=k(()=>{"use strict";zt();se();St();Ls=class extends te{constructor(t,r){super(C.dependency,t),q.IsNullOrEmpty(r)||this.setDefaultProperties(r)}set id(t){this.setProperty(y.id,t)}get id(){return this.getProperty(y.id)}setDefaultProperties(t){this.id=t}}});var i2,ks,ey=k(()=>{"use strict";et();Z0();se();St();vo();(function(e){e[e.Form=0]="Form",e[e.Cell=1]="Cell",e[e.Tab=2]="Tab",e[e.Control=3]="Control"})(i2||(i2={}));ks=class extends jt{constructor(t,r){super(C.formEvent,t),r&&(this.eventName=r,this.application="false",this.active="false")}set eventName(t){this.setProperty(y.Name,t)}get eventName(){return this.getProperty(y.Name)}set application(t){this.setProperty(y.application,t)}get application(){return this.getProperty(y.application)}set attribute(t){this.setProperty(y.EventAttribute,t)}get attribute(){return this.getProperty(y.EventAttribute)}set relationship(t){this.setProperty(y.Relationship,t)}get relationship(){return this.getProperty(y.Relationship)}set control(t){this.setProperty(y.Control,t)}get control(){return this.getProperty(y.Control)}set active(t){this.setProperty(y.EventActive,t)}get active(){return this.getProperty(y.EventActive)}getAllHandlers(){let t=this.getChildren(C.EventHandlers);return t&&t.length?t[0].getChildren(C.handler):[]}getAllDependencies(){let t=this.getChildren(C.formDependencies);return t.length===0?[]:t[0].getAllChildren()}setDependencies(t){let r=this.getFirstChild(C.formDependencies);if(P.IsNullOrUndefined(r)){if(t.length===0)return;this.addChild(new te(C.formDependencies,this)),r=this.getFirstChild(C.formDependencies)}if(t.length===0)r.getParentNode().deleteChild(r);else{r.deleteAllChildren();for(let n of t)r.addChild(new Ls(r,n.toString()))}}}});var _n,Ru=k(()=>{"use strict";ct();Bl();et();ra();se();St();An();_n=class extends te{previewVersion;constructor(t){super(C.formControl,t)}updatePreview(){this.previewVersion=Date.now()}get ClassId(){let t=this.getProperty(y.classid);return t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t)}set ClassId(t){this.setProperty(y.classid,`{${t.ToString()}}`)}get dataFieldName(){return this.getProperty(y.datafieldname)}set dataFieldName(t){this.setProperty(y.datafieldname,t)}set id(t){this.setProperty(y.id,t)}get id(){return this.getProperty(y.id)}get UniqueId(){let t=this.getProperty(y.uniqueid);return P.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t))}set UniqueId(t){this.setProperty(y.uniqueid,`{${t.ToString()}}`)}get isRequired(){return this.getProperty(y.isRequired)==="true"}set isRequired(t){P.IsNullOrUndefined(t)||this.setProperty(y.isRequired,String(t))}get disableMru(){return this.getParam(y.DisableMru)==="true"}set disableMru(t){P.IsNullOrUndefined(t)||this.setParameter(y.DisableMru,t)}get useMFDForCreate(){return this.getParam(y.UseMFDForCreate)==="true"}set useMFDForCreate(t){P.IsNullOrUndefined(t)||this.setParameter(y.UseMFDForCreate,t)}get useMFDForEdit(){return this.getParam(y.UseMFDForEdit)==="true"}set useMFDForEdit(t){P.IsNullOrUndefined(t)||this.setParameter(y.UseMFDForEdit,t)}get disabled(){return this.getProperty(y.disabled)==="true"}set disabled(t){P.IsNullOrUndefined(t)||this.setProperty(y.disabled,String(t))}get indicationOfSubgrid(){return this.getProperty(y.indicationOfSubgrid)==="true"}set indicationOfSubgrid(t){this.setProperty(y.indicationOfSubgrid,String(t))}getAllParameters(){let t=new er,r=this.getFirstChild(y.parameters);return r&&r.getAllChildren().forEach(n=>{if(n){let i=n.getAllChildren(),o=i&&i.length>0&&i[0];o&&t.add(n.getNodeName(),o.getNodeName())}}),t}setParameter(t,r){let n=!1;r===null&&(n=!0);let i=(Ri.StartTag+r).toString(),o=this.parametersNode;if(o){let a=o.findFirst(s=>s&&s.getNodeName()===t);if(a)if(n){this.deleteFirstGrandChildOfName(C.controlParameters,a);return}else{let s=a.getAllChildren();s&&s.length>0&&s[0]?s[0].setNodeName(i):a.addChild(new te(i,a))}else n||(a=new te(t,o),a.addChild(new te(i,a)),o.addChild(a))}else if(!n){o=new te("parameters",this);let a=new te(t,o);a.addChild(new te(i,a)),o.addChild(a),this.addChild(o)}}getParam(t){if(this.parametersNode){let r=this.parametersNode.findFirst(n=>n&&n.getNodeName()===t);if(r){let n=r.getAllChildren(),i=n&&n.length>0&&n[0];if(i){let o=i.getNodeName();return o.charAt(0)===Ri.StartTag?o.substring(1):o}}}return null}get parametersNode(){let t=this.getChildren(y.parameters);return t.length===0?null:t[0]}async serializeParameters(t,r){let n=new er;switch(this.ClassId.guidString.toUpperCase()){case N.LookupControl:if(t&&t.getKeys())if(t.getKeys().forEach(a=>{n.add(a,this.getParam(a))}),t&&t.containsKey("DefaultViewId")){let a=this.getParam("DefaultViewId").replace("{","").replace("}","");n.upsert("DefaultViewId",a)}else{let a=this.getParent(),s=await r.formModelService.lookupControlService.populateDefaultView(this,a.getParentForm().entityName);s&&s.id&&n.upsert("DefaultViewId",s.id.replace("{","").replace("}",""))}break;default:t&&t.getKeys()&&t.getKeys().forEach(a=>{n.add(a,this.getParam(a))});break}let i=n.getInternalObject(),o=[];for(let a in i)i.hasOwnProperty(a)&&o.push({Name:a,Value:i[a]});return o}getIsUnbound(){return this.getProperty(y.isUnbound)==="true"}getAttributeTypeFromClassId(t){if(t)switch(t.toUpperCase()){case N.BooleanControl:case N.CheckboxControl:return 0;case N.DateTimeControl:return 2;case N.DecimalControl:return 3;case N.FloatingNumberControl:return 4;case N.IntegerControl:case N.DurationControl:case N.LanguageControl:case N.TimezoneControl:return 5;case N.LookupControl:return 6;case N.CurrencyControl:return 8;case N.PartyListControl:return 10;case N.ChoiceControl:case N.RelationshipRoleChoiceControl:return 11;case N.ChoiceStatusControl:return 13;case N.TextAreaControl:case N.TextboxControl:case N.LabelControl:case N.EmailAddressControl:case N.UrlControl:case N.TickerControl:case N.ButtonControl:case N.PhoneNumberControl:return 14;case N.ChoicesControl:return 24;default:return}return 14}async toJSON(t){let r=this.getParent(),n=t&&t.formModelService&&t.formModelService.getFormType()===dt.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 xs,ty=k(()=>{"use strict";zt();jo();Ru();se();St();xs=class extends _n{constructor(t){super(t)}get targetEntityType(){return this.getParam(y.targetEntityType)||q.EmptyString}set targetEntityType(t){this.setParameter(y.targetEntityType,t)}get viewId(){return q.StripBraces(this.getParam(y.viewId))||q.EmptyString}set viewId(t){this.setParameter(y.viewId,q.AddBraces(t))}get viewIds(){return this.getParam(y.viewIds)||q.EmptyString}set viewIds(t){this.setParameter(y.viewIds,t)}get relationshipName(){return this.getParam(y.RelationshipName)||q.EmptyString}set relationshipName(t){this.setParameter(y.RelationshipName,t)}get isUserView(){return q.IsStrictTrue(this.getParam(y.isUserView))}set isUserView(t){this.setParameter(y.isUserView,t.toString())}get enableViewPicker(){return q.IsStrictTrue(this.getParam(y.enableViewPicker))}set enableViewPicker(t){this.setParameter(y.enableViewPicker,t)}get autoExpand(){return this.getParent().autoexpand&&this.getParam(y.autoExpand)===y.Auto}set autoExpand(t){let r=this.getParent();this.setParameter(y.autoExpand,t?y.Auto:y.Fixed),r.autoexpand=t}get recordsPerPage(){return this.getParam(y.recordsPerPage)?Number(this.getParam(y.recordsPerPage)):Number(y.RecordsPerPageRAControlDefault)}set recordsPerPage(t){this.setParameter(y.recordsPerPage,String(t))}get enableQuickFind(){return q.IsStrictTrue(this.getParam(y.enableQuickFind))}set enableQuickFind(t){this.setParameter(y.enableQuickFind,t)}get teamTemplateId(){return q.StripBraces(this.getParam(y.teamTemplateId))||q.EmptyString}set teamTemplateId(t){this.setParameter(y.teamTemplateId,q.AddBraces(t))}get chartId(){return this.getParam(y.visualizationId)||q.EmptyString}set chartId(t){this.setParameter(y.visualizationId,t)}get enableChartPicker(){return q.IsStrictTrue(this.getParam(y.enableChartPicker))}set enableChartPicker(t){this.setParameter(y.enableChartPicker,t)}get chartGridMode(){switch(this.getParam(y.chartGridMode)){case nn.Chart:return nn.Chart;case nn.Grid:return nn.Grid;default:return nn.All}}set chartGridMode(t){this.setParameter(y.chartGridMode,t)}updateChartGridMode(t){t?this.chartGridMode=nn.Chart:this.chartGridMode=this.enableChartPicker?nn.All:nn.Grid}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case y.targetEntityType:n.getAllChildren()[0].setNodeName("<"+r.targetEntityType);break;case y.viewId:n.getAllChildren()[0].setNodeName("<"+q.AddBraces(r.viewId));break;case y.isUserView:n.getAllChildren()[0].setNodeName("<"+r.isUserView);break;case y.enableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.enableViewPicker);break;case y.RelationshipName:let i=n.getAllChildren(),o="<"+r.relationshipName;i.length?n.getAllChildren()[0].setNodeName(o):n.addChild(new te(o,n));break;default:break}}updateControlDescription(t){let r=t.getControlDescriptionByForControl(this.UniqueId);if(r){let n=r.customControls;for(let i=0;i<n.length;i++){let o=n[i].getParameters().get(qt.dataset)?n[i].getParameters().get(qt.dataset)[0]:null;if(o){let a=o.getAllChildren();this.updateDefaultProperties(a,this)}else{let a=n[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(a,this)}}}}}});var $s,ry=k(()=>{"use strict";zt();jo();Ru();se();$s=class extends _n{constructor(t){super(t)}get defaultViewId(){return q.StripBraces(this.getParam(y.DefaultViewId))||q.EmptyString}set defaultViewId(t){this.setParameter(y.DefaultViewId,q.AddBraces(t))}get autoResolve(){return q.IsStrictTrue(this.getParam(y.AutoResolve))}set autoResolve(t){this.setParameter(y.AutoResolve,t)}get disableQuickFind(){return q.IsStrictTrue(this.getParam(y.DisableQuickFind))}set disableQuickFind(t){this.setParameter(y.DisableQuickFind,t)}get disableViewPicker(){return q.IsStrictTrue(this.getParam(y.DisableViewPicker))}set disableViewPicker(t){this.setParameter(y.DisableViewPicker,t)}get allowFilterOff(){return q.IsStrictTrue(this.getParam(y.AllowFilterOff))}set allowFilterOff(t){this.setParameter(y.AllowFilterOff,t)}get disableMru(){return q.IsStrictTrue(this.getParam(y.DisableMru))}set disableMru(t){this.setParameter(y.DisableMru,t)}get dependentAttributeName(){return this.getParam(y.DependentAttributeName)||q.EmptyString}set dependentAttributeName(t){this.setParameter(y.DependentAttributeName,t)}get dependentAttributeType(){return this.getParam(y.DependentAttributeType)||q.EmptyString}set dependentAttributeType(t){this.setParameter(y.DependentAttributeType,t)}get filterRelationshipName(){return this.getParam(y.FilterRelationshipName)||q.EmptyString}set filterRelationshipName(t){this.setParameter(y.FilterRelationshipName,t)}get availableViewIds(){return this.getParam(y.AvailableViewIds)||q.EmptyString}set availableViewIds(t){this.setParameter(y.AvailableViewIds,t)}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case y.datafieldname:case y.bindAttribute:n.getAllChildren()[0].setNodeName("<"+r.dataFieldName);break;case y.DefaultViewId:n.getAllChildren()[0].setNodeName("<"+q.AddBraces(r.defaultViewId));break;case y.AllowFilterOff:n.getAllChildren()[0].setNodeName("<"+r.allowFilterOff);break;case y.DisableQuickFind:n.getAllChildren()[0].setNodeName("<"+r.disableQuickFind);break;case y.DisableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.disableViewPicker);break;case y.FilterRelationshipName:n.getAllChildren()[0].setNodeName("<"+r.filterRelationshipName);break;case y.DependentAttributeName:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeName);break;case y.DependentAttributeType:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeType);break;case y.AvailableViewIds:n.getAllChildren()[0].setNodeName("<"+r.availableViewIds);break;case y.DisableMru:n.getAllChildren()[0].setNodeName("<"+r.disableMru);break;case y.AutoResolve:n.getAllChildren()[0].setNodeName("<"+r.autoResolve);break;default:break}}updateControlDescription(t){let r=t.getControlDescriptionByForControl(this.UniqueId);if(r){let n=r.customControls;for(let i=0;i<n.length;i++){let o=n[i].getParameters().get(qt.value)?n[i].getParameters().get(qt.value)[0]:null;if(o){let a=o.getAllChildren();this.updateDefaultProperties(a,this)}else{let a=n[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(a,this)}}}}}});var o2,ny,Ar,Lu=k(()=>{"use strict";o2=we(n2());vo();se();et();ct();ey();Ru();fu();c0();zg();An();ra();gs();ty();ry();iy();is();ny="_",Ar=class e extends jt{fieldPlaceholder;fieldRequiredLevel;isNewField;cellColType;dependentFields=[];constructor(t){super(C.formCell,t),this.isNewField=!1}get cellType(){return this.cellColType}set cellType(t){this.cellColType=t}setDefaultProperties(t){this.showlabel=t,this.isLocked=!1,P.IsNullOrUndefined(this.getProperty(y.id))&&(this.id=new U(U.NewGuid()))}addControl(t,r,n,i,o,a,s){n instanceof _n?this.addChild(n):n instanceof U&&this.addChild(this.getControlWithControlSpecificProperties(t,r,n,i,o,a,s))}removeControl(){return this.deleteChild(this.control)>=0}get isIndependent(){if(!P.IsNullOrUndefined(this.control))return P.IsNullOrUndefined(this.control.dataFieldName)?P.IsNullOrUndefined(this.control.id)?!0:!ia.dependencyFieldCount.containsKey(this.control.id):!ia.dependencyFieldCount.containsKey(this.control.dataFieldName)}createOnLoadEvent(){this.addEvent(new ks(this,iu.onLoad))}get dependencies(){let t=this.getChildren(C.formEvents);for(let r of t){let n=r.getChildren(C.formEvent);for(let i of n)this.buildDependencyList(i,this.dependentFields)}return this.dependentFields}getNextAvailableControlName(t,r,n,i){let o;if(i&&zd[i])o=zd[i].replace(/ /g,ny)+ny;else{o="Control_";let u=new Error("Control class id does not exist or is undefined");(0,o2.trackErrorTrace)(ir,{eventName:`${n_}/getNextAvailableControlName`},u)}let a="new_",s=this.getHighestIndexById(t,i)+1,l=`${o}${a}${s}`;for(;n.has(l);)s++,l=`${o}${a}${s}`;return l}getUnboundControlProperties(t){e.prototype.setProperty.call(t,y.isUnbound,"true"),e.prototype.setProperty.call(t,y.isRequired,"false")}getControlWithControlSpecificProperties(t,r,n,i,o,a,s){let l;o===an.Grid?(l=new xs(this),l.indicationOfSubgrid=!0):o===an.Lookup?l=new $s(this):l=new _n(this);let u=n.guidString,c=a||this.getNextAvailableControlName(t,i,this.getUsedNodeNameSet(t),u);if(e.prototype.setProperty.call(l,y.id,c),l.ClassId=n,!P.IsNullOrUndefined(s)&&(l.UniqueId=s),!a&&r)this.getUnboundControlProperties(l);else{let d=tt.getUniqueIdentifierForControl(l);P.IsNullOrUndefined(d)||(tt.getControlDataTypeByControlOrUniqueId(d)===ee.QuickFormCollectionControl||!tt.isUnboundFormControlByIdentifier(d)?o!==an.Grid&&a&&u!==N.IframeControl&&u!==N.SubgridControl&&u!==N.ReferencePanelSubgridControl&&(l.dataFieldName=a,e.prototype.setProperty.call(l,y.disabled,"false")):(this.rowspan=tt.GetRowSpan(l),(tt.getControlDataTypeByControlOrUniqueId(d)===ee.NotesControl||tt.getControlDataTypeByControlOrUniqueId(d)===ee.TimeLineControl)&&(e.prototype.setProperty.call(l,y.disabled,"false"),l.id=ee.NotesControl)),(tt.getUnboundControlNameFromIdentifier(n)===ee.SubGridControl||tt.getUnboundControlNameFromIdentifier(n)===ee.NotesControl||tt.getUnboundControlNameFromIdentifier(n)===ee.TimeLineControl)&&(this.availableforphone=!0))}return l}buildDependencyList(t,r){if(P.IsNullOrUndefined(t))return;let n=t.getAllChildren();for(let i of n){let o=i.getAllChildren();for(let a of o){let s=a.GetPropertyByParameter(y.id);a.getNodeName()===C.dependency&&s?r.push(s):this.buildDependencyList(a,r)}}}get control(){return this.getFirstChild(C.formControl)}set rowspan(t){this.setProperty(y.rowspan,String(t))}get rowspan(){let t=this.getProperty(y.rowspan);return P.IsNullOrUndefined(t)?1:parseInt(t,10)}set autoexpand(t){this.setProperty(y.auto,String(t))}get autoexpand(){return this.getProperty(y.auto)==="true"}set colspan(t){let r=Number(l0.ONE_COLUMN),n=Number(l0.FOUR_COLUMN);P.IsNullOrUndefined(t)||t>n||t<r||this.setProperty(y.colspan,String(t))}get colspan(){let t=this.getProperty(y.colspan);return P.IsNullOrUndefined(t)?1:parseInt(t,10)}getParentRow(){return this.getAncestor(C.formRow)}getParentSection(){return this.getAncestor(C.formSection)}getParentTab(){return this.getAncestor(C.formTab)}getParentForm(){return this.getAncestor(C.form)}isInHeader(){let t=this.getAncestor(C.formHeader);return!P.IsNullOrUndefined(t)}isInFooter(){let t=this.getAncestor(C.formFooter);return!P.IsNullOrUndefined(t)}isEmpty(){return P.IsNullOrUndefined(this.control)&&!this.IsUserSpacer}getHeaderFooter(){return this.isInHeader()?this.getAncestor(C.formHeader):this.isInFooter()?this.getAncestor(C.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(y.userspacer);return P.IsNullOrUndefined(t)?!1:t==="true"}SetUserSpacer(){this.setProperty(y.userspacer,"true")}ClearUserSpacer(){this.setProperty(y.userspacer,"false")}get columns(){let t=this.getProperty(y.columnName);return P.IsNullOrUndefined(t)?null:parseInt(t,10)}getColumnLayoutValue(t){let r;switch(t){case Ge.TWO_COLUMN:r="11";break;case Ge.THREE_COLUMN:r="111";break;case Ge.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(!P.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();P.IsNullOrUndefined(t)||(t.autoExpandCell=this,t.tabContainsAutoExpandControl=!0)}isCellRequiredOrLocked(t,r,n){let i=this.getParentForm();if(this?.control){if(this.IsUserSpacer)return!1;{if(this.isLocked||r().has(this.control.dataFieldName))return!0;let o=i.isDuplicateCell(this,n),a=this.getRequiredLevel(t);if((a===no.ApplicationRequired||a===no.SystemRequired)&&!o||this.isCellLockedByExternal(t)&&!o)return!0}}return!1}getRequiredLevel(t){return!this.control?.dataFieldName||!this.control?.id||this.IsNewField||!this.control?.ClassId?no.None:t.getEntityAttributeByName(this.control.dataFieldName)?.requiredLevel?.toString()??no.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()===C.formCell){let i=n;i.control&&i!==this&&r.add(n.control.id)}return!1}),r}getHighestIndexById(t,r){let n=t.findAll(o=>o.getNodeName()===C.formCell&&o.control&&o.control.ClassId.guidString===r),i=0;return n.forEach(o=>{i=Math.max(this.parseControlNameIndex(o.control.id),i)}),i}parseControlNameIndex(t){let r=t.length-1,n=0;for(;r>0&&parseInt(t.charAt(r),10);)r--;return r>0&&r!==t.length-1&&t.charAt(r)===ny&&(r++,n=parseInt(t.substr(r,t.length-r),10)),n}}});var Fs,oy=k(()=>{"use strict";zt();se();St();Fs=class extends te{isInternal;constructor(t,r,n,i){super(C.library,t),this.isInternal=!!i,q.IsNullOrEmpty(n)||(this.name=r,this.libraryUniqueId=n)}get libraryUniqueId(){let t=this.getProperty(y.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(y.libraryUniqueId,t)}get name(){return this.getProperty(y.libraryName)}set name(t){this.setProperty(y.libraryName,t)}get displayName(){return this.getProperty(y.displayName)}set displayName(t){this.setProperty(y.displayName,t)}get description(){return this.getProperty(y.description)}set description(t){this.setProperty(y.description,t)}}});var ca,ay=k(()=>{"use strict";et();Lu();se();St();ca=class extends te{isRowAddedOnDragOver;constructor(t){super(C.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 P.IsNullOrUndefined(t)?!1:this.deleteChild(t)>=0}insertCellAtIndex(t,r){return P.IsNullOrUndefined(t)?!1:(this.insertChildAtIndex(t,r),!0)}isEmpty(){return!this.cells||this.cells.every(t=>t.isEmpty())}getParentSection(){return this.getAncestor(C.formSection)}insertPaddingCellAtIndex(t){let r=new Ar(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(C.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 rQ(e){switch(e){case oa.Left:return sa.Left;case oa.Right:return sa.Right;case oa.Center:return sa.Center;default:return sa.Left}}function nQ(e){switch(e){case bs.Left:return vs.Left;case bs.Top:return vs.Top;default:return vs.Left}}function a2(e){switch(e){case 1:return 1;case 2:return 11;case 3:return 111;case 4:return 1111;default:return 1}}var iQ,ei,ku=k(()=>{"use strict";d0();ct();et();zt();X0();Lu();se();An();vo();ay();iQ=115,ei=class e extends jt{colSpan=1;constructor(t,r){super(t,r)}getSectionType(){let t;switch(this.columns){case 1:t=Ge.ONE_COLUMN;break;case 11:t=Ge.TWO_COLUMN;break;case 111:t=Ge.THREE_COLUMN;break;case 1111:t=Ge.FOUR_COLUMN;break;default:t=this.colSpan-1}return t}setUniqueName(){let t=this.getParentTab(),r=Ue.namePrefix;if(t){let n=t.Name,i=t.TotalSectionsCount+1;r=n+Ue.namePrefix+i.toString()}else r+=Math.floor(Math.random()*1e3);this.setProperty(y.Name,r)}initializeDefaultProperties(t,r,n){if(n===Ge.REFERENCE_PANEL){this.addProperty(y.rowheight,"25");let i=`${Ue.referencePanelNamePrefix}${U.NewGuid()}${Ue.namePrefix}`;this.addProperty(y.Name,i)}else this.setUniqueName();if(this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.IsUserDefined,Ue.IsUserDefined),this.addProperty(y.locklevel,Ue.LockLevel),this.addProperty(y.showlabel,Ue.ShowLabel),this.addProperty(y.showbar,Ue.ShowBar),this.addProperty(y.layout,Ue.Layout),this.addProperty(y.Fieldlabelalignment,Ue.labelAlignment),this.addProperty(y.Fieldlabelposition,Ue.labelPosition),P.IsNullOrUndefined(n))this.addProperty(y.columnName,Ue.columns);else{let i=this.getColumnLayoutValue(n);this.addProperty(y.columnName,i)}this.addProperty(y.LabelWidth,Ue.LabelWidth),this.setDisplayName(r,t)}getColumnLayoutValue(t){let r;switch(t){case Ge.TWO_COLUMN:r="11";break;case Ge.THREE_COLUMN:r="111";break;case Ge.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 P.IsNullOrUndefined(this.columns)?t=this.ColSpan:this.columns.toString().split(q.EmptyString).forEach(r=>{t+=parseInt(r,10)}),t}get ColSpan(){return this.colSpan}initializeRow(t){if(t>0&&t<5){let r=new ca(null);if(this.addGrandChild(C.formRows,r),ZR.getConfig().enableAutoInsertionOfCellInRow)for(let n=0;n<t;n++){let i=new Ar(r);i.setDefaultProperties(!1),r.addCell(i)}}}initialize(t,r,n){this.initializeDefaultProperties(t,r,n),n===Ge.REFERENCE_PANEL&&(n=Ge.ONE_COLUMN),this.initializeRow(n+1)}setColSpan(t){this.colSpan=t}appendRow(t){this.addGrandChild(C.formRows,t)}insertRowAtIndex(t,r){this.addGrandChildAtIndex(C.formRows,t,r)}insertRowsAtIndex(t,r){if(t&&t.length>0)for(let n=0;n<t.length;n++)this.addGrandChildAtIndex(C.formRows,t[n],r+n)}indexOfRow(t){return this.rows.indexOf(t)}deleteRow(t){return this.deleteFirstGrandChildOfName(C.formRows,t)}deleteRows(t,r){this.deleteGrandChildren(C.formRows,t,r)}get rows(){return this.getRows()}getRows(){let t=this.getChildren(C.formRows);return t.length===0?[]:t[0].getChildren(C.formRow)}get columns(){let t=this.getProperty(y.columnName),r=P.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 a2(n)}return r}set columns(t){P.IsNullOrUndefined(t)||this.setProperty(y.columnName,String(t))}get rowHeight(){let t=this.getProperty(y.rowheight);return P.IsNullOrUndefined(t)?null:parseInt(t,10)}set rowHeight(t){this.setProperty(y.rowheight,String(t))}set autoexpand(t){this.setProperty(y.autoExpand.toLowerCase(),String(t))}get autoexpand(){return this.getProperty(y.autoExpand.toLowerCase())==="true"}get isUserDefined(){return+this.getProperty(y.IsUserDefined)!=0}set isUserDefined(t){t?this.setProperty(y.IsUserDefined,"1"):this.setProperty(y.IsUserDefined,"0")}getParentColumn(){return this.getAncestor(C.formColumn)}getParentTab(){return this.getAncestor(C.formTab)}get hasMultiColumnRow(){return this.getColumnCountValue()>1}get showlabel(){return this.getProperty(y.showlabel)==="true"}set showlabel(t){P.IsNullOrUndefined(t)||this.setProperty(y.showlabel,String(t))}get fieldLabelAlignment(){let t=Ue.labelAlignment,r=this.getProperty(y.Fieldlabelalignment);return P.IsNullOrUndefined(r)?t:r}set fieldLabelAlignment(t){P.IsNullOrUndefined(t)||this.setProperty(y.Fieldlabelalignment,t)}get fieldLabelPosition(){let t=this.getProperty(y.Fieldlabelposition);return P.IsNullOrUndefined(t)?Ue.labelPosition:t}set fieldLabelPosition(t){P.IsNullOrUndefined(t)||this.setProperty(y.Fieldlabelposition,String(t))}get showbar(){return this.getProperty(y.showbar)==="true"}set showbar(t){P.IsNullOrUndefined(t)||this.setProperty(y.showbar,String(t))}get labelwidth(){let t=+this.getProperty(y.LabelWidth);return t===0?iQ:t}set labelwidth(t){P.IsNullOrUndefined(t)||t>283&&t<57||this.setProperty(y.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:rQ(this.fieldLabelAlignment),Position:nQ(this.fieldLabelPosition)},Columns:a2(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()===C.formSection){let i=n;i.Name&&!q.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}isReferencePanelSection(){return!P.IsNullOrUndefined(this)&&!P.IsNullOrUndefined(this.Name)&&this.Name.indexOf(Ue.referencePanelNamePrefix)===0}getAllMultiRowCells(){return this.findAll(t=>{if(t.getNodeName()===C.formCell){let r=t;return!r.isEmpty()&&r.rowspan>1}return!1})}isHeaderOrFooterSection(){return this.NodeName===C.formFooter||this.NodeName===C.formHeader}}});var wo,wf=k(()=>{"use strict";se();St();ku();wo=class e extends te{constructor(t){super(C.formColumn,t)}initializeDefaultProperties(t){this.addProperty(y.width,t.toString()+"%")}insertSectionAtIndex(t,r){this.addGrandChildAtIndex(C.formSections,t,r)}static createAndInitNewSection(t,r,n){let i=new ei(C.formSection,null);return i.initialize(t,r,n),i}addSectionAtIndex(t,r){this.addGrandChildAtIndex(C.formSections,t,r)}initialize(t,r,n,i=Ge.ONE_COLUMN){this.initializeDefaultProperties(t);let o=e.createAndInitNewSection(r,n,i);this.addSectionAtIndex(o,this.sections.length),o.setUniqueName()}get parentTab(){return this.getAncestor(C.formTab)}get sections(){let t=this.getChildren("sections");return t.length!==1?[]:t[0].getChildren(C.formSection)}get width(){return this.getProperty(y.width)}set width(t){this.setProperty(y.width,t)}deleteSection(t){return this.deleteFirstGrandChildOfName(C.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(y.Name),Id:this.getProperty(y.id),Label:null,ShowLabel:!1,Visible:!0,LabelId:null,PreviewId:this.getProperty(y.id),Sections:await this.getSectionsJSON(t),Width:this.width}}}});var Cf,s2=k(()=>{"use strict";ct();se();An();ku();Cf=class extends ei{initializeNavArea(t,r,n){this.initializeNavAreaProps(t,r,n)}get AreaName(){return this.Name}initializeNavAreaProps(t,r,n){this.addProperty(y.Name,n),this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.columnName,Ue.columns),this.setDisplayName(r,t)}}});var Ef,l2=k(()=>{"use strict";wf();se();s2();Ef=class extends wo{addAndIntializeNavBarSection(t,r,n,i){let o=new Cf(C.formSection,null);return o.initializeNavArea(t,r,i),this.addGrandChildAtIndex(C.formSections,o,n),o}}});var ki,Af=k(()=>{"use strict";ct();et();zt();wf();se();St();vo();ki=class extends jt{tabContainsAutoExpandControl;autoExpandCell;constructor(t,r){super(C.formTab,t),this.tabContainsAutoExpandControl=!1}getParentForm(){return this.getAncestor(C.form)}getTabLayoutType(){let t;switch(this.columns.length){case 1:t=Ve.ONE_COLUMN;break;case 2:if(parseInt(this.columns[0].width,10)===50&&parseInt(this.columns[1].width,10)===50){t=Ve.TWO_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===67&&parseInt(this.columns[1].width,10)===33){t=Ve.TWO_COLUMN_WIDER_LEFT;break}if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===66){t=Ve.TWO_COLUMN_WIDER_RIGHT;break}t=Ve.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=Ve.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=Ve.THREE_COLUMN_WIDER_MID;break}t=Ve.THREE_COLUMN_CUSTOM_LAYOUT;break;default:}return t}initializeProperties(t,r,n){this.addProperty(y.Name,mo.namePrefix+t.toString()),this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.IsUserDefined,mo.IsUserDefined),this.addProperty(y.locklevel,mo.LockLevel),this.addProperty(y.showlabel,mo.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=Ge.ONE_COLUMN,o=!0,a){let s=this.getChildren(C.formColumns)[0],l=[];switch(t){case Ve.ONE_COLUMN:l.push(100);break;case Ve.TWO_COLUMN_EQUAL:l.push(50),l.push(50);break;case Ve.TWO_COLUMN_WIDER_LEFT:l.push(67),l.push(33);break;case Ve.TWO_COLUMN_WIDER_RIGHT:l.push(34),l.push(66);break;case Ve.THREE_COLUMN_EQUAL:l.push(34),l.push(33),l.push(33);break;case Ve.THREE_COLUMN_WIDER_MID:l.push(28),l.push(44),l.push(28);break;default:}for(let u of l){let c=new wo(s);c.initialize(u,r,n,i),this.addGrandChild(C.formColumns,c)}}initialize(t,r,n,i,o,a=Ge.ONE_COLUMN,s=!0,l){this.addChild(new te(C.formColumns,this)),this.initializeProperties(r,n,i),this.initializeColumns(t,n,o,a,s,l)}get columns(){let t=this.getChildren(C.formColumns);return t.length!==1?[]:t[0].getChildren(C.formColumn)}get expanded(){return this.getProcessedValue(y.expanded)}set expanded(t){P.IsNullOrUndefined(t)||this.setProperty(y.expanded,String(t))}get groupName(){return this.getProperty(y.groupName)}get contentType(){return this.getProperty(y.contentType)}set contentType(t){this.setProperty(y.contentType,t)}insertNewColumnAtIndex(t,r,n,i,o){t.initialize(n,i,o),this.addGrandChildAtIndex(C.formColumns,t,r)}insertColumnAtIndex(t,r){this.addGrandChildAtIndex(C.formColumns,t,r)}deleteColumn(t){return this.deleteFirstGrandChildOfName(C.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()===C.formTab){let i=n;i.Name&&!q.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}}});var da,sy=k(()=>{"use strict";ct();se();St();An();l2();Af();da=class extends ki{constructor(t,r,n){super(t,Ve.THREE_COLUMN_EQUAL),this.setDisplayName(r,n),this.id=new U(U.NewGuid())}initializeDefaultProps(){this.addChild(new te(C.formColumns,this)),this.initializeFiveColumns()}get columns(){let t=this.getChildren("columns");return t.length!==1?[]:t[0].getChildren(C.formColumn)}getNavSectionForArea(t){for(let r of this.columns)for(let n of r.sections)if(n.AreaName===t)return n;return null}getNavCellFromNavId(t){for(let r of this.columns)for(let n of r.sections)for(let i of n.rows)for(let o of i.cells)if(o.NavId===t)return o;return null}initializeFiveColumns(){for(let t=0;t<tf.FIVE_COLUMN;t++){let r=new Ef(this.getChildren(C.formColumns)[0]);r.initializeDefaultProperties(D_.FiveEqColumn),this.addGrandChild(C.formColumns,r)}}}});function aQ(e){switch(e){case dt.Main:return ho.Main;case dt.QuickCreate:return ho.QuickCreate;case dt.QuickViewForm:return ho.Quick;case dt.Dialog:return ho.Dialog;default:return ho.None}}function sQ(e,t){if(t===dt.Main){if(e)switch(e.toLowerCase()){case"low":return po.Low;case"highreadonlyvalues":return po.HighReadOnlyValues;default:return po.HighWithControls}return po.Low}}var Nf,oQ,Sf,u2=k(()=>{"use strict";$_();Nf=we(na());d0();et();zt();gs();X0();se();jo();Rg();ra();Lu();se();vo();oy();sy();Af();oQ="1920";Sf=class e extends jt{_formUniqueName;isHeaderDefaulted;consistencyStrong=!1;_formId;_rawFormXml;_entityName;_entityDisplayName;_status;_formName;_langCode;_description;_formType;_formPresentation;parameters=[];_formactivationstate;_changeTracker;_metadataChangeEvent;_etag;constructor(t,r,n,i,o,a,s,l,u){super(C.form,null),this._formUniqueName=o,this._formId=t,this._entityName=r,this._status=n,this._formName=i,this._description=l,this._formType=a,this._formPresentation=s,this._formactivationstate=u,this._changeTracker=new qd,this._metadataChangeEvent=new nf}get FormLibraries(){let t=this.getFirstChild(C.formLibraries),r=t?t.getAllChildren():[],n=this._getInternalLibraries();return r.concat(n)}getAllEvents(){let t=[],r=this.events;r&&(t=t.concat(r));for(let n of this.tabs){let i=n.events;i&&(t=t.concat(i)),n.findAll(o=>o instanceof Ar).forEach(o=>{let a=o.events;a&&(t=t.concat(a))})}return t}getEventsForNode(t){if(t instanceof e){let r=t.events;return r?r.filter(n=>!n.control&&!n.attribute):null}else if(t instanceof Ar){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()===C.internalLibraries),r=[],n="src";return t.length>0&&(r=t.map(i=>{let o=i.GetPropertyByParameter(n).replace("$webresource:",""),a=new Fs(void 0,void 0,"",!0);return a.name=o,a.displayName=o,a})),r}getDependentFields(){let t=this.getAllEvents(),r=new Set;return t.forEach(n=>{try{n.getAllDependencies().forEach(o=>{r.add(o.id)})}catch(i){throw(0,Nf.trackErrorTrace)(i_,{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 q.IsNullOrEmpty(this.getProperty(y.ShowImage))?!0:this.getProperty(y.ShowImage)!=="false"}set ShowImagecheck(t){t?this.setProperty(y.ShowImage,String(t)):this.setProperty(y.ShowImage,"false")}get ShowNavigation(){return q.IsNullOrEmpty(this.getProperty(y.ShowNavigationbar))?!0:this.getProperty(y.ShowNavigationbar)!=="false"}set ShowNavigation(t){t?this.setProperty(y.ShowNavigationbar,String(t)):this.setProperty(y.ShowNavigationbar,"false")}get MaxWidth(){return q.IsNullOrEmpty(this.getProperty(y.MaxWidth))?oQ:this.getProperty(y.MaxWidth)}set MaxWidth(t){this.setProperty(y.MaxWidth,t)}get headerDensityType(){return this.getProperty(y.HeaderDensityType)}set headerDensityType(t){t&&this.formType===dt.Main?this.setProperty(y.HeaderDensityType,t):this.formType!==dt.Main&&this.headerDensityType&&this.removeProperty(y.HeaderDensityType)}IsMainOrQuickCreateForm(){return this.formType===dt.Main||this.formType===dt.QuickCreate}get FormPresentation(){return this._formPresentation}get LanguageCode(){return this._langCode}set LanguageCode(t){this._langCode=t}get header(){let t=this.getChildren(C.formHeader);return t.length!==1?null:t[0]}set header(t){P.IsNullOrUndefined(t)||(this.deleteChild(this.header),this.addChild(t))}getAllDependencies(){return this.getChildren(C.quickFormDependencies).length===0?[]:this.ConvertModelToArray(this.getChildren(C.quickFormDependencies)[0].getAllChildren())}ConvertModelToArray(t){let r=[];return P.IsNullOrUndefined(t)||t.forEach(n=>{r.push(n.id)}),r}get footer(){let t=this.getChildren(C.formFooter);return t.length!==1?null:t[0]}set footer(t){P.IsNullOrUndefined(t)||(this.deleteChild(this.footer),this.addChild(t))}createAndInitNewTab(t,r,n){let i=new ki(null,t),o=this.getNextTabCounter(this.tabs.length+1);return i.initialize(t,o,this.LanguageCode,r,n),i}addTabAtIndex(t,r){this.addGrandChildAtIndex(C.formTabs,t,r)}createAndInitNewTabWithMarginalControl(t,r,n,i,o){let a=new ki(null,Ve.ONE_COLUMN),s=this.getNextTabCounter(this.tabs.length+1);a.initialize(Ve.ONE_COLUMN,s,this.LanguageCode,r,n,o,!1),this.addGrandChildAtIndex(C.formTabs,a,i);let l=a.columns[0].sections[0];for(let u=0;u<t.rows.length;u++)l.appendRow(t.rows[u])}getNextTabCounter(t){for(let r=0;r<this.tabs.length;r++)if(this.tabs[r].Name===mo.namePrefix+t.toString())return this.getNextTabCounter(t+1);return t}get allTabs(){let t=this.getChildren(C.formTabs);return t.length!==1?[]:t[0].getChildren(C.formTab)}get CanvasNavigationTab(){if(this.tabs.length>0){let t=this.tabs[this.tabs.length-1];if(t instanceof da)return t}return null}get NavigationNode(){let t=this.getChildren(C.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(C.formTabs,t)}insertTabAtIndex(t,r){this.addGrandChildAtIndex(C.formTabs,t,r)}insertRelatedTab(t){let r=this.getAllGrandChildren(C.formTabs);if(!P.IsNullOrUndefined(r)){let n=r.length;this.insertTabAtIndex(t,n)}}get isfooterPresent(){return this.getChildren(C.formFooter).length>0}get displayCondition(){let t=this.getChildren(C.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(C.formTabs).indexOf(t)}get ControlDescriptions(){return this.getAllGrandChildren(C.controlDescriptions)}addControlDescriptionNode(t){this.addGrandChild(C.controlDescriptions,t)}deleteControlDescByForControlId(t){let r=this.getControlDescriptionByForControl(t);P.IsNullOrUndefined(r)||this.deleteFirstGrandChildOfName(C.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 Ar))return!1;let o=!0;return r==="Tab"?o=i.getParentTab()!==t.getParentTab():r==="Section"?o=i.getParentSection()!==t.getParentSection():o=i!==t,i instanceof Ar&&i.control&&t.control&&o&&i.control.dataFieldName===t.control.dataFieldName})}isCellEditableGridControl(t){return!t?.control?.indicationOfSubgrid||t.control.ClassId.guidString.toUpperCase()!==N.CustomControl?!1:this.cellHasCustomControlWithName(t,Si.EditableGridControl)||e2.getConfig()?.enableOneGridEventsForFormDesigner&&this.cellHasCustomControlWithName(t,Si.PowerAppsOneGrid)}isCellCanvasAppControl(t){return t?.control?.ClassId.guidString.toUpperCase()===N.CustomControl&&this.cellHasCustomControlWithName(t,Si.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()===C.formCell){let i=n;return i&&i.control&&i.control.ClassId.guidString===t}return!1}):null}async getTabsJSON(t){let r=this.tabs,n=[],i=[];if(r){for(let o of r)if(!(o instanceof da)){let a=o.toJSON(t);n.push(a)}for(let o of n)i.push(await o)}return i}async getControlDescriptionsToJSON(t){let r=[];for(let n of this.ControlDescriptions){let i=await n.toJSON(t);i&&r.push(i)}return r}async toJSON(t){let r=[];r=await this.getControlDescriptionsToJSON(t);let n=this.NavigationNode&&await this.NavigationNode.toJSON(t);return{Id:this._formId.guidString,Name:this.formName,Label:this.getDisplayName(t.langCode),ShowLabel:this.showlabel,Visible:this.visible,LabelId:this.labelId&&this.labelId.guidString,PreviewId:this._formId.guidString,PreviewSessionId:(0,Nf.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===dt.Main?{HeaderDensity:sQ(this.headerDensityType,this.formType)}:{},InlineEditGridRow:[],InlineQuickForms:[],QuickFormEntities:[],EventHandlers:[],LinkControlSections:[],FormType:aQ(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 _f,ly,c2=k(()=>{"use strict";ct();et();se();St();vo();_f=class extends jt{constructor(t){super(C.formDisplayConditions,t)}get Order(){let t=this.getProperty(y.Order);return P.IsNullOrUndefined(t)?null:parseInt(t,10)}set Order(t){this.setProperty(y.Order,t.toString())}get FallbackForm(){return this.getProperty(y.FallbackForm)==="true"}set FallbackForm(t){this.setProperty(y.FallbackForm,t.toString())}addRoles(t){this.deleteAllChildren();for(let r=0;r<t.length;r++)this.addChild(t[r])}isRoleEveryone(){return!!(this.getChildren(C.formEveryOne)&&this.getChildren(C.formEveryOne)[0])}setRoleEveryone(){this.deleteAllChildren(),this.addChild(new ly(this))}},ly=class extends te{constructor(t){super(C.formEveryOne,t)}}});var Tf,d2=k(()=>{"use strict";se();St();Tf=class extends te{constructor(t,r){super(C.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(y.HandlerUniqueId)}set HandlerUniqueID(t){this.setProperty(y.HandlerUniqueId,t)}get FunctionName(){return this.getProperty(y.functionName)}set FunctionName(t){this.setProperty(y.functionName,t)}get LibraryName(){return this.getProperty(y.libraryNameEventHandler)}set LibraryName(t){this.setProperty(y.libraryNameEventHandler,t)}get Enabled(){return this.getProperty(y.enabledForField)}set Enabled(t){this.setProperty(y.enabledForField,t)}get PassExecutionContext(){return this.getProperty(y.passExecutionContext)}set PassExecutionContext(t){this.setProperty(y.passExecutionContext,t)}get Parameters(){return this.getProperty(y.parameters)}set Parameters(t){this.setProperty(y.parameters,t)}}});var Ms,uy=k(()=>{"use strict";se();ku();Ms=class extends ei{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(C.formCell);for(let o of i)r.push(o)}}return r}get occupiedCells(){return this.cells.filter(t=>!t.isEmpty())}get maxColumns(){return super.getColumnCountValue()}}});var xu,f2=k(()=>{"use strict";se();uy();xu=class extends Ms{_customFooter;constructor(t,r){super(C.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 $u,p2=k(()=>{"use strict";se();uy();$u=class extends Ms{_customHeader;constructor(t,r){super(C.formHeader,t),this._customHeader=r}get customHeader(){return this._customHeader}set customHeader(t){this._customHeader=t}get showCommandBar(){return this.getProcessedValue(y.showCommandBar)}set showCommandBar(t){t!=null&&this.setProperty(y.showCommandBar,String(t))}get showBody(){return this.getProcessedValue(y.showBody)}set showBody(t){t!=null&&this.setProperty(y.showBody,String(t))}get showTabNavigator(){return this.getProcessedValue(y.showTabNavigator)}set showTabNavigator(t){t!=null&&this.setProperty(y.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 Sr,fa=k(()=>{"use strict";ct();zt();se();vo();Sr=class e extends jt{constructor(t,r){super(t,r)}getTitle(t){for(let r of this.getAllTitles())if(+r.getProperty(y.LCID)===t)return r.getProperty(y.text);return null}getAllTitles(){let t=this.getChildren(C.Titles);return t.length===0?[]:t[0].getChildren(C.Title)}setTitle(t,r){for(let i of this.getAllTitles())if(+i.getProperty(y.LCID)===r){i.setProperty(y.text,t);return}let n=new e(C.Title,null);n.setProperty(y.text,t),n.setProperty(y.LCID,String(r)),this.addGrandChild(C.Titles,n)}get Sequence(){return+this.getProperty(y.Sequence)}set Sequence(t){this.setProperty(y.Sequence,t.toString())}get Area(){return this.getProperty(y.Area)}set Area(t){this.setProperty(y.Area,t)}set Id(t){this.setProperty(y.Id,t)}get Id(){return this.getProperty(y.Id)}get id(){return new U(this.Id??"",!0)}set id(t){this.Id=t.guidString}get Show(){return!0}get Icon(){return this.getProperty(y.icon)}set Icon(t){t=t||q.EmptyString,this.setProperty(y.icon,t)}updateCommonProperties(t,r){this.Area=t.Area,this.Sequence=t.Sequence,this.setTitle(t.getDisplayName(r),r)}}});var Fu,m2=k(()=>{"use strict";(function(e){e[e.NavLinkNotAvailable=-1]="NavLinkNotAvailable",e[e.NavLinkIdConflict=-2]="NavLinkIdConflict",e[e.NavBarNotAvailable=-3]="NavBarNotAvailable"})(Fu||(Fu={}))});var Df,h2=k(()=>{"use strict";et();se();fa();m2();Df=class extends Sr{constructor(t){super(C.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 P.IsNullOrUndefined(r)?Fu.NavLinkNotAvailable:r.length===1?this.deleteChild(r[0]):Fu.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 $e,lQ,g2,Lge,Us,cy=k(()=>{"use strict";ct();se();fa();(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"})($e||($e={}));lQ=new Map([[$e.Info,"Info"],[$e.Sales,"Sales"],[$e.Service,"Service"],[$e.Marketing,"Marketing"],[$e.ProcessCenter,"ProcessCenter"]]),g2=new Map([["Info",$e.Info],["Sales",$e.Sales],["Service",$e.Service],["Marketing",$e.Marketing],["ProcessCenter",$e.ProcessCenter]]),Lge=new Map([[$e.Info,9e3],[$e.Sales,9200],[$e.Service,9400],[$e.Marketing,9600],[$e.ProcessCenter,9800],[$e.InternetMarketing,1e4],[$e.Async,10200]]),Us=class extends Sr{constructor(t,r){super(C.formNavBarArea,r)}setDefaultPropertiesByType(t,r,n){this.AreaId=lQ.get(t);let i=n?.(`navBarArea.title.${this.AreaId}`)??this.AreaId;this.setTitle(i,r)}get ParentNavigation(){return this.getAncestor(C.formNavigation)}get AreaId(){return this.getProperty(y.Id)}set AreaId(t){this.setProperty(y.Id,t)}get id(){return new U(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 Bs,dy=k(()=>{"use strict";se();fa();Bs=class extends Sr{constructor(t,r){super(C.formNavBarAreas,r)}get AllNavBarAreaItems(){return this.getChildren(C.formNavBarArea)}get ParentNavigation(){return this.getAncestor(C.formNavigation)}addNavBarArea(t){this.addChild(t)}}});var If,y2=k(()=>{"use strict";et();se();fa();If=class extends Sr{RelationshipNameUCIRuntime;constructor(t){super(C.formNavBarByRelationshipItem,t)}get RelationshipName(){return this.getProperty(y.RelationshipName)}set RelationshipName(t){this.setProperty(y.RelationshipName,t)}set Show(t){this.setProperty(y.Show,String(t))}get Show(){let t=this.getProperty(y.Show);return P.IsNullOrUndefined(t)||t==="true"}get TitleResourceId(){return this.getProperty(y.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 Of,b2=k(()=>{"use strict";se();fa();Of=class extends Sr{constructor(t){super(C.formNavBarItem,t)}get Url(){return this.getProperty(y.url)}set Url(t){this.setProperty(y.url,t)}}});var Pf,v2=k(()=>{"use strict";ct();se();cy();dy();fa();Pf=class extends Sr{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(C.formNavBarAreas)}setDefaultNavBarAreas(t,r){let n=[$e.Info,$e.Sales,$e.Service,$e.Marketing,$e.ProcessCenter];if(this.navBarAreas){let i=this.navBarAreas?.AllNavBarAreaItems;if(i&&i.length>0){let o=new Set(i.map(a=>g2.get(a.AreaId)));n=n.filter(a=>!o.has(a))}}else{let i=new Bs(C.formNavBarAreas,this);i.isTransient=!0,this.addChild(i)}return n.length>0?(n.forEach(i=>{let o=new Us(C.formNavBarArea,this.navBarAreas);o.setDefaultPropertiesByType(i,t,r),this.navBarAreas.addNavBarArea(o)}),!0):!1}get navBar(){return this.getFirstChild(C.formNavBar)}get id(){return new U(Wg,!0)}replaceNavAreaToGivenIndex(t,r){this.navBarAreas?.AllNavBarAreaItems.indexOf(r)!==-1&&(this.deleteFirstGrandChildOfName(C.formNavBarAreas,r),this.addGrandChildAtIndex(C.formNavBarAreas,r,t))}async getNavBarAreasJSON(t){let r=[],n=[];if(this.navBarAreas?.AllNavBarAreaItems){for(let o of this.navBarAreas.AllNavBarAreaItems)n.push(o.toJSON(t));r=await Promise.all(n)}return r}async getNavBarRelationshipItemsJSON(t){let r=[],n=[];if(this.navBar?.AllRelationShipItems){for(let i of this.navBar.AllRelationShipItems)n.push(i.toJSON(t));r=await Promise.all(n)}return r}async toJSON(t){let r=await this.getNavBarAreasJSON(t),n=await this.getNavBarRelationshipItemsJSON(t);return{NavBarAreas:{NavBarAreas:r},NavBarByRelationshipItems:n,NavBarItems:[],NavPaneIsvItems:{NavBarIsvItems:[]},ShowEmptyNavBarAreas:t.formModelService.showHiddenElements}}}});var w2={};jr(w2,{ControlType:()=>an,DeserializationService:()=>my,DeserializationServiceScope:()=>py,DeserializedFormElementNode:()=>Nr});var fy,Nr,py,an,my,iy=k(()=>{"use strict";fy=we(na());ct();et();zt();gs();zg();ra();o_();k_();fu();u2();Lu();wf();Ru();Z0();se();se();c2();St();An();ey();d2();f2();ty();ry();p2();oy();ay();ku();Af();h2();cy();dy();y2();b2();v2();Nr=class extends te{constructor(t,r){super(t,r)}insertProperty(t,r){this.addProperty(t,r)}insertChild(t){this.addChild(t)}},py="DeserializationService";(function(e){e.Grid="Grid",e.Lookup="Lookup",e.Base="Base"})(an||(an={}));my=class{lcid;constructor(t){this.lcid=t}deSerializeFormXml(t,r,n,i,o,a,s,l,u,c){if(!t)throw new Error("Formxml could not be parsed.");let d=t.getElementsByTagName("form");if(d.length!==1){let p="";throw d.length===0?p="FormXml has no form node.":p="FormXml has multiple form nodes.",(0,fy.trackErrorTrace)(ir,{eventName:py,eventData:{error:p}}),new Error(p)}let f=this.createFormModel(d.item(0),r,n,i,o,a,s,l,u,c);return P.IsNullOrUndefined(f.displayCondition)&&s!==dt.Dialog&&this.appendDefaultDisplayCondition(f),f}upsertFieldCount(t,r){let n=ia.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(!P.IsNullOrUndefined(t)){let n=P.ParseXml(r);n!==null&&this.populateElementChildren(t,n.childNodes)}}createFormModel(t,r,n,i,o,a,s,l,u,c){let d=new Sf(r,n,i,o,a,s,l,u,c);return this.populateElementProperties(d,t.attributes),this.populateElementChildren(d,t.childNodes),s===dt.Main&&(this.insertHeaderFooterElementProperties(C.formHeader,d,d.header),this.insertHeaderFooterElementProperties(C.formFooter,d,d.footer)),d}insertHeaderFooterElementProperties(t,r,n){if(P.IsNullOrUndefined(n)){let i=t===C.formHeader?new $u(r,!0):new xu(r,!0);Nr.prototype.insertProperty.call(i,y.id,"{"+U.NewGuid()+"}"),Nr.prototype.insertProperty.call(i,y.Fieldlabelposition,"Top"),Nr.prototype.insertProperty.call(i,y.columnName,Ue.MarginalControlColumns),Nr.prototype.insertProperty.call(i,y.LabelWidth,Ue.LabelWidth),Nr.prototype.insertProperty.call(i,y.Fieldlabelalignment,"Left");let o=null,a=new ca(o);for(let s=0;s<i.maxColumns;s++){let l=new Ar(a);Nr.prototype.insertProperty.call(l,y.id,"{"+U.NewGuid()+"}"),l.setDisplayName(q.EmptyString,this.lcid),Nr.prototype.insertProperty.call(l,y.showlabel,"false"),a.addCell(l)}i.appendRow(a),t===C.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 Nr(`<${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,fy.trackErrorTrace)(ir,{eventName:py,eventData:{error:n}}),new Error(n)}for(let n=0;n<r.length;n++){let i=r.item(n);i&&(Nr.prototype.insertProperty.call(t,i.name,i.value),t.getNodeName()===C.formCell&&i.name===y.auto&&i.value==="true"&&t.setAutoExpandDetailsForTab())}}populateElementChildren(t,r){for(let n=0;n<r.length;n++){let i=r.item(n),o=this.deSerializeFormXmlNode(i,t);o&&Nr.prototype.insertChild.call(t,o)}}createModelNode(t,r){switch(t.nodeName){case C.form:throw new Error("Form node shouldn't be created using this method");case C.formTab:return new ki(r);case C.formColumn:return new wo(r);case C.formHeader:return new $u(r,!1);case C.formFooter:return new xu(r,!1);case C.formSection:return new ei(C.formSection,r);case C.formRow:return new ca(r);case C.formCell:return new Ar(r);case C.formControl:let n=t.attributes,i=t.childNodes.length>0?t.childNodes[0].childNodes:null,o;for(let s=0;s<n.length;s++){let l=n.item(s);if(l.name===y.indicationOfSubgrid&&l.value==="true"||l.name===y.classid&&(l.value?.toLocaleUpperCase()===`{${N.SubgridControl}}`||l.value?.toLocaleUpperCase()===`{${N.ReferencePanelSubgridControl}}`))o=an.Grid;else if(l.name===y.classid&&l.value?.toLocaleUpperCase()===`{${N.LookupControl}}`)o=an.Lookup;else if(l.name===y.classid&&l.value?.toLocaleUpperCase()===`{${N.CustomControl}}`)for(let u=0;u<i?.length;u++)i[u].nodeName===y.DefaultViewId&&(o=an.Lookup)}return o===an.Grid?new xs(r):o===an.Lookup?new $s(r):new _n(r);case C.formEvent:return new ks(r,q.EmptyString);case C.dependency:return this.populateDependencyTable(t),new Ls(r,q.EmptyString);case C.Handler:let a=[];return new Tf(a,r);case C.formNavigation:return new Pf(t.nodeName,r);case C.formNavBarArea:return new Us(t.nodeName,r);case C.formNavBarAreas:return new Bs(t.nodeName,r);case C.formNavBar:return new Df(r);case C.formNavBarByRelationshipItem:return new If(r);case C.formNavBarItem:return new Of(r);case C.formDisplayConditions:return new _f(r);case C.library:return new Fs(r,q.EmptyString,q.EmptyString);case C.controlDescription:return new jd(r);case C.customControl:return this.populateCustomControlConfigurationId(t),new rf(r);default:return new Nr(t.nodeName,r)}}populateDependencyTable(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);i.name===y.id&&this.upsertFieldCount(i.value,Yn.DependencyFieldTable)}}populateCustomControlConfigurationId(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);if(i.name===y.id){let o=new U(i.value.substr(1,i.value.length-2));for(let a=0;a<t.parentNode.attributes.length;a++){let s=t.parentNode.attributes.item(a);if(s.name===y.ForControl){let l=s.value.substr(1,i.value.length-2);tt.CustomControlIdMap.upsert(l,o);break}}break}}}}});var C2={};jr(C2,{SerializationService:()=>hy,SerializationServiceScope:()=>uQ,SerializedFormElementNode:()=>qs});var uQ,qs,hy,E2=k(()=>{"use strict";zt();St();An();sy();uQ="SerializationService",qs=class extends te{fetchNodeName(){return this.getNodeName()}enumerateProperties(){return this.getAllProperties()}enumerateChildren(){return this.getAllChildren()}},hy=class{langCode;constructor(t){this.langCode=t}serializeFormXmlNode(t){let r=qs.prototype.fetchNodeName.call(t);if(r.charAt(0)===Ri.StartTag)return q.EscapeXml(r.substr(1),!1);if(t.isTransient&&!t.isDirty())return q.EmptyString;let n=qs.prototype.enumerateProperties.call(t),i=qs.prototype.enumerateChildren.call(t);if(!(t instanceof da)){let o=`<${r}`;if(n.length!==0&&(o+=` ${this.getPropertiesString(n)}`),i.length===0)o+=" />";else{let a=q.EmptyString;for(let s of i)a+=this.serializeFormXmlNode(s);o+=`>${a}</${r}>`}return o}return q.EmptyString}getPropertiesString(t){let r=q.EmptyString;return t.forEach((n,i)=>{i!==0&&(r+=" "),r+=`${n.key}="${q.EscapeXml(n.value,!0)}"`}),r}}});var vy=v(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});Vs.completeRecordAsStored=Vs.completeLabelsAsStored=void 0;var gy=lo(),cQ="E7A81278-8635-4D9E-8D4D-59480B391C5B",dQ=new Set(["tab","section","cell"]);function Tn(e){let t=[];for(let r=e.firstChild;r;r=r.nextSibling)r.nodeType===1&&t.push(r);return t}function Co(e,t){return Tn(e).find(r=>r.tagName===t)}function S2(e,t){return e.length===t.length&&e.every((r,n)=>r.tagName===t[n].tagName)}function yy(e){let t=Co(e,"control");return t?(t.getAttribute("datafieldname")||"")!==""?!0:(t.getAttribute("classid")||"").replace(/[{}]/g,"").toUpperCase()===cQ:!1}function by(e,t){var r,n;let i=((r=Co(e,"control"))===null||r===void 0?void 0:r.getAttribute("id"))||"";return i!==""&&i===(((n=Co(t,"control"))===null||n===void 0?void 0:n.getAttribute("id"))||"")}function fQ(e,t){if(Co(e,"labels"))return;let r=Tn(e),n=Tn(t),i=n[0];if(!i||i.tagName!=="labels"||n.length!==r.length+1||!S2(r,n.slice(1)))return;let o=Tn(i);if(!(o.length===0||o.some(s=>s.tagName!=="label"||!s.hasAttribute("description")||!s.hasAttribute("languagecode"))||!(e.tagName==="cell"&&yy(e)&&by(e,t))&&o.some(s=>s.getAttribute("description")!=="")))return i}function pQ(e,t){let r=mQ(e.ownerDocument,t),n=Tn(e)[0];n?e.insertBefore(r,n):e.appendChild(r)}function mQ(e,t){let r=e.createElement("labels");for(let n of Tn(t))r.appendChild(N2(e,n));return r}function N2(e,t){let r=e.createElement("label");for(let n=0;n<t.attributes.length;n+=1){let{name:i,value:o}=t.attributes[n];(i==="description"||i==="languagecode")&&r.setAttribute(i,o)}return r}function A2(e,t){let r=Co(e,"labels");return r?Tn(r).find(n=>n.tagName==="label"&&n.getAttribute("languagecode")===String(t)):void 0}function hQ(e,t,r){if(e.tagName!=="cell"||!yy(e)||!by(e,t))return!1;let n=A2(e,r),i=A2(t,r),o=i?.getAttribute("description")||"";return!n||!n.hasAttribute("description")||(n.getAttribute("description")||"")!==""||o===""?!1:(n.setAttribute("description",o),!0)}function gQ(e,t){if(e.tagName!=="cell"||!yy(e)||!by(e,t))return;let r=Co(e,"labels"),n=Co(t,"labels");if(!r||!n)return;let i=Tn(r),o=Tn(n),a=f=>f.tagName==="label"&&f.hasAttribute("description")&&f.hasAttribute("languagecode");if(o.length<=i.length||!i.every(a)||!o.every(a))return;let s=new Map(i.map(f=>[f.getAttribute("languagecode")||"",f]));if(s.size!==i.length)return;let l=new Set,u=0,c=[],d=[];for(let f of o){let p=f.getAttribute("languagecode")||"";if(l.has(p))return;l.add(p);let m=s.get(p);if(!m){d.push(f);continue}if((m.getAttribute("description")||"")!==(f.getAttribute("description")||""))return;u+=1,c.push(...d.map(h=>({label:h,before:m}))),d=[]}return c.push(...d.map(f=>({label:f}))),u===i.length?c:void 0}function _2(e,t,r,n){if(e.tagName!==t.tagName)return;if(dQ.has(e.tagName)){let a=fQ(e,t);a&&(pQ(e,a),n.changed=!0),hQ(e,t,r)&&(n.changed=!0);let s=gQ(e,t),l=Co(e,"labels");if(s&&l){for(let{label:u,before:c}of s){let d=N2(e.ownerDocument,u);c?l.insertBefore(d,c):l.appendChild(d)}n.changed=!0}}let i=Tn(e),o=Tn(t);S2(i,o)&&i.forEach((a,s)=>_2(a,o[s],r,n))}function T2(e,t,r){if(e===t)return e;let n,i;try{n=(0,gy.parseXmlRoot)(e,""),i=(0,gy.parseXmlRoot)(t,"")}catch{return e}let o={changed:!1};return _2(n,i,r,o),o.changed?(0,gy.serializeNode)(n):e}Vs.completeLabelsAsStored=T2;function yQ(e,t,r){let n=e?.formxml,i=t?.formxml;if(typeof n!="string"||typeof i!="string")return e;let o=T2(n,i,r);return o===n?e:{...e,formxml:o}}Vs.completeRecordAsStored=yQ});var H2=v(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.pcfReadIssues=le.pcfBindingIssues=le.commitPcfState=le.mayCommitPcfState=le.reconcilePcfDescriptions=le.customControlNeeds=le.mintPcfIdentity=le.planPcfBinding=le.projectPcfBindings=le.supportsPcfFormType=le.storedBindingOf=le.hasCustomControl=le.sameAsStored=le.readPcfDescription=le.newPcfDescription=le.editorText=le.nativeClassFor=le.pcfEntryLayout=void 0;var bQ=(fu(),kr(x_)),vQ=Q(),D2=lt(),V=yd(),wQ=Lh(),ve=Zr(),Fi=["web","phone","tablet"],Mu={web:"2",phone:"0",tablet:"1"},L2=new Map([["2","web"],["0","phone"],["1","tablet"]]),CQ=["phone","web","tablet"];function Lf(e){let t=new Set(e),r=CQ.filter(n=>!t.has(n));return{defaults:r.length===0?[null]:r,named:Fi.filter(n=>t.has(n))}}le.pcfEntryLayout=Lf;function or(e){return Array.isArray(e)?e:[]}function rt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Uu(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Cy(e){return{n:`<${e}`,a:[],c:[]}}function k2(e){return typeof e?.n=="string"&&e.n.startsWith("<")}function I2(e){let t=or(e.c);return t.length===1&&k2(t[0])&&(0,V.rawText)(e)!==""?(0,V.rawText)(e):void 0}function ln(e,t){return JSON.stringify(e)===JSON.stringify(t)}function x2(e){return`{${e.replace(/^\{|\}$/g,"").toUpperCase()}}`}function Ey(e){try{let t=(0,bQ.mapFieldTypeToControl)(e.attributeTypeName,e.format);return t?x2(String(t)):void 0}catch{return}}le.nativeClassFor=Ey;var Ay=new Map([["Whole.None",{digits:0,min:-2147483648,max:2147483647}],["Whole.Duration",{digits:0,min:0,max:2147483647}],["Decimal",{digits:7,min:-922337203685477,max:922337203685477}],["FP",{digits:5,min:-1e11,max:1e11}],["Currency",{digits:4,min:-1e11,max:1e11}]]),$2=new Set(["TwoOptions","Boolean"]),F2=new Set(["SingleLine.Text","SingleLine.TextArea","SingleLine.Email","SingleLine.Phone","SingleLine.URL","SingleLine.Ticker","Multiple"]),EQ=new Map([...[...F2].map(e=>[e,100]),["SingleLine.TextArea",2e3],["Multiple",1048576]]),AQ=/^[A-Za-z_][A-Za-z0-9_.-]*$/;function M2(e){return AQ.test(e)&&e!=="__proto__"}function Sy(e){return e!==void 0&&(e==="Enum"||Ay.has(e)||$2.has(e)||F2.has(e))}function U2(e){return typeof e=="number"?e:e!==""&&!Number.isNaN(Number(e))?Number(e):void 0}function Bu(e,t){let r=e!==void 0?Ay.get(e):void 0;if(r&&typeof t!="boolean"){let n=U2(t);if(n!==void 0)return n.toFixed(r.digits)}return typeof t=="boolean"?t?"true":"false":String(t)}le.editorText=Bu;function SQ(e,t,r){var n;let i=[];for(let o of e.properties){let a=o.name,s;if(o.isPrimary?s=t:o.usage==="input"&&Uu(r,a)?s=Bu(o.defaultType,r[a]):s=(n=o.defaultValue)!==null&&n!==void 0?n:"",s==="")continue;let l=[];o.defaultType&&l.push(["type",o.defaultType]),!o.isPrimary&&(o.defaultType==="Enum"||o.usage==="input")&&l.push(["static","true"]),i.push({n:a,a:l,c:[Cy(s)]})}return i}function B2(e,t,r,n,i){var o,a;let s=(o=n.formFactors)!==null&&o!==void 0?o:Fi.filter(d=>Ny(i).has(d)),l=Lf(s),u=SQ(i,t,(a=n.parameters)!==null&&a!==void 0?a:{}),c=d=>JSON.parse(JSON.stringify(d));return{n:"controlDescription",a:[["forControl",e]],c:[...l.defaults.map(d=>({n:"customControl",a:d===null?[["id",r]]:[["id",r],["formFactor",Mu[d]]],c:[{n:"parameters",a:[],c:[{n:"datafieldname",a:[],c:[Cy(t)]}]}]})),...l.named.map(d=>({n:"customControl",a:[["name",n.name],["formFactor",Mu[d]]],c:[{n:"parameters",a:[],c:c(u)}]}))]}}le.newPcfDescription=B2;function Ny(e){return new Set(Fi.filter(t=>e.availableOn[t]))}function Rf(e){var t;let r=or(e.c);if(r.length!==1||((t=r[0])===null||t===void 0?void 0:t.n)!=="parameters"||or(r[0].a).length>0)return;let n=or(r[0].c);return n.every(i=>rt(i)&&!k2(i))?n:void 0}function pa(e){let t=or(e?.c);if(t.length===0||!t.every(m=>rt(m)&&m.n==="customControl"))return;let r=t.findIndex(m=>(0,V.rawAttr)(m,"name")!==void 0);if(r<=0)return;let n=t.slice(r),i=(0,V.rawAttr)(n[0],"name"),o=[];for(let m of n){let h=or(m.a),g=h.length===2?L2.get(h[1][1]):void 0;if(!g||h[0][0]!=="name"||h[0][1]!==i||h[1][0]!=="formFactor"||o.includes(g))return;o.push(g)}let a=Lf(o);if(!ln(a.named,o)||i==="")return;let s=Rf(n[0]);if(!s||!n.every(m=>ln(Rf(m),s)))return;let l=t.slice(0,r);if(l.length!==a.defaults.length)return;let u=(0,V.rawAttr)(l[0],"id"),c;for(let m=0;m<l.length;m+=1){let h=a.defaults[m],g=h===null?[["id",u??""]]:[["id",u??""],["formFactor",Mu[h]]],b=Rf(l[m]),w=b?.length===1&&b[0].n==="datafieldname"&&or(b[0].a).length===0?I2(b[0]):void 0;if(!u||!ln(or(l[m].a),g)||w===void 0||c!==void 0&&w!==c)return;c=w}let d={},f={},p;for(let m of s){let h=or(m.a),g=I2(m),b=h.map(w=>w[0]);if(g===void 0||!M2(m.n)||Uu(d,m.n)||m.n===p)return;if((0,V.rawAttr)(m,"static")===void 0){if(p!==void 0||g!==c||!(b.length===0||ln(b,["type"])))return;p=m.n;continue}if((0,V.rawAttr)(m,"static")!=="true"||!(ln(b,["static"])||ln(b,["type","static"])))return;d[m.n]=g,f[m.n]=(0,V.rawAttr)(m,"type")}if(!(p===void 0||c===void 0||u===void 0))return{binding:{name:i,...Object.keys(d).length>0?{parameters:d}:{},...o.length===Fi.length?{}:{formFactors:o}},fieldName:c,nativeClass:u,parameterTypes:f,boundProperty:p}}le.readPcfDescription=pa;function q2(e,t,r){return e===t?!0:typeof e!="string"&&(t===String(e)||t===Bu(r,e))}function V2(e){let t=e.formFactors;return t===void 0?[...Fi]:Array.isArray(t)?Fi.filter(r=>t.includes(r)):[]}function wy(e,t){var r,n,i;if(e.name!==t.binding.name||!ln(V2(e),(r=t.binding.formFactors)!==null&&r!==void 0?r:Fi))return!1;let o=(n=e.parameters)!==null&&n!==void 0?n:{},a=(i=t.binding.parameters)!==null&&i!==void 0?i:{},s=Object.keys(o);return s.length!==Object.keys(a).length?!1:s.every(l=>Uu(a,l)&&q2(o[l],a[l],t.parameterTypes[l]))}le.sameAsStored=wy;function ft(e){return rt(e)&&e.customControl!==void 0}le.hasCustomControl=ft;function $i(e,t){var r;return t?or((r=(0,V.descriptionsRegion)(e))===null||r===void 0?void 0:r.node.c).filter(n=>n?.n==="controlDescription"&&(0,V.normGuid)((0,V.rawAttr)(n,"forControl"))===t):[]}function _y(e,t){let r=$i(e.bag,(0,V.controlUniqueId)(t));return r.length===1?pa(r[0]):void 0}le.storedBindingOf=_y;function Ty(e){let t=(0,V.effectiveFormType)(e);return t==="Main"||t==="QuickCreate"}le.supportsPcfFormType=Ty;function NQ(e){if(!Ty(e))return;let t=(0,V.controlUniqueIds)(e);for(let{cell:r}of(0,V.typedCellSites)(e)){let n=r.control;if(!rt(n)||!n.fieldName||!xi(n.classId)||t.get((0,V.controlUniqueId)(n))!==1)continue;let i=_y(e,n);i&&i.fieldName===n.fieldName&&(n.customControl=JSON.parse(JSON.stringify(i.binding)))}}le.projectPcfBindings=NQ;function xi(e){return typeof e=="string"&&e.replace(/^\{|\}$/g,"").toUpperCase()===V.CUSTOM_CONTROL_CLASS_ID}var sn=(e,t)=>({kind:"refused",rule:e,message:t});function _Q(e){let t=e.replace(/^\{|\}$/g,"");return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)&&!xi(e)}function O2(e,t,r){var n,i;let o=pa(r);if(!o)return sn("pcf-binding-other-control","the control already has a description the SDK cannot read as a binding; adding would replace it");if(o.fieldName!==e.fieldName)return sn("pcf-binding-rebind",`the binding is filed for "${o.fieldName}": remove it, push, then bind the new column`);if(t.name!==o.binding.name)return sn("pcf-binding-control-swap",`the binding uses "${o.binding.name}": to use another control, remove customControl, push, then add it`);let a=rt(t.parameters)?t.parameters:{},s=(n=o.binding.parameters)!==null&&n!==void 0?n:{},l=Object.keys(a).sort();if(!ln(l,Object.keys(s).sort()))return sn("pcf-binding-edit-parameter-set",`an edit changes parameter values only \u2014 the binding stores exactly ${Object.keys(s).sort().map(g=>`"${g}"`).join(", ")||"none"}: to add or remove one, remove the binding, push, then add it`);let u=l.filter(g=>!q2(a[g],s[g],o.parameterTypes[g])),c=u.find(g=>Bu(o.parameterTypes[g],a[g]).trim()==="");if(c!==void 0)return sn("pcf-binding-edit-parameter-set",`"${c}" cannot be cleared in place \u2014 an empty value is not written, which removes the parameter: remove the binding, push, then add it`);let d=V2(t),f=(i=o.binding.formFactors)!==null&&i!==void 0?i:[...Fi],p=d.filter(g=>!f.includes(g)),m=f.filter(g=>!d.includes(g));if(u.length===0&&p.length===0&&m.length===0)return{kind:"unchanged"};let h=u.find(g=>!Sy(o.parameterTypes[g]));if(h!==void 0){let g=o.parameterTypes[h];return sn("pcf-binding-edit-stored-type",`"${h}" is stored ${g===void 0?"with no type":`as type "${g}"`}, which the property editor does not write: remove the binding, push, then add it`)}return(p.length>0||m.length>0)&&!_Q(o.nativeClass)?sn("pcf-binding-edit-fallback",`the factors the control leaves fall back to "${o.nativeClass}", which is not a native control class: remove the binding, push, then add it`):{kind:"edit",description:r,stored:o,changed:u,factors:d,added:p,removed:m}}function TQ(e,t){return t&&(0,V.typedCellSites)(e).find(({cell:n})=>ft(n.control)&&(0,V.controlUniqueId)(n.control)===t)?{descriptions:$i(e.bag,t)}:void 0}function G2(e,t){let r=new Map,n=DQ(e),i=new Set,o=new Map,a=u=>{let c=o.get(u);return c||(c={before:[],now:[]},o.set(u,c)),c},s=(u,c)=>({cell:PQ(u),uid:(0,V.controlUniqueId)(c),bound:ft(c)});for(let{cell:u}of(0,V.typedCellSites)(e)){let c=u.control;rt(c)&&typeof c.id=="string"&&c.id&&a(c.id).now.push({...s(u,c),control:c})}for(let{cell:u}of(0,V.typedCellSites)(t)){let c=u.control;if(!rt(c))continue;let d=s(u,c);d.bound&&d.uid&&i.add(d.uid),typeof c.id=="string"&&c.id&&a(c.id).before.push(d)}let l=(u,c)=>{let d=u.filter(f=>f.cell===c);return d.length===1?d[0]:void 0};for(let[u,{before:c,now:d}]of o){let f=c.filter(D=>D.bound&&D.uid!==""&&!n.has(D.uid));if(f.length===0||d.length===0)continue;let p=[...c],m=D=>{let O=p.findIndex(D);return O<0?void 0:p.splice(O,1)[0]},g=d.filter(D=>!D.bound||D.uid===""?!0:m(O=>O.bound&&O.uid===D.uid)!==void 0?!1:!i.has(D.uid)).filter(D=>{let O=D.cell?l(c,D.cell):void 0;return!O||!l(d,D.cell)||!p.includes(O)?!0:(p.splice(p.indexOf(O),1),f.includes(O)&&D.uid!==O.uid&&P2(D.control)&&r.set(D.control,R2(O.uid)),!1)}),b=[],w=(D,O)=>{let $=D.uid===""?void 0:m(K=>K.uid===D.uid&&(!O||K.bound===D.bound));return $&&f.includes($)&&b.push($),$!==void 0},A=g.filter(D=>!w(D,!0)).filter(D=>!w(D,!1)&&P2(D.control)),L=f.filter(D=>p.includes(D));if(A.length===0||L.length===0&&b.length===0)continue;let R=[...L,...b],I=L.length===1&&A.length===1&&p.length===1?R2(L[0].uid):`the controls with id "${u}" cannot all be matched to those last synced \u2014 their cells do not tell them apart \u2014 and ${R.map(D=>`{${D.uid}}`).join(", ")} no longer ${R.length===1?"names":"name"} a control: which control held ${R.length===1?"that binding":"those bindings"} is ambiguous. Re-fetch the form; to drop a bound control, remove its customControl and push before removing the control`;for(let D of A)r.set(D.control,I)}return r}function DQ(e){let t=(0,V.controlUniqueIds)(e),r=new Map;for(let{cell:i}of(0,V.typedCellSites)(e)){let o=rt(i.control)?(0,V.controlUniqueId)(i.control):"";o&&!r.has(o)&&r.set(o,i.control)}let n=new Set;for(let[i,o]of t){let a=r.get(i);(a===void 0||ft(a)||o>1)&&n.add(i)}return n}function P2(e){return ft(e)||e.genPage===void 0&&xi((0,V.effectiveClassId)(e))}function IQ(e,t){let r=o=>(0,V.typedCellSites)(o).flatMap(({cell:a,pointer:s})=>{let l=a.control;if(!rt(l)||ft(l)||l.genPage!==void 0||!xi((0,V.effectiveClassId)(l)))return[];let u=(0,V.controlUniqueId)(l);return u===""||$i(o.bag,u).length===0?[{control:l,pointer:`${s}/control`}]:[]}),n=o=>`${String(o.id)}\0${(0,V.controlUniqueId)(o)}`,i=r(t).map(({control:o})=>n(o));return r(e).filter(({control:o})=>{let a=i.indexOf(n(o));return a<0?!0:(i.splice(a,1),!1)})}var OQ="this control would keep the custom-control class with no binding (its customControl and uniqueid are gone): remove the binding from an unchanged copy \u2014 keep its uniqueid, and the native control comes back \u2014 or set classId to the column's native control";function R2(e){return`this control's uniqueid changed since it was last synced (it was {${e}}), and a binding is linked to its description by it: restore it (re-fetch the form), or remove the binding, push, then add the new one`}function PQ(e){let t=typeof e.id=="string"?e.id.trim():"";return(0,V.normGuid)(t)||t.toLowerCase()}function qu(e,t,r,n){let i=t.customControl,o=(0,V.controlUniqueId)(t),a=$i(e.bag,o),s=r?G2(e,r).get(t):void 0;if(s!==void 0)return sn("pcf-binding-unique-id",s);let l=r?TQ(r,o):void 0;if(l){let c=l.descriptions,d=c.length===1?pa(c[0]):void 0;if(d&&d.fieldName!==t.fieldName)return sn("pcf-binding-rebind",`the binding is filed for "${d.fieldName}": remove it, push, then bind the new column`);if(c.length===1&&a.length===1&&ln(c[0],a[0]))return O2(t,i,a[0]);let f=a.length===1?pa(a[0]):void 0;return d&&f&&f.fieldName===t.fieldName&&wy(i,d)&&wy(i,f)?{kind:"unchanged"}:sn("pcf-binding-edit-changed-description","the binding\u2019s description changed since it was last synced (edited in the bag, re-keyed or deleted): re-fetch the form before changing the binding")}if(a.length===0)return{kind:"new"};if(a.length>1)return sn("pcf-binding-other-control","the control already has a description the SDK cannot read as a binding; adding would replace it");let u=O2(t,i,a[0]);return n&&(u.kind==="edit"||u.kind==="unchanged")?u.kind==="unchanged"?u:sn("pcf-binding-edit","this binding\u2019s description was never synced from the server (no baseline): changing it in place is not supported \u2014 remove customControl, push, then add the new one"):u}le.planPcfBinding=qu;function W2(e){return e.kind==="edit"&&(e.changed.length>0||e.added.length>0)}function RQ(e){let t=n=>ft(n.control)&&(!n.control.id||!n.id||(0,V.authoredUniqueId)(n.control)===void 0);if(!(0,V.typedCellSites)(e).some(({cell:n})=>t(n)))return e;let r=JSON.parse(JSON.stringify(e));for(let{cell:n}of(0,V.typedCellSites)(r)){if(!t(n))continue;let i=n.control;i.id||(i.id=(0,D2.newId)()),n.id||(n.id=(0,D2.newId)()),(0,V.authoredUniqueId)(i)===void 0&&(0,V.setUniqueId)(i)}return r}le.mintPcfIdentity=RQ;function LQ(e,t){let r=new Set,n=new Set;for(let{cell:i}of(0,V.typedCellSites)(e)){let o=i.control;if(!ft(o)||!rt(o.customControl))continue;let a=o.customControl.name;if(typeof a!="string"||a===""||typeof o.fieldName!="string"||!o.fieldName)continue;let s=qu(e,o,t,!0);s.kind==="new"?(r.add(a),n.add(o.fieldName)):W2(s)&&r.add(a)}return{controls:[...r],columns:[...n],...n.size>0&&(0,V.effectiveFormType)(e)==="QuickCreate"?{requireCreateEligibility:!0}:{}}}le.customControlNeeds=LQ;function kQ(e,t,r){var n,i,o,a,s,l;let u=e.bag,c=new Map;for(let{cell:f,pointer:p}of(0,V.typedCellSites)(e)){let m=f.control;if(!ft(m)||!rt(m.customControl))continue;let h=(0,V.controlUniqueId)(m);h&&$i(u,h).length>0&&c.set(m,{plan:qu(e,m,t,!0),pointer:`${p}/control/customControl`})}let d=(0,V.descriptionsRegion)(u);if(d&&t){let f=(0,V.controlUniqueIds)(e),p=new Set,m=new Map;for(let{cell:h}of(0,V.typedCellSites)(e)){let g=rt(h.control)?(0,V.controlUniqueId)(h.control):"";g&&!m.has(g)&&m.set(g,h.control)}for(let{cell:h}of(0,V.typedCellSites)(t)){let g=h.control;if(!ft(g))continue;let b=(0,V.controlUniqueId)(g),w=$i(t.bag,b),E=$i(u,b);if(w.length!==1||E.length!==1||!ln(w[0],E[0])||!pa(E[0]))continue;let A=m.get(b);if(A&&!ft(A)){if(((n=f.get(b))!==null&&n!==void 0?n:0)>1)continue;let L=(o=(i=pa(E[0]))===null||i===void 0?void 0:i.nativeClass)!==null&&o!==void 0?o:"";A.classId=L.replace(/^\{|\}$/g,"").toUpperCase(),xQ(A,"uniqueid"),p.add(b)}else!A&&!f.has(b)&&p.add(b)}p.size>0&&(d.node.c=or(d.node.c).filter(h=>!(h?.n==="controlDescription"&&p.has((0,V.normGuid)((0,V.rawAttr)(h,"forControl"))))))}for(let{cell:f}of(0,V.typedCellSites)(e)){let p=f.control;if(!ft(p)||!rt(p.customControl))continue;xi(p.classId)||(p.classId=V.CUSTOM_CONTROL_CLASS_ID);let m=(0,V.controlUniqueId)(p);if(!m){if((0,V.authoredUniqueId)(p)!==void 0)continue;m=(0,V.setUniqueId)(p)}let h=c.get(p);if(h){if(h.plan.kind==="refused")throw new vQ.ValidationError("form",e.id,[(0,ve.issue)(h.pointer,h.plan.rule,h.plan.message)]);h.plan.kind==="edit"&&$Q(h.plan,p.customControl);continue}let g=r?.control(p.customControl.name),b=r?.column(e.entityLogicalName,p.fieldName),w=b?.kind==="found"?Ey(b.value):void 0;if(g?.kind!=="found"||!w)continue;d||(d={i:(0,V.embedAppendIndex)(u),node:{n:"controlDescriptions",a:[],c:[]}},u.c.push(d));let E=((l=(s=or((a=p.bag)===null||a===void 0?void 0:a.a).find(L=>L[0]==="uniqueid"))===null||s===void 0?void 0:s[1])!==null&&l!==void 0?l:"").trim(),A=E.startsWith("{")?E:`{${m}}`;d.node.c.push(B2(A,p.fieldName,w,p.customControl,g.value))}}le.reconcilePcfDescriptions=kQ;function xQ(e,t){rt(e.bag)&&(e.bag.a=or(e.bag.a).filter(r=>r[0]!==t))}function $Q(e,t){var r,n;let i=or(e.description.c),o=i.findIndex(g=>(0,V.rawAttr)(g,"name")!==void 0),a=i.slice(0,o),s=i.slice(o),l=(r=t.parameters)!==null&&r!==void 0?r:{};for(let g of s)for(let b of(n=Rf(g))!==null&&n!==void 0?n:[])e.changed.includes(b.n)&&(b.c=[Cy(Bu(e.stored.parameterTypes[b.n],l[b.n]))]);if(e.added.length===0&&e.removed.length===0)return;let u=g=>JSON.parse(JSON.stringify(g)),c=g=>{var b;let w=(0,V.rawAttr)(g,"formFactor");return w===void 0?null:(b=L2.get(w))!==null&&b!==void 0?b:null},d=(0,V.rawAttr)(a[0],"id"),f=(0,V.rawAttr)(s[0],"name"),p=Lf(e.factors),m=p.defaults.map(g=>{let b=a.find(E=>c(E)===g);if(b)return b;let w=u(a[0]);return w.a=g===null?[["id",d]]:[["id",d],["formFactor",Mu[g]]],w}),h=p.named.map(g=>{let b=s.find(E=>c(E)===g);if(b)return b;let w=u(s[0]);return w.a=[["name",f],["formFactor",Mu[g]]],w});e.description.c=[...m,...h]}function FQ(e){return(0,V.typedCellSites)(e).some(({cell:t})=>ft(t.control))}le.mayCommitPcfState=FQ;function MQ(e,t){var r;let n=JSON.parse(JSON.stringify(e)),i=!1;for(let{cell:o}of(0,V.typedCellSites)(n)){let a=o.control;if(!ft(a))continue;let s=_y(n,a);if(!s||s.fieldName!==a.fieldName)continue;let l=t(V.CUSTOM_CONTROL_CLASS_ID),u=or((r=a.bag)===null||r===void 0?void 0:r.a).find(c=>c[0]==="classid");(!xi(a.classId)||a.type!==l||u!==void 0&&!xi(u[1])||!ln(a.customControl,s.binding))&&(xi(a.classId)||(a.classId=V.CUSTOM_CONTROL_CLASS_ID),a.type=l,u&&!xi(u[1])&&(u[1]=x2(V.CUSTOM_CONTROL_CLASS_ID)),a.customControl=JSON.parse(JSON.stringify(s.binding)),i=!0)}return i?n:e}le.commitPcfState=MQ;var UQ=new Set(["name","parameters","formFactors"]);function BQ(e,t,r){let n=[],i=(0,V.controlUniqueIds)(e);for(let{cell:o,pointer:a}of(0,V.typedCellSites)(e)){let s=o.control;ft(s)&&VQ(e,s,`${a}/control`,i,n,t,r?.atPush===!0)}return t&&GQ(e,t,n),n}le.pcfBindingIssues=BQ;function qQ(e,t,r){let n=r.length;if(!rt(e))return r.push((0,ve.issue)(t,"pcf-binding-shape","customControl must be an object")),!1;for(let i of Object.keys(e))UQ.has(i)||r.push((0,ve.issue)(`${t}/${i}`,"pcf-binding-unknown-key",`customControl has no "${i}"`));if((typeof e.name!="string"||e.name.trim()==="")&&r.push((0,ve.issue)(`${t}/name`,"pcf-binding-shape","name must be the control's non-empty customcontrols name")),e.parameters!==void 0)if(!rt(e.parameters))r.push((0,ve.issue)(`${t}/parameters`,"pcf-binding-shape","parameters must be an object"));else for(let[i,o]of Object.entries(e.parameters))typeof o=="string"||typeof o=="boolean"||typeof o=="number"&&Number.isFinite(o)||r.push((0,ve.issue)(`${t}/parameters/${i}`,"pcf-binding-shape","a parameter must be a string, a finite number or a boolean"));if(e.formFactors!==void 0){let i=e.formFactors;Array.isArray(i)&&i.length>0&&i.every(a=>typeof a=="string"&&Fi.includes(a))&&new Set(i).size===i.length||r.push((0,ve.issue)(`${t}/formFactors`,"pcf-binding-shape","formFactors must be distinct 'web', 'phone' and 'tablet', at least one"))}return r.length===n}function VQ(e,t,r,n,i,o,a){var s;let l=`${r}/customControl`,u=qQ(t.customControl,l,i);t.fieldName||i.push((0,ve.issue)(l,"pcf-binding-unbound","a PCF binding needs a control bound to a column (fieldName)")),t.genPage!==void 0&&i.push((0,ve.issue)(l,"pcf-binding-with-genpage","a control cannot embed a page and bind a PCF control")),Ty(e)||i.push((0,ve.issue)(l,"pcf-binding-form-type","PCF bindings are supported on Main and Quick Create forms only (not Quick View or Card)")),t.classId!==void 0&&typeof t.classId!="string"&&i.push((0,ve.issue)(`${r}/classId`,"pcf-binding-class-id","classId must be a string"));let c=(0,V.authoredUniqueId)(t),d=(0,V.controlUniqueId)(t);if(c!==void 0&&!d?i.push((0,ve.issue)(`${r}/bag`,"pcf-binding-unique-id","the control's uniqueid must be a GUID")):d&&((s=n.get(d))!==null&&s!==void 0?s:0)>1&&i.push((0,ve.issue)(`${r}/bag`,"pcf-binding-unique-id","another control carries the same uniqueid")),!u)return;let f=qu(e,t,o,a);f.kind==="refused"&&i.push((0,ve.issue)(l,f.rule,f.message))}function GQ(e,t,r){var n;let i=new Map,o=G2(e,t);for(let{cell:l,pointer:u}of(0,V.typedCellSites)(e)){let c=rt(l.control)?(0,V.controlUniqueId)(l.control):"";if(c&&!i.has(c)&&i.set(c,{control:l.control,pointer:`${u}/control`}),rt(l.control)&&!ft(l.control)){let d=o.get(l.control);d!==void 0&&r.push((0,ve.issue)(`${u}/control`,"pcf-binding-unique-id",d))}}let a=(0,V.controlUniqueIds)(e);for(let{cell:l}of(0,V.typedCellSites)(t)){if(!ft(l.control))continue;let u=(0,V.controlUniqueId)(l.control),c=i.get(u);!c||ft(c.control)||(((n=a.get(u))!==null&&n!==void 0?n:0)>1?r.push((0,ve.issue)(c.pointer,"pcf-binding-unique-id","another control carries this binding\u2019s uniqueid; removing the binding would delete its description too")):ln($i(t.bag,u),$i(e.bag,u))?c.control.fieldName!==l.control.fieldName&&r.push((0,ve.issue)(c.pointer,"pcf-binding-rebind","remove the binding, push, then bind the new column")):r.push((0,ve.issue)(c.pointer,"pcf-binding-removed-changed","the binding changed since it was last pushed; remove it from an unchanged copy (re-fetch)")))}let s=new Set(r.map(l=>l.pointer));for(let{pointer:l}of IQ(e,t))s.has(l)||r.push((0,ve.issue)(l,"pcf-binding-unique-id",OQ))}var WQ=new Set(["Form.Card"]),zQ="MscrmControls.ModelForm.ModelFormControl";function z2(e,t){var r;if(e.hasDataset||e.hasGroups)return"it has a data-set or groups";if(!e.isBound)return"its first property is not bound to a column";let n=e.properties;if(n.filter(s=>s.usage==="bound").length!==1)return"it has more than one bound property";let i=n.map(s=>s.name);if(i.some(s=>!s)||new Set(i).size!==i.length)return"a property has no name, or two share one";let o=i.find(s=>!M2(s));if(o!==void 0)return`the property name "${o}" cannot be written as an element`;if(t===zQ||n.some(s=>s.defaultType!==void 0&&WQ.has(s.defaultType)))return"a property needs a special encoding";if(n.some(s=>s.usage==="output"&&s.defaultValue!==null&&s.defaultValue!==""))return"an output property has a default";let a=n.find(s=>s.usage==="input"&&!Sy(s.defaultType));return a?`input "${a.name}" has a type the property editor does not write as text (${(r=a.defaultType)!==null&&r!==void 0?r:"none"})`:void 0}function jQ(e){return e.ofType!==null?[e.ofType]:e.ofTypeGroup}function j2(e,t,r=e.defaultType){if(r==="Enum")return e.enumValues.some(o=>o.value===String(t))?void 0:`must be one of ${e.enumValues.map(o=>`"${o.value}"`).join(", ")}`;let n=r!==void 0?Ay.get(r):void 0;if(n){let o=typeof t=="boolean"?void 0:U2(t);return o===void 0||o<n.min||o>n.max?`must be a number from ${n.min.toFixed(n.digits)} through ${n.max.toFixed(n.digits)}`:void 0}if(r!==void 0&&$2.has(r))return t===!0||t===!1||t==="true"||t==="false"?void 0:"must be true or false";let i=r!==void 0?EQ.get(r):void 0;return i!==void 0&&String(t).length>i?`must be at most ${i} characters`:e.required&&String(t)===""?"is required":void 0}function HQ(e,t,r){var n,i,o,a;let s={issues:[]},l=s.issues;for(let{cell:u,pointer:c}of(0,V.typedCellSites)(e)){let d=u.control;if(!ft(d)||!d.fieldName)continue;let f=d.customControl;if(!rt(f)||typeof f.name!="string")continue;let p=`${c}/control/customControl`,m=qu(e,d,r,!0);if(m.kind==="edit"){W2(m)&&YQ(m,f,p,t,s);continue}if(m.kind!=="new")continue;let h=t?.control(f.name),g=t?.column((n=e.entityLogicalName)!==null&&n!==void 0?n:"",d.fieldName);if(!h||h.kind==="unavailable"){(i=s.unavailable)!==null&&i!==void 0||(s.unavailable={code:"PCF_MANIFEST_UNAVAILABLE",message:`the manifest of "${f.name}" could not be read`,...h?.kind==="unavailable"?{cause:h.error}:{}});continue}if(h.kind!=="found"){l.push((0,ve.issue)(`${p}/name`,"PCF_CONTROL_NOT_FOUND",`no single installed control is named "${f.name}" (${h.kind})`));continue}if(!g||g.kind==="unavailable"){(o=s.unavailable)!==null&&o!==void 0||(s.unavailable={code:"PCF_COLUMN_UNAVAILABLE",message:`the column "${d.fieldName}" could not be read`,...g?.kind==="unavailable"?{cause:g.error}:{}});continue}let b=z2(h.value,f.name);if(b){l.push((0,ve.issue)(`${p}/name`,"pcf-binding-unsupported-control",`"${f.name}" is not supported: ${b}`));continue}let w=h.value.properties.find($=>$.isPrimary),E=g.kind==="found"?g.value:void 0,A=E?(a=(0,wQ.manifestTypesForColumn)(E.attributeTypeName,E.format,E.formatName))!==null&&a!==void 0?a:[]:[];E!==void 0&&!E.isPrimaryId&&E.isValidForForm&&Ey(E)!==void 0&&jQ(w).some($=>A.includes($))?(0,V.effectiveFormType)(e)==="QuickCreate"&&E?.isValidForCreate!==!0&&l.push((0,ve.issue)(p,"pcf-binding-quick-create-column",`"${d.fieldName}" cannot be set when a record is created, so a Quick Create form cannot bind it`)):l.push((0,ve.issue)(p,"pcf-binding-incompatible-column",`"${f.name}" cannot be bound to "${d.fieldName}"`));let R=new Map(h.value.properties.filter($=>$.usage==="input").map($=>[$.name,$])),I=rt(f.parameters)?f.parameters:{};for(let[$,K]of Object.entries(I)){let Re=R.get($);if(!Re){l.push((0,ve.issue)(`${p}/parameters/${$}`,"pcf-binding-unknown-parameter",`"${f.name}" has no input "${$}"`));continue}let It=j2(Re,K);It&&l.push((0,ve.issue)(`${p}/parameters/${$}`,"pcf-binding-parameter-value",`"${$}" ${It}`))}for(let $ of R.values())$.required&&!Uu(I,$.name)&&!$.defaultValue&&l.push((0,ve.issue)(`${p}/parameters`,"pcf-binding-missing-parameter",`"${$.name}" is required`));let D=Ny(h.value),O=Array.isArray(f.formFactors)?f.formFactors:void 0;(O?O.some($=>!D.has($)):D.size===0)&&l.push((0,ve.issue)(`${p}/formFactors`,"pcf-binding-form-factor",`"${f.name}" is available on ${D.size===0?"no form factor":[...D].join(", ")}`))}return s}le.pcfReadIssues=HQ;function KQ(e,t){return t===void 0||!Sy(t)?!1:e.ofType!==null?e.ofType===t:e.ofTypeGroup.includes(t)}function JQ(e,t,r){var n,i;let o=z2(e,t);if(o)return`it is no longer supported (${o})`;let a=e.properties.find(d=>d.isPrimary);if(a?.name!==r.boundProperty)return`its bound property is now "${(n=a?.name)!==null&&n!==void 0?n:"none"}", not "${r.boundProperty}"`;let s=(i=r.binding.parameters)!==null&&i!==void 0?i:{},l=new Set(e.properties.filter(d=>d.usage==="input").map(d=>d.name)),u=Object.keys(s).find(d=>!l.has(d));if(u!==void 0)return`"${u}" is no longer one of its inputs`;let c=e.properties.find(d=>d.usage==="input"&&d.required&&!d.defaultValue&&!Uu(s,d.name));return c?`it now requires "${c.name}", which the binding does not store`:void 0}function YQ(e,t,r,n,i){var o,a,s;let l=i.issues,u=n?.control(t.name);if(!u||u.kind==="unavailable"){(o=i.unavailable)!==null&&o!==void 0||(i.unavailable={code:"PCF_MANIFEST_UNAVAILABLE",message:`the manifest of "${t.name}" could not be read`,...u?.kind==="unavailable"?{cause:u.error}:{}});return}if(u.kind!=="found"){l.push((0,ve.issue)(`${r}/name`,"PCF_CONTROL_NOT_FOUND",`no single installed control is named "${t.name}" (${u.kind})`));return}let c=JQ(u.value,t.name,e.stored);if(c){l.push((0,ve.issue)(r,"pcf-binding-edit-manifest-changed",`"${t.name}" changed since this binding was written: ${c} \u2014 remove the binding, push, then add it`));return}let d=new Map(u.value.properties.filter(h=>h.usage==="input").map(h=>[h.name,h])),f=l.length;for(let h of Object.keys((a=e.stored.binding.parameters)!==null&&a!==void 0?a:{})){let g=e.stored.parameterTypes[h];KQ(d.get(h),g)||l.push((0,ve.issue)(`${r}/parameters/${h}`,"pcf-binding-edit-stored-type",`"${h}" is stored ${g===void 0?"with no type":`as type "${g}"`}, which "${t.name}" does not take for it now: remove the binding, push, then add it`))}if(l.length>f)return;let p=(s=t.parameters)!==null&&s!==void 0?s:{};for(let h of e.changed){let g=j2(d.get(h),p[h],e.stored.parameterTypes[h]);g&&l.push((0,ve.issue)(`${r}/parameters/${h}`,"pcf-binding-parameter-value",`"${h}" ${g}`))}let m=Ny(u.value);e.added.some(h=>!m.has(h))&&l.push((0,ve.issue)(`${r}/formFactors`,"pcf-binding-form-factor",`"${t.name}" is available on ${m.size===0?"no form factor":[...m].join(", ")}`))}});var uL=v(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0});Tr.classIdForAttributeType=Tr.QUICK_VIEW_CLASS_ID=Tr.NOTES_CLASS_ID=Tr.SUBGRID_CLASS_ID=Tr.formRegistration=Tr.FormAdapter=void 0;var Mi=(ct(),kr(YN)),K2=(et(),kr(QN)),QQ=(St(),kr(ZN)),Nt=(se(),kr(XN)),nt=(ra(),kr(e_)),XQ=(iy(),kr(w2)),ZQ=(E2(),kr(C2)),pt=ao(),J2=Kr(),_r=Zr(),eX=pg(),Ws=lt(),tX=vy(),Ht=yd(),ti=H2(),Gs=Q(),Ry=ue(),Dy=so(),rL=Ko(),rX={[Nt.FormType.Main]:"Main",[Nt.FormType.QuickCreate]:"QuickCreate",[Nt.FormType.QuickViewForm]:"QuickView",[Nt.FormType.Card]:"Card"},kf={Main:Nt.FormType.Main,QuickCreate:Nt.FormType.QuickCreate,QuickView:Nt.FormType.QuickViewForm,Card:Nt.FormType.Card},nX=new Map(Object.entries(nt.ControlClassId).map(([e,t])=>[String(t).toUpperCase(),e]));function Ly(e){var t;return e&&(t=nX.get(e.toUpperCase()))!==null&&t!==void 0?t:"Unknown"}function Vu(e){return e.getAllProperties().map(t=>[t.key,t.value])}function ma(e){let t=new Map;for(let r of e.getAllProperties())t.has(r.key)||t.set(r.key,r.value);return t}function nL(e,t){return e.getAllChildren().find(r=>r.getNodeName()===t)}function ky(e,t){var r,n;let i=nL(e,"labels");if(!i)return"";let o=i.getAllChildren().filter(s=>s.getNodeName()==="label"),a=(r=o.find(s=>ma(s).get("languagecode")===String(t)))!==null&&r!==void 0?r:o[0];return a&&(n=ma(a).get("description"))!==null&&n!==void 0?n:""}function iX(e){let t=nL(e,"parameters"),r={};if(!t)return r;for(let n of t.getAllChildren()){let i=n.getNodeName();if(i.charAt(0)==="<"||i.charAt(0)==="#")continue;let o=n.getAllChildren()[0],a=o?o.getNodeName():"";a.charAt(0)==="<"&&(a=a.substring(1)),r[i]=a}return r}function iL(e){return/^1+$/.test(e)&&e.length>=1&&e.length<=4?e.length:1}function Iy(e){let t=Math.min(Math.max(Math.trunc(e),1),4);return"1".repeat(t)}function Gu(e){return String(e??"").replace(/[{}]/g,"")}function Oy(e){return`{${Gu(e)}}`}function Y2(e,t){if(e===void 0||e==="")return t;let r=Number(e);return Number.isNaN(r)?t:r}function $f(e,t,r){let n=e.getAllChildren(),i=n.findIndex(u=>u.getNodeName()===t),o=[];if(n.forEach((u,c)=>{c!==i&&o.push({i:c,node:(0,pt.rawFromNode)(u)})}),i<0)return{modeled:[],bag:{a:Vu(e),c:o}};let a=n[i],s=[],l=[];return a.getAllChildren().forEach((u,c)=>{u.getNodeName()===r?s.push(u):l.push({i:c,node:(0,pt.rawFromNode)(u)})}),{modeled:s,bag:{a:Vu(e),c:o,w:{n:a.getNodeName(),a:Vu(a),c:l}}}}function oL(e,t,r){let n=[],i=[];return e.getAllChildren().forEach((o,a)=>{o.getNodeName()===t&&(!r||n.length===0)?n.push(o):i.push({i:a,node:(0,pt.rawFromNode)(o)})}),{modeled:n,bag:{a:Vu(e),c:i}}}function Q2(e,t){let{modeled:r,bag:n}=$f(e,"tabs","tab");return{tabs:r.map(i=>oX(i,t)),bag:n}}function oX(e,t){var r,n;let i=ma(e),{modeled:o,bag:a}=$f(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:ky(e,t),expanded:i.get("expanded")==="true",visible:i.has("visible")?i.get("visible")==="true":!0,columns:o.map(s=>aX(s,t)),bag:a}}function aX(e,t){let r=ma(e),{modeled:n,bag:i}=$f(e,"sections","section");return{width:r.get("width"),sections:n.map(o=>sX(o,t)),bag:i}}function sX(e,t){var r,n,i;let o=ma(e),{modeled:a,bag:s}=$f(e,"rows","row");return{id:(r=o.get("id"))!==null&&r!==void 0?r:"",name:(n=o.get("name"))!==null&&n!==void 0?n:"",label:ky(e,t),visible:o.has("visible")?o.get("visible")==="true":!0,showLabel:o.get("showlabel")==="true",columns:iL((i=o.get("columns"))!==null&&i!==void 0?i:"1"),rows:a.map(l=>lX(l,t)),bag:s}}function lX(e,t){let{modeled:r,bag:n}=oL(e,"cell",!1);return{cells:r.map(i=>uX(i,t)),bag:n}}function uX(e,t){var r;let n=ma(e),{modeled:i,bag:o}=oL(e,"control",!0),a=ky(e,t),s=n.get("showlabel")==="true",l=i[0]?cX(i[0],a,s):null;return{id:(r=n.get("id"))!==null&&r!==void 0?r:"",visible:n.has("visible")?n.get("visible")==="true":!0,colspan:Y2(n.get("colspan"),1),rowspan:Y2(n.get("rowspan"),1),control:l,bag:o}}function cX(e,t,r){var n,i;let o=ma(e),a=Gu((n=o.get("classid"))!==null&&n!==void 0?n:""),s=o.get("datafieldname");return{id:(i=o.get("id"))!==null&&i!==void 0?i:"",classId:a,fieldName:s||null,type:Ly(a),isRequired:o.get("isrequired")==="true",isReadOnly:o.get("disabled")==="true",label:t,showLabel:r,parameters:iX(e),bag:{a:Vu(e),c:e.getAllChildren().map((l,u)=>({i:u,node:(0,pt.rawFromNode)(l)}))}}}function So(e){return e.a.length===0&&e.c.length===0&&!e.w}function aL(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function ha(e,t){var r;let n=new Set(e.a.map(a=>a[0])),i=So(e),o=[];for(let a of t)if(n.has(a.key)){let s=(r=aL(e,a.key))!==null&&r!==void 0?r:"";a.matches(s)||o.push([a.key,a.render()])}else i?o.push([a.key,a.render()]):a.matches(a.absentDefault)||o.push([a.key,a.render()]);return(0,pt.mergeAttrs)(e.a,o)}var Eo=(e,t)=>({key:e,matches:r=>r===t,render:()=>t,absentDefault:""}),Ao=(e,t,r=!1)=>({key:e,matches:n=>n==="true"===t,render:()=>String(t),absentDefault:String(r)}),X2=(e,t,r=1)=>({key:e,matches:n=>Number(n)===t,render:()=>String(t),absentDefault:String(r)});function xy(e,t){return{n:"labels",a:[],c:[{n:"label",a:[["description",e],["languagecode",String(t)]],c:[]}]}}function Py(e){return{n:"parameters",a:[],c:Object.keys(e).map(t=>({n:(0,Ry.assertXmlName)(t,"Form control parameter name"),a:[],c:[{n:`<${e[t]}`,a:[],c:[]}]}))}}function dX(e,t){var r,n;let i=e.c.find(a=>a.n==="label"&&a.a.some(s=>s[0]==="languagecode"&&s[1]===String(t))),o=i??e.c.find(a=>a.n==="label");return(n=(r=o?.a.find(a=>a[0]==="description"))===null||r===void 0?void 0:r[1])!==null&&n!==void 0?n:""}function fX(e,t,r){let n=!1,i=e.c.map(o=>o.n!=="label"||!o.a.some(s=>s[0]==="languagecode"&&s[1]===String(r))?o:(n=!0,{...o,a:o.a.map(s=>s[0]==="description"?["description",t]:s)}));return n||i.push({n:"label",a:[["description",t],["languagecode",String(r)]],c:[]}),{...e,c:i}}function $y(e,t,r){let n=e.c.findIndex(o=>o.node.n==="labels");if(n<0){if(!t||So(e))return e;let a=e.c.some(s=>s.i===0)?e.c.map(s=>({...s,i:s.i+1})):e.c;return{...e,c:[{i:0,node:xy(t,r)},...a]}}if(dX(e.c[n].node,r)===t)return e;let i=fX(e.c[n].node,t,r);return{...e,c:e.c.map((o,a)=>a===n?{...o,node:i}:o)}}function pX(e){let t={};for(let r of e.c){let n=r.n;if(n.charAt(0)==="<"||n.charAt(0)==="#")continue;let i=r.c[0],o=i?i.n:"";o.charAt(0)==="<"&&(o=o.substring(1)),t[n]=o}return t}function mX(e,t){let r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every(i=>e[i]===t[i])}function hX(e,t){return e.a.some(r=>r[0]===t)?{...e,a:e.a.filter(r=>r[0]!==t)}:e}function gX(e,t){let r=e.c.findIndex(i=>i.node.n==="parameters");if(r<0){if(Object.keys(t).length===0||So(e))return e;let i=e.c.reduce((o,a)=>a.i>o?a.i:o,-1);return{...e,c:[...e.c,{i:i+1,node:Py(t)}]}}if(mX(pX(e.c[r].node),t))return e;let n=Py(t);return{...e,c:e.c.map((i,o)=>o===r?{...i,node:n}:i)}}function Ff(e,t,r,n){if(e.w){let a={n:e.w.n,a:e.w.a.map(s=>[s[0],s[1]]),c:(0,pt.spliceChildren)(e.w.c,r)};return(0,pt.spliceChildren)(e.c,[a])}let i=n(),o={n:t,a:[],c:r};return e.c.length===0?[...i,o]:(0,pt.spliceChildren)(e.c,[...i,o])}function yX(e,t){let r=e.tabs.map(n=>bX(n,t));return{n:"form",a:ha(e.bag,[]),c:e.tabs.length===0&&So(e.bag)?[]:Ff(e.bag,"tabs",r,()=>[])}}function sL(e,t,r){return t&&!e.c.some(n=>n.node.n==="labels")?[xy(t,r)]:[]}function bX(e,t){let r=[Eo("id",e.id),Eo("name",e.name),Ao("expanded",e.expanded),Ao("visible",e.visible,!0)],n=e.columns.map(o=>vX(o,t)),i=$y(e.bag,e.label,t);return{n:"tab",a:ha(i,r),c:Ff(i,"columns",n,()=>sL(i,e.label,t))}}function vX(e,t){let r=e.width!==void 0?[Eo("width",e.width)]:[],n=e.sections.map(i=>wX(i,t));return{n:"column",a:ha(e.bag,r),c:Ff(e.bag,"sections",n,()=>[])}}function wX(e,t){let r=[Eo("id",e.id),Eo("name",e.name),Ao("showlabel",e.showLabel),Ao("visible",e.visible,!0),{key:"columns",matches:o=>iL(o)===e.columns,render:()=>Iy(e.columns),absentDefault:Iy(1)}],n=e.rows.map(o=>CX(o,t)),i=$y(e.bag,e.label,t);return{n:"section",a:ha(i,r),c:Ff(i,"rows",n,()=>sL(i,e.label,t))}}function CX(e,t){let r=e.cells.map(n=>EX(n,t));return{n:"row",a:ha(e.bag,[]),c:So(e.bag)?r:(0,pt.assembleChildren)(e.bag,r)}}function EX(e,t){let r=e.control?e.control.showLabel:aL(e.bag,"showlabel")==="true",n=[Eo("id",e.id),Ao("showlabel",r),Ao("visible",e.visible,!0),X2("colspan",e.colspan),X2("rowspan",e.rowspan)],i=e.control?[AX(e.control)]:[],o;if(So(e.bag))o=[...e.control&&e.control.label?[xy(e.control.label,t)]:[],...i];else{let a=e.control?$y(e.bag,e.control.label,t):e.bag;o=(0,pt.assembleChildren)(a,i)}return{n:"cell",a:ha(e.bag,n),c:o}}function AX(e){let t=[Eo("id",e.id),{key:"classid",matches:i=>Gu(i)===e.classId,render:()=>Oy(e.classId),absentDefault:""}];e.fieldName!==null&&t.push(Eo("datafieldname",e.fieldName)),t.push(Ao("disabled",e.isReadOnly)),t.push(Ao("isrequired",e.isRequired));let r=e.fieldName===null?hX(e.bag,"datafieldname"):e.bag,n;return So(r)?n=Object.keys(e.parameters).length>0?[Py(e.parameters)]:[]:n=(0,pt.assembleChildren)(gX(r,e.parameters),[]),{n:"control",a:ha(r,t),c:n}}var SX={make:(e,t)=>new QQ.FormElementNode(e,t),setProp:(e,t,r)=>e.setProperty(t,r),addChild:(e,t)=>e.addChild(t)};function Z2(e,t,r,n){(0,Dy.installDomShim)();let i=_X(e,r);(0,Ht.reconcileEmbedDescriptions)(i,n),(0,ti.reconcilePcfDescriptions)(i,n,r?.pcf);let o=(0,pt.rebuildRaw)(yX(i,t),SX,null);return new ZQ.SerializationService(t).serializeFormXmlNode(o)}function NX(e){return JSON.parse(JSON.stringify(e))}function _X(e,t){var r;let n=NX(e);n.bag||(n.bag=(0,pt.emptyBag)()),kX(n.bag),t&&TX(n,t);for(let i of(r=n.tabs)!==null&&r!==void 0?r:[])DX(i);return n}function TX(e,t){var r;let n=(r=e.entityLogicalName)!==null&&r!==void 0?r:"";Fy(e,i=>{let o=i.fieldName,a=i;if(!o||a.label!==void 0&&a.classId!==void 0)return;let s=t.resolveField(n,o);s&&(a.label===void 0&&s.displayName&&(a.label=s.displayName),a.classId===void 0&&s.attributeType&&(a.classId=lL(s.attributeType)))})}function eL(e){let t=[];return Fy(e,r=>t.push(r)),t}function Fy(e,t){var r,n,i,o,a;for(let s of(r=e.tabs)!==null&&r!==void 0?r:[])for(let l of(n=s.columns)!==null&&n!==void 0?n:[])for(let u of(i=l.sections)!==null&&i!==void 0?i:[])for(let c of(o=u.rows)!==null&&o!==void 0?o:[])for(let d of(a=c.cells)!==null&&a!==void 0?a:[])d.control&&t(d.control)}function DX(e){e.id||(e.id=Mi.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)IX(t);e.bag||(e.bag=(0,pt.emptyBag)())}function IX(e){e.sections||(e.sections=[]);for(let t of e.sections)OX(t);e.bag||(e.bag=(0,pt.emptyBag)()),e.width===void 0&&So(e.bag)&&(e.width="100%")}function OX(e){e.id||(e.id=Mi.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)PX(t);e.bag||(e.bag=(0,pt.emptyBag)())}function PX(e){e.cells||(e.cells=[]);for(let t of e.cells)RX(t);e.bag||(e.bag=(0,pt.emptyBag)())}function RX(e){(0,Ht.hasGenPage)(e.control)&&(0,Ht.applyEmbedCellDefaults)(e),e.id||(e.id=Mi.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&&LX(e.control),e.bag||(e.bag=(0,pt.emptyBag)())}function LX(e){var t;(0,Ht.hasGenPage)(e)&&(0,Ht.applyEmbedControlDefaults)(e),e.id||(e.id=Mi.Guid.NewGuid()),e.classId===void 0&&(e.classId=String(nt.ControlClassId.TextboxControl)),e.fieldName===void 0&&(e.fieldName=null),e.type===void 0&&(e.type=e.fieldName?"Field":Ly(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,Ry.assertXmlName)(r,"Form control parameter name");e.bag||(e.bag=(0,pt.emptyBag)())}function kX(e){for(let t of e.c){let r=t.node;if(r.n==="events"){for(let n of r.c)if(n.n==="event"){for(let i of n.c)if(i.n==="Handlers")for(let o of i.c)o.n==="Handler"&&!tL(o,"handlerUniqueId")&&o.a.push(["handlerUniqueId",Oy(Mi.Guid.NewGuid())])}}else if(r.n==="formLibraries")for(let n of r.c)n.n==="Library"&&!tL(n,"libraryUniqueId")&&n.a.push(["libraryUniqueId",Oy(Mi.Guid.NewGuid())])}}var xf=class{constructor(t=rL.DEFAULT_LCID){this.lcid=t}toArtifact(t,r){var n,i,o;let{tabs:a,bag:s}=Q2(t,this.lcid),l={id:t.formId?t.formId.guidString:"",name:(n=t.formName)!==null&&n!==void 0?n:"",entityLogicalName:(i=t.entityName)!==null&&i!==void 0?i:"",formType:(o=rX[t.formType])!==null&&o!==void 0?o:"Main",status:this.readActivationStatus(t),...r!==void 0&&r!==""?{description:r}:{},tabs:a,bag:s};return(0,Ht.projectGenPageEmbeds)(l),(0,ti.projectPcfBindings)(l),l}fromArtifact(t){var r;return this.deserialize({formxml:Z2(t,this.lcid),formid:t.id||(0,Ws.newId)(),objecttypecode:t.entityLogicalName,type:kf[t.formType],name:t.name,uniquename:t.name,description:(r=t.description)!==null&&r!==void 0?r:"",formpresentation:Nt.FormPresentation.AirForm,formactivationstate:t.status==="Active"?Nt.FormActivationState.Active:Nt.FormActivationState.InActive})}fromApiResponse(t){var r,n,i,o,a,s,l;let u=t,c=(r=u.formxml)!==null&&r!==void 0?r:"",d={formxml:c,formid:(n=u.formid)!==null&&n!==void 0?n:(0,Ws.newId)(),objecttypecode:(i=u.objecttypecode)!==null&&i!==void 0?i:"",type:u.type,name:(o=u.name)!==null&&o!==void 0?o:"",uniquename:(a=u.uniquename)!==null&&a!==void 0?a:"",description:(s=u.description)!==null&&s!==void 0?s:"",formpresentation:u.formpresentation,formactivationstate:u.formactivationstate};(0,Dy.installDomShim)();let f=K2.ScriptUtilities.ParseXml(c),p=xX(f),m=this.deserializeDocument(d,f);return $X(this.toArtifact(m,(l=u.description)!==null&&l!==void 0?l:void 0),p)}toApiPayload(t,r,n){let i=(0,Ht.genPageEmbedIssues)(t);if(i.length>0)throw new Gs.ValidationError("form",t.id,i);let o=(0,ti.pcfBindingIssues)(t,r,{atPush:!0});if(o.length>0)throw new Gs.ValidationError("form",t.id,o);let a=(0,ti.pcfReadIssues)(t,n?.pcf,r);if(a.unavailable)throw(0,Gs.attachCause)(new Gs.SdkError(a.unavailable.code,a.unavailable.message),a.unavailable.cause);if(a.issues.length>0)throw new Gs.ValidationError("form",t.id,a.issues);return{formxml:Z2(t,this.lcid,n,r),name:t.name,type:kf[t.formType],objecttypecode:t.entityLogicalName,...t.description!==void 0?{description:t.description}:{}}}metadataNeeds(t){let r=t.entityLogicalName;if(!r)return[];let n=new Map;return Fy(t,i=>{var o;let a=i.fieldName,s=i;if(!a||s.label!==void 0&&s.classId!==void 0)return;let l=(o=n.get(a))!==null&&o!==void 0?o:{entityLogicalName:r,fieldName:a};s.label===void 0&&(l.needsLabel=!0),n.set(a,l)}),[...n.values()]}customControlNeeds(t,r){var n;return{entityLogicalName:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",...(0,ti.customControlNeeds)(t,r)}}createDefault(t){var r,n,i,o,a,s,l,u,c,d,f;let p=[...(0,Ht.genPageEmbedIssues)(t),...(0,ti.pcfBindingIssues)(t)];if(p.length>0)throw new Gs.ValidationError("form",t.id||"(new)",p);let m=t.tabs&&t.tabs.length>0?void 0:jX(this.lcid),h=m!==void 0?m:t.tabs.map(w=>FX(w,this.lcid)).join(""),g=this.deserialize({formxml:`<form><tabs>${h}</tabs></form>`,formid:t.id||(0,Ws.newId)(),objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",type:kf[(n=t.formType)!==null&&n!==void 0?n:"Main"],name:(i=t.name)!==null&&i!==void 0?i:"New Form",uniquename:(o=t.name)!==null&&o!==void 0?o:"New Form",description:(a=t.description)!==null&&a!==void 0?a:"",formpresentation:Nt.FormPresentation.AirForm,formactivationstate:((s=t.status)!==null&&s!==void 0?s:"Active")==="Active"?Nt.FormActivationState.Active:Nt.FormActivationState.InActive}),b=this.toArtifact(g,t.description);if(t.tabs&&t.tabs.length>0){let w=eL(t);eL(b).forEach((E,A)=>{w[A]&&w[A].label===void 0&&delete E.label,w[A]&&w[A].genPage!==void 0&&(E.genPage=JSON.parse(JSON.stringify(w[A].genPage))),w[A]&&w[A].customControl!==void 0&&(E.customControl=JSON.parse(JSON.stringify(w[A].customControl)))})}return{id:(l=t.id)!==null&&l!==void 0?l:b.id,name:(u=t.name)!==null&&u!==void 0?u:"New Form",entityLogicalName:(c=t.entityLogicalName)!==null&&c!==void 0?c:"",formType:(d=t.formType)!==null&&d!==void 0?d:"Main",status:(f=t.status)!==null&&f!==void 0?f:"Active",...t.description!==void 0?{description:t.description}:{},tabs:b.tabs,bag:b.bag}}assignMissingIds(t){return(0,Ws.assignMissingIds)(t)}completeAsStored(t,r){return(0,tX.completeRecordAsStored)(t,r,this.lcid)}normalize(t){return(0,ti.mintPcfIdentity)((0,Ht.mintEmbedIdentity)(t))}committed(t,r){var n,i,o,a,s,l;let u=r?.formxml;if(typeof u!="string"||!((0,Ht.mayCommitEmbedState)(t)||(0,ti.mayCommitPcfState)(t)))return{artifact:t,baseline:t};let c=this.deserialize({formxml:u,formid:t.id||(0,Ws.newId)(),objecttypecode:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",type:kf[(i=t.formType)!==null&&i!==void 0?i:"Main"],name:(o=t.name)!==null&&o!==void 0?o:"",uniquename:(a=t.name)!==null&&a!==void 0?a:"",description:(s=t.description)!==null&&s!==void 0?s:"",formpresentation:Nt.FormPresentation.AirForm,formactivationstate:Nt.FormActivationState.Active}),{bag:d}=Q2(c,this.lcid),f=(0,ti.commitPcfState)((0,Ht.commitEmbedState)(t,(l=(0,Ht.descriptionsRegion)(d))===null||l===void 0?void 0:l.node),Ly);return{artifact:f,baseline:f}}validate(t){return tZ(t)}deserialize(t){return(0,Dy.installDomShim)(),this.deserializeDocument(t,K2.ScriptUtilities.ParseXml(t.formxml))}deserializeDocument(t,r){let n=new XQ.DeserializationService(this.lcid).deSerializeFormXml(r,new Mi.Guid(t.formid),t.objecttypecode,Nt.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===Nt.FormActivationState.InActive?"Inactive":"Active"}};Tr.FormAdapter=xf;function xX(e){var t;let r=e?.getElementsByTagName("form")[0],n=new Set;for(let i=(t=r?.firstChild)!==null&&t!==void 0?t:null;i;i=i.nextSibling)i.nodeType===1&&(i.nodeName==="header"||i.nodeName==="footer")&&n.add(i.nodeName);return n}function $X(e,t){var r;if(!(!((r=e.bag)===null||r===void 0)&&r.c))return e;let n=["header","footer"].filter(o=>!t.has(o)),i=e.bag.c.filter(o=>{var a;return n.includes((a=o?.node)===null||a===void 0?void 0:a.n)}).map(o=>o.i);return i.length>0&&(e.bag.c=e.bag.c.filter(o=>{var a;return!n.includes((a=o?.node)===null||a===void 0?void 0:a.n)}).map(o=>({...o,i:o.i-i.filter(a=>a<o.i).length}))),e}function Dn(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function My(e,t){return e?`<labels><label description="${Dn(e)}" languagecode="${t}" /></labels>`:""}function Uy(e){return e&&e.length>0?Gu(e):(0,Ws.newId)()}function FX(e,t){var r,n,i,o;let a=(r=e.columns)!==null&&r!==void 0?r:[],s=(a.length>0?a:[zX()]).map(l=>MX(l,t)).join("");return`<tab id="{${Dn(Uy(e.id))}}" name="${Dn((n=e.name)!==null&&n!==void 0?n:"")}" expanded="${(i=e.expanded)!==null&&i!==void 0?i:!0}" visible="${(o=e.visible)!==null&&o!==void 0?o:!0}">${My(e.label,t)}<columns>${s}</columns></tab>`}function MX(e,t){var r,n;let i=((r=e.sections)!==null&&r!==void 0?r:[]).map(o=>UX(o,t)).join("");return`<column width="${Dn((n=e.width)!==null&&n!==void 0?n:"100%")}"><sections>${i}</sections></column>`}function UX(e,t){var r,n,i,o,a;let s=((r=e.rows)!==null&&r!==void 0?r:[]).map(l=>BX(l,t)).join("");return`<section id="{${Dn(Uy(e.id))}}" name="${Dn((n=e.name)!==null&&n!==void 0?n:"")}" showlabel="${(i=e.showLabel)!==null&&i!==void 0?i:!1}" visible="${(o=e.visible)!==null&&o!==void 0?o:!0}" columns="${Iy((a=e.columns)!==null&&a!==void 0?a:1)}">${My(e.label,t)}<rows>${s}</rows></section>`}function BX(e,t){var r;return`<row>${((r=e.cells)!==null&&r!==void 0?r:[]).map(n=>qX(n,t)).join("")}</row>`}function qX(e,t){var r,n,i,o,a;let s=VX(e),l=s.control,u=l?My((r=l.label)!==null&&r!==void 0?r:"",t):"",c=l?GX(l):"";return`<cell id="{${Dn(Uy(s.id))}}" showlabel="${l?(n=l.showLabel)!==null&&n!==void 0?n:!0:!1}" visible="${(i=s.visible)!==null&&i!==void 0?i:!0}" colspan="${(o=s.colspan)!==null&&o!==void 0?o:1}" rowspan="${(a=s.rowspan)!==null&&a!==void 0?a:1}">${u}${c}</cell>`}function VX(e){if(!(0,Ht.hasGenPage)(e.control))return e;let t={...e.control};(0,Ht.applyEmbedControlDefaults)(t);let r={...e,control:t};return(0,Ht.applyEmbedCellDefaults)(r),r}function GX(e){var t,r,n;let i=e.fieldName?` datafieldname="${Dn(e.fieldName)}"`:"",o=WX(e.parameters),a=e.classId?Gu(e.classId):String(nt.ControlClassId.TextboxControl);return`<control id="${Dn((t=e.id)!==null&&t!==void 0?t:"")}" classid="{${Dn(a)}}"${i} disabled="${(r=e.isReadOnly)!==null&&r!==void 0?r:!1}" isrequired="${(n=e.isRequired)!==null&&n!==void 0?n:!1}">${o}</control>`}function WX(e){let t=Object.keys(e??{});return t.length===0?"":(t.forEach(n=>(0,Ry.assertXmlName)(n,"Form control parameter name")),`<parameters>${t.map(n=>`<${n}>${Dn(e[n])}</${n}>`).join("")}</parameters>`)}function zX(){return{width:"100%",sections:[],bag:{a:[],c:[]}}}function jX(e){return`<tab id="{${Mi.Guid.NewGuid()}}" name="tab_general" expanded="true" visible="true"><labels><label description="General" languagecode="${e}" /></labels><columns><column width="100%"><sections><section id="{${Mi.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 HX(e=rL.DEFAULT_LCID){return{adapter:new xf(e),api:eX.formApi,languageSensitive:!0,publish:(t,r,n)=>(0,J2.publishBoundEntity)(t,n),publishScope:(t,r)=>(0,J2.boundEntityPublishScope)(r),rebaselineAfterPublish:"bracket"}}Tr.formRegistration=HX;var KX=new Set(["id","name","label","expanded","visible","columns","bag"]),JX=new Set(["id","width","sections","bag"]),YX=new Set(["id","name","label","visible","showLabel","columns","rows","bag"]),QX=new Set(["id","cells","bag"]),XX=new Set(["id","visible","colspan","rowspan","control","bag"]),ZX=new Set(["id","classId","fieldName","type","isRequired","isReadOnly","label","showLabel","parameters","genPage","customControl","bag"]),eZ={elsewhere:{isReadOnly:"control",isRequired:"control",fieldName:"control",classId:"control",label:"control",showLabel:"control",parameters:"control"},unsupported:{createOnly:"FormXml has no create-only concept; gate the field with a business rule instead. Raise it with the SDK owners if you need it modeled.",updateOnly:"FormXml has no update-only concept; gate the field with a business rule instead. Raise it with the SDK owners if you need it modeled."}};function tZ(e){let t=[];return(0,_r.childObjects)(e,"tabs","","tab",t).forEach(({node:n,index:i})=>{let o=`/tabs/${i}`;(0,_r.rejectUnknownKeys)(n,KX,o,"tab",t),(0,_r.childObjects)(n,"columns",o,"column",t).forEach(({node:s,index:l})=>{let u=`${o}/columns/${l}`;(0,_r.rejectUnknownKeys)(s,JX,u,"column",t),(0,_r.childObjects)(s,"sections",u,"section",t).forEach(({node:d,index:f})=>{let p=`${u}/sections/${f}`;(0,_r.rejectUnknownKeys)(d,YX,p,"section",t),(0,_r.childObjects)(d,"rows",p,"row",t).forEach(({node:h,index:g})=>{let b=`${p}/rows/${g}`;(0,_r.rejectUnknownKeys)(h,QX,b,"row",t),(0,_r.childObjects)(h,"cells",b,"cell",t).forEach(({node:E,index:A})=>{let L=`${b}/cells/${A}`;(0,_r.rejectUnknownKeys)(E,XX,L,"cell",t,eZ);let R=E.control;R!=null&&!(0,_r.isJsonObject)(R)?t.push((0,_r.issue)(`${L}/control`,"control-must-be-object-or-null",`a cell control must be a JSON object or null, got ${typeof R}`)):(0,_r.isJsonObject)(R)&&(0,_r.rejectUnknownKeys)(R,ZX,`${L}/control`,"control",t)})})})})}),t.push(...(0,Ht.genPageEmbedIssues)(e)),t.push(...(0,ti.pcfBindingIssues)(e)),t}Tr.SUBGRID_CLASS_ID=nt.ControlClassId.SubgridControl;Tr.NOTES_CLASS_ID=nt.ControlClassId.TimelineControl;Tr.QUICK_VIEW_CLASS_ID=nt.ControlClassId.QuickViewControl;var rZ={Lookup:String(nt.ControlClassId.LookupControl),Customer:String(nt.ControlClassId.LookupControl),Owner:String(nt.ControlClassId.LookupControl),PartyList:String(nt.ControlClassId.PartyListControl),Boolean:String(nt.ControlClassId.BooleanControl),DateTime:String(nt.ControlClassId.DateTimeControl),Decimal:String(nt.ControlClassId.DecimalControl),Double:String(nt.ControlClassId.FloatingNumberControl),Money:String(nt.ControlClassId.CurrencyControl),Integer:String(nt.ControlClassId.IntegerControl),BigInt:String(nt.ControlClassId.IntegerControl),Memo:String(nt.ControlClassId.TextAreaControl),String:String(nt.ControlClassId.TextboxControl)},nZ="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE";function lL(e){return e==="Picklist"||e==="State"||e==="Status"?nZ:e&&rZ[e]||String(nt.ControlClassId.TextboxControl)}Tr.classIdForAttributeType=lL;function tL(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}});var By=v(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.viewApi=zs.findDefaultViews=void 0;var pL=Xt(),ar=ye(),In=ue(),iZ=rs(),cL="savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault",oZ="savedqueryid,name,returnedtypecode,querytype,isdefault",aZ=60*1e3;function Mf(e){return(e.localName||e.nodeName).toLowerCase()}function Wu(e,t){let r;for(let n=0;n<e.attributes.length;n+=1){let i=e.attributes[n];i.nodeName.toLowerCase()===t&&(r=r===void 0?i.value:null)}return r}function sZ(e){if(!e)return;let t=!0,r=()=>{t=!1},n=new iZ.DOMParser({errorHandler:{warning:r,error:r,fatalError:r}}).parseFromString(e,"text/xml").documentElement;return t&&n&&Mf(n)==="fetch"?n:void 0}function lZ(e){for(let t=e.parentNode;t;t=t.parentNode)if(Mf(t)==="link-entity")return!0;return!1}function dL(e,t){var r,n,i;if(((r=e.canbedeleted)===null||r===void 0?void 0:r.Value)!==!1)return!1;let o=sZ(e.fetchxml);if(!o)return!1;let a=Array.from(o.getElementsByTagName("*")),s=a.filter(u=>Mf(u)==="condition"),l=s.length===1?s[0]:void 0;return l!==void 0&&a.filter(u=>Mf(u)==="link-entity").every(u=>{var c;return((c=Wu(u,"link-type"))===null||c===void 0?void 0:c.toLowerCase())==="outer"})&&!lZ(l)&&Wu(l,"entityname")===void 0&&((n=Wu(l,"attribute"))===null||n===void 0?void 0:n.toLowerCase())==="statecode"&&((i=Wu(l,"operator"))===null||i===void 0?void 0:i.toLowerCase())==="eq"&&Wu(l,"value")===String(t)}function uZ(e,t){let r=String(e??"").trim().toLowerCase().split(/\s+/),n=String(t??"").trim().toLowerCase().split(/\s+/);return r.length===n.length&&r.filter((i,o)=>i!==n[o]).length===1}function cZ(e){var t,r;let n=e.filter(a=>dL(a,0)),i=e.filter(a=>dL(a,1)),o=[];for(let a of n)for(let s of i)Math.abs(Date.parse(String((t=s.createdon)!==null&&t!==void 0?t:""))-Date.parse(String((r=a.createdon)!==null&&r!==void 0?r:"")))<=aZ&&uZ(a.name,s.name)&&o.push({active:a,inactive:s});return o.length===1?o[0]:void 0}async function dZ(e,t,r={}){var n;let i=new Set(((n=r.excludeViewIds)!==null&&n!==void 0?n:[]).filter(Boolean)),o=`returnedtypecode eq '${(0,In.odataLiteral)(t)}' and querytype eq 0`,a=`/savedqueries${(0,In.odataQuery)([["$select","savedqueryid,name,canbedeleted,fetchxml,createdon"],["$filter",o]])}`,s=await(0,pL.collectPages)(e,a,`findDefaultViews('${t}')`),l=cZ(s),u=new Set(l?[l.active,l.inactive]:[]);return s.filter(c=>c.savedqueryid&&!i.has(c.savedqueryid)&&u.has(c)).map(c=>{var d;return{id:String(c.savedqueryid),name:String((d=c.name)!==null&&d!==void 0?d:"")}})}zs.findDefaultViews=dZ;async function fZ(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,In.odataPathLiteral)(t)}')${(0,In.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status>=200&&i.status<300){let o=(r=i.body)===null||r===void 0?void 0:r.ObjectTypeCode;return typeof o=="number"?o:void 0}}async function fL(e,t,r){if(!r||!/<grid\b/.test(t)||/<grid[^>]*\bobject=/.test(t))return t;let n=await fZ(e,r);return n===void 0?t:t.replace(/<grid\b/,`<grid object="${n}"`)}zs.viewApi={async get(e,t){let r=(0,In.normalizeGuid)(t,"id"),n=await(0,ar.readRowEtag)(e,"savedqueries","savedqueryid",r),i=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,In.odataQuery)([["$select",cL]]);return{raw:(0,ar.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},async readContentThenToken(e,t){let r=(0,In.normalizeGuid)(t,"id"),n=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,In.odataQuery)([["$select",cL]]),i=(0,ar.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=await(0,ar.readRowEtag)(e,"savedqueries","savedqueryid",r);return{raw:i.body,etag:o}},async list(e,t){let r=`/savedqueries${(0,In.odataQuery)([["$select",oZ],["$filter",t?.entityLogicalName?`returnedtypecode eq '${(0,In.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,pL.collectPages)(e,r,"listArtifacts('view')")).map(i=>{var o,a;return{type:"view",id:(o=i.savedqueryid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",entityLogicalName:i.returnedtypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,ar.echoWrite)("savedqueryid"),o=`/savedqueries${i.query}`,a=await fL(e,n.layoutxml,n.returnedtypecode),s=Object.freeze((0,ar.withClientMintedId)({name:n.name,description:n.description,fetchxml:n.fetchxml,layoutxml:a,returnedtypecode:n.returnedtypecode,querytype:n.querytype,isdefault:n.isdefault},"savedqueryid",r)),l=(0,ar.ensureSuccess)(await(0,ar.resendDeadlockVictim)(()=>e.post(o,{...s},i.options)),e.apiUrl(o));return{id:(0,ar.resolveCreatedId)(l,"savedqueryid","view",r),etag:(0,ar.readEtag)(l)}},async update(e,t,r,n){let i=r,o=(0,In.normalizeGuid)(t,"id"),a=(0,ar.echoWrite)("savedqueryid",{"If-Match":(0,ar.requireEtag)(n,"view",o)}),s=`/savedqueries(${o})${a.query}`,l=await fL(e,i.layoutxml,i.returnedtypecode),u=(0,ar.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,fetchxml:i.fetchxml,layoutxml:l},a.options),e.apiUrl(s));return{id:o,etag:(0,ar.readEtag)(u)}},delete(e,t){return(0,ar.deleteRecord)(e,"savedqueries",t)}}});var DL=v(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});js.viewRegistration=js.ViewAdapter=void 0;var wL=Q(),qr=Zr(),qy=ao(),ga=lo(),mL=Kr(),pZ=By(),Vy=so(),mZ=lt(),CL=100,Bf=class{toArtifact(t){var r,n,i,o,a,s,l,u;(0,Vy.installDomShim)();let c=(r=t.fetchxml)!==null&&r!==void 0?r:"",d=(n=t.layoutxml)!==null&&n!==void 0?n:"",f=(0,ga.parseXmlRoot)(c,"<fetch/>"),p=(0,ga.parseXmlRoot)(d,"<grid/>"),m=AL(f);return{id:(i=t.savedqueryid)!==null&&i!==void 0?i:"",name:(o=t.name)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",entityLogicalName:(s=t.returnedtypecode)!==null&&s!==void 0?s:gZ(f),queryType:(l=t.querytype)!==null&&l!==void 0?l:0,isDefault:(u=t.isdefault)!==null&&u!==void 0?u:!1,columns:EL(p,f),filters:NL(f),sort:SL(f),...m.length>0?{linkEntities:m}:{},fetchBag:c?(0,ga.projectElementBag)(f):void 0,layoutBag:d?(0,ga.projectElementBag)(p):void 0}}fromArtifact(t){(0,Vy.installDomShim)();let{fetchxml:r,layoutxml:n}=hL(t);return{savedqueryid:t.id,name:t.name,description:t.description,returnedtypecode:t.entityLogicalName,querytype:t.queryType,isdefault:t.isDefault,fetchxml:r,layoutxml:n}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){var r,n,i,o,a;(0,Vy.installDomShim)();let{fetchxml:s,layoutxml:l}=hL(t);return{name:(r=t.name)!==null&&r!==void 0?r:"",description:(n=t.description)!==null&&n!==void 0?n:"",fetchxml:s,layoutxml:l,returnedtypecode:(i=t.entityLogicalName)!==null&&i!==void 0?i:"",querytype:(o=t.queryType)!==null&&o!==void 0?o:0,isdefault:(a=t.isDefault)!==null&&a!==void 0?a:!1}}createDefault(t){var r,n,i,o,a,s,l,u;let c=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,mZ.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New View",description:(o=t.description)!==null&&o!==void 0?o:"",entityLogicalName:c,queryType:(a=t.queryType)!==null&&a!==void 0?a:0,isDefault:(s=t.isDefault)!==null&&s!==void 0?s:!1,columns:t.columns&&t.columns.length>0?t.columns:[{name:`${c}id`,width:300,order:0}],filters:(l=t.filters)!==null&&l!==void 0?l:{type:"and",conditions:[],groups:[]},sort:(u=t.sort)!==null&&u!==void 0?u:[],...t.linkEntities&&t.linkEntities.length>0?{linkEntities:t.linkEntities}:{}}}assignMissingIds(t){return t}validate(t){let r=[],n=t;(0,qr.childObjects)(n,"columns","","column",r),(0,qr.childObjects)(n,"sort","","sort",r),(0,qr.childObjects)(n,"linkEntities","","linkEntity",r),hZ(n.linkEntities,r);let i=n.filters;return i!=null&&((0,qr.isJsonObject)(i)?Gy(i,"/filters",r):r.push((0,qr.issue)("/filters","filters-must-be-object",`filters must be a JSON object, got ${typeof i}`))),r}};js.ViewAdapter=Bf;function hZ(e,t){Array.isArray(e)&&e.forEach((r,n)=>{if(!(0,qr.isJsonObject)(r))return;for(let o of["name","from","to"]){let a=r[o];(typeof a!="string"||a.trim()==="")&&t.push((0,qr.issue)(`/linkEntities/${n}/${o}`,"linkentity-needs-keys",`a join needs a non-empty '${o}' \u2014 'from'/'to' are what DEFINE the relationship, and a link without them is unresolvable. Got ${JSON.stringify(a)}.`))}let i=r.filters;i!=null&&((0,qr.isJsonObject)(i)?Gy(i,`/linkEntities/${n}/filters`,t):t.push((0,qr.issue)(`/linkEntities/${n}/filters`,"filters-must-be-object",`filters must be a JSON object, got ${typeof i}`)))})}function Gy(e,t,r){(0,qr.childObjects)(e,"conditions",t,"condition",r),(0,qr.childObjects)(e,"groups",t,"filterGroup",r).forEach(({node:i,index:o})=>Gy(i,`${t}/groups/${o}`,r))}function gZ(e){var t;let r=e.getElementsByTagName("entity")[0];return(t=r?.getAttribute("name"))!==null&&t!==void 0?t:""}function EL(e,t){var r;let n=Wy(t),i=e.getElementsByTagName("cell"),o=[],a=0;for(let s=0;s<i.length;s+=1){let l=i[s];if(l.getAttribute("ishidden")==="1")continue;let u=l.getAttribute("name");if(!u)continue;let c=parseInt((r=l.getAttribute("width"))!==null&&r!==void 0?r:"",10),d={name:u,width:Number.isNaN(c)?CL:c,order:a},f=n.get(u);f&&(d.relatedEntity=f.linkKey,f.attributeName&&f.attributeName!==u&&(d.sourceAttribute=f.attributeName)),a+=1,o.push(d)}return o}function Wy(e){let t=new Map,r=e.getElementsByTagName("link-entity");for(let n=0;n<r.length;n+=1){let i=r[n],o=i.getAttribute("name");if(!o)continue;let a=i.getElementsByTagName("attribute");for(let s=0;s<a.length;s+=1){let l=a[s],u=l.getAttribute("name")||"",c=l.getAttribute("alias")||u;c&&t.set(c,{linkKey:i.getAttribute("alias")||o,linkName:o,attributeName:u,link:i})}}return t}function AL(e){let t=e.getElementsByTagName("entity")[0];if(!t)return[];let r=[];for(let n of Kt(t,"link-entity")){let i=n.getAttribute("name"),o=n.getAttribute("from"),a=n.getAttribute("to");if(!i||!o||!a)continue;let s=n.getAttribute("alias"),l=n.getAttribute("link-type"),u=Kt(n,"filter").find(c=>!qf(c));r.push({name:i,from:o,to:a,...s?{alias:s}:{},...l==="inner"||l==="outer"?{linkType:l}:{},...u?{filters:zy(u)}:{}})}return r}function SL(e){var t;let r=e.getElementsByTagName("entity")[0];if(!r)return[];let n=[],i=r.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];if(a.nodeType===1&&a.tagName==="order"){let s=a.getAttribute("attribute");s&&n.push({attribute:s,descending:((t=a.getAttribute("descending"))!==null&&t!==void 0?t:"").toLowerCase()==="true",entityname:a.getAttribute("entityname")||""})}}return n}function NL(e){let t=e.getElementsByTagName("entity")[0],r={type:"and",conditions:[],groups:[]};if(!t)return r;let n=Kt(t,"filter").filter(i=>!qf(i)).map(zy);return n.length===0?r:n.length===1?n[0]:{type:"and",conditions:[],groups:n}}function qf(e){if(e.getAttribute("isquickfindfields")==="1")return!0;if(Kt(e,"filter").length>0)return!1;let t=Kt(e,"condition");return t.length===0?!1:t.some(r=>r.getAttribute("isquickfindfields")==="1"||Kt(r,"value").length>0||bZ(r))}var yZ=new Set(["attribute","operator","value","entityname","uiname","uitype"]);function bZ(e){var t;let r=e.attributes;for(let n=0;n<r.length;n+=1){let i=(t=r[n])===null||t===void 0?void 0:t.name;if(i&&!yZ.has(i))return!0}return!1}function zy(e){var t,r;let n=((t=e.getAttribute("type"))!==null&&t!==void 0?t:"and").toLowerCase()==="or"?"or":"and",i=[],o=[],a=e.childNodes;for(let s=0;s<a.length;s+=1){let l=a[s];if(l.nodeType===1)if(l.tagName==="condition"){if(l.getAttribute("isquickfindfields")==="1")continue;let u=l.getAttribute("attribute");if(!u)continue;let c={attribute:u,operator:(r=l.getAttribute("operator"))!==null&&r!==void 0?r:""},d=l.getAttribute("value");d!==null&&(c.value=d);let f=l.getAttribute("entityname")||"";f&&(c.entityname=f),i.push(c)}else l.tagName==="filter"&&o.push(zy(l))}return{type:n,conditions:i,groups:o}}function Kt(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName===t&&r.push(o)}return r}var jy=e=>{var t,r;return`${(t=e.relatedEntity)!==null&&t!==void 0?t:""}::${(r=e.sourceAttribute)!==null&&r!==void 0?r:e.name}`};function vZ(e,t){let r=Wy(e),n=new Map;for(let i of t){if(!i.relatedEntity)continue;let o=r.get(i.name);if(o){let a=jy(i),s=n.get(a);s?s.push(o.link):n.set(a,[o.link])}}return n}function wZ(e,t,r,n){if(!n||n.size===0)return;let i=new Set,o=t.getElementsByTagName("link-entity");for(let s=0;s<o.length;s+=1)i.add(o[s]);let a=r.filter(s=>{if(!s.relatedEntity)return!1;let l=n.get(jy(s));return!!l&&l.some(u=>!i.has(u))});if(a.length!==0)throw new wL.ValidationError("view",e.id,a.map(s=>(0,qr.issue)(`/columns/${r.indexOf(s)}`,"view-column-orphaned-by-join-removal",`column '${s.name}' came from a join this push REMOVED. Another join matching '${s.relatedEntity}' still exists, but nothing can say whether it is the one the column belonged to \u2014 re-attaching it there would silently change the data the column shows. Remove the column too, keep the join it came from, or point the column at the join you want by setting relatedEntity to that join's alias.`)))}function hL(e){let t=CZ(e.columns);if(!gL(e.fetchBag)||!gL(e.layoutBag))return{fetchxml:LZ({...e,columns:t}),layoutxml:kZ({...e,columns:t},`${e.entityLogicalName}id`)};let r=new DOMParser().parseFromString("<root/>","text/xml"),n=yL(e.fetchBag,"fetch",r),i=yL(e.layoutBag,"grid",r),o=EL(i,n),a=!Uf(t,o),s=!Uf(e.sort,SL(n)),l=!Uf(e.filters,NL(n)),u=e.linkEntities,c=u!==void 0&&!Uf(u,AL(n)),d=c?vZ(n,o):void 0;return c&&OZ(r,n,u),c&&(RZ(e,n,t,d),wZ(e,n,t,d)),a?(bL(r,n,t,o),NZ(r,i,t)):c&&bL(r,n,t,o),s&&DZ(r,n,e.sort),l&&IZ(r,n,e.filters),{fetchxml:(0,ga.serializeNode)(n),layoutxml:(0,ga.serializeNode)(i)}}function CZ(e){return(e??[]).map((t,r)=>{var n,i;return{name:String(t.name).toLowerCase(),width:(n=t.width)!==null&&n!==void 0?n:CL,order:(i=t.order)!==null&&i!==void 0?i:r,...t.relatedEntity?{relatedEntity:t.relatedEntity}:{},...t.sourceAttribute?{sourceAttribute:String(t.sourceAttribute).toLowerCase()}:{}}})}function gL(e){return!!e&&(e.c.length>0||e.a.length>0)}function yL(e,t,r){let n={n:t,a:(0,qy.mergeAttrs)(e.a,[]),c:(0,qy.spliceChildren)(e.c,[])};return(0,qy.rebuildRaw)(n,(0,ga.domEngine)(r),null)}function bL(e,t,r,n){var i,o;let a=t.getElementsByTagName("entity")[0];if(!a)return;let s=d=>{var f,p;return`${(f=d.relatedEntity)!==null&&f!==void 0?f:""}:${d.name}:${(p=d.sourceAttribute)!==null&&p!==void 0?p:d.name}`},l=new Set(r.map(s));for(let d of n)l.has(s(d))||EZ(a,d);let u=Wy(t),c=new Set(Kt(a,"attribute").map(d=>d.getAttribute("name")).filter(d=>!!d));for(let d of[...r].sort((f,p)=>f.order-p.order))if(d.relatedEntity){let f=u.get(d.name);if(f&&f.attributeName===((i=d.sourceAttribute)!==null&&i!==void 0?i:d.name)&&(f.linkKey===d.relatedEntity||f.linkName===d.relatedEntity||!TL(a,d.relatedEntity)))continue;let p=AZ(e,a,d.relatedEntity),m=e.createElement("attribute");_L(m,d),p.appendChild(m),u.set(d.name,{linkKey:d.relatedEntity,linkName:p.getAttribute("name")||d.relatedEntity,attributeName:(o=d.sourceAttribute)!==null&&o!==void 0?o:d.name,link:p})}else{if(c.has(d.name))continue;let f=e.createElement("attribute");f.setAttribute("name",d.name),SZ(a,f),c.add(d.name)}}function _L(e,t){if(t.sourceAttribute&&t.sourceAttribute!==t.name){e.setAttribute("name",t.sourceAttribute),e.setAttribute("alias",t.name);return}e.setAttribute("name",t.name)}function EZ(e,t){if(t.relatedEntity){for(let r of Kt(e,"link-entity"))if(!(r.getAttribute("alias")!==t.relatedEntity&&r.getAttribute("name")!==t.relatedEntity)){for(let n of Kt(r,"attribute"))if((n.getAttribute("alias")||n.getAttribute("name"))===t.name){r.removeChild(n);return}}return}for(let r of Kt(e,"attribute"))if(r.getAttribute("name")===t.name){e.removeChild(r);return}}function TL(e,t,r=!1){let n=o=>o.getAttribute("alias")===t||o.getAttribute("name")===t;for(let o of Kt(e,"link-entity"))if(n(o))return o;if(r)return;let i=e.getElementsByTagName("link-entity");for(let o=0;o<i.length;o+=1)if(n(i[o]))return i[o]}function AZ(e,t,r){let n=TL(t,r);if(n)return n;let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function SZ(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 NZ(e,t,r){let n=t.getElementsByTagName("row")[0];if(!n)return;let i=[...r].sort((s,l)=>s.order-l.order),o=_Z(n);if(TZ(o,i)){for(let s=0;s<i.length;s+=1){let l=String(i[s].width);o[s].getAttribute("width")!==l&&o[s].setAttribute("width",l)}return}let a=new Map;for(let s of o){let l=s.getAttribute("name");l&&a.set(l,s),n.removeChild(s)}for(let s of i){let l=a.get(s.name);l||(l=e.createElement("cell"),l.setAttribute("name",s.name)),l.setAttribute("width",String(s.width)),n.appendChild(l)}}function _Z(e){return Kt(e,"cell").filter(t=>!!t.getAttribute("name")&&t.getAttribute("ishidden")!=="1")}function TZ(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 DZ(e,t,r){let n=t.getElementsByTagName("entity")[0];if(!n)return;let i=(f,p)=>`${f.toLowerCase()}\0${p.toLowerCase()}`,o=new Map,a=new Map,s=(f,p,m)=>{let h=f.get(p);h?h.push(m):f.set(p,[m])};for(let f of Kt(n,"order")){let p=f.getAttribute("attribute")||"";p&&(s(o,i(f.getAttribute("entityname")||"",p),f),s(a,p.toLowerCase(),f)),n.removeChild(f)}let l=new Set,u=(f,p)=>{let m=f.get(p);for(;m&&m.length>0;){let h=m.shift();if(!l.has(h))return l.add(h),h}},c=f=>{var p;let m=a.get(f.toLowerCase());if(!m)return;let h=m.filter(b=>!l.has(b)),g=(p=h.find(b=>!b.getAttribute("entityname")))!==null&&p!==void 0?p:h[0];return g&&l.add(g),g},d=r.map(f=>{let p=String(f.attribute);return f.entityname===void 0?{expression:f,element:void 0}:{expression:f,element:u(o,i(f.entityname,p))}});for(let f of d)f.expression.entityname===void 0&&(f.element=c(String(f.expression.attribute)));for(let{expression:f,element:p}of d){let m=p??e.createElement("order");m.setAttribute("attribute",f.attribute),m.setAttribute("descending",String(f.descending)),f.entityname?m.setAttribute("entityname",f.entityname):f.entityname===""&&m.removeAttribute("entityname"),n.appendChild(m)}}function IZ(e,t,r){let n=t.getElementsByTagName("entity")[0];if(n){for(let i of Kt(n,"filter"))qf(i)||n.removeChild(i);(r.conditions.length>0||r.groups.length>0)&&n.appendChild(zu(e,r))}}function Uf(e,t){return JSON.stringify(e)===JSON.stringify(t)}function OZ(e,t,r){var n;let i=t.getElementsByTagName("entity")[0];if(!i)return;let o=Kt(i,"link-entity").filter(m=>m.getAttribute("name")&&m.getAttribute("from")&&m.getAttribute("to")),a=(m,h)=>m.getAttribute(h)||"",s=new Array(r.length),l=new Set,u=m=>{r.forEach((h,g)=>{if(s[g])return;let b=o.filter(A=>!l.has(A)&&m(A,h));if(b.length!==1)return;let w=b[0];r.some((A,L)=>L!==g&&!s[L]&&m(w,A))||(s[g]=w,l.add(w))})};u((m,h)=>!!h.alias&&a(m,"name")===h.name&&a(m,"alias")===h.alias),u((m,h)=>a(m,"name")===h.name&&a(m,"from")===h.from&&a(m,"to")===h.to),u((m,h)=>a(m,"name")===h.name&&a(m,"from")===h.from),u((m,h)=>a(m,"name")===h.name&&a(m,"to")===h.to),u((m,h)=>a(m,"name")===h.name);let c=r.map((m,h)=>h).filter(m=>!s[m]),d=o.filter(m=>!l.has(m)),f=new Map;for(let m of d){let h=f.get(a(m,"name"));h?h.push(m):f.set(a(m,"name"),[m])}let p=new Map;for(let m of c){let h=p.get(r[m].name);h?h.push(m):p.set(r[m].name,[m])}for(let[m,h]of p){let g=(n=f.get(m))!==null&&n!==void 0?n:[];g.length===h.length&&h.forEach((b,w)=>{s[b]=g[w],l.add(g[w])})}r.forEach((m,h)=>{let g=s[h];if(g){vL(e,g,m);return}let b=e.createElement("link-entity");vL(e,b,m),i.appendChild(b)});for(let m of o)l.has(m)||i.removeChild(m)}var PZ=new Set(["inner","outer"]);function RZ(e,t,r,n){if(!t.getElementsByTagName("entity")[0])return;let o=new Set,a=t.getElementsByTagName("link-entity");for(let c=0;c<a.length;c+=1){let d=a[c],f=d.getAttribute("name"),p=d.getAttribute("alias");f&&o.add(f),p&&o.add(p)}let s=new Set;for(let c=0;c<a.length;c+=1)s.add(a[c]);let l=c=>{let d=n?.get(jy(c));return!!d&&d.every(f=>s.has(f))},u=r.filter(c=>c.relatedEntity&&!o.has(c.relatedEntity)&&!l(c));if(u.length!==0)throw new wL.ValidationError("view",e.id,u.map(c=>{var d;let f=((d=e.linkEntities)!==null&&d!==void 0?d:[]).some(p=>p.name===c.relatedEntity||p.alias===c.relatedEntity);return(0,qr.issue)(`/columns/${r.indexOf(c)}`,"view-column-dangling-link",`column '${c.name}' has relatedEntity '${c.relatedEntity}', but no matching join remains in linkEntities. `+(f?"Remove the column too, or keep the join.":"That join is NESTED (a join off a join), which the typed layer does not model, so it cannot be re-declared in linkEntities \u2014 it only survives while the join above it does. Remove the column, or restore the parent join this push replaced."))}))}function vL(e,t,r){t.setAttribute("name",r.name),t.setAttribute("from",r.from),t.setAttribute("to",r.to),r.alias?t.setAttribute("alias",r.alias):t.removeAttribute("alias"),r.linkType?t.setAttribute("link-type",r.linkType):PZ.has(t.getAttribute("link-type")||"")&&t.removeAttribute("link-type");let n=Kt(t,"filter").find(o=>!qf(o)),i=r.filters&&(r.filters.conditions.length>0||r.filters.groups.length>0)?zu(e,r.filters):null;n&&i?t.replaceChild(i,n):n?t.removeChild(n):i&&t.appendChild(i)}function LZ(e){var t;let r=new DOMParser().parseFromString("<fetch/>","text/xml"),n=r.documentElement;n.setAttribute("version","1.0"),n.setAttribute("mapping","logical");let i=r.createElement("entity");i.setAttribute("name",e.entityLogicalName),n.appendChild(i);let o=new Map;for(let a of(t=e.linkEntities)!==null&&t!==void 0?t:[]){let s=r.createElement("link-entity");s.setAttribute("name",a.name),s.setAttribute("from",a.from),s.setAttribute("to",a.to),a.alias&&s.setAttribute("alias",a.alias),a.linkType&&s.setAttribute("link-type",a.linkType),a.filters&&(a.filters.conditions.length>0||a.filters.groups.length>0)&&s.appendChild(zu(r,a.filters)),i.appendChild(s);for(let l of[a.alias||a.name,a.name])o.has(l)||o.set(l,s)}for(let a of[...e.columns].sort((s,l)=>s.order-l.order)){let s=r.createElement("attribute");if(a.relatedEntity){_L(s,a);let l=o.get(a.relatedEntity);l||(l=r.createElement("link-entity"),l.setAttribute("name",a.relatedEntity),i.appendChild(l),o.set(a.relatedEntity,l)),l.appendChild(s)}else s.setAttribute("name",a.name),i.appendChild(s)}for(let a of e.sort){let s=r.createElement("order");s.setAttribute("attribute",a.attribute),s.setAttribute("descending",String(a.descending)),a.entityname&&s.setAttribute("entityname",a.entityname),i.appendChild(s)}return(e.filters.conditions.length>0||e.filters.groups.length>0)&&i.appendChild(zu(r,e.filters)),new XMLSerializer().serializeToString(r)}function zu(e,t){let r=e.createElement("filter");r.setAttribute("type",t.type);for(let n of t.conditions){let i=e.createElement("condition");i.setAttribute("attribute",n.attribute),i.setAttribute("operator",n.operator),n.entityname&&i.setAttribute("entityname",n.entityname),n.value!==void 0&&i.setAttribute("value",n.value),r.appendChild(i)}for(let n of t.groups)r.appendChild(zu(e,n));return r}function kZ(e,t){var r;let n=new DOMParser().parseFromString("<grid/>","text/xml"),i=n.documentElement,o=[...e.columns].sort((s,l)=>s.order-l.order);i.setAttribute("name","resultset"),i.setAttribute("jump",((r=o[0])===null||r===void 0?void 0:r.name)||t||`${e.entityLogicalName}id`),i.setAttribute("select","1"),i.setAttribute("icon","1"),i.setAttribute("preview","1");let a=n.createElement("row");a.setAttribute("name","result"),a.setAttribute("id",t||`${e.entityLogicalName}id`),i.appendChild(a);for(let s of o){let l=n.createElement("cell");l.setAttribute("name",s.name),l.setAttribute("width",String(s.width)),a.appendChild(l)}return new XMLSerializer().serializeToString(n)}function xZ(){return{adapter:new Bf,api:pZ.viewApi,publish:(e,t,r)=>(0,mL.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,mL.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}js.viewRegistration=xZ});function Vf(e,t){return e==="SetFieldValue"&&t!==void 0&&$Z.has(t.attributeType)&&(t.requiredLevel==="None"||t.requiredLevel==="Recommended")}var $Z,Hy=k(()=>{"use strict";$Z=new Set(["Integer","Double","Decimal","Money","String","Memo","DateTime","Picklist","Lookup"])});function IL(e){return e!=="Entity"&&e!=="AllForms"&&typeof e=="string"&&e.trim()!==""}function Ky(e){return e==="AllForms"||IL(e)?1:2}function Jy(e){return IL(e)?e:null}function OL(e,t){return{"@odata.type":"#Microsoft.Dynamics.CRM.workflow",name:e.name,description:e.description,workflowid:t,ondemand:!1,subprocess:!1,triggeroncreate:!1,triggerondelete:!1,category:Hs.WorkflowCategory.BusinessRule,type:Hs.WorkflowTypeCode.Definition,mode:1,scope:Hs.WorkflowScope.Organization,primaryentity:e.entityLogicalName,iscrmuiworkflow:!0,processtriggerscope:Ky(e.scope),processtriggerformid:Jy(e.scope)}}var Hs,PL=k(()=>{"use strict";Hs=we(Ji());});function RL(e,t=0){return(kt[e[t+0]]+kt[e[t+1]]+kt[e[t+2]]+kt[e[t+3]]+"-"+kt[e[t+4]]+kt[e[t+5]]+"-"+kt[e[t+6]]+kt[e[t+7]]+"-"+kt[e[t+8]]+kt[e[t+9]]+"-"+kt[e[t+10]]+kt[e[t+11]]+kt[e[t+12]]+kt[e[t+13]]+kt[e[t+14]]+kt[e[t+15]]).toLowerCase()}var kt,LL=k(()=>{kt=[];for(let e=0;e<256;++e)kt.push((e+256).toString(16).slice(1))});function Yy(){return Gf>Wf.length-16&&((0,kL.randomFillSync)(Wf),Gf=0),Wf.slice(Gf,Gf+=16)}var kL,Wf,Gf,xL=k(()=>{kL=require("crypto"),Wf=new Uint8Array(256),Gf=Wf.length});var $L,Qy,FL=k(()=>{$L=require("crypto"),Qy={randomUUID:$L.randomUUID}});function FZ(e,t,r){if(Qy.randomUUID&&!t&&!e)return Qy.randomUUID();e=e||{};let n=e.random??e.rng?.()??Yy();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 RL(n)}var sr,ML=k(()=>{FL();xL();LL();sr=FZ});var Xy=k(()=>{ML()});var UL=k(()=>{"use strict";});function BL(e){return e!=null&&MZ.has(e)}function zf(e){if(e==null)return!1;let t=e.trim();if(!/^[+-]?\d+$/.test(t))return!1;let r=Number(t);return Number.isInteger(r)&&r>=-2147483648&&r<=2147483647}var MZ,Zy=k(()=>{"use strict";MZ=new Set(["Picklist","State","Status"])});var jf=v(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.WorkflowConditionOperator=un.WorkflowAttributeType=un.SystemStep=un.FieldRequiredLevelTypes=un.AttributeDateTimeBehavior=void 0;un.AttributeDateTimeBehavior={None:0,Dynamic:1,DateOnly:2,StaticTimeZoneInvariant:3,UserLocal:4};un.FieldRequiredLevelTypes={None:"0",Required:"1",Recommended:"2"};un.SystemStep={IdentifyContact:"IdentifyContact",IdentifyAccount:"IdentifyAccount",IdentifyCustomer:"IdentifyCustomer",IdentifyCase:"IdentifyCase",Solution:"Solution",Resolve:"Resolve"};un.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"};un.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 Hf(e){return e!=null&&VL.includes(e)}function eb(e){return e===oe.WorkflowAttributeType.Integer}function tb(e,t){return t===oe.WorkflowConditionOperator.Equal||t===oe.WorkflowConditionOperator.NotEqual?e:UZ.includes(t)?VL.includes(e)||e===oe.WorkflowAttributeType.DateTime?e:oe.WorkflowAttributeType.String:t===oe.WorkflowConditionOperator.On||t===oe.WorkflowConditionOperator.NotOn?e===oe.WorkflowAttributeType.DateTime?e:oe.WorkflowAttributeType.String:oe.WorkflowAttributeType.String}function GL(e){let t=e.leftWorkflowType??e.valueWorkflowType??oe.WorkflowAttributeType.String,r=ju[e.operator]??oe.WorkflowConditionOperator.Equal;return tb(t,r)}function WL(e,t){let r=e.trim(),i=(r.startsWith("+")||r.startsWith("-")?r.slice(1):r).split(".");if(i.length>2)return!1;let[o,a=""]=i;return o.length===0&&a.length===0||!qL.test(o)||!qL.test(a)||o.length>1&&o.startsWith("0")||o.length>BZ?!1:t!==oe.WorkflowAttributeType.Integer||i.length===1}var oe,ju,VL,UZ,qL,BZ,rb=k(()=>{"use strict";oe=we(jf());ju={Equals:oe.WorkflowConditionOperator.Equal,DoesNotEqual:oe.WorkflowConditionOperator.NotEqual,IsGreaterThan:oe.WorkflowConditionOperator.GreaterThan,IsLessThan:oe.WorkflowConditionOperator.LessThan,IsGreaterThanEqualTo:oe.WorkflowConditionOperator.GreaterThanOrEqual,IsLessThanEqualTo:oe.WorkflowConditionOperator.LessThanOrEqual,Contains:oe.WorkflowConditionOperator.Contains,DoesNotContain:oe.WorkflowConditionOperator.DoesNotContain,BeginsWith:oe.WorkflowConditionOperator.BeginsWith,DoesNotBeginWith:oe.WorkflowConditionOperator.DoesNotBeginWith,EndsWith:oe.WorkflowConditionOperator.EndsWith,DoesNotEndWith:oe.WorkflowConditionOperator.DoesNotEndWith,On:oe.WorkflowConditionOperator.On,NotOn:oe.WorkflowConditionOperator.NotOn,ContainsData:oe.WorkflowConditionOperator.NotNull,DoesNotContainData:oe.WorkflowConditionOperator.IsNull},VL=[oe.WorkflowAttributeType.Decimal,oe.WorkflowAttributeType.Float,oe.WorkflowAttributeType.Integer,oe.WorkflowAttributeType.Money],UZ=[oe.WorkflowConditionOperator.GreaterThan,oe.WorkflowConditionOperator.GreaterThanOrEqual,oe.WorkflowConditionOperator.LessThan,oe.WorkflowConditionOperator.LessThanOrEqual];qL=/^\d*$/,BZ=28});var zL=k(()=>{"use strict";});function On(e){return!qZ.has(e)}function nb(e){return e==="Equals"||e==="DoesNotEqual"}function Kf(e){return HL.has(e)?VZ:HZ.has(e)?GZ:KL.has(e)?WZ:JZ.has(e)?jZ:zZ}function JL(e){return Kf(e)[0]}function YL(e,t){return Kf(t).includes(e)}function jL(e){return HL.has(e)?"string":e==="Money"?"money":e==="Integer"||e==="BigInt"?"integer":e==="Decimal"||e==="Double"?"decimal":KL.has(e)?"date":KZ.has(e)?"boolean":"other"}function Jf(e,t){let r=jL(e),n=jL(t);return r==="other"||n==="other"?e===t:r===n}var qZ,VZ,GZ,WZ,zZ,jZ,HL,HZ,KL,KZ,JZ,Yf=k(()=>{"use strict";zL();qZ=new Set(["ContainsData","DoesNotContainData"]);VZ=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],GZ=["Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],WZ=["On","NotOn","Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],zZ=["Equals","DoesNotEqual","ContainsData","DoesNotContainData"],jZ=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],HL=new Set(["String","Memo","EntityName"]),HZ=new Set(["Integer","BigInt","Money","Decimal","Double"]),KL=new Set(["DateTime"]),KZ=new Set(["Boolean"]),JZ=new Set(["Lookup","Owner","Customer"])});function e1(e){switch(e){case"Boolean":return Fe.WorkflowAttributeType.Boolean;case"Customer":return Fe.WorkflowAttributeType.Customer;case"DateTime":return Fe.WorkflowAttributeType.DateTime;case"Decimal":return Fe.WorkflowAttributeType.Decimal;case"Double":return Fe.WorkflowAttributeType.Float;case"Integer":return Fe.WorkflowAttributeType.Integer;case"Lookup":return Fe.WorkflowAttributeType.Lookup;case"Money":return Fe.WorkflowAttributeType.Money;case"Owner":return Fe.WorkflowAttributeType.Owner;case"Picklist":return Fe.WorkflowAttributeType.Picklist;case"State":return Fe.WorkflowAttributeType.State;case"Status":return Fe.WorkflowAttributeType.Status;case"Uniqueidentifier":case"UniqueIdentifier":return Fe.WorkflowAttributeType.UniqueIdentifier;case"BigInt":return Fe.WorkflowAttributeType.BigType;default:return Fe.WorkflowAttributeType.String}}function s1(e){return e&&e!==Fe.WorkflowAttributeType.String?e:void 0}function XZ(e){return{__class:a1,parameterName:"primaryEntity",entityName:e}}function QL(e){return{__class:ob,type:ib,typeSet:!1,behavior:Fe.AttributeDateTimeBehavior.None,method:t1,parameters:[e]}}function XL(e,t,r=Fe.WorkflowAttributeType.String){return{__class:n1,type:r,behavior:Fe.AttributeDateTimeBehavior.None,typeSet:!1,entity:XZ(t),attributeName:e}}function ZZ(e,t=Fe.WorkflowAttributeType.String){return{__class:i1,type:t,behavior:Fe.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function eee(e){return{__class:o1,type:ib,typeSet:!1,behavior:Fe.AttributeDateTimeBehavior.None,days:e,hours:"0",minutes:"0",months:"0",years:"0"}}function l1(e,t){let r=YZ[e.operator],n=QL(XL(e.leftField,t,e.leftWorkflowType)),i;e.dateArithmetic?i=eee(e.right.value??"0"):e.right.kind==="field"?i=XL(e.right.field??"",t,e.right.workflowType):i=ZZ(e.right.value??"",e.right.workflowType??e.leftWorkflowType);let o=QL(i);return{__class:ob,type:ib,typeSet:!1,behavior:Fe.AttributeDateTimeBehavior.None,method:r1,parameters:[r,n,o]}}function u1(e){return typeof e=="object"&&e.__class===ob}function tee(e){return typeof e=="object"&&e.__class===o1}function Qf(e){return u1(e)&&e.method===t1&&e.parameters.length>0?Qf(e.parameters[0]):e}function ZL(e){if(typeof e!="object"||e.__class!==n1)return null;let t=e.entity;if(t&&t.__class&&t.__class!==a1)return null;let r=e.attributeName;return r?{field:r,workflowType:s1(e.type)}:null}function c1(e){if(!e)return null;let t=Qf(e);if(!u1(t)||t.method!==r1||t.parameters.length!==3)return null;let r=t.parameters[0],n=QZ[String(r)];if(!n)return null;let i=ZL(Qf(t.parameters[1]));if(!i)return null;let o=Qf(t.parameters[2]);if(tee(o))return n!=="+"&&n!=="-"?null:{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:String(o.days??"")},dateArithmetic:!0};let a=ZL(o);if(a)return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"field",field:a.field,workflowType:a.workflowType}};if(typeof o=="object"&&o.__class===i1){let s=o.primitiveValue;return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:s!=null?String(s):"",workflowType:s1(o.type)}}}return null}function sb(e){let t=(e??"").trim();if(!/^\d+$/.test(t))return!1;let r=Number(t);return Number.isSafeInteger(r)&&r>=ab&&r<=Ks}function ya(e){if(!e||!e.leftField)return"incomplete";if(e.right.kind==="field")return e.right.field&&e.right.field.trim()?null:"incomplete";let t=e.right.value;return!t||!t.trim()?"incomplete":e.dateArithmetic&&!sb(t)?"invalidDayCount":null}function Js(e){return ya(e)===null}var Fe,t1,r1,ib,n1,i1,ob,o1,a1,YZ,QZ,ab,Ks,Hu=k(()=>{"use strict";Fe=we(jf());Yf();t1="0",r1="3",ib="0",n1="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",i1="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",ob="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",o1="TimeSpanExpression:#Microsoft.Crm.Workflow.Expressions",a1="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions";YZ={"+":0,"-":1,"*":2,"/":3},QZ={0:"+",1:"-",2:"*",3:"/"};ab=0,Ks=2147483647});function nee(e){return e.startsWith("__")&&!ree.has(e)}function iee(e){let t=Object.create(null);return Object.keys(e).forEach(r=>{nee(r)&&(t[r]=e[r])}),Object.keys(t).length>0?t:void 0}function S1(e){return e.__class==="BinaryExpression:#Microsoft.Crm.Workflow.Expressions"}function va(e){return e.__class==="UnaryExpression:#Microsoft.Crm.Workflow.Expressions"}function Xf(e){return S1(e)||va(e)}function oee(e){return e.__class==="ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel"}function Ku(){return{list:[]}}function lb(e,t,r){return e&&e.list.length>0?{list:[{...e.list[0],description:t},...e.list.slice(1)]}:{list:[{labelId:sr(),languageCode:r,description:t}]}}function cb(e){return{__class:"PrimaryEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:"primaryEntity",entityName:e}}function rp(e,t,r,n=z.AttributeDateTimeBehavior.None){return{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:n,typeSet:!1,entity:cb(t),attributeName:e}}function ba(e,t,r=z.AttributeDateTimeBehavior.None){return{__class:"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",type:t,behavior:r,typeSet:!1,primitiveValue:e}}function lee(e){return e.bpfField==="StageCategory"?e.stageType==="SelectedStage"?T1:_1:N1}function D1(e){return e.bpfField==="StageCategory"?z.WorkflowAttributeType.BpfStageCategory:z.WorkflowAttributeType.BpfProcess}function uee(e,t){let r=D1(e),n=e.bpfField==="StageCategory"?{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,entity:{__class:"RelatedEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:`related_${f1}_${d1}`,entityName:d1,relatedAttributeName:f1},attributeName:see}:rp(aee,t,r);return{__class:"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,method:pb,parameters:[lee(e),n]}}function I1(e){let t=e;if(t.__class!=="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"||String(t.method)!==pb)return null;let r=(t.parameters??[])[0];if(typeof r!="string")return null;let n=r.replace(/^"+|"+$/g,"");return n===_1?{bpfField:"StageCategory",stageType:"ActiveStage"}:n===T1?{bpfField:"StageCategory",stageType:"SelectedStage"}:n===N1?{bpfField:"ProcessName"}:null}function Zf(e){if(!e)return!1;let t=e;if(t.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"&&String(t.method)===pb){let r=(t.parameters??[])[0];if(typeof r=="string"&&cee.has(r.replace(/^"+|"+$/g,"")))return!0}return va(e)?Zf(e.operand):S1(e)?Zf(e.left)||(e.right??[]).some(Zf):!1}function O1(e){if(e?.__class!=="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions")return!1;let t=e.entity;return t==null||t.__class==="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions"}function dee(e){if(e?.__class!=="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions")return!1;let t=e.primitiveValue;return t===!0||typeof t=="string"&&t.toLowerCase()==="true"}function p1(e){if(!e)return!1;switch(e.__class){case"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions":return O1(e);case"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions":return e.primitiveValue!=null||e.type!==void 0;case"LookupExpression:#Microsoft.Crm.Workflow.Expressions":case"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions":return!0;default:return!1}}function fee(e){let t=fb[e.conditionOperatoroperator];if(!t)return!1;let r=t==="ContainsData"||t==="DoesNotContainData";if(va(e))return r&&m1(e.operand,!0);let n=e.right??[];return n.length!==(r?0:1)?!1:m1(e.left,r,n[0])}function m1(e,t,r){return I1(e)||O1(e)?t||p1(r):!1}function db(e){if(!e||!Xf(e))return!1;let t=e.conditionOperatoroperator;if(!va(e)&&(t===z.WorkflowConditionOperator.LogicalAnd||t===z.WorkflowConditionOperator.LogicalOr)){let r=e.right??[];return r.length>0&&db(e.left)&&r.every(db)}return fee(e)}function h1(e){return!e||dee(e)?!1:Zf(e)||!db(e)}function P1(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:ba(e.id.replace(/[{}]/g,""),z.WorkflowAttributeType.UniqueIdentifier)}}function mee(e){return e===z.WorkflowAttributeType.DateTime?z.AttributeDateTimeBehavior.DateOnly:z.AttributeDateTimeBehavior.None}function hee(e,t){if(t!==z.WorkflowAttributeType.DateTime)return z.AttributeDateTimeBehavior.None;let r=e.leftDateTimeBehavior;return r!==void 0&&r!==z.AttributeDateTimeBehavior.None?r:mee(t)}function gee(e,t,r){if(t!==z.WorkflowAttributeType.DateTime)return z.AttributeDateTimeBehavior.None;let n=e.valueFieldDateTimeBehavior;return n!==void 0&&n!==z.AttributeDateTimeBehavior.None?n:r}function bee(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return"1";if(t==="false"||t==="0")return"0"}function _ee(e){let t=Nee.exec(e);if(t)return`${t[1]}T${t[2]}`;let r=See.exec(e);if(!r)return;let[,n,i,o,a,s,l]=r,u=Aee.indexOf(i.toLowerCase());if(u<0)return;let c=String(u+1).padStart(2,"0");return`${o}-${c}-${n}T${a}:${s}:${l}`}function Tee(e){let t=_ee(e.trim());return t!==void 0&&R1(t)?t:e}function R1(e){let t=e.trim(),r=t.indexOf("T")>=0?"T":" ",n=t.indexOf(r),i=n>=0?t.slice(0,n):t,o=n>=0?t.slice(n+1):"";if(!vee.test(i)||o.length>0&&!wee.test(o)&&!Cee.test(o)&&!Eee.test(o))return!1;let[a,s,l]=i.split("-"),u=new Date(`${a}-${s}-${l}T00:00:00Z`);return!Number.isNaN(u.getTime())&&u.getUTCFullYear()===Number(a)&&u.getUTCMonth()+1===Number(s)&&u.getUTCDate()===Number(l)}function Dee(e,t){let r={value:e,type:z.WorkflowAttributeType.String};if(t===z.WorkflowAttributeType.String||yee.includes(t)||e.trim().length===0)return r;if(t===z.WorkflowAttributeType.Boolean){let n=bee(e);return n==null?r:{value:n,type:t}}return pee.includes(t)?zf(e)?{value:e.trim(),type:t}:r:Hf(t)?{value:e.trim(),type:t}:t===z.WorkflowAttributeType.DateTime&&R1(e)?{value:e.trim(),type:t}:r}function g1(e){return e==="ContainsData"||e==="DoesNotContainData"}function y1(e){return Iee.has(e)}function b1(e,t){return{__class:"UnaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:t,operand:e}}function v1(e,t){let r=e.leftWorkflowType??e.valueWorkflowType??z.WorkflowAttributeType.String,n=ju[e.operator]??z.WorkflowConditionOperator.Equal,i=hee(e,r),o=tb(r,n);if(e.source==="BusinessProcess"){let l=uee(e,t);if(g1(e.operator))return b1(l,n);let u=D1(e);return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:l,right:[ba(e.value??"",u)]}}let a=rp(e.field,t,r,i);if(g1(e.operator))return b1(a,n);let s;if(e.valueType==="Field"&&e.valueField){let l=y1(o)&&y1(e.valueFieldWorkflowType??"")?e.valueFieldWorkflowType:o;s=[rp(e.valueField,t,l,gee(e,l,i))]}else if(e.valueType==="Lookup"){if(!e.lookupValue)throw new Error("Lookup condition is missing its record value.");s=[P1(e.lookupValue)]}else if(e.valueType==="Clear")s=[ba(null,z.WorkflowAttributeType.String,i)];else if(e.valueType==="Expression")s=[tp(e.valueType,e.value,e.valueField,t,e.expression,e.rawExpression)];else{let l=Dee(e.value??"",o);s=[ba(l.value,l.type,i)]}return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:a,right:s}}function Oee(){return ba(!0,z.WorkflowAttributeType.Boolean)}function Pee(e,t,r){if(e.length===0)return null;let n=v1(e[0],r);for(let i=1;i<e.length;i++){let o=e[i].connector??t;n={__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:o==="AND"?z.WorkflowConditionOperator.LogicalAnd:z.WorkflowConditionOperator.LogicalOr,left:n,right:[v1(e[i],r)]}}return n}function ep(e){if(!e)return{valueType:"Value",value:""};if(e.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions")return{valueType:"Field",valueField:e.attributeName,valueFieldWorkflowType:e.type};if(e.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"){if(e.primitiveValue==null)return{valueType:"Clear",valueWorkflowType:e.type};let t=String(e.primitiveValue);if(e.type===z.WorkflowAttributeType.Boolean){let r=t.trim().toLowerCase();if(r==="1"||r==="true")return{valueType:"Value",value:"true",valueWorkflowType:e.type};if(r==="0"||r==="false")return{valueType:"Value",value:"false",valueWorkflowType:e.type}}return e.type===z.WorkflowAttributeType.DateTime?{valueType:"Value",value:Tee(t),valueWorkflowType:e.type}:{valueType:"Value",value:t,valueWorkflowType:e.type}}if(e.__class==="LookupExpression:#Microsoft.Crm.Workflow.Expressions"){let t=e.staticValue,r=typeof t=="object"&&t?.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"?t.primitiveValue:t;return{valueType:"Lookup",lookupValue:{entityType:e.entityType,id:String(r??""),label:e.label,...e.type!==z.WorkflowAttributeType.Lookup?{workflowType:e.type}:{}}}}if(e.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"){let t=c1(e);return t?{valueType:"Expression",expression:t}:{valueType:"Expression",rawExpression:e}}return{valueType:"Value",value:""}}function Ree(e){let t=fb[e.conditionOperatoroperator]??"Equals",r=t==="ContainsData"||t==="DoesNotContainData",n=va(e)?e.operand:e.left,i=va(e)?[]:e.right??[],o=I1(n);if(o){let g=i[0];return{id:sr(),field:"",fieldDisplayName:"",source:"BusinessProcess",bpfField:o.bpfField,...o.stageType?{stageType:o.stageType}:{},operator:t,valueType:"Value",value:g?.primitiveValue!=null&&!r?String(g.primitiveValue):""}}let a=n.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",s=n.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"?n.attributeName:"",l=a?n.type:void 0,u=r?{valueType:"Value"}:ep(i[0]),c=l,d=a&&n.type===z.WorkflowAttributeType.DateTime&&n.behavior!==z.AttributeDateTimeBehavior.None?n.behavior:void 0,f=u.valueWorkflowType??l,p=r?void 0:i[0],h=p?.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"&&p.type===z.WorkflowAttributeType.DateTime&&p.behavior!==z.AttributeDateTimeBehavior.None?p.behavior:void 0;return{id:sr(),field:s,fieldDisplayName:s,operator:t,...u,...f?{valueWorkflowType:f}:{},...c?{leftWorkflowType:c}:{},...d!==void 0?{leftDateTimeBehavior:d}:{},...h!==void 0?{valueFieldDateTimeBehavior:h}:{}}}function w1(e){if(!e||!Xf(e))return{clauses:[],logic:"AND"};let t=[],r=(o,a)=>{let s=o.conditionOperatoroperator;if(va(o)||s!==z.WorkflowConditionOperator.LogicalAnd&&s!==z.WorkflowConditionOperator.LogicalOr){t.push({...Ree(o),...a?{connector:a}:{}});return}let l=s===z.WorkflowConditionOperator.LogicalAnd?"AND":"OR";Xf(o.left)&&r(o.left,a),(o.right??[]).filter(Xf).forEach(u=>r(u,l))};r(e,void 0);let i=t.slice(1).map(o=>o.connector??"AND")[0]??"AND";return{clauses:t,logic:i}}function tp(e,t,r,n,i,o,a,s){if(e==="Field"&&r)return rp(r,n,z.WorkflowAttributeType.String);if(e==="Expression"){if(i)return l1(i,n);if(o!=null)return o}return e==="Lookup"&&a?P1(a):e==="Clear"?ba(null,s??z.WorkflowAttributeType.String):ba(t??"",z.WorkflowAttributeType.String)}function ub(e,t){return{propertyName:e,propertyValueExpr:t}}function Ys(e){return`Step_${e.value++}`}function cn(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 C1(e,t,r){return e&&!r.used.has(e)?(r.used.add(e),e):cn(t,r)}function Lee(e){return e===A1.StateCode.Activated?"Active":"Draft"}function kee(e,t){let r=e.processtriggerscope,n=e.processtriggerformid;return r===1?n&&n.trim()!==""?n:"AllForms":r===2?"Entity":t??"Entity"}function L1(e,t=1033){return new Qs({languageCode:t}).serialize(e)}function k1(e){return new Qs().deserialize(e)}var A1,z,ree,fb,pb,N1,_1,T1,aee,see,d1,f1,cee,pee,yee,vee,wee,Cee,Eee,Aee,See,Nee,Iee,mb,Qs,hb=k(()=>{"use strict";Xy();A1=we(Ji());UL();Zy();rb();Hu();z=we(jf());ree=new Set(["__class"]);fb={};for(let e of Object.keys(ju))fb[ju[e]]=e;pb="23",N1="BpfProcess",_1="ActiveStageCategory",T1="SelectedStageCategory",aee="processid",see="stagecategory",d1="processstage",f1="stageid";cee=new Set(["ActiveStage","SelectedStage","Stage"]);pee=[z.WorkflowAttributeType.Picklist,z.WorkflowAttributeType.State,z.WorkflowAttributeType.Status];yee=[z.WorkflowAttributeType.Lookup,z.WorkflowAttributeType.Customer,z.WorkflowAttributeType.Owner];vee=/^\d{4}-\d{2}-\d{2}$/,wee=/^\d{2}:\d{2}$/,Cee=/^\d{2}:\d{2}:\d{2}$/,Eee=/^\d{2}:\d{2}:\d{2}\.\d{1,7}$/,Aee=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],See=/^[A-Za-z]{3}, (\d{2}) ([A-Za-z]{3}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/,Nee=/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}:\d{2}\.\d{1,7}|\d{2}:\d{2}:\d{2}|\d{2}:\d{2})Z$/;Iee=new Set([z.WorkflowAttributeType.Lookup,z.WorkflowAttributeType.Owner,z.WorkflowAttributeType.Customer]);mb={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"};Qs=class{resolveLabel;languageCode;entityName="";stepCounter={value:0};idCounter={counts:{},used:new Set};constructor(t={}){this.resolveLabel=t.resolveLabel??(r=>mb[r]),this.languageCode=t.languageCode??1033}label(t){return this.resolveLabel(t)}serialize(t){let r=t.wfomRoot;this.entityName=t.entityLogicalName,this.stepCounter={value:r?Number(r.nextStepIndex):1},this.idCounter={counts:{},used:new Set};let n=t.scope!=="Entity"&&t.scope!=="AllForms"?t.scope:null,i=t.rootCondition?[this.serializeConditionNode(t.rootCondition)]:[],o={...r?.reservedProperties??{},__class:"WorkflowStep:#Microsoft.Crm.Workflow.ObjectModel",id:r?.id??t.ruleId??sr(),name:r?.name??"Step_0",description:r!==void 0?r.description:t.description||null,stepLabels:Ku(),argumentsArray:[],primaryEntityName:r?.primaryEntityName??this.entityName,nextStepIndex:String(this.stepCounter.value),isCrmUIWorkflow:!0,category:r?.category??"2",businessProcessType:r?.businessProcessType??"0",mode:r?.mode??"0",title:r?.title??t.name,formId:n,workflowEntityId:r?.workflowEntityId??t.ruleId??"",variables:r?.variables??[],inputs:r?.inputs??[],steps:{list:i}};return JSON.stringify(o)}makeApplyActionStep(t){return{__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",id:cn("SetAttributeValueStep",this.idCounter),description:t.displayName||"New Action",name:t.stepName??Ys(this.stepCounter),stepLabels:{list:[]},specification:ub(t.field,tp(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType)),entity:cb(this.entityName)}}makeRecommendationActionStep(t,r,n){let i=r.map(l=>this.makeApplyActionStep(l)),o=t??"",a=n?.stepLabels,s=lb(a,o,this.languageCode);return{__class:"ActionStep:#Microsoft.Crm.Workflow.ObjectModel",id:C1(n?.id,"ActionStep",this.idCounter),name:n?.name??Ys(this.stepCounter),description:n?.description??"Action step",stepLabels:s,steps:{list:i},actionId:null,actionType:n?.actionType??"4",processId:n?.processId??sr(),uniqueName:n?.uniqueName??`id_${sr().replace(/-/g,"")}ActionStep`}}serializeAction(t){let r=cb(this.entityName),n=t.stepName??Ys(this.stepCounter),i=t.stepLabels??Ku(),o={name:n,stepLabels:i,description:t.displayName},a=t.type;switch(a){case"SetFieldValue":return{...o,id:cn("SetAttributeValueStep",this.idCounter),__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:ub(t.field,tp(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"SetDefaultValue":return{...o,id:cn("SetDefaultValueStep",this.idCounter),__class:"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:ub(t.field,tp(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"LockUnlock":return{...o,id:cn("SetDisplayModeStep",this.idCounter),__class:"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isReadOnly:t.lock,entity:r};case"SetBusinessRequired":return{...o,id:cn("SetFieldRequiredLevelStep",this.idCounter),__class:"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",requiredLevel:t.required?z.FieldRequiredLevelTypes.Required:z.FieldRequiredLevelTypes.None,entity:r};case"SetVisibility":return{...o,id:cn("SetVisibilityStep",this.idCounter),__class:"SetVisibilityStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isVisible:t.visible,entity:r};case"ShowErrorMessage":{let s=t.errorMessage||t.displayName,l=lb(t.stepLabels,s,this.languageCode);return{...o,id:cn("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=lb(t.stepLabels,s,this.languageCode),u={list:[this.makeRecommendationActionStep(t.acceptanceText,t.applyActions??[],t.recommendationActionStepMeta)]};return{...o,id:cn("SetMessageStep",this.idCounter),__class:"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel",stepLabels:l,description:t.recommendationTitle||t.displayName,controlId:t.field,entity:r,level:"RECOMMENDATION",actionSteps:u}}default:throw new Error(`Unsupported action type: ${a}`)}}serializeConditionNode(t){let r=t.stepName??Ys(this.stepCounter),n=cn("ConditionStep",this.idCounter),i=[],o=t,a=!0;for(;o;){let s=o.rawConditionExpression??Pee(o.clauses,o.logic,this.entityName),l=a?o.branchName??Ys(this.stepCounter):Ys(this.stepCounter),c={__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:a?C1(o.branchId,"ConditionBranchStep",this.idCounter):cn("ConditionBranchStep",this.idCounter),name:l,description:o.displayName,stepLabels:Ku(),conditionExpression:s??(a?Oee():void 0),steps:{list:o.trueBranch.map(f=>this.serializeBranchItem(f))}};i.push(c);let d=o.falseBranch;if(d.length===1&&d[0].kind==="condition"){o=d[0],a=!1;continue}d.length>0&&i.push(this.makeTerminalElseBranch(d)),o=void 0}return{__class:"ConditionStep:#Microsoft.Crm.Workflow.ObjectModel",id:n,name:r,description:"",stepLabels:Ku(),containsElsebranch:i.length>1,steps:{list:i}}}makeTerminalElseBranch(t){return{__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:cn("ConditionBranchStep",this.idCounter),name:"Else",description:null,stepLabels:Ku(),conditionExpression:void 0,steps:{list:t.map(r=>this.serializeBranchItem(r))}}}serializeBranchItem(t){return t.kind==="condition"?this.serializeConditionNode(t):this.serializeAction(t)}deserialize(t){let r=t,n=null,i;if(t.wfomJson)try{let o=JSON.parse(t.wfomJson);i={id:o.id==="WorkflowStep0"||!o.id?t.workflowid??sr():o.id,name:o.name,description:o.description,nextStepIndex:o.nextStepIndex,category:o.category==="0"||o.category===0?"2":o.category,businessProcessType:o.businessProcessType,mode:o.mode,title:o.title||t.name||"",primaryEntityName:o.primaryEntityName==="1"||!o.primaryEntityName?t.primaryentity??"":o.primaryEntityName,workflowEntityId:o.workflowEntityId==="00000000-0000-0000-0000-000000000000"||!o.workflowEntityId?t.workflowid??"":o.workflowEntityId,formId:o.formId,variables:o.variables,inputs:o.inputs,reservedProperties:iee(o)};let s=(o.steps?.list??[]).find(l=>l.__class==="ConditionStep:#Microsoft.Crm.Workflow.ObjectModel");s&&(n=this.deserializeConditionStep(s))}catch{}return{ruleId:t.workflowid??null,name:t.name??"",description:t.description??"",entityLogicalName:t.primaryentity??"",scope:kee(r,i?.formId),status:Lee(t.statecode),rootCondition:n,wfomRoot:i}}deserializeConditionStep(t){let r=(t.steps?.list??[]).filter(oee);return this.buildConditionNodeFromBranches(r,t,!0)}buildConditionNodeFromBranches(t,r,n){let[i,...o]=t,{clauses:a,logic:s}=w1(i?.conditionExpression),l=this.deserializeBranch(i?.steps?.list??[]),u=this.deserializeElseChain(o,r),c=i?.description||i?.name||r.description||r.name||this.label("condition");return{kind:"condition",id:(n?r.id:i?.id)??sr(),displayName:c,clauses:a,logic:s,trueBranch:l,falseBranch:u,isCollapsed:!1,stepName:n?r.name:void 0,branchId:n?i?.id:void 0,branchName:n?i?.name:void 0,...h1(i?.conditionExpression)?{rawConditionExpression:i?.conditionExpression}:{}}}deserializeElseChain(t,r){if(t.length===0)return[];let[n]=t,{clauses:i}=w1(n.conditionExpression);return i.length===0&&!h1(n.conditionExpression)?this.deserializeBranch(n.steps?.list??[]):[this.buildConditionNodeFromBranches(t,r,!1)]}deserializeBranch(t){return t.map(r=>r.__class==="ConditionStep:#Microsoft.Crm.Workflow.ObjectModel"?this.deserializeConditionStep(r):this.deserializeAction(r)).filter(r=>r!==null)}parseRecommendationApplyActions(t){let n=(t?.list??[])[0];if(!n)return{applyActions:[]};let i={id:n.id,name:n.name,description:n.description??void 0,stepLabels:n.stepLabels,processId:n.processId,uniqueName:n.uniqueName,actionType:n.actionType},o=n.stepLabels?.list,a=o&&o.length>0?o[0].description??"":"";return{applyActions:(n.steps?.list??[]).filter(l=>l.__class==="SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel").map(l=>{let u=l.specification;return{id:l.id||sr(),field:u?.propertyName??"",stepName:l.name??void 0,displayName:l.description??void 0,...ep(u?.propertyValueExpr)}}),meta:i,acceptanceText:a}}deserializeAction(t){switch(t.__class){case"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=ep(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=ep(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:o,acceptanceText:a}=this.parseRecommendationApplyActions(t.actionSteps);return{kind:"action",id:t.id,type:"Recommendation",displayName:t.description||this.label("recommendation"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,recommendationTitle:t.description||"",messageText:n,acceptanceText:a,applyActions:i,recommendationActionStepMeta:o}}return{kind:"action",id:t.id,type:"ShowErrorMessage",displayName:t.description||this.label("showErrorMessage"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,errorMessage:n||t.name||"",messageLevel:t.level??void 0,messageActionSteps:t.actionSteps}}case"ActionStep:#Microsoft.Crm.Workflow.ObjectModel":{let{applyActions:r,meta:n,acceptanceText:i}=this.parseRecommendationApplyActions({list:[t]});return{kind:"action",id:t.id,type:"Recommendation",displayName:t.name||this.label("recommendation"),stepName:t.name,stepLabels:t.stepLabels,field:t.actionControl?.controlId??"",recommendationTitle:t.name||"",messageText:t.description||"",acceptanceText:i,applyActions:r,recommendationActionStepMeta:n}}default:return null}}}});var x1=k(()=>{"use strict";});function Uee(e){return typeof e=="object"&&e!==null?e:null}function Xs(e){let t=Uee(e);if(!t)return!1;if(t.__class===Fee){let r=t;return String(r.method)===Mee?!0:Array.isArray(r.parameters)&&r.parameters.some(Xs)}if(t.__class===$ee)return Xs(t.operand);if(t.__class===xee){let r=t;return Xs(r.left)||Array.isArray(r.right)&&r.right.some(Xs)}return!1}var xee,$ee,Fee,Mee,$1=k(()=>{"use strict";x1();xee="BinaryExpression:#Microsoft.Crm.Workflow.Expressions",$ee="UnaryExpression:#Microsoft.Crm.Workflow.Expressions",Fee="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",Mee="23"});function vb(e){return Bee.has(e.type)}function gb(e,t,r,n,i,o,a){let s=i.get(r);!s||!U1.has(s.attributeType)||n!=="Value"||a?.operator&&!nb(a.operator)||o.push({nodeId:e,kind:"INVALID_VALUE_TYPE_FOR_FIELD",message:`${t}: please select a record for this lookup field; a typed text value cannot be saved.`,target:a?.target,itemId:a?.itemId,messageKey:"Validation.InvalidValueTypeForField",messageParams:{label:t}})}function qee(e,t){let r=t.get(e.field);return!!r&&U1.has(r.attributeType)&&nb(e.operator)}function yb(e){return!!(e?.entityType?.trim()&&e.id?.trim())}function bb(e,t,r){return{nodeId:e,kind:"INVALID_DAY_COUNT",message:`Please enter a whole number of days between 0 and ${Ks}.`,target:t,itemId:r,messageKey:"Validation.InvalidDayCount",messageParams:{max:Ks}}}function F1(e,t,r,n,i,o,a,s){if(i!=="Clear")return;let l=o.get(n);Vf(r,l)||a.push({nodeId:e,kind:"INVALID_CLEAR_FOR_FIELD",message:`${t}: Clear is only supported for optional fields with a legacy-compatible type.`,target:s?.target,itemId:s?.itemId,messageKey:"Validation.InvalidClearForField",messageParams:{label:t}})}function ip(e){if(!e)return!1;for(let t of[...e.trueBranch,...e.falseBranch])if(t.kind==="action"){if(vb(t))return!0}else if(ip(t))return!0;return!1}function wb(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=wb(r,t);if(n)return n}}return null}function Vee(e){if(!e||typeof e!="object")return!1;let{__class:t,primitiveValue:r}=e;return t!=="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"?!1:r===!0||typeof r=="string"&&r.toLowerCase()==="true"}function Gee(e){return e.clauses.length===0&&(e.rawConditionExpression===void 0||Vee(e.rawConditionExpression))}function zee(e){return!!e.clauses?.some(t=>t.source==="BusinessProcess")||Xs(e.rawConditionExpression)}function Zs(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=Zs(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=Zs(n,t);if(i)return i}}return null}function Cb(e,t){return{...e,trueBranch:M1(e.trueBranch,t),falseBranch:M1(e.falseBranch,t)}}function M1(e,t){return e.filter(r=>r.id!==t).map(r=>r.kind==="condition"?Cb(r,t):r)}function No(e,t,r){return e.id===t?r(e):{...e,trueBranch:e.trueBranch.map(n=>n.kind==="condition"?No(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="condition"?No(n,t,r):n)}}function np(e,t,r){return{...e,trueBranch:e.trueBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?np(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?np(n,t,r):n)}}function B1(e,t,r,n){return No(e,t,i=>({...i,trueBranch:r==="true"?[...i.trueBranch,n]:i.trueBranch,falseBranch:r==="false"?[...i.falseBranch,n]:i.falseBranch}))}function Eb(e){return e.length===1&&e[0].kind==="condition"}function Hee(e){let t=0,r=e??void 0;for(;r;){t+=1;let{falseBranch:n}=r;if(Eb(n)){r=n[0];continue}n.length>0&&(t+=1),r=void 0}return t}function Kee(e){return!!e&&Hee(e)<jee}function Jee(e,t){if(!e)return;let r=(n,i)=>{if(n.id===t)return i;let o=[];if(Eb(n.falseBranch)){let a=r(n.falseBranch[0],i);if(a)return a}else o.push(...n.falseBranch.filter(a=>a.kind==="condition"));o.push(...n.trueBranch.filter(a=>a.kind==="condition"));for(let a of o){let s=r(a,a);if(s)return s}};return r(e,e)}function q1(e,t,r){let n=Jee(e,t);return!n||!Kee(n)?e:No(e,t,i=>V1(i,r))}function V1(e,t){if(Eb(e.falseBranch))return{...e,falseBranch:[V1(e.falseBranch[0],t)]};let r=Ab(t);return r.falseBranch=e.falseBranch,{...e,falseBranch:[r]}}function G1(e,t){let r=Zs(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 No(e,r.node.id,o=>({...o,falseBranch:i}))}function W1(e,t,r){let n=Zs(e,t);if(!n)return e;let i=o=>{let a=[...o],s=a[n.index+r];return s?(a[n.index+r]=a[n.index],a[n.index]=s,a):o};return No(e,n.node.id,o=>({...o,trueBranch:n.branch==="true"?i(o.trueBranch):o.trueBranch,falseBranch:n.branch==="false"?i(o.falseBranch):o.falseBranch}))}function Ab(e){return{kind:"condition",id:sr(),displayName:e??"New Condition",clauses:[],logic:"AND",trueBranch:[],falseBranch:[],isCollapsed:!1}}function z1(e,t){let r={kind:"action",id:sr(),type:e,displayName:t??`New ${e}`};switch(e){case"Recommendation":return{...r,type:"Recommendation",field:"",recommendationTitle:"",messageText:"",applyActions:[{id:sr(),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 j1(e){if(!e)return[];let t=[];return H1(e,t),[...new Set(t)]}function H1(e,t){e.clauses.forEach(r=>{r.field&&t.push(r.field)}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"?H1(r,t):"field"in r&&r.field&&t.push(r.field)})}function K1(e,t=[],r){if(!e)return[{nodeId:"root",kind:"NO_CONDITION",message:"A business rule must include at least one condition.",target:"node"}];let n=[],i=new Map(t.map(o=>[o.logicalName,o]));return Y1(e,n,i,!0),r==="Entity"&&J1(e,n),ip(e)||n.push({nodeId:"root",kind:"NO_ACTION",message:"A business rule must include at least one action step.",target:"node"}),n}function J1(e,t){zee(e)&&t.push({nodeId:e.id,kind:"BPF_IN_ENTITY_SCOPE",message:"Process based conditions are not allowed in Entity scope.",target:"node",messageKey:"Validation.ProcessConditionNotAllowedInEntityScope"}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"&&J1(r,t)})}function Y1(e,t,r,n=!1){let i=n&&Gee(e),o=!!e.rawConditionExpression;e.clauses.length===0&&!n&&!o&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Add at least one clause to this condition.",target:"node",messageKey:"Validation.AddClause"}),i&&e.falseBranch.length>0&&t.push({nodeId:e.id,kind:"UNREACHABLE_ELSE",message:"Add a condition to the IF clause, or delete the ELSE clause it can never reach.",target:"node",messageKey:"Validation.UnreachableElse"}),e.clauses.forEach(a=>{if(o)return;if(a.source==="BusinessProcess"){a.bpfField?a.value||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:a.id}):t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a business process field for this clause.",target:"clauseField",itemId:a.id,messageKey:"Validation.SelectBusinessProcessField"});return}let s=a.valueType==="Expression"&&!a.rawExpression?ya(a.expression):null;if(!a.field)t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a field for this clause.",target:"clauseField",itemId:a.id});else if(On(a.operator)&&a.valueType==="Value"&&!a.value&&!qee(a,r))t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:a.id});else if(On(a.operator)&&a.valueType==="Value"&&a.value){let u=r.get(a.field);u?.maxLength&&a.value.length>u.maxLength&&t.push({nodeId:e.id,kind:"CLAUSE_VALUE_TOO_LONG",message:`Value exceeds the field's maximum length of ${u.maxLength} characters.`,target:"clauseValue",itemId:a.id,messageParams:{maxLength:u.maxLength}})}else On(a.operator)&&a.valueType==="Expression"&&!a.rawExpression&&!Js(a.expression)?t.push(s==="invalidDayCount"?bb(e.id,"clauseValue",a.id):{nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please complete the formula for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.CompleteClauseFormula"}):On(a.operator)&&a.valueType==="Field"&&!a.valueField&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a field to compare to for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.EmptyClauseCompareField"});On(a.operator)&&a.valueType==="Value"&&a.value&&BL(r.get(a.field)?.attributeType)&&!zf(a.value)&&t.push({nodeId:e.id,kind:"INVALID_CLAUSE_OPTION_VALUE",message:"Please enter a whole number option value for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.InvalidClauseOptionValue"});let l=GL(a);On(a.operator)&&a.valueType==="Value"&&a.value&&Hf(l)&&!WL(a.value,l)&&t.push({nodeId:e.id,kind:"INVALID_CLAUSE_NUMERIC_VALUE",message:eb(l)?"Please enter a whole number for this clause.":"Please enter a valid number for this clause.",target:"clauseValue",itemId:a.id,messageKey:eb(l)?"Validation.InvalidClauseWholeNumberValue":"Validation.InvalidClauseNumericValue"}),On(a.operator)&&a.valueType==="Lookup"&&(yb(a.lookupValue)||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a lookup record for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.EmptyClauseLookupValue"})),On(a.operator)&&gb(e.id,"Condition",a.field,a.valueType,r,t,{operator:a.operator,target:"clauseValue",itemId:a.id})}),i&&e.trueBranch.forEach(a=>{a.kind==="action"&&Wee.has(a.type)&&t.push({nodeId:a.id,kind:"ACTION_REQUIRES_CONDITION",message:"Set field value, Show error message, and Recommendation actions require a condition. Add a condition to the IF clause, or use a different action.",target:"node",messageKey:"Validation.ActionRequiresCondition",messageParams:{actionType:a.type}})}),[...e.trueBranch,...e.falseBranch].forEach(a=>{if(a.kind==="condition")Y1(a,t,r);else{if(!("field"in a)||!a.field)t.push({nodeId:a.id,kind:"EMPTY_ACTION_FIELD",message:`${a.type}: a target field is required.`,target:"actionField",messageParams:{actionType:a.type}});else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&(a.valueType??"Value")==="Value"&&!a.value?.trim())t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please provide a value.`,target:"actionValue",messageParams:{actionType:a.type}});else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Value"&&a.value){let s=r.get(a.field);s?.maxLength&&a.value.length>s.maxLength&&t.push({nodeId:a.id,kind:"ACTION_VALUE_TOO_LONG",message:`${a.type}: value exceeds the field's maximum length of ${s.maxLength} characters.`,target:"actionValue",messageParams:{actionType:a.type,maxLength:s.maxLength}})}else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Field"){if(!a.valueField)t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please select a field to copy from.`,target:"actionValue",messageKey:"Validation.SelectActionSourceField",messageParams:{actionType:a.type}});else if(r.size>0){let s=r.get(a.field),l=r.get(a.valueField);s&&l&&!Jf(s.attributeType,l.attributeType)&&t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: the source field's type is not compatible with the target field.`,target:"actionValue",messageKey:"Validation.IncompatibleActionSourceField",messageParams:{actionType:a.type}})}}else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Expression"){let s=a.rawExpression?null:ya(a.expression);!a.rawExpression&&!Js(a.expression)&&t.push(s==="invalidDayCount"?bb(a.id,"actionValue"):{nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please complete the formula.`,target:"actionValue",messageKey:"Validation.CompleteActionFormula",messageParams:{actionType:a.type}})}else(a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Lookup"&&!yb(a.lookupValue)&&t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please complete the lookup record.`,target:"actionValue",messageKey:"Validation.EmptyActionLookupValue",messageParams:{actionType:a.type}});if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.field&&(gb(a.id,a.type,a.field,a.valueType,r,t,{target:"actionValue"}),F1(a.id,a.type,a.type,a.field,a.valueType,r,t,{target:"actionValue"})),a.type==="ShowErrorMessage"&&!a.errorMessage?.trim()&&t.push({nodeId:a.id,kind:"EMPTY_ACTION_MESSAGE",message:"Show error message: please enter an error message.",target:"actionMessage"}),a.type==="Recommendation"){let s=a.applyActions??[];a.recommendationTitle?.trim()||t.push({nodeId:a.id,kind:"EMPTY_RECOMMENDATION_TITLE",message:"Recommendation: please enter a recommendation title.",target:"recommendationTitle"}),a.messageText?.trim()||t.push({nodeId:a.id,kind:"EMPTY_RECOMMENDATION_MESSAGE",message:"Recommendation: please enter a recommendation message.",target:"recommendationMessage"}),s.length===0&&t.push({nodeId:a.id,kind:"RECOMMENDATION_NO_APPLY_ACTION",message:"Recommendation: add at least one action to apply.",target:"node"}),s.forEach(l=>{if(!l.field)t.push({nodeId:a.id,kind:"EMPTY_ACTION_FIELD",message:"Recommendation: a target field is required for each action to apply.",target:"applyActionField",itemId:l.id,messageKey:"Validation.RecommendationApplyField"});else if(l.valueType==="Field")l.valueField||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please select a field to copy from.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplySourceField"});else if(l.valueType==="Expression"){let u=l.rawExpression?null:ya(l.expression);!l.rawExpression&&!Js(l.expression)&&t.push(u==="invalidDayCount"?bb(a.id,"applyActionValue",l.id):{nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the formula.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplyFormula"})}else l.valueType==="Lookup"?yb(l.lookupValue)||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the lookup record.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplyLookupValue"}):l.valueType==="Clear"||l.value?.trim()||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please enter a value for each action to apply.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplyValue"});l.field&&(gb(a.id,"Recommendation",l.field,l.valueType,r,t,{target:"applyActionValue",itemId:l.id}),F1(a.id,"Recommendation","SetFieldValue",l.field,l.valueType,r,t,{target:"applyActionValue",itemId:l.id}))})}}})}var Bee,U1,Wee,jee,Sb=k(()=>{"use strict";Xy();Hy();Yf();Hu();$1();rb();Zy();Bee=new Set(["LockUnlock","ShowErrorMessage","Recommendation","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]);U1=new Set(["Lookup","Customer","Owner"]);Wee=new Set(["SetFieldValue","ShowErrorMessage","Recommendation"]);jee=10});var Q1={};jr(Q1,{DAY_COUNT_MAX:()=>Ks,DAY_COUNT_MIN:()=>ab,DEFAULT_DESERIALIZE_LABELS:()=>mb,WorkflowJsonMapper:()=>Qs,addElseIfInTree:()=>q1,appendToBranch:()=>B1,areFieldKindsCompatible:()=>Jf,attributeTypeToWorkflowType:()=>e1,buildWorkflowEntity:()=>OL,collectUsedFields:()=>j1,createEmptyAction:()=>z1,createEmptyCondition:()=>Ab,deserializeWorkflowJson:()=>k1,findNode:()=>wb,findParent:()=>Zs,getDefaultOperatorForFieldType:()=>JL,getExpressionModelIssue:()=>ya,getOperatorsForFieldType:()=>Kf,hasAnyTriggerGeneratingAction:()=>ip,isDayCountValid:()=>sb,isExpressionModelComplete:()=>Js,isOperatorCompatible:()=>YL,isTriggerGeneratingAction:()=>vb,moveBranchItemInTree:()=>W1,operatorNeedsValue:()=>On,processTriggerFormIdFromScope:()=>Jy,processTriggerScopeFromScope:()=>Ky,removeElseIfInTree:()=>G1,removeNodeFromTree:()=>Cb,serializeToWorkflowJson:()=>L1,supportsClearForActionType:()=>Vf,updateActionInTree:()=>np,updateConditionInTree:()=>No,validateBusinessRule:()=>K1});var X1=k(()=>{"use strict";Hy();PL();hb();hb();Sb();Sb();Yf();Hu();Hu();});var Nb=v(op=>{"use strict";Object.defineProperty(op,"__esModule",{value:!0});op.cloneJson=void 0;function Yee(e){return JSON.parse(JSON.stringify(e))}op.cloneJson=Yee});var ck=v(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:!0});_o.BUSINESS_RULE_NULL_GUID=_o.businessRuleRegistration=_o.BusinessRuleAdapter=void 0;var Z1=lt(),Ju=(X1(),kr(Q1)),ek=Kr(),tk=Q(),Qee=Nb(),ri=Zr(),Xee=Sm(),Zee=lt(),ete=Ko(),tte=new Set(["ShowErrorMessage","Recommendation"]);function ok(e){var t,r;return e?[...(t=e.trueBranch)!==null&&t!==void 0?t:[],...(r=e.falseBranch)!==null&&r!==void 0?r:[]].some(n=>Array.isArray(n.trueBranch)||Array.isArray(n.falseBranch)?ok(n):tte.has(String(n.type))):!1}function rte(e){return ak((0,Qee.cloneJson)(e))}function ak(e){var t,r;let n=i=>(i??[]).map(o=>nte(o)?ak(o):o);return{...e,logic:(t=e.logic)!==null&&t!==void 0?t:"AND",clauses:(r=e.clauses)!==null&&r!==void 0?r:[],trueBranch:n(e.trueBranch),falseBranch:n(e.falseBranch)}}function nte(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 ite(e){var t;if(e===null||typeof e!="object"||Array.isArray(e))throw new tk.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 tk.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 ote="00000000-0000-0000-0000-000000000000";_o.BUSINESS_RULE_NULL_GUID=ote;var ate=new Set(["Recommendation","LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]),ste=["ruleId","name","description","entityLogicalName","scope","status","rootCondition"],lte=["kind","id","displayName","logic","clauses","trueBranch","falseBranch"],ute=["id","field","fieldDisplayName","operator","valueType","value","valueField","lookupValue","expression","rawExpression","valueWorkflowType"];function Pn(e,t){return e===void 0?t:{...e,...t}}var wa=["kind","id","type","displayName","field","stepName","stepLabels"],rk=["valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression"],cte={Recommendation:[...wa,"recommendationTitle","messageText","acceptanceText","applyActions","recommendationActionStepMeta"],LockUnlock:[...wa,"lock"],ShowErrorMessage:[...wa,"errorMessage","messageLevel","messageActionSteps"],SetFieldValue:[...wa,...rk],SetDefaultValue:[...wa,...rk],SetBusinessRequired:[...wa,"required"],SetVisibility:[...wa,"visible"]};function re(e,t){return t===void 0?{}:{[e]:t}}function sk(e){var t;return e===void 0?void 0:{...e,label:(t=e.label)!==null&&t!==void 0?t:""}}function _b(e){return{valueType:e.valueType,...re("valueWorkflowType",e.valueWorkflowType),...re("value",e.value),...re("valueField",e.valueField),...re("lookupValue",sk(e.lookupValue)),...re("expression",e.expression),...re("rawExpression",e.rawExpression)}}function lk(e,t){let r=new Set(t),n={};for(let[i,o]of Object.entries(e))r.has(i)||o!==void 0&&(n[i]=o);return Object.keys(n).length>0?n:void 0}var dte=["id","field","valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression","stepName","displayName"];function fte(e){return Pn(e.bag,{id:e.id,field:e.field,..._b(e),...re("stepName",e.stepName),...re("displayName",e.displayName)})}function pte(e){let t=lk(e,dte);return{id:e.id,field:e.field,valueType:e.valueType,...re("valueWorkflowType",e.valueWorkflowType),...re("value",e.value),...re("valueField",e.valueField),...re("lookupValue",e.lookupValue),...re("expression",e.expression),...re("rawExpression",e.rawExpression),...re("stepName",e.stepName),...re("displayName",e.displayName),...re("bag",t)}}function nk(e){return{valueType:e.valueType,...re("valueWorkflowType",e.valueWorkflowType),...re("value",e.value),...re("valueField",e.valueField),...re("lookupValue",e.lookupValue),...re("expression",e.expression),...re("rawExpression",e.rawExpression)}}function ik(e){throw new Error(`Unsupported business-rule action type: ${e.type}`)}var mte=new Set(["INVALID_CLEAR_FOR_FIELD","INVALID_VALUE_TYPE_FOR_FIELD","CLAUSE_VALUE_TOO_LONG","ACTION_VALUE_TOO_LONG"]),hte=new Set,gte="INVALID_CLEAR_FOR_FIELD";function yte(e){let t=n=>{var i;return(0,ri.isJsonObject)(n)&&(n.label===""||n.label===void 0)?{...n,label:String((i=n.id)!==null&&i!==void 0?i:"")}:n},r=n=>{if(!(0,ri.isJsonObject)(n))return n;let i={...n};"lookupValue"in i&&(i.lookupValue=t(i.lookupValue)),Array.isArray(i.applyActions)&&(i.applyActions=i.applyActions.map(r));for(let o of["clauses","trueBranch","falseBranch"])Array.isArray(i[o])&&(i[o]=i[o].map(r));return i};return r(e)}var ap=class{toArtifact(t){let r=this.residualBag(t,ste),n={id:t.ruleId,name:t.name,description:t.description,entityLogicalName:t.entityLogicalName,scope:t.scope,status:t.status,rootCondition:t.rootCondition?this.conditionToJson(t.rootCondition):null};return r&&(n.bag=r),n}fromArtifact(t){let r=t.rootCondition?this.conditionFromJson(t.rootCondition):null;return Pn(t.bag,{ruleId:t.id,name:t.name,description:t.description,entityLogicalName:t.entityLogicalName,scope:t.scope,status:t.status,rootCondition:r})}fromApiResponse(t){var r;let n=t??{},i={...(r=n.Entity)!==null&&r!==void 0?r:{},wfomJson:n.WfomJson},o=(0,Ju.deserializeWorkflowJson)(i);return this.toArtifact(o)}needsBaseLanguage(t){return ok(t.rootCondition)}toApiPayload(t,r,n){var i,o;let a=this.fromArtifact(t);a.wfomRoot&&(a.wfomRoot={...a.wfomRoot,name:t.name,title:t.name,primaryEntityName:t.entityLogicalName||a.wfomRoot.primaryEntityName});let s=(0,Ju.serializeToWorkflowJson)(a,(i=n?.baseLanguageCode)!==null&&i!==void 0?i:ete.DEFAULT_LCID),l=(o=a.ruleId)!==null&&o!==void 0?o:(0,Z1.newId)();return{Entity:this.buildWorkflowEntity(a,l),WfomJson:s,status:t.status}}createDefault(t){var r,n,i,o,a,s;let l={ruleId:(r=t.id)!==null&&r!==void 0?r:null,name:(n=t.name)!==null&&n!==void 0?n:"New business rule",description:(i=t.description)!==null&&i!==void 0?i:"",entityLogicalName:(o=t.entityLogicalName)!==null&&o!==void 0?o:"",scope:(a=t.scope)!==null&&a!==void 0?a:"Entity",status:(s=t.status)!==null&&s!==void 0?s:"Draft",rootCondition:t.rootCondition===void 0?(0,Ju.createEmptyCondition)():t.rootCondition===null?null:this.conditionFromJson(rte(ite(t.rootCondition)))},u=this.toArtifact(l);return u.id||(u.id=(0,Z1.newId)()),u}assignMissingIds(t){return(0,Zee.assignMissingIds)(t)}validate(t){let r=[],n=t.rootCondition;return n==null?r:(0,ri.isJsonObject)(n)?(uk(n,"/rootCondition",r),r):(r.push((0,ri.issue)("/rootCondition","condition-must-be-object",`rootCondition must be a JSON object or null, got ${typeof n}`)),r)}semanticIssues(t,r=[]){let n;try{n=this.fromArtifact(t)}catch(a){return[(0,ri.issue)("/rootCondition","rule-not-representable",a instanceof Error?a.message:String(a))]}let i=n.rootCondition===null?null:yte(n.rootCondition),o;return r.length===0?o=mte:r.some(a=>a.requiredLevel!==void 0)?o=hte:o=new Set([gte]),(0,Ju.validateBusinessRule)(i,r).filter(a=>!o.has(a.kind)).map(a=>(0,ri.issue)(`/rootCondition (${a.nodeId})`,`business-rule-${a.kind}`,a.message))}issuesBlockingPush(t,r=[],n){return this.semanticIssues(t,r)}columnsCheckedAtPush(t){let r;try{r=this.fromArtifact(t)}catch{return[]}let n=new Set,i=a=>{a&&n.add(a)},o=a=>{var s;for(let l of a.clauses)i(l.field),i(l.valueField);for(let l of[...a.trueBranch,...a.falseBranch]){if(l.kind==="condition"){o(l);continue}if(i(l.field),l.type==="SetFieldValue"||l.type==="SetDefaultValue")i(l.valueField);else if(l.type==="Recommendation")for(let u of(s=l.applyActions)!==null&&s!==void 0?s:[])i(u.field),i(u.valueField)}};return r.rootCondition&&o(r.rootCondition),[...n]}residualBag(t,r){return lk(t,r)}buildWorkflowEntity(t,r){return(0,Ju.buildWorkflowEntity)(t,r)}conditionToJson(t){let r=this.residualBag(t,lte),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,ute),n={id:t.id,field:t.field,fieldDisplayName:t.fieldDisplayName,operator:t.operator,valueType:t.valueType,...t.value!==void 0?{value:t.value}:{},...t.valueField!==void 0?{valueField:t.valueField}:{},...t.lookupValue!==void 0?{lookupValue:t.lookupValue}:{},...t.expression!==void 0?{expression:t.expression}:{},...t.rawExpression!==void 0?{rawExpression:t.rawExpression}:{},...t.valueWorkflowType!==void 0?{valueWorkflowType:t.valueWorkflowType}:{}};return r&&(n.bag=r),n}branchItemToJson(t){return t.kind==="condition"?this.conditionToJson(t):this.actionToJson(t)}actionToJson(t){let r=this.residualBag(t,cte[t.type]),n={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...re("stepName",t.stepName),...re("stepLabels",t.stepLabels),...re("bag",r)};switch(t.type){case"Recommendation":return{...n,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...re("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(pte),...re("recommendationActionStepMeta",t.recommendationActionStepMeta)};case"LockUnlock":return{...n,type:"LockUnlock",lock:t.lock};case"ShowErrorMessage":return{...n,type:"ShowErrorMessage",errorMessage:t.errorMessage,...re("messageLevel",t.messageLevel),...re("messageActionSteps",t.messageActionSteps)};case"SetFieldValue":return{...n,type:"SetFieldValue",...nk(t)};case"SetDefaultValue":return{...n,type:"SetDefaultValue",...nk(t)};case"SetBusinessRequired":return{...n,type:"SetBusinessRequired",required:t.required};case"SetVisibility":return{...n,type:"SetVisibility",visible:t.visible};default:return ik(t)}}conditionFromJson(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:{};return Pn(n,{kind:"condition",isCollapsed:typeof n.isCollapsed=="boolean"?n.isCollapsed:!1,id:t.id,displayName:t.displayName,logic:t.logic,clauses:t.clauses.map(i=>this.clauseFromJson(i)),trueBranch:t.trueBranch.map(i=>this.branchItemFromJson(i)),falseBranch:t.falseBranch.map(i=>this.branchItemFromJson(i))})}clauseFromJson(t){var r;return Pn(t.bag,{id:t.id,field:t.field,fieldDisplayName:(r=t.fieldDisplayName)!==null&&r!==void 0?r:t.field,operator:t.operator,valueType:t.valueType,...re("value",t.value),...re("valueField",t.valueField),...re("lookupValue",sk(t.lookupValue)),...re("expression",t.expression),...re("rawExpression",t.rawExpression),...re("valueWorkflowType",t.valueWorkflowType)})}branchItemFromJson(t){return this.isConditionJson(t)?this.conditionFromJson(t):this.actionFromJson(t)}actionFromJson(t){if(!ate.has(t.type))throw new Error(`Unsupported business-rule action type: ${t.type}`);vte(t);let r={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...re("stepName",t.stepName),...re("stepLabels",t.stepLabels)};switch(t.type){case"Recommendation":return Pn(t.bag,{...r,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...re("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(fte),...re("recommendationActionStepMeta",t.recommendationActionStepMeta)});case"LockUnlock":return Pn(t.bag,{...r,type:"LockUnlock",lock:t.lock});case"ShowErrorMessage":return Pn(t.bag,{...r,type:"ShowErrorMessage",errorMessage:t.errorMessage,...re("messageLevel",t.messageLevel),...re("messageActionSteps",t.messageActionSteps)});case"SetFieldValue":return Pn(t.bag,{...r,type:"SetFieldValue",..._b(t)});case"SetDefaultValue":return Pn(t.bag,{...r,type:"SetDefaultValue",..._b(t)});case"SetBusinessRequired":return Pn(t.bag,{...r,type:"SetBusinessRequired",required:t.required});case"SetVisibility":return Pn(t.bag,{...r,type:"SetVisibility",visible:t.visible});default:return ik(t)}}isConditionJson(t){return Object.prototype.hasOwnProperty.call(t,"clauses")&&Object.prototype.hasOwnProperty.call(t,"logic")&&!Object.prototype.hasOwnProperty.call(t,"type")}};_o.BusinessRuleAdapter=ap;function uk(e,t,r){(0,ri.optionalEnum)(e,"logic",["AND","OR"],t,"condition-logic-invalid",r),(0,ri.childObjects)(e,"clauses",t,"clause",r);for(let n of["trueBranch","falseBranch"])(0,ri.childObjects)(e,n,t,"branchItem",r).forEach(({node:o,index:a})=>{"clauses"in o||"trueBranch"in o||"falseBranch"in o?uk(o,`${t}/${n}/${a}`,r):bte(o,`${t}/${n}/${a}`,r)})}function bte(e,t,r){e.type==="SetDefaultValue"&&e.valueType==="Clear"&&r.push((0,ri.issue)(`${t}/valueType`,"clear-only-set-field-value","Clear is only supported for SetFieldValue actions."))}function vte(e){if(e.type==="SetDefaultValue"&&e.valueType==="Clear")throw new Error("Clear is only supported for SetFieldValue actions.")}function wte(){return{adapter:new ap,api:Xee.businessRuleApi,publish:(e,t,r)=>(0,ek.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,ek.boundEntityPublishScope)(t)}}_o.businessRuleRegistration=wte});var Tk=v(To=>{"use strict";Object.defineProperty(To,"__esModule",{value:!0});To.appRegistration=To.AppAdapter=To.HEADER_NAV_BOOLEAN_RULE=void 0;var Ui=Zr(),_t=ao(),Qu=lo(),Cte=Kr(),wk=Fd(),Tb=Id(),Db=so(),Ete=lt(),Ate=ue(),Ck=Ko(),Ek=Q(),Ak=Pd();Object.defineProperty(To,"HEADER_NAV_BOOLEAN_RULE",{enumerable:!0,get:function(){return Ak.HEADER_NAV_BOOLEAN_RULE}});var cp="7.0.0.0",dk=`<SiteMap IntroducedVersion="${cp}"></SiteMap>`,fk="/_imgs/imagestrips/transparent_spacer.gif",pk="/_imgs/TableIconsFluentV9/document_one_page_sparkle.svg",Ste=["Entity","Url","DefaultDashboard","Page","GenPageId"],Yu="sitemapId",mk="sitemapName",Nte="sitemapNameUnique",hk="aiDescription",gk="[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}",_te=new RegExp(`^(?:\\{${gk}\\}|${gk})$`);function yk(e,t){if(!_te.test(e.trim()))throw new Ek.ValidationError("app",t,[{pointer:"/sitemapId",rule:"app-sitemapid-guid",message:`sitemapId must be a GUID; received '${e}'.`}]);return e.trim()}function bk(e,t,r){if(e===void 0)return r;if(typeof e!="boolean")throw new Ek.ValidationError("app",t,[Sk(e)]);return e}function Sk(e){return(0,Ui.issue)("/headerAndNavigationRefresh",Ak.HEADER_NAV_BOOLEAN_RULE,`headerAndNavigationRefresh must be a boolean, got ${typeof e}`)}function Tte(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,Ate.normalizeGuid)(i,n)}catch{return}};switch(e.type){case"Entity":return t("entity")&&`Entity:${t("entity").toLowerCase()}`;case"URL":return t("url")&&`URL:${t("url").toLowerCase()}`;case"DashBoard":return r("dashboardId")&&`DashBoard:${r("dashboardId")}`;case"CustomPage":return t("page")&&`CustomPage:${t("page").toLowerCase()}`;case"GenPage":return r("genPageId")&&`GenPage:${r("genPageId")}`;default:return}}function Dte(e){var t,r,n,i;let o=[];for(let a of(r=(t=e.siteMap)===null||t===void 0?void 0:t.areas)!==null&&r!==void 0?r:[])for(let s of(n=a.groups)!==null&&n!==void 0?n:[])for(let l of(i=s.subAreas)!==null&&i!==void 0?i:[])l.type==="Entity"&&l.entity&&o.push(l.entity);return o}var dp=class{constructor(t=Ck.DEFAULT_LCID){this.lcid=t}toArtifact(t){let{bag:r,modeledEls:n}=sp(t,"Area");return{id:"",name:"",uniqueName:"",description:"",siteMap:{areas:n.map(i=>this.areaToJson(i)),bag:r},bag:(0,_t.emptyBag)()}}fromArtifact(t){(0,Db.installDomShim)();let r=this.assignMissingIds(JSON.parse(JSON.stringify(t))),n=new DOMParser().parseFromString("<root/>","text/xml"),i=this.rootToRaw(r);return(0,_t.rebuildRaw)(i,(0,Qu.domEngine)(n),null)}fromApiResponse(t){var r,n,i,o,a,s,l,u,c,d,f;(0,Db.installDomShim)();let p=t??{},m=(r=p.$sitemap)!==null&&r!==void 0?r:p,h=(0,Qu.parseXmlRoot)((n=m.sitemapxml)!==null&&n!==void 0?n:dk,dk),g=this.toArtifact(h);return g.id=(i=p.appmoduleid)!==null&&i!==void 0?i:"",g.name=(o=p.name)!==null&&o!==void 0?o:"",g.uniqueName=(a=p.uniquename)!==null&&a!==void 0?a:"",g.description=(s=p.description)!==null&&s!==void 0?s:"",p.aiappdescription&&(g.aiDescription=p.aiappdescription),g.bag={a:[[Yu,(u=(l=m.sitemapid)!==null&&l!==void 0?l:p._sitemapid_value)!==null&&u!==void 0?u:""],[mk,(c=m.sitemapname)!==null&&c!==void 0?c:""],[Nte,(d=m.sitemapnameunique)!==null&&d!==void 0?d:""],[hk,(f=p.aiappdescription)!==null&&f!==void 0?f:""]],c:[]},g}toApiPayload(t,r){var n,i,o,a,s,l,u,c,d,f,p,m,h,g,b;(0,Db.installDomShim)();let w=(0,Qu.serializeNode)(this.fromArtifact(t)),E=[],A=[];for(let R of(i=(n=t.siteMap)===null||n===void 0?void 0:n.areas)!==null&&i!==void 0?i:[])for(let I of(o=R.groups)!==null&&o!==void 0?o:[])for(let D of(a=I.subAreas)!==null&&a!==void 0?a:[])D.type==="Entity"&&D.entity?E.push(D.entity):D.type==="DashBoard"&&D.dashboardId&&A.push(D.dashboardId);let L=(s=t.bag)!==null&&s!==void 0?s:(0,_t.emptyBag)();return{sitemapId:Ob(L,Yu)||(t.sitemapId?yk(t.sitemapId,t.id):""),sitemapxml:w,sitemapname:Ob(L,mk)||t.name,appModuleId:t.id,appModuleName:t.name,appModuleDescription:t.description,...t.aiDescription!==void 0&&t.aiDescription!==(r?r.aiDescription:Ob(L,hk))?{appModuleAiDescription:t.aiDescription}:{},appModuleUniqueName:t.uniqueName,...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},...t.headerAndNavigationRefresh===void 0?{}:{appSettings:{[Tb.HEADER_AND_NAVIGATION_REFRESH]:bk(t.headerAndNavigationRefresh,(l=t.id)!==null&&l!==void 0?l:"(unknown)",!0)?Tb.APP_SETTING_ON:Tb.APP_SETTING_OFF}},...typeof t.published=="boolean"?{published:t.published}:{},entities:E,components:{forms:(c=(u=t.components)===null||u===void 0?void 0:u.forms)!==null&&c!==void 0?c:[],views:(f=(d=t.components)===null||d===void 0?void 0:d.views)!==null&&f!==void 0?f:[],charts:(m=(p=t.components)===null||p===void 0?void 0:p.charts)!==null&&m!==void 0?m:[],dashboards:[...(g=(h=t.components)===null||h===void 0?void 0:h.dashboards)!==null&&g!==void 0?g:[],...A],...((b=t.components)===null||b===void 0?void 0:b.mainFormsByTable)!==void 0?{mainFormsByTable:t.components.mainFormsByTable}:{}}}}createDefault(t){var r,n,i,o,a,s;let l=!((r=t.siteMap)===null||r===void 0)&&r.areas&&t.siteMap.areas.length>0?t.siteMap.areas:[{id:"",title:"Area",groups:[{id:"",title:"Group",subAreas:[]}]}],u=(n=t.id)!==null&&n!==void 0?n:(0,Ete.newId)();return{id:u,name:(i=t.name)!==null&&i!==void 0?i:"New App",uniqueName:(o=t.uniqueName)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",...t.aiDescription?{aiDescription:t.aiDescription}:{},siteMap:{areas:l},...t.sitemapId?{sitemapId:yk(t.sitemapId,u)}:{},...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},headerAndNavigationRefresh:bk(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(Rb):Array.isArray(r.areas)?r.areas.forEach(Rb):Array.isArray(r.groups)?Rb(r):Array.isArray(r.subAreas)?_k(r):"type"in r&&fp(r,"subarea"),t}validate(t){let r=[],n=t.published;n!==void 0&&typeof n!="boolean"&&r.push((0,Ui.issue)("/published","published-must-be-boolean",`published must be a boolean, got ${typeof n}`));let i=t.siteMap,o=t.headerAndNavigationRefresh;if(o!==void 0&&typeof o!="boolean"&&r.push(Sk(o)),i==null)return r;if(!(0,Ui.isJsonObject)(i))return r.push((0,Ui.issue)("/siteMap","sitemap-must-be-object",`siteMap must be a JSON object, got ${typeof i}`)),r;let a=(0,Ui.childObjects)(i,"areas","/siteMap","area",r),s=new Map;return a.forEach(({node:l,index:u})=>{let c=`/siteMap/areas/${u}`;(0,Ui.childObjects)(l,"groups",c,"group",r).forEach(({node:f,index:p})=>{let m=`${c}/groups/${p}`;(0,Ui.childObjects)(f,"subAreas",m,"subArea",r).forEach(({node:g,index:b})=>{let w=`${m}/subAreas/${b}`;(0,Ui.optionalEnum)(g,"type",["Entity","URL","DashBoard","CustomPage","GenPage"],w,"subarea-type-invalid",r);let E=Tte(g);if(!E)return;let A=s.get(E);if(A===void 0){s.set(E,w);return}r.push((0,Ui.issue)(w,"subarea-duplicate-target",`the sitemap already navigates to this target at ${A}; a duplicate SubArea would pin it twice and a single removeElement would leave one behind`))})})}),r}issuesBlockingPush(t){var r;return(0,wk.mainFormSetShapeIssues)((r=t.components)===null||r===void 0?void 0:r.mainFormsByTable,Dte(t))}applyServerIdentity(t,r){let n=r[Yu];if(!n)return;t.bag||(t.bag=(0,_t.emptyBag)());let i=t.bag.a.find(o=>o[0]===Yu);i?i[1]=n:t.bag.a.push([Yu,n])}areaToJson(t){var r;let{bag:n,modeledEls:i}=sp(t,"Group"),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:Ib(t,this.lcid),groups:i.map(l=>this.groupToJson(l)),bag:n},a=t.getAttribute("Icon");a&&(o.icon=a);let s=t.getAttribute("VectorIcon");return s&&(o.vectorIcon=s),o}groupToJson(t){var r;let{bag:n,modeledEls:i}=sp(t,"SubArea");return{id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:Ib(t,this.lcid),subAreas:i.map(o=>this.subAreaToJson(o)),bag:n}}subAreaToJson(t){var r;let{bag:n}=sp(t,null),i=Ite(t),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",type:i,title:Ib(t,this.lcid),bag:n};if(i==="Entity"){let l=t.getAttribute("Entity");l&&(o.entity=l)}else if(i==="DashBoard"){let l=t.getAttribute("DefaultDashboard");l&&(o.dashboardId=l);let u=t.getAttribute("Url");u&&(o.dashboardUrl=u)}else if(i==="CustomPage"){let l=t.getAttribute("Page");l&&(o.page=l)}else if(i==="GenPage"){let l=t.getAttribute("GenPageId");l&&(o.genPageId=l)}else{let l=t.getAttribute("Url");l&&(o.url=l)}let a=t.getAttribute("Icon");a&&a!==fk&&(o.icon=a);let s=t.getAttribute("VectorIcon");return s&&(o.vectorIcon=s),o}rootToRaw(t){var r,n,i,o;let a=(n=(r=t.siteMap)===null||r===void 0?void 0:r.bag)!==null&&n!==void 0?n:(0,_t.emptyBag)(),l=lp(a)?[["IntroducedVersion",cp]]:[],u=((o=(i=t.siteMap)===null||i===void 0?void 0:i.areas)!==null&&o!==void 0?o:[]).map(c=>this.areaToRaw(c));return{n:"SiteMap",a:(0,_t.mergeAttrs)(a.a,l),c:(0,_t.spliceChildren)(a.c,u)}}areaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,_t.emptyBag)(),i=lp(n),o=[],a=[];t.id&&o.push(["Id",t.id]),i&&o.push(["ShowGroups","true"],["ResourceId","SitemapDesigner.NewTitle"],["DescriptionResourceId","SitemapDesigner.NewTitle"],["IntroducedVersion",cp]),t.icon!==void 0?o.push(["Icon",t.icon]):up(n.a,"Icon")&&a.push("Icon"),t.vectorIcon!==void 0?o.push(["VectorIcon",t.vectorIcon]):up(n.a,"VectorIcon")&&a.push("VectorIcon");let s=t.groups.map(u=>this.groupToRaw(u)),l=Pb((0,_t.spliceChildren)(n.c,s),t.title,i,this.lcid);return{n:"Area",a:(0,_t.mergeAttrs)(n.a,o,a),c:l}}groupToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,_t.emptyBag)(),i=lp(n),o=[];t.id&&o.push(["Id",t.id]),i&&o.push(["ResourceId","SitemapDesigner.NewGroup"],["DescriptionResourceId","SitemapDesigner.NewGroup"],["ToolTipResourseId","SitemapDesigner.Unknown"],["IntroducedVersion",cp],["IsProfile","false"]);let a=t.subAreas.map(l=>this.subAreaToRaw(l)),s=Pb((0,_t.spliceChildren)(n.c,a),t.title,i,this.lcid);return{n:"Group",a:(0,_t.mergeAttrs)(n.a,o),c:s}}subAreaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,_t.emptyBag)(),i=lp(n),o=Pte(n.a,t.type),a=[],s=[];t.id&&a.push(["Id",t.id]),Lte(a,t),i?(a.push(["ResourceId","SitemapDesigner.NewSubArea"],["Client","All,Outlook,OutlookLaptopClient,OutlookWorkstationClient,Web"],["Sku","All,OnPremise,Live,SPLA"],["AvailableOffline","true"],["PassParams","false"]),t.icon&&a.push(["Icon",t.icon])):t.icon!==void 0?a.push(["Icon",t.icon]):up(o,"Icon",fk)&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):up(o,"VectorIcon")?t.type==="GenPage"?a.push(["VectorIcon",pk]):s.push("VectorIcon"):t.type==="GenPage"&&!Ote(o,"VectorIcon")&&a.push(["VectorIcon",pk]);let l=Pb((0,_t.spliceChildren)(n.c,[]),t.title,i,this.lcid);return{n:"SubArea",a:(0,_t.mergeAttrs)(o,a,s),c:l}}};To.AppAdapter=dp;function sp(e,t){let r=(0,Qu.nodeLikeFromDom)(e).getAllProperties().map(s=>[s.key,s.value]),n=[],i=[],o=e.childNodes,a=0;for(let s=0;s<o.length;s+=1){let l=o[s];l.nodeType!==1&&l.nodeType!==3||(l.nodeType===1&&t!==null&&l.tagName===t?i.push(l):n.push({i:a,node:(0,_t.rawFromNode)((0,Qu.nodeLikeFromDom)(l))}),a+=1)}return{bag:{a:r,c:n},modeledEls:i}}function vk(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName===t&&r.push(o)}return r}function Ib(e,t){var r;let n=vk(e,"Titles")[0];if(!n)return"";let o=vk(n,"Title").find(a=>a.getAttribute("LCID")===String(t));return o&&(r=o.getAttribute("Title"))!==null&&r!==void 0?r:""}function Ite(e){return e.getAttribute("GenPageId")?"GenPage":e.getAttribute("Entity")?"Entity":e.getAttribute("Page")?"CustomPage":e.getAttribute("DefaultDashboard")?"DashBoard":"URL"}function lp(e){return e.a.length===0&&e.c.length===0}function Ote(e,t){return e.some(([r])=>r===t)}function up(e,t,r){let n=e.find(([o])=>o===t),i=n?.[1];return!!i&&i!==r}function Ob(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function Pte(e,t){let r=Rte(t);return e.filter(([n])=>!Ste.includes(n)||r.has(n)).map(n=>[n[0],n[1]])}function Rte(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 Lte(e,t){var r,n,i,o,a;switch(t.type){case"Entity":e.push(["Entity",(r=t.entity)!==null&&r!==void 0?r:""]);break;case"URL":e.push(["Url",(n=t.url)!==null&&n!==void 0?n:""]);break;case"DashBoard":e.push(["DefaultDashboard",(i=t.dashboardId)!==null&&i!==void 0?i:""]),t.dashboardUrl!==void 0&&e.push(["Url",t.dashboardUrl]);break;case"CustomPage":e.push(["Page",(o=t.page)!==null&&o!==void 0?o:""]);break;case"GenPage":e.push(["GenPageId",(a=t.genPageId)!==null&&a!==void 0?a:""]);break;default:break}}function Pb(e,t,r,n){if(!t)return e;let i=e.findIndex(o=>o.n==="Titles");if(i>=0){let o=e.slice();return o[i]=kte(e[i],t,n),o}return r?[xte(t,n),...e]:e}function kte(e,t,r){let n=!1,i=e.c.map(o=>!n&&o.n==="Title"&&$te(o,"LCID")===String(r)?(n=!0,{n:o.n,a:(0,_t.mergeAttrs)(o.a,[["Title",t]]),c:o.c}):o);return n||i.unshift(Nk(t,r)),{n:e.n,a:e.a.map(o=>[o[0],o[1]]),c:i}}function xte(e,t){return{n:"Titles",a:[],c:[Nk(e,t)]}}function Nk(e,t){return{n:"Title",a:[["LCID",String(t)],["Title",e]],c:[]}}function $te(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function Fte(e){let t="0123456789abcdef",r="";for(let n=0;n<e;n+=1)r+=t[Math.floor(Math.random()*t.length)];return r}function fp(e,t){e&&(typeof e.id!="string"||e.id.length===0)&&(e.id=`${t}_${Fte(8)}`)}function Rb(e){var t;fp(e,"area");for(let r of(t=e.groups)!==null&&t!==void 0?t:[])_k(r)}function _k(e){var t;fp(e,"group");for(let r of(t=e.subAreas)!==null&&t!==void 0?t:[])fp(r,"subarea")}function Mte(e=Ck.DEFAULT_LCID){return{adapter:new dp(e),api:wk.appApi,languageSensitive:!0,publish:(t,r)=>(0,Cte.publishAppModule)(t,r),publishScope:t=>({envelope:"appmodule",targetIds:[t]}),rebaselineAfterPublish:"bracket"}}To.appRegistration=Mte});var Dk={};jr(Dk,{ActionType:()=>kb,AppActionOrigin:()=>Vb,AppActionVisibilityType:()=>qb,ButtonType:()=>$b,CannotUpdateAppActionColumns:()=>Ute,Context:()=>Mb,IconType:()=>xb,Location:()=>Fb,OnClickEventType:()=>Bb,Scope:()=>Ub,VisibilityType:()=>Lb});var Lb,kb,xb,$b,Fb,Mb,Ub,Bb,qb,Vb,Ute,Ik=k(()=>{"use strict";(function(e){e[e.NotSupported=0]="NotSupported",e[e.Show=1]="Show",e[e.ClassicRules=2]="ClassicRules",e[e.Expression=3]="Expression"})(Lb||(Lb={}));(function(e){e[e.NotSupported=0]="NotSupported",e[e.None=1]="None",e[e.JavaScript=2]="JavaScript",e[e.Expression=3]="Expression"})(kb||(kb={}));(function(e){e[e.NoIcon=0]="NoIcon",e[e.UseIcon=1]="UseIcon",e[e.UseWebResource=2]="UseWebResource"})(xb||(xb={}));(function(e){e[e.Standard=0]="Standard",e[e.Dropdown=1]="Dropdown",e[e.Split=2]="Split",e[e.Group=3]="Group"})($b||($b={}));(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"})(Fb||(Fb={}));(function(e){e[e.All=0]="All",e[e.Entity=1]="Entity"})(Mb||(Mb={}));(function(e){e[e.App=0]="App",e[e.Entity=1]="Entity",e[e.Global=2]="Global"})(Ub||(Ub={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.JavaScript=2]="JavaScript"})(Bb||(Bb={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.ClassicRules=2]="ClassicRules"})(qb||(qb={}));(function(e){e[e.Default=0]="Default",e[e.Migrated=1]="Migrated",e[e.MigratedClone=2]="MigratedClone"})(Vb||(Vb={}));Ute=["appactionid","appmoduleid","context","contextvalue","location","name","type","uniquename","isdisabled","origin"]});var $k=v(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.commandApi=Vr.COMMAND_ROW_NOT_IN_BAR_CODE=Vr.COMMAND_TABLE_MISMATCH_CODE=void 0;var Gb=Xt(),Dr=ye(),Do=Q(),Ir=ue();Vr.COMMAND_TABLE_MISMATCH_CODE="COMMAND_TABLE_MISMATCH";Vr.COMMAND_ROW_NOT_IN_BAR_CODE="COMMAND_ROW_NOT_IN_BAR";var Bte="OnClickEventJavaScriptWebResourceId($select=name,webresourceid),IconWebResourceId($select=name,webresourceid)";async function Wb(e,t){let r=`/EntityDefinitions(LogicalName='${(0,Ir.odataPathLiteral)(t)}')${(0,Ir.odataQuery)([["$select","MetadataId"]])}`,i=(0,Dr.ensureSuccess)(await e.get(r),e.apiUrl(r)).body,o=i?.MetadataId;return o?(0,Ir.normalizeGuid)(o,"entityMetadataId"):""}function zb(e,t){return t?`_contextentity_value eq ${t}`:`contextvalue eq '${(0,Ir.odataLiteral)(e)}'`}function Xu(e){return`Nothing was written. Re-fetch the command with fetchArtifact('command', '${e}', { overwrite: true }) \u2014 this discards local edits \u2014 and re-apply the change.`}function Ok(e,t){let r=e.entityLogicalName;if(t===void 0)return r;if(typeof r!="string"||r.toLowerCase()!==t.toLowerCase())throw new Do.SdkError(Vr.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': its JSON names table '${String(r)}'. A command's id is its table, so the push would write another table's command bar. Nothing was written. Fix its entityLogicalName, or push it under that table's id.`);return t}async function Pk(e,t,r){let n=await Wb(e,t);if(r){let i=(0,Ir.normalizeGuid)(r,"entityMetadataId");if(i!==n)throw new Do.SdkError(Vr.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': it was fetched for table id ${i}, but table '${t}' is ${n||"not resolvable"} on the server \u2014 the table was re-created, or the local copy edited. `+Xu(t))}return n}Vr.commandApi={async get(e,t){let r=t,n=await Wb(e,r),i=zb(r,n),o=`/appactions${(0,Ir.odataQuery)([["$expand",Bte],["$filter",i]])}`,a,s=await(0,Gb.collectPages)(e,o,"fetchArtifact('command')",c=>{a=c}),l={entityLogicalName:r,entityMetadataId:n,appActions:s},u={};for(let c of s){let d=typeof c.appactionid=="string"?c.appactionid:void 0;if(d){let f=c["@odata.etag"];u[(0,Ir.normalizeGuid)(d,"appactionid")]=typeof f=="string"?f:null}}return{raw:l,etag:a?(0,Dr.readEtag)(a):null,memberEtags:u}},async list(e,t){let r=t?.entityLogicalName;return r?[{type:"command",id:r,name:`${r} commands`,entityLogicalName:r,isDirty:!1}]:[]},async create(e,t,r){let n=t,i=Ok(n,r),o=await Pk(e,i,n.entityMetadataId);return Rk(e,i,{...n,entityMetadataId:o},!1)},async update(e,t,r,n,i){let o=r,a=Ok(o,t),s=await Pk(e,a,o.entityMetadataId);return Rk(e,a,{...o,entityMetadataId:s},!0,i)},async delete(e,t){let r=await Wb(e,t),n=`/appactions${(0,Ir.odataQuery)([["$select","appactionid"],["$filter",zb(t,r)]])}`,i=await(0,Gb.collectPages)(e,n,"deleteArtifact('command')");for(let o of i)o.appactionid&&await(0,Dr.deleteRecord)(e,"appactions",o.appactionid)}};async function Rk(e,t,r,n,i){let o=r.entityMetadataId?(0,Ir.normalizeGuid)(r.entityMetadataId,"entityMetadataId"):"",a=await Vte(e,t,r,o,n,i),s={};try{await Wte(e,a,o,s)}catch(l){throw(0,Do.withPartialTokens)(l,{memberEtags:s})}return{id:r.entityLogicalName,etag:null,memberEtags:s}}function xk(e){return e.replace(/[{}]/g,"").toLowerCase()}var qte={entities:/^\/entities\(([^()]+)\)$/,appactions:/^\/appactions\(([^()]+)\)$/};function Lk(e,t){let r=qte[t].exec(e);return r?xk(r[1]):void 0}async function Vte(e,t,r,n,i,o){var a,s;let l=zte(r.rows),u=new Set(l.map(f=>xk(f.appactionid))),c={writes:[],deletes:[]};for(let f of l){let p=f.body["[email protected]"];if(p!==void 0&&!(typeof p=="string"&&n!==""&&Lk(p,"entities")===n))throw new Do.SdkError(Vr.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': app action '${f.appactionid}' binds to ${typeof p=="string"?`'${p}'`:String(p)}, not to table '${t}' (${n?`/entities(${n})`:"whose id is not resolvable"}). `+Xu(t));let m=f.body["[email protected]"];if(typeof m=="string"){let h=Lk(m,"appactions");if(h===void 0||!u.has(h))throw new Do.SdkError(Vr.COMMAND_ROW_NOT_IN_BAR_CODE,`Refusing to push command '${t}': app action '${f.appactionid}' would be placed under '${m}', which is not a row of this command. `+Xu(t))}if(i&&f.exists){let h=(0,Ir.normalizeGuid)(f.appactionid,"id"),g=(a=o?.[h])!==null&&a!==void 0?a:f.etag;if(!(0,Dr.isVersionToken)(g))throw kk(t,h,"update",g);c.writes.push({kind:"patch",row:f,id:h,token:g})}else{if(p===void 0&&!n)throw new Do.SdkError("COMMAND_CONTEXT_ENTITY_UNRESOLVED",`Cannot create app action '${f.appactionid}' for entity '${r.entityLogicalName}': the entity MetadataId could not be resolved, so the required ContextEntity bind cannot be set. A row written without it is created but is permanently unreadable \u2014 commandApi.get filters on _contextentity_value. Verify the entity logical name exists and is readable, then retry.`);c.writes.push({kind:"post",row:f})}}for(let f of(s=r.deletedRowIds)!==null&&s!==void 0?s:[]){let p=(0,Ir.normalizeGuid)(f,"id"),m=o?.[p];if(!(0,Dr.isVersionToken)(m))throw kk(t,p,"delete",m);c.deletes.push({id:p,token:m})}let d=[...c.writes.flatMap(f=>f.kind==="patch"?[{id:f.id,verb:"update"}]:[]),...c.deletes.map(f=>({id:f.id,verb:"delete"}))];if(d.length>0){let f=await Gte(e,t,n),p=d.find(m=>!f.has(m.id));if(p)throw new Do.SdkError(Vr.COMMAND_ROW_NOT_IN_BAR_CODE,`Refusing to push command '${t}': it would ${p.verb} app action '${p.id}', which is not in table '${t}''s command bar on the server \u2014 a row of another table, or one deleted since the fetch. `+Xu(t))}return c}function kk(e,t,r,n){return new Do.SdkError(Dr.UPDATE_NO_ETAG_CODE,`Refusing to push command '${e}': ${typeof n=="string"&&n!==""?`the token held for app action '${t}' ('${n}') is not a version`:`no token is held for app action '${t}'`}, so its ${r} could not be made conditional and would overwrite or remove a concurrent edit. `+Xu(e))}async function Gte(e,t,r){let n=`/appactions${(0,Ir.odataQuery)([["$select","appactionid"],["$filter",zb(t,r)]])}`,i=await(0,Gb.collectPages)(e,n,"pushArtifact('command') bar membership"),o=new Set;for(let a of i)typeof a.appactionid=="string"&&o.add((0,Ir.normalizeGuid)(a.appactionid,"appactionid"));return o}async function Wte(e,t,r,n){for(let i of t.writes)if(i.kind==="patch"){let o=(0,Dr.echoWrite)("appactionid",{"If-Match":i.token}),a=`/appactions(${i.id})${o.query}`,s=(0,Dr.ensureSuccess)(await e.patch(a,i.row.body,o.options),e.apiUrl(a));n[i.id]=(0,Dr.readEtag)(s)}else{let o=(0,Dr.echoWrite)("appactionid"),a=`/appactions${o.query}`,s={...i.row.body};s["[email protected]"]===void 0&&(s["[email protected]"]=`/entities(${r})`);let l=(0,Dr.ensureSuccess)(await e.post(a,s,o.options),e.apiUrl(a)),u=(0,Dr.readCreatedId)(l,"appactionid");u&&(n[(0,Ir.normalizeGuid)(u,"appactionid")]=(0,Dr.readEtag)(l))}for(let{id:i,token:o}of[...t.deletes].reverse())await(0,Dr.deleteRecord)(e,"appactions",i,o),delete n[i]}function zte(e){let t=new Map(e.map(o=>[o.appactionid,o])),r=new Set,n=[],i=o=>{if(r.has(o.appactionid))return;let a=o.body["[email protected]"];if(typeof a=="string"){let s=/\(([^)]+)\)/.exec(a),l=s?t.get(s[1]):void 0;l&&i(l)}r.add(o.appactionid),n.push(o)};return e.forEach(i),n}});var Jk=v(el=>{"use strict";Object.defineProperty(el,"__esModule",{value:!0});el.commandRegistration=el.CommandAdapter=void 0;var it=(Ik(),kr(Dk)),Fk=Kr(),dn=Zr(),jte=$k(),Hte=lt(),tl=ue(),Kb="$ClientSvg:",Jb=".svg",Kte=2,Jte=1,Yte=1,Bk="entityMetadataId",Qte=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"]),pp=class{toArtifact(t){var r,n,i,o,a,s;let l=(r=t.appActions)!==null&&r!==void 0?r:[],u=(n=t.entityLogicalName)!==null&&n!==void 0?n:"",c=new Map;for(let p of l){let m=typeof p._parentappactionid_value=="string"&&p._parentappactionid_value?p._parentappactionid_value:"",h=(i=c.get(m))!==null&&i!==void 0?i:[];h.push(p),c.set(m,h)}let d=new Map;for(let p of(o=c.get(""))!==null&&o!==void 0?o:[]){let m=rre(p.location),h=(a=d.get(m))!==null&&a!==void 0?a:[];h.push(p),d.set(m,h)}let f=[];for(let[p,m]of d)f.push({location:p,groups:Zte(m,c,zk(p),u)});return{id:u,entityLogicalName:u,commandBars:tre(f),bag:{a:[[Bk,(s=t.entityMetadataId)!==null&&s!==void 0?s:""]]}}}fromArtifact(t){return{entityLogicalName:t.entityLogicalName,entityMetadataId:Qb(t),appActions:jb(t).map(r=>r.row)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t,r){let n=new Set(r?jb(r).map(l=>l.appactionid):[]),i=jb(t,new Set([...n].map(l=>l.toLowerCase()))),o=new Set(i.map(l=>l.appactionid)),a=i.map(l=>{let u=l.exists||n.has(l.appactionid);return{appactionid:l.appactionid,exists:u,etag:l.etag,body:u?mre(l.row):Kk(l.row)}}),s=[...n].filter(l=>!o.has(l));return{entityLogicalName:t.entityLogicalName,entityMetadataId:Qb(t),rows:a,...s.length>0?{deletedRowIds:s}:{}}}createDefault(t){var r,n,i,o;let a=(n=(r=t.entityLogicalName)!==null&&r!==void 0?r:t.id)!==null&&n!==void 0?n:"";return{id:(i=t.id)!==null&&i!==void 0?i:a,entityLogicalName:a,commandBars:(o=t.commandBars)!==null&&o!==void 0?o:[]}}assignMissingIds(t){return(0,Hte.assignMissingIds)(t)}validate(t){let r=[];return(0,dn.childObjects)(t,"commandBars","","commandBar",r).forEach(({node:i,index:o})=>{let a=`/commandBars/${o}`;(0,dn.optionalEnum)(i,"location",["MainTab","ContextualTab","HomeTab"],a,"bar-location-invalid",r),(0,dn.childObjects)(i,"groups",a,"group",r).forEach(({node:l,index:u})=>{let c=`${a}/groups/${u}`;qk(l.bag)||((0,dn.optionalGuidId)(l,"id",c,"group-id-invalid",r),typeof l.title=="string"&&l.title.length>0&&r.push({pointer:`${c}/title`,rule:"group-toplevel-title-unsupported",message:"a new top-level command group cannot have a title: Dataverse rejects a Group row with no parent (0x80040265). Leave the title empty to hold the commands without creating a group row, or nest them under a FlyoutAnchor control, which supplies the parent a group needs."})),Vk((0,dn.childObjects)(l,"controls",c,"control",r),`${c}/controls`,r)})}),r}};el.CommandAdapter=pp;function qk(e){let t=e?.a;return Array.isArray(t)&&t.length>0}function Vk(e,t,r){e.forEach(({node:n,index:i})=>{let o=`${t}/${i}`;qk(n.bag)||(0,dn.optionalGuidId)(n,"id",o,"control-id-invalid",r),(0,dn.optionalEnum)(n,"type",["Button","FlyoutAnchor","SplitButton"],o,"control-type-invalid",r);let a=n.location;a!==void 0&&(typeof a!="number"||!Number.isInteger(a)||a<0||a>6)&&r.push((0,dn.issue)(`${o}/location`,"control-location-invalid",`location must be an integer 0-6 when present, got ${JSON.stringify(a)}`)),n.action!==void 0&&n.action!==null&&((0,dn.isJsonObject)(n.action)?(0,dn.optionalEnum)(n.action,"type",["javascript"],`${o}/action`,"action-type-invalid",r):r.push((0,dn.issue)(`${o}/action`,"control-action-must-be-object",`a control action must be a JSON object when present, got ${typeof n.action}`)));let s=(0,dn.childObjects)(n,"children",o,"control",r);s.length>0&&Vk(s,`${o}/children`,r)})}function Yb(e){return{a:Object.entries(e)}}function Xte(e){return Object.fromEntries(e.a)}function mp(e,t){if(e){for(let[r,n]of e.a)if(r===t)return n}}function Qb(e){let t=mp(e.bag,Bk);return typeof t=="string"?t:""}function Zte(e,t,r,n){var i,o;let a=[],s=[];for(let l of gp(e))l.type===it.ButtonType.Group?a.push({id:Wk(l.name,n),title:typeof l.grouptitle=="string"?l.grouptitle:"",controls:gp((o=t.get((i=l.appactionid)!==null&&i!==void 0?i:""))!==null&&o!==void 0?o:[]).map(u=>hp(u,t,r,n)),bag:Yb(l)}):s.push(hp(l,t,r,n));return s.length>0&&a.unshift({id:pre(n,r),title:"",controls:s}),a}function Xb(e){let t=e.bag?mp(e.bag,"appactionid"):void 0;return typeof t=="string"&&t.trim()!==""?t:e.id}function hp(e,t,r,n){var i,o,a,s,l;let u=Wk(e.name,n),c={id:u,type:nre(e.type),label:typeof e.buttonlabeltext=="string"?e.buttonlabeltext:"",command:typeof e.appactionid=="string"?e.appactionid:u,bag:Yb(e)},d=Gk(e);d&&(c.icon=d);let f=ere(e);f&&(c.action=f),typeof e.hidden=="boolean"&&(c.hidden=e.hidden),typeof e.isdisabled=="boolean"&&(c.disabled=e.isdisabled),typeof e.location=="number"&&e.location!==r&&(c.location=e.location);let p=t.get((i=e.appactionid)!==null&&i!==void 0?i:"");if(p&&p.length>0){let m=[],h=[];for(let g of gp(p))if(g.type===it.ButtonType.Group){let b=(o=g.appactionid)!==null&&o!==void 0?o:"",w=Yb(g);c.flyoutGroupId===void 0&&(c.flyoutGroupId=(a=g.appactionid)!==null&&a!==void 0?a:void 0,c.flyoutGroupBag=w);let E=[];for(let A of gp((l=t.get((s=g.appactionid)!==null&&s!==void 0?s:""))!==null&&l!==void 0?l:[])){let L=hp(A,t,r,n);m.push(L),E.push(Xb(L))}h.push({id:b,bag:w,childIds:E})}else m.push(hp(g,t,r,n));c.children=m,h.length>1&&(c.flyoutGroups=h)}return c}function Gk(e){var t;if(!((t=e.IconWebResourceId)===null||t===void 0)&&t.name)return e.IconWebResourceId.name;if(e.fonticon)return e.fonticon.startsWith(Kb)?e.fonticon.slice(Kb.length)+Jb:e.fonticon}function ere(e){var t;let r=e.onclickeventjavascriptfunctionname;if(typeof r!="string"||!r)return;let n=e.OnClickEventJavaScriptWebResourceId,i=e._onclickeventjavascriptwebresourceid_value,o={type:"javascript",webResourceId:(t=typeof i=="string"?i:n?.webresourceid)!==null&&t!==void 0?t:"",functionName:r};n?.name&&(o.libraryName=n.name);let a=e.onclickeventjavascriptparameters;return typeof a=="string"&&a&&(o.parameters=a),o}function Mk(e){return typeof e.sequence=="number"?e.sequence:typeof e.buttonsequencepriority=="number"?e.buttonsequencepriority:0}function gp(e){return[...e].sort((t,r)=>Mk(t)-Mk(r))}function tre(e){let t={MainTab:0,ContextualTab:1,HomeTab:2};return[...e].sort((r,n)=>{var i,o;return((i=t[r.location])!==null&&i!==void 0?i:9)-((o=t[n.location])!==null&&o!==void 0?o:9)})}function Wk(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 rre(e){switch(e){case it.Location.Form:case it.Location.QuickForm:return"MainTab";case it.Location.HomePageGrid:case it.Location.Dashboard:return"HomeTab";default:return"ContextualTab"}}function zk(e){switch(e){case"MainTab":return it.Location.Form;case"HomeTab":return it.Location.HomePageGrid;default:return it.Location.SubGridStandard}}function nre(e){switch(e){case it.ButtonType.Dropdown:return"FlyoutAnchor";case it.ButtonType.Split:return"SplitButton";default:return"Button"}}function ire(e){switch(e){case"FlyoutAnchor":return it.ButtonType.Dropdown;case"SplitButton":return it.ButtonType.Split;default:return it.ButtonType.Standard}}function ore(e){var t;return e.bag&&e.bag.a.length>0?!0:((t=e.title)!==null&&t!==void 0?t:"").length>0}function jk(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 jb(e,t=new Set){var r,n,i,o;let a=[],s=Qb(e);for(let l of(r=e.commandBars)!==null&&r!==void 0?r:[]){let u=zk(l.location),c=((n=l.groups)!==null&&n!==void 0?n:[]).flatMap(p=>{var m;return(m=p.controls)!==null&&m!==void 0?m:[]}),d=c.length>0&&c.every(p=>!jk(p,t)),f=0;for(let p of(i=l.groups)!==null&&i!==void 0?i:[]){let m;if(ore(p)){let h=sre(p,u,void 0,e,s);a.push(h),m=h.appactionid}for(let h of(o=p.controls)!==null&&o!==void 0?o:[])Hk(h,u,m,e,s,a,d?f:void 0,t),f+=1}}return a}function Hk(e,t,r,n,i,o,a,s=new Set){var l;let u=are(e,t,r,n,i,a);o.push(u);let c=(l=e.children)!==null&&l!==void 0?l:[];if(c.length===0&&!(e.flyoutGroups&&e.flyoutGroups.length>0))return;let d=c.every(h=>!jk(h,s)),f=(h,g,b)=>{Hk(h,t,g,n,i,o,d?b:void 0,s)},p=e.flyoutGroups;if(p&&p.length>0){let h=new Map(c.map(A=>[Xb(A),A])),g=new Set,b=0,w;for(let[A,L]of p.entries()){let R=L.id||(A===0?Hb(u.appactionid):ev("flyout-group",`${u.appactionid}#${A}`)),I=Uk(R,t,u.appactionid,n,i,L.bag);o.push(I);let D=I.appactionid;w===void 0&&(w=D);for(let O of L.childIds){let $=h.get(O);!$||g.has(O)||(g.add(O),f($,D,b),b+=1)}}let E=w??Hb(u.appactionid);for(let A of c){let L=Xb(A);g.has(L)||(g.add(L),f(A,E,b),b+=1)}return}let m=e.flyoutGroupId||Hb(u.appactionid);o.push(Uk(m,t,u.appactionid,n,i,e.flyoutGroupBag));for(let[h,g]of c.entries())f(g,m,h)}function are(e,t,r,n,i,o){let a=Zb(e,t,r,n,i),s=a.row;o!==void 0&&typeof s.sequence!="number"&&(s.sequence=o);let l=Gk(s);return e.location!==void 0&&(s.location=e.location),s.type=ire(e.type),s.buttonlabeltext=e.label,ure(s,e.icon,l),dre(s,e.action),cre(s),e.hidden!==void 0&&(s.hidden=e.hidden),e.disabled!==void 0&&(s.isdisabled=e.disabled),{...a,row:s}}function sre(e,t,r,n,i){let o=Zb(e,t,r,n,i);return o.row.type=it.ButtonType.Group,o.row.grouptitle=e.title,o}function Uk(e,t,r,n,i,o){let a=Zb({id:e,bag:o},t,r,n,i),s=a.row;return s["[email protected]"]=`/appactions(${(0,tl.normalizeGuid)(r,"Command flyout group id")})`,s.type=it.ButtonType.Group,s.grouptitle===void 0&&(s.grouptitle=""),s.isgrouptitlehidden===void 0&&(s.isgrouptitlehidden=!0),a}function Zb(e,t,r,n,i){let o,a,s,l;if(e.bag&&e.bag.a.length>0){o=Xte(e.bag),a=!0;let u=mp(e.bag,"@odata.etag");s=typeof u=="string"?u:null;let c=mp(e.bag,"appactionid");l=typeof c=="string"&&c?c:e.id}else l=e.id,o=lre(l,t,n,i),a=!1,s=null;return r?o["[email protected]"]=`/appactions(${(0,tl.normalizeGuid)(r,"Command parent appaction id")})`:a&&typeof o._parentappactionid_value=="string"&&o._parentappactionid_value&&o.type!==it.ButtonType.Group&&(o["[email protected]"]=null),delete o._parentappactionid_value,{appactionid:l,exists:a,etag:s,row:o}}function lre(e,t,r,n){let i={appactionid:e,name:`${e}!${e.replace(/-/g,"").slice(0,32)}`,uniquename:"",location:t,context:it.Context.Entity,contextvalue:r.entityLogicalName,scope:it.Scope.Entity};return n&&(i["[email protected]"]=`/entities(${(0,tl.normalizeGuid)(n,"Command context entity metadata id")})`),i}function ure(e,t,r){if(t===r){let n=e._iconwebresourceid_value;typeof n=="string"&&n&&!e.fonticon&&(e["[email protected]"]=`/webresourceset(${(0,tl.normalizeGuid)(n,"Command icon web resource id")})`);return}if(t===void 0){e.fonticon="",e.IconWebResourceId=null;return}e.fonticon=t.toLowerCase().endsWith(Jb)?Kb+t.slice(0,t.length-Jb.length):t,e.IconWebResourceId=null}function cre(e){let t=(n,i)=>{let o=e[n];if(typeof o!="string"||o.length===0||e[`${i}@odata.bind`]!==void 0)return;let a=(0,tl.normalizeGuid)(o,`Command ${i}`);e[`${i}@odata.bind`]=`/canvasapps(${a})`};e.onclickeventtype===Jte&&t("_onclickeventformulacomponentlibraryid_value","OnClickEventFormulaComponentLibraryId");let r=e.visibilitytype;(!r||r===Yte)&&t("_visibilityformulacomponentlibraryid_value","VisibilityFormulaComponentLibraryId")}function dre(e,t){if(!(!t||t.type!=="javascript")){if(e.onclickeventtype=Kte,t.webResourceId){let r=(0,tl.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 fre(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 ev(e,t){let r="";for(let n=0;n<4;n+=1)r+=fre(`${n}:${e}:${t}`).toString(16).padStart(8,"0");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`}function Hb(e){return ev("flyout-group",e)}function pre(e,t){return ev("loose-group",`${e}|${t}`)}function Kk(e){let t={...e};for(let r of Qte)delete t[r];return t}function mre(e){let t=Kk(e);for(let r of it.CannotUpdateAppActionColumns)delete t[r];return t}function hre(){return{adapter:new pp,api:jte.commandApi,publish:(e,t,r)=>(0,Fk.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,Fk.boundEntityPublishScope)(t)}}el.commandRegistration=hre});var Qk=v(yp=>{"use strict";Object.defineProperty(yp,"__esModule",{value:!0});yp.chartApi=void 0;var gre=Xt(),Or=ye(),Ca=ue(),Yk="savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault",yre="savedqueryvisualizationid,name,primaryentitytypecode,charttype,isdefault";yp.chartApi={async get(e,t){let r=(0,Ca.normalizeGuid)(t,"id"),n=await(0,Or.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r),i=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Ca.odataQuery)([["$select",Yk]]);return{raw:(0,Or.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},async readContentThenToken(e,t){let r=(0,Ca.normalizeGuid)(t,"id"),n=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Ca.odataQuery)([["$select",Yk]]),i=(0,Or.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=await(0,Or.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r);return{raw:i.body,etag:o}},async list(e,t){let r=`/savedqueryvisualizations${(0,Ca.odataQuery)([["$select",yre],["$filter",t?.entityLogicalName?`primaryentitytypecode eq '${(0,Ca.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,gre.collectPages)(e,r,"listArtifacts('chart')")).map(i=>{var o,a;return{type:"chart",id:(o=i.savedqueryvisualizationid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",entityLogicalName:i.primaryentitytypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,Or.echoWrite)("savedqueryvisualizationid"),o=`/savedqueryvisualizations${i.query}`,a=(0,Or.ensureSuccess)(await e.post(o,(0,Or.withClientMintedId)({name:n.name,description:n.description,datadescription:n.datadescription,presentationdescription:n.presentationdescription,primaryentitytypecode:n.primaryentitytypecode,charttype:n.charttype,isdefault:n.isdefault},"savedqueryvisualizationid",r),i.options),e.apiUrl(o));return{id:(0,Or.resolveCreatedId)(a,"savedqueryvisualizationid","chart",r),etag:(0,Or.readEtag)(a)}},async update(e,t,r,n){let i=r,o=(0,Ca.normalizeGuid)(t,"id"),a=(0,Or.echoWrite)("savedqueryvisualizationid",{"If-Match":(0,Or.requireEtag)(n,"chart",o)}),s=`/savedqueryvisualizations(${o})${a.query}`,l=(0,Or.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,datadescription:i.datadescription,presentationdescription:i.presentationdescription},a.options),e.apiUrl(s));return{id:o,etag:(0,Or.readEtag)(l)}},delete(e,t){return(0,Or.deleteRecord)(e,"savedqueryvisualizations",t)}}});var hx=v(nl=>{"use strict";Object.defineProperty(nl,"__esModule",{value:!0});nl.chartRegistration=nl.ChartAdapter=void 0;var tv=ao(),Xk=Zr(),ni=lo(),Zk=Kr(),bre=Qk(),rv=so(),vre=lt(),wre=["Column","StackedColumn","StackedColumn100","Bar","StackedBar","StackedBar100","Area","StackedArea","StackedArea100","Line","Pie","Doughnut","Funnel","Tag"],Cre=new Map(wre.map(e=>[e.toLowerCase(),e]));function ix(e){var t;return e&&(t=Cre.get(e.toLowerCase()))!==null&&t!==void 0?t:"Column"}function Ere(){return'<Chart Palette="BrightPastel"><Series><Series ChartType="Column" ChartArea="Default" /></Series><ChartAreas><ChartArea Name="Default" /></ChartAreas><Legends><Legend Name="Default" /></Legends></Chart>'}function Are(e){var t,r;let n=e.entityLogicalName,i=e.series.map((h,g)=>({alias:`agg_${g}`,series:h})),o=e.categories.map((h,g)=>({alias:`grp_${g}`,category:h})),a=h=>`<attribute alias="${h.alias}" name="${rl(h.series.attribute)}" aggregate="${rl(h.series.aggregate)}" />`,s=h=>`<attribute alias="${h.alias}" name="${rl(h.category.attribute)}" groupby="true"${h.category.dateGrouping?` dategrouping="${rl(h.category.dateGrouping)}"`:""} />`,l=[],u=new Map,c=(h,g)=>{if(!h){l.push(g);return}let b=u.get(h);b?b.push(g):u.set(h,[g])};i.forEach(h=>c(h.series.relatedEntity,a(h))),o.forEach(h=>c(h.category.relatedEntity,s(h)));let d=[...u.entries()].map(([h,g])=>`<link-entity name="${rl(h)}">${g.join("")}</link-entity>`).join(""),f=l.join("")+d,p=i.map(h=>`<measurecollection><measure alias="${h.alias}" /></measurecollection>`).join(""),m=(r=(t=o[0])===null||t===void 0?void 0:t.alias)!==null&&r!==void 0?r:"";return`<datadefinition><fetchcollection><fetch mapping="logical" aggregate="true"><entity name="${rl(n)}">${f}</entity></fetch></fetchcollection><categorycollection><category alias="${m}">${p}</category></categorycollection></datadefinition>`}var bp=class{toArtifact(t){var r,n,i,o,a,s,l;(0,rv.installDomShim)();let u=(r=t.datadescription)!==null&&r!==void 0?r:"",c=(n=t.presentationdescription)!==null&&n!==void 0?n:"",d=(0,ni.parseXmlRoot)(u,"<datadefinition/>"),f=(0,ni.parseXmlRoot)(c,"<Chart/>");return{id:(i=t.savedqueryvisualizationid)!==null&&i!==void 0?i:"",name:(o=t.name)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",entityLogicalName:(s=t.primaryentitytypecode)!==null&&s!==void 0?s:"",chartType:ox(f),isDefault:(l=t.isdefault)!==null&&l!==void 0?l:!1,series:lx(d),categories:ux(d),presentation:ax(f),dataBag:u?(0,ni.projectElementBag)(d):void 0,presentationBag:c?(0,ni.projectElementBag)(f):void 0,rowBag:Sre(t.charttype,t.type)}}fromArtifact(t){(0,rv.installDomShim)();let{datadescription:r,presentationdescription:n}=Nre(t);return{savedqueryvisualizationid:t.id,name:t.name,description:t.description,primaryentitytypecode:t.entityLogicalName,datadescription:r,presentationdescription:n,charttype:ex(t.rowBag,"charttype"),type:ex(t.rowBag,"type"),isdefault:t.isDefault}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){var r,n,i,o,a,s,l;let u=this.fromArtifact(t);return{name:(r=u.name)!==null&&r!==void 0?r:"",description:(n=u.description)!==null&&n!==void 0?n:"",datadescription:(i=u.datadescription)!==null&&i!==void 0?i:"",presentationdescription:(o=u.presentationdescription)!==null&&o!==void 0?o:"",primaryentitytypecode:(a=u.primaryentitytypecode)!==null&&a!==void 0?a:"",charttype:(s=u.charttype)!==null&&s!==void 0?s:0,isdefault:(l=u.isdefault)!==null&&l!==void 0?l:!1}}createDefault(t){var r,n,i,o,a,s,l;(0,rv.installDomShim)();let u=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,vre.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New Chart",description:(o=t.description)!==null&&o!==void 0?o:"",entityLogicalName:u,chartType:(a=t.chartType)!==null&&a!==void 0?a:"Column",isDefault:(s=t.isDefault)!==null&&s!==void 0?s:!1,series:t.series&&t.series.length>0?t.series:[{attribute:"createdon",aggregate:"count"}],categories:t.categories&&t.categories.length>0?t.categories:[{attribute:"createdon",dateGrouping:"month"}],presentation:(l=t.presentation)!==null&&l!==void 0?l:{palette:"BrightPastel",showLegend:!0}}}assignMissingIds(t){return t}validate(t){let r=[],n=t;return(0,Xk.childObjects)(n,"series","","series",r),(0,Xk.childObjects)(n,"categories","","category",r),r}};nl.ChartAdapter=bp;function Sre(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 ex(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 ox(e){let t=e.getElementsByTagName("Series");for(let r=0;r<t.length;r+=1)if(t[r].getAttribute("ChartType"))return ix(t[r].getAttribute("ChartType"));return"Column"}function ax(e){var t;let r={showLegend:e.getElementsByTagName("Legend").length>0},n=e.getAttribute("Palette");n&&(r.palette=n);let i=e.getElementsByTagName("Title")[0],o=((t=i?.textContent)!==null&&t!==void 0?t:"").trim();return o&&(r.title=o),r}function vp(e){return e.getElementsByTagName("fetch")[0]}function sx(e){let t=new Map;if(!e)return t;let r=e.getElementsByTagName("link-entity");for(let n=0;n<r.length;n+=1){let i=r[n],o=i.getAttribute("name");if(!o)continue;let a=i.getElementsByTagName("attribute");for(let s=0;s<a.length;s+=1){let l=a[s],u=l.getAttribute("alias")||l.getAttribute("name");u&&t.set(u,o)}}return t}function lx(e){let t=vp(e);if(!t)return[];let r=sx(t),n=t.getElementsByTagName("attribute"),i=[];for(let o=0;o<n.length;o+=1){let a=n[o],s=a.getAttribute("aggregate");if(!s)continue;let l=a.getAttribute("name");if(!l)continue;let u={attribute:l,aggregate:s},c=a.getAttribute("charttype");c&&(u.seriesType=ix(c));let d=a.getAttribute("alias");d&&(u.alias=d);let f=d??l,p=r.get(f);p&&(u.relatedEntity=p),i.push(u)}return i}function ux(e){var t;let r=vp(e);if(!r)return[];let n=sx(r),i=r.getElementsByTagName("attribute"),o=[];for(let a=0;a<i.length;a+=1){let s=i[a];if(((t=s.getAttribute("groupby"))!==null&&t!==void 0?t:"").toLowerCase()!=="true")continue;let l=s.getAttribute("name");if(!l)continue;let u={attribute:l},c=s.getAttribute("dategrouping");c&&(u.dateGrouping=c);let d=s.getAttribute("alias");d&&(u.alias=d);let f=d??l,p=n.get(f);p&&(u.relatedEntity=p),o.push(u)}return o}function Nre(e){if(!tx(e.dataBag)||!tx(e.presentationBag)){let o=Are(e);return{datadescription:o,presentationdescription:Wre(e,o)}}let t=new DOMParser().parseFromString("<root/>","text/xml"),r=rx(e.dataBag,"datadefinition",t),n=rx(e.presentationBag,"Chart",t),i=lx(r);if(!nv(e.series,i)){let o=iv(r);_re(t,r,e.series);let a=iv(r),s=a.length>0?a:e.series.map(()=>"");cx(t,n,s,o,e.chartType)}return nv(e.categories,ux(r))||Tre(t,r,e.categories),e.chartType!==ox(n)&&px(n,e.chartType),nv(e.presentation,ax(n))||mx(n,e.presentation),{datadescription:(0,ni.serializeNode)(r),presentationdescription:(0,ni.serializeNode)(n)}}function tx(e){return!!e&&(e.c.length>0||e.a.length>0)}function cx(e,t,r,n,i){let o,a=t.childNodes;for(let d=0;d<a.length;d+=1)if(a[d].nodeType===1&&a[d].tagName==="Series"){o=a[d];break}o||(o=e.createElement("Series"),t.insertBefore(o,t.firstChild));let s=[],l=o.childNodes;for(let d=0;d<l.length;d+=1)l[d].nodeType===1&&l[d].tagName==="Series"&&s.push(l[d]);let u=new Map;n.forEach((d,f)=>{let p=s[f];if(!p)return;let m=u.get(d);m?m.push(p):u.set(d,[p])});let c=r.map(d=>{let f=u.get(d),p=f&&f.length>0?f.shift():void 0;if(p)return p;let m=e.createElement("Series");m.setAttribute("ChartType",i);let h=s.length>0?s[0].getAttribute("ChartArea"):null;return h&&m.setAttribute("ChartArea",h),m});for(let d of s)o.removeChild(d);for(let d of c)o.appendChild(d)}function iv(e){let t=[],r=e.getElementsByTagName("measure");for(let n=0;n<r.length;n+=1)t.push(r[n].getAttribute("alias")||"");return t}function rx(e,t,r){let n={n:t,a:(0,tv.mergeAttrs)(e.a,[]),c:(0,tv.spliceChildren)(e.c,[])};return(0,tv.rebuildRaw)(n,(0,ni.domEngine)(r),null)}function _re(e,t,r){let n=vp(t),i=n?.getElementsByTagName("entity")[0];!n||!i||dx(e,t,i,kre(n),r,$re,{aliasPrefix:"aggregate_column",addRef:Ore,removeRef:Lre})}function Tre(e,t,r){let n=vp(t),i=n?.getElementsByTagName("entity")[0];!n||!i||dx(e,t,i,xre(n),r,Fre,{aliasPrefix:"groupby_column",addRef:Pre,removeRef:Rre})}function dx(e,t,r,n,i,o,a){let s=new Map;for(let p of n){let m=p.getAttribute("alias");m&&s.set(m,p)}let l=new Set,u=[],c=(p,m)=>{var h;let g=Mre(r,p),b=m.relatedEntity;(g??void 0)!==(b??void 0)&&((h=p.parentNode)===null||h===void 0||h.removeChild(p),nx(e,r,p,b))};for(let p of i){let m=p.alias?s.get(p.alias):void 0;m&&!l.has(m)?(o(m,p),c(m,p),l.add(m)):u.push(p)}let d=n.filter(p=>!l.has(p)),f=0;for(let p of u)if(f<d.length){let m=d[f];o(m,p),c(m,p),l.add(m),f+=1}else{let m=e.createElement("attribute"),h=p.alias||Ire(t,a.aliasPrefix);m.setAttribute("alias",h),o(m,p),nx(e,r,m,p.relatedEntity),a.addRef(e,t,h)}for(let p of n)if(!l.has(p)){let m=p.getAttribute("alias");m&&a.removeRef(t,m),Bre(p)}}function Dre(e){let t=new Set;for(let r of["attribute","measure","category"]){let n=e.getElementsByTagName(r);for(let i=0;i<n.length;i+=1){let o=n[i].getAttribute("alias");o&&t.add(o)}}return t}function Ire(e,t){let r=Dre(e);if(!r.has(t))return t;for(let n=2;;n+=1){let i=`${t}_${n}`;if(!r.has(i))return i}}function fx(e,t){let r=t.getElementsByTagName("categorycollection")[0];if(r)return r;let n=e.createElement("categorycollection");return t.appendChild(n),n}function Ore(e,t,r){let n=fx(e,t),i=n.getElementsByTagName("category")[0];i||(i=e.createElement("category"),n.appendChild(i));let o=e.createElement("measurecollection"),a=e.createElement("measure");a.setAttribute("alias",r),o.appendChild(a),i.appendChild(o)}function Pre(e,t,r){let n=fx(e,t),i=e.createElement("category");i.setAttribute("alias",r),n.appendChild(i)}function Rre(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 Lre(e,t){var r;let n=e.getElementsByTagName("measure"),i=[];for(let o=0;o<n.length;o+=1)n[o].getAttribute("alias")===t&&i.push(n[o]);for(let o of i){let a=o.parentNode;a?.removeChild(o),a&&a.tagName==="measurecollection"&&!Vre(a)&&((r=a.parentNode)===null||r===void 0||r.removeChild(a))}}function kre(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 xre(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 $re(e,t){e.setAttribute("name",t.attribute),e.setAttribute("aggregate",t.aggregate),t.seriesType&&e.setAttribute("charttype",t.seriesType)}function Fre(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 Mre(e,t){let r=t.parentNode;for(;r&&r!==e;){let n=r;if(n.nodeType===1&&n.tagName==="link-entity")return n.getAttribute("name")||void 0;r=n.parentNode}}function nx(e,t,r,n){n?Ure(e,t,n).appendChild(r):t.appendChild(r)}function Ure(e,t,r){let n=t.getElementsByTagName("link-entity");for(let o=0;o<n.length;o+=1)if(n[o].getAttribute("name")===r)return n[o];let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function Bre(e){let t=e.parentNode;if(t&&(t.removeChild(e),t.tagName==="link-entity"&&!qre(t))){let r=t.parentNode;r&&r.removeChild(t)}}function qre(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 Vre(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1)if(t[r].nodeType===1)return!0;return!1}function px(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(!Gre(r[i])){r[i].setAttribute("ChartType",t);return}}}function Gre(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 mx(e,t){var r;let n=e.ownerDocument;if(t.palette!==void 0&&e.setAttribute("Palette",t.palette),t.showLegend!==void 0){let i=[],o=e.getElementsByTagName("Legends");for(let a=0;a<o.length;a+=1)i.push(o[a]);if(t.showLegend&&i.length===0){let a=n.createElement("Legends"),s=n.createElement("Legend");s.setAttribute("Name","Default"),a.appendChild(s),e.appendChild(a)}else if(!t.showLegend)for(let a of i)(r=a.parentNode)===null||r===void 0||r.removeChild(a)}if(t.title!==void 0){let i=e.getElementsByTagName("Title")[0];i&&(i.textContent=t.title)}}function Wre(e,t){let r=(0,ni.parseXmlRoot)(Ere(),"<Chart/>");px(r,e.chartType),mx(r,e.presentation);let n=iv((0,ni.parseXmlRoot)(t,"<datadefinition/>"));return n.length>0&&cx(r.ownerDocument,r,n,n.slice(0,1),e.chartType),(0,ni.serializeNode)(r)}function nv(e,t){return JSON.stringify(e)===JSON.stringify(t)}function rl(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function zre(){return{adapter:new bp,api:bre.chartApi,publish:(e,t,r)=>(0,Zk.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,Zk.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}nl.chartRegistration=zre});var vx=v(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});Ea.dashboardApi=Ea.dashboardEntity=void 0;var jre=Xt(),Io=ye(),il=ue(),Hre=lg(),gx=Zl();function yx(e){return e&&e.toLowerCase()!=="none"?e:void 0}Ea.dashboardEntity=yx;var bx="formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber",Kre={select:bx,required:["name","type","objecttypecode","istabletenabled"]},Jre="formid,name,type,objecttypecode",Yre=0,Qre=10;Ea.dashboardApi={async get(e,t){let r=(0,il.normalizeGuid)(t,"id"),n=`/systemforms(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,il.odataQuery)([["$select",bx]]),i=(0,Io.ensureSuccess)(await e.get(n),e.apiUrl(n));return(0,gx.assertSystemFormRecordKind)(i.body,r,"dashboard","fetch"),{raw:i.body,etag:(0,Io.readEtag)(i)}},async list(e,t){let r=[`(type eq ${Yre} or type eq ${Qre})`];t?.entityLogicalName&&r.push(`objecttypecode eq '${(0,il.odataLiteral)(t.entityLogicalName)}'`);let n=`/systemforms${(0,il.odataQuery)([["$select",Jre],["$filter",r.join(" and ")]])}`;return(await(0,jre.collectPages)(e,n,"listArtifacts('dashboard')")).map(o=>{var a,s;let l=yx(o.objecttypecode);return{type:"dashboard",id:(a=o.formid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",...l?{entityLogicalName:l}:{},isDirty:!1}})},async create(e,t,r){let n=t,i=(0,Io.echoWrite)("formid"),o=`/systemforms${i.query}`,a={name:n.name,description:n.description,formxml:n.formxml,istabletenabled:n.istabletenabled,type:n.type};n.objecttypecode&&(a.objecttypecode=n.objecttypecode);let s=(0,Io.ensureSuccess)(await e.post(o,(0,Io.withClientMintedId)(a,"formid",r),i.options),e.apiUrl(o));return{id:(0,Io.resolveCreatedId)(s,"formid","dashboard",r),etag:(0,Io.readEtag)(s)}},async update(e,t,r,n){let i=r;return(0,Hre.patchSystemForm)(e,(0,il.normalizeGuid)(t,"id"),"dashboard",{name:i.name,description:i.description,formxml:i.formxml,istabletenabled:i.istabletenabled},n,Kre)},readContentThenToken(e,t){return Ea.dashboardApi.get(e,t)},async delete(e,t){let r=(0,il.normalizeGuid)(t,"id");return await(0,gx.assertSystemFormKind)(e,r,"dashboard"),(0,Io.deleteRecord)(e,"systemforms",r)}}});var Rx=v(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.dashboardRegistration=ii.TILE_CLASS_ID=ii.DashboardAdapter=void 0;var ec=ao(),fn=lo(),ov=Kr(),Zu=Zr(),Nx=vx(),av=so(),Aa=lt(),_x=ue(),Tx=Ko(),Xre=vy(),wx="0",sv="10",Zre=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"]]),ene="{3FF9A528-DD50-4ACA-8F10-2E5ED73513AD}",Cp=class{constructor(t=Tx.DEFAULT_LCID){this.lcid=t}toArtifact(t){var r,n,i,o,a;(0,av.installDomShim)();let s=(r=t.formxml)!==null&&r!==void 0?r:"",l=(0,fn.parseXmlRoot)(s,"<form/>");return{id:(n=t.formid)!==null&&n!==void 0?n:"",name:(i=t.name)!==null&&i!==void 0?i:"",description:(o=t.description)!==null&&o!==void 0?o:"",dashboardType:tne(t.type),entityLogicalName:(a=(0,Nx.dashboardEntity)(t.objecttypecode))!==null&&a!==void 0?a:null,enabledForMobile:!!t.istabletenabled,layoutType:rne(l),components:Cx(l,this.lcid),bag:(0,fn.projectElementBag)(l)}}fromArtifact(t){var r;return(0,av.installDomShim)(),{formid:t.id,name:t.name,description:t.description,type:t.dashboardType==="Interactive"?sv:wx,objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",istabletenabled:t.enabledForMobile,formxml:Ex(t,this.lcid)}}fromApiResponse(t){return this.toArtifact(t??{})}completeAsStored(t,r){return(0,Xre.completeRecordAsStored)(t,r,this.lcid)}toApiPayload(t){return{name:t.name,description:t.description,formxml:Ex(t,this.lcid),istabletenabled:t.enabledForMobile,type:t.dashboardType==="Interactive"?sv:wx,objecttypecode:t.entityLogicalName}}createDefault(t){var r,n,i,o,a,s,l,u;(0,av.installDomShim)();let c=(0,fn.parseXmlRoot)(hne(),"<form/>");return{id:(r=t.id)!==null&&r!==void 0?r:(0,Aa.newId)(),name:(n=t.name)!==null&&n!==void 0?n:"New Dashboard",description:(i=t.description)!==null&&i!==void 0?i:"",dashboardType:(o=t.dashboardType)!==null&&o!==void 0?o:"Standard",entityLogicalName:(a=t.entityLogicalName)!==null&&a!==void 0?a:null,enabledForMobile:(s=t.enabledForMobile)!==null&&s!==void 0?s:!1,layoutType:(l=t.layoutType)!==null&&l!==void 0?l:0,components:(u=t.components)!==null&&u!==void 0?u:Cx(c,this.lcid),bag:(0,fn.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,Aa.newId)())}return t}validate(t){let r=[],n=(0,Zu.childObjects)(t,"components","","component",r),i=new Set;return n.forEach(({node:o,index:a})=>{let s=`/components/${a}`;for(let l of["position","parameters"]){let u=o[l];u!==void 0&&!(0,Zu.isJsonObject)(u)&&r.push((0,Zu.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,Zu.isJsonObject)(o.position)){let l=tc(o.position);i.has(l)?r.push((0,Zu.issue)(`${s}/position`,"component-position-collision",`two components occupy the same dashboard position (${l}); move one to a free cell`)):i.add(l)}}),r}};ii.DashboardAdapter=Cp;function tne(e){return String(e??"")===sv?"Interactive":"Standard"}function rne(e){let t=e?.getAttribute("formLayout")||e?.getAttribute("layoutType"),r=parseInt(t??"",10);return Number.isNaN(r)?0:r}function ae(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName.toLowerCase()===t&&r.push(o)}return r}function Cx(e,t){let r=[];return ae(e,"tabs").flatMap(i=>ae(i,"tab")).forEach((i,o)=>{ae(i,"columns").flatMap(s=>ae(s,"column")).forEach((s,l)=>{ae(s,"sections").flatMap(c=>ae(c,"section")).forEach((c,d)=>{nne(c,{tabIndex:o,columnIndex:l,sectionIndex:d},r,t)})})}),r}function nne(e,t,r,n){ae(e,"rows").flatMap(o=>ae(o,"row")).forEach((o,a)=>{ae(o,"cell").forEach((s,l)=>{let u=ine(s,{...t,rowIndex:a,cellIndex:l},n);u&&r.push(u)})})}function ine(e,t,r){var n,i;let o=Ox((n=e.getAttribute("id"))!==null&&n!==void 0?n:"");if(o.toLowerCase().startsWith("spacer"))return null;let a=ae(e,"control")[0];if(!a)return null;let s=(i=a.getAttribute("classid"))!==null&&i!==void 0?i:"",l=sne(a),u=lne(s,l,a),c=one(a);return{id:a.getAttribute("id")||o,type:u,name:Ix(e,r),classId:s,position:t,colspan:lv(e,"colspan",1),rowspan:lv(e,"rowspan",1),parameters:l,bag:(0,fn.projectElementBag)(e),...c?{icProperties:c}:{}}}function Dx(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 one(e){let t=Dx(e);return t?(0,fn.serializeNode)(t):void 0}function ane(e,t,r){let n=Dx(t);if(!r){n&&t.removeChild(n);return}let i=new DOMParser().parseFromString(r,"text/xml").documentElement,o=(0,ec.rebuildRaw)((0,ec.rawFromNode)((0,fn.nodeLikeFromDom)(i)),(0,fn.domEngine)(e),null);n&&(0,fn.serializeNode)(n)===(0,fn.serializeNode)(o)||(n?t.replaceChild(o,n):t.appendChild(o))}function Ix(e,t){var r,n;let i=ae(e,"labels")[0];if(!i)return"";let o=ae(i,"label"),a=(r=o.find(s=>s.getAttribute("languagecode")===String(t)))!==null&&r!==void 0?r:o[0];return(n=a?.getAttribute("description"))!==null&&n!==void 0?n:""}function sne(e){var t;let r={},n=ae(e,"parameters")[0];if(!n)return r;let i=n.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];a.nodeType===1&&(r[a.tagName]=((t=a.textContent)!==null&&t!==void 0?t:"").trim())}return r}function lne(e,t,r){var n;let i=Zre.get(e.toUpperCase());return i?i==="chart"?t.ChartGridMode==="Chart"?"chart":"list":i==="assistant"&&((n=r.getAttribute("uniqueid"))!==null&&n!==void 0?n:"").toUpperCase()===ene?"assistant":i:"unknown"}function lv(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 Ox(e){return e.replace(/^\{/,"").replace(/\}$/,"")}function une(e,t){let r={n:"form",a:(0,ec.mergeAttrs)(e.bag.a,[]),c:(0,ec.spliceChildren)(e.bag.c,[])};return(0,ec.rebuildRaw)(r,(0,fn.domEngine)(t),null)}function Ex(e,t){let r=new DOMParser().parseFromString("<root/>","text/xml"),n=une(e,r);return fne(r,n,e.components,t),cne(r,n,e.components,t),(0,fn.serializeNode)(n)}function cne(e,t,r,n){let i=Px(t);for(let o of r)i.has(tc(o.position))||dne(e,t,o,n)}function dne(e,t,r,n){var i,o,a,s;let l=(o=(i=r.position)===null||i===void 0?void 0:i.sectionIndex)!==null&&o!==void 0?o:0,u=gne(t,e,l);for(let $ of ae(u,"row"))ae($,"cell").some(K=>ae(K,"control").length>0)||u.removeChild($);let c=r.classId||ii.TILE_CLASS_ID[r.type]||ii.TILE_CLASS_ID.iframe,d=r.rowspan&&r.rowspan>0?r.rowspan:4,f=r.bag&&Ax(r.bag,"id")?String(Ax(r.bag,"id")):wp((0,Aa.newId)()),p=r.id?wp(r.id):wp((0,Aa.newId)()),m=u.parentNode,h=Math.max(1,parseInt(m&&m.getAttribute&&m.getAttribute("columns")||"1",10)||1),g=Math.min(Math.max(1,r.colspan&&r.colspan>0?r.colspan:1),h),b=ae(u,"row"),w=b[b.length-1],E=w?ae(w,"cell").reduce(($,K)=>$+lv(K,"colspan",1),0):0;(!w||E+g>h)&&(w=e.createElement("row"),u.appendChild(w));let A=e.createElement("cell");A.setAttribute("id",f),A.setAttribute("colspan",String(g)),A.setAttribute("rowspan",String(d)),A.setAttribute("showlabel","true");let L=e.createElement("labels"),R=e.createElement("label");R.setAttribute("description",(a=r.name)!==null&&a!==void 0?a:""),R.setAttribute("languagecode",String(n)),L.appendChild(R),A.appendChild(L);let I=e.createElement("control");I.setAttribute("id",p),I.setAttribute("classid",wp(c));let D=e.createElement("parameters"),O=(s=r.parameters)!==null&&s!==void 0?s:{};for(let $ of Object.keys(O)){let K=(0,_x.createSafeXmlElement)(e,$,"dashboard tile parameter");K.textContent=O[$],D.appendChild(K)}I.appendChild(D),A.appendChild(I),w.appendChild(A)}function Ax(e,t){if(!e)return;let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function fne(e,t,r,n){var i;let o=Px(t),a=new Set(r.map(s=>tc(s.position)));for(let s of r){let l=o.get(tc(s.position));if(!l)continue;let u=ae(l,"control")[0];u&&(pne(e,l,s.name,n),mne(e,u,s.parameters),Sx(l,"colspan",s.colspan),Sx(l,"rowspan",s.rowspan),s.icProperties!==void 0&&ane(e,u,s.icProperties))}for(let[s,l]of o)a.has(s)||(i=l.parentNode)===null||i===void 0||i.removeChild(l)}function Px(e){let t=new Map;return ae(e,"tabs").flatMap(n=>ae(n,"tab")).forEach((n,i)=>{ae(n,"columns").flatMap(a=>ae(a,"column")).forEach((a,s)=>{ae(a,"sections").flatMap(u=>ae(u,"section")).forEach((u,c)=>{ae(u,"rows").flatMap(f=>ae(f,"row")).forEach((f,p)=>{ae(f,"cell").forEach((m,h)=>{var g;Ox((g=m.getAttribute("id"))!==null&&g!==void 0?g:"").toLowerCase().startsWith("spacer")||ae(m,"control")[0]&&t.set(tc({tabIndex:i,columnIndex:s,sectionIndex:c,rowIndex:p,cellIndex:h}),m)})})})})}),t}function tc(e){let t=e??{};return`${t.tabIndex}.${t.columnIndex}.${t.sectionIndex}.${t.rowIndex}.${t.cellIndex}`}function pne(e,t,r,n){if(r===Ix(t,n))return;let i=ae(t,"labels")[0];i||(i=e.createElement("labels"),t.appendChild(i));let o=ae(i,"label").find(a=>a.getAttribute("languagecode")===String(n));o||(o=e.createElement("label"),o.setAttribute("languagecode",String(n)),i.appendChild(o)),o.setAttribute("description",r)}function mne(e,t,r){var n;if(!r)return;let i=Object.keys(r);if(i.length===0)return;let o=ae(t,"parameters")[0];o||(o=e.createElement("parameters"),t.appendChild(o));let a=new Map,s=o.childNodes;for(let l=0;l<s.length;l+=1){let u=s[l];u.nodeType===1&&a.set(u.tagName,u)}for(let l of i){let u=r[l],c=a.get(l);if(c)((n=c.textContent)!==null&&n!==void 0?n:"")!==u&&(c.textContent=u);else{let d=(0,_x.createSafeXmlElement)(e,l,"dashboard component parameter");d.textContent=u,o.appendChild(d)}}}function Sx(e,t,r){var n;((n=e.getAttribute(t))!==null&&n!==void 0?n:"")!==String(r)&&e.setAttribute(t,String(r))}function hne(e=2){let t=`{${(0,Aa.newId)()}}`,r=`{${(0,Aa.newId)()}}`,n=`{${(0,Aa.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>`}ii.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 wp(e){return`{${e.replace(/[{}]/g,"")}}`}function gne(e,t,r){var n;let i=ae(e,"tabs").flatMap(u=>ae(u,"tab"))[0];if(!i)throw new Error("addDashboardTile: dashboard formxml has no <tab>");let o=ae(i,"columns").flatMap(u=>ae(u,"column"))[0];if(!o)throw new Error("addDashboardTile: dashboard formxml has no <column>");let a=ae(o,"sections").flatMap(u=>ae(u,"section")),s=(n=a[r])!==null&&n!==void 0?n:a[0];if(!s)throw new Error("addDashboardTile: dashboard formxml has no <section>");let l=ae(s,"rows")[0];return l||(l=t.createElement("rows"),s.appendChild(l)),l}function yne(e=Tx.DEFAULT_LCID){return{adapter:new Cp(e),api:Nx.dashboardApi,languageSensitive:!0,publish:(t,r,n)=>n?.entityLogicalName?(0,ov.publishBoundEntity)(t,n):(0,ov.publishDashboardById)(t,r),publishScope:(t,r)=>r?.entityLogicalName?(0,ov.boundEntityPublishScope)(r):{envelope:"dashboard",targetIds:[t]},rebaselineAfterPublish:"bracket"}}ii.dashboardRegistration=yne});var cv=v(Pr=>{"use strict";Object.defineProperty(Pr,"__esModule",{value:!0});Pr.readEveryInOrder=Pr.readInOrder=Pr.plainRead=Pr.resolveReadConcurrency=Pr.MAX_READ_CONCURRENCY=void 0;var Lx=Q();Pr.MAX_READ_CONCURRENCY=8;function bne(e){if(e===void 0)return 1;if(typeof e!="number"||!Number.isInteger(e)||e<1||e>Pr.MAX_READ_CONCURRENCY)throw new Lx.InvalidArgumentError(`readConcurrency must be a whole number from 1 to ${Pr.MAX_READ_CONCURRENCY} (got ${typeof e=="string"?`'${e}'`:String(e)})`);return e}Pr.resolveReadConcurrency=bne;var vne=e=>({ok:!0,value:e}),uv=e=>({ok:!1,error:e});function wne(e){let t=(async()=>e())().then(vne,uv);return{outcome:t,finish:async r=>{await r()},discard:async()=>{await t}}}Pr.plainRead=wne;async function kx(e,t,r,n,i){if(!Number.isInteger(t)||t<1)throw new Lx.InvalidArgumentError(`a read window holds a whole number of reads, at least 1 (got ${String(t)})`);let o=new Map,a=0,s=Promise.resolve(),l=!1,u=0,c,d=async f=>{if(l)return{refusal:new Error("The read was not started: an earlier read had already failed.")};try{let p=await r(e[f],f),m=p.outcome.catch(uv);return i==="stop"&&m.then(h=>{l=l||!h.ok}),{read:p,outcome:m}}catch(p){return l=l||i==="stop",{refusal:p}}};try{for(let f=0;f<e.length;f+=1){for(;a<e.length&&a<f+t;){let g=a;a+=1;let b=s.then(()=>d(g));o.set(g,b),s=b}let p=await o.get(f),m="read"in p?await p.outcome:uv(p.refusal);if(!m.ok&&i==="stop"){c={error:m.error};break}u=f+1,o.delete(f);let h=()=>n(m,e[f],f);"read"in p?await p.read.finish(h):await h()}}finally{l=!0;for(let f=u;f<a;f+=1){let p=await o.get(f);"read"in p&&await p.read.discard().catch(()=>{})}}if(c)throw c.error}function Cne(e,t,r,n){return kx(e,t,r,(i,o,a)=>n(i.value,o,a),"stop")}Pr.readInOrder=Cne;function Ene(e,t,r,n){return kx(e,t,r,n,"continue")}Pr.readEveryInOrder=Ene});var Qx=v(Ap=>{"use strict";Object.defineProperty(Ap,"__esModule",{value:!0});Ap.genPageApi=void 0;var Ep=Xt(),jx=Wl(),Be=ye(),he=ue(),Rn=Td(),Qe=Q(),Hx=lt(),xx=cv();function Ane(e){if(ArrayBuffer.isView(e)){let r=e;return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}if(Object.prototype.toString.call(e)==="[object ArrayBuffer]")return new Uint8Array(e);let t=globalThis;if(t.Buffer&&t.Buffer.isBuffer(e)){let r=e;return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}}var oi="uxagentprojects",Na="uxagentprojectfiles",ic="agentconversationmessages",oc="uxagentprojectid",xt="uxagentprojectfileid",_a="agentconversationmessageid",rc=`${oc},name`,Sne=`${xt},filename,filetype`,Kx=2e8,Jx=200000001,Ta={"MSCRM.IncludeUnpublished":"true"},dv={};function Sa(e,t){return{"MSCRM.VersioningChangeset":e,...Ta,...t}}async function mv(e,t,r,n){var i;let o=`/${t}(${r})`+(0,he.odataQuery)([["$select",n]]),a=(0,Be.ensureSuccess)(await e.get(o,{headers:{...Ta}}),e.apiUrl(o));return{row:(i=a.body)!==null&&i!==void 0?i:{},etag:(0,Be.readEtag)(a)}}async function ac(e,t,r=Ta){let n=`/${Na}(${t})/filecontent/$value`,i=await e.get(n,{headers:{...r}});if(i.status===404)return{status:"unavailable",reason:"missing"};(0,Be.ensureSuccess)(i,e.apiUrl(n));let o=i.body,a=Ane(o);if(a)return{status:"available",data:(0,Rn.bytesToBase64)(a)};if(typeof o=="string")return{status:"available",data:(0,Rn.utf8ToBase64)(o)};throw new Qe.SdkError("GENPAGE_CONTENT_UNREADABLE",`Read the content of file '${t}' but the injected HttpClient returned a body this SDK cannot encode (${typeof o}). Return the response as a string, Uint8Array, Buffer, or ArrayBuffer; a byte-returning transport is required to round-trip non-UTF8 assets.`)}function Yx(e){let t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}async function Nne(e,t,r,n,i,o){if(!e.supportsBinaryPatch)throw new Qe.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED",`Refusing to push generative-page file '${t}': its content cannot be written because the injected HttpClient does not implement patchRaw(). A Dataverse File column is not writable through a JSON body, so saving the row without its bytes would report success for a page whose source never uploaded.`);let a=`/${Na}(${t})/filecontent`,s=(0,Rn.base64ToBytes)(n);(0,he.assertNoControlChars)(r,"generative-page file name"),(0,Be.ensureSuccess)(await e.patchRaw(a,s,{headers:Sa(i,{"Content-Type":"application/octet-stream","Content-Length":String(s.byteLength),"x-ms-file-name":Yx(r),...o?{"If-Match":"*"}:{}})}),e.apiUrl(a))}async function nc(e,t,r=Ta){let n=`/${Na}`+(0,he.odataQuery)([["$select",Sne],["$filter",`_${oc}_value eq ${t}`]]);return(await(0,Ep.collectPages)(e,n,"fetchArtifact('genPage')",void 0,{headers:{...r}})).map(o=>({row:o,etag:typeof o["@odata.etag"]=="string"?o["@odata.etag"]:null}))}async function fv(e,t){let r=`/${ic}`+(0,he.odataQuery)([["$select",`${_a},message,messagesender,createdon`],["$filter",`_regardingobjectid_value eq ${t}`],["$orderby","createdon asc,versionnumber asc"]]);return(0,Ep.collectPages)(e,r,"fetchArtifact('genPage')",void 0,{headers:{...Ta}})}async function $x(e,t){var r,n,i;let{row:o,etag:a}=await mv(e,oi,t,rc),s=new Map;for(let{row:l,etag:u}of await nc(e,t))s.set((0,he.normalizeGuid)(String((r=l[xt])!==null&&r!==void 0?r:""),xt),{filename:String((n=l.filename)!==null&&n!==void 0?n:""),filetype:Number(l.filetype),etag:u});return{name:String((i=o.name)!==null&&i!==void 0?i:""),etag:a,rows:s}}function Fx(e,t,r){var n,i,o,a,s;let l=[];r||l.push({kind:"createProject",name:t.name});let u=new Set;for(let c of(n=t.files)!==null&&n!==void 0?n:[]){let d=(0,he.normalizeGuid)(c.id,"file id");u.add(d);let f=r?.rows.get(d);if(c.content.status==="retain"){if(!r)throw new Qe.SdkError("GENPAGE_RETAIN_ON_CREATE",`Refusing to create generative page '${e}': file '${c.name}' asks to keep content the page does not have yet. This is an SDK defect \u2014 the page's rows were not written.`);if(!f)throw new Qe.SdkError("GENPAGE_RETAINED_ROW_MISSING",`Refusing to write generative page '${e}': file '${c.name}' was to be kept unchanged but is not on the server. Re-fetch the page and retry.`);continue}f&&c.unchanged||(f?(f.filename!==c.name||f.filetype!==c.fileType)&&l.push({kind:"renameRow",file:c}):l.push({kind:"createRow",file:c}),c.content.status==="available"&&l.push({kind:"content",file:c,data:c.content.data,existing:f!==void 0}))}for(let c of(i=r?.rows.keys())!==null&&i!==void 0?i:[])u.has(c)||l.push({kind:"deleteRow",fileId:c});(!r||l.length>0||r.name!==t.name||((a=(o=t.messages)===null||o===void 0?void 0:o.length)!==null&&a!==void 0?a:0)>0)&&l.push({kind:"patchProject",name:t.name});for(let c of(s=t.messages)!==null&&s!==void 0?s:[])l.push({kind:"message",turn:c});return l}function hv(e){let t=(0,Rn.base64ToUtf8)(e);return(0,Rn.utf8ToBase64)(t)===(0,Rn.bytesToBase64)((0,Rn.base64ToBytes)(e))?t:void 0}function _ne(e,t,r,n){var i,o,a,s,l,u,c,d;let f=t.sender==="user"?{changeSet:n,dataSources:(o=(i=r.messageContext)===null||i===void 0?void 0:i.dataSources)!==null&&o!==void 0?o:[],model:(s=(a=r.messageContext)===null||a===void 0?void 0:a.model)!==null&&s!==void 0?s:"",enabledTools:(u=(l=r.messageContext)===null||l===void 0?void 0:l.enabledTools)!==null&&u!==void 0?u:[],configurableTools:(d=(c=r.messageContext)===null||c===void 0?void 0:c.configurableTools)!==null&&d!==void 0?d:[]}:{changeSet:n};return{...t.id?{[_a]:(0,he.normalizeGuid)(t.id,"message id")}:{},"[email protected]":`/${oi}(${e})`,message:t.message,messagecontext:JSON.stringify(f),messagesender:t.sender==="user"?Kx:Jx}}async function Tne(e,t,r){var n,i,o,a;let s=((n=r.messages)!==null&&n!==void 0?n:[]).map(f=>f.id).filter(f=>typeof f=="string"&&f!=="").map(f=>(0,he.normalizeGuid)(f,"message id"));if(s.length===0)return r;let l=`/${ic}`+(0,he.odataQuery)([["$select",`${_a},message,messagesender,_regardingobjectid_value`],["$filter",s.map(f=>`${_a} eq ${f}`).join(" or ")]]),u=await(0,Ep.collectPages)(e,l,"pushArtifact('genPage')",void 0,{headers:{...Ta}});if(u.length===0)return r;let c=new Map(u.map(f=>{var p;return[String((p=f[_a])!==null&&p!==void 0?p:"").toLowerCase(),f]})),d=[];for(let f of(i=r.messages)!==null&&i!==void 0?i:[]){let p=f.id?c.get((0,he.normalizeGuid)(f.id,"message id")):void 0;if(!p){d.push(f);continue}if(!(String((o=p.message)!==null&&o!==void 0?o:"")===f.message&&Number(p.messagesender)===(f.sender==="user"?Kx:Jx)&&String((a=p._regardingobjectid_value)!==null&&a!==void 0?a:"").toLowerCase()===t))throw new Qe.SdkError("GENPAGE_TURN_CONFLICT",`Refusing to push generative page '${t}': its pending turn's identity is already recorded \u2014 as a DIFFERENT ${f.sender} message. An earlier push of this turn did commit (its response was lost), and the turn was changed since. Nothing was written, and the turn is still pending. To record it as a new turn, remove '/newTurn/id' (a new identity is minted on the next push); to keep only what was recorded, remove '/newTurn'.`)}return{...r,messages:d}}function pv(e,t,r,n){switch(t.kind){case"createProject":return{method:"POST",path:`/${oi}`,body:(0,Be.withClientMintedId)({name:t.name},oc,e),headers:Sa(n)};case"createRow":return{method:"POST",path:`/${Na}`,body:(0,Be.withClientMintedId)({filename:t.file.name,filetype:t.file.fileType,[`${oc}@odata.bind`]:`/${oi}(${e})`},xt,(0,he.normalizeGuid)(t.file.id,"file id")),headers:Sa(n)};case"renameRow":return{method:"PATCH",path:`/${Na}(${(0,he.normalizeGuid)(t.file.id,"file id")})`,body:{filename:t.file.name,filetype:t.file.fileType},headers:Sa(n,{"If-Match":"*"})};case"content":{let i=hv(t.data);if(i===void 0)throw new Qe.SdkError("GENPAGE_CONTENT_NOT_TEXT",`File '${t.file.name}' is not UTF-8 text and cannot ride in a change set.`);return(0,he.assertNoControlChars)(t.file.name,"generative-page file name"),{method:"PATCH",path:`/${Na}(${(0,he.normalizeGuid)(t.file.id,"file id")})/filecontent`,rawBody:i,contentType:"application/octet-stream; charset=utf-8",headers:Sa(n,{"x-ms-file-name":Yx(t.file.name),...t.existing?{"If-Match":"*"}:{}})}}case"deleteRow":return{method:"DELETE",path:`/${Na}(${t.fileId})`,headers:Sa(n,{"If-Match":"*"})};case"patchProject":return{method:"PATCH",path:`/${oi}(${e})`,body:{name:t.name},headers:Sa(n,{"If-Match":"*"})};case"message":return{method:"POST",path:`/${ic}`,body:_ne(e,t.turn,r,n)};default:{let i=t;throw new Qe.SdkError("GENPAGE_WRITE_UNKNOWN",`Unknown generative-page write: ${JSON.stringify(i)}`)}}}function Mx(e,t){return e.supportsAtomicBatch&&t.every(r=>r.kind!=="content"||hv(r.data)!==void 0)}async function Ux(e,t,r,n,i){await(0,jx.postChangeSet)(e,r.map(o=>pv(t,o,n,i)),`generative page '${t}' (${r.length} operation(s))`)}async function Bx(e,t,r,n,i){var o;let a=[];for(let s of r){if(s.kind==="message"){a.push(s);continue}if(s.kind==="content"){await Nne(e,(0,he.normalizeGuid)(s.file.id,"file id"),s.file.name,s.data,i,s.existing);continue}let l=pv(t,s,n,i),u={headers:(o=l.headers)!==null&&o!==void 0?o:{}},c=l.method==="POST"?await e.post(l.path,l.body,u):l.method==="PATCH"?await e.patch(l.path,l.body,u):await e.delete(l.path,u);(0,Be.ensureSuccess)(c,e.apiUrl(l.path))}if(a.length===0)return{warnings:[],turnRecorded:!0};try{let s=a.map(l=>pv(t,l,n,i));if(e.supportsAtomicBatch)await(0,jx.postChangeSet)(e,s,`the conversation turn of generative page '${t}'`);else for(let l of s)(0,Be.ensureSuccess)(await e.post(l.path,l.body),e.apiUrl(l.path));return{warnings:[],turnRecorded:!0}}catch(s){return{warnings:[`Generative page '${t}' was saved, but its conversation turn could not be recorded (${s instanceof Error?s.message:String(s)}). The turn is kept: the next push of the page records it.`],turnRecorded:!1}}}async function qx(e,t,r,n,i,o,a){var s;let l=u=>({id:t,etag:null,memberEtags:{},warnings:[...a,u]});try{let u=await $x(e,t),c=new Map;for(let E of r)(E.kind==="createRow"||E.kind==="renameRow"||E.kind==="content")&&c.set((0,he.normalizeGuid)(E.file.id,"file id"),E.file);let d=[];u.name!==n.name&&d.push(`the page is named '${u.name}', not '${n.name}'`);for(let[E,A]of c){let L=u.rows.get(E);L&&(L.filename!==A.name||L.filetype!==A.fileType)&&d.push(`file '${A.name}' is stored as '${L.filename}' (type ${L.filetype})`)}for(let E of r){if(E.kind!=="content")continue;let A=await ac(e,(0,he.normalizeGuid)(E.file.id,"file id")),L=(0,Rn.bytesToBase64)((0,Rn.base64ToBytes)(E.data));(A.status!=="available"||A.data!==L)&&d.push(A.status==="available"?`file '${E.file.name}' holds ${(0,Rn.base64ToBytes)(A.data).byteLength} byte(s) that differ from the ${(0,Rn.base64ToBytes)(L).byteLength} written`:`file '${E.file.name}' holds no content`)}let f=new Set(r.filter(E=>E.kind==="content").map(E=>(0,he.normalizeGuid)(E.file.id,"file id")));for(let[E,A]of c)!f.has(E)&&(await ac(e,E)).status==="available"&&d.push(`file '${A.name}' holds content this push did not write`);if(d.length>0)return l(`Generative page '${t}' was written, but reading it back does not match what was sent: ${d.join("; ")}. The local baseline is now unusable: re-fetch the page to see what the server holds \u2014 the next push will refuse rather than overwrite blind.`);let p=await $x(e,t),m=[...p.rows.keys()],h=p.etag!==u.etag||p.rows.size!==u.rows.size||m.some(E=>{var A,L;return((A=u.rows.get(E))===null||A===void 0?void 0:A.etag)!==((L=p.rows.get(E))===null||L===void 0?void 0:L.etag)}),g=m.length!==i.size||m.some(E=>!i.has(E)),b={},w=[];for(let[E,A]of p.rows){let L=c.has(E)||!o?A.etag:(s=o.get(E))!==null&&s!==void 0?s:null;b[E]=L,L!==A.etag&&w.push(A.filename)}return h||g||!p.etag||Object.values(b).some(E=>!E)?l(`Generative page '${t}' was written, but its files changed on the server while the write was in progress, so the new concurrency tokens cannot be trusted. The local baseline is now unusable: re-fetch the page before editing it again \u2014 the next push will refuse rather than overwrite blind.`):Dne({id:t,etag:p.etag,memberEtags:b},[...a,...w.map(E=>`Generative page '${t}' was written, but its file '${E}' changed on the server while this push ran \u2014 another writer edited it. This push did not touch that file, so the next one refuses until you re-fetch the page and see their change.`)])}catch(u){return l(`The generative page was written, but reading it back failed (${u instanceof Error?u.message:String(u)}). The local baseline is unusable: re-fetch the page before editing it \u2014 the next push will refuse rather than overwrite blind.`)}}async function Vx(e,t,r,n=e.readConcurrency){var i;let o=(0,he.normalizeGuid)(t,"id"),{row:a,etag:s}=await mv(e,oi,o,rc),l=await nc(e,o),u={},c=[];if(n>1)await(0,xx.readInOrder)(l,n,({row:f})=>{var p;let m=(0,he.normalizeGuid)(String((p=f[xt])!==null&&p!==void 0?p:""),xt);return(0,xx.plainRead)(async()=>({fileId:m,content:await ac(e,m)}))},({fileId:f,content:p},{row:m,etag:h})=>{u[f]=h,c.push({...m,content:p})});else for(let{row:f,etag:p}of l){let m=(0,he.normalizeGuid)(String((i=f[xt])!==null&&i!==void 0?i:""),xt);u[m]=p;let h=await ac(e,m);c.push({...f,content:h})}return{raw:r?{project:a,files:c,conversation:await fv(e,o)}:{project:a,files:c},etag:s,memberEtags:u}}Ap.genPageApi={get(e,t,r){return Vx(e,t,!0,r?.fileConcurrency)},getForRebaseline(e,t){return Vx(e,t,!1)},async getPublished(e,t){var r,n;let i=(0,he.normalizeGuid)(t,"id"),o=`/${oi}(${i})`+(0,he.odataQuery)([["$select",rc]]),a=await e.get(o);if(a.status===404)return null;(0,Be.ensureSuccess)(a,e.apiUrl(o));let s=(r=a.body)!==null&&r!==void 0?r:{},l={},u=[],c=await nc(e,i,dv);for(let{row:g,etag:b}of c){let w=(0,he.normalizeGuid)(String((n=g[xt])!==null&&n!==void 0?n:""),xt);l[w]=b,u.push({...g,content:await ac(e,w,dv)})}let d=g=>g.map(({row:b,etag:w})=>`${String(b[xt])}@${String(w)}`).sort().join("|"),f=()=>new Qe.SdkError("GENPAGE_PUBLISHED_READ_MOVED",`The published projection of generative page '${i}' changed while it was being read, so what was read is not one published state. PublishXml is asynchronous \u2014 re-read shortly.`),p=await e.get(o);if(p.status===404)throw f();(0,Be.ensureSuccess)(p,e.apiUrl(o));let m=await nc(e,i,dv);if([(0,Be.readEtag)(a),(0,Be.readEtag)(p),...[...c,...m].map(g=>g.etag)].some(g=>!g))throw new Qe.SdkError("GENPAGE_PUBLISHED_READ_UNVERSIONED",`The published projection of generative page '${i}' answered without a version token for the page or one of its rows, so what was read cannot be proven to be one published state.`);if((0,Be.readEtag)(p)!==(0,Be.readEtag)(a)||d(m)!==d(c))throw f();return{raw:{project:s,files:u,conversation:[]},etag:(0,Be.readEtag)(a),memberEtags:l}},async list(e,t){let r=`/${oi}`+(0,he.odataQuery)([["$select",rc]]);return(await(0,Ep.collectPages)(e,r,"listArtifacts('genPage')",void 0,{headers:{...Ta}})).map(i=>{var o,a;return{type:"genPage",id:String((o=i[oc])!==null&&o!==void 0?o:""),name:String((a=i.name)!==null&&a!==void 0?a:""),isDirty:!1}})},async create(e,t,r){var n;let i=t;zx(e,i);let o=r?(0,he.normalizeGuid)(r,"id"):(0,Hx.newId)();Wx(e,o,i);let a=Fx(o,i,void 0),s=Gx(),l=[],u=!0;Mx(e,a)?await Ux(e,o,a,i,s):{warnings:l,turnRecorded:u}=await Bx(e,o,a,i,s);let c=new Set(((n=i.files)!==null&&n!==void 0?n:[]).map(f=>(0,he.normalizeGuid)(f.id,"file id"))),d=await qx(e,o,a,i,c,void 0,l);return u?d:{...d,intentPending:!0}},async update(e,t,r,n,i){var o,a;let s=r,l=(0,he.normalizeGuid)(t,"id");zx(e,s);let u=await Tne(e,l,s);Wx(e,l,u);let c=await nc(e,l),{row:d,etag:f}=await mv(e,oi,l,rc);if(n&&f&&n!==f)throw new Qe.SdkError(Be.VERSION_CONFLICT_CODE,`Generative page '${l}' changed on the server after it was fetched (baseline ${n}, server ${f}) \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||!f)throw new Qe.SdkError(Be.VERSION_CONFLICT_CODE,`Cannot verify generative page '${l}' before writing: ${n?"the server did not return the page's current token":"no baseline token was recorded"}. This entity accepts no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let p=new Map(c.map(({row:I})=>{var D,O;return[(0,he.normalizeGuid)(String((D=I[xt])!==null&&D!==void 0?D:""),xt),{filename:String((O=I.filename)!==null&&O!==void 0?O:""),filetype:Number(I.filetype)}]})),m=new Set(p.keys()),h=new Set(((o=u.files)!==null&&o!==void 0?o:[]).map(I=>(0,he.normalizeGuid)(I.id,"file id")));if(!i)throw new Qe.SdkError(Be.VERSION_CONFLICT_CODE,`Cannot verify the files of generative page '${l}' before writing: no child baseline was recorded. These rows accept no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let g=new Set(Object.keys(i).map(I=>I.toLowerCase()));for(let I of h)if(!m.has(I)&&g.has(I))throw new Qe.SdkError(Be.VERSION_CONFLICT_CODE,`Generative-page file '${I}' existed when this page was fetched but is gone from the server now \u2014 another writer deleted it. Refusing to recreate it, because a blind re-create would undo that delete. Re-fetch the page and re-apply the edit.`);for(let I of m)if(!g.has(I))throw new Qe.SdkError(Be.VERSION_CONFLICT_CODE,`Generative-page file '${I}' is on the server but absent from this page's baseline \u2014 another writer added it after the page was fetched, so its contents cannot be verified. Refusing to write over or delete it. Re-fetch the page so the addition is part of your baseline.`);let b=new Map(c.map(({row:I,etag:D})=>{var O;return[(0,he.normalizeGuid)(String((O=I[xt])!==null&&O!==void 0?O:""),xt),D]}));for(let[I,D]of Object.entries(i)){let O=I.toLowerCase();if(!m.has(O))continue;let $=b.get(O);if(!D||!$)throw new Qe.SdkError(Be.VERSION_CONFLICT_CODE,`Cannot verify generative-page file '${O}' before writing: ${D?"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(D!==$)throw new Qe.SdkError(Be.VERSION_CONFLICT_CODE,`Generative-page file '${O}' changed on the server after this page was fetched (baseline ${D}, server ${$}) \u2014 another writer edited it. A file row accepts no If-Match validator, so this push would silently overwrite that change. Re-fetch the page and re-apply the edit.`)}let w=Fx(l,u,{rows:p,name:String((a=d.name)!==null&&a!==void 0?a:"")});if(w.length===0)return{id:l,etag:f,memberEtags:Object.fromEntries(c.map(({row:I,etag:D})=>{var O;return[(0,he.normalizeGuid)(String((O=I[xt])!==null&&O!==void 0?O:""),xt),D]}))};let E=Gx(),A=[],L=!0;Mx(e,w)?await Ux(e,l,w,u,E):{warnings:A,turnRecorded:L}=await Bx(e,l,w,u,E);let R=await qx(e,l,w,u,h,b,A);return L?R:{...R,intentPending:!0}},async delete(e,t){var r;let n=(0,he.normalizeGuid)(t,"id"),i=await fv(e,n);await(0,Be.deleteRecord)(e,oi,n);let o=new Set(i.map(l=>{var u;return String((u=l[_a])!==null&&u!==void 0?u:"")}).filter(l=>l!=="")),a=!1;try{for(let l of await fv(e,n)){let u=String((r=l[_a])!==null&&r!==void 0?r:"");u!==""&&o.add(u)}}catch{a=!0}let s=[];for(let l of o)try{await(0,Be.deleteRecord)(e,ic,l)}catch(u){u instanceof Qe.ConnectionError&&u.statusCode===404||s.push(l)}if(s.length>0||a)throw new Qe.SdkError("GENPAGE_HISTORY_NOT_DELETED",`Generative page '${n}' was deleted, but its conversation history was not fully removed`+(s.length>0?` \u2014 ${s.length} of ${o.size} message(s) could not be (${s.join(", ")})`:"")+(a?" \u2014 and re-reading it after the delete failed, so a late turn may remain":"")+`. They no longer belong to any page; delete them as ${ic} rows regarding '${n}'.`)}};function Gx(){return`uxagentproject_${(0,Hx.newId)()}`}function Dne(e,t){var r;return t.length===0?e:{...e,warnings:[...(r=e.warnings)!==null&&r!==void 0?r:[],...t]}}function Wx(e,t,r){var n,i;if(((i=(n=r.messages)===null||n===void 0?void 0:n.length)!==null&&i!==void 0?i:0)>1&&!e.supportsAtomicBatch)throw new Qe.SdkError("GENPAGE_TURN_NOT_ATOMIC",`Refusing to write generative page '${t}': its new turn has a prompt AND a reply, which must be recorded together, and the injected HttpClient does not implement postRaw() \u2014 one request at a time, a failure between the two would leave half a turn. Implement postRaw(), or record the prompt alone (omit newTurn.agentMessage). Nothing was written.`)}function zx(e,t){var r,n;if(((r=t.files)!==null&&r!==void 0?r:[]).some(a=>a.content.status==="available"&&!a.unchanged)&&!e.supportsBinaryPatch&&!e.supportsAtomicBatch)throw new Qe.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: it has file content to upload, but the injected HttpClient implements neither patchRaw() nor postRaw(). A Dataverse File column is not writable through a JSON body, so proceeding would create the page and its rows and then fail, leaving a page whose source never uploaded.");if(((n=t.files)!==null&&n!==void 0?n:[]).some(a=>a.content.status==="available"&&!a.unchanged&&hv(a.content.data)===void 0)&&!e.supportsBinaryPatch)throw new Qe.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: a file's content is not UTF-8 text, which only the binary channel can carry, and the injected HttpClient does not implement patchRaw().")}});var m$=v(al=>{"use strict";Object.defineProperty(al,"__esModule",{value:!0});al.genPageRegistration=al.GenPageAdapter=void 0;var Ine=Qx(),One=Kr(),_e=Zr(),Dp=lt(),Ip=Td(),Da=Q(),l$=Cg(),gv=Gm(),Oo=2e8,u$=200000001,qi={source:{name:"src/pages/page.tsx",fileType:Oo},output:{name:"src/pages/page.compiled",fileType:u$},config:{name:"config.json",fileType:Oo},prompt:{name:"firstPrompt.json",fileType:Oo}},c$=Object.keys(qi),Pne=["dataSources","model","connectorBindings","actionBindings"],Rne=["userMessage","agentMessage"],Xx=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Lne={source:"6f1c2a4e9b3d47a1b85c0e2f7d914a63",output:"a8e53d17c2f64b09a1d7e4b8c3f2069d",config:"3b97f0c64e2a4d8f95b1c7a0e6d3f814",prompt:"d24e8b51f7a34c6e8b09d5f1a2c7e3b6"},kne="9c3e7a15d2b84f6e8a01c5d7b3f9e240";function d$(e,t){var r;let n=e.replace(/[{}-]/g,"").toLowerCase(),i=[];for(let a=0;a<32;a+=1)i.push(parseInt((r=n[a])!==null&&r!==void 0?r:"0",16)^parseInt(t[a],16));i[12]=4,i[16]=i[16]&3|8;let o=i.map(a=>(Number.isNaN(a)?0:a).toString(16)).join("");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}function Sp(e,t){return d$(e,Lne[t])}function xne(e,t){let r=d$(e,kne),n=parseInt(r.slice(24),16)%2**47+(t==="agent"?1:0);return`${r.slice(0,24)}${n.toString(16).padStart(12,"0")}`}function Zx(e){return typeof e=="string"&&e.trim()!==""?e:(0,Dp.newId)()}function Bi(e){return(0,_e.isJsonObject)(e)?e:{}}function ol(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function Np(e){return JSON.parse(JSON.stringify(e))}function $ne(e){let t=Bi(e);return t.status==="available"&&typeof t.data=="string"?{status:"available",data:t.data}:{status:"unavailable",reason:t.reason==="unpublished"?"unpublished":"missing"}}function lc(e){if(!e||e.status!=="available")return;let t=(0,Ip.base64ToUtf8)(e.data);return(0,Ip.utf8ToBase64)(t)===e.data?t:void 0}function f$(e,t,r){var n,i,o,a;return e.source!==void 0&&t!==void 0&&t?.source===e.source&&ol((n=t?.dataSources)!==null&&n!==void 0?n:[],(i=e.dataSources)!==null&&i!==void 0?i:[])&&((a=(o=e.bag)===null||o===void 0?void 0:o.rows)!==null&&a!==void 0?a:{}).output!==void 0&&(0,l$.isLoadableGenPageOutput)(r)}function Fne(e,t){var r;try{return f$(e,t,lc((r=e.bag)===null||r===void 0?void 0:r.output))}catch{return!1}}function _p(e){if(e!==void 0)try{let t=JSON.parse(e.replace(/^\uFEFF/,""));return(0,_e.isJsonObject)(t)?t:void 0}catch{return}}function e$(e,t){if(t===Oo&&e.includes("page.tsx"))return"source";if(t===u$&&e.includes(".compiled"))return"output";if(t===Oo&&e===qi.config.name)return"config";if(t===Oo&&e===qi.prompt.name)return"prompt"}function t$(e){let t=e.toLowerCase();return c$.some(r=>qi[r].name.toLowerCase()===t)}function yv(e){return Object.fromEntries(e)}function p$(e,t,r,n){let i=[],o=new Set,a=new Set(t),s=l=>{if(o.has(l))return;let u=a.has(l)?e[l]:r&&Object.prototype.hasOwnProperty.call(r,l)?r[l]:void 0;u!==void 0&&(o.add(l),i.push([l,u]))};return(n??[]).forEach(s),t.forEach(s),Object.keys(r??{}).forEach(s),yv(i)}function r$(e){var t,r,n;return p$({dataSources:(t=e.dataSources)!==null&&t!==void 0?t:[],model:e.model,connectorBindings:e.connectorBindings,actionBindings:e.actionBindings},Pne,(r=e.bag)===null||r===void 0?void 0:r.config,(n=e.bag)===null||n===void 0?void 0:n.configKeys)}function n$(e){var t,r;return p$({userMessage:e.firstPrompt,agentMessage:e.firstAgentMessage},Rne,(t=e.bag)===null||t===void 0?void 0:t.prompt,(r=e.bag)===null||r===void 0?void 0:r.promptKeys)}function i$(e,t,r){let n=[];for(let[i,o]of Object.entries(r))if(i==="dataSources"){if(!Array.isArray(o)||!o.every(a=>typeof a=="string"))return!1;e.dataSources=o}else if(i==="model"){if(typeof o!="string")return!1;e.model=o}else i==="connectorBindings"?e.connectorBindings=o:i==="actionBindings"?e.actionBindings=o:n.push([i,o]);return t.configKeys=Object.keys(r),n.length>0&&(t.config=yv(n)),!0}function o$(e,t,r){let n=[];for(let[i,o]of Object.entries(r))if(i==="userMessage"||i==="agentMessage"){if(typeof o!="string")return!1;i==="userMessage"?e.firstPrompt=o:e.firstAgentMessage=o}else n.push([i,o]);return t.promptKeys=Object.keys(r),n.length>0&&(t.prompt=yv(n)),!0}function uc(e){var t,r;return e.source!==void 0||Object.keys((r=(t=e.bag)===null||t===void 0?void 0:t.rows)!==null&&r!==void 0?r:{}).length>0}var Mne=["dataSources","model","connectorBindings","actionBindings","firstPrompt","firstAgentMessage"];function a$(e){return uc(e)?[]:Mne.filter(t=>e[t]!==void 0).map(t=>(0,_e.issue)(`/${t}`,"genpage-raw-structured-field",`${t} cannot be applied: this page is in raw-file mode \u2014 it has no source and no managed rows, so a push writes its files[] exactly as they are, and ${t} nowhere. Set source to make the page managed (the SDK then writes config.json and firstPrompt.json from the typed fields; a file in files[] holding one of those names must be removed first), or change the file that stores the value in files[] directly.`))}function s$(){return(0,_e.issue)("/source","genpage-source-required","the page's source cannot be removed: its source row still exists, and a page without one cannot run. Set a new source, or delete the page with deleteRemoteArtifact.")}function Tp(e){return{status:"available",data:(0,Ip.utf8ToBase64)(e)}}function sc(e,t){var r,n;return{id:String((r=e.uxagentprojectid)!==null&&r!==void 0?r:""),name:String((n=e.name)!==null&&n!==void 0?n:""),files:t}}var Op=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){let r=t,n=Bi(r?.project),i=(Array.isArray(r?.files)?r.files:[]).map(g=>{var b,w,E;let A=Bi(g);return{id:String((b=A.uxagentprojectfileid)!==null&&b!==void 0?b:""),name:String((w=A.filename)!==null&&w!==void 0?w:""),fileType:Number((E=A.filetype)!==null&&E!==void 0?E:Oo),content:$ne(A.content)}}),o=Array.isArray(r?.conversation)?r.conversation.map(g=>{var b,w;let E=Bi(g);return{sender:Number(E.messagesender)===200000001?"agent":"user",message:String((b=E.message)!==null&&b!==void 0?b:""),createdOn:String((w=E.createdon)!==null&&w!==void 0?w:"")}}):void 0,a=g=>o?{...g,conversation:o}:g,s=new Map,l=[],u=!0;for(let g of i){let b=e$(g.name,g.fileType);b?((s.has(b)||g.name!==qi[b].name)&&(u=!1),s.set(b,g)):(t$(g.name)&&(u=!1),l.push(g))}if(!u||s.size===0)return a(sc(n,i));let c=sc(n,l),d={rows:{}};for(let[g,b]of s)d.rows[g]=b.id;let f=s.get("source");if(f){let g=lc(f.content);if(g===void 0)return a(sc(n,i));c.source=g}let p=s.get("output");p&&(d.output=p.content);let m=s.get("config");if(m){let g=_p(lc(m.content));if(!g||!i$(c,d,g))return a(sc(n,i))}let h=s.get("prompt");if(h){let g=_p(lc(h.content));if(!g||!o$(c,d,g))return a(sc(n,i))}return c.bag=d,a(c)}async toApiPayload(t,r,n){var i,o,a,s,l,u,c,d,f,p,m,h,g;if(r&&!ol((i=t.conversation)!==null&&i!==void 0?i:[],(o=r.conversation)!==null&&o!==void 0?o:[]))throw new Da.ValidationError("genPage",t.id,[(0,_e.issue)("/conversation","genpage-conversation-read-only","conversation is the page's recorded history and cannot be edited. Record a new turn with newTurn; revert the edit to conversation before pushing.")]);let b=a$(t);if(b.length>0)throw new Da.ValidationError("genPage",t.id,b);let w=[],E=r===void 0,A=E&&t.firstPrompt===void 0&&t.newTurn?{...t,firstPrompt:t.newTurn.prompt,...t.newTurn.agentMessage!==void 0?{firstAgentMessage:t.newTurn.agentMessage}:{}}:t;if(uc(A)){let I=(s=(a=A.bag)===null||a===void 0?void 0:a.rows)!==null&&s!==void 0?s:{},D=Le=>{var at;return(at=I[Le])!==null&&at!==void 0?at:Sp(A.id,Le)},O=(Le,at,ge)=>{w.push({id:D(Le),name:qi[Le].name,fileType:qi[Le].fileType,content:at,unchanged:ge})};if(A.source!==void 0){O("source",Tp(A.source),!E&&r?.source===A.source&&I.source!==void 0);let Le=lc((l=A.bag)===null||l===void 0?void 0:l.output);f$(A,r,Le)?O("output",{status:"retain"},!0):O("output",Tp(await this.compile(A,A.source,n)),!1)}else{if(I.source!==void 0)throw new Da.ValidationError("genPage",A.id,[s$()]);if(I.output!==void 0){if(!E&&!ol((u=r?.dataSources)!==null&&u!==void 0?u:[],(c=A.dataSources)!==null&&c!==void 0?c:[]))throw new Da.ValidationError("genPage",A.id,[(0,_e.issue)("/dataSources","genpage-source-required","the page has no source row, so its output cannot be recompiled for new data sources; set a source to change them.")]);O("output",{status:"retain"},!0)}}let $=r$(A),K=!E&&r!==void 0&&ol(r$(r),$);(E||I.config!==void 0||!K)&&O("config",Tp(JSON.stringify($)),K&&I.config!==void 0);let Re=n$(A),It=!E&&r!==void 0&&ol(n$(r),Re);(I.prompt!==void 0||Object.keys(Re).length>0&&!It)&&O("prompt",Tp(JSON.stringify(Re)),It&&I.prompt!==void 0)}for(let I of(d=A.files)!==null&&d!==void 0?d:[]){let D=(f=r?.files)===null||f===void 0?void 0:f.find(O=>O.id===I.id);w.push({id:I.id,name:I.name,fileType:I.fileType,content:I.content,unchanged:D!==void 0&&ol(D,I)})}let L=[];if(A.newTurn){let I=A.newTurn.id,D=O=>I?{id:xne(I,O)}:{};L.push({...D("user"),sender:"user",message:A.newTurn.prompt}),A.newTurn.agentMessage&&L.push({...D("agent"),sender:"agent",message:A.newTurn.agentMessage})}let R=(m=(p=A.bag)===null||p===void 0?void 0:p.config)!==null&&m!==void 0?m:{};return{name:A.name,files:w,...L.length>0?{messages:L,messageContext:{dataSources:(h=A.dataSources)!==null&&h!==void 0?h:[],model:(g=A.model)!==null&&g!==void 0?g:"",enabledTools:Array.isArray(R.enabledTools)?R.enabledTools:[],configurableTools:Array.isArray(R.configurableTools)?R.configurableTools:[]}}:{}}}committed(t,r,n={intentPending:!1}){let i=this.serverState(t,r);return n.intentPending&&t.newTurn!==void 0?{artifact:{...i,newTurn:Np(t.newTurn)},baseline:i}:{artifact:i,baseline:i}}serverState(t,r){var n,i,o,a,s,l;if(!uc(t)&&!t.newTurn)return t;let u=Np(t);if(delete u.newTurn,!uc(t))return u;let c={...(n=u.bag)!==null&&n!==void 0?n:{},rows:{...(o=(i=u.bag)===null||i===void 0?void 0:i.rows)!==null&&o!==void 0?o:{}}};for(let d of(a=r.files)!==null&&a!==void 0?a:[]){let f=c$.find(m=>qi[m].name===d.name&&qi[m].fileType===d.fileType);if(!f||u.files.some(m=>m.id===d.id)||(c.rows[f]=d.id,d.content.status!=="available"))continue;let p=(0,Ip.base64ToUtf8)(d.content.data);f==="output"?c.output={status:"available",data:d.content.data}:f==="config"?(delete c.config,delete u.dataSources,delete u.model,delete u.connectorBindings,delete u.actionBindings,i$(u,c,(s=_p(p))!==null&&s!==void 0?s:{})):f==="prompt"&&(delete c.prompt,delete u.firstPrompt,delete u.firstAgentMessage,o$(u,c,(l=_p(p))!==null&&l!==void 0?l:{}))}return u.bag=c,u}baselineContent(t){var r;let n={...t};return delete n.conversation,delete n.newTurn,n.files=[...(r=t.files)!==null&&r!==void 0?r:[]].sort((i,o)=>i.id<o.id?-1:i.id>o.id?1:0),n}normalize(t){let r=t.newTurn;return!(0,_e.isJsonObject)(r)||typeof r.id=="string"&&Xx.test(r.id)?t:{...t,newTurn:{...r,id:(0,Dp.newId)()}}}async compile(t,r,n){var i;let o=(i=t.dataSources)!==null&&i!==void 0?i:[],a=[],s=[];if(o.forEach((f,p)=>{var m;let h=(m=n?.resolveEntity)===null||m===void 0?void 0:m.call(n,f);h&&h.columnDetailComplete===!0?a.push(h):s.push((0,_e.issue)(`/dataSources/${p}`,h?"genpage-data-source-incomplete":"genpage-data-source-unresolved",h?`the column metadata of data source '${f}' could not be read completely (a choice or lookup read failed, or returned options with no label), so the page cannot be compiled with its enums. Retry the push.`:`the metadata of data source '${f}' could not be read, so the page cannot be compiled with its enums. Check the table's logical name and that it exists in this environment.`))}),s.length>0)throw new Da.ValidationError("genPage",t.id,s);if(!n?.loadTypeScript)throw new Da.ValidationError("genPage",t.id,[(0,_e.issue)("/source","genpage-compiler-unavailable","no TypeScript compiler is available to compile the page")]);let l=await n.loadTypeScript(),u=a.length>0?(0,gv.buildGenPageRuntimeTypes)(a):void 0,c=a.length>0?(0,gv.buildGenPageLegacyEnums)(a):void 0,d=(0,l$.compileGenPage)(l,r,u,c);if(d.diagnostics.length>0)throw new Da.ValidationError("genPage",t.id,d.diagnostics.map(Une));return d.code}metadataNeeds(t,r){if(t.source===void 0||!Array.isArray(t.dataSources))return[];let n=Fne(t,r)?{fetchRequired:!1}:{};return t.dataSources.filter(i=>typeof i=="string"&&i!=="").map(i=>({entityLogicalName:i,fieldName:"",needsColumnDetail:!0,...n}))}createDefault(t){var r,n;let i=Zx(t.id),o={id:i,name:(r=t.name)!==null&&r!==void 0?r:"New page",files:((n=t.files)!==null&&n!==void 0?n:[]).map(a=>{var s,l,u;return{id:Zx(a.id),name:(s=a.name)!==null&&s!==void 0?s:"index.tsx",fileType:(l=a.fileType)!==null&&l!==void 0?l:Oo,content:(u=a.content)!==null&&u!==void 0?u:{status:"available",data:""}}})};t.source!==void 0&&(o.source=t.source),t.dataSources!==void 0&&(o.dataSources=[...t.dataSources]);for(let a of["model","firstPrompt","firstAgentMessage"])t[a]!==void 0&&(o[a]=t[a]);return t.newTurn!==void 0&&(o.newTurn={...t.newTurn}),t.connectorBindings!==void 0&&(o.connectorBindings=Np(t.connectorBindings)),t.actionBindings!==void 0&&(o.actionBindings=Np(t.actionBindings)),o.source!==void 0&&(o.bag={rows:{source:Sp(i,"source"),output:Sp(i,"output"),config:Sp(i,"config")}}),o}assignMissingIds(t){if(t==null)return{id:(0,Dp.newId)()};if(!(0,_e.isJsonObject)(t))return t;let r=t;return(Object.keys(r).length===0||"id"in r||"content"in r||"fileType"in r||Array.isArray(r.files))&&(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,Dp.newId)()),r}validate(t){let r=[],n=t;for(let s of["source","model","firstPrompt","firstAgentMessage"])n[s]!==void 0&&typeof n[s]!="string"&&r.push((0,_e.issue)(`/${s}`,"genpage-field-type",`${s} must be a string, got ${typeof n[s]}`));if(n.source===void 0&&Bi(Bi(n.bag).rows).source!==void 0&&r.push(s$()),r.push(...a$(t)),n.newTurn!==void 0){let s=Bi(n.newTurn);(!(0,_e.isJsonObject)(n.newTurn)||typeof s.prompt!="string"||s.prompt.trim()==="")&&r.push((0,_e.issue)("/newTurn/prompt","genpage-turn-prompt","newTurn needs a non-empty prompt")),s.agentMessage!==void 0&&typeof s.agentMessage!="string"&&r.push((0,_e.issue)("/newTurn/agentMessage","genpage-field-type","newTurn.agentMessage must be a string")),s.id!==void 0&&(typeof s.id!="string"||!Xx.test(s.id))&&r.push((0,_e.issue)("/newTurn/id","genpage-turn-id","newTurn.id is the turn's identity, which the SDK mints \u2014 remove it, or keep the GUID it minted"))}if(n.dataSources!==void 0)if(!Array.isArray(n.dataSources))r.push((0,_e.issue)("/dataSources","genpage-data-sources-array","dataSources must be an array of table logical names"));else{let s=new Set;n.dataSources.forEach((l,u)=>{typeof l!="string"||!gv.TABLE_LOGICAL_NAME.test(l)?r.push((0,_e.issue)(`/dataSources/${u}`,"genpage-data-source-name",`a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(l)}'`)):s.has(l)?r.push((0,_e.issue)(`/dataSources/${u}`,"genpage-data-source-duplicate",`data source '${l}' is listed twice`)):s.add(l)})}n.conversation!==void 0&&!Array.isArray(n.conversation)&&r.push((0,_e.issue)("/conversation","genpage-conversation-array","conversation must be an array"));let i=n.files;if(i!==void 0&&!Array.isArray(i))return r.push((0,_e.issue)("/files","files-must-be-array",`files must be an array, got ${typeof i}`)),r;let o=uc(t),a=new Map;return(Array.isArray(i)?i:[]).forEach((s,l)=>{let u=`/files/${l}`,c=Bi(s),d=typeof c.id=="string"?c.id.trim().toLowerCase():"";if(d==="")r.push((0,_e.issue)(u,"file-id-required","a generative-page file needs an id"));else{let g=a.get(d);g!==void 0?r.push((0,_e.issue)(u,"file-id-duplicate",`two files share the id '${c.id}' (also at /files/${g}); a file's id is its identity, so a duplicate makes an edit ambiguous`)):a.set(d,l)}let f=typeof c.name=="string"?c.name:"",p=f.split("/");f===""||/[\u0000-\u001F\u007F]/.test(f)||f.includes("\\")||p.some(g=>g===""||g==="."||g==="..")?r.push((0,_e.issue)(u+"/name","file-name-invalid",`a file name must be a relative path of non-empty '/'-separated segments (no '.', '..', backslash or control character \u2014 its last segment is sent as an HTTP header); got '${f}'`)):o&&(t$(f)||e$(f,Number(c.fileType))!==void 0)&&r.push((0,_e.issue)(u+"/name","file-name-reserved",`'${f}' would be read by the maker portal as one of the page's managed rows (its source, output, config or first prompt), which the SDK writes from source and the configuration fields; it cannot also be a file in files[]`));let m=c.content;if(m===void 0){r.push((0,_e.issue)(u+"/content","file-content-required","content is required: omitting it is indistinguishable from an empty file, and the two have opposite effects on the next push"));return}let h=Bi(m);h.status==="available"?typeof h.data!="string"&&r.push((0,_e.issue)(u+"/content/data","file-content-data-invalid","available content needs base64 `data`")):h.status!=="unavailable"&&r.push((0,_e.issue)(u+"/content/status","file-content-status-invalid",`content.status must be 'available' or 'unavailable', got ${String(h.status)}`))}),r}};al.GenPageAdapter=Op;function Une(e){let t=`line ${e.line}, column ${e.column}`;return e.rule==="genpage-source-syntax"?(0,_e.issue)("/source",e.rule,`${t}: ${e.message} (TS${e.code}) \u2014 the page cannot run, so it was not pushed`):(0,_e.issue)("/source",e.rule,`${t}: ${e.message}`)}function Bne(){return{adapter:new Op,api:Ine.genPageApi,publish:(e,t)=>(0,One.publishGenPageById)(e,t),publishScope:e=>({envelope:"uxagentproject",targetIds:[e]}),rebaselineAfterPublish:"snapshot"}}al.genPageRegistration=Bne});var g$=v(Lp=>{"use strict";Object.defineProperty(Lp,"__esModule",{value:!0});Lp.reconcileBpfSecurityRoles=void 0;var Rp=ye(),Pp=ue(),qne="Global",h$={create:"Create",read:"Read",write:"Write",delete:"Delete"};async function Vne(e,t){var r,n;let i=`/EntityDefinitions(LogicalName='${(0,Pp.odataPathLiteral)(t)}')?$select=LogicalName,Privileges`,a=(n=(r=(0,Rp.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(h$).forEach(u=>{let c=a.find(d=>d.PrivilegeType===h$[u]);if(c){let d=(0,Pp.normalizeGuid)(c.PrivilegeId,"PrivilegeId");s[u]=d,l.add(d)}}),{byAccess:s,all:l}}async function Gne(e,t){var r,n;let i=`/RetrieveRolePrivilegesRole(RoleId=${t})`,a=(n=(r=(0,Rp.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.RolePrivileges)!==null&&n!==void 0?n:[];return new Set(a.map(s=>(0,Pp.normalizeGuid)(s.PrivilegeId,"PrivilegeId")))}async function Wne(e,t,r){if(r.length===0)return;let n={Privileges:r.map(o=>({Depth:qne,PrivilegeId:o}))},i=`/roles(${t})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;(0,Rp.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function zne(e,t,r){let n={Privilege:{"@odata.type":"Microsoft.Dynamics.CRM.privilege",privilegeid:r}},i=`/roles(${t})/Microsoft.Dynamics.CRM.RemovePrivilegeRole`;(0,Rp.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function jne(e,t,r){var n;if(!r||r.length===0)return;let i=await Vne(e,t.toLowerCase());for(let o of r){let a=(0,Pp.normalizeGuid)(o.roleId,"roleId"),s=new Set(((n=o.access)!==null&&n!==void 0?n:[]).map(f=>i.byAccess[f]).filter(f=>!!f)),l=await Gne(e,a),u=new Set([...l].filter(f=>i.all.has(f))),c=[...s].filter(f=>!u.has(f)),d=[...u].filter(f=>!s.has(f));await Wne(e,a,c);for(let f of d)await zne(e,a,f)}}Lp.reconcileBpfSecurityRoles=jne});var I$=v(xp=>{"use strict";Object.defineProperty(xp,"__esModule",{value:!0});xp.bpfApi=void 0;var lr=Ji(),y$=Wl(),Hne=Xt(),He=Q(),ot=ye(),pn=ue(),Kne=g$(),Jne=Cm(),cc=Am(),Yne={"Content-Type":"application/json",Accept:"application/json"},vv={...Yne,Prefer:"return=representation"},Qne=`category eq ${lr.WorkflowCategory.BusinessProcessFlow} and type eq ${lr.WorkflowTypeCode.Definition} and businessprocesstype eq ${lr.BusinessProcessType.BusinessFlow}`,Xne="workflowid,name,description,primaryentity,statecode,category,type,businessprocesstype,processorder",Zne="workflowid,name,uniquename,description,primaryentity,statecode,statuscode,category,type,businessprocesstype,processorder,xaml,clientdata",eie=["xaml","name","description","processorder"];async function bv(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,Kne.reconcileBpfSecurityRoles)(e,n,t.securityRoles)}async function Cv(e,t,r){let n={statecode:lr.StateCode.Activated,statuscode:lr.StatusCode.Activated},i=`/workflows(${t})`,{response:o,resent:a}=await D$(e,i,n,r,null);try{return(0,ot.ensureSuccess)(o,e.apiUrl(i))}catch(s){throw a?_$(s):s}}var N$=new WeakSet;function _$(e){return typeof e=="object"&&e!==null&&N$.add(e),e}function T$(e){return typeof e=="object"&&e!==null&&N$.has(e)}function b$(e){return e instanceof He.ConnectionError&&(e.statusCode===0||ot.AMBIGUOUS_WRITE_STATUSES.has(e.statusCode))}async function D$(e,t,r,n,i){let o=n??i,a=0;try{return{response:await(0,ot.resendWhile)(ot.isConcurrencyLockRefusal,()=>{a+=1;let l=a===1?n:o,u={...vv};return l&&(u["If-Match"]=l),e.patch(t,r,{headers:u})},o?ot.LOCK_BACKOFF_MS:[]),resent:a>1}}catch(s){throw a>1?_$(s):s}}async function v$(e,t,r){return(0,ot.readEtag)(await Cv(e,t,r))}function w$(e,t){return new He.SdkError("BPF_WRITE_NOT_ECHOED",`The ${t} of business process flow '${e}' was applied, but the server returned no concurrency token for it (this environment did not honour 'Prefer: return=representation'), so the next step could not be conditioned on a token this push produced and was NOT sent. `+kp(e))}async function dc(e,t){var r;let n=`/workflows(${t})${(0,pn.odataQuery)([["$select","statecode"]])}`,i=(0,ot.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.statecode,a=Number(o);if(o==null||o===""||!Number.isFinite(a))throw new He.SdkError("BPF_STATE_UNREADABLE",`Reading the state of business process flow '${t}' answered HTTP ${i.status} without a usable statecode, so whether it is Active cannot be decided.`);return a}async function wv(e,t,r,n,i=null){if((n??await dc(e,t))!==lr.StateCode.Activated)return{deactivated:!1,etag:null};let o={statecode:lr.StateCode.Draft,statuscode:lr.StatusCode.Draft},a=`/workflows(${t})`,s,l;try{({response:s,resent:l}=await D$(e,a,o,r,i))}catch(c){return await C$(e,t,c,T$(c))}if(ot.AMBIGUOUS_WRITE_STATUSES.has(s.status))return await C$(e,t,new He.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",`Deactivating business process flow '${t}' answered HTTP ${s.status} from an intermediary, so whether it committed is unknown.`),l);let u=(0,ot.ensureSuccess)(s,e.apiUrl(a));return{deactivated:!0,etag:(0,ot.readEtag)(u)}}async function C$(e,t,r,n){let i;try{i=await dc(e,t)}catch{i=void 0}if(i===lr.StateCode.Draft&&!n)return{deactivated:!0,etag:null,uncertainCause:r};if(i===lr.StateCode.Activated)throw r;let o=new He.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",i===lr.StateCode.Draft?`Deactivating business process flow '${t}' waited for the platform's concurrency lock, and its last attempt ended without a definitive answer. The process now reads Draft, but whether this deactivate or another writer's change put it there is unknown \u2014 the row may even have been replaced at the same id \u2014 so nothing more was sent: no edit, no re-activation, no delete. It MAY be left DISABLED: read it before retrying. Original failure: ${r instanceof Error?r.message:String(r)}`:`Deactivating business process flow '${t}' did not complete, and its state could not be re-read \u2014 it MAY be left DISABLED and needs reconciling. Original failure: ${r instanceof Error?r.message:String(r)}`);throw(0,He.attachCause)(o,r),o}async function tie(e,t){let r=(0,pn.normalizeGuid)(t,"workflowid");try{return await Cv(e,r,null),"restored"}catch{return Ev(e,r)}}async function rie(e,t,r){let n=(0,pn.normalizeGuid)(t,"workflowid");try{return await Cv(e,n,r),"restored"}catch(i){return i instanceof He.SdkError&&i.code===ot.VERSION_CONFLICT_CODE?"changed":Ev(e,n)}}async function Ev(e,t){try{let r=await dc(e,t);return r===lr.StateCode.Activated?"restored":r===lr.StateCode.Draft?"disabled":"unknown"}catch{return"unknown"}}async function E$(e,t,r,n){return r?{outcome:await rie(e,t,r),attempted:!0}:n?{outcome:await Ev(e,(0,pn.normalizeGuid)(t,"workflowid")),attempted:!1}:{outcome:await tie(e,t),attempted:!0}}function nie(e,t){let r=new He.SdkError(cc.WORKFLOW_DELETE_UNSETTLED_CODE,`Deleting business process flow '${e}' failed${(0,cc.failedAfterResend)(t)?" after it was re-sent":""}, and re-activating the process this delete had deactivated was refused (HTTP 412): the row at that id is no longer the version this delete deactivated \u2014 it was edited, or deleted and re-created at the same id \u2014 so it was NOT re-activated, and it MAY be left DISABLED. Read the row before deleting it again. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,He.attachCause)(r,t),r}function A$(e,t,r,n,i=!0){let o=`Original failure: ${n instanceof Error?n.message:String(n)}`,a="it was NOT re-activated: it waited for the platform's concurrency lock, and no write of this operation proves the row is still its own, so a re-activation could have enabled another writer's edit",s;return r==="changed"?s=new He.SdkError("BPF_REACTIVATE_OUTCOME_UNKNOWN",`Business process flow '${e}' was deactivated ${t}, and re-activating it was refused (HTTP 412): the row is no longer the version this operation last wrote \u2014 another writer changed it, or replaced it at the same id \u2014 so it was NOT re-activated, and it MAY be left DISABLED. Read it before retrying. ${o}`):r==="disabled"?s=new He.SdkError("BPF_LEFT_DEACTIVATED",i?`Business process flow '${e}' was deactivated ${t}, and it could NOT be reactivated \u2014 it is left DISABLED. ${o}`:`Business process flow '${e}' was deactivated ${t}, and ${a} \u2014 it is left DISABLED. ${o}`):s=new He.SdkError("BPF_REACTIVATE_OUTCOME_UNKNOWN",i?`Business process flow '${e}' was deactivated ${t}, and whether it was reactivated could not be confirmed \u2014 it MAY be left DISABLED and needs checking. ${o}`:`Business process flow '${e}' was deactivated ${t}, and ${a}; its state could not be read \u2014 it MAY be left DISABLED and needs checking. ${o}`),(0,He.attachCause)(s,n),s}async function iie(e,t){try{return await dc(e,t),"survived"}catch(r){return r instanceof He.ConnectionError&&r.statusCode===404?"removed":"unknown"}}async function oie(e,t,r){if(r)try{let{deactivated:n,etag:i}=await wv(e,t,r),o=n?i:r;if(o)return await(0,cc.deleteWorkflowResending)(e,t,{bindingToken:o,kindName:"business process flow",resendDeadlockVictim:!0,ifMatchOnFirst:!0}),"removed"}catch{}return iie(e,t)}function kp(e){return`Adopt the server's copy with fetchArtifact('bpf', '${e}', { overwrite: true }) \u2014 it REPLACES the local copy, so keep any outstanding local changes aside first \u2014 then re-apply them and push.`}function S$(e,t){return new He.SdkError("BPF_CREATE_NO_TOKEN",`Created business process flow '${e}' but the server returned no concurrency token for it (this environment did not honour 'Prefer: return=representation'), so the next push would have nothing to condition on. ${t} It was NOT rolled back: deleting it without a token could remove an edit made since. ${kp(e)}`)}function aie(e,t){let r=new He.SdkError("BPF_CREATE_NOT_ROLLED_BACK",`Creating business process flow '${e}' failed part-way, and the rollback could NOT remove it \u2014 it still EXISTS, possibly Active and half-configured. (The rollback deletes only on a token this create produced, so a row somebody has since edited is left in place on purpose; a delete the platform refused or failed leaves it too.) ${kp(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,He.attachCause)(r,t),r}function sie(e,t){let r=new He.SdkError("BPF_CREATE_ROLLBACK_OUTCOME_UNKNOWN",`Creating business process flow '${e}' failed part-way, and whether its rollback removed the process could not be confirmed \u2014 it MAY still exist, possibly Active and half-configured. ${kp(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,He.attachCause)(r,t),r}function lie(e,t){let r=new He.SdkError("BPF_CREATE_REMOVED_AFTER_CONFLICT",`Creating business process flow '${e}' was interrupted: another writer changed it right after it was created, so this push's next step was refused rather than overwrite or activate their edit \u2014 and the process has since been removed. Nothing is left behind and there is nothing to fetch. If the removal was deliberate, stop here; otherwise push again to re-create it at the same id. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,He.attachCause)(r,t),r}function Av(e){let t={};for(let r of eie)e[r]!==void 0&&(t[r]=e[r]);return t}var uie=["name,processorder","description,name,processorder"];function cie(e){let{xaml:t,...r}=Av(e);return typeof t=="string"&&uie.includes(Object.keys(r).sort().join(","))}async function die(e,t,r,n){let{xaml:i,...o}=Av(r),[,a]=await(0,y$.sendChangeSet)(e,[{method:"PATCH",path:`/workflows(${t})`,body:o,etag:n},{method:"PATCH",path:`/workflows(${t})${(0,pn.odataQuery)([["$select","workflowid"]])}`,body:{xaml:i},headers:{Prefer:"return=representation"}}],`business process flow '${t}'`);return(0,ot.readEtag)((0,y$.partResponse)(a))}xp.bpfApi={async get(e,t){let n=`/workflows(${(0,pn.normalizeGuid)(t,"id")})${(0,pn.odataQuery)([["$select",Zne]])}`,i=(0,ot.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,ot.readEtag)(i)}},async list(e,t){let r=[Qne];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,pn.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,pn.odataQuery)([["$select",Xne],["$filter",r.join(" and ")]])}`;return(await(0,Hne.collectPages)(e,n,"listArtifacts('bpf')")).map(o=>{var a,s;return{type:"bpf",id:(a=o.workflowid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",entityLogicalName:o.primaryentity,isDirty:!1}})},async create(e,t){let r=t,n=(0,pn.normalizeGuid)(r.record.workflowid,"workflowid"),i="/workflows",o=(0,ot.ensureSuccess)(await e.post(i,r.record,{headers:vv}),e.apiUrl(i)),a=(0,ot.readEtag)(o);if(!a)throw S$(n,r.status==="Active"?"The process EXISTS as Draft and was NOT activated \u2014 an activation that cannot be conditioned on our own write could activate somebody else's edit.":"The process EXISTS as Draft.");let s=a;try{r.status==="Active"&&(s=await v$(e,n,a)),await bv(e,r)}catch(l){let u=await oie(e,n,s);throw u==="survived"?aie(n,l):u==="unknown"?sie(n,l):l instanceof He.SdkError&&l.code===ot.VERSION_CONFLICT_CODE?lie(n,l):l}if(!s)throw S$(n,"The process EXISTS and IS Active, but its activation returned no token.");return{id:n,etag:s}},async update(e,t,r,n){let i=r,o=(0,pn.normalizeGuid)(t,"id"),a=(0,ot.requireEtag)(n,"bpf",o),s=await dc(e,o);if(s===lr.StateCode.Activated&&i.status==="Active"&&e.supportsAtomicBatch&&cie(i.record)){let p=await die(e,o,i.record,a);return await bv(e,i),{id:o,etag:p}}let{deactivated:l,etag:u,uncertainCause:c}=await wv(e,o,a,s),d=u,f=!1;try{if(c!==void 0)throw c;let p=a;if(l){if(!u)throw w$(o,"deactivation");p=u}let m=`/workflows(${o})`,h;try{h=(0,ot.ensureSuccess)(await e.patch(m,Av(i.record),{headers:{...vv,"If-Match":p}}),e.apiUrl(m))}catch(b){throw b$(b)&&(d=null),b}let g=(0,ot.readEtag)(h);if(d=g,i.status==="Active"){if(!g)throw w$(o,"definition write");try{g=await v$(e,o,g)}catch(b){throw b$(b)&&(d=null),b}f=!0}return await bv(e,i),{id:o,etag:g}}catch(p){if(l&&!f){let{outcome:m,attempted:h}=await E$(e,o,d,T$(p));if(m!=="restored")throw A$(o,"to apply an edit, the edit failed",m,p,h)}throw p}},async delete(e,t){let r=(0,pn.normalizeGuid)(t,"id"),n=await(0,Jne.assertWorkflowKind)(e,r,lr.WorkflowCategory.BusinessProcessFlow),{deactivated:i,etag:o}=await wv(e,r,null,void 0,n);try{await(0,cc.deleteWorkflowResending)(e,r,{bindingToken:i?o:n,kindName:"business process flow",deactivated:i,resendDeadlockVictim:!0})}catch(a){if(i&&!(0,cc.isWorkflowDeleteUnsettled)(a)){let{outcome:s,attempted:l}=await E$(e,r,o,!1);if(s==="changed")throw nie(r,a);if(s!=="restored")throw A$(r,"so it could be deleted, the delete failed",s,a,l)}throw a}}}});var fF=v(ll=>{"use strict";Object.defineProperty(ll,"__esModule",{value:!0});ll.bpfRegistration=ll.BpfAdapter=void 0;var $p=Ji(),fie=I$(),Sv=ao(),Ia=lo(),V$=so(),Gr=Zr(),Rr=lt(),ai=Q(),pie=100,_v='<?xml version="1.0" encoding="utf-16"?>',O$=1033,G$="mxswa:Workflow",mie="mxswa:ActivityReference.Properties",hie="mcwo:StepLabel",gie="mcwb:Control",P$="mcwb:Control.ControlDisplayName",W$="mcwb:Control.DataFieldName",z$="DataFieldName",R$="ControlDisplayName",j$="Literal",Fp="x:Null",L$="x:String",Tv="x:Key",Dv="DisplayName",Up="Activities",yie="StepLabels",H$="StageId",K$="StageCategory",J$="NextStageId",Y$="ProcessStepId",Iv="IsProcessRequired",Q$="EntityComposite",X$="StageComposite",Z$="StepComposite";function Nv(e){return(0,Gr.isJsonObject)(e)?e:{}}function si(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 Oa(e,t){var r;return(r=si(e).find(n=>n.tagName===t))!==null&&r!==void 0?r:null}function li(e){return Oa(e,mie)}function ur(e,t){var r;return(r=si(e).find(n=>n.getAttribute(Tv)===t))!==null&&r!==void 0?r:null}function sl(e,t){var r;return((r=e.getAttribute("AssemblyQualifiedName"))!==null&&r!==void 0?r:"").includes(t)}function Gi(e){var t;return!e||!e.firstChild?"":(t=e.firstChild.nodeValue)!==null&&t!==void 0?t:""}function eF(e,t,r){e.firstChild?e.firstChild.nodeValue=r:e.appendChild(t.createTextNode(r))}function fc(e){var t;let r=(t=e.getAttribute(Dv))!==null&&t!==void 0?t:"",n=r.indexOf(": ");return n>=0?r.slice(n+2):r}function tF(e,t){var r;let n=(r=e.getAttribute(Dv))!==null&&r!==void 0?r:"",i=n.indexOf(": ");e.setAttribute(Dv,i>=0?n.slice(0,i+2)+t:t)}function rF(e,t){let r=ur(e,yie),n=Oa(r,hie);n&&n.setAttribute("Description",t)}function bie(e){let t=ur(e,K$);if(!t||t.tagName===Fp)return;let r=Gi(t).trim();return r===""?void 0:Number(r)}function vie(e){let t=ur(e,J$);if(!t||t.tagName===Fp)return;let r=Gi(t).trim();return r===""?void 0:r}function nF(e){let t=iF(e);if(!t)return;let r=aF(t,z$,W$);return r===""?void 0:r}function Ov(e,t){let r=si(e);for(;r.length>0;){let n=r.pop();if(n.tagName===t)return n;for(let i of si(n))r.push(i)}return null}function iF(e){let t=ur(li(e),Up);return t?Ov(t,gie):null}function oF(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 aF(e,t,r){var n;return oF(e,t)?(n=e.getAttribute(t))!==null&&n!==void 0?n:"":Sie(e,r)}function k$(e,t,r,n){if(oF(e,t)){e.setAttribute(t,n);return}if(Oa(e,r)){wie(e,r,n);return}throw new ai.InvalidArgumentError(`BPF step control exposes neither a '${t}' attribute nor a <${r}> wrapper to bind a column`)}function wie(e,t,r){let n=Oa(e,t),i=n?Ov(n,j$):null;i&&i.setAttribute("Value",r)}function sF(e){return fc(e)}function Bp(e){let t=Oa(e,G$),r=[];for(let n of si(t).filter(i=>sl(i,Q$))){let i=ur(li(n),Up);for(let o of si(i).filter(a=>sl(a,X$)))r.push({el:o,entity:sF(n)})}return r}function Pv(e){let t=ur(li(e),Up);return si(t).filter(r=>sl(r,Z$))}function Cie(e){let t=li(e),r=Gi(ur(t,Iv)).trim().toLowerCase(),n=nF(e),i={id:Gi(ur(t,Y$)),name:fc(e)};return n!==void 0&&(i.fieldName=n),r==="true"&&(i.required=!0),i}function Eie(e,t){let r=li(e),n=bie(r),i=vie(r),o={id:Gi(ur(r,H$)),name:fc(e),entityLogicalName:t,steps:Pv(e).map(Cie)};return n!==void 0&&(o.category=n),i!==void 0&&(o.nextStageId=i),o}function Aie(e){return Bp(e).map(({el:t,entity:r})=>Eie(t,r))}function Vi(e){return new ai.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 Sie(e,t){var r;let n=Oa(e,t),i=n?Ov(n,j$):null;return(r=i?.getAttribute("Value"))!==null&&r!==void 0?r:""}function Rv(e,t){var r;let n=e.createElement(t.tagName),i=t.attributes;for(let a=0;a<i.length;a+=1)n.setAttribute(i[a].name,i[a].value);let o=t.childNodes;for(let a=0;a<o.length;a+=1){let s=o[a];s.nodeType===1?n.appendChild(Rv(e,s)):s.nodeType===3&&n.appendChild(e.createTextNode((r=s.nodeValue)!==null&&r!==void 0?r:""))}return n}function lF(e){return ur(li(e),Up)}function Nie(e,t,r){var n;let i=t.entityLogicalName&&t.entityLogicalName.trim()!==""?t.entityLogicalName:r,o=!((n=t.steps[0])===null||n===void 0)&&n.id&&t.steps[0].id.trim()!==""?t.steps[0].id:(0,Rr.newId)(),{body:a}=qp(Lv(i,(0,Rr.newId)(),t.id,o));return Rv(e,Bp((0,Ia.parseXmlRoot)(a,"<Activity/>"))[0].el)}function _ie(e,t){let{body:r}=qp(Lv("account",(0,Rr.newId)(),(0,Rr.newId)(),t.id));return Rv(e,Pv(Bp((0,Ia.parseXmlRoot)(r,"<Activity/>"))[0].el)[0])}function uF(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);for(let r of t)e.appendChild(r)}function cF(e,t,r,n){let i=ur(e,r);if(!i||!i.parentNode){if(n!==void 0&&n!=="")throw Vi(`setting '${r}' on a stage whose xaml does not expose that slot`);return}let o=i.parentNode;if(n===void 0||n===""){if(i.tagName!==Fp){let s=t.createElement(Fp);s.setAttribute(Tv,r),o.replaceChild(s,i)}return}if(i.tagName===L$){Gi(i)!==n&&eF(i,t,n);return}let a=t.createElement(L$);a.setAttribute(Tv,r),a.appendChild(t.createTextNode(n)),o.replaceChild(a,i)}function Tie(e,t,r){cF(e,t,K$,r===void 0?void 0:String(r))}function Die(e,t,r){cF(e,t,J$,r)}function dF(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 x$(e){return Gi(ur(li(e),H$))}function $$(e){return Gi(ur(li(e),Y$))}function F$(e,t,r){var n,i,o,a;let s=li(e);r.name!==fc(e)&&(tF(e,r.name),rF(s,r.name));let l=Gi(ur(s,Iv)).trim().toLowerCase()==="true";if(((n=r.required)!==null&&n!==void 0?n:!1)!==l){let u=ur(s,Iv);u&&eF(u,t,r.required?"True":"False")}if(((i=r.fieldName)!==null&&i!==void 0?i:"")!==((o=nF(e))!==null&&o!==void 0?o:"")){let u=iF(e);if(!u)throw new ai.InvalidArgumentError("BPF step has no <mcwb:Control> element to bind a column to");let c=(a=r.fieldName)!==null&&a!==void 0?a:"";k$(u,z$,W$,c),c!==""&&aF(u,R$,P$)===""&&k$(u,R$,P$,c)}}function M$(e,t,r,n){var i;let o=li(e);if(!o)throw new ai.InvalidArgumentError("BPF stage composite has no <\u2026ActivityReference.Properties>");if(r.name!==fc(e)&&(tF(e,r.name),rF(o,r.name)),Tie(o,t,r.category),Die(o,t,n),r.relationshipName&&r.relationshipName.trim()!=="")throw Vi("a stage relationship / table change (multi-table authoring)");if(r.actions&&r.actions.length>0||r.branch)throw Vi("stage actions or conditional branching");let a=lF(e);if(!a)throw new ai.InvalidArgumentError("BPF stage has no [Activities] collection");let s=(i=r.steps)!==null&&i!==void 0?i:[];if(s.length===0)throw new ai.InvalidArgumentError(`BPF stage '${r.name}' must have at least one step`);let l=Pv(e);if(dF(l,s.map(d=>d.id),$$)){l.forEach((d,f)=>F$(d,t,s[f]));return}let u=new Map(l.map(d=>[$$(d),d]));if(si(a).some(d=>!sl(d,Z$)))throw Vi("adding, removing or reordering steps on a stage that also contains branching or actions");let c=s.map(d=>{var f;return(f=u.get(d.id))!==null&&f!==void 0?f:_ie(t,d)});uF(a,c),c.forEach((d,f)=>F$(d,t,s[f]))}function Iie(e,t,r){let n=Oa(e,G$);if(!n)throw new ai.InvalidArgumentError("BPF xaml has no <mxswa:Workflow> root activity");if(r.globalActions&&r.globalActions.length>0)throw Vi("global (process-completed/abandoned) actions");if(!r.stages||r.stages.length===0)throw new ai.InvalidArgumentError("a BPF must have at least one stage");let i=Bp(e),o=i.map(f=>f.el);if(dF(o,r.stages.map(f=>f.id),x$)){i.forEach(({el:f,entity:p},m)=>{let h=r.stages[m];if(h.entityLogicalName&&h.entityLogicalName.trim()!==""&&h.entityLogicalName!==p)throw Vi(`changing a stage's table ('${h.entityLogicalName}' vs the process's '${p}')`);M$(f,t,h,h.nextStageId)});return}let a=si(n).filter(f=>sl(f,Q$));if(a.length!==1)throw Vi("adding, removing or reordering stages on a multi-table process");let s=a[0],l=sF(s),u=lF(s);if(!u)throw new ai.InvalidArgumentError("BPF primary entity composite has no [Activities] collection");if(si(u).some(f=>!sl(f,X$)))throw Vi("adding, removing or reordering stages on a process whose primary composite holds non-stage activities (multi-table nesting or advanced constructs)");for(let f of r.stages)if(f.entityLogicalName&&f.entityLogicalName.trim()!==""&&f.entityLogicalName!==l)throw Vi(`a stage on a different table ('${f.entityLogicalName}') than the process primary ('${l}')`);let c=new Map(o.map(f=>[x$(f),f])),d=r.stages.map(f=>{var p;return(p=c.get(f.id))!==null&&p!==void 0?p:Nie(t,f,l)});uF(u,d),d.forEach((f,p)=>{let m=p<d.length-1?r.stages[p+1].id:void 0;M$(f,t,r.stages[p],m)})}function qp(e){let t=e.match(/^<\?xml[^>]*\?>\s*/),r=t?t[0]:"";return{prolog:r,body:e.slice(r.length)}}function Oie(e){var t,r,n,i,o,a;(0,V$.installDomShim)();let s=(t=e.bag)===null||t===void 0?void 0:t.xaml;if(s){let f=new DOMParser().parseFromString("<root/>","text/xml"),p={n:"Activity",a:(0,Sv.mergeAttrs)(s.a,[]),c:(0,Sv.spliceChildren)(s.c,[])};return{root:(0,Sv.rebuildRaw)(p,(0,Ia.domEngine)(f),null),prolog:(n=(r=e.bag)===null||r===void 0?void 0:r.xamlProlog)!==null&&n!==void 0?n:_v,eol:(o=(i=e.bag)===null||i===void 0?void 0:i.xamlEol)!==null&&o!==void 0?o:"lf"}}let l=e.stages[0],u=(a=l?.steps)===null||a===void 0?void 0:a[0],c=Lv(e.entityLogicalName,(0,Rr.newId)(),l?.id&&l.id.trim()!==""?l.id:(0,Rr.newId)(),u?.id&&u.id.trim()!==""?u.id:(0,Rr.newId)()),{body:d}=qp(c);return{root:(0,Ia.parseXmlRoot)(d,"<Activity/>"),prolog:_v,eol:"lf"}}function Pie(e){let{root:t,prolog:r,eol:n}=Oie(e);Iie(t,t.ownerDocument,e);let i=(0,Ia.serializeNode)(t);return n==="crlf"&&(i=i.replace(/\n/g,`\r-`)),r+i}function Rie(e){return e.uniqueName&&e.uniqueName.trim()!==""?e.uniqueName:`new_${(e.name||"businessprocessflow").toLowerCase().replace(/[^a-z0-9]/g,"")||"businessprocessflow"}`}var Mp=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var r,n;(0,V$.installDomShim)();let i=t,o=typeof i.xaml=="string"?i.xaml:"",a={id:i.workflowid?String(i.workflowid):null,name:String((r=i.name)!==null&&r!==void 0?r:""),entityLogicalName:String((n=i.primaryentity)!==null&&n!==void 0?n:""),status:Number(i.statecode)===1?"Active":"Draft",stages:[]};if(i.uniquename&&(a.uniqueName=String(i.uniquename)),i.description!=null&&i.description!==""&&(a.description=String(i.description)),i.processorder!=null&&i.processorder!==""&&(a.order=Number(i.processorder)),o.trim()!==""){let{prolog:s,body:l}=qp(o),u=(0,Ia.parseXmlRoot)(l,"<Activity/>");a.stages=Aie(u),a.bag={xaml:(0,Ia.projectElementBag)(u),xamlProlog:s,xamlEol:/\r\n/.test(o)?"crlf":"lf"}}return a}toApiPayload(t){var r;let n={workflowid:t.id&&t.id.trim()!==""?t.id:(0,Rr.newId)(),name:t.name,uniquename:Rie(t),primaryentity:t.entityLogicalName,xaml:Pie(t),category:$p.WorkflowCategory.BusinessProcessFlow,type:$p.WorkflowTypeCode.Definition,businessprocesstype:$p.BusinessProcessType.BusinessFlow,scope:$p.WorkflowScope.Organization,processorder:(r=t.order)!==null&&r!==void 0?r:pie};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 ai.InvalidArgumentError('securityRoles require the BPF to be Active \u2014 the backing table they grant access to is created on activation; set status to "Active" to wire security roles');i.securityRoles=t.securityRoles}return i}createDefault(t){var r,n,i;let o=t.stages&&t.stages.length>0?t.stages.map(B$):[B$({id:(0,Rr.newId)(),name:"New Stage",steps:[]})],a={id:t.id&&t.id.trim()!==""?t.id:(0,Rr.newId)(),name:(r=t.name)!==null&&r!==void 0?r:"New business process flow",entityLogicalName:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",status:(i=t.status)!==null&&i!==void 0?i:"Draft",stages:o};return t.uniqueName&&(a.uniqueName=t.uniqueName),t.description!==void 0&&(a.description=t.description),t.order!==void 0&&(a.order=t.order),t.globalActions!==void 0&&(a.globalActions=t.globalActions),t.securityRoles!==void 0&&(a.securityRoles=t.securityRoles),a}assignMissingIds(t){let r=Nv(t);(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,Rr.newId)());for(let n of["stages","steps","actions","globalActions"]){let i=r[n];Array.isArray(i)&&i.forEach(o=>this.assignMissingIds(o))}return r}validate(t){let r=[],n=t.stages;if(n!==void 0&&!Array.isArray(n))return r.push((0,Gr.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,Gr.issue)("/stages","too-many-stages",`a BPF allows at most 30 stages, got ${i.length}`));let o=new Set,a=new Map;i.forEach((l,u)=>{let c=`/stages/${u}`,d=Nv(l),f=typeof d.id=="string"?d.id.trim():"";f===""?r.push((0,Gr.issue)(`${c}/id`,"stage-id-required","a stage needs an id")):a.has(f.toLowerCase())?r.push((0,Gr.issue)(`${c}/id`,"stage-id-duplicate",`two stages share the id '${l.id}' (also at /stages/${a.get(f.toLowerCase())})`)):a.set(f.toLowerCase(),u),typeof l.entityLogicalName=="string"&&l.entityLogicalName!==""&&o.add(l.entityLogicalName);let p=Array.isArray(l.steps)?l.steps:[];p.length===0&&r.push((0,Gr.issue)(`${c}/steps`,"stage-needs-step","a BPF stage must have at least one step")),p.length>30&&r.push((0,Gr.issue)(`${c}/steps`,"too-many-steps",`a stage allows at most 30 steps, got ${p.length}`));let m=new Map;p.forEach((h,g)=>{let b=`${c}/steps/${g}`,w=typeof Nv(h).id=="string"?h.id.trim():"";w===""?r.push((0,Gr.issue)(`${b}/id`,"step-id-required","a step needs an id")):m.has(w.toLowerCase())?r.push((0,Gr.issue)(`${b}/id`,"step-id-duplicate",`two steps in this stage share the id '${h.id}'`)):m.set(w.toLowerCase(),g)}),l.branch&&!U$(i,l.branch.nextStageId)&&r.push((0,Gr.issue)(`${c}/branch/nextStageId`,"branch-target-unknown",`branch nextStageId '${l.branch.nextStageId}' does not match any stage id`)),typeof l.nextStageId=="string"&&l.nextStageId!==""&&!U$(i,l.nextStageId)&&r.push((0,Gr.issue)(`${c}/nextStageId`,"next-stage-unknown",`nextStageId '${l.nextStageId}' does not match any stage id`))}),o.size>5&&r.push((0,Gr.issue)("/stages","too-many-tables",`a BPF spans at most 5 tables, got ${o.size}`));let s=Lie(i);return s>=0&&r.push((0,Gr.issue)(`/stages/${s}/nextStageId`,"next-stage-cycle","the stage nextStageId links form a cycle; the flow must be acyclic")),r}};ll.BpfAdapter=Mp;function Lie(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 U$(e,t){return e.some(r=>r.id===t)}function B$(e){var t,r;let n=e.steps&&e.steps.length>0?e.steps.map(q$):[q$({id:(0,Rr.newId)(),name:"New Step"})],i={id:e.id&&e.id.trim()!==""?e.id:(0,Rr.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 q$(e){var t;let r={id:e.id&&e.id.trim()!==""?e.id:(0,Rr.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 Lv(e,t,r,n){return`${_v}<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="${O$}" /></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="${O$}" /></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 kie(){return{adapter:new Mp,api:fie.bpfApi,languageSensitive:!0}}ll.bpfRegistration=kie});var pF=v(Vp=>{"use strict";Object.defineProperty(Vp,"__esModule",{value:!0});Vp.buildRegistrations=void 0;var xie=uL(),$ie=DL(),Fie=ck(),Mie=Tk(),Uie=Jk(),Bie=hx(),qie=Rx(),Vie=m$(),Gie=fF();function Wie(e){let t=new Map;return t.set("form",(0,xie.formRegistration)(e)),t.set("view",(0,$ie.viewRegistration)()),t.set("businessRule",(0,Fie.businessRuleRegistration)()),t.set("app",(0,Mie.appRegistration)(e)),t.set("command",(0,Uie.commandRegistration)()),t.set("chart",(0,Bie.chartRegistration)()),t.set("dashboard",(0,qie.dashboardRegistration)(e)),t.set("genPage",(0,Vie.genPageRegistration)()),t.set("bpf",(0,Gie.bpfRegistration)()),t}Vp.buildRegistrations=Wie});var _F=v(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE=Pe.ROW_SUMMARY_MODEL_NOT_DELETED_CODE=Pe.removeRowSummary=Pe.configureRowSummary=Pe.buildGptDynamicPrompt=Pe.setAppAiFeatures=Pe.getAiReadiness=Pe.saveSettingValue=Pe.retrieveSetting=Pe.AI_GATE=void 0;var mn=ye(),We=ue(),mF=lt(),Wr=Q();Pe.AI_GATE={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabled",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"EnableNLGridSearch",nlChart:"NLChartVisualizationSetting",summaries:"EnableFormInsights",m365:"m365copilotmodelappenabled"};var wF={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabledOnByDefault",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"NLGridSearchSetting",nlChart:"NLChartDataVisualizationSetting",m365:"m365copilotmodelappenabled"},zie=new Set(Object.entries(Pe.AI_GATE).filter(([e,t])=>wF[e]===t).map(([e])=>e)),jie={formFill:{enabled:"2",disabled:"1"},formFillSuggestions:{enabled:"2",disabled:"1"},formFillSmartPaste:{enabled:"2",disabled:"1"},formFillFiles:{enabled:"2",disabled:"1"}};function kv(e){return jie[e]}var Gp=1e6;function Hie(e,t){let r=kv(t),n=()=>{throw new Wr.InvalidArgumentError(`setAppAiFeatures: '${t}' must be a boolean or an integer between 0 and ${Gp} (e.g. 0, 1, 2); got '${String(e)}'.`)},i=o=>r?o?r.enabled:r.disabled:o?"1":"0";if(typeof e=="boolean")return i(e);if(typeof e=="number")return!Number.isSafeInteger(e)||e<0||e>Gp?n():String(e);if(typeof e=="string"){let o=e.trim(),a=o.toLowerCase();if(a==="true")return i(!0);if(a==="false")return i(!1);if(/^[0-9]+$/.test(o)){let s=o.replace(/^0+(?=[0-9])/,"");return s.length>String(Gp).length||Number(s)>Gp?n():s}}return n()}function Kie(e,t){let r=kv(t);return r?e===r.enabled:e!=="0"}async function Jie(e,t){var r,n,i;let o=`/appmodules${(0,We.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,We.odataLiteral)(t)}'`]])}`,a=await e.get(o);return a.status>=200&&a.status<300?(i=((n=(r=a.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0])===null||i===void 0?void 0:i.appmoduleid:void 0}async function Yie(e,t){var r,n;let i=`/appmodules${(0,We.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,We.odataLiteral)(t)}'`]])}`,o;try{o=await e.get(i)}catch(l){throw new Wr.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup failed (${l.message}). Retry, or omit appModuleId to verify by name.`)}if(o.status<200||o.status>=300)throw new Wr.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned HTTP ${o.status}. Retry, or omit appModuleId to verify by name.`);let a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new Wr.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a malformed body.`);if(a.length===0)return;let s=(n=a[0])===null||n===void 0?void 0:n.appmoduleid;if(!s)throw new Wr.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a row with no appmoduleid.`);return s}var hF=new WeakMap;async function Qie(e,t){var r,n,i;let o=hF.get(e);if(o||(o=new Map,hF.set(e,o)),o.has(t))return o.get(t);let a=`/settingdefinitions${(0,We.odataQuery)([["$select","settingdefinitionid"],["$filter",`uniquename eq '${(0,We.odataLiteral)(t)}'`]])}`,s=await e.get(a),l=s.status>=200&&s.status<300?(i=((n=(r=s.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0])===null||i===void 0?void 0:i.settingdefinitionid:void 0;return l&&o.set(t,l),l}async function Xie(e,t,r){var n,i,o;let a=await Qie(e,r);if(!t||!a)return;let s=`/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()${(0,We.odataQuery)([["$select","value,componentstate"],["$filter",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${a}`]])}`,l=await e.get(s);if(l.status<200||l.status>=300)return;let u=(i=(n=l.body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[];if(u.length===0)return{exists:!1};let c=(o=u.find(d=>d?.componentstate===1))!==null&&o!==void 0?o:u[0];return{exists:!0,value:c.value,pendingPublish:c.componentstate===1}}var Zie=4,eoe=500,gF=20,yF=3e4;function toe(e){if(e===void 0)return Zie;if(!Number.isFinite(e))throw new Wr.InvalidArgumentError(`setAppAiFeatures: verifyAttempts must be a finite integer between 1 and ${gF}; got ${e}.`);return Math.min(gF,Math.max(1,Math.floor(e)))}function roe(e){if(e===void 0)return eoe;if(!Number.isFinite(e))throw new Wr.InvalidArgumentError(`setAppAiFeatures: verifyDelayMs must be a finite number between 0 and ${yF}; got ${e}.`);return Math.min(yF,Math.max(0,Math.floor(e)))}async function noe(e,t,r,n,i,o,a){let s,l,u,c=!1;for(let d=0;d<o;d+=1){d>0&&await new Promise(p=>setTimeout(p,a*d));let f;try{let p=await t();p?(f=await Xie(e,p,n),f===void 0&&(u="the app-scope override row could not be read (insufficient access or unresolvable ids)")):u=`the app '${r}' could not be resolved to an appmoduleid \u2014 a newly created app is not readable until it is published, so either publish it first or pass \`appModuleId\` in the options to verify without the lookup`}catch(p){f=void 0,u=p.message}c=f!==void 0,l=f?.exists;try{s=(await Wp(e,n,{appUniqueName:r})).value}catch{}if(f?.exists&&f.value===i)return{result:"proven",effectiveValue:f.value,appOverrideExists:!0,...f.pendingPublish?{pendingPublish:!0}:{}}}return c?{result:"absent",effectiveValue:s,appOverrideExists:l}:{result:"unverifiable",effectiveValue:s,appOverrideExists:void 0,reason:u}}function CF(e,t,r){if(t===2)return String(e).toLowerCase()==="true";let n=r?kv(r):void 0;return n?e===n.enabled:e!=null&&e!=="0"&&e!==""}async function Wp(e,t,r={}){var n,i;let o=[`SettingName='${(0,We.odataPathLiteral)(t)}'`];r.appUniqueName&&o.push(`AppUniqueName='${(0,We.odataPathLiteral)(r.appUniqueName)}'`);let a=`/RetrieveSetting(${o.join(",")})`,l=(i=(n=(0,mn.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.SettingDetail)!==null&&i!==void 0?i:{};return{value:l.Value,dataType:l.DataType}}Pe.retrieveSetting=Wp;async function EF(e,t,r,n={}){let i={SettingName:t,Value:r};n.appUniqueName&&(i.AppUniqueName=n.appUniqueName),n.solutionUniqueName&&(i.SolutionUniqueName=n.solutionUniqueName),(0,mn.ensureSuccess)(await e.post("/SaveSettingValue",i),e.apiUrl("/SaveSettingValue"))}Pe.saveSettingValue=EF;async function ioe(e,t={}){let r={};for(let[n,i]of Object.entries(Pe.AI_GATE)){let{value:o,dataType:a}=await Wp(e,i,t);r[n]={enabled:CF(o,a,n),setting:i,value:o}}return r}Pe.getAiReadiness=ioe;async function ooe(e,t,r,n={}){var i,o;if(!t||!t.trim())throw new Wr.InvalidArgumentError("setAppAiFeatures: a non-empty appUniqueName is required (an empty value would write the setting at organization scope, affecting every app).");let a=toe(n.verifyAttempts),s=roe(n.verifyDelayMs),l=[];for(let[h,g]of Object.entries(r)){if(g===void 0)continue;let b=wF[h];b&&l.push({feature:h,setting:b,requestedValue:Hie(g,h)})}let u=[],c=n.appModuleId?(0,We.normalizeGuid)(n.appModuleId,"appModuleId"):void 0;if(c){let h=await Yie(e,t);if(h&&(0,We.normalizeGuid)(h,"appModuleId")!==c)throw new Wr.InvalidArgumentError(`setAppAiFeatures: appModuleId '${c}' does not belong to app '${t}' (which resolves to '${h}'). Settings are written by unique name, so verifying against a different app would report success for a write that never landed.`)}let d,f=async()=>c||(d||(d=await Jie(e,t)),d),p=new Map,m=async h=>{if(zie.has(h))return;let g=Pe.AI_GATE[h];if(g){if(!p.has(g))try{let{value:b,dataType:w}=await Wp(e,g);p.set(g,{enabled:CF(b,w,h),setting:g,value:b})}catch{p.set(g,void 0)}return p.get(g)}};for(let{feature:h,setting:g,requestedValue:b}of l)try{await EF(e,g,b,{appUniqueName:t,solutionUniqueName:n.solutionUniqueName});let w=await noe(e,f,t,g,b,a,s),E={feature:h,setting:g,requestedValue:b,effectiveValue:w.effectiveValue,appOverrideExists:w.appOverrideExists};if(w.result==="proven")u.push({...E,status:"applied",...w.pendingPublish?{pendingPublish:!0}:{}});else if(w.result==="absent"){let A=Kie(b,h)?await m(h):void 0;A&&!A.enabled?u.push({...E,status:"skipped",reason:`the write was issued and no app-scope override holding '${b}' was observed for '${g}' after ${a} attempt(s); the org readiness gate '${A.setting}' reads '${A.value}', so an environment admin must enable it before this app can turn the feature on`}):u.push({...E,status:"notPersisted",reason:`the write reported success but no app-scope override holding '${b}' was observed for '${g}' after ${a} attempt(s) \u2014 it reads '${(i=w.effectiveValue)!==null&&i!==void 0?i:""}' for this app (Dataverse can accept an app-scope write without storing it)`})}else u.push({...E,status:"unverified",reason:`the write was issued but could not be confirmed: ${(o=w.reason)!==null&&o!==void 0?o:"the app-scope override row could not be read"}. The value may or may not be in force \u2014 verify manually before relying on it.`})}catch(w){u.push({feature:h,setting:g,requestedValue:b,status:"failed",reason:w.message})}return{applied:u.filter(h=>h.status==="applied").map(h=>h.feature),skipped:u.filter(h=>h.status==="skipped").map(h=>h.feature),notPersisted:u.filter(h=>h.status==="notPersisted").map(h=>h.feature),unverified:u.filter(h=>h.status==="unverified").map(h=>h.feature),failed:u.filter(h=>h.status==="failed").map(h=>h.feature),outcomes:u}}Pe.setAppAiFeatures=ooe;var aoe="GptPowerPrompt",soe='{ "consumptionSource": "Api", "partnerSource": "AIBuilder", "consumptionSourceVersion": "GptApiClient"}';function AF(e){var t,r,n,i;let o=e.entityLogicalName,a=[{type:"literal",text:e.instruction.replace(/\s*$/,"")+" "}];return e.columns.forEach((s,l)=>{a.push({type:"data",id:`${o}.${s.logical}`,text:s.display}),l<e.columns.length-1&&a.push({type:"literal",text:", "})}),{version:"GptDynamicPrompt-2",prompt:a,definitions:{inputs:[{id:"RecordId",text:"RecordId",type:"text"},{id:"LanguageCode",text:"LanguageCode",type:"text"}],formulas:[],data:[{id:o,displayName:o,type:"dataverseTable",filters:[{filterType:"equal",attribute:e.primaryKey,valueType:"inputVariable",value:"RecordId"}]}],output:{formats:[(t=e.outputFormat)!==null&&t!==void 0?t:"text"]}},modelParameters:{modelType:"default",gptParameters:{temperature:(r=e.temperature)!==null&&r!==void 0?r:0}},settings:{recordRetrievalLimit:(n=e.recordRetrievalLimit)!==null&&n!==void 0?n:30,shouldPreserveRecordLinks:null,runtime:null,enableReasoning:(i=e.enableReasoning)!==null&&i!==void 0?i:!0},code:"",signature:""}}Pe.buildGptDynamicPrompt=AF;async function loe(e,t){var r,n;let i=`/EntityDefinitions(LogicalName='${(0,We.odataPathLiteral)(t)}')${(0,We.odataQuery)([["$select","MetadataId"]])}`;return(n=(r=(0,mn.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.MetadataId)!==null&&n!==void 0?n:""}async function SF(e){var t,r,n;let i=`/msdyn_aitemplates${(0,We.odataQuery)([["$select","msdyn_aitemplateid"],["$filter",`msdyn_uniquename eq '${aoe}'`],["$top",1]])}`;return((n=(r=(t=(0,mn.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||t===void 0?void 0:t.value)===null||r===void 0?void 0:r[0])!==null&&n!==void 0?n:{}).msdyn_aitemplateid}function NF(e){return`${e} row summary`}async function uoe(e,t,r){var n;let i=`/msdyn_aimodels(${t})${(0,We.odataQuery)([["$select","msdyn_name,_msdyn_templateid_value"]])}`,o=await e.get(i);if(o.status===404)return!1;let a=(n=(0,mn.ensureSuccess)(o,e.apiUrl(i)).body)!==null&&n!==void 0?n:{},s=await SF(e);return typeof a.msdyn_name=="string"&&a.msdyn_name.toLowerCase()===NF(r).toLowerCase()&&typeof a._msdyn_templateid_value=="string"&&s!==void 0&&a._msdyn_templateid_value.toLowerCase()===s.toLowerCase()}async function coe(e,t,r={}){var n,i;let o=`ais_RowSummary_${t.entityLogicalName}`,a=`/aiskillconfigs${(0,We.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,We.odataLiteral)(o)}'`],["$top",1]])}`,s=((i=(n=(0,mn.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[])[0];if(s)return{modelId:s._aimodel_value,aiSkillConfigId:s.aiskillconfigid};let l=await SF(e),u=(0,mF.newId)(),c=(0,mF.newId)(),d=JSON.stringify(AF(t)),f={ModelId:u,RunConfigurationId:c,ModelName:NF(t.entityLogicalName),TemplateId:l,CustomConfiguration:d,Source:soe,RunConfiguration:""};(0,mn.ensureSuccess)(await e.post("/AIModelPublish",f),e.apiUrl("/AIModelPublish"));try{let p=await loe(e,t.entityLogicalName),m={uniquename:o,description:`${t.entityLogicalName} row summary`,"[email protected]":`/entities(${p})`,"[email protected]":`/msdyn_aimodels(${u})`,aiskill:"RowSummary"},h=(0,mn.ensureSuccess)(await e.post("/aiskillconfigs",m),e.apiUrl("/aiskillconfigs")),g=(0,mn.requireCreatedId)(h,"aiskillconfigid","row-summary skill");return{modelId:u,aiSkillConfigId:g}}catch(p){try{await e.delete(`/msdyn_aimodels(${u})`)}catch{}throw p}}Pe.configureRowSummary=coe;async function doe(e,t){var r,n;let i=`ais_RowSummary_${t.entityLogicalName}`,o=`/aiskillconfigs${(0,We.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,We.odataLiteral)(i)}'`],["$top",1]])}`,a=((n=(r=(0,mn.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0];if(!a)return;let s=(0,We.normalizeGuid)(a.aiskillconfigid,"aiskillconfigid"),l=a._aimodel_value?(0,We.normalizeGuid)(a._aimodel_value,"_aimodel_value"):void 0,u=l?await uoe(e,l,t.entityLogicalName):!1,c=t.entityLogicalName,d=`/aiskillconfigs(${s})`,f=await bF(e,d,`${d}${(0,We.odataQuery)([["$select","aiskillconfigid"]])}`);if(f.kind==="failed")throw f.stillThere===void 0&&l&&u?(0,Wr.attachCause)(new Wr.SdkError(Pe.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE,`Removing the row summary of '${c}' could not be confirmed: deleting its skill row failed (${vF(f.failure)}) and the row could not be read back. If it is gone, its AI model '${l}' is left behind, unreferenced. Retry removeRowSummary: while the skill row exists it removes both; once it is gone, delete that model.`),f.failure):f.failure;if(l&&u){let p=`/msdyn_aimodels(${l})`,m=await bF(e,p,`${p}${(0,We.odataQuery)([["$select","msdyn_aimodelid"]])}`,poe);if(m.kind==="failed")throw(0,Wr.attachCause)(new Wr.SdkError(Pe.ROW_SUMMARY_MODEL_NOT_DELETED_CODE,`The row summary of '${c}' was removed, but its AI model '${l}' ${m.stillThere?"was not deleted":"could not be confirmed deleted"} (${vF(m.failure)}). The model is no longer used by the row summary; delete it before configuring a row summary for '${c}' again, which needs its name.`),m.failure)}}Pe.removeRowSummary=doe;Pe.ROW_SUMMARY_MODEL_NOT_DELETED_CODE="ROW_SUMMARY_MODEL_NOT_DELETED";Pe.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE="ROW_SUMMARY_REMOVAL_UNCONFIRMED";var foe="0x8004f01f";function poe(e){var t,r;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return e.status===400&&typeof n=="string"&&n.toLowerCase()===foe}function moe(e){if(e.status!==400&&e.status!==500||e.body===void 0||e.body===null)return!1;let t=typeof e.body=="string"?e.body:JSON.stringify(e.body);return/chosen as the deadlock victim|\bSql Number:\s*1205\b/i.test(t)}async function bF(e,t,r,n=()=>!1){let i;try{let o=await(0,mn.resendWhile)(moe,()=>e.delete(t));if(o.status>=200&&o.status<300||o.status===404)return{kind:"gone"};if(n(o))return{kind:"kept"};try{(0,mn.ensureSuccess)(o,e.apiUrl(t))}catch(a){i=a}}catch(o){i=o}try{let o=await e.get(r);return o.status===404?{kind:"gone"}:{kind:"failed",failure:i,stillThere:o.status>=200&&o.status<300?!0:void 0}}catch{return{kind:"failed",failure:i,stillThere:void 0}}}function vF(e){return e instanceof Error?e.message:String(e)}});var IF=v(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});ul.findArtifact=ul.resolveArtifact=void 0;var $t=ue(),Wi=Nd(),hoe=Fd(),goe=Xt(),yoe=ye(),TF=Q();async function DF(e,t,r){let n="/uxagentprojects"+(0,$t.odataQuery)([["$select","uxagentprojectid,name"],["$filter",`name eq '${(0,$t.odataLiteral)(t)}'`],...r!==void 0?[["$top",String(r)]]:[]]);return(await(0,goe.collectPages)(e,n,"resolveArtifact('genPage')",void 0,{headers:{"MSCRM.IncludeUnpublished":"true"}})).map(o=>({id:String(o.uxagentprojectid),name:String(o.name)}))}async function boe(e,t,r){var n,i,o,a,s,l,u,c,d,f,p,m,h;switch(t){case"app":{let g=(0,hoe.unpublishedAppModulesQuery)("appmoduleid,name,appmoduleidunique",`uniquename eq '${(0,$t.odataLiteral)((n=r.uniqueName)!==null&&n!==void 0?n:"")}'`,1),w=(i=(0,yoe.ensureSuccess)(await e.get(g),e.apiUrl(g)).body)===null||i===void 0?void 0:i.value,E=w&&w[0];return E?[{id:String(E.appmoduleid),name:String(E.name),appModuleIdUnique:String(E.appmoduleidunique)}]:[]}case"dashboard":return(await(0,Wi.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,$t.odataLiteral)((o=r.name)!==null&&o!==void 0?o:"")}' and type eq 0`,top:10})||[]).map(b=>({id:String(b.formid),name:String(b.name)}));case"command":{let g=await(0,Wi.queryRecords)(e,"appaction",{select:["appactionid","buttonlabeltext"],filter:`contextvalue eq '${(0,$t.odataLiteral)((a=r.entity)!==null&&a!==void 0?a:"")}'`,top:1});return g&&g.length?[{id:String(r.entity),entity:String(r.entity)}]:[]}case"form":return(await(0,Wi.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,$t.odataLiteral)((s=r.name)!==null&&s!==void 0?s:"")}' and objecttypecode eq '${(0,$t.odataLiteral)((l=r.entity)!==null&&l!==void 0?l:"")}'`,top:10})||[]).map(b=>({id:String(b.formid),name:String(b.name)}));case"chart":return(await(0,Wi.queryRecords)(e,"savedqueryvisualization",{select:["savedqueryvisualizationid","name"],filter:`name eq '${(0,$t.odataLiteral)((u=r.name)!==null&&u!==void 0?u:"")}' and primaryentitytypecode eq '${(0,$t.odataLiteral)((c=r.entity)!==null&&c!==void 0?c:"")}'`,top:10})||[]).map(b=>({id:String(b.savedqueryvisualizationid),name:String(b.name)}));case"view":return(await(0,Wi.queryRecords)(e,"savedquery",{select:["savedqueryid","name"],filter:`name eq '${(0,$t.odataLiteral)((d=r.name)!==null&&d!==void 0?d:"")}' and returnedtypecode eq '${(0,$t.odataLiteral)((f=r.entity)!==null&&f!==void 0?f:"")}'`,top:10})||[]).map(b=>({id:String(b.savedqueryid),name:String(b.name)}));case"webResource":return(await(0,Wi.queryRecords)(e,"webresource",{select:["webresourceid","name"],filter:`name eq '${(0,$t.odataLiteral)((p=r.name)!==null&&p!==void 0?p:"")}'`,top:1})||[]).map(b=>({id:String(b.webresourceid),name:String(b.name)}));case"solution":return(await(0,Wi.queryRecords)(e,"solution",{select:["solutionid","uniquename"],filter:`uniquename eq '${(0,$t.odataLiteral)((m=r.uniqueName)!==null&&m!==void 0?m:"")}'`,top:1})||[]).map(b=>({id:String(b.solutionid),name:String(b.uniquename)}));case"genPage":return DF(e,(h=r.name)!==null&&h!==void 0?h:"");default:return[]}}ul.resolveArtifact=boe;async function voe(e,t,r){var n,i,o,a,s,l,u;let c=(0,$t.odataLiteral)((n=r.name)!==null&&n!==void 0?n:""),d=(0,$t.odataLiteral)((i=r.entity)!==null&&i!==void 0?i:"");if(t==="command"){let g=await(0,Wi.queryRecords)(e,"appaction",{select:["appactionid"],filter:`contextvalue eq '${(0,$t.odataLiteral)((o=r.entity)!==null&&o!==void 0?o:"")}'`,top:1});return g&&g.length?String(r.entity):null}if(t==="genPage"){let g=await DF(e,(a=r.name)!==null&&a!==void 0?a:"",2);if(g.length>1)throw new TF.AmbiguousArtifactError(t,(s=r.name)!==null&&s!==void 0?s:"",g.length);return g.length===1?g[0].id:null}let f=woe(t,c,d,r),p=t!=="app",m=await(0,Wi.queryRecords)(e,f.set,{select:[f.idField],filter:f.filter,top:p?2:1});if(p&&m&&m.length>1)throw new TF.AmbiguousArtifactError(t,(u=(l=r.name)!==null&&l!==void 0?l:r.uniqueName)!==null&&u!==void 0?u:"",m.length);let h=m&&m[0]&&m[0][f.idField];return h!=null?String(h):null}ul.findArtifact=voe;function woe(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,$t.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 PF=v(jp=>{"use strict";Object.defineProperty(jp,"__esModule",{value:!0});jp.seedRecordGraph=void 0;var OF=Nd(),Coe=sd(),zp=ue(),Eoe=Q();async function Aoe(e,t,r={}){var n,i,o,a,s;let l=(n=r.createdIds)!==null&&n!==void 0?n:{},u=(i=r.entitySetFor)!==null&&i!==void 0?i:(f=>(0,Coe.resolveEntitySetName)(e,f)),c={},d=f=>{var p;return(p=c[f])!==null&&p!==void 0?p:l[f]};for(let f of t){let p=f.entityLogical.toLowerCase(),m=(o=f.matchOn)===null||o===void 0?void 0:o.toLowerCase(),h=[];for(let R of f.records){let I={...R.body};for(let D of(a=R.binds)!==null&&a!==void 0?a:[]){let O=D.parentEntity.toLowerCase(),$=(s=d(O))===null||s===void 0?void 0:s[D.parentIndex];if(!$)throw new Eoe.InvalidArgumentError(`Cannot resolve bind '${D.navProperty}' on a '${p}' record: parent '${D.parentEntity}'[${D.parentIndex}] has no created id. Seed the parent group before the child, or supply it via options.createdIds.`);let K=(0,zp.assertODataName)(await u(O),`entity set for parent '${D.parentEntity}'`),Re=(0,zp.normalizeGuid)($,`parent id for bind '${D.navProperty}'`);I[`${D.navProperty}@odata.bind`]=`/${K}(${Re})`}h.push(I)}let g=m?h.map(R=>{let I=R[m];return I!=null&&I!==""?String(I):null}):h.map(()=>null),b=new Map;if(m){let R=(0,zp.assertODataName)(m,"RecordGraph matchOn key"),I=[...new Set(g.filter(D=>D!==null))];if(I.length){let D=I.map($=>`${R} eq '${(0,zp.odataLiteral)($)}'`).join(" or "),O=await(0,OF.queryRecords)(e,p,{select:[R,`${p}id`],filter:D,top:5e3});for(let $ of O??[]){let K=$[R];K!=null&&b.set(String(K).toLowerCase(),String($[`${p}id`]))}}}let w=[],E=new Map,A=h.map((R,I)=>{let D=g[I];if(D&&b.has(D.toLowerCase()))return null;if(D){let O=D.toLowerCase(),$=E.get(O);if($!==void 0)return $;let K=w.push(R)-1;return E.set(O,K),K}return w.push(R)-1}),L=w.length?await(0,OF.createRecordsBulk)(e,p,w):[];c[p]=h.map((R,I)=>{let D=g[I];return D&&b.has(D.toLowerCase())?b.get(D.toLowerCase()):L[A[I]]})}return{createdIds:c}}jp.seedRecordGraph=Aoe});var qF=v(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.getEntityPrivileges=Jt.addEntityPrivilegesToRole=Jt.deleteSecurityRole=Jt.createPersonaRole=Jt.createSecurityRole=Jt.SDK_ROLE_MARKER=void 0;var Ln=ye(),Tt=ue(),zr=Q(),Hp={read:"Read",create:"Create",write:"Write",delete:"Delete",append:"Append",appendTo:"AppendTo",assign:"Assign",share:"Share"},$v={user:"Basic",businessUnit:"Local",parentChild:"Deep",organization:"Global"},RF={user:1,businessUnit:2,parentChild:3,organization:4},xv={user:"CanBeBasic",businessUnit:"CanBeLocal",parentChild:"CanBeDeep",organization:"CanBeGlobal"};Jt.SDK_ROLE_MARKER="Authored by @maker-studio/cds-maker-sdk (persona/security role).";function Soe(e){return Object.prototype.hasOwnProperty.call(Hp,e)?Hp[e]:void 0}function Noe(e){return Object.prototype.hasOwnProperty.call($v,e)}var LF=new WeakMap,kF=new WeakMap;async function FF(e,t){var r,n;(0,Tt.assertODataName)(t,"entity logical name");let i=LF.get(e);i||(i=new Map,LF.set(e,i));let o=i.get(t);if(o)return o;let a=`/EntityDefinitions(LogicalName='${(0,Tt.odataPathLiteral)(t)}')${(0,Tt.odataQuery)([["$select","LogicalName,Privileges"]])}`,l=(n=(r=(0,Ln.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||r===void 0?void 0:r.Privileges)!==null&&n!==void 0?n:[];if(l.length===0)throw new zr.InvalidArgumentError(`Entity '${t}' exposes no privileges (unknown or non-securable entity).`);return i.set(t,l),l}async function _oe(e){var t,r,n;let i=kF.get(e);if(i)return i;let o=`/businessunits${(0,Tt.odataQuery)([["$select","businessunitid"],["$filter","_parentbusinessunitid_value eq null"],["$top",1]])}`,l=(n=((r=(t=(0,Ln.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||t===void 0?void 0:t.value)!==null&&r!==void 0?r:[])[0])===null||n===void 0?void 0:n.businessunitid;if(!l)throw new zr.InvalidArgumentError("Could not resolve the root business unit.");let u=(0,Tt.normalizeGuid)(l,"businessUnitId");return kF.set(e,u),u}async function MF(e,t){var r;let n=new Map;for(let i of t){if(!i.access||i.access.length===0)throw new zr.InvalidArgumentError(`Entity '${i.entity}' privilege request has no access levels.`);let o=(r=i.scope)!==null&&r!==void 0?r:"user";if(!Noe(o))throw new zr.InvalidArgumentError(`Unknown privilege scope '${o}' for entity '${i.entity}'.`);let a=await FF(e,i.entity);for(let s of i.access){let l=Soe(s);if(!l)throw new zr.InvalidArgumentError(`Unknown access level '${s}' for entity '${i.entity}'.`);let u=a.find(m=>m.PrivilegeType===l);if(!u)throw new zr.InvalidArgumentError(`Entity '${i.entity}' does not support '${s}' access.`);let c=xv[o];if(u[c]===!1)throw new zr.InvalidArgumentError(`Privilege '${u.Name}' on '${i.entity}' does not support the '${o}' scope.`);let d=(0,Tt.normalizeGuid)(u.PrivilegeId,"PrivilegeId"),f=n.get(d);if(!f){n.set(d,{privilegeName:u.Name,privilegeType:l,scope:o,entities:new Set([i.entity])});continue}if(f.scope===o){f.entities.add(i.entity);continue}if(!(f.entities.size===1&&f.entities.has(i.entity))){let m=[...f.entities].sort().join(", ");throw new zr.InvalidArgumentError(`Entities '${m}' and '${i.entity}' share the Dataverse privilege '${u.Name}' but request different scopes; a role holds one depth per privilege. Use the same scope for all entities that share this privilege, or split them.`)}f.scope=RF[o]>RF[f.scope]?o:f.scope}}return[...n.entries()].map(([i,o])=>({entity:[...o.entities].sort().join(", "),privilegeId:i,privilegeName:o.privilegeName,privilegeType:o.privilegeType,scope:o.scope}))}async function Toe(e,t,r,n){if(r.length===0&&!n)return;let i={Privileges:r.map(a=>({Depth:$v[a.scope],PrivilegeId:a.privilegeId}))},o=`/roles(${t})/Microsoft.Dynamics.CRM.ReplacePrivilegesRole`;(0,Ln.ensureSuccess)(await e.post(o,i),e.apiUrl(o))}async function xF(e,t,r,n,i){var o,a;let s=`/${t}(${r})/${n}${(0,Tt.odataQuery)([["$select","roleid"],["$filter",`roleid eq ${i}`]])}`;return((a=(o=(0,Ln.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||o===void 0?void 0:o.value)!==null&&a!==void 0?a:[]).length>0}async function Doe(e,t,r){var n,i;let o=[],a=[],s={"@odata.id":e.apiUrl(`/roles(${t})`)};for(let l of(n=r?.teams)!==null&&n!==void 0?n:[]){let u=(0,Tt.normalizeGuid)(l,"teamId");if(!await xF(e,"teams",u,"teamroles_association",t)){let c=`/teams(${u})/teamroles_association/$ref`;(0,Ln.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}o.push(u)}for(let l of(i=r?.users)!==null&&i!==void 0?i:[]){let u=(0,Tt.normalizeGuid)(l,"userId");if(!await xF(e,"systemusers",u,"systemuserroles_association",t)){let c=`/systemusers(${u})/systemuserroles_association/$ref`;(0,Ln.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}a.push(u)}return{teams:o,users:a}}async function $F(e,t,r){var n,i;let o=`/roles${(0,Tt.odataQuery)([["$select","roleid,description,ismanaged"],["$filter",`name eq '${(0,Tt.odataLiteral)(t)}' and _businessunitid_value eq ${r}`]])}`,l=((i=(n=(0,Ln.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]).filter(d=>!!d.roleid);if(l.length===0)return;let u=d=>{var f;return d.ismanaged!==!0&&((f=d.description)!==null&&f!==void 0?f:"")===Jt.SDK_ROLE_MARKER};if(l.some(d=>!u(d)))throw new zr.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 zr.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,Tt.normalizeGuid)(c,"roleId"):void 0}function Ioe(e){var t,r;return{teams:((t=e?.teams)!==null&&t!==void 0?t:[]).map(n=>(0,Tt.normalizeGuid)(n,"teamId")),users:((r=e?.users)!==null&&r!==void 0?r:[]).map(n=>(0,Tt.normalizeGuid)(n,"userId"))}}function UF(e){return e.map(t=>({entity:t.entity,privilegeName:t.privilegeName,privilegeType:t.privilegeType,scope:t.scope}))}async function BF(e,t){var r,n;let i=(r=t.name)===null||r===void 0?void 0:r.trim();if(!i)throw new zr.InvalidArgumentError("createSecurityRole: a non-empty role name is required.");let o=t.businessUnitId?(0,Tt.normalizeGuid)(t.businessUnitId,"businessUnitId"):await _oe(e),a=await MF(e,(n=t.privileges)!==null&&n!==void 0?n:[]),s=Ioe(t.assignTo),l=await $F(e,i,o),u=l!==void 0;if(!l){let d="/roles",f={name:i,description:Jt.SDK_ROLE_MARKER,"[email protected]":`/businessunits(${o})`};try{let p=(0,Ln.ensureSuccess)(await e.post(d,f),e.apiUrl(d));l=(0,Tt.normalizeGuid)((0,Ln.requireCreatedId)(p,"roleid","role"),"roleId")}catch(p){let m;try{m=await $F(e,i,o)}catch{m=void 0}if(!m)throw p;l=m}}await Toe(e,l,a,u);let c=await Doe(e,l,s);return{roleId:l,name:i,reused:u,appliedPrivileges:UF(a),assignedTeams:c.teams,assignedUsers:c.users}}Jt.createSecurityRole=BF;async function Ooe(e,t){var r,n;let i=(r=t.persona)===null||r===void 0?void 0:r.trim();if(!i)throw new zr.InvalidArgumentError("createPersonaRole: a non-empty persona name is required.");let o=[...t.jobs.flatMap(a=>{var s;return(s=a.privileges)!==null&&s!==void 0?s:[]}),...(n=t.additionalPrivileges)!==null&&n!==void 0?n:[]];return BF(e,{name:i,businessUnitId:t.businessUnitId,privileges:o,assignTo:t.assignTo})}Jt.createPersonaRole=Ooe;async function Poe(e,t){let n=`/roles(${(0,Tt.normalizeGuid)(t,"roleId")})`;(0,Ln.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Jt.deleteSecurityRole=Poe;async function Roe(e,t,r){let n=(0,Tt.normalizeGuid)(t,"roleId");if(r.length===0)throw new zr.InvalidArgumentError("addEntityPrivilegesToRole requires at least one entity privilege (an empty grant would be a silent no-op).");let i=await MF(e,r),o={Privileges:i.map(s=>({Depth:$v[s.scope],PrivilegeId:s.privilegeId}))},a=`/roles(${n})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;return(0,Ln.ensureSuccess)(await e.post(a,o),e.apiUrl(a)),UF(i)}Jt.addEntityPrivilegesToRole=Roe;var Loe=new Map(Object.keys(Hp).map(e=>[Hp[e],e]));async function koe(e,t){return(await FF(e,t)).map(n=>{let i=Object.keys(xv).filter(a=>n[xv[a]]!==!1),o=Loe.get(n.PrivilegeType);return{name:n.Name,privilegeId:n.PrivilegeId,privilegeType:n.PrivilegeType,...o?{access:o}:{},scopes:i}})}Jt.getEntityPrivileges=koe});var iM=v(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});dr.createMakerSdk=dr.MakerSdk=dr.PUSH_NOT_ATTEMPTED_CODE=dr.ALREADY_EXISTS_CODE=void 0;var VF=Sm(),GF=Kr(),Z=Q(),hn=Fa(),xoe=CC(),eM=DC(),cl=kC(),$oe=_m(),Foe=tE(),dl=iE(),Moe=bE(),Uoe=SE(),Boe=tA(),WF=YA(),Dt=sd(),Fv=pg(),zF=nN(),Kp=Zl(),zi=Nd(),Jp=cN(),fl=Id(),qoe=Pd(),Yt=mg(),Voe=Cg(),Goe=Ig(),jF=Eg(),Woe=pF(),Yp=lt(),zoe=Ko(),ui=Nb(),gn=Pm(),Mv=cv(),joe=3e5,cr=ye(),Pa=ue(),pl=_F(),HF=IF(),Hoe=PF(),Koe=By(),pc=qF(),tM=Symbol("cds-maker-sdk.committedWrite");function Joe(e){return typeof e=="object"&&e!==null&&(e[tM]=!0),e}function Yoe(e){return typeof e=="object"&&e!==null&&e[tM]===!0}var Qoe={fileConcurrency:1},Uv="SOLUTION_COMPONENT_UNCLASSIFIED",Xoe=2,Zoe=4,eae="This table is in the solution with ALL its subcomponents. Those are members the solution does not list one by one, so fetchSolution did not enumerate or fetch them: none of its forms, views, charts or dashboards were fetched here. To fetch them, read the table's logical name from its metadata (EntityDefinitions(<componentId>), $select=LogicalName), list each kind with fetchArtifactList \u2014 'form' with formTypes Main, QuickView, QuickCreate and Card; 'view'; 'chart'; 'dashboard' \u2014 passing { entityLogicalName }, and fetch each listed id with fetchArtifact: listing returns ids and names only.";function KF(e){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"unsupported",...e.includesAllSubcomponents?{detail:eae}:{}}}function JF(e,t){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"failed",error:Po(t)}}function YF(e,t,r){let n=r;return{type:e,id:t.objectId,name:typeof n.name=="string"?n.name:t.objectId,entityLogicalName:typeof n.entityLogicalName=="string"?n.entityLogicalName:void 0,lastFetched:(0,cr.nowIso)(),isDirty:!1}}var tae=new Set(["entity","appmodule","dashboard","uxagentproject"]);function rae(e){var t;let r={entity:[],appmodule:[],dashboard:[],uxagentproject:[]},n=new Set,i=(s,l)=>{let u=`${s}\0${l.toLowerCase()}`;n.has(u)||(n.add(u),r[s].push(l))};for(let{scope:s}of e)if(s?.envelope==="entity")s.entityLogicalName&&i("entity",s.entityLogicalName);else if(s&&s.envelope!=="webresource")for(let l of(t=s.targetIds)!==null&&t!==void 0?t:[])i(s.envelope,l);let o=(s,l,u)=>u.length>0?`<${s}>${u.map(c=>`<${l}>${(0,Pa.xmlText)(c)}</${l}>`).join("")}</${s}>`:"",a=o("entities","entity",r.entity)+o("appmodules","appmodule",r.appmodule)+o("dashboards","dashboard",r.dashboard)+o("uxagentprojects","uxagentproject",r.uxagentproject);return a?`<importexportxml>${a}</importexportxml>`:void 0}function nae(e){let t=e.workspaceStorage;if(t==null)throw new Error("createMakerSdk requires a workspaceStorage. Node callers can build one with `createNodeWorkspaceStorage(path)` from '@maker-studio/cds-maker-sdk/node'; a host with no filesystem implements WorkspaceStorage directly.");return new eM.WorkspaceManager(oae,e.instanceUrl,(0,$oe.assertStorageContract)(t))}dr.ALREADY_EXISTS_CODE="ARTIFACT_ALREADY_EXISTS";var iae="this build answers a replayed create with HTTP 404, and the unpublished read of an existing row is not authoritative after another writer's save on it, so the row cannot be proven to be what this create wrote";dr.PUSH_NOT_ATTEMPTED_CODE="PUSH_NOT_ATTEMPTED";var oae="<injected workspaceStorage>",Qp=class{constructor(t){var r,n;if(this.artifactLocks=new Map,this.observedGenerations=new Map,this.baselineObserved=new Map,this.generationHighWater=new Map,this.entityMetadataLoads=new Map,this.entityMetadataLoadEpochs=new WeakMap,this.schemaWrites=new Map,this.undroppedMetadata=new Set,this.metadataPublications=new Set,t.createRecovery!==void 0&&t.createRecovery!=="adoptExact")throw new Z.InvalidArgumentError(`createRecovery must be 'adoptExact' or omitted (got '${String(t.createRecovery)}').`);this.createRecovery=t.createRecovery,this.readConcurrency=(0,Mv.resolveReadConcurrency)(t.readConcurrency),this.languageCode=(r=t.languageCode)!==null&&r!==void 0?r:zoe.DEFAULT_LCID,this.cacheStalenessMs=(n=t.cacheStalenessMs)!==null&&n!==void 0?n:joe,this.compiler={load:(0,Voe.createGenPageTypeScriptLoader)(t.typescript)},this.workspace=nae(t),this.versions=new cl.VersionManager(this.workspace),this.dataverse=new Foe.DataverseClient(t.instanceUrl,t.httpClient,t.solutionUniqueName,this.readConcurrency),this.connectivity=new Boe.ConnectivityRouter(this.dataverse,t.instanceUrl,{powerAppsServiceClient:t.powerAppsServiceClient,powerPlatformApiClient:t.powerPlatformApiClient,connectorRuntimeClient:t.connectorRuntimeClient}),this.registrations=(0,Woe.buildRegistrations)(this.languageCode)}async initWorkspace(){await this.workspace.init()}async getManifest(){return this.workspace.getManifest()}async cleanWorkspace(){await this.workspace.clean()}withArtifactLock(t,r,n){var i;let o=this.artifactKey(t,r),s=((i=this.artifactLocks.get(o))!==null&&i!==void 0?i:Promise.resolve()).then(n,n),l=s.then(()=>{},()=>{});return this.artifactLocks.set(o,l),l.then(()=>{this.artifactLocks.get(o)===l&&this.artifactLocks.delete(o)}),s}async fetchArtifact(t,r,n){return this.withArtifactLock(t,r,async()=>{let i=await this.fetchArtifactUnlocked(t,r,n);return await this.acknowledgeRefresh(t,r),i})}async fetchArtifactUnlocked(t,r,n){let i=this.requireRegistration(t,"fetchArtifact"),o=await i.api.get(this.dataverse,r);return this.applyFetchedArtifactUnlocked(t,r,i,o,n)}async applyFetchedArtifactUnlocked(t,r,n,i,o){var a,s,l;let{raw:u,etag:c,memberEtags:d,siblingEtags:f}=i,p=n.adapter.fromApiResponse(u);if(!o?.overwrite&&await this.versions.isDirty(t,r)){let h=(s=(a=await this.versions.getMeta(t,r))===null||a===void 0?void 0:a.etag)!==null&&s!==void 0?s:null;if(h&&c&&h!==c)throw new Z.LocalEditsWouldBeLostError(t,r,h,c);let g=await this.workspace.readArtifact(t,r);if(g){let b=await this.versions.getMeta(t,r);if(b&&!b.etag&&c){if(!(0,gn.deepEqual)(b.snapshot,p))throw new Z.LocalEditsWouldBeLostError(t,r,h,c);await this.versions.storeMeta(t,r,{...b,etag:c,fetchedAt:(0,cr.nowIso)()},b)}return(0,ui.cloneJson)(g)}}await this.workspace.writeArtifact(t,r,p);let m=await this.versions.getMeta(t,r);return await this.versions.storeMeta(t,r,{etag:c,languageCode:this.languageCode,projectionVersion:cl.PROJECTION_VERSION,fetchedAt:(0,cr.nowIso)(),snapshot:(0,ui.cloneJson)(p),...d?{memberEtags:d}:{},...f?{siblingEtags:f}:{},...m?.refreshGeneration?{refreshGeneration:m.refreshGeneration,observedGeneration:(l=m.observedGeneration)!==null&&l!==void 0?l:0}:{}},m),(0,ui.cloneJson)(p)}async fetchArtifactList(t,r){return this.requireRegistration(t,"fetchArtifactList").api.list(this.dataverse,r)}async fetchSolution(t){await this.workspace.ensureReady();let r=await(0,Yt.fetchSolutionComponents)(this.dataverse,t),n=[],i=[];if(this.readConcurrency>1)await this.fetchComponentsOverlapped(r,n,i);else for(let o of r)try{let a=await this.resolveComponentType(o);if(!a){i.push(KF(o));continue}let s=await this.fetchArtifact(a,o.objectId);n.push(YF(a,o,s))}catch(a){i.push(JF(o,a))}return await this.workspace.updateManifest({lastSyncAt:(0,cr.nowIso)()}),{summaries:n,skipped:i}}async fetchComponentsOverlapped(t,r,n){await(0,Mv.readEveryInOrder)(t,this.readConcurrency,i=>this.beginComponentRead(i),async(i,o)=>{try{if(!i.ok)throw i.error;let a=i.value;if(a.kind==="unsupported"){n.push(KF(o));return}let s=await this.applyFetchedArtifactUnlocked(a.type,o.objectId,a.reg,a.fetched);await this.acknowledgeRefresh(a.type,o.objectId),r.push(YF(a.type,o,s))}catch(a){n.push(JF(o,a))}})}async beginComponentRead(t){let r=await this.resolveComponentType(t);return r?this.lockedRead(r,t.objectId,async()=>{let n=this.requireRegistration(r,"fetchArtifact"),i=await n.api.get(this.dataverse,t.objectId,Qoe);return{kind:"artifact",type:r,reg:n,fetched:i}}):(0,Mv.plainRead)(async()=>({kind:"unsupported"}))}lockedRead(t,r,n){let i,o=new Promise(u=>{i=u}),a,s=new Promise(u=>{a=u}),l=this.withArtifactLock(t,r,async()=>{try{i({ok:!0,value:await n()})}catch(c){i({ok:!1,error:c})}let u=await s;await u?.()});return{outcome:o,finish:u=>(a(u),l),discard:async()=>{a(void 0),await l}}}async fetchEntityMetadata(t){let r=t.toLowerCase(),n=this.schemaEpoch(r),i=await(0,dl.fetchEntityMetadataFromApi)(this.dataverse,t);if(this.schemaEpoch(r)!==n)return i;let o=this.workspace.writeEntityMetadata(t,i),a={key:r,settled:o.then(()=>{},()=>{})};this.metadataPublications.add(a);try{await o}finally{this.metadataPublications.delete(a)}return this.schemaEpoch(r)===n&&this.undroppedMetadata.delete(r),i}schemaEpoch(t){var r,n;return`${(r=this.schemaWrites.get("*"))!==null&&r!==void 0?r:0}:${(n=this.schemaWrites.get(t.toLowerCase()))!==null&&n!==void 0?n:0}`}async schemaWrite(t,r){try{return await r()}finally{await this.forgetEntityMetadata(t)}}async forgetEntityMetadata(t){let r=i=>{var o;this.schemaWrites.set(i,((o=this.schemaWrites.get(i))!==null&&o!==void 0?o:0)+1)};if(t===void 0){r("*"),await this.publicationsSettled(void 0),await this.dropCachedMetadata(void 0);return}let n=[...new Set(t.filter(i=>typeof i=="string"&&i!=="").map(i=>i.toLowerCase()))];n.forEach(r),await this.publicationsSettled(n);for(let i of n)await this.dropCachedMetadata(i)}async publicationsSettled(t){let r=t===void 0?void 0:new Set(t);await Promise.all([...this.metadataPublications].filter(n=>r===void 0||r.has(n.key)).map(n=>n.settled))}async dropCachedMetadata(t){try{await this.workspace.dropEntityMetadata(t)}catch(r){r instanceof Z.WorkspaceNotInitializedError||r instanceof Z.WorkspaceOrgMismatchError||this.undroppedMetadata.add(t??"*");return}t===void 0?this.undroppedMetadata.clear():this.undroppedMetadata.delete(t)}async readCachedEntityMetadata(t){let r=t.toLowerCase();return this.undroppedMetadata.has("*")&&await this.dropCachedMetadata(void 0),this.undroppedMetadata.has(r)&&await this.dropCachedMetadata(r),this.undroppedMetadata.has("*")||this.undroppedMetadata.has(r)?null:this.workspace.readEntityMetadata(t)}loadMissedEntityMetadata(t){let r=this.schemaEpoch(t),n=this.entityMetadataLoads.get(t);if(n&&this.entityMetadataLoadEpochs.get(n)===r)return n;let i=this.fetchEntityMetadata(t).then(()=>{});this.entityMetadataLoads.set(t,i),this.entityMetadataLoadEpochs.set(i,r);let o=()=>{this.entityMetadataLoads.get(t)===i&&this.entityMetadataLoads.delete(t)};return i.then(o,o),i}generateGenPageRuntimeTypes(t,r){return(0,Moe.generateGenPageRuntimeTypes)(n=>this.fetchEntityMetadata(n),t,r)}findTables(t,r){return(0,dl.findTables)(this.dataverse,t,r)}getEnvironmentLanguages(){return(0,Uoe.getEnvironmentLanguages)(this.dataverse)}listConnections(){return this.connectivity.listConnections()}listConnectorOperations(t){return this.connectivity.listConnectorOperations(t)}getConnectorOperationSchema(t,r){return this.connectivity.getConnectorOperationSchema(t,r)}listConnectorTables(t,r,n){return this.connectivity.listConnectorTables(t,r,n)}getConnectorTableSchema(t,r,n,i){return this.connectivity.getConnectorTableSchema(t,r,n,i)}findColumns(t,r,n){return(0,dl.findColumns)(this.dataverse,t,r,n)}createTable(t){return this.schemaWrite([t.schemaName],()=>(0,Dt.createTable)(this.dataverse,t))}createColumn(t,r){return this.schemaWrite([t],()=>(0,Dt.createColumn)(this.dataverse,t,r))}createColumns(t,r){return this.schemaWrite([t],()=>(0,Dt.createColumns)(this.dataverse,t,r))}updateColumn(t,r,n){return this.schemaWrite([t],()=>(0,Dt.updateColumn)(this.dataverse,t,r,n))}deleteColumn(t,r){return this.schemaWrite([t],()=>(0,Dt.deleteColumn)(this.dataverse,t,r))}setFormSecurityRoles(t,r){return(0,Fv.setFormSecurityRoles)(this.dataverse,t,r)}getFormSecurityRoles(t){return(0,Fv.getFormSecurityRoles)(this.dataverse,t)}setColumnVisualization(t,r,n){return(0,Dt.setColumnVisualization)(this.dataverse,t,r,n)}getColumnVisualization(t,r){return(0,Dt.getColumnVisualization)(this.dataverse,t,r)}createCustomerColumn(t,r){return this.schemaWrite([t,"account","contact"],()=>(0,Dt.createCustomerColumn)(this.dataverse,t,r))}insertStatusValue(t,r){return this.schemaWrite([t],()=>(0,Dt.insertStatusValue)(this.dataverse,t,r))}updateTable(t,r){return this.schemaWrite([t],()=>(0,Dt.updateTable)(this.dataverse,t,r))}async setEntityIcon(t,r){if(await this.schemaWrite([t],()=>(0,Dt.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,Pa.xmlText)(t)}</entity></entities></importexportxml>`;(0,cr.ensureSuccess)(await this.dataverse.post("/PublishXml",{ParameterXml:n}),this.dataverse.apiUrl("/PublishXml"))}}createAlternateKey(t,r){return(0,Dt.createAlternateKey)(this.dataverse,t,r)}deleteAlternateKey(t,r){return(0,Dt.deleteAlternateKey)(this.dataverse,t,r)}createRelationship(t){let r=t.type==="ManyToMany"?[t.entity1,t.entity2]:[t.referencedEntity,t.referencingEntity];return this.schemaWrite(r,()=>(0,Dt.createRelationship)(this.dataverse,t))}deleteRelationship(t){return this.schemaWrite(void 0,()=>(0,Dt.deleteRelationship)(this.dataverse,t))}createGlobalOptionSet(t){return(0,Dt.createGlobalOptionSet)(this.dataverse,t)}deleteGlobalOptionSet(t){return(0,Dt.deleteGlobalOptionSet)(this.dataverse,t)}deleteTable(t){return this.schemaWrite(void 0,()=>(0,Dt.deleteTable)(this.dataverse,t))}createSecurityRole(t){return(0,pc.createSecurityRole)(this.dataverse,t)}createPersonaRole(t){return(0,pc.createPersonaRole)(this.dataverse,t)}deleteSecurityRole(t){return(0,pc.deleteSecurityRole)(this.dataverse,t)}addEntityPrivilegesToRole(t,r){return(0,pc.addEntityPrivilegesToRole)(this.dataverse,t,r)}getEntityPrivileges(t){return(0,pc.getEntityPrivileges)(this.dataverse,t)}createRecord(t,r){return(0,zi.createRecord)(this.dataverse,t,r)}createRecordsBulk(t,r){return(0,zi.createRecordsBulk)(this.dataverse,t,r)}updateRecord(t,r,n){return(0,zi.updateRecord)(this.dataverse,t,r,n)}upsertRecord(t,r,n){return(0,zi.upsertRecord)(this.dataverse,t,r,n)}deleteRecord(t,r){return(0,zi.deleteRecord)(this.dataverse,t,r)}getRecord(t,r,n){return(0,zi.getRecord)(this.dataverse,t,r,n)}queryRecords(t,r){return(0,zi.queryRecords)(this.dataverse,t,r)}seedRecordGraph(t,r){return(0,Hoe.seedRecordGraph)(this.dataverse,t,r)}resolveArtifact(t,r){return(0,HF.resolveArtifact)(this.dataverse,t,r)}findArtifact(t,r){return(0,HF.findArtifact)(this.dataverse,t,r)}async deleteAppCascade(t,r){await this.workspace.ensureReady();let n=await(0,Goe.deleteAppCascade)(this.dataverse,t,r),i=(0,Pa.normalizeGuid)(t,"appModuleId");return await this.workspace.readArtifact("app",i)&&await this.workspace.deleteArtifact("app",i),n}associateRecords(t,r,n){return(0,zi.associateRecords)(this.dataverse,t,r,n)}disassociateRecords(t,r,n,i){return(0,zi.disassociateRecords)(this.dataverse,t,r,n,i)}createWebResource(t){return(0,Jp.createWebResource)(this.dataverse,t)}updateWebResource(t,r){return(0,Jp.updateWebResource)(this.dataverse,t,r)}getWebResource(t){return(0,Jp.getWebResource)(this.dataverse,t)}deleteWebResource(t){return(0,Jp.deleteWebResource)(this.dataverse,t)}getAppSettings(t){return(0,fl.readAppSettings)(this.dataverse,t)}setAppSetting(t,r,n){return(0,fl.setAppSetting)(this.dataverse,t,r,n)}setHeaderAndNavigationRefresh(t,r){if(typeof r!="boolean")throw new Z.ValidationError("app",t,[{pointer:"/headerAndNavigationRefresh",rule:qoe.HEADER_NAV_BOOLEAN_RULE,message:`enabled must be a boolean, got ${typeof r}`}]);return(0,fl.setAppSetting)(this.dataverse,t,fl.HEADER_AND_NAVIGATION_REFRESH,r?fl.APP_SETTING_ON:fl.APP_SETTING_OFF)}getSolution(t){return(0,Yt.getSolution)(this.dataverse,t)}createPublisher(t){return(0,Yt.createPublisher)(this.dataverse,t)}createSolution(t){return(0,Yt.createSolution)(this.dataverse,t)}setSolutionVersion(t,r){return(0,Yt.setSolutionVersion)(this.dataverse,t,r)}addSolutionComponent(t){return(0,Yt.addSolutionComponent)(this.dataverse,t)}removeSolutionComponent(t,r,n){return(0,Yt.removeSolutionComponent)(this.dataverse,t,r,n)}exportSolution(t){return(0,Yt.exportSolution)(this.dataverse,t)}importSolution(t){return this.schemaWrite(void 0,()=>(0,Yt.importSolution)(this.dataverse,t))}getDeploymentSettingsTemplate(t){return(0,Yt.getDeploymentSettingsTemplate)(this.dataverse,t)}deleteSolution(t){return this.schemaWrite(void 0,()=>(0,Yt.deleteSolution)(this.dataverse,t))}async getArtifact(t,r){return this.withArtifactLock(t,r,async()=>{let{artifact:n,meta:i}=await this.readWhole(t,r);return await this.acknowledgeRefresh(t,r,i),n})}async getArtifactUnlocked(t,r){return this.readRaw(t,r)}async readWhole(t,r){let{meta:n}=await this.revalidate(t,r);return{artifact:await this.readLocal(t,r),meta:n}}async acknowledgeRefresh(t,r,n){var i,o,a;let s=this.artifactKey(t,r),l=n===void 0?await this.versions.getMeta(t,r):n;this.baselineObserved.has(s)||this.baselineObserved.set(s,(i=l?.observedGeneration)!==null&&i!==void 0?i:0);let u=(o=l?.refreshGeneration)!==null&&o!==void 0?o:0;this.raiseGenerationHighWater(s,u),l&&u!==((a=l.observedGeneration)!==null&&a!==void 0?a:0)&&await this.versions.storeMeta(t,r,{...l,observedGeneration:u},l),this.observedGenerations.set(s,u)}raiseGenerationHighWater(t,r){var n;r>((n=this.generationHighWater.get(t))!==null&&n!==void 0?n:0)&&this.generationHighWater.set(t,r)}async observedAtInvocation(t,r,n){var i,o;if(n!==void 0)return n;let a=this.baselineObserved.get(this.artifactKey(t,r));return a!==void 0?a:(o=(i=await this.versions.getMeta(t,r))===null||i===void 0?void 0:i.observedGeneration)!==null&&o!==void 0?o:0}artifactKey(t,r){return`${t}\0${(0,eM.canonicalArtifactId)(r)}`}nextRefreshGeneration(t,r,n){var i,o,a;let s=this.artifactKey(t,r),l=Math.max((i=n?.refreshGeneration)!==null&&i!==void 0?i:0,(o=n?.observedGeneration)!==null&&o!==void 0?o:0,(a=this.generationHighWater.get(s))!==null&&a!==void 0?a:0)+1;return this.raiseGenerationHighWater(s,l),l}async readRaw(t,r){return await this.revalidateIfStale(t,r),this.readLocal(t,r)}async readForMutation(t,r,n,i){var o,a;let s=await this.observedAtInvocation(t,r,i);if(((a=(o=await this.versions.getMeta(t,r))===null||o===void 0?void 0:o.refreshGeneration)!==null&&a!==void 0?a:0)>s)throw new Z.StaleArtifactError(t,r,n,"pushed");if(await this.revalidateIfStale(t,r)==="refreshed-changed")throw new Z.StaleArtifactError(t,r,n);return this.readLocal(t,r)}async readLocal(t,r){let n=await this.workspace.readArtifact(t,r);if(!n)throw new Z.ArtifactNotFoundError(t,r);return n}async revalidateIfStale(t,r){return(await this.revalidate(t,r)).outcome}async revalidate(t,r){let n=await this.versions.getMeta(t,r);if(!n)return{outcome:"skipped",meta:null};let i=n.fetchedAt?Date.parse(n.fetchedAt):NaN,o=Date.now()-i;if(!Number.isNaN(i)&&this.cacheStalenessMs>0&&o<=this.cacheStalenessMs)return{outcome:"fresh",meta:n};if(await this.versions.isDirty(t,r,n))return{outcome:"skipped",meta:n};let a=await this.workspace.readArtifact(t,r);await this.fetchArtifactUnlocked(t,r);let s=await this.workspace.readArtifact(t,r);return{outcome:(0,gn.deepEqual)(a,s)?"refreshed-unchanged":"refreshed-changed"}}async queryTree(t,r,n){return this.withArtifactLock(t,r,async()=>{let{artifact:i,meta:o}=await this.readWhole(t,r),a=hn.JsonPointer.resolve(i,n);if(a===void 0)throw new Z.PathNotFoundError(t,r,n);return n===""&&await this.acknowledgeRefresh(t,r,o),a})}async findElements(t,r,n){return this.withArtifactLock(t,r,async()=>(0,xoe.findElements)(await this.getArtifactUnlocked(t,r),n))}async withDirtyFlags(t){let r=[];for(let n of t)r.push({...n,isDirty:await this.versions.isDirty(n.type,n.id)});return r}async listArtifacts(t,r){return this.withDirtyFlags(await this.workspace.listArtifacts(t,r))}async getEntityMetadata(t){let r=await this.readCachedEntityMetadata(t);if(!r)throw new Z.ArtifactNotFoundError("entityMetadata",t);return r}async getFieldMetadata(t,r){let i=(await this.getEntityMetadata(t)).attributes.find(o=>o.logicalName===r);if(!i)throw new Z.PathNotFoundError("entityMetadata",t,r);return i}async updateElement(t,r,n,i){let o=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let a=await this.readForMutation(t,r,n,o),s=hn.JsonPointer.resolve(a,n);if(s===void 0)throw new Z.PathNotFoundError(t,r,n);let l=ji(s)&&ji(i)?{...s,...i}:i;return hn.JsonPointer.set(a,n,(0,ui.cloneJson)(l)),this.assertStructurallyValid(t,r,a,n),await this.workspace.writeArtifact(t,r,a),this.getArtifactUnlocked(t,r)})}async addElement(t,r,n,i,o){let a=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let s=await this.readForMutation(t,r,n,a),l=hn.JsonPointer.resolve(s,n);if(l===void 0)throw new Z.PathNotFoundError(t,r,n);if(!Array.isArray(l)){if(!ji(l)||!ji(i))throw new Z.ValidationError(t,r,n,"parent must be an array, or an object with an object of properties to add");if(o?.position!==void 0)throw new Z.ValidationError(t,r,n,"position is not supported for an object parent");let d={};for(let f of Object.keys(i)){if(f==="id")throw new Z.ValidationError(t,r,n,"refusing to write 'id' \u2014 that re-keys the node rather than adding a property");let p=(0,ui.cloneJson)(i[f]),m=(0,Yp.isValueMapKey)(f)||(0,Yp.pointerTouchesValueMap)(n);d[f]=m?p:Array.isArray(p)?p.map(h=>ji(h)?this.assignMissingIds(t,h):h):ji(p)?this.assignMissingIds(t,p):p}for(let f of Object.keys(d))hn.JsonPointer.set(s,hn.JsonPointer.append(n,f),d[f]);return this.assertStructurallyValid(t,r,s,n),await this.workspace.writeArtifact(t,r,s),this.getArtifactUnlocked(t,r)}let u=(0,Yp.pointerTouchesValueMap)(n)?(0,ui.cloneJson)(i):this.assignMissingIds(t,(0,ui.cloneJson)(i)),c=uae(l,o?.position);return l.splice(c,0,u),this.assertStructurallyValid(t,r,s,n),await this.workspace.writeArtifact(t,r,s),this.getArtifactUnlocked(t,r)})}async moveElement(t,r,n,i,o){let a=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{var s;let l=await this.readForMutation(t,r,n,a),u=hn.JsonPointer.resolve(l,n);if(u===void 0)throw new Z.PathNotFoundError(t,r,n);let c=hn.JsonPointer.resolve(l,i);if(c===void 0)throw new Z.PathNotFoundError(t,r,i);if(!Array.isArray(c))throw new Z.ValidationError(t,r,i,"move target must be an array");if(i===n||i.startsWith(`${n}/`))throw new Z.ValidationError(t,r,i,"cannot move an element into its own subtree");hn.JsonPointer.remove(l,n);let d=(s=o?.index)!==null&&s!==void 0?s:c.length;c.splice(Math.max(0,Math.min(d,c.length)),0,u),ZF(c);let f=hn.JsonPointer.resolve(l,XF(n));return Array.isArray(f)&&f!==c&&ZF(f),this.assertStructurallyValid(t,r,l,i),await this.workspace.writeArtifact(t,r,l),this.getArtifactUnlocked(t,r)})}async removeElement(t,r,n){let i=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let o=await this.readForMutation(t,r,n,i);if(hn.JsonPointer.resolve(o,n)===void 0)throw new Z.PathNotFoundError(t,r,n);return hn.JsonPointer.remove(o,n),this.assertStructurallyValid(t,r,o,XF(n)),await this.workspace.writeArtifact(t,r,o),this.getArtifactUnlocked(t,r)})}assertStructurallyValid(t,r,n,i){var o,a,s;let l=this.registrations.get(t),u=(s=(a=l==null?void 0:(o=l.adapter).validate)===null||a===void 0?void 0:a.call(o,n,i))!==null&&s!==void 0?s:[];if(u.length>0)throw new Z.ValidationError(t,r,u)}retrieveSetting(t,r){return(0,pl.retrieveSetting)(this.dataverse,t,r)}saveSettingValue(t,r,n){return(0,pl.saveSettingValue)(this.dataverse,t,r,n)}getAiReadiness(t){return(0,pl.getAiReadiness)(this.dataverse,t)}setAppAiFeatures(t,r,n){return(0,pl.setAppAiFeatures)(this.dataverse,t,r,n)}configureRowSummary(t,r){return(0,pl.configureRowSummary)(this.dataverse,t,r)}removeRowSummary(t){return(0,pl.removeRowSummary)(this.dataverse,t)}async enrichDefaultViews(t,r,n={}){let i=await(0,Koe.findDefaultViews)(this.dataverse,t,{excludeViewIds:n.excludeViewIds}),o=n.publish===!1,a=[],s=[],l=()=>({updated:[...a],results:[...s],pendingPublish:a.length>0?[{scope:(0,GF.boundEntityPublishScope)({entityLogicalName:t}),artifacts:a.map(c=>({type:"view",id:c}))}]:[]}),u;try{for(let c of i){await this.fetchArtifact("view",c.id),await this.updateElement("view",c.id,"/columns",r),u=c.id;let d=await this.pushArtifact("view",c.id);u=void 0,s.push(d),d.saved&&a.push(c.id)}}catch(c){throw u&&Yoe(c)&&a.push(u),o?(0,Z.withPartialEnrichment)(c,l()):c}if(o)return l();if(a.length){let c=await this.publishArtifact("view",a[0]);if(c.publish.kind==="failed")throw new Z.SdkError("ENRICH_DEFAULT_VIEWS_PUBLISH_FAILED",`enrichDefaultViews: ${a.length} view(s) on '${t}' were saved but the publish FAILED, so none of them is live (${c.publish.error.message}). Re-publish the entity to make them visible; the saves themselves are unaffected.`)}return{updated:a}}async createArtifact(t,r){let n=this.requireRegistration(t,"createArtifact"),i=n.adapter.assignMissingIds(n.adapter.createDefault(r)),o=i.id;if(!o)throw new Z.ValidationError(t,"(new)","/id","created artifact must have an id");return this.withArtifactLock(t,o,async()=>(await this.workspace.writeArtifact(t,o,i),(0,ui.cloneJson)(i)))}async deleteArtifact(t,r){return this.withArtifactLock(t,r,async()=>{await this.workspace.deleteArtifact(t,r)})}async deleteRemoteArtifact(t,r){return this.withArtifactLock(t,r,async()=>{let n=this.requireRegistration(t,"deleteRemoteArtifact");await this.workspace.ensureReady(),await n.api.delete(this.dataverse,r),await this.workspace.readArtifact(t,r)&&await this.workspace.deleteArtifact(t,r)})}async publishArtifact(t,r,n){let{result:i,siblings:o}=await this.withArtifactLock(t,r,()=>this.publishArtifactUnlocked(t,r,n));for(let a of o)await this.withArtifactLock(a.type,a.id,()=>this.adoptBracket(a));return i}async publishArtifacts(t,r){var n,i;let o=new Map;for(let m of t){let h=this.artifactKey(m.type,m.id);o.has(h)||o.set(h,{type:m.type,id:m.id})}let a=[];for(let[m,h]of o)a.push(await this.withArtifactLock(h.type,h.id,()=>this.preparePublish(m,h.type,h.id)));let s=new Set(o.keys()),l=[],u=new Set;for(let m of a){let h=((n=m.scope)===null||n===void 0?void 0:n.envelope)==="entity"?(i=m.scope.entityLogicalName)===null||i===void 0?void 0:i.toLowerCase():void 0;m.scope&&h&&!u.has(h)&&(u.add(h),l.push(m.scope))}let c=await this.captureSiblings(l,s),d=rae(a),f;if(d)try{await(0,GF.publishXml)(this.dataverse,d)}catch(m){f=Po(m)}let p=new Map;for(let m of a)p.set(m.key,await this.withArtifactLock(m.type,m.id,()=>this.settlePublish(m,f,r)));for(let m of c)await this.withArtifactLock(m.type,m.id,()=>this.adoptBracket(m));return t.map(m=>({...p.get(this.artifactKey(m.type,m.id))}))}async preparePublish(t,r,n){var i;let o=await this.readRaw(r,n),a=this.registrations.get(r);if(!a?.publish)return{key:t,type:r,id:n,artifact:o,notApplicable:!0};let s=(i=a.publishScope)===null||i===void 0?void 0:i.call(a,n,o);if(!s||!tae.has(s.envelope))throw new Z.InvalidArgumentError(`publishArtifacts: ${r} '${n}' publishes through ${s?`a '${s.envelope}'`:"no declared"} scope, which one PublishXml envelope cannot carry. Publish it with publishArtifact.`);let l=a.rebaselineAfterPublish==="bracket"?await this.captureBracket(a,r,n):void 0;return{key:t,type:r,id:n,artifact:o,reg:a,scope:s,...l?{own:l}:{}}}async settlePublish(t,r,n){let{type:i,id:o}=t;if(t.notApplicable||!t.reg)return{type:i,id:o,shipped:!1,publish:{kind:"notApplicable"}};let a=t.scope?{publishScope:t.scope}:{};if(t.reg.rebaselineAfterPublish==="snapshot"&&await this.rebaselineAfterPublish(t.reg,i,o),t.own&&await this.adoptBracket(t.own),r)return{type:i,id:o,shipped:!1,publish:{kind:"failed",error:r},...a};if(!n?.verify)return{type:i,id:o,shipped:!1,publish:{kind:"submitted"},...a};let s=await this.workspace.readArtifact(i,o).catch(()=>null);if(!s||!(0,gn.deepEqual)(s,t.artifact))return{type:i,id:o,shipped:!1,publish:{kind:"unverifiable",reason:`the local ${i} was ${s?"edited":"deleted"} while the publish was in flight, so what shipped cannot be told from what is local now; verify it with publishArtifact`},...a};let l=await this.verifyPublished(i,o,t.artifact);return{type:i,id:o,shipped:l.kind==="verified",publish:l,...a}}async publishArtifactUnlocked(t,r,n){var i;let o=await this.readRaw(t,r),a=this.registrations.get(t);if(!a?.publish)return{result:{type:t,id:r,shipped:!1,publish:{kind:"notApplicable"}},siblings:[]};let s=(i=a.publishScope)===null||i===void 0?void 0:i.call(a,r,o),l=a.rebaselineAfterPublish==="bracket"?await this.captureBracket(a,t,r):void 0,u=s?await this.captureSiblings([s],new Set([this.artifactKey(t,r)])):[];try{await a.publish(this.dataverse,r,o)}catch(d){return{result:{type:t,id:r,shipped:!1,publish:{kind:"failed",error:Po(d)},...s?{publishScope:s}:{}},siblings:[]}}if(a.rebaselineAfterPublish==="snapshot"&&await this.rebaselineAfterPublish(a,t,r),l&&await this.adoptBracket(l),!n?.verify)return{result:{type:t,id:r,shipped:!1,publish:{kind:"submitted"},...s?{publishScope:s}:{}},siblings:u};let c=await this.verifyPublished(t,r,o);return{result:{type:t,id:r,shipped:c.kind==="verified",publish:c,...s?{publishScope:s}:{}},siblings:u}}async captureBracket(t,r,n){try{let i=await this.versions.getMeta(r,n),o=i?.etag;if(!(0,cr.isVersionToken)(o)||!t.api.readContentThenToken)return;let{raw:a,etag:s,siblingEtags:l}=await t.api.readContentThenToken(this.dataverse,n),u=i?.siblingEtags;return s!==o||!sae(u,l)?void 0:{type:r,id:n,reg:t,heldEtag:o,...u?{heldSiblings:u}:{},content:this.bracketContent(t,a)}}catch{return}}async captureSiblings(t,r){var n,i,o;let a=new Map;for(let u of t){let c=u.envelope==="entity"?(n=u.entityLogicalName)===null||n===void 0?void 0:n.toLowerCase():void 0;c&&!a.has(c)&&a.set(c,[])}if(a.size===0)return[];let s;try{s=await this.workspace.listArtifacts()}catch{return[]}for(let u of s){let c=this.registrations.get(u.type);if(!(r.has(this.artifactKey(u.type,u.id))||c?.rebaselineAfterPublish!=="bracket"||!c.publishScope))try{let d=await this.workspace.readArtifact(u.type,u.id),f=d?c.publishScope(u.id,d):void 0,p=f?.envelope==="entity"?(i=f.entityLogicalName)===null||i===void 0?void 0:i.toLowerCase():void 0;p!==void 0&&((o=a.get(p))===null||o===void 0||o.push(u))}catch{continue}}let l=[];for(let u of a.values())for(let c of u){let d=this.registrations.get(c.type),f=d?await this.captureBracket(d,c.type,c.id):void 0;f&&l.push(f)}return l}async adoptBracket(t){var r;try{let n=await this.versions.getMeta(t.type,t.id);if(!n||n.etag!==t.heldEtag||!(0,gn.deepEqual)((r=n.siblingEtags)!==null&&r!==void 0?r:void 0,t.heldSiblings))return;let{raw:i,etag:o,siblingEtags:a}=await t.reg.api.get(this.dataverse,t.id);if(!(0,cr.isVersionToken)(o)||!rM(a,t.heldSiblings)||!nM(a)||!(o!==t.heldEtag||!(0,gn.deepEqual)(a??void 0,t.heldSiblings))||!(0,gn.deepEqual)(this.bracketContent(t.reg,i),t.content))return;await this.versions.storeMeta(t.type,t.id,{...n,etag:o,...t.heldSiblings?{siblingEtags:{...a}}:{},fetchedAt:(0,cr.nowIso)()},n)}catch{}}bracketContent(t,r){var n,i,o;let a=t.adapter.fromApiResponse(r);return(o=(i=(n=t.adapter).baselineContent)===null||i===void 0?void 0:i.call(n,a))!==null&&o!==void 0?o:a}adoptReadBack(t,r){try{return{artifact:t.adapter.fromApiResponse(r)}}catch(n){return{warning:`The write was saved, but the record read back after it could not be read into the local copy (${Po(n).message}). The SDK holds no version for it now, so the next push is refused: re-fetch before editing again.`}}}adoptedAsSent(t,r,n,i){try{let o={...n,...i},a=t.adapter.fromApiResponse(t.adapter.completeAsStored?t.adapter.completeAsStored(o,n):o);return(0,gn.deepEqual)(r,a)}catch{return!1}}async rebaselineAfterPublish(t,r,n){try{let i=await this.versions.getMeta(r,n);if(!i)return;let{raw:o,etag:a,memberEtags:s,siblingEtags:l}=t.api.getForRebaseline?await t.api.getForRebaseline(this.dataverse,n):await t.api.get(this.dataverse,n),u=t.adapter.fromApiResponse(o),c=d=>{var f,p,m;return(m=(p=(f=t.adapter).baselineContent)===null||p===void 0?void 0:p.call(f,d))!==null&&m!==void 0?m:d};if(!a||!(0,gn.deepEqual)(c(i.snapshot),c(u)))return;await this.versions.storeMeta(r,n,{...i,etag:a,fetchedAt:(0,cr.nowIso)(),...s?{memberEtags:s}:{},...l?{siblingEtags:l}:{}},i)}catch{}}async verifyPublished(t,r,n){var i,o,a,s,l;if(t!=="app"){let u=this.registrations.get(t);return u?.api.getPublished?this.verifyPublishedContent(u,t,r,n):{kind:"unverifiable",reason:`published-projection verification is not characterised for '${t}'; the publish was submitted`}}try{let u=`/appmodules(${(0,Pa.normalizeGuid)(r,"id")})${(0,Pa.odataQuery)([["$select","appmoduleid,name,description"]])}`,c=await this.dataverse.get(u);if(c.status>=200&&c.status<300){let d=(i=c.body)!==null&&i!==void 0?i:{},f=n;if(!f)return{kind:"unverifiable",reason:"there is no local copy of the app to compare the published projection with"};let p=[];return((o=f.name)!==null&&o!==void 0?o:"")!==((a=d.name)!==null&&a!==void 0?a:"")&&p.push("name"),((s=f.description)!==null&&s!==void 0?s:"")!==((l=d.description)!==null&&l!==void 0?l:"")&&p.push("description"),p.length>0?{kind:"unverifiable",reason:`the published projection does not yet match the saved app (${p.join(", ")} still differ). PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}:{kind:"verified"}}return{kind:"unverifiable",reason:`the published projection answered HTTP ${c.status}`}}catch(u){return{kind:"unverifiable",reason:Po(u).message}}}async verifyPublishedContent(t,r,n,i){var o,a,s;try{let l=f=>{var p,m,h;return(h=(m=(p=t.adapter).baselineContent)===null||m===void 0?void 0:m.call(p,f))!==null&&h!==void 0?h:f},u=l(i),c=(o=await this.versions.getMeta(r,n))===null||o===void 0?void 0:o.snapshot;if(c===void 0||!(0,gn.deepEqual)(u,l(c)))return{kind:"unverifiable",reason:`the local ${r} holds edits that were never pushed, so no publish could have shipped them \u2014 push, then publish again`};let d=await((s=(a=t.api).getPublished)===null||s===void 0?void 0:s.call(a,this.dataverse,n));return d?(0,gn.deepEqual)(u,l(t.adapter.fromApiResponse(d.raw)))?{kind:"verified"}:{kind:"unverifiable",reason:"the published projection does not show what was pushed. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists"}:{kind:"unverifiable",reason:`the ${r} is not in the published projection yet. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}}catch(l){return{kind:"unverifiable",reason:Po(l).message}}}async pushArtifact(t,r){return this.withArtifactLock(t,r,()=>this.pushArtifactUnlocked(t,r))}async prepareArtifactUnlocked(t,r,n){var i,o;let a=this.requireRegistration(t,"pushArtifact"),s=await this.workspace.readArtifactWithText(t,r);if(!s)throw new Z.ArtifactNotFoundError(t,r);let l=s.artifact,u=s.text,c=(o=(i=a.adapter).normalize)===null||o===void 0?void 0:o.call(i,l);c&&c!==l&&(await this.workspace.writeArtifact(t,r,c),l=c,u=void 0);let d=await this.versions.getMeta(t,r);this.assertLanguageMatches(t,r,d,a),this.assertProjectionMatches(t,r,d);let f=await this.buildMetadataContext(a.adapter,l,d?.snapshot),p=await a.adapter.toApiPayload(l,d?.snapshot,f);return await this.assertSemanticallyComplete(a,t,r,l,d===null,d?.everActivated,n),{type:t,id:r,reg:a,json:l,...u!==void 0?{storedText:u}:{},meta:d,payload:p}}async assertSemanticallyComplete(t,r,n,i,o,a,s){let l=t.adapter.issuesBlockingPush;if(!l)return;let u=i.entityLogicalName,d=(u?await this.columnsForCheck(t,u,i,s):[]).map(p=>({logicalName:p.logicalName,displayName:p.displayName,attributeType:p.attributeType,isCustomAttribute:p.isCustomAttribute,...p.maxLength!==void 0?{maxLength:p.maxLength}:{},...p.options?{options:p.options.map(m=>({value:m.value,label:m.label}))}:{},...p.targets?{targets:p.targets}:{}})),f=l.call(t.adapter,i,d,{isCreate:o,everActivated:a});if(f.length>0)throw new Z.ValidationError(r,n,f)}columnsForCheck(t,r,n,i){var o,a,s;let l=(s=(a=(o=t.adapter).columnsCheckedAtPush)===null||a===void 0?void 0:a.call(o,n))!==null&&s!==void 0?s:[],u=async()=>{let f=await this.readCachedEntityMetadata(r);if(f)return f.attributes;try{return await(0,dl.readCheckColumns)(this.dataverse,r,l)}catch{return[]}};if(!i)return u();let c=[r,...[...new Set(l)].sort()].join("\0"),d=i.get(c);return d||(d=u(),i.set(c,d)),d}async pushArtifactUnlocked(t,r,n){return this.executePrepared(await this.prepareArtifactUnlocked(t,r,n))}async executePrepared(t){var r,n,i,o,a,s,l,u,c;let{type:d,id:f,reg:p,json:m,meta:h,payload:g}=t,b=!1;try{let w;if(h)w=await p.api.update(this.dataverse,f,g,h.etag,h.memberEtags,h.siblingEtags);else{let O=await this.createWithMintedId(p,d,f,g,m);if("adopted"in O)return await this.persistAdoption(d,f,m,O.adopted);w=O.written}b=!0;let E=f;h||(w.serverIdentity&&p.adapter.applyServerIdentity&&p.adapter.applyServerIdentity(m,w.serverIdentity),w.id&&w.id!==f&&(m.id=w.id,await this.workspace.deleteArtifact(d,f),E=w.id));let A=h&&w.readBack!==void 0?this.adoptReadBack(p,w.readBack):void 0,L=A?.artifact?{artifact:A.artifact,baseline:A.artifact}:p.adapter.committed?p.adapter.committed(m,g,{intentPending:w.intentPending===!0}):{artifact:m,baseline:m};await this.workspace.writeArtifact(d,E,L.artifact,h&&E===f?t.storedText:void 0);let R=A?.artifact!==void 0&&!(0,gn.deepEqual)(A.artifact,m),I=R?this.nextRefreshGeneration(d,E,h):(r=h?.refreshGeneration)!==null&&r!==void 0?r:0,D=[...(n=w.warnings)!==null&&n!==void 0?n:[],...A?.warning?[A.warning]:[],...A?.artifact!==void 0&&!this.adoptedAsSent(p,A.artifact,w.readBack,g)?[`Saved, but the server holds something other than what was pushed (another writer saved in between, or the platform rewrote something the SDK does not model \u2014 a label in a language the org does not provision, a hand-written fragment); the local ${d} now holds the server's version. Read it (getArtifact) before the next edit: a mutation whose pointer was derived from the earlier copy is refused (StaleArtifactError).`]:[]];return await this.versions.storeMeta(d,E,{etag:A&&!A.artifact?null:w.etag,...I>0?{refreshGeneration:I,observedGeneration:(i=h?.observedGeneration)!==null&&i!==void 0?i:0}:{},languageCode:this.languageCode,projectionVersion:cl.PROJECTION_VERSION,fetchedAt:(0,cr.nowIso)(),snapshot:(0,ui.cloneJson)(L.baseline),...w.memberEtags?{memberEtags:w.memberEtags}:{},...w.siblingEtags?{siblingEtags:w.siblingEtags}:{}},E===f?h:void 0),{type:d,id:E,saved:!0,shipped:!1,publish:(o=w.publish)!==null&&o!==void 0?o:{kind:"notRequested"},...w.publish&&w.publish.kind!=="notRequested"?(()=>{var O;let $=(O=p.publishScope)===null||O===void 0?void 0:O.call(p,E,m);return $?{publishScope:$}:{}})():{},...R?{refreshed:!0}:{},...D.length>0?{warnings:D}:{}}}catch(w){let E=(0,Z.readPartialTokens)(w);if(E&&h){let A={...(a=h.memberEtags)!==null&&a!==void 0?a:{},...(s=E.memberEtags)!==null&&s!==void 0?s:{}},L={...(l=h.siblingEtags)!==null&&l!==void 0?l:{},...(u=E.siblingEtags)!==null&&u!==void 0?u:{}};await this.versions.storeMeta(d,f,{...h,...Object.keys(A).length>0?{memberEtags:A}:{},...Object.keys(L).length>0?{siblingEtags:L}:{}},h)}if(w instanceof Z.SdkError&&w.code===dr.ALREADY_EXISTS_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===VF.WFOM_API_UNAVAILABLE_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===VF.BUSINESS_RULE_LEFT_DEACTIVATED_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===cr.VERSION_CONFLICT_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:(0,jF.isFailureAfterPrimaryWrite)(w)?w:new Z.VersionConflictError(d,f,(c=h?.etag)!==null&&c!==void 0?c:null,null,w.message)};throw b?Joe(w):w}}assertLanguageMatches(t,r,n,i){if(i?.languageSensitive&&!(n?.languageCode===void 0||n.languageCode===this.languageCode))throw new Z.SdkError("ARTIFACT_LANGUAGE_MISMATCH",`Refusing to push ${t} '${r}': it was fetched with languageCode ${n.languageCode} but this SDK is configured with ${this.languageCode}. Pushing would rewrite labels read in one language as labels in another. Re-fetch with languageCode ${this.languageCode}, or create the SDK with languageCode ${n.languageCode}.`)}assertProjectionMatches(t,r,n){var i;if(n&&n.projectionVersion!==cl.PROJECTION_VERSION)throw new Z.SdkError("ARTIFACT_PROJECTION_STALE",`Refusing to push ${t} '${r}': its workspace copy was produced by projection version ${(i=n.projectionVersion)!==null&&i!==void 0?i:"unknown (pre-versioning)"}, but this SDK produces version ${cl.PROJECTION_VERSION}. The parsers changed in between, so an unedited part of this artifact can no longer be told apart from an edited one and pushing could overwrite server content the caller never touched. Re-fetch it with fetchArtifact('${t}', '${r}') and re-apply any local edits.`)}async createWithMintedId(t,r,n,i,o){try{return{written:await t.api.create(this.dataverse,i,n)}}catch(a){let s=r==="form"?(0,Fv.readPrimaryCreateRefusal)(a):void 0;if(s?.status===404&&await(0,zF.formExistsAtId)(()=>t.api.get(this.dataverse,n),s.sent.formid)){let u=`the platform answered the create with ${a.message} \u2014 this build refuses a replayed create that way \u2014 but a read of that id finds the record`;throw(0,Z.attachCause)(new Z.SdkError(dr.ALREADY_EXISTS_CODE,Bv(r,n,u)+(this.createRecovery==="adoptExact"?` ${QF(iae)}`:"")),a)}if(!(a instanceof Z.SdkError)||a.code!==cr.VERSION_CONFLICT_CODE||(0,jF.isFailureAfterPrimaryWrite)(a))throw a;if(this.createRecovery==="adoptExact"&&s?.status===412){let l=await(0,zF.recoverFormCreate)({client:this.dataverse,read:()=>t.api.get(this.dataverse,n),sent:s.sent,authoredFormType:o.formType,project:u=>t.adapter.fromApiResponse(u)});if("adopted"in l)return{adopted:l.adopted};throw new Z.SdkError(dr.ALREADY_EXISTS_CODE,`${Bv(r,n)} ${QF(l.refused)}`)}throw new Z.SdkError(dr.ALREADY_EXISTS_CODE,Bv(r,n))}}async persistAdoption(t,r,n,i){let{artifact:o,etag:a}=i,s=!(0,gn.deepEqual)(o,n);return await this.versions.storeMeta(t,r,{etag:a,...s?{refreshGeneration:this.nextRefreshGeneration(t,r,null),observedGeneration:0}:{},languageCode:this.languageCode,projectionVersion:cl.PROJECTION_VERSION,fetchedAt:(0,cr.nowIso)(),snapshot:(0,ui.cloneJson)(o)},null),s&&await this.workspace.writeArtifact(t,r,o),{type:t,id:r,saved:!1,adoptedExisting:!0,shipped:!1,publish:{kind:"notRequested"},...s?{refreshed:!0}:{}}}async buildMetadataContext(t,r,n){var i,o,a,s;let l=(o=(i=t.metadataNeeds)===null||i===void 0?void 0:i.call(t,r,n))!==null&&o!==void 0?o:[],u=new Set(l.map(R=>R.entityLogicalName).filter(R=>!!R)),c=new Set(l.filter(R=>R.needsColumnDetail).map(R=>R.entityLogicalName)),d=new Set(l.filter(R=>R.needsColumnDetail||!R.fieldName).map(R=>R.entityLogicalName)),f=R=>l.filter(I=>I.entityLogicalName===R).every(I=>I.fetchRequired===!1),p=new Map,m=new Map;for(let R of u){let I=await this.readCachedEntityMetadata(R);if(I&&c.has(R)&&(I.columnDetailComplete!==!0||!(typeof I.columnDetailVersion=="number"&&I.columnDetailVersion>=dl.COLUMN_DETAIL_VERSION)||I.attributes.some(D=>typeof D.attributeTypeName!="string"))&&(I=null),!I&&!d.has(R)){if(!f(R)){let D=l.filter(O=>O.entityLogicalName===R).map(O=>O.fieldName);try{let O=await(0,dl.readColumnHints)(this.dataverse,R,D);m.set(R,new Map(O.map($=>[$.logicalName,$])))}catch{}}continue}if(!I&&!f(R))try{await this.loadMissedEntityMetadata(R),I=await this.readCachedEntityMetadata(R)}catch{}I&&p.set(R,I)}let h=(R,I)=>{var D,O,$;return(O=(D=p.get(R))===null||D===void 0?void 0:D.attributes.find(K=>K.logicalName===I))!==null&&O!==void 0?O:($=m.get(R))===null||$===void 0?void 0:$.get(I)},g=this.languageCode,w=l.some(R=>{if(!R.needsLabel||!R.fieldName)return!1;let I=h(R.entityLogicalName,R.fieldName);return I?.localizedDisplayName!==void 0&&!I.localizedDisplayName[g]})?await this.readBaseLanguage():void 0,E=!((a=t.needsBaseLanguage)===null||a===void 0)&&a.call(t,r)?await this.readBaseLanguage():void 0,A=(s=t.customControlNeeds)===null||s===void 0?void 0:s.call(t,r,n),L=A&&(A.controls.length>0||A.columns.length>0)?await this.readPcfNeeds(A):void 0;return{resolveField:(R,I)=>{let D=h(R,I);return D?{displayName:lae(D,g,w),attributeType:D.attributeType}:void 0},resolveEntity:R=>p.get(R),loadTypeScript:()=>this.compiler.load(),...E!==void 0?{baseLanguageCode:E}:{},...L?{pcf:L}:{}}}async readPcfNeeds(t){let r=new Map;for(let i of t.controls)r.set(i,await(0,WF.readControlManifest)(this.dataverse,i));let n=new Map;for(let i of t.columns)n.set(i,await(0,WF.readPcfColumn)(this.dataverse,t.entityLogicalName,i,t.requireCreateEligibility?{requireCreateEligibility:!0}:void 0));return{control:i=>r.get(i),column:(i,o)=>i===t.entityLogicalName?n.get(o):void 0}}readBaseLanguage(){if(!this.baseLanguage){let t=(async()=>{var r,n,i;try{let o=await this.dataverse.get("/organizations?$select=languagecode");if(o.status<200||o.status>=300)return;let a=Number((i=(n=(r=o.body)===null||r===void 0?void 0:r.value)===null||n===void 0?void 0:n[0])===null||i===void 0?void 0:i.languagecode);return Number.isInteger(a)&&a>0?a:void 0}catch{return}})();this.baseLanguage=t,t.then(r=>{r===void 0&&this.baseLanguage===t&&(this.baseLanguage=void 0)})}return this.baseLanguage}async pushAll(){let t=await this.getDirtyArtifacts();await this.warmBatchMetadata(t);let r=new Map,n=new Map;for(let o=0;o<t.length;o+=1){let a=t[o];try{await this.withArtifactLock(a.type,a.id,()=>this.prepareArtifactUnlocked(a.type,a.id,r))}catch(s){n.set(o,{type:a.type,id:a.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:Po(s)})}}if(n.size>0)return t.map((o,a)=>{var s;return(s=n.get(a))!==null&&s!==void 0?s:{type:o.type,id:o.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:new Z.SdkError(dr.PUSH_NOT_ATTEMPTED_CODE,`Not attempted: ${n.size} artifact(s) in this batch could not be prepared, so no writes were issued. Fix the reported failures and push again.`)}});let i=[];for(let o of t)try{i.push(await this.withArtifactLock(o.type,o.id,()=>this.pushArtifactUnlocked(o.type,o.id,r)))}catch(a){i.push({type:o.type,id:o.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:Po(a)})}return i}async warmBatchMetadata(t){var r,n,i;let o=new Set;for(let a of t){let s=this.registrations.get(a.type);if(!s)continue;let l;try{l=await this.readLocal(a.type,a.id)}catch{continue}let u=l.entityLogicalName;u&&o.add(u);for(let c of(i=(n=(r=s.adapter).metadataNeeds)===null||n===void 0?void 0:n.call(r,l))!==null&&i!==void 0?i:[])c.entityLogicalName&&o.add(c.entityLogicalName)}for(let a of o)if(!await this.readCachedEntityMetadata(a))try{await this.loadMissedEntityMetadata(a)}catch{}}async getDirtyArtifacts(){return(await this.withDirtyFlags(await this.workspace.listArtifacts())).filter(r=>r.isDirty)}async diffArtifact(t,r){return this.versions.diff(t,r)}assignMissingIds(t,r){let n=this.registrations.get(t);return n?n.adapter.assignMissingIds(r):(0,Yp.assignMissingIds)(r)}async resolveComponentType(t){if(t.genPage)return"genPage";switch(t.componentType){case Yt.SolutionComponentType.SavedQuery:return"view";case Yt.SolutionComponentType.SavedQueryVisualization:return"chart";case Yt.SolutionComponentType.AppModule:return"app";case Yt.SolutionComponentType.Workflow:return this.workflowArtifactType(t);case Yt.SolutionComponentType.SystemForm:return this.systemFormArtifactType(t.objectId);default:return}}async systemFormArtifactType(t){let r=await(0,Kp.readSystemFormType)(this.dataverse,t);if(Number.isNaN(r))throw new Z.SdkError(Uv,`System form '${t}' answered without a readable type, so whether it is a form or a dashboard cannot be told.`);return(0,Kp.systemFormKindOf)(r)}async workflowArtifactType(t){let r=(0,Pa.normalizeGuid)(t.objectId,"workflowId"),n=`/workflows(${r})${(0,Pa.odataQuery)([["$select","category,businessprocesstype"]])}`,o=(0,cr.ensureSuccess)(await this.dataverse.get(n),this.dataverse.apiUrl(n)).body,a=(0,Kp.decodeCode)(o?.category);if(Number.isNaN(a))throw new Z.SdkError(Uv,`Workflow '${r}' answered without a readable category, so its kind cannot be told.`);if(t.workflowCategory=a,a===Xoe)return"businessRule";if(a===Zoe){let s=(0,Kp.decodeCode)(o?.businessprocesstype);if(Number.isNaN(s))throw new Z.SdkError(Uv,`Workflow '${r}' (category 4) answered without a readable businessprocesstype, so whether it is a business process flow or a task flow cannot be told.`);return s===0?"bpf":void 0}}requireRegistration(t,r){let n=this.registrations.get(t);if(!n)throw new Z.NotImplementedError(r,`no adapter registered for artifact type '${t}'`);return n}};dr.MakerSdk=Qp;function aae(e){return new Qp(e)}dr.createMakerSdk=aae;function Po(e){return e instanceof Error?e:new Error(String(e))}function rM(e,t){let r=Object.keys(e??{}),n=Object.keys(t??{});return r.length===n.length&&r.every(i=>Object.prototype.hasOwnProperty.call(t??{},i))}function nM(e){return Object.values(e??{}).every(cr.isVersionToken)}function sae(e,t){return rM(e,t)&&nM(e)&&Object.keys(e??{}).every(r=>t?.[r]===e?.[r])}function QF(e){return`createRecovery 'adoptExact' did not adopt it: ${e}.`}function Bv(e,t,r){return`Cannot create ${e} '${t}': a record already exists at that id${r?` (${r})`:""}, so an earlier push of this artifact committed before its local version metadata was saved. No duplicate was created. Run fetchArtifact('${e}', '${t}', { overwrite: true }) to adopt the existing record's identity, etag and snapshot \u2014 the overwrite is required, because this local copy has never been pushed, so a plain fetch keeps it and adopts nothing; it REPLACES the local copy, so keep any outstanding local changes aside first \u2014 then re-apply them and push again: a conditional update, provided the adopted record is complete. If the earlier push committed only PART of a multi-row artifact (e.g. an app's appmodule without its sitemap), that update refuses, naming what is missing and how to remove the partial record. This is not done automatically because the only recovery available here would be an UNCONDITIONAL overwrite, which would destroy any edit made to the record in the meantime.`}function lae(e,t,r){let n=e.localizedDisplayName;return n?.[t]||(r===void 0?void 0:n?.[r])||e.displayName}function ji(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function XF(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function ZF(e){e.length===0||!e.every(t=>ji(t)&&typeof t.order=="number")||e.forEach((t,r)=>{t.order=r})}function uae(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=>ji(i)&&i.id===t.before);return n<0?e.length:n}let r=e.findIndex(n=>ji(n)&&n.id===t.after);return r<0?e.length:r+1}});var oM=v(Xp=>{"use strict";Object.defineProperty(Xp,"__esModule",{value:!0});Xp.ARTIFACT_TYPES=void 0;Xp.ARTIFACT_TYPES=["form","view","businessRule","app","command","chart","dashboard","genPage","bpf"]});var sM=v(aM=>{"use strict";Object.defineProperty(aM,"__esModule",{value:!0})});var uM=v(lM=>{"use strict";Object.defineProperty(lM,"__esModule",{value:!0})});var dM=v(cM=>{"use strict";Object.defineProperty(cM,"__esModule",{value:!0})});var pM=v(fM=>{"use strict";Object.defineProperty(fM,"__esModule",{value:!0})});var hM=v(mM=>{"use strict";Object.defineProperty(mM,"__esModule",{value:!0})});var yM=v(gM=>{"use strict";Object.defineProperty(gM,"__esModule",{value:!0})});var vM=v(bM=>{"use strict";Object.defineProperty(bM,"__esModule",{value:!0})});var CM=v(wM=>{"use strict";Object.defineProperty(wM,"__esModule",{value:!0})});var AM=v(EM=>{"use strict";Object.defineProperty(EM,"__esModule",{value:!0})});var NM=v(SM=>{"use strict";Object.defineProperty(SM,"__esModule",{value:!0})});var TM=v(_M=>{"use strict";Object.defineProperty(_M,"__esModule",{value:!0})});var IM=v(DM=>{"use strict";Object.defineProperty(DM,"__esModule",{value:!0})});var PM=v(OM=>{"use strict";Object.defineProperty(OM,"__esModule",{value:!0})});var LM=v(RM=>{"use strict";Object.defineProperty(RM,"__esModule",{value:!0})});var xM=v(kM=>{"use strict";Object.defineProperty(kM,"__esModule",{value:!0})});var FM=v($M=>{"use strict";Object.defineProperty($M,"__esModule",{value:!0})});var UM=v(MM=>{"use strict";Object.defineProperty(MM,"__esModule",{value:!0})});var qM=v(BM=>{"use strict";Object.defineProperty(BM,"__esModule",{value:!0})});var GM=v(VM=>{"use strict";Object.defineProperty(VM,"__esModule",{value:!0})});var zM=v(WM=>{"use strict";Object.defineProperty(WM,"__esModule",{value:!0})});var HM=v(jM=>{"use strict";Object.defineProperty(jM,"__esModule",{value:!0})});var JM=v(ce=>{"use strict";var cae=ce&&ce.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),qe=ce&&ce.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&cae(t,e,r)};Object.defineProperty(ce,"__esModule",{value:!0});ce.projectConnectorOperationSchema=ce.projectConnectorOperations=ce.createMakerSdk=void 0;var dae=iM();Object.defineProperty(ce,"createMakerSdk",{enumerable:!0,get:function(){return dae.createMakerSdk}});qe(oM(),ce);qe(sM(),ce);qe(uM(),ce);qe(dM(),ce);qe(pM(),ce);qe(hM(),ce);qe(yM(),ce);qe(vM(),ce);qe(CM(),ce);qe(AM(),ce);qe(NM(),ce);qe(TM(),ce);qe(IM(),ce);qe(PM(),ce);qe(LM(),ce);qe(Pd(),ce);qe(xM(),ce);qe(FM(),ce);qe(UM(),ce);qe(qM(),ce);qe(GM(),ce);qe(zM(),ce);qe(HM(),ce);qe(Q(),ce);var KM=Al();Object.defineProperty(ce,"projectConnectorOperations",{enumerable:!0,get:function(){return KM.projectConnectorOperations}});Object.defineProperty(ce,"projectConnectorOperationSchema",{enumerable:!0,get:function(){return KM.projectConnectorOperationSchema}})});var Vv=v(ci=>{"use strict";var fae=ci&&ci.__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]})),pae=ci&&ci.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),XM=ci&&ci.__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)&&fae(t,e,r);return pae(t,e),t};Object.defineProperty(ci,"__esModule",{value:!0});ci.NodeFileSystemStorage=void 0;var mt=XM(require("fs")),Qt=XM(require("path")),YM=Q(),QM=Tm();async function ZM(e){let t;try{t=await mt.promises.lstat(e)}catch{return}if(t.isSymbolicLink()){try{await mt.promises.unlink(e)}catch{await mt.promises.rmdir(e)}return}if(!t.isDirectory()){await mt.promises.unlink(e);return}for(let r of await mt.promises.readdir(e))await ZM(Qt.join(e,r));await mt.promises.rmdir(e)}var qv=class{constructor(t){this.root=t}getRoot(){return this.root}pathFor(t,r=!0){return this.assertWithinRoot(Qt.join(this.root,...t),r)}realPathThroughNearestAncestor(t){let r=t,n=[];for(;!mt.existsSync(r);){n.unshift(Qt.basename(r));let i=Qt.dirname(r);if(i===r)return Qt.resolve(t);r=i}return Qt.resolve(mt.realpathSync(r),...n)}assertWithinRoot(t,r){let n=Qt.resolve(this.root),i=Qt.resolve(t);if(i!==n&&!i.startsWith(n+Qt.sep))throw new YM.PathTraversalError(t,this.root);let o=this.realPathThroughNearestAncestor(n),a=r?this.realPathThroughNearestAncestor(i):Qt.resolve(this.realPathThroughNearestAncestor(Qt.dirname(i)),Qt.basename(i));if(a!==o&&!a.startsWith(o+Qt.sep))throw new YM.PathTraversalError(t,this.root);return i}async readText(t){let r=this.pathFor(t);if(!mt.existsSync(r))return null;try{return await(0,QM.retryTransientIoAsync)(()=>mt.promises.readFile(r,"utf8"))}catch(n){if(n.code==="ENOENT")return null;throw n}}async writeTextAtomic(t,r){let n=this.pathFor(t),i=Qt.dirname(n);await mt.promises.mkdir(i,{recursive:!0});let o=Qt.join(i,`.${Qt.basename(n)}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);try{await mt.promises.writeFile(o,r,"utf8"),await(0,QM.retryTransientIoAsync)(()=>mt.promises.rename(o,n))}catch(a){try{mt.existsSync(o)&&await mt.promises.unlink(o)}catch{}throw a}}async deleteFile(t){let r=this.pathFor(t);mt.existsSync(r)&&await mt.promises.unlink(r)}async deleteByPrefix(t){await ZM(this.pathFor(t,!1))}async ensureContainer(t){await mt.promises.mkdir(this.pathFor(t),{recursive:!0})}async exists(t){return mt.existsSync(this.pathFor(t))}};ci.NodeFileSystemStorage=qv});var eU=v(Lr=>{"use strict";var mae=Lr&&Lr.__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]})),hae=Lr&&Lr.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),gae=Lr&&Lr.__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)&&mae(t,e,r);return hae(t,e),t};Object.defineProperty(Lr,"__esModule",{value:!0});Lr.loadNodeTypeScript=Lr.createNodeWorkspaceStorage=Lr.NodeFileSystemStorage=void 0;var yae=Vv(),bae=Vv();Object.defineProperty(Lr,"NodeFileSystemStorage",{enumerable:!0,get:function(){return bae.NodeFileSystemStorage}});function vae(e){return new yae.NodeFileSystemStorage(e)}Lr.createNodeWorkspaceStorage=vae;async function wae(){return await Promise.resolve().then(()=>gae(require("typescript")))}Lr.loadNodeTypeScript=wae});var Hi={};module.exports=kr(Hi);Ki(Hi,we(JM()),module.exports);Ki(Hi,we(eU()),module.exports);+`),a=e.apiUrl("/$batch"),s=i.map((m,p)=>String(p+1)),l;try{l=await(0,ge.resendWhile)(m=>Zz(m,s),()=>e.postBatch(o,r),ge.DEADLOCK_BACKOFF_MS)}catch(m){return{kind:"unknown",error:m}}let u=FT(l,a);if(u.kind!=="deleted")return u;let c=`app '${t[0].path}'`;if(typeof l.body!="string"||l.body.length===0)return{kind:"unknown",error:new _e.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`)};let d=(0,PT.parseChangeSetStatuses)(l.body,s);if(d===void 0)return{kind:"unknown",error:new _e.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`)};let f=d.find(m=>m<200||m>=300);return f!==void 0?{kind:"refused",error:new _e.ConnectionError(a,f,`atomic delete of ${c} was rolled back: the change set reported HTTP ${f}`)}:d.length!==i.length?{kind:"unknown",error:new _e.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response reported ${d.length} operation result(s), expected exactly ${i.length}`)}:{kind:"deleted"}}async function vf(e,t){try{let r=await e.get(`/sitemaps(${t})?$select=sitemapid`);return r.status<200||r.status>=300?null:(0,ge.readEtag)(r)}catch{return null}}async function TT(e,t){let r=`/appmodules(${t})?$select=appmoduleid`,n=await e.get(r);if(n.status!==404)return(0,ge.ensureSuccess)(n,e.apiUrl(r)),(0,ge.readEtag)(n)}async function C0(e,t,r,n){if(!n)return null;let i=await vf(e,t);if(!i)return null;try{let o=await e.get(Cf(t,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"));if(o.status<200||o.status>=300)return null;let a=_u(o);return!a||!Ef(a.sitemapid,t)||a.sitemapnameunique!==n||a.sitemapxml!==r.sitemapxml||a.sitemapname!==r.sitemapname?null:i}catch{return null}}function UT(e){return e>=400&&e<500&&e!==408&&e!==429}function DT(e,t,r){if(!e)throw new _e.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 BT(e,t,r){let n=`/appmodules(${t})`,i=r.draft?void 0:DT(r.appEtag,t,"app");if(!r.sitemapId){if(r.draft){(0,ge.ensureSuccess)(await(0,ge.resendAppSearchIndexRace)(()=>e.delete(n)),e.apiUrl(n));return}await ej(e,n,i);return}if(!e.supportsAtomicBatch)throw new _e.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 Xz(e,[{path:n,etag:i},{path:`/sitemaps(${r.sitemapId})`,etag:DT(r.sitemapEtag,t,"sitemap")}])}async function ej(e,t,r){(0,ge.ensureSuccess)(await(0,ge.resendAppSearchIndexRace)(()=>e.delete(t,{headers:{"If-Match":r}})),e.apiUrl(t))}async function IT(e,t){if(!/GenPageId/i.test(t))return;let r;try{r=[...new Set((0,Rz.collectGenPageIds)(t))]}catch(i){throw new _e.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 (${Gi(i)}).`)}if(r.length===0)return;let n=await(0,Lz.findMissingGenPages)(e,r,"sitemap generative-page preflight");if(n.length>0)throw new _e.SdkError("SITEMAP_TARGET_NOT_FOUND",`Refusing to push the app: its sitemap navigates to generative page(s) ${n.map(i=>`'${i}'`).join(", ")} that do not exist in this environment. Push the page before the app that links to it.`)}function tj(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")}async function OT(e,t,r){var n;let i=(0,Ae.normalizeGuid)(t,"id"),o=r==="tokens-first",a=o?await TT(e,i):null,s=S0(A0,i),l=(0,ge.ensureSuccess)(await e.get(s),e.apiUrl(s)),u=(n=_u(l))!==null&&n!==void 0?n:{};if(!u.appmoduleid)throw new _e.SdkError("APP_NOT_FOUND",`App '${i}' was not found (checked the unpublished-aware projection, which includes drafts).`);let c=await RT(e,u.uniquename),d=c?(0,Ae.normalizeGuid)(c,"sitemapId"):void 0,f=null;if(d){o&&(f=await vf(e,d));let p=Cf(d,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"),h=(0,ge.ensureSuccess)(await e.get(p),e.apiUrl(p)),g=_u(h),b=w=>{throw new _e.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': its sitemap '${d}' was located by unique name, but ${w}, so the sitemap cannot be read. Persisting the app without it would misreport it as having no sitemap, or write an empty one over its navigation. Retry.`)};if(!g)return b("the by-id read returned no row");if(g.sitemapnameunique!==u.uniquename)throw new _e.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': sitemap '${d}' now carries sitemapnameunique '${String(g.sitemapnameunique)}', not '${String(u.uniquename)}', so it is no longer this app's sitemap. Retry.`);if(!Ef(g.sitemapid,d))return b(`the by-id read returned a row carrying sitemapid '${String(g.sitemapid)}'`);if(typeof g.sitemapxml!="string")return b("the by-id read returned no sitemapxml");u.$sitemap=g,o||(f=await vf(e,d))}o||(a=await TT(e,i));let m=a??Fz(u);return{raw:u,etag:f,...u.appmoduleid?{siblingEtags:{[(0,Ae.normalizeGuid)(u.appmoduleid,"appmoduleid")]:m}}:{}}}li.appApi={get(e,t){return OT(e,t,"tokens-first")},readContentThenToken(e,t){return OT(e,t,"content-first")},async list(e,t){let r=S0(A0);return(await(0,$s.collectPages)(e,r,"listArtifacts('app')")).map(i=>{var o,a;return{type:"app",id:(o=i.appmoduleid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",isDirty:!1}})},async create(e,t,r){let n=t;await IT(e,n.sitemapxml);let i=await ST(e,n,n.appModuleId),o=n.iconWebResourceId?void 0:await Uz(e),a=n.iconWebResourceId||o?.id;if(!a)throw new _e.SdkError("APP_ICON_UNRESOLVED",`Cannot create app '${n.appModuleName}': its icon (\`appmodule.webresourceid\`) is a REQUIRED attribute and this environment has no image web resource to use. Pass \`iconWebResourceId\` explicitly, or add an image (PNG/JPG/GIF/ICO/SVG) web resource to the environment.`);let s=null;o?.managed&&(s=`No unmanaged image web resource was available, so the app icon resolved to a MANAGED one (${o.id}). That creates a cross-solution dependency which can fail to import into an environment without the owning managed solution. Pass \`iconWebResourceId\` with an in-solution image to avoid it.`);let l=n.appModuleUniqueName||Mz(n.appModuleId),u={name:n.appModuleName,uniquename:l,clienttype:4,formfactor:1,navigationtype:0};n.appModuleDescription&&(u.description=n.appModuleDescription),n.appModuleAiDescription&&(u.aiappdescription=n.appModuleAiDescription),a&&(u.webresourceid=a);let c="/appmodules",d=(0,ge.ensureSuccess)(await(0,ge.resendDeadlockVictim)(()=>e.post(c,(0,ge.withClientMintedId)(u,"appmoduleid",r))),e.apiUrl(c)),f=(0,ge.resolveCreatedId)(d,"appmoduleid","app module",r),m=null,p=null,h=[];s&&h.push(s);let g={kind:"notRequested"},b=n.sitemapId?(0,Ae.normalizeGuid)(n.sitemapId,"sitemapId"):(0,E0.newId)(),w=!1,C={sitemapxml:n.sitemapxml,sitemapname:n.sitemapname};try{let O="/sitemaps",L=(0,ge.echoWrite)("sitemapid"),I=await e.post(`${O}${L.query}`,{sitemapid:b,sitemapnameunique:l,...C},L.options);w=UT(I.status);let D=(0,ge.ensureSuccess)(I,e.apiUrl(O));p=(0,ge.readEtag)(D),m=p??await C0(e,b,C,l);let P=await ET(e,n,i);h.push(...P.warnings);let x=P.components;x.unshift({"@odata.type":"Microsoft.Dynamics.CRM.sitemap",sitemapid:b}),await NT(e,f,x);let K=bf(e,f);await _T(e,f,P.tables,K),i&&await zz(e,f,i,K);let Le=await Bz(e,f);Le&&h.push(Le),n.appSettings&&Object.keys(n.appSettings).length>0&&h.push(...await(0,kz.applyAppSettings)(e,f,n.appSettings)),n.published!==!1&&(await(0,bT.publishAppModule)(e,f),g={kind:"submitted"})}catch(O){let L=await Hz(e,f,{sitemapId:b,sitemapNameUnique:l,serverRefusedSitemap:w,sitemapWriteToken:p});throw(0,$z.failedAfterPrimaryWrite)(Kz(O,L,{appId:f,sitemapId:b,uniqueName:l}))}let S=null;if(g.kind==="submitted")try{let O=await e.get(`/appmodules(${f})?$select=appmoduleid`);O.status>=200&&O.status<300&&(S=(0,ge.readEtag)(O))}catch{}return{id:f,etag:m,serverIdentity:{sitemapId:b},siblingEtags:{[f]:S},publish:g,...h.length>0?{warnings:h}:{}}},async update(e,t,r,n,i,o){var a,s,l,u,c,d,f,m,p;let h=r,g=(0,Ae.normalizeGuid)(t,"id");if(await IT(e,h.sitemapxml),!h.sitemapId)throw new _e.ValidationError("app",g,[{pointer:"/sitemapId",rule:"app-sitemap-identity-missing",message:`missing sitemap identity \u2014 re-fetch the app before pushing edits: fetchArtifact('app', '${g}', { overwrite: true }) (it REPLACES the local copy \u2014 keep outstanding changes aside), push that refreshed copy UNTOUCHED, then re-apply your changes and push again. If the untouched push is refused with this same rule, the app has NO sitemap on the server \u2014 an earlier create committed its appmodule but not its sitemap \u2014 and it can be neither updated, published nor removed with deleteRemoteArtifact (an unpublished app reads back 404). Only for an app you have confirmed is your own abandoned partial create, with nothing else provisioning it: remove its appmodule row with deleteRecord('appmodule', '${g}'), clear the local copy with deleteArtifact('app', '${g}'), then author the app again and push.`}]);let b=(0,Ae.normalizeGuid)(h.sitemapId,"sitemapId");if(!(0,ge.isVersionToken)(n))throw new _e.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${g}': ${n?`the concurrency token held for its sitemap row ('${n}') is not a version`:"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 ST(e,h,g),C=await ET(e,h,w),S=`/appmodules(${g})`,O=(a=o?.[g])!==null&&a!==void 0?a:null,L=!0,I;try{let Bt=S0(A0,g),Ni=await e.get(Bt);if(Ni.status>=200&&Ni.status<300){let Ha=(s=_u(Ni))!==null&&s!==void 0?s:{};I=typeof Ha.uniquename=="string"&&Ha.uniquename?Ha.uniquename:void 0,L=String((l=Ha.name)!==null&&l!==void 0?l:"")!==String((u=h.appModuleName)!==null&&u!==void 0?u:"")||String((c=Ha.description)!==null&&c!==void 0?c:"")!==String((d=h.appModuleDescription)!==null&&d!==void 0?d:"")||h.appModuleAiDescription!==void 0&&String((f=Ha.aiappdescription)!==null&&f!==void 0?f:"")!==String(h.appModuleAiDescription)}}catch{}let D=O;if(L){if(!(0,ge.isVersionToken)(O))throw new _e.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${g}': ${O?`the concurrency token held for its appmodule header ('${O}') is not a version`:"no concurrency token is held for its appmodule header"}, so its header edit could not be made conditional and would silently overwrite a concurrent edit. Nothing was modified. Re-fetch the app (fetchArtifact('app', '${g}', { overwrite: true })) and re-apply the change.`);let Bt=(0,ge.echoWrite)("appmoduleid",{"If-Match":O}),Ni=await e.patch(`${S}${Bt.query}`,{name:h.appModuleName,description:h.appModuleDescription,...h.appModuleAiDescription!==void 0?{aiappdescription:h.appModuleAiDescription}:{}},Bt.options);if(tj(Ni))throw new _e.SdkError("APP_DRAFT_HEADER_NOT_WRITABLE",`Refusing to update app '${g}': its appmodule row is UNPUBLISHED, and Dataverse cannot resolve version numbers for a draft appmodule (HTTP 400). A draft header cannot be PATCHed at all \u2014 a plain retry fails too, as an upsert-create ("webresourceid cannot be NULL"). Publish the app first, then push the header edit. Nothing was modified by this call.`);(0,ge.ensureSuccess)(Ni,e.apiUrl(S)),D=(0,ge.readEtag)(Ni)}let P={sitemapxml:h.sitemapxml,sitemapname:h.sitemapname},x=I||h.appModuleUniqueName||void 0,K=(0,ge.echoWrite)("sitemapid",{"If-Match":n}),Le=`/sitemaps(${b})`,lr;try{lr=(0,ge.ensureSuccess)(await e.patch(`${Le}${K.query}`,{...P},K.options),e.apiUrl(Le))}catch(Bt){throw(0,_e.withPartialTokens)(Bt,{siblingEtags:{[g]:D}})}let Ge=[...C.warnings],Ut=bf(e,g);try{await NT(e,g,C.components),await _T(e,g,C.tables,Ut)}catch(Bt){Ge.push(`App '${g}': one or more components were not pinned (${Bt.message}). Navigation may reference content not included in the app; re-push to retry.`)}w&&Ge.push(...await jz(e,g,w,Ut));let de={kind:"notRequested"},Ke=D,ur=(m=(0,ge.readEtag)(lr))!==null&&m!==void 0?m:await C0(e,b,P,x);if(h.published===!0){try{await(0,bT.publishAppModule)(e,g),de={kind:"submitted"}}catch(Bt){de={kind:"failed",error:Bt},Ge.push(`App '${g}': saved, but publishing failed (${Bt.message}). The app remains unpublished; re-push to retry.`)}if(de.kind==="submitted"){Ke=null;try{let Bt=await e.get(`/appmodules(${g})?$select=appmoduleid`);Bt.status>=200&&Bt.status<300&&(Ke=(0,ge.readEtag)(Bt)),ur=(p=await C0(e,b,P,x))!==null&&p!==void 0?p:ur}catch{}}}return{id:g,etag:ur,siblingEtags:{[g]:Ke},publish:de,...Ge.length>0?{warnings:Ge}:{}}},async delete(e,t){let r=(0,Ae.normalizeGuid)(t,"id");await BT(e,r,await xT(e,r))}}});var T0=v(xs=>{"use strict";Object.defineProperty(xs,"__esModule",{value:!0});xs.deleteAppCascade=xs.collectGenPageIds=void 0;var rj=Af(),nj=Q(),D0=oe(),ij=ys();function qT(e){let t=[],r=s=>l=>t.push(`${s}: ${l}`),n=new ij.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml"),i=n?.documentElement;if(!i||t.length>0)throw new nj.InvalidArgumentError(`The app sitemap xml could not be parsed cleanly, so its generative-page children cannot be determined${t.length>0?` (${t[0]})`:""}`);let o=[],a=s=>{if(s.nodeName==="SubArea"){let u=s.getAttribute("GenPageId");u&&o.push((0,D0.normalizeGuid)(u,"GenPageId"))}let l=s.childNodes;for(let u=0;u<l.length;u+=1){let c=l[u];c.nodeType===1&&a(c)}};return a(i),o}xs.collectGenPageIds=qT;async function oj(e,t,r){let n=(0,D0.normalizeGuid)(t,"appModuleId");(0,D0.normalizeGuid)(r,"appModuleIdUnique");let i=[],o=[],a=[];await(0,rj.deleteAppResolvingOnce)(e,n,l=>{l!==void 0&&a.push(...qT(l))}),i.push({type:"app",id:n});let s=[...new Set(a)].map(l=>({type:"genPage",id:l}));return{success:o.length===0,deleted:i,failures:o,retained:s}}xs.deleteAppCascade=oj});var VT={};nn(VT,{Guid:()=>U});var U,vt=k(()=>{"use strict";U=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 q,rr=k(()=>{"use strict";dt();q=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(!R.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 R.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 GT={};nn(GT,{ScriptUtilities:()=>R});var R,dt=k(()=>{"use strict";vt();rr();R=class e{static IsNullOrUndefined(t){return t==null||t===void 0}static IsMacMachine(){return navigator.platform.indexOf("Mac")!==-1}static IsNullOrEmptyGuid(t){return q.IsNullOrEmpty(t.ToString())?!0:U.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:q.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 Sf,Nf,ha,_f,I0,Tf,O0=k(()=>{"use strict";(function(e){e[e.FormElementNodeChange=0]="FormElementNodeChange",e[e.FormElementAttributeChange=1]="FormElementAttributeChange"})(Sf||(Sf={}));Nf=class{type;targetNode;constructor(t,r){this.type=t,this.targetNode=r}},ha=class extends Nf{key;oldValue;newValue;constructor(t,r,n,i){super(Sf.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)}},_f=class extends Nf{property;oldValue;newValue;constructor(t,r,n,i){super(Sf.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)}},I0=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()})}},Tf=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 I0(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 WT={};nn(WT,{ChartGridMode:()=>hn,ColumnLayoutWidths:()=>cj,ComponentCategory:()=>If,ComponentType:()=>P0,ControlLayoutTypes:()=>M0,DisplayConditionsInfo:()=>lj,ElementNames:()=>E,ElementProperties:()=>y,ElementType:()=>L0,EntityAttributeProperty:()=>k0,EventType:()=>Tu,FormActivationState:()=>F0,FormCanvasServiceScope:()=>Ej,FormDesignerSideBarTab:()=>R0,FormPresentation:()=>$0,FormState:()=>Df,FormType:()=>wt,HeaderDensityType:()=>Do,LookUpTable:()=>ui,MORE_TAB_PREFIX:()=>fj,NavBarChildElementType:()=>x0,PREVIEW_ID_HEADER_FLYOUT:()=>gj,PREVIEW_ID_HEADER_OVERFLOW_BUTTON:()=>bj,PREVIEW_ID_NAVIGATION_AREA:()=>mj,PREVIEW_ID_QUICKCREATE_ROOT:()=>wj,PREVIEW_ID_TAB:()=>vj,PREVIEW_ID_TAB_LIST:()=>yj,PREVIEW_ID_TAB_PANEL:()=>hj,PropertyModelKeys:()=>q0,PropertyModelSectionKeys:()=>dj,RELATED_TAB_ID:()=>V0,RELATED_TAB_PREFIX:()=>pj,SectionDefaultProperties:()=>uj,SectionLayoutTypes:()=>je,TabContentType:()=>U0,TabDefaultProperties:()=>Io,TabLayoutTypes:()=>ze,TelemetryPropertyNames:()=>Cj,UnboundControlPropertyKeys:()=>B0,compositeAddressFields:()=>sj,compositeFieldNames:()=>Zr,compositeFields:()=>aj});var wt,P0,R0,E,y,L0,Zr,aj,sj,k0,ui,Df,Do,$0,lj,x0,F0,ze,uj,Io,je,M0,U0,cj,B0,q0,dj,Tu,hn,V0,fj,pj,mj,hj,gj,yj,bj,vj,wj,Cj,If,Ej,le=k(()=>{"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"})(wt||(wt={}));(function(e){e[e.Form=0]="Form",e[e.Dialog=1]="Dialog"})(P0||(P0={}));(function(e){e[e.Components=0]="Components",e[e.Properties=1]="Properties",e[e.Relationship=2]="Relationship",e[e.BusinessRules=3]="BusinessRules"})(R0||(R0={}));(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"})(E||(E={}));y={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"})(L0||(L0={}));Zr={fullname:"fullname",yomifullname:"yomifullname",address1_composite:"address1_composite",address2_composite:"address2_composite",address3_composite:"address3_composite",billto:"billto_composite",shipto:"shipto_composite"},aj=[Zr.fullname,Zr.yomifullname,Zr.address1_composite,Zr.address2_composite,Zr.address3_composite,Zr.billto,Zr.shipto],sj=[Zr.address1_composite,Zr.address2_composite,Zr.address3_composite,Zr.billto,Zr.shipto];(function(e){e[e.IsValidForForm=0]="IsValidForForm",e[e.IsValidForCreate=1]="IsValidForCreate"})(k0||(k0={}));(function(e){e[e.DependencyFieldTable=0]="DependencyFieldTable",e[e.LockedFieldTable=1]="LockedFieldTable"})(ui||(ui={}));(function(e){e[e.Published=0]="Published",e[e.Draft=1]="Draft",e[e.New=2]="New",e[e.SaveAs=3]="SaveAs"})(Df||(Df={}));(function(e){e.Low="Low",e.HighReadOnlyValues="HighReadOnlyValues",e.HighWithControls="HighWithControls"})(Do||(Do={}));(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})($0||($0={}));lj={TopOrderFormId:"topOrderFormId",NextDisplayOrder:"nextDisplayOrder"};(function(e){e[e.NavBarRelationShipItem=0]="NavBarRelationShipItem",e[e.NavBarItem=1]="NavBarItem"})(x0||(x0={}));(function(e){e[e.InActive=0]="InActive",e[e.Active=1]="Active"})(F0||(F0={}));(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"})(ze||(ze={}));uj={ShowLabel:"false",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_"},Io={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"})(je||(je={}));(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"})(M0||(M0={}));(function(e){e.cardSections="cardSections",e.singleComponent="singleComponent",e.default="default",e.expandAvailableSpace="expandAvailableSpace"})(U0||(U0={}));cj={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"})(B0||(B0={}));(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"})(q0||(q0={}));dj={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"})(Tu||(Tu={}));(function(e){e.All="All",e.Chart="Chart",e.Grid="Grid"})(hn||(hn={}));V0="tab_related3b554255-7717-4d17-bb7f-9936fb1e75ca",fj="more_tab_",pj="related_tab_",mj="preview_id_navigation_area",hj="tab-section",gj="headerFieldsFlyout",yj="tablist",bj="header_overflowButton",vj="tab",wj="quickCreateRoot",Cj={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"})(If||(If={}));Ej="CellCanvasServiceScope"});var zT={};nn(zT,{Attribute:()=>Of,FormElementNode:()=>re});var Of,re,kt=k(()=>{"use strict";dt();rr();O0();le();vt();Of=class{key;value;constructor(t,r){this.key=t,this.value=r}},re=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-${U.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(E.form);r&&r.raiseMetadataChange(t)}trackPropertyAddition(t,r){this.trackPropertyCollectionChange(()=>{this.properties.push(new Of(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 ha(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 ha(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 ha(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 _f(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 ha(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){R.IsNullOrUndefined(t)||(t.trackParentNodeChange(()=>{t.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(r,0,t)}))}moveChild(t,r){let n=this.childrenNodes.indexOf(t);if(n<0)return!1;let i=Math.min(Math.max(0,n+r),this.childrenNodes.length-1);return n!==i&&this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(i,0,this.childrenNodes.splice(n,1)[0])}),!0}getChildren(t){let r=[];for(let n of this.childrenNodes)n.nodeName===t&&r.push(n);return r}getFirstChild(t){for(let r of this.childrenNodes)if(r.nodeName===t)return r;return null}getAllGrandChildren(t){let r=this.getChildren(t),n=null;return r.length===0?new Array:(n=r[0],n.childrenNodes)}deleteChild(t){if(R.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:q.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=R.IsNullOrUndefined(r)?this.childrenNodes.length:r,this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(t,r)})}deleteGrandChildren(t,r,n){this.getChildren(t)[0].deleteChildren(r,n)}addGrandChild(t,r){let n=this.getChildren(t),i=null;n.length===0?(i=new e(t,this),this.addChild(i)):i=n[0],i.addChild(r)}addGrandChildAtIndex(t,r,n){let i=this.getChildren(t),o=null;i.length===0?(o=new e(t,this),this.addChild(o)):o=i[0],o.insertChildAtIndex(r,n)}GetPropertyByParameter(t){return this.getProperty(t)}getSemanticParent(){switch(this.getNodeName()){case E.formCell:let t=this.getAncestor(E.formSection);return t||(t=this.getAncestor(E.formHeader),t)||(t=this.getAncestor(E.formFooter),t)?t:null;case E.formSection:return this.getAncestor(E.formTab);case E.formTab:return this.getAncestor(E.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(E.form);return t?t.changeTracker():null}}});var jT={};nn(jT,{ControlClassId:()=>N,ControlNamePrefixes:()=>Pf,getControlDisplayNames:()=>Aj});function Aj(e){return{[N.AccessPrivilegeControl]:e("controls.controlNames.accessPrivilege"),[N.AccessTeamTablePickerControl]:e("controls.controlNames.accessTeamTablePicker"),[N.ACIControl]:e("controls.controlNames.aci"),[N.ActivitiesContainerControl]:e("controls.controlNames.activitiesContainer"),[N.ActivitiesWallControl]:e("controls.controlNames.activitiesWall"),[N.AppliedFiltersControl]:e("controls.controlNames.appliedFilters"),[N.ArticleContentControl]:e("controls.controlNames.articleContent"),[N.BooleanControl]:e("controls.controlNames.twoOption"),[N.ButtonControl]:e("controls.controlNames.button"),[N.CheckboxControl]:e("controls.controlNames.checkbox"),[N.CompositionLinkControl]:e("controls.controlNames.compositionLink"),[N.ConnectionControl]:e("controls.controlNames.connection"),[N.ConnectionRoleObjectTypeListControl]:e("controls.controlNames.connectionRoleObjectTypeList"),[N.CoverageChoiceControl]:e("controls.controlNames.coverageChoice"),[N.DashboardControl]:e("controls.controlNames.dashboard"),[N.DynamicPropertyListControl]:e("controls.controlNames.dynamicPropertyList"),[N.EditFilterControl]:e("controls.controlNames.editFilter"),[N.ErrorStatusControl]:e("controls.controlNames.errorStatus"),[N.GlobalFilterControl]:e("controls.controlNames.globalFilter"),[N.HiddenInputControl]:e("controls.controlNames.hiddenInput"),[N.KBViewerControl]:e("controls.controlNames.kbViewer"),[N.LabelControl]:e("controls.controlNames.label"),[N.MailMergeLanguagePickerControl]:e("controls.controlNames.mailMergeLanguagePicker"),[N.MapLinkControl]:e("controls.controlNames.mapLink"),[N.OrgInsightsControl]:e("controls.controlNames.orgInsights"),[N.ChoiceLookupControl]:e("controls.controlNames.choiceLookup"),[N.PowerBIControl]:e("controls.controlNames.powerBI"),[N.ProcessControl]:e("controls.controlNames.process"),[N.RelatedInformationControl]:e("controls.controlNames.relatedInformation"),[N.RelationshipRoleChoiceControl]:e("controls.controlNames.relationshipRoleChoice"),[N.ReportControl]:e("controls.controlNames.report"),[N.StreamsControl]:e("controls.controlNames.streams"),[N.WebResourceSilverlightControl]:e("controls.controlNames.webResourceSilverlight"),[N.CurrencyControl]:e("controls.controlNames.currency"),[N.DateTimeControl]:e("controls.controlNames.dateAndTime"),[N.DecimalControl]:e("controls.controlNames.decimal"),[N.DurationControl]:e("controls.controlNames.duration"),[N.EmailAddressControl]:e("controls.controlNames.email"),[N.FileControl]:e("controls.controlNames.file"),[N.FloatingNumberControl]:e("controls.controlNames.floatingNumber"),[N.IframeControl]:e("controls.controlNames.iframe"),[N.ImageControl]:e("controls.controlNames.image"),[N.LookupControl]:e("controls.controlNames.lookup"),[N.MapsControl]:e("controls.controlNames.maps"),[N.PhoneNumberControl]:e("controls.controlNames.phoneNumber"),[N.ChoiceControl]:e("controls.controlNames.choice"),[N.QuickViewControl]:e("controls.controlNames.quickView"),[N.QuickFormControl]:e("controls.controlNames.quickForm"),[N.CustomControl]:e("controls.controlNames.customControl"),[N.SearchWidgetControl]:e("controls.controlNames.searchWidget"),[N.SocialInsightsControl]:e("controls.controlNames.socialInsights"),[N.SubgridControl]:e("controls.controlNames.subgrid"),[N.TextAreaControl]:e("controls.controlNames.textArea"),[N.TextboxControl]:e("controls.controlNames.textBox"),[N.TickerControl]:e("controls.controlNames.ticker"),[N.UrlControl]:e("controls.controlNames.url"),[N.WebResourceHTMLControl]:e("controls.controlNames.webResourceHTML"),[N.WebResourceImageControl]:e("controls.controlNames.webResourceImage"),[N.IntegerControl]:e("controls.controlNames.integer"),[N.TimerControl]:e("controls.controlNames.timer"),[N.TimelineControl]:e("controls.controlNames.timeline"),[N.EmailBodyControl]:e("controls.controlNames.emailBody"),[N.PartyListControl]:e("controls.controlNames.partyList"),[N.TimezoneControl]:e("controls.controlNames.timezone"),[N.LanguageControl]:e("controls.controlNames.language"),[N.ChoiceStatusControl]:e("controls.controlNames.choiceStatus"),[N.ChoicesControl]:e("controls.controlNames.choices"),[N.RegardingControl]:e("controls.controlNames.regarding"),[N.EmailEngagementActionsControl]:e("controls.controlNames.emailEngagementActions"),[N.EmailRecipientActivityControl]:e("controls.controlNames.emailRecipientActivity"),[N.ReferencePanelSearchWidgetControl]:e("controls.controlNames.referencePanelSearchWidget"),[N.ReferencePanelQuickViewControl]:e("controls.controlNames.referencePanelQuickView"),[N.ReferencePanelSubgridControl]:e("controls.controlNames.referencePanelSubgrid"),[N.KBEditorControl]:e("controls.controlNames.KBEditor"),[N.LinkControl]:e("controls.controlNames.link")}}var N,Pf,ga=k(()=>{"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"})(N||(N={}));Pf={[N.WebResourceHTMLControl]:"WebResource",[N.WebResourceImageControl]:"WebResource",[N.IframeControl]:"IFRAME",[N.SearchWidgetControl]:"Search widget",[N.SubgridControl]:"Subgrid",[N.TimelineControl]:"Timeline",[N.QuickViewControl]:"QuickviewControl"}});var ya=v((Ade,KT)=>{var Du=new Proxy(function(){return Du},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Du},apply:function(){return Du},construct:function(){return{}}}),HT=function(){return Du};Object.setPrototypeOf(HT,Du);KT.exports=HT});var hr,Wi,JT,YT,Fs=k(()=>{"use strict";hr="cds-designer-models",Wi="FormCustomControl",JT="FormCell",YT="Form"});var ba,G0=k(()=>{"use strict";su();le();ba=class e{static lockedFieldCount=new dr;static dependencyFieldCount=new dr;static getNecessaryLookUpTable(t){switch(t){case ui.DependencyFieldTable:return e.dependencyFieldCount;case ui.LockedFieldTable:return e.lockedFieldCount}}static initCanvasLockedFieldLookUp(t){switch(t){case ui.DependencyFieldTable:e.dependencyFieldCount=new dr;case ui.LockedFieldTable:e.lockedFieldCount=new dr}}}});var Rf,QT=k(()=>{"use strict";vt();dt();le();kt();Rf=class extends re{constructor(t){super(E.controlDescription,t)}get forControl(){let t=this.getProperty(y.ForControl);return R.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t))}set forControl(t){this.setProperty(y.ForControl,`{${t.ToString()}}`)}get customControls(){return this.getChildren(E.customControl)}set customControls(t){this.deleteAllChildren();for(let r of t)this.addChild(r)}get DefaultControlClassId(){for(let t of this.customControls)if(!R.IsNullOrUndefined(t.id))return t.id;return null}get DefaultCustomControl(){for(let t of this.customControls)if(!R.IsNullOrUndefined(t.id))return t;return null}get DefaultCustomControls(){let t=[];for(let r of this.customControls)R.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}}});function zi(){return ci||(ci=window._makerConfig,ci&&window?.location?.search?.indexOf("useProductionConfig")>-1&&(ci={...ci,region:"prod",graphQLEndpoint:"https://graph.make.powerapps.com/"}),ci?.region==="prod"&&(ci={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/"}}},...ci}),ci||{aadClientId:"a8f7a65c-f5ba-4859-b2d6-df772c264e9d",location:"cus",region:"test",publicPath:"/",graphQLEndpoint:"https://graph.make.test.powerapps.com/"})}var ci,Lf=k(()=>{"use strict";});function XT(e,t,r){if(!e)return kf.has(e)||(window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoIsEmpty"}),kf.add("")),!1;if(e){if(e=e.toLowerCase(),kf.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}}),kf.add(e),!1}return!0}function Sj(e){return XT(e,W0,"Location dictionary")?W0[e.toLowerCase()]:"us"}function Nj(){let e=zi().location.toLowerCase();return XT(e,W0,"Current location dictionary")?e:"us"}var kf,W0,xde,ZT=k(()=>{"use strict";Lf();kf=new Set,W0={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"};xde=Sj(Nj())});var Y,Mde,eD=k(()=>{"use strict";Y={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"},Mde={[Y.USWest]:{geoName:"us",regionShortName:"wus"},[Y.USCentral]:{geoName:"us",regionShortName:"cus"},[Y.USEast]:{geoName:"us",regionShortName:"eus"},[Y.USEast2]:{geoName:"us",regionShortName:"eus2"},[Y.USWestCentral]:{geoName:"us",regionShortName:"wcus"},[Y.USWest2]:{geoName:"us",regionShortName:"wus2"},[Y.USSouthCentral]:{geoName:"br",regionShortName:"scus"},[Y.BrazilSouth]:{geoName:"br",regionShortName:"sbr"},[Y.UKSouth]:{geoName:"uk",regionShortName:"suk"},[Y.UKWest]:{geoName:"uk",regionShortName:"wuk"},[Y.JapanEast]:{geoName:"jp",regionShortName:"ejp"},[Y.JapanWest]:{geoName:"jp",regionShortName:"wjp"},[Y.IndiaCentral]:{geoName:"in",regionShortName:"cin"},[Y.IndiaSouth]:{geoName:"in",regionShortName:"sin"},[Y.ItalyNorth]:{geoName:"it",regionShortName:"nit"},[Y.GermanyWestCentral]:{geoName:"de",regionShortName:"wcde"},[Y.GermanyNorth]:{geoName:"de",regionShortName:"nde"},[Y.EuropeNorth]:{geoName:"eu",regionShortName:"neu"},[Y.EuropeWest]:{geoName:"eu",regionShortName:"weu"},[Y.AustraliaEast]:{geoName:"au",regionShortName:"eau"},[Y.AustraliaSouthEast]:{geoName:"au",regionShortName:"seau"},[Y.AsiaSouthEast]:{geoName:"as",regionShortName:"seas"},[Y.AsiaEast]:{geoName:"as",regionShortName:"eas"},[Y.CanadaCentral]:{geoName:"ca",regionShortName:"cca"},[Y.CanadaEast]:{geoName:"ca",regionShortName:"eca"},[Y.SouthAfricaNorth]:{geoName:"za",regionShortName:"nza"},[Y.SouthAfricaWest]:{geoName:"za",regionShortName:"wza"},[Y.FranceCentral]:{geoName:"fr",regionShortName:"cfr"},[Y.FranceSouth]:{geoName:"fr",regionShortName:"sfr"},[Y.UAENorth]:{geoName:"ae",regionShortName:"nae"},[Y.UAECentral]:{geoName:"ae",regionShortName:"cae"},[Y.SwedenCentral]:{geoName:"se",regionShortName:"cse"},[Y.SwitzerlandNorth]:{geoName:"ch",regionShortName:"nch"},[Y.SwitzerlandWest]:{geoName:"ch",regionShortName:"wch"},[Y.NorwayEast]:{geoName:"no",regionShortName:"eno"},[Y.NorwayWest]:{geoName:"no",regionShortName:"wno"},[Y.KoreaCentral]:{geoName:"kr",regionShortName:"ckr"},[Y.KoreaSouth]:{geoName:"kr",regionShortName:"skr"},[Y.SingaporeSouthEast]:{geoName:"sg",regionShortName:"seas"},[Y.PolandCentral]:{geoName:"pl",regionShortName:"cpl"},[Y.QatarCentral]:{geoName:"qa",regionShortName:"cqa"},[Y.NewZealandNorth]:{geoName:"nz",regionShortName:"nnz"},[Y.GovernmentUSTexas]:{geoName:"us",regionShortName:"ugtx"},[Y.GovernmentUSVirginia]:{geoName:"us",regionShortName:"ugva"},[Y.GovernmentUSDodCentral]:{regionShortName:"udc"},[Y.GovernmentUSDodEast]:{regionShortName:"ude"},[Y.ChinaEast]:{regionShortName:"cne"},[Y.ChinaEast2]:{regionShortName:"cne2"},[Y.ChinaEast3]:{regionShortName:"cne3"},[Y.ChinaNorth]:{regionShortName:"cnn"},[Y.ChinaNorth2]:{regionShortName:"cnn2"},[Y.ChinaNorth3]:{regionShortName:"cnn3"},[Y.UssecEast]:{geoName:"us",regionShortName:"erx"},[Y.UssecWest]:{geoName:"us",regionShortName:"wrx"},[Y.UsnatEast]:{geoName:"us",regionShortName:"eex"},[Y.UsnatWest]:{geoName:"us",regionShortName:"wex"}}});var tD=k(()=>{"use strict";Lf();});var Iu=k(()=>{"use strict";Lf();ZT();eD();tD();});function Ou(e,t){return rD?rD.isOverridden(e,t):{overridden:!1}}var rD,Pu=k(()=>{"use strict";});var z0=k(()=>{"use strict";Iu();Pu();});function _j(e,t){let{region:r}=zi();return()=>{let n=e.settings[t];if(n.allowOverrides){let s=Ou(e.packageName,t);if(s.overridden)return typeof s.value=="string"?Tj(s.value):s.value}let o=n.values,a=process.env.SETTINGS_FALLBACK_REGION?.[r];return o[r]!==void 0?o[r]:a&&o[a]!==void 0?o[a]:o.default}}function Tj(e){return isNaN(Number(e))?e==="true"?!0:e==="false"?!1:e:Number(e)}function Dj(e){let t=e.packageName;if($f.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=>H0(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=>!Ff(i))){let i=`error parsing settings config for package ${t}, setting ${r} has invalid region`;throw console.error(i),new Error(i)}})}function Ru(e){Dj(e);let t={};return Object.keys(e.settings).forEach(r=>{t[r]={enumerable:!0,get:_j(e,r)}}),$f.set(e.packageName,e),Object.defineProperties({},t)}function j0(e,t){return $f.has(e)?!!$f.get(e).settings[t]:!1}var $f,xf=k(()=>{"use strict";Iu();Pu();K0();Lu();$f=new Map});function nD(e,t){let{region:r}=zi();return()=>{let n=Ou(e.packageName,t);if(n.overridden)return n.value.toString()==="true";let i=e.features[t].enabledFor,o=process.env.SETTINGS_FALLBACK_REGION?.[r];return i[r]!==void 0?!!i[r]:o&&i[o]!==void 0?!!i[o]:!1}}function Ij(e){let t=e.packageName;if(Mf.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=>j0(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=>!Ff(i))){let i=`error parsing feature gates config for package ${t}, feature ${r} has invalid region`;throw console.error(i),new Error(i)}})}function J0(e){Ij(e);let t={};Object.keys(e.features).forEach(i=>{t[i]={enumerable:!0,configurable:!0,get:nD(e,i)}});let r={},n=new Set;return t.dangerouslySet={enumerable:!1,value:(i,o)=>{n.add(i),Object.defineProperty(r,i,{enumerable:!0,configurable:!0,value:o})}},t.dangerouslyReset={enumerable:!1,value:()=>{let i={};n.forEach(o=>{i[o.toString()]={enumerable:!0,configurable:!0,get:nD(e,o.toString())}}),Object.defineProperties(r,i),n.clear()}},Mf.set(e.packageName,e),Object.defineProperties(r,t)}function H0(e,t){return Mf.has(e)?!!Mf.get(e).features[t]:!1}var Mf,K0=k(()=>{"use strict";Iu();Lu();Pu();xf();Mf=new Map});var oD=v((ufe,iD)=>{"use strict";iD.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 lD=v(Y0=>{"use strict";var Oj=Object.prototype.hasOwnProperty,Pj;function aD(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch{return null}}function sD(e){try{return encodeURIComponent(e)}catch{return null}}function Rj(e){for(var t=/([^=?#&]+)=?([^&]*)/g,r={},n;n=t.exec(e);){var i=aD(n[1]),o=aD(n[2]);i===null||o===null||i in r||(r[i]=o)}return r}function Lj(e,t){t=t||"";var r=[],n,i;typeof t!="string"&&(t="?");for(i in e)if(Oj.call(e,i)){if(n=e[i],!n&&(n===null||n===Pj||isNaN(n))&&(n=""),i=sD(i),n=sD(n),i===null||n===null)continue;r.push(i+"="+n)}return r.length?t+r.join("&"):""}Y0.stringify=Lj;Y0.parse=Rj});var Z0=v((dfe,mD)=>{"use strict";var cD=oD(),Uf=lD(),dD=/[\n\r\t]/g,kj=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,$j=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,xj=/^[a-zA-Z]:/,Fj=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;function X0(e){return(e||"").toString().replace(Fj,"")}var Q0=[["#","hash"],["?","query"],function(t,r){return di(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]],uD={hash:1,query:1};function fD(e){var t;typeof window<"u"?t=window:typeof global<"u"?t=global:typeof self<"u"?t=self:t={};var r=t.location||{};e=e||r;var n={},i=typeof e,o;if(e.protocol==="blob:")n=new fi(unescape(e.pathname),{});else if(i==="string"){n=new fi(e,{});for(o in uD)delete n[o]}else if(i==="object"){for(o in e)o in uD||(n[o]=e[o]);n.slashes===void 0&&(n.slashes=kj.test(e.href))}return n}function di(e){return e==="file:"||e==="ftp:"||e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function pD(e,t){e=X0(e),e=e.replace(dD,""),t=t||{};var r=$j.exec(e),n=r[1]?r[1].toLowerCase():"",i=!!r[2],o=!!r[3],a=0,s;return i?o?(s=r[2]+r[3]+r[4],a=r[2].length+r[3].length):(s=r[2]+r[4],a=r[2].length):o?(s=r[3]+r[4],a=r[3].length):s=r[4],n==="file:"?a>=2&&(s=s.slice(2)):di(n)?s=r[4]:n?i&&(s=s.slice(2)):a>=2&&di(t.protocol)&&(s=r[4]),{protocol:n,slashes:i||di(n),slashesCount:a,rest:s}}function Mj(e,t){if(e==="")return t;for(var r=(t||"/").split("/").slice(0,-1).concat(e.split("/")),n=r.length,i=r[n-1],o=!1,a=0;n--;)r[n]==="."?r.splice(n,1):r[n]===".."?(r.splice(n,1),a++):a&&(n===0&&(o=!0),r.splice(n,1),a--);return o&&r.unshift(""),(i==="."||i==="..")&&r.push(""),r.join("/")}function fi(e,t,r){if(e=X0(e),e=e.replace(dD,""),!(this instanceof fi))return new fi(e,t,r);var n,i,o,a,s,l,u=Q0.slice(),c=typeof t,d=this,f=0;for(c!=="object"&&c!=="string"&&(r=t,t=null),r&&typeof r!="function"&&(r=Uf.parse),t=fD(t),i=pD(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||xj.test(e))||!i.slashes&&(i.protocol||i.slashesCount<2||!di(d.protocol)))&&(u[3]=[/(.*)/,"pathname"]);f<u.length;f++){if(a=u[f],typeof a=="function"){e=a(e,d);continue}o=a[0],l=a[1],o!==o?d[l]=e:typeof o=="string"?(s=o==="@"?e.lastIndexOf(o):e.indexOf(o),~s&&(typeof a[2]=="number"?(d[l]=e.slice(0,s),e=e.slice(s+a[2])):(d[l]=e.slice(s),e=e.slice(0,s)))):(s=o.exec(e))&&(d[l]=s[1],e=e.slice(0,s.index)),d[l]=d[l]||n&&a[3]&&t[l]||"",a[4]&&(d[l]=d[l].toLowerCase())}r&&(d.query=r(d.query)),n&&t.slashes&&d.pathname.charAt(0)!=="/"&&(d.pathname!==""||t.pathname!=="")&&(d.pathname=Mj(d.pathname,t.pathname)),d.pathname.charAt(0)!=="/"&&di(d.protocol)&&(d.pathname="/"+d.pathname),cD(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:"&&di(d.protocol)&&d.host?d.protocol+"//"+d.host:"null",d.href=d.toString()}function Uj(e,t,r){var n=this;switch(e){case"query":typeof t=="string"&&t.length&&(t=(r||Uf.parse)(t)),n[e]=t;break;case"port":n[e]=t,cD(t,n.protocol)?t&&(n.host=n.hostname+":"+t):(n.host=n.hostname,n[e]="");break;case"hostname":n[e]=t,n.port&&(t+=":"+n.port),n.host=t;break;case"host":n[e]=t,/:\d+$/.test(t)?(t=t.split(":"),n.port=t.pop(),n.hostname=t.join(":")):(n.hostname=t,n.port="");break;case"protocol":n.protocol=t.toLowerCase(),n.slashes=!r;break;case"pathname":case"hash":if(t){var i=e==="pathname"?"/":"#";n[e]=t.charAt(0)!==i?i+t:t}else n[e]=t;break;case"username":case"password":n[e]=encodeURIComponent(t);break;case"auth":var o=t.indexOf(":");~o?(n.username=t.slice(0,o),n.username=encodeURIComponent(decodeURIComponent(n.username)),n.password=t.slice(o+1),n.password=encodeURIComponent(decodeURIComponent(n.password))):n.username=encodeURIComponent(decodeURIComponent(t))}for(var a=0;a<Q0.length;a++){var s=Q0[a];s[4]&&(n[s[1]]=n[s[1]].toLowerCase())}return n.auth=n.password?n.username+":"+n.password:n.username,n.origin=n.protocol!=="file:"&&di(n.protocol)&&n.host?n.protocol+"//"+n.host:"null",n.href=n.toString(),n}function Bj(e){(!e||typeof e!="function")&&(e=Uf.stringify);var t,r=this,n=r.host,i=r.protocol;i&&i.charAt(i.length-1)!==":"&&(i+=":");var o=i+(r.protocol&&r.slashes||di(r.protocol)?"//":"");return r.username?(o+=r.username,r.password&&(o+=":"+r.password),o+="@"):r.password?(o+=":"+r.password,o+="@"):r.protocol!=="file:"&&di(r.protocol)&&!n&&r.pathname!=="/"&&(o+="@"),n[n.length-1]===":"&&(n+=":"),o+=n+r.pathname,t=typeof r.query=="object"?e(r.query):r.query,t&&(o+=t.charAt(0)!=="?"?"?"+t:t),r.hash&&(o+=r.hash),o}fi.prototype={set:Uj,toString:Bj};fi.extractProtocol=pD;fi.location=fD;fi.trimLeft=X0;fi.qs=Uf;mD.exports=fi});var qj,hD=k(()=>{"use strict";qj=Ce(Z0());});function ey(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 Bf=k(()=>{"use strict";});var ty,ry,ny=k(()=>{"use strict";Bf();ty=class{features=new Map;register(t,r){let n=ey(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()}},ry=new ty});var iy=k(()=>{"use strict";});function Ff(e){return Vj.has(e)}var Vj,Lu=k(()=>{"use strict";z0();K0();xf();Pu();z0();hD();ny();Bf();iy();Vj=new Set(["tie","test","prod","preview","preprod","gov","high","dod","mooncake","ex","rx"])});var Gj,gD=k(()=>{"use strict";Lu();Gj=Ru({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 wD,ay,Ms,va,oy,qf,Us,ji,qe,yD,bD,vD,kn=k(()=>{"use strict";wD={ThreeEqColumn_FirstColumn:34,ThreeEqColumn_SecondColumn:33,ThreeEqColumn_ThirdColumn:33,FiveEqColumn:20},ay={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"})(Ms||(Ms={}));(function(e){e.Left="Left",e.Right="Right",e.Center="Center"})(va||(va={}));(function(e){e[e.Mobile=0]="Mobile",e[e.Tablet=1]="Tablet",e[e.Web=2]="Web"})(oy||(oy={}));qf=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"})(Us||(Us={}));ji=class{static StartTag="<"},qe={ShowLabel:"true",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_",labelAlignment:va.Left,labelPosition:Us.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"})(yD||(yD={}));(function(e){e.TabWithLockedFieldRemoval="TabWithLockedFieldRemoval",e.SectionWithLockedFieldRemoval="SectionWithLockedFieldRemoval",e.LockedSectionRemoval="LockedSectionRemoval",e.LockedFieldRemoval="LockedFieldRemoval",e.RequiredFieldRemoval="RequiredFieldRemoval",e.LastRemainingTab="LastRemainingTab",e.UnknownRemoval="UnknownRemoval"})(bD||(bD={}));(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"})(vD||(vD={}))});var sy,CD=k(()=>{"use strict";(function(e){e.DefaultValue="defaultValue",e.Loaded="loaded"})(sy||(sy={}))});var SD,Wj,ED,ape,spe,ku,AD,lpe,upe,ND=k(()=>{"use strict";SD=Ce(ya());dt();Fs();gD();vs();kn();oa();le();Wj=Ce(lo());CD();(function(e){e.Model="Model",e.Canvas="Canvas",e.CustomPages="CustomPages"})(ED||(ED={}));ape={Read:go.Read,Edit:go.Edit,Both:go.Both,Container:go.Container},spe={input:ia.Input,bound:ia.Bound,output:ia.Output};(function(e){e[e.dataset=0]="dataset",e[e.property=1]="property",e[e.groups=2]="groups",e[e.group=3]="group"})(ku||(ku={}));(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"})(AD||(AD={}));lpe=new Set([F.Currency,F.Decimal,F.FP,F.Multiple,F.SingleLineEmail,F.SingleLinePhone,F.SingleLineText,F.SingleLineTextArea,F.SingleLineURL,F.SingleLineTickerSymbol,F.WholeNone,F.WholeDuration,F.WholeLanguage,F.WholeTimeZone,F.Enum,F.LookupSimple,F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.TwoOptions,F.Boolean,F.PowerBIReport,F.DateAndTimeDateAndTime,F.DateAndTimeDateOnly,F.OptionSet,F.MultiSelectOptionSet,F.CardForm]),upe={numbers:[F.WholeNone,F.FP,F.Decimal,F.Currency],text:[F.SingleLineText,F.SingleLineTextArea,F.Multiple],lookup:[F.LookupSimple,F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding],dates:[F.DateAndTimeDateOnly,F.DateAndTimeDateAndTime],allFields:[F.TwoOptions,F.DateAndTimeDateOnly,F.DateAndTimeDateAndTime,F.FP,F.Decimal,F.WholeNone,F.WholeDuration,F.WholeTimeZone,F.WholeLanguage,F.LookupSimple,F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.Multiple,F.OptionSet,F.SingleLineText,F.SingleLineTextArea,F.SingleLineEmail,F.SingleLineURL,F.SingleLineTickerSymbol,F.SingleLinePhone]}});var $n,Vf,_D=k(()=>{"use strict";$n=Ce(ya());vt();dt();rr();Fs();oa();ND();vs();le();kt();kn();Vf=class extends re{constructor(t){super(E.customControl,t)}customControlId;get id(){let t=this.getProperty(y.id);return R.IsNullOrUndefined(t)?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new U(t.substr(1,t.length-2)):new U(t)}getParameters(){let t=new Map,r=this.getAllChildren();if(r&&r.length!==0&&r[0]){let n=r[0].getAllChildren();if(n!=null){for(let i of n)if(i&&i.getAllChildren().length>0){let o=i.getNodeName();t.get(o)?t.get(o).push(i):t.set(o,[i])}}}return t}getFormComponentValueByParameterName(t){let r=this.getParameters()?.get(Xt.value);if(r?.length>0){let n=r[0],i=n?.getAllChildren()?.length>0?n.getAllChildren().find(a=>a.getNodeName()===t):null,o=i?.getAllChildren()?.length>0?i.getAllChildren()[0].getNodeName():"";return this.normalizePropertyValue(o)}}getParameterValue(t){let r=this.getParameterNodeChild(t);return r&&this.normalizePropertyValue(r.getNodeName())}getParameterNodeChild(t){let r=this.getParameters().get(t);return r?.length>0&&r[0].getAllChildren()?.length>0?r[0].getAllChildren()[0]:null}getDatasetName(t){return t.getAllProperties().find(r=>r.key===Xt.name)?.value}getParameterChildrenValues(t,r,n){if(this.isDataSet(t)){let i=r.find(u=>u.key===Xt.name)?.value,o={Name:i,Type:F.Grid,Columns:[]},l=this.getParameters().get(Xt.dataset).find(u=>this.getDatasetName(u)===i).getAllChildren();for(let u of l){let c=u.getNodeName();if(u&&u.getAllChildren().length>0){let d=this.normalizePropertyValue(u.getAllChildren()[0].getNodeName());o[c]=d}}return o}}getParameterIsStatic(t){let r=!1,n=this.getParameters().get(t)[0],i=n&&n.getAllProperties();if(i){for(let o of i)if(o.key===y.static&&o.value==="true"){r=!0;break}}return r}get name(){return this.getProperty(y.Name)}get formFactor(){return this.getProperty(y.formFactor)}set formFactor(t){this.setProperty(y.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(ji.StartTag)&&(t=t.substring(1)),t}async parametersToJSON(t){let r=[];if(!this.name)return r;try{let n=await t.formModelService.customControlDiscoveryService.getCustomControlMetadata(this.name);if(n)if(n.configurations){let i=n.configurations,o=this.getParameters();for(let[a,s]of o)if(this.isDataSet(a))for(let l of o.get(a)){let u=l.getAllProperties(),c=this.getDatasetName(l),d=i.get(c),f=await this.parameterJSON(a,u,d,t);r.push({Name:c,Value:f})}else if(this.isGroups(s))r.push({Name:a,Value:{Type:hg.GroupDefinition,Value:this.normalizePropertyValue(this.getParameterNodeChild(s[0].NodeName).NodeName)}}),i.get(a).groupSet?.forEach(u=>{u.groupConfigurableProperties.forEach(async c=>{let d=c.name;c.propertyType===ku.dataset?o.get(Xt.dataset)?.some(m=>this.getDatasetName(m)===d)||r.push({Name:d,Value:{Name:d,Columns:[],Type:F.Grid}}):c.propertyType===ku.property&&(o.has(d)||r.push({Name:d,Value:{Usage:c.usage}}))})});else{let l=s[0].getAllProperties(),u=i.get(a),c=await this.parameterJSON(a,l,u,t);if(c)r.push({Name:a,Value:c});else{(0,$n.trackInfoTrace)(hr,{eventName:`${Wi}/parametersToJSON`,eventData:{message:`Configuration metadata for custom control parameter ${a} is not available for custom control : ${this.name}.`}}),r=[];break}}}else(0,$n.trackErrorTrace)(hr,{eventName:`${Wi}/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,$n.trackErrorTrace)(hr,{eventName:`${Wi}/parametersToJSON`,eventData:{message:"Custom Control Manifest not found"}},new Error(`No custom control manifest found for ${this.name}`))}catch(n){(0,$n.trackErrorTrace)(hr,{eventName:`${Wi}/parametersToJSON`,eventData:{message:"parameters to json failed"}},n)}return r}async parameterJSON(t,r,n,i){if(this.isDataSet(t)){let o=n,a=r.find(s=>s.key===Xt.name)?.value;if(o)return this.getParameterChildrenValues(t,r);{let s=new Error(`No dataset manifest info for ${a}`);(0,$n.trackErrorTrace)(hr,{eventName:`${Wi}/parameterJSON`,eventData:{message:"Missing custom control manifest dataset info"}},s)}}else{let o=n,a=r&&r.find(l=>l.key===y.Type),s=o&&!o.ofTypeGroup.every(l=>!Od.includes(l));if(this.isLookupType(a?.value)||this.isLookupType(o?.ofType)||s)if(o){let l=o.usage,u=this.getParameterIsStatic(t),c=o.isPrimary;if(this.name===Mi.FormComponent){let d=this.getFormComponentValueByParameterName(y.bindAttribute),f=await i.formModelService.loadLookupModel(d),m=f.lookupColumn,p=this.getLookupDataTypeFromAttributeMetadata(m);return{Name:t,Type:p,Usage:l,Static:u,Primary:c,EntityName:f.primaryTableName,Value:d,ViewId:this.getFormComponentValueByParameterName(mg.DefaultViewId),TargetEntityType:m.targets[0],FilterRelationshipName:this.getFormComponentValueByParameterName(y.FilterRelationshipName),AvailableViewIds:this.getFormComponentValueByParameterName(y.AvailableViewIds),DependentAttributeName:this.getFormComponentValueByParameterName(y.DependentAttributeName),DependentAttributeType:this.getFormComponentValueByParameterName(y.DependentAttributeType),AllowFilterOff:q.IsStrictTrue(this.getFormComponentValueByParameterName(y.AllowFilterOff)),DisableQuickFind:q.IsStrictTrue(this.getFormComponentValueByParameterName(y.DisableQuickFind)),EnableViewPicker:!q.IsStrictTrue(this.getFormComponentValueByParameterName(y.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,$n.trackErrorTrace)(hr,{eventName:`${Wi}/parameterJSON`,eventData:{message:"Missing custom control manifest lookup property info"}},l)}if(o){let l=o.usage,u=this.getParameterIsStatic(t),c=this.getParameterValue(t),d=o.isPrimary;if(a){let m=a.value;return{Type:m,Static:u,Usage:l,Value:this.isNumberTypeProperty(o,m)&&Number(c)?Number(c):c,Primary:d}}if(o.ofType)return{Type:o.ofType,Static:u,Usage:l,Value:c,Primary:!0};if(o.ofTypeGroup)return{Static:u,Usage:l,Value:c,Primary:!0};let f=new Error(`No property type info for ${t}`);(0,$n.trackErrorTrace)(hr,{eventName:`${Wi}/parameterJSON`,eventData:{message:"Missing property type info"}},f)}else{let l=new Error(`No property manifest info for ${t}`);(0,$n.trackWarningTrace)(hr,{eventName:`${Wi}/parameterJSON`,eventData:{message:"Missing custom control manifest property info"}},l)}}return null}getLookupDataTypeFromAttributeMetadata(t){let{attributeType:r,format:n}=t;switch(r){case $.Customer:return F.LookupCustomer;case $.Owner:return F.LookupOwner;case $.PartyList:return F.LookupPartyList;default:return n===W.Regarding?F.LookupRegarding:F.LookupSimple}}isLookupType(t){return Od.includes(t)}isNumberTypeProperty(t,r){return Pd.includes(r)||t.ofTypeGroup.some(n=>Pd.includes(n))}isDataSet(t){return Xt.dataset===t}isGroups(t){return!!t[0].getAllProperties().find(n=>n.key==="isGroup"&&n.value==="true")}}});var ee,ly=k(()=>{"use strict";ee=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 TD={};nn(TD,{CustomControlUniqueId:()=>wa,DeprecatedControlClassIds:()=>G,FieldControlTypes:()=>ft,mapFieldTypeToControl:()=>zj});function zj(e,t){switch(e){case $.TwoOptions:return N.BooleanControl;case $.Customer:case $.CustomerType:return N.LookupControl;case $.DateTime:return t===W.DateAndTime?N.DateTimeControl:N.DateTimeControl;case $.DecimalNumber:return N.DecimalControl;case $.FloatingPointNumber:return N.FloatingNumberControl;case $.WholeNumber:return t===W.Duration?N.DurationControl:t===W.Language?N.LanguageControl:t===W.TimeZone?N.TimezoneControl:N.IntegerControl;case $.CustomerType:case $.Lookup:case $.LookupType:return t===W.Regarding?N.RegardingControl:N.LookupControl;case $.MultipleLineofText:return t===W.Email?N.EmailBodyControl:N.TextAreaControl;case $.Currency:return N.CurrencyControl;case $.Owner:case $.OwnerType:return N.LookupControl;case $.PartyList:case $.PartyListType:return N.PartyListControl;case $.Status:case $.OptionSet:return N.ChoiceControl;case $.SingleLineofText:return t===W.Email?N.EmailAddressControl:t===W.Phone?N.PhoneNumberControl:t===W.Text?N.TextboxControl:t===W.TextArea?N.TextAreaControl:t===W.TickerSymbol?N.TickerControl:t===W.Url?N.UrlControl:t===W.PhoneticGuide?N.TextboxControl:N.TextboxControl;case $.MultiSelectOptionSet:return N.ChoicesControl;case $.Image:return N.ImageControl;case $.File:return N.FileControl;case $.State:return N.ChoiceControl;case $.Status:return N.ChoiceStatusControl;default:throw new Error(`Cannot get base control for ${e} field type`)}}var G,wa,ft,$u=k(()=>{"use strict";vt();su();dt();rr();vs();ga();ly();kn();G=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"}};wa=class{static get RelationshipAssistant(){return"3ff9a528-dd50-4aca-8f10-2e5ed73513ad"}static get PredictiveLeadScoring(){return"6f503f2a-d033-4106-b62c-f8f2e5f01a57"}},ft=class e{static FieldControlIds=e.initializeFieldControls();static UnboundControlIds=e.initializeUnboundControls();static ControlsAllowedForReferencePanel=e.initializeReferencePanelControls();static ControlsAllowedForFooter=e.initializeFooterControls();static CustomControlIdMap=new dr;static initializeFieldControls(){let t=new dr,r=e.getControlName($.SingleLineofText,W.Phone);t.add(r,new U(G.PhoneNumberControl));let n=e.getControlName($.SingleLineofText,W.TextArea);t.add(n,new U(G.TextAreaControl));let i=e.getControlName($.SingleLineofText,W.Text);t.add(i,new U(G.TextBoxControl));let o=e.getControlName($.SingleLineofText,W.Email);t.add(o,new U(G.EmailAddressControl));let a=e.getControlName($.SingleLineofText,W.Url);t.add(a,new U(G.UrlControl));let s=e.getControlName($.SingleLineofText,W.TickerSymbol);t.add(s,new U(G.TickerControl));let l=e.getControlName($.SingleLineofText,W.PhoneticGuide);t.add(l,new U(G.TextBoxControl));let u=e.getControlName($.WholeNumber,W.Duration);t.add(u,new U(G.DurationControl));let c=e.getControlName($.WholeNumber,W.Language);t.add(c,new U(G.LanguagePickerControl));let d=e.getControlName($.WholeNumber,W.TimeZone);t.add(d,new U(G.TimeZonePicklistControl));let f=e.getControlName($.WholeNumber,W.None);t.add(f,new U(G.IntegerControl));let m=e.getControlName($.DateTime,W.DateOnly);t.add(m,new U(G.DateTimeControl));let p=e.getControlName($.DateTime,W.DateAndTime);t.add(p,new U(G.DateTimeControl));let h=e.getControlName($.LookupType,W.None);t.add(h,new U(G.LookupControl));let g=e.getControlName($.CustomerType,W.None);t.add(g,new U(G.LookupControl));let b=e.getControlName($.FloatingPointNumber,W.None);t.add(b,new U(G.FloatControl));let w=e.getControlName($.DecimalNumber,W.None);t.add(w,new U(G.DecimalControl));let C=e.getControlName($.Currency,W.None);t.add(C,new U(G.MoneyControl));let S=e.getControlName($.MultipleLineofText,W.None);t.add(S,new U(G.TextAreaControl));let O=e.getControlName($.MultipleLineofText,W.Text);t.add(O,new U(G.TextAreaControl));let L=e.getControlName($.MultipleLineofText,W.TextArea);t.add(L,new U(G.TextAreaControl));let I=e.getControlName($.MultipleLineofText,W.Email);t.add(I,new U(G.EmailBodyControl));let D=e.getControlName($.OptionSet,W.None);t.add(D,new U(G.PicklistControl));let P=e.getControlName($.TwoOptions,W.None);t.add(P,new U(G.RadioControl));let x=e.getControlName($.Image,W.None);t.add(x,new U(G.WebResourceImageControl));let K=e.getControlName($.Image,W.None);t.add(K,new U(G.WebResourceHtmlControl));let Le=e.getControlName($.TwoOptions,"Radio");t.add(Le,new U(G.RadioControl));let lr=e.getControlName($.TwoOptions,"CheckBox");t.add(lr,new U(G.CheckBoxControl));let Ge=e.getControlName($.TwoOptions,"List");t.add(Ge,new U(G.PicklistControl));let Ut=e.getControlName($.State,W.None);t.add(Ut,new U(G.PicklistControl));let de=e.getControlName($.Status,W.None);t.add(de,new U(G.PicklistStatusControl));let Ke=e.getControlName($.OwnerType,W.None);t.add(Ke,new U(G.LookupControl));let ur=e.getControlName($.PartyListType,W.None);t.add(ur,new U(G.PartyListControl));let Bt=e.getControlName($.LookupType,W.Regarding);t.add(Bt,new U(G.RegardingControl));let Ni=e.getControlName($.MultiSelectOptionSet,W.None);return t.add(Ni,new U(G.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(!R.IsNullOrEmptyGuid(t)){let r=e.getTypeAndFormatByControlOrUniqueId(t.guidString.toLowerCase());return r=R.IsNullOrUndefined(r)?e.getUnboundControlNameFromIdentifier(t):r.substring(0,r.indexOf("_")),r}return null}static isCustomControl(t){return R.IsNullOrUndefined(t.control)||R.IsNullOrUndefined(t.control.ClassId)||t.control.ClassId.guidString===G.CustomControl}static initializeUnboundControls(){let t=new dr;return t.add(G.ACIControl,ee.ACIControl),t.add(G.IframeControl,ee.IframeControl),t.add(G.SearchWidgetControl,ee.SearchWidgetControl),t.add(G.MapsControl,ee.MapsControl),t.add(G.QuickFormCollectionControl,ee.QuickFormCollectionControl),t.add(G.GridControl,ee.SubGridControl),t.add(G.WebResourceImageControl,ee.WebResourceImageControl),t.add(G.WebResourceHtmlControl,ee.WebResourceHtmlControl),t.add(G.ReferencePanelSearchWidget,ee.SearchWidgetControl),t.add(G.ReferencePanelQuickFormCollectionControl,ee.QuickFormCollectionControl),t.add(G.ReferencePanelSubgridControl,ee.SubGridControl),t.add(G.TimerControl,ee.TimerControl),t.add(G.TimeLineControl,ee.NotesControl),t.add(G.TimeLineControlUC,ee.NotesControl),t.add(G.SocialInsightControl,ee.SocialInsightControl),t.add(wa.RelationshipAssistant,ee.CustomControl),t}static initializeReferencePanelControls(){let t=new dr;return t.add(G.IframeControl,ee.IframeControl),t.add(G.ReferencePanelSearchWidget,ee.SearchWidgetControl),t.add(G.ReferencePanelQuickFormCollectionControl,ee.QuickFormCollectionControl),t.add(G.ReferencePanelSubgridControl,ee.SubGridControl),t.add(G.WebResourceHtmlControl,ee.WebResourceHtmlControl),t.add(G.WebResourceImageControl,ee.WebResourceHtmlControl),t}static initializeFooterControls(){let t=new bs;return t.add(Ms.IFRAME,!0),t.add(Ms.SPACER,!0),t.add(Ms.WEB_RESOURCE_HTML,!0),t}static isUnboundFormControl(t){if(R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.control)||R.IsNullOrUndefined(t.control.ClassId))return!1;let r=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.containsKey(r.guidString)}static isReferencePanelSection(t){return!R.IsNullOrUndefined(t)&&!R.IsNullOrUndefined(t.Name)&&t.Name.indexOf(qe.referencePanelNamePrefix)===0}static isUnboundFormControlByIdentifier(t){return R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.guidString)?!1:e.UnboundControlIds.containsKey(t.guidString)}static getUnboundFormControlName(t){let r=q.EmptyString;if(R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.control)||R.IsNullOrUndefined(t.control.ClassId))return r;let n=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.getValue(n.guidString).toString()}static getUnboundControlNameFromIdentifier(t){return R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.guidString)?q.EmptyString:e.UnboundControlIds.getValue(t.guidString).toString()}static isSpacerControl(t){return t===G.SpacerControl}static GetRowSpan(t){let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===G.CustomControl&&!R.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}switch(e.UnboundControlIds.getValue(r.guidString)){case ee.IframeControl:case ee.ACIControl:case ee.SocialInsightControl:return 6;case ee.SubGridControl:case ee.CustomControl:return 4;case ee.WebResourceImageControl:return 15;case ee.WebResourceHtmlControl:return 15;case ee.MapsControl:return 8;case ee.SearchWidgetControl:return 10;case ee.NotesControl:case ee.TimeLineControl:return 15;case ee.TimerControl:return 2;default:}}static isLookUpControl(t){return!R.IsNullOrUndefined(t)&&t.ClassId.guidString===G.LookupControl}static isRelationshipAssistantOrLeadScoringControl(t){return!R.IsNullOrUndefined(t)&&e.isRelationshipAssistantOrLeadScoring(t.UniqueId)}static isRelationshipAssistantOrLeadScoring(t){return!R.IsNullOrUndefined(t)&&(t.guidString===wa.RelationshipAssistant||t.guidString===wa.PredictiveLeadScoring)}static isRelationshipAssistantControl(t){return!R.IsNullOrUndefined(t)&&e.isRelationshipAssistant(t.UniqueId)}static isRelationshipAssistant(t){return!R.IsNullOrUndefined(t)&&t.guidString===wa.RelationshipAssistant}static getUniqueIdentifierForControl(t){if(R.IsNullOrUndefined(t))return null;let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===G.CustomControl&&!R.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}return r}}});var Gf,DD=k(()=>{"use strict";Gf=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 Ca,Bs,ID,OD,Oo,PD,RD,uy=k(()=>{"use strict";(function(e){e[e.Center=0]="Center",e[e.Left=1]="Left",e[e.Right=2]="Right"})(Ca||(Ca={}));(function(e){e[e.Left=0]="Left",e[e.Top=1]="Top"})(Bs||(Bs={}));(function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle"})(ID||(ID={}));(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"})(OD||(OD={}));(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"})(Oo||(Oo={}));(function(e){e[e.None=0]="None",e[e.SystemRequired=1]="SystemRequired",e[e.ApplicationRequired=2]="ApplicationRequired",e[e.Recommended=3]="Recommended"})(PD||(PD={}));(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"})(RD||(RD={}))});var qs,LD=k(()=>{"use strict";Lu();qs=J0({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 kD(e){return{...e,extractConfig:t=>jj(t,Object.keys(e.fallback))}}function jj(e,t){let r={};for(let n of t)typeof e[n]<"u"&&(r[n]=e[n]);return r}var cy=k(()=>{"use strict";});var dy=v((xpe,xD)=>{var xu=new Proxy(function(){return xu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:xu},apply:function(){return xu},construct:function(){return{}}}),$D=function(){return xu};Object.setPrototypeOf($D,xu);xD.exports=$D});var UD=v((Fpe,MD)=>{var Fu=new Proxy(function(){return Fu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Fu},apply:function(){return Fu},construct:function(){return{}}}),FD=function(){return Fu};Object.setPrototypeOf(FD,Fu);MD.exports=FD});var fy=v((Mpe,qD)=>{var Mu=new Proxy(function(){return Mu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Mu},apply:function(){return Mu},construct:function(){return{}}}),BD=function(){return Mu};Object.setPrototypeOf(BD,Mu);qD.exports=BD});var GD=v((Upe,VD)=>{function Hj(){this.__data__=[],this.size=0}VD.exports=Hj});var Vs=v((Bpe,WD)=>{function Kj(e,t){return e===t||e!==e&&t!==t}WD.exports=Kj});var Uu=v((qpe,zD)=>{var Jj=Vs();function Yj(e,t){for(var r=e.length;r--;)if(Jj(e[r][0],t))return r;return-1}zD.exports=Yj});var HD=v((Vpe,jD)=>{var Qj=Uu(),Xj=Array.prototype,Zj=Xj.splice;function e7(e){var t=this.__data__,r=Qj(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():Zj.call(t,r,1),--this.size,!0}jD.exports=e7});var JD=v((Gpe,KD)=>{var t7=Uu();function r7(e){var t=this.__data__,r=t7(t,e);return r<0?void 0:t[r][1]}KD.exports=r7});var QD=v((Wpe,YD)=>{var n7=Uu();function i7(e){return n7(this.__data__,e)>-1}YD.exports=i7});var ZD=v((zpe,XD)=>{var o7=Uu();function a7(e,t){var r=this.__data__,n=o7(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}XD.exports=a7});var Bu=v((jpe,eI)=>{var s7=GD(),l7=HD(),u7=JD(),c7=QD(),d7=ZD();function Gs(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])}}Gs.prototype.clear=s7;Gs.prototype.delete=l7;Gs.prototype.get=u7;Gs.prototype.has=c7;Gs.prototype.set=d7;eI.exports=Gs});var rI=v((Hpe,tI)=>{var f7=Bu();function p7(){this.__data__=new f7,this.size=0}tI.exports=p7});var iI=v((Kpe,nI)=>{function m7(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}nI.exports=m7});var aI=v((Jpe,oI)=>{function h7(e){return this.__data__.get(e)}oI.exports=h7});var lI=v((Ype,sI)=>{function g7(e){return this.__data__.has(e)}sI.exports=g7});var py=v((Qpe,uI)=>{var y7=typeof global=="object"&&global&&global.Object===Object&&global;uI.exports=y7});var xn=v((Xpe,cI)=>{var b7=py(),v7=typeof self=="object"&&self&&self.Object===Object&&self,w7=b7||v7||Function("return this")();cI.exports=w7});var qu=v((Zpe,dI)=>{var C7=xn(),E7=C7.Symbol;dI.exports=E7});var hI=v((eme,mI)=>{var fI=qu(),pI=Object.prototype,A7=pI.hasOwnProperty,S7=pI.toString,Vu=fI?fI.toStringTag:void 0;function N7(e){var t=A7.call(e,Vu),r=e[Vu];try{e[Vu]=void 0;var n=!0}catch{}var i=S7.call(e);return n&&(t?e[Vu]=r:delete e[Vu]),i}mI.exports=N7});var yI=v((tme,gI)=>{var _7=Object.prototype,T7=_7.toString;function D7(e){return T7.call(e)}gI.exports=D7});var Ea=v((rme,wI)=>{var bI=qu(),I7=hI(),O7=yI(),P7="[object Null]",R7="[object Undefined]",vI=bI?bI.toStringTag:void 0;function L7(e){return e==null?e===void 0?R7:P7:vI&&vI in Object(e)?I7(e):O7(e)}wI.exports=L7});var Hi=v((nme,CI)=>{function k7(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}CI.exports=k7});var Wf=v((ime,EI)=>{var $7=Ea(),x7=Hi(),F7="[object AsyncFunction]",M7="[object Function]",U7="[object GeneratorFunction]",B7="[object Proxy]";function q7(e){if(!x7(e))return!1;var t=$7(e);return t==M7||t==U7||t==F7||t==B7}EI.exports=q7});var SI=v((ome,AI)=>{var V7=xn(),G7=V7["__core-js_shared__"];AI.exports=G7});var TI=v((ame,_I)=>{var my=SI(),NI=(function(){var e=/[^.]+$/.exec(my&&my.keys&&my.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function W7(e){return!!NI&&NI in e}_I.exports=W7});var hy=v((sme,DI)=>{var z7=Function.prototype,j7=z7.toString;function H7(e){if(e!=null){try{return j7.call(e)}catch{}try{return e+""}catch{}}return""}DI.exports=H7});var OI=v((lme,II)=>{var K7=Wf(),J7=TI(),Y7=Hi(),Q7=hy(),X7=/[\\^$.*+?()[\]{}|]/g,Z7=/^\[object .+?Constructor\]$/,eH=Function.prototype,tH=Object.prototype,rH=eH.toString,nH=tH.hasOwnProperty,iH=RegExp("^"+rH.call(nH).replace(X7,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function oH(e){if(!Y7(e)||J7(e))return!1;var t=K7(e)?iH:Z7;return t.test(Q7(e))}II.exports=oH});var RI=v((ume,PI)=>{function aH(e,t){return e?.[t]}PI.exports=aH});var Po=v((cme,LI)=>{var sH=OI(),lH=RI();function uH(e,t){var r=lH(e,t);return sH(r)?r:void 0}LI.exports=uH});var zf=v((dme,kI)=>{var cH=Po(),dH=xn(),fH=cH(dH,"Map");kI.exports=fH});var Gu=v((fme,$I)=>{var pH=Po(),mH=pH(Object,"create");$I.exports=mH});var MI=v((pme,FI)=>{var xI=Gu();function hH(){this.__data__=xI?xI(null):{},this.size=0}FI.exports=hH});var BI=v((mme,UI)=>{function gH(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}UI.exports=gH});var VI=v((hme,qI)=>{var yH=Gu(),bH="__lodash_hash_undefined__",vH=Object.prototype,wH=vH.hasOwnProperty;function CH(e){var t=this.__data__;if(yH){var r=t[e];return r===bH?void 0:r}return wH.call(t,e)?t[e]:void 0}qI.exports=CH});var WI=v((gme,GI)=>{var EH=Gu(),AH=Object.prototype,SH=AH.hasOwnProperty;function NH(e){var t=this.__data__;return EH?t[e]!==void 0:SH.call(t,e)}GI.exports=NH});var jI=v((yme,zI)=>{var _H=Gu(),TH="__lodash_hash_undefined__";function DH(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=_H&&t===void 0?TH:t,this}zI.exports=DH});var KI=v((bme,HI)=>{var IH=MI(),OH=BI(),PH=VI(),RH=WI(),LH=jI();function Ws(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])}}Ws.prototype.clear=IH;Ws.prototype.delete=OH;Ws.prototype.get=PH;Ws.prototype.has=RH;Ws.prototype.set=LH;HI.exports=Ws});var QI=v((vme,YI)=>{var JI=KI(),kH=Bu(),$H=zf();function xH(){this.size=0,this.__data__={hash:new JI,map:new($H||kH),string:new JI}}YI.exports=xH});var ZI=v((wme,XI)=>{function FH(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}XI.exports=FH});var Wu=v((Cme,eO)=>{var MH=ZI();function UH(e,t){var r=e.__data__;return MH(t)?r[typeof t=="string"?"string":"hash"]:r.map}eO.exports=UH});var rO=v((Eme,tO)=>{var BH=Wu();function qH(e){var t=BH(this,e).delete(e);return this.size-=t?1:0,t}tO.exports=qH});var iO=v((Ame,nO)=>{var VH=Wu();function GH(e){return VH(this,e).get(e)}nO.exports=GH});var aO=v((Sme,oO)=>{var WH=Wu();function zH(e){return WH(this,e).has(e)}oO.exports=zH});var lO=v((Nme,sO)=>{var jH=Wu();function HH(e,t){var r=jH(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}sO.exports=HH});var jf=v((_me,uO)=>{var KH=QI(),JH=rO(),YH=iO(),QH=aO(),XH=lO();function zs(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])}}zs.prototype.clear=KH;zs.prototype.delete=JH;zs.prototype.get=YH;zs.prototype.has=QH;zs.prototype.set=XH;uO.exports=zs});var dO=v((Tme,cO)=>{var ZH=Bu(),eK=zf(),tK=jf(),rK=200;function nK(e,t){var r=this.__data__;if(r instanceof ZH){var n=r.__data__;if(!eK||n.length<rK-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new tK(n)}return r.set(e,t),this.size=r.size,this}cO.exports=nK});var gy=v((Dme,fO)=>{var iK=Bu(),oK=rI(),aK=iI(),sK=aI(),lK=lI(),uK=dO();function js(e){var t=this.__data__=new iK(e);this.size=t.size}js.prototype.clear=oK;js.prototype.delete=aK;js.prototype.get=sK;js.prototype.has=lK;js.prototype.set=uK;fO.exports=js});var mO=v((Ime,pO)=>{var cK="__lodash_hash_undefined__";function dK(e){return this.__data__.set(e,cK),this}pO.exports=dK});var gO=v((Ome,hO)=>{function fK(e){return this.__data__.has(e)}hO.exports=fK});var bO=v((Pme,yO)=>{var pK=jf(),mK=mO(),hK=gO();function Hf(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new pK;++t<r;)this.add(e[t])}Hf.prototype.add=Hf.prototype.push=mK;Hf.prototype.has=hK;yO.exports=Hf});var wO=v((Rme,vO)=>{function gK(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}vO.exports=gK});var EO=v((Lme,CO)=>{function yK(e,t){return e.has(t)}CO.exports=yK});var yy=v((kme,AO)=>{var bK=bO(),vK=wO(),wK=EO(),CK=1,EK=2;function AK(e,t,r,n,i,o){var a=r&CK,s=e.length,l=t.length;if(s!=l&&!(a&&l>s))return!1;var u=o.get(e),c=o.get(t);if(u&&c)return u==t&&c==e;var d=-1,f=!0,m=r&EK?new bK:void 0;for(o.set(e,t),o.set(t,e);++d<s;){var p=e[d],h=t[d];if(n)var g=a?n(h,p,d,t,e,o):n(p,h,d,e,t,o);if(g!==void 0){if(g)continue;f=!1;break}if(m){if(!vK(t,function(b,w){if(!wK(m,w)&&(p===b||i(p,b,r,n,o)))return m.push(w)})){f=!1;break}}else if(!(p===h||i(p,h,r,n,o))){f=!1;break}}return o.delete(e),o.delete(t),f}AO.exports=AK});var by=v(($me,SO)=>{var SK=xn(),NK=SK.Uint8Array;SO.exports=NK});var _O=v((xme,NO)=>{function _K(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}NO.exports=_K});var DO=v((Fme,TO)=>{function TK(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}TO.exports=TK});var LO=v((Mme,RO)=>{var IO=qu(),OO=by(),DK=Vs(),IK=yy(),OK=_O(),PK=DO(),RK=1,LK=2,kK="[object Boolean]",$K="[object Date]",xK="[object Error]",FK="[object Map]",MK="[object Number]",UK="[object RegExp]",BK="[object Set]",qK="[object String]",VK="[object Symbol]",GK="[object ArrayBuffer]",WK="[object DataView]",PO=IO?IO.prototype:void 0,vy=PO?PO.valueOf:void 0;function zK(e,t,r,n,i,o,a){switch(r){case WK:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case GK:return!(e.byteLength!=t.byteLength||!o(new OO(e),new OO(t)));case kK:case $K:case MK:return DK(+e,+t);case xK:return e.name==t.name&&e.message==t.message;case UK:case qK:return e==t+"";case FK:var s=OK;case BK:var l=n&RK;if(s||(s=PK),e.size!=t.size&&!l)return!1;var u=a.get(e);if(u)return u==t;n|=LK,a.set(e,t);var c=IK(s(e),s(t),n,i,o,a);return a.delete(e),c;case VK:if(vy)return vy.call(e)==vy.call(t)}return!1}RO.exports=zK});var $O=v((Ume,kO)=>{function jK(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}kO.exports=jK});var Ro=v((Bme,xO)=>{var HK=Array.isArray;xO.exports=HK});var MO=v((qme,FO)=>{var KK=$O(),JK=Ro();function YK(e,t,r){var n=t(e);return JK(e)?n:KK(n,r(e))}FO.exports=YK});var BO=v((Vme,UO)=>{function QK(e,t){for(var r=-1,n=e==null?0:e.length,i=0,o=[];++r<n;){var a=e[r];t(a,r,e)&&(o[i++]=a)}return o}UO.exports=QK});var VO=v((Gme,qO)=>{function XK(){return[]}qO.exports=XK});var zO=v((Wme,WO)=>{var ZK=BO(),eJ=VO(),tJ=Object.prototype,rJ=tJ.propertyIsEnumerable,GO=Object.getOwnPropertySymbols,nJ=GO?function(e){return e==null?[]:(e=Object(e),ZK(GO(e),function(t){return rJ.call(e,t)}))}:eJ;WO.exports=nJ});var HO=v((zme,jO)=>{function iJ(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}jO.exports=iJ});var Lo=v((jme,KO)=>{function oJ(e){return e!=null&&typeof e=="object"}KO.exports=oJ});var YO=v((Hme,JO)=>{var aJ=Ea(),sJ=Lo(),lJ="[object Arguments]";function uJ(e){return sJ(e)&&aJ(e)==lJ}JO.exports=uJ});var wy=v((Kme,ZO)=>{var QO=YO(),cJ=Lo(),XO=Object.prototype,dJ=XO.hasOwnProperty,fJ=XO.propertyIsEnumerable,pJ=QO((function(){return arguments})())?QO:function(e){return cJ(e)&&dJ.call(e,"callee")&&!fJ.call(e,"callee")};ZO.exports=pJ});var tP=v((Jme,eP)=>{function mJ(){return!1}eP.exports=mJ});var Kf=v((zu,Hs)=>{var hJ=xn(),gJ=tP(),iP=typeof zu=="object"&&zu&&!zu.nodeType&&zu,rP=iP&&typeof Hs=="object"&&Hs&&!Hs.nodeType&&Hs,yJ=rP&&rP.exports===iP,nP=yJ?hJ.Buffer:void 0,bJ=nP?nP.isBuffer:void 0,vJ=bJ||gJ;Hs.exports=vJ});var Jf=v((Yme,oP)=>{var wJ=9007199254740991,CJ=/^(?:0|[1-9]\d*)$/;function EJ(e,t){var r=typeof e;return t=t??wJ,!!t&&(r=="number"||r!="symbol"&&CJ.test(e))&&e>-1&&e%1==0&&e<t}oP.exports=EJ});var Cy=v((Qme,aP)=>{var AJ=9007199254740991;function SJ(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=AJ}aP.exports=SJ});var lP=v((Xme,sP)=>{var NJ=Ea(),_J=Cy(),TJ=Lo(),DJ="[object Arguments]",IJ="[object Array]",OJ="[object Boolean]",PJ="[object Date]",RJ="[object Error]",LJ="[object Function]",kJ="[object Map]",$J="[object Number]",xJ="[object Object]",FJ="[object RegExp]",MJ="[object Set]",UJ="[object String]",BJ="[object WeakMap]",qJ="[object ArrayBuffer]",VJ="[object DataView]",GJ="[object Float32Array]",WJ="[object Float64Array]",zJ="[object Int8Array]",jJ="[object Int16Array]",HJ="[object Int32Array]",KJ="[object Uint8Array]",JJ="[object Uint8ClampedArray]",YJ="[object Uint16Array]",QJ="[object Uint32Array]",xe={};xe[GJ]=xe[WJ]=xe[zJ]=xe[jJ]=xe[HJ]=xe[KJ]=xe[JJ]=xe[YJ]=xe[QJ]=!0;xe[DJ]=xe[IJ]=xe[qJ]=xe[OJ]=xe[VJ]=xe[PJ]=xe[RJ]=xe[LJ]=xe[kJ]=xe[$J]=xe[xJ]=xe[FJ]=xe[MJ]=xe[UJ]=xe[BJ]=!1;function XJ(e){return TJ(e)&&_J(e.length)&&!!xe[NJ(e)]}sP.exports=XJ});var cP=v((Zme,uP)=>{function ZJ(e){return function(t){return e(t)}}uP.exports=ZJ});var fP=v((ju,Ks)=>{var eY=py(),dP=typeof ju=="object"&&ju&&!ju.nodeType&&ju,Hu=dP&&typeof Ks=="object"&&Ks&&!Ks.nodeType&&Ks,tY=Hu&&Hu.exports===dP,Ey=tY&&eY.process,rY=(function(){try{var e=Hu&&Hu.require&&Hu.require("util").types;return e||Ey&&Ey.binding&&Ey.binding("util")}catch{}})();Ks.exports=rY});var Yf=v((ehe,hP)=>{var nY=lP(),iY=cP(),pP=fP(),mP=pP&&pP.isTypedArray,oY=mP?iY(mP):nY;hP.exports=oY});var Ay=v((the,gP)=>{var aY=HO(),sY=wy(),lY=Ro(),uY=Kf(),cY=Jf(),dY=Yf(),fY=Object.prototype,pY=fY.hasOwnProperty;function mY(e,t){var r=lY(e),n=!r&&sY(e),i=!r&&!n&&uY(e),o=!r&&!n&&!i&&dY(e),a=r||n||i||o,s=a?aY(e.length,String):[],l=s.length;for(var u in e)(t||pY.call(e,u))&&!(a&&(u=="length"||i&&(u=="offset"||u=="parent")||o&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||cY(u,l)))&&s.push(u);return s}gP.exports=mY});var Qf=v((rhe,yP)=>{var hY=Object.prototype;function gY(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||hY;return e===r}yP.exports=gY});var Sy=v((nhe,bP)=>{function yY(e,t){return function(r){return e(t(r))}}bP.exports=yY});var wP=v((ihe,vP)=>{var bY=Sy(),vY=bY(Object.keys,Object);vP.exports=vY});var EP=v((ohe,CP)=>{var wY=Qf(),CY=wP(),EY=Object.prototype,AY=EY.hasOwnProperty;function SY(e){if(!wY(e))return CY(e);var t=[];for(var r in Object(e))AY.call(e,r)&&r!="constructor"&&t.push(r);return t}CP.exports=SY});var Ku=v((ahe,AP)=>{var NY=Wf(),_Y=Cy();function TY(e){return e!=null&&_Y(e.length)&&!NY(e)}AP.exports=TY});var NP=v((she,SP)=>{var DY=Ay(),IY=EP(),OY=Ku();function PY(e){return OY(e)?DY(e):IY(e)}SP.exports=PY});var TP=v((lhe,_P)=>{var RY=MO(),LY=zO(),kY=NP();function $Y(e){return RY(e,kY,LY)}_P.exports=$Y});var OP=v((uhe,IP)=>{var DP=TP(),xY=1,FY=Object.prototype,MY=FY.hasOwnProperty;function UY(e,t,r,n,i,o){var a=r&xY,s=DP(e),l=s.length,u=DP(t),c=u.length;if(l!=c&&!a)return!1;for(var d=l;d--;){var f=s[d];if(!(a?f in t:MY.call(t,f)))return!1}var m=o.get(e),p=o.get(t);if(m&&p)return m==t&&p==e;var h=!0;o.set(e,t),o.set(t,e);for(var g=a;++d<l;){f=s[d];var b=e[f],w=t[f];if(n)var C=a?n(w,b,f,t,e,o):n(b,w,f,e,t,o);if(!(C===void 0?b===w||i(b,w,r,n,o):C)){h=!1;break}g||(g=f=="constructor")}if(h&&!g){var S=e.constructor,O=t.constructor;S!=O&&"constructor"in e&&"constructor"in t&&!(typeof S=="function"&&S instanceof S&&typeof O=="function"&&O instanceof O)&&(h=!1)}return o.delete(e),o.delete(t),h}IP.exports=UY});var RP=v((che,PP)=>{var BY=Po(),qY=xn(),VY=BY(qY,"DataView");PP.exports=VY});var kP=v((dhe,LP)=>{var GY=Po(),WY=xn(),zY=GY(WY,"Promise");LP.exports=zY});var xP=v((fhe,$P)=>{var jY=Po(),HY=xn(),KY=jY(HY,"Set");$P.exports=KY});var MP=v((phe,FP)=>{var JY=Po(),YY=xn(),QY=JY(YY,"WeakMap");FP.exports=QY});var jP=v((mhe,zP)=>{var Ny=RP(),_y=zf(),Ty=kP(),Dy=xP(),Iy=MP(),WP=Ea(),Js=hy(),UP="[object Map]",XY="[object Object]",BP="[object Promise]",qP="[object Set]",VP="[object WeakMap]",GP="[object DataView]",ZY=Js(Ny),eQ=Js(_y),tQ=Js(Ty),rQ=Js(Dy),nQ=Js(Iy),Aa=WP;(Ny&&Aa(new Ny(new ArrayBuffer(1)))!=GP||_y&&Aa(new _y)!=UP||Ty&&Aa(Ty.resolve())!=BP||Dy&&Aa(new Dy)!=qP||Iy&&Aa(new Iy)!=VP)&&(Aa=function(e){var t=WP(e),r=t==XY?e.constructor:void 0,n=r?Js(r):"";if(n)switch(n){case ZY:return GP;case eQ:return UP;case tQ:return BP;case rQ:return qP;case nQ:return VP}return t});zP.exports=Aa});var eR=v((hhe,ZP)=>{var Oy=gy(),iQ=yy(),oQ=LO(),aQ=OP(),HP=jP(),KP=Ro(),JP=Kf(),sQ=Yf(),lQ=1,YP="[object Arguments]",QP="[object Array]",Xf="[object Object]",uQ=Object.prototype,XP=uQ.hasOwnProperty;function cQ(e,t,r,n,i,o){var a=KP(e),s=KP(t),l=a?QP:HP(e),u=s?QP:HP(t);l=l==YP?Xf:l,u=u==YP?Xf:u;var c=l==Xf,d=u==Xf,f=l==u;if(f&&JP(e)){if(!JP(t))return!1;a=!0,c=!1}if(f&&!c)return o||(o=new Oy),a||sQ(e)?iQ(e,t,r,n,i,o):oQ(e,t,l,r,n,i,o);if(!(r&lQ)){var m=c&&XP.call(e,"__wrapped__"),p=d&&XP.call(t,"__wrapped__");if(m||p){var h=m?e.value():e,g=p?t.value():t;return o||(o=new Oy),i(h,g,r,n,o)}}return f?(o||(o=new Oy),aQ(e,t,r,n,i,o)):!1}ZP.exports=cQ});var iR=v((ghe,nR)=>{var dQ=eR(),tR=Lo();function rR(e,t,r,n,i){return e===t?!0:e==null||t==null||!tR(e)&&!tR(t)?e!==e&&t!==t:dQ(e,t,r,n,rR,i)}nR.exports=rR});var aR=v((yhe,oR)=>{var fQ=iR();function pQ(e,t){return fQ(e,t)}oR.exports=pQ});var Py=v((bhe,sR)=>{var mQ=Po(),hQ=(function(){try{var e=mQ(Object,"defineProperty");return e({},"",{}),e}catch{}})();sR.exports=hQ});var Zf=v((vhe,uR)=>{var lR=Py();function gQ(e,t,r){t=="__proto__"&&lR?lR(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}uR.exports=gQ});var Ry=v((whe,cR)=>{var yQ=Zf(),bQ=Vs();function vQ(e,t,r){(r!==void 0&&!bQ(e[t],r)||r===void 0&&!(t in e))&&yQ(e,t,r)}cR.exports=vQ});var fR=v((Che,dR)=>{function wQ(e){return function(t,r,n){for(var i=-1,o=Object(t),a=n(t),s=a.length;s--;){var l=a[e?s:++i];if(r(o[l],l,o)===!1)break}return t}}dR.exports=wQ});var mR=v((Ehe,pR)=>{var CQ=fR(),EQ=CQ();pR.exports=EQ});var vR=v((Ju,Ys)=>{var AQ=xn(),bR=typeof Ju=="object"&&Ju&&!Ju.nodeType&&Ju,hR=bR&&typeof Ys=="object"&&Ys&&!Ys.nodeType&&Ys,SQ=hR&&hR.exports===bR,gR=SQ?AQ.Buffer:void 0,yR=gR?gR.allocUnsafe:void 0;function NQ(e,t){if(t)return e.slice();var r=e.length,n=yR?yR(r):new e.constructor(r);return e.copy(n),n}Ys.exports=NQ});var ER=v((Ahe,CR)=>{var wR=by();function _Q(e){var t=new e.constructor(e.byteLength);return new wR(t).set(new wR(e)),t}CR.exports=_Q});var SR=v((She,AR)=>{var TQ=ER();function DQ(e,t){var r=t?TQ(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}AR.exports=DQ});var _R=v((Nhe,NR)=>{function IQ(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}NR.exports=IQ});var IR=v((_he,DR)=>{var OQ=Hi(),TR=Object.create,PQ=(function(){function e(){}return function(t){if(!OQ(t))return{};if(TR)return TR(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})();DR.exports=PQ});var Ly=v((The,OR)=>{var RQ=Sy(),LQ=RQ(Object.getPrototypeOf,Object);OR.exports=LQ});var RR=v((Dhe,PR)=>{var kQ=IR(),$Q=Ly(),xQ=Qf();function FQ(e){return typeof e.constructor=="function"&&!xQ(e)?kQ($Q(e)):{}}PR.exports=FQ});var kR=v((Ihe,LR)=>{var MQ=Ku(),UQ=Lo();function BQ(e){return UQ(e)&&MQ(e)}LR.exports=BQ});var FR=v((Ohe,xR)=>{var qQ=Ea(),VQ=Ly(),GQ=Lo(),WQ="[object Object]",zQ=Function.prototype,jQ=Object.prototype,$R=zQ.toString,HQ=jQ.hasOwnProperty,KQ=$R.call(Object);function JQ(e){if(!GQ(e)||qQ(e)!=WQ)return!1;var t=VQ(e);if(t===null)return!0;var r=HQ.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&$R.call(r)==KQ}xR.exports=JQ});var ky=v((Phe,MR)=>{function YQ(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}MR.exports=YQ});var $y=v((Rhe,UR)=>{var QQ=Zf(),XQ=Vs(),ZQ=Object.prototype,eX=ZQ.hasOwnProperty;function tX(e,t,r){var n=e[t];(!(eX.call(e,t)&&XQ(n,r))||r===void 0&&!(t in e))&&QQ(e,t,r)}UR.exports=tX});var qR=v((Lhe,BR)=>{var rX=$y(),nX=Zf();function iX(e,t,r,n){var i=!r;r||(r={});for(var o=-1,a=t.length;++o<a;){var s=t[o],l=n?n(r[s],e[s],s,r,e):void 0;l===void 0&&(l=e[s]),i?nX(r,s,l):rX(r,s,l)}return r}BR.exports=iX});var GR=v((khe,VR)=>{function oX(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}VR.exports=oX});var zR=v(($he,WR)=>{var aX=Hi(),sX=Qf(),lX=GR(),uX=Object.prototype,cX=uX.hasOwnProperty;function dX(e){if(!aX(e))return lX(e);var t=sX(e),r=[];for(var n in e)n=="constructor"&&(t||!cX.call(e,n))||r.push(n);return r}WR.exports=dX});var xy=v((xhe,jR)=>{var fX=Ay(),pX=zR(),mX=Ku();function hX(e){return mX(e)?fX(e,!0):pX(e)}jR.exports=hX});var KR=v((Fhe,HR)=>{var gX=qR(),yX=xy();function bX(e){return gX(e,yX(e))}HR.exports=bX});var e2=v((Mhe,ZR)=>{var JR=Ry(),vX=vR(),wX=SR(),CX=_R(),EX=RR(),YR=wy(),QR=Ro(),AX=kR(),SX=Kf(),NX=Wf(),_X=Hi(),TX=FR(),DX=Yf(),XR=ky(),IX=KR();function OX(e,t,r,n,i,o,a){var s=XR(e,r),l=XR(t,r),u=a.get(l);if(u){JR(e,r,u);return}var c=o?o(s,l,r+"",e,t,a):void 0,d=c===void 0;if(d){var f=QR(l),m=!f&&SX(l),p=!f&&!m&&DX(l);c=l,f||m||p?QR(s)?c=s:AX(s)?c=CX(s):m?(d=!1,c=vX(l,!0)):p?(d=!1,c=wX(l,!0)):c=[]:TX(l)||YR(l)?(c=s,YR(s)?c=IX(s):(!_X(s)||NX(s))&&(c=EX(l))):d=!1}d&&(a.set(l,c),i(c,l,n,o,a),a.delete(l)),JR(e,r,c)}ZR.exports=OX});var Fy=v((Uhe,r2)=>{var PX=gy(),RX=Ry(),LX=mR(),kX=e2(),$X=Hi(),xX=xy(),FX=ky();function t2(e,t,r,n,i){e!==t&&LX(t,function(o,a){if(i||(i=new PX),$X(o))kX(e,t,a,r,t2,n,i);else{var s=n?n(FX(e,a),o,a+"",e,t,i):void 0;s===void 0&&(s=o),RX(e,a,s)}},xX)}r2.exports=t2});var My=v((Bhe,n2)=>{function MX(e){return e}n2.exports=MX});var o2=v((qhe,i2)=>{function UX(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)}i2.exports=UX});var l2=v((Vhe,s2)=>{var BX=o2(),a2=Math.max;function qX(e,t,r){return t=a2(t===void 0?e.length-1:t,0),function(){for(var n=arguments,i=-1,o=a2(n.length-t,0),a=Array(o);++i<o;)a[i]=n[t+i];i=-1;for(var s=Array(t+1);++i<t;)s[i]=n[i];return s[t]=r(a),BX(e,this,s)}}s2.exports=qX});var c2=v((Ghe,u2)=>{function VX(e){return function(){return e}}u2.exports=VX});var p2=v((Whe,f2)=>{var GX=c2(),d2=Py(),WX=My(),zX=d2?function(e,t){return d2(e,"toString",{configurable:!0,enumerable:!1,value:GX(t),writable:!0})}:WX;f2.exports=zX});var h2=v((zhe,m2)=>{var jX=800,HX=16,KX=Date.now;function JX(e){var t=0,r=0;return function(){var n=KX(),i=HX-(n-r);if(r=n,i>0){if(++t>=jX)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}m2.exports=JX});var y2=v((jhe,g2)=>{var YX=p2(),QX=h2(),XX=QX(YX);g2.exports=XX});var v2=v((Hhe,b2)=>{var ZX=My(),eZ=l2(),tZ=y2();function rZ(e,t){return tZ(eZ(e,t,ZX),e+"")}b2.exports=rZ});var C2=v((Khe,w2)=>{var nZ=Vs(),iZ=Ku(),oZ=Jf(),aZ=Hi();function sZ(e,t,r){if(!aZ(r))return!1;var n=typeof t;return(n=="number"?iZ(r)&&oZ(t,r.length):n=="string"&&t in r)?nZ(r[t],e):!1}w2.exports=sZ});var Uy=v((Jhe,E2)=>{var lZ=v2(),uZ=C2();function cZ(e){return lZ(function(t,r){var n=-1,i=r.length,o=i>1?r[i-1]:void 0,a=i>2?r[2]:void 0;for(o=e.length>3&&typeof o=="function"?(i--,o):void 0,a&&uZ(r[0],r[1],a)&&(o=i<3?void 0:o,i=1),t=Object(t);++n<i;){var s=r[n];s&&e(t,s,n,o)}return t})}E2.exports=cZ});var S2=v((Yhe,A2)=>{var dZ=Fy(),fZ=Uy(),pZ=fZ(function(e,t,r,n){dZ(e,t,r,n)});A2.exports=pZ});var gn,Yu=k(()=>{"use strict";(function(e){e[e.NotLoaded=0]="NotLoaded",e[e.Initialized=1]="Initialized",e[e.ConfigsLoaded=2]="ConfigsLoaded",e[e.Error=3]="Error"})(gn||(gn={}))});function _2(e,t,r="PROD"){let n=i=>`ShellSettings_ECS_ClientCache_${e}_${N2.EcsConfigType[i]}_${r}`;return{getData:i=>{let o=t.getItem(n(i));return Promise.resolve(o?JSON.parse(o):void 0)},putData:(i,o)=>(t.setItem(n(i),JSON.stringify(o)),Promise.resolve())}}var N2,mZ,T2=k(()=>{"use strict";N2=Ce(fy()),mZ=Ce(dy());});var By,D2=k(()=>{"use strict";xf();By=Ru({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 O2,P2,R2,L2,qy,hZ,ep,I2,Vy=k(()=>{"use strict";O2=Ce(dy()),P2=Ce(UD()),R2=Ce(fy()),L2=Ce(aR()),qy=Ce(S2());Yu();T2();D2();hZ=60*1e3,ep=class{clientName;logger;ecsEndpoint;resolveLoadingPromise;loadingPromise=new Promise(t=>this.resolveLoadingPromise=t);_status=gn.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"?By.prodEcsEndpoint:By.integrationEcsEndpoint}client=new P2.default;init=async({clientVersion:t,getFilters:r,cacheStorage:n=O2.StorageHelper.transientWithGlobalFallback,updateIntervalInMinutes:i,overrideEcsInitParams:o})=>{this.client.telemetryEventAdded.subscribe(this.logger.logEvent),this.client.configUpdated.subscribe(this.handleConfigUpdated);let a=(async()=>{let s=await r();return this.logEvent("FeaturesClient/configRequested",{ecsClientName:this.clientName,filters:s}),s});try{await this.client.initialize({clientName:this.clientName,clientVersion:t??"1.0.0.0",configsToFetch:[R2.EcsConfigType.Default],hosts:[this.ecsEndpoint],initialAppActiveState:!0,getEcsParameters:a,databaseInterface:_2(this.clientName,n,this.endpointType),...o}),this.client.requestUpdate(),this._status===gn.NotLoaded&&(this._status=gn.Initialized)}catch(s){this._status=gn.Error,this.resolveLoadingPromise(),this.logEvent("FeaturesClient/initializationFailed",{ecsClientName:this.clientName,error:s},"Error")}i&&window.setInterval(()=>this.client.requestUpdate(),i*hZ)};getConfig=t=>{let r=this.getMergedClientConfigByTeamName(t.teamName),n=r?t.extractConfig(r):{};return(0,qy.default)({},t.fallback,n,t.override,I2)};getAllConfigs=()=>this.getMergedClientConfig();getAllConfigsByTeamName=t=>this.getMergedClientConfigByTeamName(t);requestConfigUpdate=()=>{this.client.requestUpdate()};subscribe=(t,r)=>{let n=this.getConfig(t),i=this.client.configUpdated.subscribe(()=>{let o=this.getConfig(t);(0,L2.default)(o,n)||(n={...o},r(o))});return{unsubscribe:()=>i.unsubscribe()}};waitUntilLoaded=async t=>{if(t!==void 0){let r,n=new Promise((i,o)=>{r=window.setTimeout(()=>{o(new Error("Timed out waiting for configuration to load"))},t)});await Promise.race([this.loadingPromise,n]),clearTimeout(r)}else await this.loadingPromise};overrideClientConfig(t){this.logger.logEvent("FeaturesClient/overrideClientConfig",{clientConfigOverride:t}),this.clientConfigOverride=t}undoClientConfigOverride(){this.clientConfigOverride=void 0,this.logger.logEvent("FeaturesClient/undoClientConfigOverride")}getMergedClientConfig=()=>(0,qy.default)({},this.client.getConfig()?.config,this.clientConfigOverride,I2);getMergedClientConfigByTeamName=t=>this.getMergedClientConfig()?.[t];handleConfigUpdated=()=>{let t=this.client.getConfig();if(t===void 0)return;this.resolveLoadingPromise(),this._status=gn.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})}},I2=(e,t)=>{if(Array.isArray(t))return t}});var $2=v((oge,k2)=>{"use strict";var gZ=()=>{let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e};k2.exports=gZ});var Gy=v((age,F2)=>{var Qu=new Proxy(function(){return Qu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Qu},apply:function(){return Qu},construct:function(){return{}}}),x2=function(){return Qu};Object.setPrototypeOf(x2,Qu);F2.exports=x2});var B2=v((sge,U2)=>{var Xu=new Proxy(function(){return Xu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Xu},apply:function(){return Xu},construct:function(){return{}}}),M2=function(){return Xu};Object.setPrototypeOf(M2,Xu);U2.exports=M2});var H2=v((lge,j2)=>{"use strict";var Wy=B2(),yZ={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},bZ={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},vZ={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},W2={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},zy={};zy[Wy.ForwardRef]=vZ;zy[Wy.Memo]=W2;function q2(e){return Wy.isMemo(e)?W2:zy[e.$$typeof]||yZ}var wZ=Object.defineProperty,CZ=Object.getOwnPropertyNames,V2=Object.getOwnPropertySymbols,EZ=Object.getOwnPropertyDescriptor,AZ=Object.getPrototypeOf,G2=Object.prototype;function z2(e,t,r){if(typeof t!="string"){if(G2){var n=AZ(t);n&&n!==G2&&z2(e,n,r)}var i=CZ(t);V2&&(i=i.concat(V2(t)));for(var o=q2(e),a=q2(t),s=0;s<i.length;++s){var l=i[s];if(!bZ[l]&&!(r&&r[l])&&!(a&&a[l])&&!(o&&o[l])){var u=EZ(t,l);try{wZ(e,l,u)}catch{}}}}return e}j2.exports=z2});function J2(e,t,r){let[n,i]=(0,Qs.useState)(e.getConfig(t));return(0,Qs.useEffect)(()=>{if(!r?.subscribe&&e.status===gn.ConfigsLoaded)return;let o=e.subscribe(t,a=>{i(a),r?.subscribe||o.unsubscribe()});return o?.unsubscribe},[]),n}function Y2(e){return function(t,r){return J2(e,t,r)}}function Q2(e,t,r,n){let i=o=>{let a=J2(e,t,n),s={...o,...a};return Qs.default.createElement(r,{...s})};return(0,K2.default)(i,r),i.displayName=`WithFeature(${r.name})`,i}function X2(e,t,r,n){return t.reduce((i,o)=>Q2(e,o,i,n),r)}function Z2(e){return function(t,r,n){return Q2(e,t,r,n)}}var K2,Qs,jy=k(()=>{"use strict";K2=Ce(H2()),Qs=Ce(Gy());Yu();});var t1=v((dge,e1)=>{var SZ=Fy(),NZ=Uy(),_Z=NZ(function(e,t,r){SZ(e,t,r)});e1.exports=_Z});var tp=v((fge,r1)=>{var TZ=Ea(),DZ=Lo(),IZ="[object Symbol]";function OZ(e){return typeof e=="symbol"||DZ(e)&&TZ(e)==IZ}r1.exports=OZ});var i1=v((pge,n1)=>{var PZ=Ro(),RZ=tp(),LZ=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,kZ=/^\w*$/;function $Z(e,t){if(PZ(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||RZ(e)?!0:kZ.test(e)||!LZ.test(e)||t!=null&&e in Object(t)}n1.exports=$Z});var s1=v((mge,a1)=>{var o1=jf(),xZ="Expected a function";function Hy(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(xZ);var r=function(){var n=arguments,i=t?t.apply(this,n):n[0],o=r.cache;if(o.has(i))return o.get(i);var a=e.apply(this,n);return r.cache=o.set(i,a)||o,a};return r.cache=new(Hy.Cache||o1),r}Hy.Cache=o1;a1.exports=Hy});var u1=v((hge,l1)=>{var FZ=s1(),MZ=500;function UZ(e){var t=FZ(e,function(n){return r.size===MZ&&r.clear(),n}),r=t.cache;return t}l1.exports=UZ});var d1=v((gge,c1)=>{var BZ=u1(),qZ=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,VZ=/\\(\\)?/g,GZ=BZ(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(qZ,function(r,n,i,o){t.push(i?o.replace(VZ,"$1"):n||r)}),t});c1.exports=GZ});var p1=v((yge,f1)=>{function WZ(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}f1.exports=WZ});var v1=v((bge,b1)=>{var m1=qu(),zZ=p1(),jZ=Ro(),HZ=tp(),KZ=1/0,h1=m1?m1.prototype:void 0,g1=h1?h1.toString:void 0;function y1(e){if(typeof e=="string")return e;if(jZ(e))return zZ(e,y1)+"";if(HZ(e))return g1?g1.call(e):"";var t=e+"";return t=="0"&&1/e==-KZ?"-0":t}b1.exports=y1});var C1=v((vge,w1)=>{var JZ=v1();function YZ(e){return e==null?"":JZ(e)}w1.exports=YZ});var A1=v((wge,E1)=>{var QZ=Ro(),XZ=i1(),ZZ=d1(),eee=C1();function tee(e,t){return QZ(e)?e:XZ(e,t)?[e]:ZZ(eee(e))}E1.exports=tee});var N1=v((Cge,S1)=>{var ree=tp(),nee=1/0;function iee(e){if(typeof e=="string"||ree(e))return e;var t=e+"";return t=="0"&&1/e==-nee?"-0":t}S1.exports=iee});var D1=v((Ege,T1)=>{var oee=$y(),aee=A1(),see=Jf(),_1=Hi(),lee=N1();function uee(e,t,r,n){if(!_1(e))return e;t=aee(t,e);for(var i=-1,o=t.length,a=o-1,s=e;s!=null&&++i<o;){var l=lee(t[i]),u=r;if(l==="__proto__"||l==="constructor"||l==="prototype")return e;if(i!=a){var c=s[l];u=n?n(c,l,s):void 0,u===void 0&&(u=_1(c)?c:see(t[i+1])?[]:{})}oee(s,l,u),s=s[l]}return e}T1.exports=uee});var O1=v((Age,I1)=>{var cee=D1();function dee(e,t,r){return e==null?e:cee(e,t,r)}I1.exports=dee});function k1(e){let{query:t}=(0,L1.default)(window.location.href,!0);return pee(e,t),e}function pee(e,t){let r=fee+e.clientName,n=Object.keys(t).filter(o=>o.startsWith(r));if(!n)return;let i={};n.forEach(o=>{let a=t[o];if(a)try{let s=JSON.parse(a),l=r+$1,u={};if(o===r)u=s;else if(o.startsWith(l)){let c=o.substring(l.length);(0,R1.default)(u,c,s)}(0,P1.default)(i,u)}catch{}}),Object.keys(i).length>0&&e.overrideClientConfig(i)}var P1,R1,L1,$1,fee,x1=k(()=>{"use strict";P1=Ce(t1()),R1=Ce(O1()),L1=Ce(Z0());$1=".",fee="ecs"+$1});function np(e,t,r){let n=k1(new ep(e,t,r));function i(o){(0,rp.useEffect)(()=>{n.init(o)},[])}return{featuresClient:n,createFeature:hee(n),useFeaturesClientInitParams:i,withFeatures:(o,a,s)=>X2(n,o,a,s)}}function hee(e){let t=Y2(e),r=Z2(e);return function(i){let o=kD(i);return o.getConfig=()=>e.getConfig(o),o.isLoaded=()=>e.status===gn.ConfigsLoaded,ry.register(o,e.clientName),{useFeature:a=>t(o,a),withFeature:(a,s)=>r(o,a,s),feature:o}}}var mee,rp,Ky=k(()=>{"use strict";mee=Ce($2()),rp=Ce(Gy());cy();Vy();Yu();jy();x1();ny();});var F1=k(()=>{"use strict";cy();Vy();Ky();Yu();jy();Bf();iy();});function ip(e){return{logEvent:(t,r,n)=>{switch(n){case"Error":(0,Xs.trackErrorTrace)(e,{eventName:t,eventData:r});break;case"Warning":(0,Xs.trackWarningTrace)(e,{eventName:t,eventData:r});break;default:(0,Xs.trackInfoTrace)(e,{eventName:t,eventData:r});break}}}}var Xs,Jy=k(()=>{"use strict";Xs=Ce(ya());});var Gge,Wge,zge,M1=k(()=>{"use strict";F1();Jy();({featuresClient:Gge,createFeature:Wge,useFeaturesClientInitParams:zge}=np("PowerApps-Shell-Test",ip("shell-features")))});var q1=v((Hge,B1)=>{var Zu=new Proxy(function(){return Zu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Zu},apply:function(){return Zu},construct:function(){return{}}}),U1=function(){return Zu};Object.setPrototypeOf(U1,Zu);B1.exports=U1});var gee,yee,V1=k(()=>{"use strict";Iu();gee=Ce(q1()),yee=Ce(ya());});var G1=k(()=>{"use strict";M1();Jy();V1();});var r0e,Zs,n0e,W1=k(()=>{"use strict";G1();Ky();({featuresClient:r0e,createFeature:Zs,useFeaturesClientInitParams:n0e}=np("PowerApps-MakerPortal",ip("powerapps-features")))});var z1,j1,s0e,l0e,u0e,c0e,Yy=k(()=>{"use strict";LD();W1();({feature:z1}=Zs({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:qs.enableAutoInsertionOfCellInRow}})),{feature:j1}=Zs({teamName:"MakerPortal",owners:["aansu"],description:"Enable the one grid events for form designer",createdOn:"08/21/2024",fallback:{enableOneGridEventsForFormDesigner:qs.enableOneGridEvents}}),{feature:s0e}=Zs({teamName:"MakerPortal",owners:["adekulkarni"],description:"Disables PBI components and cleans them up from the form",createdOn:"01/03/2023",fallback:{enableFallbackFormTemplate:qs.disablePBIComponents}}),{feature:l0e}=Zs({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:qs.enableAgentResponse}}),{feature:u0e,useFeature:c0e}=Zs({teamName:"MakerPortal",owners:["aansu"],description:"Enables delayed localization of custom control",createdOn:"06/08/2025",fallback:{enableDelayedLocalizationForCustomControls:qs.enableDelayedLocalizationForCustomControls}})});var J1=v((f0e,K1)=>{var ec=new Proxy(function(){return ec},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:ec},apply:function(){return ec},construct:function(){return{}}}),H1=function(){return ec};Object.setPrototypeOf(H1,ec);K1.exports=H1});var nr,ko=k(()=>{"use strict";vt();dt();rr();$u();le();kt();nr=class extends re{static HighestUsedIndexByClass=new Map;get colspan(){let t=this.getProperty(y.colspan);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}set colspan(t){R.IsNullOrUndefined(t)||this.setProperty(y.colspan,String(t))}constructor(t,r){super(t,r)}get id(){let t=this.getProperty(y.id);return t==null?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new U(t.substr(1,t.length-2)):new U(t)}set id(t){this.setProperty(y.id,`{${t.ToString()}}`)}set labelId(t){this.setProperty(y.labelId,`{${t.ToString()}}`)}get labelId(){let t=this.getProperty(y.labelId);return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new U(t.substr(1,t.length-2)):new U(t)}get Name(){return this.getProperty(y.Name)}set Name(t){this.setProperty(y.Name,t)}setDisplayName(t,r){for(let i of this.getAllLabels())if(+i.getProperty(y.languagecode)===r){i.setProperty(y.description,t);return}let n=new re(E.formLabel,null);n.setProperty(y.description,t),n.setProperty(y.languagecode,String(r)),this.addGrandChild("labels",n)}getDisplayName(t){for(let r of this.getAllLabels())if(+r.getProperty(y.languagecode)===t)return r.getProperty(y.description)}getAllLabels(){let t=this.getChildren("labels");return t.length!==1?[]:t[0].getChildren("label")}get isLocked(){return+this.getProperty(y.locklevel)==1}set isLocked(t){!this.IsUnboundControl&&this.setProperty(y.locklevel,t?"1":"0")}get availableforphone(){return this.getProcessedValue(y.availableforphone)}set availableforphone(t){R.IsNullOrUndefined(t)||!this.IsAllowedUBCForAvailableOnPhone()||this.setProperty(y.availableforphone,String(t))}get visible(){return this.getProcessedValue(y.visible)}set visible(t){R.IsNullOrUndefined(t)||!this.IsAllowedUBCForVisibleByDefault()||this.setProperty(y.visible,String(t))}isLockLevelSettable(){return!this.IsUnboundControl}get showlabel(){return this.getProcessedValue(y.showlabel)}set showlabel(t){R.IsNullOrUndefined(t)||this.setProperty(y.showlabel,String(t))}isAvailableForPhoneSettable(){return this.IsAllowedUBCForAvailableOnPhone()}isVisibleSettable(){return this.IsAllowedUBCForVisibleByDefault()}getProcessedValue(t){let r=this.getProperty(t);return R.IsNullOrUndefined(r)||this.getProperty(t)==="true"}get readonly(){let t=this.getFirstChild(E.formControl);return t?t.disabled:!1}set readonly(t){let r=this.getFirstChild(E.formControl);r&&(r.disabled=t)}get allowfilteroff(){let t=this.getFirstChild(E.formControl);if(t)return t.getParam(y.AllowFilterOff)==="true"}set allowfilteroff(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AllowFilterOff,t)}get autoresolve(){let t=this.getFirstChild(E.formControl);if(t)return t.getParam(y.AutoResolve)==="true"}set autoresolve(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AutoResolve,t)}get defaultviewid(){let t=this.getFirstChild(E.formControl);return t?t.getParam(y.DefaultViewId):q.EmptyString}set defaultviewid(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DefaultViewId,t)}get dependentattributename(){let t=this.getFirstChild(E.formControl);return t?t.getParam(y.DependentAttributeName):q.EmptyString}set dependentattributename(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DependentAttributeName,t)}get dependentattributetype(){let t=this.getFirstChild(E.formControl);return t?t.getParam(y.DependentAttributeType):q.EmptyString}set dependentattributetype(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DependentAttributeType,t)}get disablequickfind(){let t=this.getFirstChild(E.formControl);if(t)return t.getParam(y.DisableQuickFind)==="true"}set disablequickfind(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DisableQuickFind,t)}get disableviewpicker(){let t=this.getFirstChild(E.formControl);if(t)return t.getParam(y.DisableViewPicker)==="true"}set disableviewpicker(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DisableViewPicker,t)}get filterrelationshipname(){let t=this.getFirstChild(E.formControl);return t?t.getParam(y.FilterRelationshipName):q.EmptyString}set filterrelationshipname(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.FilterRelationshipName,t)}get availableviewids(){let t=this.getFirstChild(E.formControl);return t?t.getParam(y.AvailableViewIds):q.EmptyString}set availableviewids(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AvailableViewIds,t)}get IsUnboundControl(){let t=this.getFirstChild(E.formControl);if(t&&t.ClassId){let r=ft.getUniqueIdentifierForControl(t);return!R.IsNullOrUndefined(r)&&ft.isUnboundFormControlByIdentifier(r)}else return!1}IsAllowedUBCForAvailableOnPhone(){let t=this.getFirstChild(E.formControl);if(t){let n=ft.getUniqueIdentifierForControl(t).guidString,i=n===G.GridControl||n===G.TimeLineControl||n===G.TimeLineControlUC;return this.IsUnboundControl?i:!0}return this.NodeName===E.formSection||this.NodeName===E.formTab}IsAllowedUBCForVisibleByDefault(){let t=this.getFirstChild(E.formControl);if(t){let n=ft.getUniqueIdentifierForControl(t).guidString,i=n===G.MapsControl||n===G.WebResourceHtmlControl||n===G.WebResourceImageControl||n===G.IframeControl||n===G.SocialInsightControl;return this.IsUnboundControl?i:!0}else return!0}get events(){let t=this.getChildren(E.formEvents);return t.length===1?t[0].getAllChildren():[]}addEvent(t){this.addGrandChild(E.formEvents,t)}getUsedNodeNameSet(t){return null}getHighestIndexById(t,r){return null}}});var el,Qy=k(()=>{"use strict";rr();le();kt();el=class extends re{constructor(t,r){super(E.dependency,t),q.IsNullOrEmpty(r)||this.setDefaultProperties(r)}set id(t){this.setProperty(y.id,t)}get id(){return this.getProperty(y.id)}setDefaultProperties(t){this.id=t}}});var Y1,tl,Xy=k(()=>{"use strict";dt();Qy();le();kt();ko();(function(e){e[e.Form=0]="Form",e[e.Cell=1]="Cell",e[e.Tab=2]="Tab",e[e.Control=3]="Control"})(Y1||(Y1={}));tl=class extends nr{constructor(t,r){super(E.formEvent,t),r&&(this.eventName=r,this.application="false",this.active="false")}set eventName(t){this.setProperty(y.Name,t)}get eventName(){return this.getProperty(y.Name)}set application(t){this.setProperty(y.application,t)}get application(){return this.getProperty(y.application)}set attribute(t){this.setProperty(y.EventAttribute,t)}get attribute(){return this.getProperty(y.EventAttribute)}set relationship(t){this.setProperty(y.Relationship,t)}get relationship(){return this.getProperty(y.Relationship)}set control(t){this.setProperty(y.Control,t)}get control(){return this.getProperty(y.Control)}set active(t){this.setProperty(y.EventActive,t)}get active(){return this.getProperty(y.EventActive)}getAllHandlers(){let t=this.getChildren(E.EventHandlers);return t&&t.length?t[0].getChildren(E.handler):[]}getAllDependencies(){let t=this.getChildren(E.formDependencies);return t.length===0?[]:t[0].getAllChildren()}setDependencies(t){let r=this.getFirstChild(E.formDependencies);if(R.IsNullOrUndefined(r)){if(t.length===0)return;this.addChild(new re(E.formDependencies,this)),r=this.getFirstChild(E.formDependencies)}if(t.length===0)r.getParentNode().deleteChild(r);else{r.deleteAllChildren();for(let n of t)r.addChild(new el(r,n.toString()))}}}});var Fn,tc=k(()=>{"use strict";vt();su();dt();ga();le();kt();kn();Fn=class extends re{previewVersion;constructor(t){super(E.formControl,t)}updatePreview(){this.previewVersion=Date.now()}get ClassId(){let t=this.getProperty(y.classid);return t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t)}set ClassId(t){this.setProperty(y.classid,`{${t.ToString()}}`)}get dataFieldName(){return this.getProperty(y.datafieldname)}set dataFieldName(t){this.setProperty(y.datafieldname,t)}set id(t){this.setProperty(y.id,t)}get id(){return this.getProperty(y.id)}get UniqueId(){let t=this.getProperty(y.uniqueid);return R.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t))}set UniqueId(t){this.setProperty(y.uniqueid,`{${t.ToString()}}`)}get isRequired(){return this.getProperty(y.isRequired)==="true"}set isRequired(t){R.IsNullOrUndefined(t)||this.setProperty(y.isRequired,String(t))}get disableMru(){return this.getParam(y.DisableMru)==="true"}set disableMru(t){R.IsNullOrUndefined(t)||this.setParameter(y.DisableMru,t)}get useMFDForCreate(){return this.getParam(y.UseMFDForCreate)==="true"}set useMFDForCreate(t){R.IsNullOrUndefined(t)||this.setParameter(y.UseMFDForCreate,t)}get useMFDForEdit(){return this.getParam(y.UseMFDForEdit)==="true"}set useMFDForEdit(t){R.IsNullOrUndefined(t)||this.setParameter(y.UseMFDForEdit,t)}get disabled(){return this.getProperty(y.disabled)==="true"}set disabled(t){R.IsNullOrUndefined(t)||this.setProperty(y.disabled,String(t))}get indicationOfSubgrid(){return this.getProperty(y.indicationOfSubgrid)==="true"}set indicationOfSubgrid(t){this.setProperty(y.indicationOfSubgrid,String(t))}getAllParameters(){let t=new dr,r=this.getFirstChild(y.parameters);return r&&r.getAllChildren().forEach(n=>{if(n){let i=n.getAllChildren(),o=i&&i.length>0&&i[0];o&&t.add(n.getNodeName(),o.getNodeName())}}),t}setParameter(t,r){let n=!1;r===null&&(n=!0);let i=(ji.StartTag+r).toString(),o=this.parametersNode;if(o){let a=o.findFirst(s=>s&&s.getNodeName()===t);if(a)if(n){this.deleteFirstGrandChildOfName(E.controlParameters,a);return}else{let s=a.getAllChildren();s&&s.length>0&&s[0]?s[0].setNodeName(i):a.addChild(new re(i,a))}else n||(a=new re(t,o),a.addChild(new re(i,a)),o.addChild(a))}else if(!n){o=new re("parameters",this);let a=new re(t,o);a.addChild(new re(i,a)),o.addChild(a),this.addChild(o)}}getParam(t){if(this.parametersNode){let r=this.parametersNode.findFirst(n=>n&&n.getNodeName()===t);if(r){let n=r.getAllChildren(),i=n&&n.length>0&&n[0];if(i){let o=i.getNodeName();return o.charAt(0)===ji.StartTag?o.substring(1):o}}}return null}get parametersNode(){let t=this.getChildren(y.parameters);return t.length===0?null:t[0]}async serializeParameters(t,r){let n=new dr;switch(this.ClassId.guidString.toUpperCase()){case N.LookupControl:if(t&&t.getKeys())if(t.getKeys().forEach(a=>{n.add(a,this.getParam(a))}),t&&t.containsKey("DefaultViewId")){let a=this.getParam("DefaultViewId").replace("{","").replace("}","");n.upsert("DefaultViewId",a)}else{let a=this.getParent(),s=await r.formModelService.lookupControlService.populateDefaultView(this,a.getParentForm().entityName);s&&s.id&&n.upsert("DefaultViewId",s.id.replace("{","").replace("}",""))}break;default:t&&t.getKeys()&&t.getKeys().forEach(a=>{n.add(a,this.getParam(a))});break}let i=n.getInternalObject(),o=[];for(let a in i)i.hasOwnProperty(a)&&o.push({Name:a,Value:i[a]});return o}getIsUnbound(){return this.getProperty(y.isUnbound)==="true"}getAttributeTypeFromClassId(t){if(t)switch(t.toUpperCase()){case N.BooleanControl:case N.CheckboxControl:return 0;case N.DateTimeControl:return 2;case N.DecimalControl:return 3;case N.FloatingNumberControl:return 4;case N.IntegerControl:case N.DurationControl:case N.LanguageControl:case N.TimezoneControl:return 5;case N.LookupControl:return 6;case N.CurrencyControl:return 8;case N.PartyListControl:return 10;case N.ChoiceControl:case N.RelationshipRoleChoiceControl:return 11;case N.ChoiceStatusControl:return 13;case N.TextAreaControl:case N.TextboxControl:case N.LabelControl:case N.EmailAddressControl:case N.UrlControl:case N.TickerControl:case N.ButtonControl:case N.PhoneNumberControl:return 14;case N.ChoicesControl:return 24;default:return}return 14}async toJSON(t){let r=this.getParent(),n=t&&t.formModelService&&t.formModelService.getFormType()===wt.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 rl,Zy=k(()=>{"use strict";rr();oa();tc();le();kt();rl=class extends Fn{constructor(t){super(t)}get targetEntityType(){return this.getParam(y.targetEntityType)||q.EmptyString}set targetEntityType(t){this.setParameter(y.targetEntityType,t)}get viewId(){return q.StripBraces(this.getParam(y.viewId))||q.EmptyString}set viewId(t){this.setParameter(y.viewId,q.AddBraces(t))}get viewIds(){return this.getParam(y.viewIds)||q.EmptyString}set viewIds(t){this.setParameter(y.viewIds,t)}get relationshipName(){return this.getParam(y.RelationshipName)||q.EmptyString}set relationshipName(t){this.setParameter(y.RelationshipName,t)}get isUserView(){return q.IsStrictTrue(this.getParam(y.isUserView))}set isUserView(t){this.setParameter(y.isUserView,t.toString())}get enableViewPicker(){return q.IsStrictTrue(this.getParam(y.enableViewPicker))}set enableViewPicker(t){this.setParameter(y.enableViewPicker,t)}get autoExpand(){return this.getParent().autoexpand&&this.getParam(y.autoExpand)===y.Auto}set autoExpand(t){let r=this.getParent();this.setParameter(y.autoExpand,t?y.Auto:y.Fixed),r.autoexpand=t}get recordsPerPage(){return this.getParam(y.recordsPerPage)?Number(this.getParam(y.recordsPerPage)):Number(y.RecordsPerPageRAControlDefault)}set recordsPerPage(t){this.setParameter(y.recordsPerPage,String(t))}get enableQuickFind(){return q.IsStrictTrue(this.getParam(y.enableQuickFind))}set enableQuickFind(t){this.setParameter(y.enableQuickFind,t)}get teamTemplateId(){return q.StripBraces(this.getParam(y.teamTemplateId))||q.EmptyString}set teamTemplateId(t){this.setParameter(y.teamTemplateId,q.AddBraces(t))}get chartId(){return this.getParam(y.visualizationId)||q.EmptyString}set chartId(t){this.setParameter(y.visualizationId,t)}get enableChartPicker(){return q.IsStrictTrue(this.getParam(y.enableChartPicker))}set enableChartPicker(t){this.setParameter(y.enableChartPicker,t)}get chartGridMode(){switch(this.getParam(y.chartGridMode)){case hn.Chart:return hn.Chart;case hn.Grid:return hn.Grid;default:return hn.All}}set chartGridMode(t){this.setParameter(y.chartGridMode,t)}updateChartGridMode(t){t?this.chartGridMode=hn.Chart:this.chartGridMode=this.enableChartPicker?hn.All:hn.Grid}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case y.targetEntityType:n.getAllChildren()[0].setNodeName("<"+r.targetEntityType);break;case y.viewId:n.getAllChildren()[0].setNodeName("<"+q.AddBraces(r.viewId));break;case y.isUserView:n.getAllChildren()[0].setNodeName("<"+r.isUserView);break;case y.enableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.enableViewPicker);break;case y.RelationshipName:let i=n.getAllChildren(),o="<"+r.relationshipName;i.length?n.getAllChildren()[0].setNodeName(o):n.addChild(new re(o,n));break;default:break}}updateControlDescription(t){let r=t.getControlDescriptionByForControl(this.UniqueId);if(r){let n=r.customControls;for(let i=0;i<n.length;i++){let o=n[i].getParameters().get(Xt.dataset)?n[i].getParameters().get(Xt.dataset)[0]:null;if(o){let a=o.getAllChildren();this.updateDefaultProperties(a,this)}else{let a=n[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(a,this)}}}}}});var nl,eb=k(()=>{"use strict";rr();oa();tc();le();nl=class extends Fn{constructor(t){super(t)}get defaultViewId(){return q.StripBraces(this.getParam(y.DefaultViewId))||q.EmptyString}set defaultViewId(t){this.setParameter(y.DefaultViewId,q.AddBraces(t))}get autoResolve(){return q.IsStrictTrue(this.getParam(y.AutoResolve))}set autoResolve(t){this.setParameter(y.AutoResolve,t)}get disableQuickFind(){return q.IsStrictTrue(this.getParam(y.DisableQuickFind))}set disableQuickFind(t){this.setParameter(y.DisableQuickFind,t)}get disableViewPicker(){return q.IsStrictTrue(this.getParam(y.DisableViewPicker))}set disableViewPicker(t){this.setParameter(y.DisableViewPicker,t)}get allowFilterOff(){return q.IsStrictTrue(this.getParam(y.AllowFilterOff))}set allowFilterOff(t){this.setParameter(y.AllowFilterOff,t)}get disableMru(){return q.IsStrictTrue(this.getParam(y.DisableMru))}set disableMru(t){this.setParameter(y.DisableMru,t)}get dependentAttributeName(){return this.getParam(y.DependentAttributeName)||q.EmptyString}set dependentAttributeName(t){this.setParameter(y.DependentAttributeName,t)}get dependentAttributeType(){return this.getParam(y.DependentAttributeType)||q.EmptyString}set dependentAttributeType(t){this.setParameter(y.DependentAttributeType,t)}get filterRelationshipName(){return this.getParam(y.FilterRelationshipName)||q.EmptyString}set filterRelationshipName(t){this.setParameter(y.FilterRelationshipName,t)}get availableViewIds(){return this.getParam(y.AvailableViewIds)||q.EmptyString}set availableViewIds(t){this.setParameter(y.AvailableViewIds,t)}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case y.datafieldname:case y.bindAttribute:n.getAllChildren()[0].setNodeName("<"+r.dataFieldName);break;case y.DefaultViewId:n.getAllChildren()[0].setNodeName("<"+q.AddBraces(r.defaultViewId));break;case y.AllowFilterOff:n.getAllChildren()[0].setNodeName("<"+r.allowFilterOff);break;case y.DisableQuickFind:n.getAllChildren()[0].setNodeName("<"+r.disableQuickFind);break;case y.DisableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.disableViewPicker);break;case y.FilterRelationshipName:n.getAllChildren()[0].setNodeName("<"+r.filterRelationshipName);break;case y.DependentAttributeName:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeName);break;case y.DependentAttributeType:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeType);break;case y.AvailableViewIds:n.getAllChildren()[0].setNodeName("<"+r.availableViewIds);break;case y.DisableMru:n.getAllChildren()[0].setNodeName("<"+r.disableMru);break;case y.AutoResolve:n.getAllChildren()[0].setNodeName("<"+r.autoResolve);break;default:break}}updateControlDescription(t){let r=t.getControlDescriptionByForControl(this.UniqueId);if(r){let n=r.customControls;for(let i=0;i<n.length;i++){let o=n[i].getParameters().get(Xt.value)?n[i].getParameters().get(Xt.value)[0]:null;if(o){let a=o.getAllChildren();this.updateDefaultProperties(a,this)}else{let a=n[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(a,this)}}}}}});var Q1,tb,kr,rc=k(()=>{"use strict";Q1=Ce(J1());ko();le();dt();vt();Xy();tc();$u();ly();G0();kn();ga();Fs();Zy();eb();rb();vs();tb="_",kr=class e extends nr{fieldPlaceholder;fieldRequiredLevel;isNewField;cellColType;dependentFields=[];constructor(t){super(E.formCell,t),this.isNewField=!1}get cellType(){return this.cellColType}set cellType(t){this.cellColType=t}setDefaultProperties(t){this.showlabel=t,this.isLocked=!1,R.IsNullOrUndefined(this.getProperty(y.id))&&(this.id=new U(U.NewGuid()))}addControl(t,r,n,i,o,a,s){n instanceof Fn?this.addChild(n):n instanceof U&&this.addChild(this.getControlWithControlSpecificProperties(t,r,n,i,o,a,s))}removeControl(){return this.deleteChild(this.control)>=0}get isIndependent(){if(!R.IsNullOrUndefined(this.control))return R.IsNullOrUndefined(this.control.dataFieldName)?R.IsNullOrUndefined(this.control.id)?!0:!ba.dependencyFieldCount.containsKey(this.control.id):!ba.dependencyFieldCount.containsKey(this.control.dataFieldName)}createOnLoadEvent(){this.addEvent(new tl(this,Tu.onLoad))}get dependencies(){let t=this.getChildren(E.formEvents);for(let r of t){let n=r.getChildren(E.formEvent);for(let i of n)this.buildDependencyList(i,this.dependentFields)}return this.dependentFields}getNextAvailableControlName(t,r,n,i){let o;if(i&&Pf[i])o=Pf[i].replace(/ /g,tb)+tb;else{o="Control_";let u=new Error("Control class id does not exist or is undefined");(0,Q1.trackErrorTrace)(hr,{eventName:`${JT}/getNextAvailableControlName`},u)}let a="new_",s=this.getHighestIndexById(t,i)+1,l=`${o}${a}${s}`;for(;n.has(l);)s++,l=`${o}${a}${s}`;return l}getUnboundControlProperties(t){e.prototype.setProperty.call(t,y.isUnbound,"true"),e.prototype.setProperty.call(t,y.isRequired,"false")}getControlWithControlSpecificProperties(t,r,n,i,o,a,s){let l;o===yn.Grid?(l=new rl(this),l.indicationOfSubgrid=!0):o===yn.Lookup?l=new nl(this):l=new Fn(this);let u=n.guidString,c=a||this.getNextAvailableControlName(t,i,this.getUsedNodeNameSet(t),u);if(e.prototype.setProperty.call(l,y.id,c),l.ClassId=n,!R.IsNullOrUndefined(s)&&(l.UniqueId=s),!a&&r)this.getUnboundControlProperties(l);else{let d=ft.getUniqueIdentifierForControl(l);R.IsNullOrUndefined(d)||(ft.getControlDataTypeByControlOrUniqueId(d)===ee.QuickFormCollectionControl||!ft.isUnboundFormControlByIdentifier(d)?o!==yn.Grid&&a&&u!==N.IframeControl&&u!==N.SubgridControl&&u!==N.ReferencePanelSubgridControl&&(l.dataFieldName=a,e.prototype.setProperty.call(l,y.disabled,"false")):(this.rowspan=ft.GetRowSpan(l),(ft.getControlDataTypeByControlOrUniqueId(d)===ee.NotesControl||ft.getControlDataTypeByControlOrUniqueId(d)===ee.TimeLineControl)&&(e.prototype.setProperty.call(l,y.disabled,"false"),l.id=ee.NotesControl)),(ft.getUnboundControlNameFromIdentifier(n)===ee.SubGridControl||ft.getUnboundControlNameFromIdentifier(n)===ee.NotesControl||ft.getUnboundControlNameFromIdentifier(n)===ee.TimeLineControl)&&(this.availableforphone=!0))}return l}buildDependencyList(t,r){if(R.IsNullOrUndefined(t))return;let n=t.getAllChildren();for(let i of n){let o=i.getAllChildren();for(let a of o){let s=a.GetPropertyByParameter(y.id);a.getNodeName()===E.dependency&&s?r.push(s):this.buildDependencyList(a,r)}}}get control(){return this.getFirstChild(E.formControl)}set rowspan(t){this.setProperty(y.rowspan,String(t))}get rowspan(){let t=this.getProperty(y.rowspan);return R.IsNullOrUndefined(t)?1:parseInt(t,10)}set autoexpand(t){this.setProperty(y.auto,String(t))}get autoexpand(){return this.getProperty(y.auto)==="true"}set colspan(t){let r=Number(ay.ONE_COLUMN),n=Number(ay.FOUR_COLUMN);R.IsNullOrUndefined(t)||t>n||t<r||this.setProperty(y.colspan,String(t))}get colspan(){let t=this.getProperty(y.colspan);return R.IsNullOrUndefined(t)?1:parseInt(t,10)}getParentRow(){return this.getAncestor(E.formRow)}getParentSection(){return this.getAncestor(E.formSection)}getParentTab(){return this.getAncestor(E.formTab)}getParentForm(){return this.getAncestor(E.form)}isInHeader(){let t=this.getAncestor(E.formHeader);return!R.IsNullOrUndefined(t)}isInFooter(){let t=this.getAncestor(E.formFooter);return!R.IsNullOrUndefined(t)}isEmpty(){return R.IsNullOrUndefined(this.control)&&!this.IsUserSpacer}getHeaderFooter(){return this.isInHeader()?this.getAncestor(E.formHeader):this.isInFooter()?this.getAncestor(E.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(y.userspacer);return R.IsNullOrUndefined(t)?!1:t==="true"}SetUserSpacer(){this.setProperty(y.userspacer,"true")}ClearUserSpacer(){this.setProperty(y.userspacer,"false")}get columns(){let t=this.getProperty(y.columnName);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}getColumnLayoutValue(t){let r;switch(t){case je.TWO_COLUMN:r="11";break;case je.THREE_COLUMN:r="111";break;case je.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(!R.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();R.IsNullOrUndefined(t)||(t.autoExpandCell=this,t.tabContainsAutoExpandControl=!0)}isCellRequiredOrLocked(t,r,n){let i=this.getParentForm();if(this?.control){if(this.IsUserSpacer)return!1;{if(this.isLocked||r().has(this.control.dataFieldName))return!0;let o=i.isDuplicateCell(this,n),a=this.getRequiredLevel(t);if((a===yo.ApplicationRequired||a===yo.SystemRequired)&&!o||this.isCellLockedByExternal(t)&&!o)return!0}}return!1}getRequiredLevel(t){return!this.control?.dataFieldName||!this.control?.id||this.IsNewField||!this.control?.ClassId?yo.None:t.getEntityAttributeByName(this.control.dataFieldName)?.requiredLevel?.toString()??yo.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()===E.formCell){let i=n;i.control&&i!==this&&r.add(n.control.id)}return!1}),r}getHighestIndexById(t,r){let n=t.findAll(o=>o.getNodeName()===E.formCell&&o.control&&o.control.ClassId.guidString===r),i=0;return n.forEach(o=>{i=Math.max(this.parseControlNameIndex(o.control.id),i)}),i}parseControlNameIndex(t){let r=t.length-1,n=0;for(;r>0&&parseInt(t.charAt(r),10);)r--;return r>0&&r!==t.length-1&&t.charAt(r)===tb&&(r++,n=parseInt(t.substr(r,t.length-r),10)),n}}});var il,nb=k(()=>{"use strict";rr();le();kt();il=class extends re{isInternal;constructor(t,r,n,i){super(E.library,t),this.isInternal=!!i,q.IsNullOrEmpty(n)||(this.name=r,this.libraryUniqueId=n)}get libraryUniqueId(){let t=this.getProperty(y.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(y.libraryUniqueId,t)}get name(){return this.getProperty(y.libraryName)}set name(t){this.setProperty(y.libraryName,t)}get displayName(){return this.getProperty(y.displayName)}set displayName(t){this.setProperty(y.displayName,t)}get description(){return this.getProperty(y.description)}set description(t){this.setProperty(y.description,t)}}});var Sa,ib=k(()=>{"use strict";dt();rc();le();kt();Sa=class extends re{isRowAddedOnDragOver;constructor(t){super(E.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 R.IsNullOrUndefined(t)?!1:this.deleteChild(t)>=0}insertCellAtIndex(t,r){return R.IsNullOrUndefined(t)?!1:(this.insertChildAtIndex(t,r),!0)}isEmpty(){return!this.cells||this.cells.every(t=>t.isEmpty())}getParentSection(){return this.getAncestor(E.formSection)}insertPaddingCellAtIndex(t){let r=new kr(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(E.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 bee(e){switch(e){case va.Left:return Ca.Left;case va.Right:return Ca.Right;case va.Center:return Ca.Center;default:return Ca.Left}}function vee(e){switch(e){case Us.Left:return Bs.Left;case Us.Top:return Bs.Top;default:return Bs.Left}}function X1(e){switch(e){case 1:return 1;case 2:return 11;case 3:return 111;case 4:return 1111;default:return 1}}var wee,pi,nc=k(()=>{"use strict";uy();vt();dt();rr();Yy();rc();le();kn();ko();ib();wee=115,pi=class e extends nr{colSpan=1;constructor(t,r){super(t,r)}getSectionType(){let t;switch(this.columns){case 1:t=je.ONE_COLUMN;break;case 11:t=je.TWO_COLUMN;break;case 111:t=je.THREE_COLUMN;break;case 1111:t=je.FOUR_COLUMN;break;default:t=this.colSpan-1}return t}setUniqueName(){let t=this.getParentTab(),r=qe.namePrefix;if(t){let n=t.Name,i=t.TotalSectionsCount+1;r=n+qe.namePrefix+i.toString()}else r+=Math.floor(Math.random()*1e3);this.setProperty(y.Name,r)}initializeDefaultProperties(t,r,n){if(n===je.REFERENCE_PANEL){this.addProperty(y.rowheight,"25");let i=`${qe.referencePanelNamePrefix}${U.NewGuid()}${qe.namePrefix}`;this.addProperty(y.Name,i)}else this.setUniqueName();if(this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.IsUserDefined,qe.IsUserDefined),this.addProperty(y.locklevel,qe.LockLevel),this.addProperty(y.showlabel,qe.ShowLabel),this.addProperty(y.showbar,qe.ShowBar),this.addProperty(y.layout,qe.Layout),this.addProperty(y.Fieldlabelalignment,qe.labelAlignment),this.addProperty(y.Fieldlabelposition,qe.labelPosition),R.IsNullOrUndefined(n))this.addProperty(y.columnName,qe.columns);else{let i=this.getColumnLayoutValue(n);this.addProperty(y.columnName,i)}this.addProperty(y.LabelWidth,qe.LabelWidth),this.setDisplayName(r,t)}getColumnLayoutValue(t){let r;switch(t){case je.TWO_COLUMN:r="11";break;case je.THREE_COLUMN:r="111";break;case je.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 R.IsNullOrUndefined(this.columns)?t=this.ColSpan:this.columns.toString().split(q.EmptyString).forEach(r=>{t+=parseInt(r,10)}),t}get ColSpan(){return this.colSpan}initializeRow(t){if(t>0&&t<5){let r=new Sa(null);if(this.addGrandChild(E.formRows,r),z1.getConfig().enableAutoInsertionOfCellInRow)for(let n=0;n<t;n++){let i=new kr(r);i.setDefaultProperties(!1),r.addCell(i)}}}initialize(t,r,n){this.initializeDefaultProperties(t,r,n),n===je.REFERENCE_PANEL&&(n=je.ONE_COLUMN),this.initializeRow(n+1)}setColSpan(t){this.colSpan=t}appendRow(t){this.addGrandChild(E.formRows,t)}insertRowAtIndex(t,r){this.addGrandChildAtIndex(E.formRows,t,r)}insertRowsAtIndex(t,r){if(t&&t.length>0)for(let n=0;n<t.length;n++)this.addGrandChildAtIndex(E.formRows,t[n],r+n)}indexOfRow(t){return this.rows.indexOf(t)}deleteRow(t){return this.deleteFirstGrandChildOfName(E.formRows,t)}deleteRows(t,r){this.deleteGrandChildren(E.formRows,t,r)}get rows(){return this.getRows()}getRows(){let t=this.getChildren(E.formRows);return t.length===0?[]:t[0].getChildren(E.formRow)}get columns(){let t=this.getProperty(y.columnName),r=R.IsNullOrUndefined(t)?NaN:parseInt(t,10);if(isNaN(r)){let n=1;for(let i of this.rows)n=Math.max(n,i.cells.length);return X1(n)}return r}set columns(t){R.IsNullOrUndefined(t)||this.setProperty(y.columnName,String(t))}get rowHeight(){let t=this.getProperty(y.rowheight);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}set rowHeight(t){this.setProperty(y.rowheight,String(t))}set autoexpand(t){this.setProperty(y.autoExpand.toLowerCase(),String(t))}get autoexpand(){return this.getProperty(y.autoExpand.toLowerCase())==="true"}get isUserDefined(){return+this.getProperty(y.IsUserDefined)!=0}set isUserDefined(t){t?this.setProperty(y.IsUserDefined,"1"):this.setProperty(y.IsUserDefined,"0")}getParentColumn(){return this.getAncestor(E.formColumn)}getParentTab(){return this.getAncestor(E.formTab)}get hasMultiColumnRow(){return this.getColumnCountValue()>1}get showlabel(){return this.getProperty(y.showlabel)==="true"}set showlabel(t){R.IsNullOrUndefined(t)||this.setProperty(y.showlabel,String(t))}get fieldLabelAlignment(){let t=qe.labelAlignment,r=this.getProperty(y.Fieldlabelalignment);return R.IsNullOrUndefined(r)?t:r}set fieldLabelAlignment(t){R.IsNullOrUndefined(t)||this.setProperty(y.Fieldlabelalignment,t)}get fieldLabelPosition(){let t=this.getProperty(y.Fieldlabelposition);return R.IsNullOrUndefined(t)?qe.labelPosition:t}set fieldLabelPosition(t){R.IsNullOrUndefined(t)||this.setProperty(y.Fieldlabelposition,String(t))}get showbar(){return this.getProperty(y.showbar)==="true"}set showbar(t){R.IsNullOrUndefined(t)||this.setProperty(y.showbar,String(t))}get labelwidth(){let t=+this.getProperty(y.LabelWidth);return t===0?wee:t}set labelwidth(t){R.IsNullOrUndefined(t)||t>283&&t<57||this.setProperty(y.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:bee(this.fieldLabelAlignment),Position:vee(this.fieldLabelPosition)},Columns:X1(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()===E.formSection){let i=n;i.Name&&!q.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}isReferencePanelSection(){return!R.IsNullOrUndefined(this)&&!R.IsNullOrUndefined(this.Name)&&this.Name.indexOf(qe.referencePanelNamePrefix)===0}getAllMultiRowCells(){return this.findAll(t=>{if(t.getNodeName()===E.formCell){let r=t;return!r.isEmpty()&&r.rowspan>1}return!1})}isHeaderOrFooterSection(){return this.NodeName===E.formFooter||this.NodeName===E.formHeader}}});var $o,op=k(()=>{"use strict";le();kt();nc();$o=class e extends re{constructor(t){super(E.formColumn,t)}initializeDefaultProperties(t){this.addProperty(y.width,t.toString()+"%")}insertSectionAtIndex(t,r){this.addGrandChildAtIndex(E.formSections,t,r)}static createAndInitNewSection(t,r,n){let i=new pi(E.formSection,null);return i.initialize(t,r,n),i}addSectionAtIndex(t,r){this.addGrandChildAtIndex(E.formSections,t,r)}initialize(t,r,n,i=je.ONE_COLUMN){this.initializeDefaultProperties(t);let o=e.createAndInitNewSection(r,n,i);this.addSectionAtIndex(o,this.sections.length),o.setUniqueName()}get parentTab(){return this.getAncestor(E.formTab)}get sections(){let t=this.getChildren("sections");return t.length!==1?[]:t[0].getChildren(E.formSection)}get width(){return this.getProperty(y.width)}set width(t){this.setProperty(y.width,t)}deleteSection(t){return this.deleteFirstGrandChildOfName(E.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(y.Name),Id:this.getProperty(y.id),Label:null,ShowLabel:!1,Visible:!0,LabelId:null,PreviewId:this.getProperty(y.id),Sections:await this.getSectionsJSON(t),Width:this.width}}}});var ap,Z1=k(()=>{"use strict";vt();le();kn();nc();ap=class extends pi{initializeNavArea(t,r,n){this.initializeNavAreaProps(t,r,n)}get AreaName(){return this.Name}initializeNavAreaProps(t,r,n){this.addProperty(y.Name,n),this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.columnName,qe.columns),this.setDisplayName(r,t)}}});var sp,eL=k(()=>{"use strict";op();le();Z1();sp=class extends $o{addAndIntializeNavBarSection(t,r,n,i){let o=new ap(E.formSection,null);return o.initializeNavArea(t,r,i),this.addGrandChildAtIndex(E.formSections,o,n),o}}});var Ki,lp=k(()=>{"use strict";vt();dt();rr();op();le();kt();ko();Ki=class extends nr{tabContainsAutoExpandControl;autoExpandCell;constructor(t,r){super(E.formTab,t),this.tabContainsAutoExpandControl=!1}getParentForm(){return this.getAncestor(E.form)}getTabLayoutType(){let t;switch(this.columns.length){case 1:t=ze.ONE_COLUMN;break;case 2:if(parseInt(this.columns[0].width,10)===50&&parseInt(this.columns[1].width,10)===50){t=ze.TWO_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===67&&parseInt(this.columns[1].width,10)===33){t=ze.TWO_COLUMN_WIDER_LEFT;break}if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===66){t=ze.TWO_COLUMN_WIDER_RIGHT;break}t=ze.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=ze.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=ze.THREE_COLUMN_WIDER_MID;break}t=ze.THREE_COLUMN_CUSTOM_LAYOUT;break;default:}return t}initializeProperties(t,r,n){this.addProperty(y.Name,Io.namePrefix+t.toString()),this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.IsUserDefined,Io.IsUserDefined),this.addProperty(y.locklevel,Io.LockLevel),this.addProperty(y.showlabel,Io.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=je.ONE_COLUMN,o=!0,a){let s=this.getChildren(E.formColumns)[0],l=[];switch(t){case ze.ONE_COLUMN:l.push(100);break;case ze.TWO_COLUMN_EQUAL:l.push(50),l.push(50);break;case ze.TWO_COLUMN_WIDER_LEFT:l.push(67),l.push(33);break;case ze.TWO_COLUMN_WIDER_RIGHT:l.push(34),l.push(66);break;case ze.THREE_COLUMN_EQUAL:l.push(34),l.push(33),l.push(33);break;case ze.THREE_COLUMN_WIDER_MID:l.push(28),l.push(44),l.push(28);break;default:}for(let u of l){let c=new $o(s);c.initialize(u,r,n,i),this.addGrandChild(E.formColumns,c)}}initialize(t,r,n,i,o,a=je.ONE_COLUMN,s=!0,l){this.addChild(new re(E.formColumns,this)),this.initializeProperties(r,n,i),this.initializeColumns(t,n,o,a,s,l)}get columns(){let t=this.getChildren(E.formColumns);return t.length!==1?[]:t[0].getChildren(E.formColumn)}get expanded(){return this.getProcessedValue(y.expanded)}set expanded(t){R.IsNullOrUndefined(t)||this.setProperty(y.expanded,String(t))}get groupName(){return this.getProperty(y.groupName)}get contentType(){return this.getProperty(y.contentType)}set contentType(t){this.setProperty(y.contentType,t)}insertNewColumnAtIndex(t,r,n,i,o){t.initialize(n,i,o),this.addGrandChildAtIndex(E.formColumns,t,r)}insertColumnAtIndex(t,r){this.addGrandChildAtIndex(E.formColumns,t,r)}deleteColumn(t){return this.deleteFirstGrandChildOfName(E.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()===E.formTab){let i=n;i.Name&&!q.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}}});var Na,ob=k(()=>{"use strict";vt();le();kt();kn();eL();lp();Na=class extends Ki{constructor(t,r,n){super(t,ze.THREE_COLUMN_EQUAL),this.setDisplayName(r,n),this.id=new U(U.NewGuid())}initializeDefaultProps(){this.addChild(new re(E.formColumns,this)),this.initializeFiveColumns()}get columns(){let t=this.getChildren("columns");return t.length!==1?[]:t[0].getChildren(E.formColumn)}getNavSectionForArea(t){for(let r of this.columns)for(let n of r.sections)if(n.AreaName===t)return n;return null}getNavCellFromNavId(t){for(let r of this.columns)for(let n of r.sections)for(let i of n.rows)for(let o of i.cells)if(o.NavId===t)return o;return null}initializeFiveColumns(){for(let t=0;t<qf.FIVE_COLUMN;t++){let r=new sp(this.getChildren(E.formColumns)[0]);r.initializeDefaultProperties(wD.FiveEqColumn),this.addGrandChild(E.formColumns,r)}}}});function Eee(e){switch(e){case wt.Main:return Oo.Main;case wt.QuickCreate:return Oo.QuickCreate;case wt.QuickViewForm:return Oo.Quick;case wt.Dialog:return Oo.Dialog;default:return Oo.None}}function Aee(e,t){if(t===wt.Main){if(e)switch(e.toLowerCase()){case"low":return Do.Low;case"highreadonlyvalues":return Do.HighReadOnlyValues;default:return Do.HighWithControls}return Do.Low}}var cp,Cee,up,tL=k(()=>{"use strict";DD();cp=Ce(ya());uy();dt();rr();Fs();Yy();le();oa();O0();ga();rc();le();ko();nb();ob();lp();Cee="1920";up=class e extends nr{_formUniqueName;isHeaderDefaulted;consistencyStrong=!1;_formId;_rawFormXml;_entityName;_entityDisplayName;_status;_formName;_langCode;_description;_formType;_formPresentation;parameters=[];_formactivationstate;_changeTracker;_metadataChangeEvent;_etag;constructor(t,r,n,i,o,a,s,l,u){super(E.form,null),this._formUniqueName=o,this._formId=t,this._entityName=r,this._status=n,this._formName=i,this._description=l,this._formType=a,this._formPresentation=s,this._formactivationstate=u,this._changeTracker=new Tf,this._metadataChangeEvent=new Gf}get FormLibraries(){let t=this.getFirstChild(E.formLibraries),r=t?t.getAllChildren():[],n=this._getInternalLibraries();return r.concat(n)}getAllEvents(){let t=[],r=this.events;r&&(t=t.concat(r));for(let n of this.tabs){let i=n.events;i&&(t=t.concat(i)),n.findAll(o=>o instanceof kr).forEach(o=>{let a=o.events;a&&(t=t.concat(a))})}return t}getEventsForNode(t){if(t instanceof e){let r=t.events;return r?r.filter(n=>!n.control&&!n.attribute):null}else if(t instanceof kr){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()===E.internalLibraries),r=[],n="src";return t.length>0&&(r=t.map(i=>{let o=i.GetPropertyByParameter(n).replace("$webresource:",""),a=new il(void 0,void 0,"",!0);return a.name=o,a.displayName=o,a})),r}getDependentFields(){let t=this.getAllEvents(),r=new Set;return t.forEach(n=>{try{n.getAllDependencies().forEach(o=>{r.add(o.id)})}catch(i){throw(0,cp.trackErrorTrace)(YT,{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 q.IsNullOrEmpty(this.getProperty(y.ShowImage))?!0:this.getProperty(y.ShowImage)!=="false"}set ShowImagecheck(t){t?this.setProperty(y.ShowImage,String(t)):this.setProperty(y.ShowImage,"false")}get ShowNavigation(){return q.IsNullOrEmpty(this.getProperty(y.ShowNavigationbar))?!0:this.getProperty(y.ShowNavigationbar)!=="false"}set ShowNavigation(t){t?this.setProperty(y.ShowNavigationbar,String(t)):this.setProperty(y.ShowNavigationbar,"false")}get MaxWidth(){return q.IsNullOrEmpty(this.getProperty(y.MaxWidth))?Cee:this.getProperty(y.MaxWidth)}set MaxWidth(t){this.setProperty(y.MaxWidth,t)}get headerDensityType(){return this.getProperty(y.HeaderDensityType)}set headerDensityType(t){t&&this.formType===wt.Main?this.setProperty(y.HeaderDensityType,t):this.formType!==wt.Main&&this.headerDensityType&&this.removeProperty(y.HeaderDensityType)}IsMainOrQuickCreateForm(){return this.formType===wt.Main||this.formType===wt.QuickCreate}get FormPresentation(){return this._formPresentation}get LanguageCode(){return this._langCode}set LanguageCode(t){this._langCode=t}get header(){let t=this.getChildren(E.formHeader);return t.length!==1?null:t[0]}set header(t){R.IsNullOrUndefined(t)||(this.deleteChild(this.header),this.addChild(t))}getAllDependencies(){return this.getChildren(E.quickFormDependencies).length===0?[]:this.ConvertModelToArray(this.getChildren(E.quickFormDependencies)[0].getAllChildren())}ConvertModelToArray(t){let r=[];return R.IsNullOrUndefined(t)||t.forEach(n=>{r.push(n.id)}),r}get footer(){let t=this.getChildren(E.formFooter);return t.length!==1?null:t[0]}set footer(t){R.IsNullOrUndefined(t)||(this.deleteChild(this.footer),this.addChild(t))}createAndInitNewTab(t,r,n){let i=new Ki(null,t),o=this.getNextTabCounter(this.tabs.length+1);return i.initialize(t,o,this.LanguageCode,r,n),i}addTabAtIndex(t,r){this.addGrandChildAtIndex(E.formTabs,t,r)}createAndInitNewTabWithMarginalControl(t,r,n,i,o){let a=new Ki(null,ze.ONE_COLUMN),s=this.getNextTabCounter(this.tabs.length+1);a.initialize(ze.ONE_COLUMN,s,this.LanguageCode,r,n,o,!1),this.addGrandChildAtIndex(E.formTabs,a,i);let l=a.columns[0].sections[0];for(let u=0;u<t.rows.length;u++)l.appendRow(t.rows[u])}getNextTabCounter(t){for(let r=0;r<this.tabs.length;r++)if(this.tabs[r].Name===Io.namePrefix+t.toString())return this.getNextTabCounter(t+1);return t}get allTabs(){let t=this.getChildren(E.formTabs);return t.length!==1?[]:t[0].getChildren(E.formTab)}get CanvasNavigationTab(){if(this.tabs.length>0){let t=this.tabs[this.tabs.length-1];if(t instanceof Na)return t}return null}get NavigationNode(){let t=this.getChildren(E.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(E.formTabs,t)}insertTabAtIndex(t,r){this.addGrandChildAtIndex(E.formTabs,t,r)}insertRelatedTab(t){let r=this.getAllGrandChildren(E.formTabs);if(!R.IsNullOrUndefined(r)){let n=r.length;this.insertTabAtIndex(t,n)}}get isfooterPresent(){return this.getChildren(E.formFooter).length>0}get displayCondition(){let t=this.getChildren(E.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(E.formTabs).indexOf(t)}get ControlDescriptions(){return this.getAllGrandChildren(E.controlDescriptions)}addControlDescriptionNode(t){this.addGrandChild(E.controlDescriptions,t)}deleteControlDescByForControlId(t){let r=this.getControlDescriptionByForControl(t);R.IsNullOrUndefined(r)||this.deleteFirstGrandChildOfName(E.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 kr))return!1;let o=!0;return r==="Tab"?o=i.getParentTab()!==t.getParentTab():r==="Section"?o=i.getParentSection()!==t.getParentSection():o=i!==t,i instanceof kr&&i.control&&t.control&&o&&i.control.dataFieldName===t.control.dataFieldName})}isCellEditableGridControl(t){return!t?.control?.indicationOfSubgrid||t.control.ClassId.guidString.toUpperCase()!==N.CustomControl?!1:this.cellHasCustomControlWithName(t,Mi.EditableGridControl)||j1.getConfig()?.enableOneGridEventsForFormDesigner&&this.cellHasCustomControlWithName(t,Mi.PowerAppsOneGrid)}isCellCanvasAppControl(t){return t?.control?.ClassId.guidString.toUpperCase()===N.CustomControl&&this.cellHasCustomControlWithName(t,Mi.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()===E.formCell){let i=n;return i&&i.control&&i.control.ClassId.guidString===t}return!1}):null}async getTabsJSON(t){let r=this.tabs,n=[],i=[];if(r){for(let o of r)if(!(o instanceof Na)){let a=o.toJSON(t);n.push(a)}for(let o of n)i.push(await o)}return i}async getControlDescriptionsToJSON(t){let r=[];for(let n of this.ControlDescriptions){let i=await n.toJSON(t);i&&r.push(i)}return r}async toJSON(t){let r=[];r=await this.getControlDescriptionsToJSON(t);let n=this.NavigationNode&&await this.NavigationNode.toJSON(t);return{Id:this._formId.guidString,Name:this.formName,Label:this.getDisplayName(t.langCode),ShowLabel:this.showlabel,Visible:this.visible,LabelId:this.labelId&&this.labelId.guidString,PreviewId:this._formId.guidString,PreviewSessionId:(0,cp.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===wt.Main?{HeaderDensity:Aee(this.headerDensityType,this.formType)}:{},InlineEditGridRow:[],InlineQuickForms:[],QuickFormEntities:[],EventHandlers:[],LinkControlSections:[],FormType:Eee(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 dp,ab,rL=k(()=>{"use strict";vt();dt();le();kt();ko();dp=class extends nr{constructor(t){super(E.formDisplayConditions,t)}get Order(){let t=this.getProperty(y.Order);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}set Order(t){this.setProperty(y.Order,t.toString())}get FallbackForm(){return this.getProperty(y.FallbackForm)==="true"}set FallbackForm(t){this.setProperty(y.FallbackForm,t.toString())}addRoles(t){this.deleteAllChildren();for(let r=0;r<t.length;r++)this.addChild(t[r])}isRoleEveryone(){return!!(this.getChildren(E.formEveryOne)&&this.getChildren(E.formEveryOne)[0])}setRoleEveryone(){this.deleteAllChildren(),this.addChild(new ab(this))}},ab=class extends re{constructor(t){super(E.formEveryOne,t)}}});var fp,nL=k(()=>{"use strict";le();kt();fp=class extends re{constructor(t,r){super(E.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(y.HandlerUniqueId)}set HandlerUniqueID(t){this.setProperty(y.HandlerUniqueId,t)}get FunctionName(){return this.getProperty(y.functionName)}set FunctionName(t){this.setProperty(y.functionName,t)}get LibraryName(){return this.getProperty(y.libraryNameEventHandler)}set LibraryName(t){this.setProperty(y.libraryNameEventHandler,t)}get Enabled(){return this.getProperty(y.enabledForField)}set Enabled(t){this.setProperty(y.enabledForField,t)}get PassExecutionContext(){return this.getProperty(y.passExecutionContext)}set PassExecutionContext(t){this.setProperty(y.passExecutionContext,t)}get Parameters(){return this.getProperty(y.parameters)}set Parameters(t){this.setProperty(y.parameters,t)}}});var ol,sb=k(()=>{"use strict";le();nc();ol=class extends pi{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(E.formCell);for(let o of i)r.push(o)}}return r}get occupiedCells(){return this.cells.filter(t=>!t.isEmpty())}get maxColumns(){return super.getColumnCountValue()}}});var ic,iL=k(()=>{"use strict";le();sb();ic=class extends ol{_customFooter;constructor(t,r){super(E.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 oc,oL=k(()=>{"use strict";le();sb();oc=class extends ol{_customHeader;constructor(t,r){super(E.formHeader,t),this._customHeader=r}get customHeader(){return this._customHeader}set customHeader(t){this._customHeader=t}get showCommandBar(){return this.getProcessedValue(y.showCommandBar)}set showCommandBar(t){t!=null&&this.setProperty(y.showCommandBar,String(t))}get showBody(){return this.getProcessedValue(y.showBody)}set showBody(t){t!=null&&this.setProperty(y.showBody,String(t))}get showTabNavigator(){return this.getProcessedValue(y.showTabNavigator)}set showTabNavigator(t){t!=null&&this.setProperty(y.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 $r,_a=k(()=>{"use strict";vt();rr();le();ko();$r=class e extends nr{constructor(t,r){super(t,r)}getTitle(t){for(let r of this.getAllTitles())if(+r.getProperty(y.LCID)===t)return r.getProperty(y.text);return null}getAllTitles(){let t=this.getChildren(E.Titles);return t.length===0?[]:t[0].getChildren(E.Title)}setTitle(t,r){for(let i of this.getAllTitles())if(+i.getProperty(y.LCID)===r){i.setProperty(y.text,t);return}let n=new e(E.Title,null);n.setProperty(y.text,t),n.setProperty(y.LCID,String(r)),this.addGrandChild(E.Titles,n)}get Sequence(){return+this.getProperty(y.Sequence)}set Sequence(t){this.setProperty(y.Sequence,t.toString())}get Area(){return this.getProperty(y.Area)}set Area(t){this.setProperty(y.Area,t)}set Id(t){this.setProperty(y.Id,t)}get Id(){return this.getProperty(y.Id)}get id(){return new U(this.Id??"",!0)}set id(t){this.Id=t.guidString}get Show(){return!0}get Icon(){return this.getProperty(y.icon)}set Icon(t){t=t||q.EmptyString,this.setProperty(y.icon,t)}updateCommonProperties(t,r){this.Area=t.Area,this.Sequence=t.Sequence,this.setTitle(t.getDisplayName(r),r)}}});var ac,aL=k(()=>{"use strict";(function(e){e[e.NavLinkNotAvailable=-1]="NavLinkNotAvailable",e[e.NavLinkIdConflict=-2]="NavLinkIdConflict",e[e.NavBarNotAvailable=-3]="NavBarNotAvailable"})(ac||(ac={}))});var pp,sL=k(()=>{"use strict";dt();le();_a();aL();pp=class extends $r{constructor(t){super(E.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 R.IsNullOrUndefined(r)?ac.NavLinkNotAvailable:r.length===1?this.deleteChild(r[0]):ac.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 Fe,See,lL,tve,al,lb=k(()=>{"use strict";vt();le();_a();(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"})(Fe||(Fe={}));See=new Map([[Fe.Info,"Info"],[Fe.Sales,"Sales"],[Fe.Service,"Service"],[Fe.Marketing,"Marketing"],[Fe.ProcessCenter,"ProcessCenter"]]),lL=new Map([["Info",Fe.Info],["Sales",Fe.Sales],["Service",Fe.Service],["Marketing",Fe.Marketing],["ProcessCenter",Fe.ProcessCenter]]),tve=new Map([[Fe.Info,9e3],[Fe.Sales,9200],[Fe.Service,9400],[Fe.Marketing,9600],[Fe.ProcessCenter,9800],[Fe.InternetMarketing,1e4],[Fe.Async,10200]]),al=class extends $r{constructor(t,r){super(E.formNavBarArea,r)}setDefaultPropertiesByType(t,r,n){this.AreaId=See.get(t);let i=n?.(`navBarArea.title.${this.AreaId}`)??this.AreaId;this.setTitle(i,r)}get ParentNavigation(){return this.getAncestor(E.formNavigation)}get AreaId(){return this.getProperty(y.Id)}set AreaId(t){this.setProperty(y.Id,t)}get id(){return new U(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 sl,ub=k(()=>{"use strict";le();_a();sl=class extends $r{constructor(t,r){super(E.formNavBarAreas,r)}get AllNavBarAreaItems(){return this.getChildren(E.formNavBarArea)}get ParentNavigation(){return this.getAncestor(E.formNavigation)}addNavBarArea(t){this.addChild(t)}}});var mp,uL=k(()=>{"use strict";dt();le();_a();mp=class extends $r{RelationshipNameUCIRuntime;constructor(t){super(E.formNavBarByRelationshipItem,t)}get RelationshipName(){return this.getProperty(y.RelationshipName)}set RelationshipName(t){this.setProperty(y.RelationshipName,t)}set Show(t){this.setProperty(y.Show,String(t))}get Show(){let t=this.getProperty(y.Show);return R.IsNullOrUndefined(t)||t==="true"}get TitleResourceId(){return this.getProperty(y.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 hp,cL=k(()=>{"use strict";le();_a();hp=class extends $r{constructor(t){super(E.formNavBarItem,t)}get Url(){return this.getProperty(y.url)}set Url(t){this.setProperty(y.url,t)}}});var gp,dL=k(()=>{"use strict";vt();le();lb();ub();_a();gp=class extends $r{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(E.formNavBarAreas)}setDefaultNavBarAreas(t,r){let n=[Fe.Info,Fe.Sales,Fe.Service,Fe.Marketing,Fe.ProcessCenter];if(this.navBarAreas){let i=this.navBarAreas?.AllNavBarAreaItems;if(i&&i.length>0){let o=new Set(i.map(a=>lL.get(a.AreaId)));n=n.filter(a=>!o.has(a))}}else{let i=new sl(E.formNavBarAreas,this);i.isTransient=!0,this.addChild(i)}return n.length>0?(n.forEach(i=>{let o=new al(E.formNavBarArea,this.navBarAreas);o.setDefaultPropertiesByType(i,t,r),this.navBarAreas.addNavBarArea(o)}),!0):!1}get navBar(){return this.getFirstChild(E.formNavBar)}get id(){return new U(V0,!0)}replaceNavAreaToGivenIndex(t,r){this.navBarAreas?.AllNavBarAreaItems.indexOf(r)!==-1&&(this.deleteFirstGrandChildOfName(E.formNavBarAreas,r),this.addGrandChildAtIndex(E.formNavBarAreas,r,t))}async getNavBarAreasJSON(t){let r=[],n=[];if(this.navBarAreas?.AllNavBarAreaItems){for(let o of this.navBarAreas.AllNavBarAreaItems)n.push(o.toJSON(t));r=await Promise.all(n)}return r}async getNavBarRelationshipItemsJSON(t){let r=[],n=[];if(this.navBar?.AllRelationShipItems){for(let i of this.navBar.AllRelationShipItems)n.push(i.toJSON(t));r=await Promise.all(n)}return r}async toJSON(t){let r=await this.getNavBarAreasJSON(t),n=await this.getNavBarRelationshipItemsJSON(t);return{NavBarAreas:{NavBarAreas:r},NavBarByRelationshipItems:n,NavBarItems:[],NavPaneIsvItems:{NavBarIsvItems:[]},ShowEmptyNavBarAreas:t.formModelService.showHiddenElements}}}});var fL={};nn(fL,{ControlType:()=>yn,DeserializationService:()=>fb,DeserializationServiceScope:()=>db,DeserializedFormElementNode:()=>xr});var cb,xr,db,yn,fb,rb=k(()=>{"use strict";cb=Ce(ya());vt();dt();rr();Fs();G0();ga();QT();_D();$u();tL();rc();op();tc();Qy();le();le();rL();kt();kn();Xy();nL();iL();Zy();eb();oL();nb();ib();nc();lp();sL();lb();ub();uL();cL();dL();xr=class extends re{constructor(t,r){super(t,r)}insertProperty(t,r){this.addProperty(t,r)}insertChild(t){this.addChild(t)}},db="DeserializationService";(function(e){e.Grid="Grid",e.Lookup="Lookup",e.Base="Base"})(yn||(yn={}));fb=class{lcid;constructor(t){this.lcid=t}deSerializeFormXml(t,r,n,i,o,a,s,l,u,c){if(!t)throw new Error("Formxml could not be parsed.");let d=t.getElementsByTagName("form");if(d.length!==1){let m="";throw d.length===0?m="FormXml has no form node.":m="FormXml has multiple form nodes.",(0,cb.trackErrorTrace)(hr,{eventName:db,eventData:{error:m}}),new Error(m)}let f=this.createFormModel(d.item(0),r,n,i,o,a,s,l,u,c);return R.IsNullOrUndefined(f.displayCondition)&&s!==wt.Dialog&&this.appendDefaultDisplayCondition(f),f}upsertFieldCount(t,r){let n=ba.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(!R.IsNullOrUndefined(t)){let n=R.ParseXml(r);n!==null&&this.populateElementChildren(t,n.childNodes)}}createFormModel(t,r,n,i,o,a,s,l,u,c){let d=new up(r,n,i,o,a,s,l,u,c);return this.populateElementProperties(d,t.attributes),this.populateElementChildren(d,t.childNodes),s===wt.Main&&(this.insertHeaderFooterElementProperties(E.formHeader,d,d.header),this.insertHeaderFooterElementProperties(E.formFooter,d,d.footer)),d}insertHeaderFooterElementProperties(t,r,n){if(R.IsNullOrUndefined(n)){let i=t===E.formHeader?new oc(r,!0):new ic(r,!0);xr.prototype.insertProperty.call(i,y.id,"{"+U.NewGuid()+"}"),xr.prototype.insertProperty.call(i,y.Fieldlabelposition,"Top"),xr.prototype.insertProperty.call(i,y.columnName,qe.MarginalControlColumns),xr.prototype.insertProperty.call(i,y.LabelWidth,qe.LabelWidth),xr.prototype.insertProperty.call(i,y.Fieldlabelalignment,"Left");let o=null,a=new Sa(o);for(let s=0;s<i.maxColumns;s++){let l=new kr(a);xr.prototype.insertProperty.call(l,y.id,"{"+U.NewGuid()+"}"),l.setDisplayName(q.EmptyString,this.lcid),xr.prototype.insertProperty.call(l,y.showlabel,"false"),a.addCell(l)}i.appendRow(a),t===E.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 xr(`<${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,cb.trackErrorTrace)(hr,{eventName:db,eventData:{error:n}}),new Error(n)}for(let n=0;n<r.length;n++){let i=r.item(n);i&&(xr.prototype.insertProperty.call(t,i.name,i.value),t.getNodeName()===E.formCell&&i.name===y.auto&&i.value==="true"&&t.setAutoExpandDetailsForTab())}}populateElementChildren(t,r){for(let n=0;n<r.length;n++){let i=r.item(n),o=this.deSerializeFormXmlNode(i,t);o&&xr.prototype.insertChild.call(t,o)}}createModelNode(t,r){switch(t.nodeName){case E.form:throw new Error("Form node shouldn't be created using this method");case E.formTab:return new Ki(r);case E.formColumn:return new $o(r);case E.formHeader:return new oc(r,!1);case E.formFooter:return new ic(r,!1);case E.formSection:return new pi(E.formSection,r);case E.formRow:return new Sa(r);case E.formCell:return new kr(r);case E.formControl:let n=t.attributes,i=t.childNodes.length>0?t.childNodes[0].childNodes:null,o;for(let s=0;s<n.length;s++){let l=n.item(s);if(l.name===y.indicationOfSubgrid&&l.value==="true"||l.name===y.classid&&(l.value?.toLocaleUpperCase()===`{${N.SubgridControl}}`||l.value?.toLocaleUpperCase()===`{${N.ReferencePanelSubgridControl}}`))o=yn.Grid;else if(l.name===y.classid&&l.value?.toLocaleUpperCase()===`{${N.LookupControl}}`)o=yn.Lookup;else if(l.name===y.classid&&l.value?.toLocaleUpperCase()===`{${N.CustomControl}}`)for(let u=0;u<i?.length;u++)i[u].nodeName===y.DefaultViewId&&(o=yn.Lookup)}return o===yn.Grid?new rl(r):o===yn.Lookup?new nl(r):new Fn(r);case E.formEvent:return new tl(r,q.EmptyString);case E.dependency:return this.populateDependencyTable(t),new el(r,q.EmptyString);case E.Handler:let a=[];return new fp(a,r);case E.formNavigation:return new gp(t.nodeName,r);case E.formNavBarArea:return new al(t.nodeName,r);case E.formNavBarAreas:return new sl(t.nodeName,r);case E.formNavBar:return new pp(r);case E.formNavBarByRelationshipItem:return new mp(r);case E.formNavBarItem:return new hp(r);case E.formDisplayConditions:return new dp(r);case E.library:return new il(r,q.EmptyString,q.EmptyString);case E.controlDescription:return new Rf(r);case E.customControl:return this.populateCustomControlConfigurationId(t),new Vf(r);default:return new xr(t.nodeName,r)}}populateDependencyTable(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);i.name===y.id&&this.upsertFieldCount(i.value,ui.DependencyFieldTable)}}populateCustomControlConfigurationId(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);if(i.name===y.id){let o=new U(i.value.substr(1,i.value.length-2));for(let a=0;a<t.parentNode.attributes.length;a++){let s=t.parentNode.attributes.item(a);if(s.name===y.ForControl){let l=s.value.substr(1,i.value.length-2);ft.CustomControlIdMap.upsert(l,o);break}}break}}}}});var pL={};nn(pL,{SerializationService:()=>pb,SerializationServiceScope:()=>Nee,SerializedFormElementNode:()=>ll});var Nee,ll,pb,mL=k(()=>{"use strict";rr();kt();kn();ob();Nee="SerializationService",ll=class extends re{fetchNodeName(){return this.getNodeName()}enumerateProperties(){return this.getAllProperties()}enumerateChildren(){return this.getAllChildren()}},pb=class{langCode;constructor(t){this.langCode=t}serializeFormXmlNode(t){let r=ll.prototype.fetchNodeName.call(t);if(r.charAt(0)===ji.StartTag)return q.EscapeXml(r.substr(1),!1);if(t.isTransient&&!t.isDirty())return q.EmptyString;let n=ll.prototype.enumerateProperties.call(t),i=ll.prototype.enumerateChildren.call(t);if(!(t instanceof Na)){let o=`<${r}`;if(n.length!==0&&(o+=` ${this.getPropertiesString(n)}`),i.length===0)o+=" />";else{let a=q.EmptyString;for(let s of i)a+=this.serializeFormXmlNode(s);o+=`>${a}</${r}>`}return o}return q.EmptyString}getPropertiesString(t){let r=q.EmptyString;return t.forEach((n,i)=>{i!==0&&(r+=" "),r+=`${n.key}="${q.EscapeXml(n.value,!0)}"`}),r}}});var yb=v(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});ul.completeRecordAsStored=ul.completeLabelsAsStored=void 0;var mb=Eo(),_ee="E7A81278-8635-4D9E-8D4D-59480B391C5B",Tee=new Set(["tab","section","cell"]);function Mn(e){let t=[];for(let r=e.firstChild;r;r=r.nextSibling)r.nodeType===1&&t.push(r);return t}function xo(e,t){return Mn(e).find(r=>r.tagName===t)}function gL(e,t){return e.length===t.length&&e.every((r,n)=>r.tagName===t[n].tagName)}function hb(e){let t=xo(e,"control");return t?(t.getAttribute("datafieldname")||"")!==""?!0:(t.getAttribute("classid")||"").replace(/[{}]/g,"").toUpperCase()===_ee:!1}function gb(e,t){var r,n;let i=((r=xo(e,"control"))===null||r===void 0?void 0:r.getAttribute("id"))||"";return i!==""&&i===(((n=xo(t,"control"))===null||n===void 0?void 0:n.getAttribute("id"))||"")}function Dee(e,t){if(xo(e,"labels"))return;let r=Mn(e),n=Mn(t),i=n[0];if(!i||i.tagName!=="labels"||n.length!==r.length+1||!gL(r,n.slice(1)))return;let o=Mn(i);if(!(o.length===0||o.some(s=>s.tagName!=="label"||!s.hasAttribute("description")||!s.hasAttribute("languagecode"))||!(e.tagName==="cell"&&hb(e)&&gb(e,t))&&o.some(s=>s.getAttribute("description")!=="")))return i}function Iee(e,t){let r=Oee(e.ownerDocument,t),n=Mn(e)[0];n?e.insertBefore(r,n):e.appendChild(r)}function Oee(e,t){let r=e.createElement("labels");for(let n of Mn(t))r.appendChild(yL(e,n));return r}function yL(e,t){let r=e.createElement("label");for(let n=0;n<t.attributes.length;n+=1){let{name:i,value:o}=t.attributes[n];(i==="description"||i==="languagecode")&&r.setAttribute(i,o)}return r}function hL(e,t){let r=xo(e,"labels");return r?Mn(r).find(n=>n.tagName==="label"&&n.getAttribute("languagecode")===String(t)):void 0}function Pee(e,t,r){if(e.tagName!=="cell"||!hb(e)||!gb(e,t))return!1;let n=hL(e,r),i=hL(t,r),o=i?.getAttribute("description")||"";return!n||!n.hasAttribute("description")||(n.getAttribute("description")||"")!==""||o===""?!1:(n.setAttribute("description",o),!0)}function Ree(e,t){if(e.tagName!=="cell"||!hb(e)||!gb(e,t))return;let r=xo(e,"labels"),n=xo(t,"labels");if(!r||!n)return;let i=Mn(r),o=Mn(n),a=f=>f.tagName==="label"&&f.hasAttribute("description")&&f.hasAttribute("languagecode");if(o.length<=i.length||!i.every(a)||!o.every(a))return;let s=new Map(i.map(f=>[f.getAttribute("languagecode")||"",f]));if(s.size!==i.length)return;let l=new Set,u=0,c=[],d=[];for(let f of o){let m=f.getAttribute("languagecode")||"";if(l.has(m))return;l.add(m);let p=s.get(m);if(!p){d.push(f);continue}if((p.getAttribute("description")||"")!==(f.getAttribute("description")||""))return;u+=1,c.push(...d.map(h=>({label:h,before:p}))),d=[]}return c.push(...d.map(f=>({label:f}))),u===i.length?c:void 0}function bL(e,t,r,n){if(e.tagName!==t.tagName)return;if(Tee.has(e.tagName)){let a=Dee(e,t);a&&(Iee(e,a),n.changed=!0),Pee(e,t,r)&&(n.changed=!0);let s=Ree(e,t),l=xo(e,"labels");if(s&&l){for(let{label:u,before:c}of s){let d=yL(e.ownerDocument,u);c?l.insertBefore(d,c):l.appendChild(d)}n.changed=!0}}let i=Mn(e),o=Mn(t);gL(i,o)&&i.forEach((a,s)=>bL(a,o[s],r,n))}function vL(e,t,r){if(e===t)return e;let n,i;try{n=(0,mb.parseXmlRoot)(e,""),i=(0,mb.parseXmlRoot)(t,"")}catch{return e}let o={changed:!1};return bL(n,i,r,o),o.changed?(0,mb.serializeNode)(n):e}ul.completeLabelsAsStored=vL;function Lee(e,t,r){let n=e?.formxml,i=t?.formxml;if(typeof n!="string"||typeof i!="string")return e;let o=vL(n,i,r);return o===n?e:{...e,formxml:o}}ul.completeRecordAsStored=Lee});var UL=v(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.pcfReadIssues=ue.pcfBindingIssues=ue.commitPcfState=ue.mayCommitPcfState=ue.reconcilePcfDescriptions=ue.customControlNeeds=ue.mintPcfIdentity=ue.planPcfBinding=ue.projectPcfBindings=ue.supportsPcfFormType=ue.storedBindingOf=ue.hasCustomControl=ue.sameAsStored=ue.readPcfDescription=ue.newPcfDescription=ue.editorText=ue.nativeClassFor=ue.pcfEntryLayout=void 0;var kee=($u(),zr(TD)),$ee=Q(),wL=ct(),V=zd(),xee=cu(),we=cn(),Qi=["web","phone","tablet"],sc={web:"2",phone:"0",tablet:"1"},NL=new Map([["2","web"],["0","phone"],["1","tablet"]]),Fee=["phone","web","tablet"];function bp(e){let t=new Set(e),r=Fee.filter(n=>!t.has(n));return{defaults:r.length===0?[null]:r,named:Qi.filter(n=>t.has(n))}}ue.pcfEntryLayout=bp;function gr(e){return Array.isArray(e)?e:[]}function pt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function lc(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function vb(e){return{n:`<${e}`,a:[],c:[]}}function _L(e){return typeof e?.n=="string"&&e.n.startsWith("<")}function CL(e){let t=gr(e.c);return t.length===1&&_L(t[0])&&(0,V.rawText)(e)!==""?(0,V.rawText)(e):void 0}function vn(e,t){return JSON.stringify(e)===JSON.stringify(t)}function TL(e){return`{${e.replace(/^\{|\}$/g,"").toUpperCase()}}`}function wb(e){try{let t=(0,kee.mapFieldTypeToControl)(e.attributeTypeName,e.format);return t?TL(String(t)):void 0}catch{return}}ue.nativeClassFor=wb;var Cb=new Map([["Whole.None",{digits:0,min:-2147483648,max:2147483647}],["Whole.Duration",{digits:0,min:0,max:2147483647}],["Decimal",{digits:7,min:-922337203685477,max:922337203685477}],["FP",{digits:5,min:-1e11,max:1e11}],["Currency",{digits:4,min:-1e11,max:1e11}]]),DL=new Set(["TwoOptions","Boolean"]),IL=new Set(["SingleLine.Text","SingleLine.TextArea","SingleLine.Email","SingleLine.Phone","SingleLine.URL","SingleLine.Ticker","Multiple"]),Mee=new Map([...[...IL].map(e=>[e,100]),["SingleLine.TextArea",2e3],["Multiple",1048576]]),Uee=/^[A-Za-z_][A-Za-z0-9_.-]*$/;function OL(e){return Uee.test(e)&&e!=="__proto__"}function Eb(e){return e!==void 0&&(e==="Enum"||Cb.has(e)||DL.has(e)||IL.has(e))}function PL(e){return typeof e=="number"?e:e!==""&&!Number.isNaN(Number(e))?Number(e):void 0}function uc(e,t){let r=e!==void 0?Cb.get(e):void 0;if(r&&typeof t!="boolean"){let n=PL(t);if(n!==void 0)return n.toFixed(r.digits)}return typeof t=="boolean"?t?"true":"false":String(t)}ue.editorText=uc;function Bee(e,t,r){var n;let i=[];for(let o of e.properties){let a=o.name,s;if(o.isPrimary?s=t:o.usage==="input"&&lc(r,a)?s=uc(o.defaultType,r[a]):s=(n=o.defaultValue)!==null&&n!==void 0?n:"",s==="")continue;let l=[];o.defaultType&&l.push(["type",o.defaultType]),!o.isPrimary&&(o.defaultType==="Enum"||o.usage==="input")&&l.push(["static","true"]),i.push({n:a,a:l,c:[vb(s)]})}return i}function RL(e,t,r,n,i){var o,a;let s=(o=n.formFactors)!==null&&o!==void 0?o:Qi.filter(d=>Ab(i).has(d)),l=bp(s),u=Bee(i,t,(a=n.parameters)!==null&&a!==void 0?a:{}),c=d=>JSON.parse(JSON.stringify(d));return{n:"controlDescription",a:[["forControl",e]],c:[...l.defaults.map(d=>({n:"customControl",a:d===null?[["id",r]]:[["id",r],["formFactor",sc[d]]],c:[{n:"parameters",a:[],c:[{n:"datafieldname",a:[],c:[vb(t)]}]}]})),...l.named.map(d=>({n:"customControl",a:[["name",n.name],["formFactor",sc[d]]],c:[{n:"parameters",a:[],c:c(u)}]}))]}}ue.newPcfDescription=RL;function Ab(e){return new Set(Qi.filter(t=>e.availableOn[t]))}function yp(e){var t;let r=gr(e.c);if(r.length!==1||((t=r[0])===null||t===void 0?void 0:t.n)!=="parameters"||gr(r[0].a).length>0)return;let n=gr(r[0].c);return n.every(i=>pt(i)&&!_L(i))?n:void 0}function Ta(e){let t=gr(e?.c);if(t.length===0||!t.every(p=>pt(p)&&p.n==="customControl"))return;let r=t.findIndex(p=>(0,V.rawAttr)(p,"name")!==void 0);if(r<=0)return;let n=t.slice(r),i=(0,V.rawAttr)(n[0],"name"),o=[];for(let p of n){let h=gr(p.a),g=h.length===2?NL.get(h[1][1]):void 0;if(!g||h[0][0]!=="name"||h[0][1]!==i||h[1][0]!=="formFactor"||o.includes(g))return;o.push(g)}let a=bp(o);if(!vn(a.named,o)||i==="")return;let s=yp(n[0]);if(!s||!n.every(p=>vn(yp(p),s)))return;let l=t.slice(0,r);if(l.length!==a.defaults.length)return;let u=(0,V.rawAttr)(l[0],"id"),c;for(let p=0;p<l.length;p+=1){let h=a.defaults[p],g=h===null?[["id",u??""]]:[["id",u??""],["formFactor",sc[h]]],b=yp(l[p]),w=b?.length===1&&b[0].n==="datafieldname"&&gr(b[0].a).length===0?CL(b[0]):void 0;if(!u||!vn(gr(l[p].a),g)||w===void 0||c!==void 0&&w!==c)return;c=w}let d={},f={},m;for(let p of s){let h=gr(p.a),g=CL(p),b=h.map(w=>w[0]);if(g===void 0||!OL(p.n)||lc(d,p.n)||p.n===m)return;if((0,V.rawAttr)(p,"static")===void 0){if(m!==void 0||g!==c||!(b.length===0||vn(b,["type"])))return;m=p.n;continue}if((0,V.rawAttr)(p,"static")!=="true"||!(vn(b,["static"])||vn(b,["type","static"])))return;d[p.n]=g,f[p.n]=(0,V.rawAttr)(p,"type")}if(!(m===void 0||c===void 0||u===void 0))return{binding:{name:i,...Object.keys(d).length>0?{parameters:d}:{},...o.length===Qi.length?{}:{formFactors:o}},fieldName:c,nativeClass:u,parameterTypes:f,boundProperty:m}}ue.readPcfDescription=Ta;function LL(e,t,r){return e===t?!0:typeof e!="string"&&(t===String(e)||t===uc(r,e))}function kL(e){let t=e.formFactors;return t===void 0?[...Qi]:Array.isArray(t)?Qi.filter(r=>t.includes(r)):[]}function bb(e,t){var r,n,i;if(e.name!==t.binding.name||!vn(kL(e),(r=t.binding.formFactors)!==null&&r!==void 0?r:Qi))return!1;let o=(n=e.parameters)!==null&&n!==void 0?n:{},a=(i=t.binding.parameters)!==null&&i!==void 0?i:{},s=Object.keys(o);return s.length!==Object.keys(a).length?!1:s.every(l=>lc(a,l)&&LL(o[l],a[l],t.parameterTypes[l]))}ue.sameAsStored=bb;function Ct(e){return pt(e)&&e.customControl!==void 0}ue.hasCustomControl=Ct;function Yi(e,t){var r;return t?gr((r=(0,V.descriptionsRegion)(e))===null||r===void 0?void 0:r.node.c).filter(n=>n?.n==="controlDescription"&&(0,V.normGuid)((0,V.rawAttr)(n,"forControl"))===t):[]}function Sb(e,t){let r=Yi(e.bag,(0,V.controlUniqueId)(t));return r.length===1?Ta(r[0]):void 0}ue.storedBindingOf=Sb;function Nb(e){let t=(0,V.effectiveFormType)(e);return t==="Main"||t==="QuickCreate"}ue.supportsPcfFormType=Nb;function qee(e){if(!Nb(e))return;let t=(0,V.controlUniqueIds)(e);for(let{cell:r}of(0,V.typedCellSites)(e)){let n=r.control;if(!pt(n)||!n.fieldName||!Ji(n.classId)||t.get((0,V.controlUniqueId)(n))!==1)continue;let i=Sb(e,n);i&&i.fieldName===n.fieldName&&(n.customControl=JSON.parse(JSON.stringify(i.binding)))}}ue.projectPcfBindings=qee;function Ji(e){return typeof e=="string"&&e.replace(/^\{|\}$/g,"").toUpperCase()===V.CUSTOM_CONTROL_CLASS_ID}var bn=(e,t)=>({kind:"refused",rule:e,message:t});function Vee(e){let t=e.replace(/^\{|\}$/g,"");return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)&&!Ji(e)}function EL(e,t,r){var n,i;let o=Ta(r);if(!o)return bn("pcf-binding-other-control","the control already has a description the SDK cannot read as a binding; adding would replace it");if(o.fieldName!==e.fieldName)return bn("pcf-binding-rebind",`the binding is filed for "${o.fieldName}": remove it, push, then bind the new column`);if(t.name!==o.binding.name)return bn("pcf-binding-control-swap",`the binding uses "${o.binding.name}": to use another control, remove customControl, push, then add it`);let a=pt(t.parameters)?t.parameters:{},s=(n=o.binding.parameters)!==null&&n!==void 0?n:{},l=Object.keys(a).sort();if(!vn(l,Object.keys(s).sort()))return bn("pcf-binding-edit-parameter-set",`an edit changes parameter values only \u2014 the binding stores exactly ${Object.keys(s).sort().map(g=>`"${g}"`).join(", ")||"none"}: to add or remove one, remove the binding, push, then add it`);let u=l.filter(g=>!LL(a[g],s[g],o.parameterTypes[g])),c=u.find(g=>uc(o.parameterTypes[g],a[g]).trim()==="");if(c!==void 0)return bn("pcf-binding-edit-parameter-set",`"${c}" cannot be cleared in place \u2014 an empty value is not written, which removes the parameter: remove the binding, push, then add it`);let d=kL(t),f=(i=o.binding.formFactors)!==null&&i!==void 0?i:[...Qi],m=d.filter(g=>!f.includes(g)),p=f.filter(g=>!d.includes(g));if(u.length===0&&m.length===0&&p.length===0)return{kind:"unchanged"};let h=u.find(g=>!Eb(o.parameterTypes[g]));if(h!==void 0){let g=o.parameterTypes[h];return bn("pcf-binding-edit-stored-type",`"${h}" is stored ${g===void 0?"with no type":`as type "${g}"`}, which the property editor does not write: remove the binding, push, then add it`)}return(m.length>0||p.length>0)&&!Vee(o.nativeClass)?bn("pcf-binding-edit-fallback",`the factors the control leaves fall back to "${o.nativeClass}", which is not a native control class: remove the binding, push, then add it`):{kind:"edit",description:r,stored:o,changed:u,factors:d,added:m,removed:p}}function Gee(e,t){return t&&(0,V.typedCellSites)(e).find(({cell:n})=>Ct(n.control)&&(0,V.controlUniqueId)(n.control)===t)?{descriptions:Yi(e.bag,t)}:void 0}function $L(e,t){let r=new Map,n=Wee(e),i=new Set,o=new Map,a=u=>{let c=o.get(u);return c||(c={before:[],now:[]},o.set(u,c)),c},s=(u,c)=>({cell:Hee(u),uid:(0,V.controlUniqueId)(c),bound:Ct(c)});for(let{cell:u}of(0,V.typedCellSites)(e)){let c=u.control;pt(c)&&typeof c.id=="string"&&c.id&&a(c.id).now.push({...s(u,c),control:c})}for(let{cell:u}of(0,V.typedCellSites)(t)){let c=u.control;if(!pt(c))continue;let d=s(u,c);d.bound&&d.uid&&i.add(d.uid),typeof c.id=="string"&&c.id&&a(c.id).before.push(d)}let l=(u,c)=>{let d=u.filter(f=>f.cell===c);return d.length===1?d[0]:void 0};for(let[u,{before:c,now:d}]of o){let f=c.filter(D=>D.bound&&D.uid!==""&&!n.has(D.uid));if(f.length===0||d.length===0)continue;let m=[...c],p=D=>{let P=m.findIndex(D);return P<0?void 0:m.splice(P,1)[0]},g=d.filter(D=>!D.bound||D.uid===""?!0:p(P=>P.bound&&P.uid===D.uid)!==void 0?!1:!i.has(D.uid)).filter(D=>{let P=D.cell?l(c,D.cell):void 0;return!P||!l(d,D.cell)||!m.includes(P)?!0:(m.splice(m.indexOf(P),1),f.includes(P)&&D.uid!==P.uid&&AL(D.control)&&r.set(D.control,SL(P.uid)),!1)}),b=[],w=(D,P)=>{let x=D.uid===""?void 0:p(K=>K.uid===D.uid&&(!P||K.bound===D.bound));return x&&f.includes(x)&&b.push(x),x!==void 0},S=g.filter(D=>!w(D,!0)).filter(D=>!w(D,!1)&&AL(D.control)),O=f.filter(D=>m.includes(D));if(S.length===0||O.length===0&&b.length===0)continue;let L=[...O,...b],I=O.length===1&&S.length===1&&m.length===1?SL(O[0].uid):`the controls with id "${u}" cannot all be matched to those last synced \u2014 their cells do not tell them apart \u2014 and ${L.map(D=>`{${D.uid}}`).join(", ")} no longer ${L.length===1?"names":"name"} a control: which control held ${L.length===1?"that binding":"those bindings"} is ambiguous. Re-fetch the form; to drop a bound control, remove its customControl and push before removing the control`;for(let D of S)r.set(D.control,I)}return r}function Wee(e){let t=(0,V.controlUniqueIds)(e),r=new Map;for(let{cell:i}of(0,V.typedCellSites)(e)){let o=pt(i.control)?(0,V.controlUniqueId)(i.control):"";o&&!r.has(o)&&r.set(o,i.control)}let n=new Set;for(let[i,o]of t){let a=r.get(i);(a===void 0||Ct(a)||o>1)&&n.add(i)}return n}function AL(e){return Ct(e)||e.genPage===void 0&&Ji((0,V.effectiveClassId)(e))}function zee(e,t){let r=o=>(0,V.typedCellSites)(o).flatMap(({cell:a,pointer:s})=>{let l=a.control;if(!pt(l)||Ct(l)||l.genPage!==void 0||!Ji((0,V.effectiveClassId)(l)))return[];let u=(0,V.controlUniqueId)(l);return u===""||Yi(o.bag,u).length===0?[{control:l,pointer:`${s}/control`}]:[]}),n=o=>`${String(o.id)}\0${(0,V.controlUniqueId)(o)}`,i=r(t).map(({control:o})=>n(o));return r(e).filter(({control:o})=>{let a=i.indexOf(n(o));return a<0?!0:(i.splice(a,1),!1)})}var jee="this control would keep the custom-control class with no binding (its customControl and uniqueid are gone): remove the binding from an unchanged copy \u2014 keep its uniqueid, and the native control comes back \u2014 or set classId to the column's native control";function SL(e){return`this control's uniqueid changed since it was last synced (it was {${e}}), and a binding is linked to its description by it: restore it (re-fetch the form), or remove the binding, push, then add the new one`}function Hee(e){let t=typeof e.id=="string"?e.id.trim():"";return(0,V.normGuid)(t)||t.toLowerCase()}function cc(e,t,r,n){let i=t.customControl,o=(0,V.controlUniqueId)(t),a=Yi(e.bag,o),s=r?$L(e,r).get(t):void 0;if(s!==void 0)return bn("pcf-binding-unique-id",s);let l=r?Gee(r,o):void 0;if(l){let c=l.descriptions,d=c.length===1?Ta(c[0]):void 0;if(d&&d.fieldName!==t.fieldName)return bn("pcf-binding-rebind",`the binding is filed for "${d.fieldName}": remove it, push, then bind the new column`);if(c.length===1&&a.length===1&&vn(c[0],a[0]))return EL(t,i,a[0]);let f=a.length===1?Ta(a[0]):void 0;return d&&f&&f.fieldName===t.fieldName&&bb(i,d)&&bb(i,f)?{kind:"unchanged"}:bn("pcf-binding-edit-changed-description","the binding\u2019s description changed since it was last synced (edited in the bag, re-keyed or deleted): re-fetch the form before changing the binding")}if(a.length===0)return{kind:"new"};if(a.length>1)return bn("pcf-binding-other-control","the control already has a description the SDK cannot read as a binding; adding would replace it");let u=EL(t,i,a[0]);return n&&(u.kind==="edit"||u.kind==="unchanged")?u.kind==="unchanged"?u:bn("pcf-binding-edit","this binding\u2019s description was never synced from the server (no baseline): changing it in place is not supported \u2014 remove customControl, push, then add the new one"):u}ue.planPcfBinding=cc;function xL(e){return e.kind==="edit"&&(e.changed.length>0||e.added.length>0)}function Kee(e){let t=n=>Ct(n.control)&&(!n.control.id||!n.id||(0,V.authoredUniqueId)(n.control)===void 0);if(!(0,V.typedCellSites)(e).some(({cell:n})=>t(n)))return e;let r=JSON.parse(JSON.stringify(e));for(let{cell:n}of(0,V.typedCellSites)(r)){if(!t(n))continue;let i=n.control;i.id||(i.id=(0,wL.newId)()),n.id||(n.id=(0,wL.newId)()),(0,V.authoredUniqueId)(i)===void 0&&(0,V.setUniqueId)(i)}return r}ue.mintPcfIdentity=Kee;function Jee(e,t){let r=new Set,n=new Set;for(let{cell:i}of(0,V.typedCellSites)(e)){let o=i.control;if(!Ct(o)||!pt(o.customControl))continue;let a=o.customControl.name;if(typeof a!="string"||a===""||typeof o.fieldName!="string"||!o.fieldName)continue;let s=cc(e,o,t,!0);s.kind==="new"?(r.add(a),n.add(o.fieldName)):xL(s)&&r.add(a)}return{controls:[...r],columns:[...n],...n.size>0&&(0,V.effectiveFormType)(e)==="QuickCreate"?{requireCreateEligibility:!0}:{}}}ue.customControlNeeds=Jee;function Yee(e,t,r){var n,i,o,a,s,l;let u=e.bag,c=new Map;for(let{cell:f,pointer:m}of(0,V.typedCellSites)(e)){let p=f.control;if(!Ct(p)||!pt(p.customControl))continue;let h=(0,V.controlUniqueId)(p);h&&Yi(u,h).length>0&&c.set(p,{plan:cc(e,p,t,!0),pointer:`${m}/control/customControl`})}let d=(0,V.descriptionsRegion)(u);if(d&&t){let f=(0,V.controlUniqueIds)(e),m=new Set,p=new Map;for(let{cell:h}of(0,V.typedCellSites)(e)){let g=pt(h.control)?(0,V.controlUniqueId)(h.control):"";g&&!p.has(g)&&p.set(g,h.control)}for(let{cell:h}of(0,V.typedCellSites)(t)){let g=h.control;if(!Ct(g))continue;let b=(0,V.controlUniqueId)(g),w=Yi(t.bag,b),C=Yi(u,b);if(w.length!==1||C.length!==1||!vn(w[0],C[0])||!Ta(C[0]))continue;let S=p.get(b);if(S&&!Ct(S)){if(((n=f.get(b))!==null&&n!==void 0?n:0)>1)continue;let O=(o=(i=Ta(C[0]))===null||i===void 0?void 0:i.nativeClass)!==null&&o!==void 0?o:"";S.classId=O.replace(/^\{|\}$/g,"").toUpperCase(),Qee(S,"uniqueid"),m.add(b)}else!S&&!f.has(b)&&m.add(b)}m.size>0&&(d.node.c=gr(d.node.c).filter(h=>!(h?.n==="controlDescription"&&m.has((0,V.normGuid)((0,V.rawAttr)(h,"forControl"))))))}for(let{cell:f}of(0,V.typedCellSites)(e)){let m=f.control;if(!Ct(m)||!pt(m.customControl))continue;Ji(m.classId)||(m.classId=V.CUSTOM_CONTROL_CLASS_ID);let p=(0,V.controlUniqueId)(m);if(!p){if((0,V.authoredUniqueId)(m)!==void 0)continue;p=(0,V.setUniqueId)(m)}let h=c.get(m);if(h){if(h.plan.kind==="refused")throw new $ee.ValidationError("form",e.id,[(0,we.issue)(h.pointer,h.plan.rule,h.plan.message)]);h.plan.kind==="edit"&&Xee(h.plan,m.customControl);continue}let g=r?.control(m.customControl.name),b=r?.column(e.entityLogicalName,m.fieldName),w=b?.kind==="found"?wb(b.value):void 0;if(g?.kind!=="found"||!w)continue;d||(d={i:(0,V.embedAppendIndex)(u),node:{n:"controlDescriptions",a:[],c:[]}},u.c.push(d));let C=((l=(s=gr((a=m.bag)===null||a===void 0?void 0:a.a).find(O=>O[0]==="uniqueid"))===null||s===void 0?void 0:s[1])!==null&&l!==void 0?l:"").trim(),S=C.startsWith("{")?C:`{${p}}`;d.node.c.push(RL(S,m.fieldName,w,m.customControl,g.value))}}ue.reconcilePcfDescriptions=Yee;function Qee(e,t){pt(e.bag)&&(e.bag.a=gr(e.bag.a).filter(r=>r[0]!==t))}function Xee(e,t){var r,n;let i=gr(e.description.c),o=i.findIndex(g=>(0,V.rawAttr)(g,"name")!==void 0),a=i.slice(0,o),s=i.slice(o),l=(r=t.parameters)!==null&&r!==void 0?r:{};for(let g of s)for(let b of(n=yp(g))!==null&&n!==void 0?n:[])e.changed.includes(b.n)&&(b.c=[vb(uc(e.stored.parameterTypes[b.n],l[b.n]))]);if(e.added.length===0&&e.removed.length===0)return;let u=g=>JSON.parse(JSON.stringify(g)),c=g=>{var b;let w=(0,V.rawAttr)(g,"formFactor");return w===void 0?null:(b=NL.get(w))!==null&&b!==void 0?b:null},d=(0,V.rawAttr)(a[0],"id"),f=(0,V.rawAttr)(s[0],"name"),m=bp(e.factors),p=m.defaults.map(g=>{let b=a.find(C=>c(C)===g);if(b)return b;let w=u(a[0]);return w.a=g===null?[["id",d]]:[["id",d],["formFactor",sc[g]]],w}),h=m.named.map(g=>{let b=s.find(C=>c(C)===g);if(b)return b;let w=u(s[0]);return w.a=[["name",f],["formFactor",sc[g]]],w});e.description.c=[...p,...h]}function Zee(e){return(0,V.typedCellSites)(e).some(({cell:t})=>Ct(t.control))}ue.mayCommitPcfState=Zee;function ete(e,t){var r;let n=JSON.parse(JSON.stringify(e)),i=!1;for(let{cell:o}of(0,V.typedCellSites)(n)){let a=o.control;if(!Ct(a))continue;let s=Sb(n,a);if(!s||s.fieldName!==a.fieldName)continue;let l=t(V.CUSTOM_CONTROL_CLASS_ID),u=gr((r=a.bag)===null||r===void 0?void 0:r.a).find(c=>c[0]==="classid");(!Ji(a.classId)||a.type!==l||u!==void 0&&!Ji(u[1])||!vn(a.customControl,s.binding))&&(Ji(a.classId)||(a.classId=V.CUSTOM_CONTROL_CLASS_ID),a.type=l,u&&!Ji(u[1])&&(u[1]=TL(V.CUSTOM_CONTROL_CLASS_ID)),a.customControl=JSON.parse(JSON.stringify(s.binding)),i=!0)}return i?n:e}ue.commitPcfState=ete;var tte=new Set(["name","parameters","formFactors"]);function rte(e,t,r){let n=[],i=(0,V.controlUniqueIds)(e);for(let{cell:o,pointer:a}of(0,V.typedCellSites)(e)){let s=o.control;Ct(s)&&ite(e,s,`${a}/control`,i,n,t,r?.atPush===!0)}return t&&ote(e,t,n),n}ue.pcfBindingIssues=rte;function nte(e,t,r){let n=r.length;if(!pt(e))return r.push((0,we.issue)(t,"pcf-binding-shape","customControl must be an object")),!1;for(let i of Object.keys(e))tte.has(i)||r.push((0,we.issue)(`${t}/${i}`,"pcf-binding-unknown-key",`customControl has no "${i}"`));if((typeof e.name!="string"||e.name.trim()==="")&&r.push((0,we.issue)(`${t}/name`,"pcf-binding-shape","name must be the control's non-empty customcontrols name")),e.parameters!==void 0)if(!pt(e.parameters))r.push((0,we.issue)(`${t}/parameters`,"pcf-binding-shape","parameters must be an object"));else for(let[i,o]of Object.entries(e.parameters))typeof o=="string"||typeof o=="boolean"||typeof o=="number"&&Number.isFinite(o)||r.push((0,we.issue)(`${t}/parameters/${i}`,"pcf-binding-shape","a parameter must be a string, a finite number or a boolean"));if(e.formFactors!==void 0){let i=e.formFactors;Array.isArray(i)&&i.length>0&&i.every(a=>typeof a=="string"&&Qi.includes(a))&&new Set(i).size===i.length||r.push((0,we.issue)(`${t}/formFactors`,"pcf-binding-shape","formFactors must be distinct 'web', 'phone' and 'tablet', at least one"))}return r.length===n}function ite(e,t,r,n,i,o,a){var s;let l=`${r}/customControl`,u=nte(t.customControl,l,i);t.fieldName||i.push((0,we.issue)(l,"pcf-binding-unbound","a PCF binding needs a control bound to a column (fieldName)")),t.genPage!==void 0&&i.push((0,we.issue)(l,"pcf-binding-with-genpage","a control cannot embed a page and bind a PCF control")),Nb(e)||i.push((0,we.issue)(l,"pcf-binding-form-type","PCF bindings are supported on Main and Quick Create forms only (not Quick View or Card)")),t.classId!==void 0&&typeof t.classId!="string"&&i.push((0,we.issue)(`${r}/classId`,"pcf-binding-class-id","classId must be a string"));let c=(0,V.authoredUniqueId)(t),d=(0,V.controlUniqueId)(t);if(c!==void 0&&!d?i.push((0,we.issue)(`${r}/bag`,"pcf-binding-unique-id","the control's uniqueid must be a GUID")):d&&((s=n.get(d))!==null&&s!==void 0?s:0)>1&&i.push((0,we.issue)(`${r}/bag`,"pcf-binding-unique-id","another control carries the same uniqueid")),!u)return;let f=cc(e,t,o,a);f.kind==="refused"&&i.push((0,we.issue)(l,f.rule,f.message))}function ote(e,t,r){var n;let i=new Map,o=$L(e,t);for(let{cell:l,pointer:u}of(0,V.typedCellSites)(e)){let c=pt(l.control)?(0,V.controlUniqueId)(l.control):"";if(c&&!i.has(c)&&i.set(c,{control:l.control,pointer:`${u}/control`}),pt(l.control)&&!Ct(l.control)){let d=o.get(l.control);d!==void 0&&r.push((0,we.issue)(`${u}/control`,"pcf-binding-unique-id",d))}}let a=(0,V.controlUniqueIds)(e);for(let{cell:l}of(0,V.typedCellSites)(t)){if(!Ct(l.control))continue;let u=(0,V.controlUniqueId)(l.control),c=i.get(u);!c||Ct(c.control)||(((n=a.get(u))!==null&&n!==void 0?n:0)>1?r.push((0,we.issue)(c.pointer,"pcf-binding-unique-id","another control carries this binding\u2019s uniqueid; removing the binding would delete its description too")):vn(Yi(t.bag,u),Yi(e.bag,u))?c.control.fieldName!==l.control.fieldName&&r.push((0,we.issue)(c.pointer,"pcf-binding-rebind","remove the binding, push, then bind the new column")):r.push((0,we.issue)(c.pointer,"pcf-binding-removed-changed","the binding changed since it was last pushed; remove it from an unchanged copy (re-fetch)")))}let s=new Set(r.map(l=>l.pointer));for(let{pointer:l}of zee(e,t))s.has(l)||r.push((0,we.issue)(l,"pcf-binding-unique-id",jee))}var ate=new Set(["Form.Card"]),ste="MscrmControls.ModelForm.ModelFormControl";function FL(e,t){var r;if(e.hasDataset||e.hasGroups)return"it has a data-set or groups";if(!e.isBound)return"its first property is not bound to a column";let n=e.properties;if(n.filter(s=>s.usage==="bound").length!==1)return"it has more than one bound property";let i=n.map(s=>s.name);if(i.some(s=>!s)||new Set(i).size!==i.length)return"a property has no name, or two share one";let o=i.find(s=>!OL(s));if(o!==void 0)return`the property name "${o}" cannot be written as an element`;if(t===ste||n.some(s=>s.defaultType!==void 0&&ate.has(s.defaultType)))return"a property needs a special encoding";if(n.some(s=>s.usage==="output"&&s.defaultValue!==null&&s.defaultValue!==""))return"an output property has a default";let a=n.find(s=>s.usage==="input"&&!Eb(s.defaultType));return a?`input "${a.name}" has a type the property editor does not write as text (${(r=a.defaultType)!==null&&r!==void 0?r:"none"})`:void 0}function lte(e){return e.ofType!==null?[e.ofType]:e.ofTypeGroup}function ML(e,t,r=e.defaultType){if(r==="Enum")return e.enumValues.some(o=>o.value===String(t))?void 0:`must be one of ${e.enumValues.map(o=>`"${o.value}"`).join(", ")}`;let n=r!==void 0?Cb.get(r):void 0;if(n){let o=typeof t=="boolean"?void 0:PL(t);return o===void 0||o<n.min||o>n.max?`must be a number from ${n.min.toFixed(n.digits)} through ${n.max.toFixed(n.digits)}`:void 0}if(r!==void 0&&DL.has(r))return t===!0||t===!1||t==="true"||t==="false"?void 0:"must be true or false";let i=r!==void 0?Mee.get(r):void 0;return i!==void 0&&String(t).length>i?`must be at most ${i} characters`:e.required&&String(t)===""?"is required":void 0}function ute(e,t,r){var n,i,o,a;let s={issues:[]},l=s.issues;for(let{cell:u,pointer:c}of(0,V.typedCellSites)(e)){let d=u.control;if(!Ct(d)||!d.fieldName)continue;let f=d.customControl;if(!pt(f)||typeof f.name!="string")continue;let m=`${c}/control/customControl`,p=cc(e,d,r,!0);if(p.kind==="edit"){xL(p)&&fte(p,f,m,t,s);continue}if(p.kind!=="new")continue;let h=t?.control(f.name),g=t?.column((n=e.entityLogicalName)!==null&&n!==void 0?n:"",d.fieldName);if(!h||h.kind==="unavailable"){(i=s.unavailable)!==null&&i!==void 0||(s.unavailable={code:"PCF_MANIFEST_UNAVAILABLE",message:`the manifest of "${f.name}" could not be read`,...h?.kind==="unavailable"?{cause:h.error}:{}});continue}if(h.kind!=="found"){l.push((0,we.issue)(`${m}/name`,"PCF_CONTROL_NOT_FOUND",`no single installed control is named "${f.name}" (${h.kind})`));continue}if(!g||g.kind==="unavailable"){(o=s.unavailable)!==null&&o!==void 0||(s.unavailable={code:"PCF_COLUMN_UNAVAILABLE",message:`the column "${d.fieldName}" could not be read`,...g?.kind==="unavailable"?{cause:g.error}:{}});continue}let b=FL(h.value,f.name);if(b){l.push((0,we.issue)(`${m}/name`,"pcf-binding-unsupported-control",`"${f.name}" is not supported: ${b}`));continue}let w=h.value.properties.find(x=>x.isPrimary),C=g.kind==="found"?g.value:void 0,S=C?(a=(0,xee.manifestTypesForColumn)(C.attributeTypeName,C.format,C.formatName))!==null&&a!==void 0?a:[]:[];C!==void 0&&!C.isPrimaryId&&C.isValidForForm&&wb(C)!==void 0&<e(w).some(x=>S.includes(x))?(0,V.effectiveFormType)(e)==="QuickCreate"&&C?.isValidForCreate!==!0&&l.push((0,we.issue)(m,"pcf-binding-quick-create-column",`"${d.fieldName}" cannot be set when a record is created, so a Quick Create form cannot bind it`)):l.push((0,we.issue)(m,"pcf-binding-incompatible-column",`"${f.name}" cannot be bound to "${d.fieldName}"`));let L=new Map(h.value.properties.filter(x=>x.usage==="input").map(x=>[x.name,x])),I=pt(f.parameters)?f.parameters:{};for(let[x,K]of Object.entries(I)){let Le=L.get(x);if(!Le){l.push((0,we.issue)(`${m}/parameters/${x}`,"pcf-binding-unknown-parameter",`"${f.name}" has no input "${x}"`));continue}let lr=ML(Le,K);lr&&l.push((0,we.issue)(`${m}/parameters/${x}`,"pcf-binding-parameter-value",`"${x}" ${lr}`))}for(let x of L.values())x.required&&!lc(I,x.name)&&!x.defaultValue&&l.push((0,we.issue)(`${m}/parameters`,"pcf-binding-missing-parameter",`"${x.name}" is required`));let D=Ab(h.value),P=Array.isArray(f.formFactors)?f.formFactors:void 0;(P?P.some(x=>!D.has(x)):D.size===0)&&l.push((0,we.issue)(`${m}/formFactors`,"pcf-binding-form-factor",`"${f.name}" is available on ${D.size===0?"no form factor":[...D].join(", ")}`))}return s}ue.pcfReadIssues=ute;function cte(e,t){return t===void 0||!Eb(t)?!1:e.ofType!==null?e.ofType===t:e.ofTypeGroup.includes(t)}function dte(e,t,r){var n,i;let o=FL(e,t);if(o)return`it is no longer supported (${o})`;let a=e.properties.find(d=>d.isPrimary);if(a?.name!==r.boundProperty)return`its bound property is now "${(n=a?.name)!==null&&n!==void 0?n:"none"}", not "${r.boundProperty}"`;let s=(i=r.binding.parameters)!==null&&i!==void 0?i:{},l=new Set(e.properties.filter(d=>d.usage==="input").map(d=>d.name)),u=Object.keys(s).find(d=>!l.has(d));if(u!==void 0)return`"${u}" is no longer one of its inputs`;let c=e.properties.find(d=>d.usage==="input"&&d.required&&!d.defaultValue&&!lc(s,d.name));return c?`it now requires "${c.name}", which the binding does not store`:void 0}function fte(e,t,r,n,i){var o,a,s;let l=i.issues,u=n?.control(t.name);if(!u||u.kind==="unavailable"){(o=i.unavailable)!==null&&o!==void 0||(i.unavailable={code:"PCF_MANIFEST_UNAVAILABLE",message:`the manifest of "${t.name}" could not be read`,...u?.kind==="unavailable"?{cause:u.error}:{}});return}if(u.kind!=="found"){l.push((0,we.issue)(`${r}/name`,"PCF_CONTROL_NOT_FOUND",`no single installed control is named "${t.name}" (${u.kind})`));return}let c=dte(u.value,t.name,e.stored);if(c){l.push((0,we.issue)(r,"pcf-binding-edit-manifest-changed",`"${t.name}" changed since this binding was written: ${c} \u2014 remove the binding, push, then add it`));return}let d=new Map(u.value.properties.filter(h=>h.usage==="input").map(h=>[h.name,h])),f=l.length;for(let h of Object.keys((a=e.stored.binding.parameters)!==null&&a!==void 0?a:{})){let g=e.stored.parameterTypes[h];cte(d.get(h),g)||l.push((0,we.issue)(`${r}/parameters/${h}`,"pcf-binding-edit-stored-type",`"${h}" is stored ${g===void 0?"with no type":`as type "${g}"`}, which "${t.name}" does not take for it now: remove the binding, push, then add it`))}if(l.length>f)return;let m=(s=t.parameters)!==null&&s!==void 0?s:{};for(let h of e.changed){let g=ML(d.get(h),m[h],e.stored.parameterTypes[h]);g&&l.push((0,we.issue)(`${r}/parameters/${h}`,"pcf-binding-parameter-value",`"${h}" ${g}`))}let p=Ab(u.value);e.added.some(h=>!p.has(h))&&l.push((0,we.issue)(`${r}/formFactors`,"pcf-binding-form-factor",`"${t.name}" is available on ${p.size===0?"no form factor":[...p].join(", ")}`))}});var tk=v(Mr=>{"use strict";Object.defineProperty(Mr,"__esModule",{value:!0});Mr.classIdForAttributeType=Mr.QUICK_VIEW_CLASS_ID=Mr.NOTES_CLASS_ID=Mr.SUBGRID_CLASS_ID=Mr.formRegistration=Mr.FormAdapter=void 0;var Xi=(vt(),zr(VT)),BL=(dt(),zr(GT)),pte=(kt(),zr(zT)),Et=(le(),zr(WT)),ot=(ga(),zr(jT)),mte=(rb(),zr(fL)),hte=(mL(),zr(pL)),At=wo(),qL=jr(),Fr=cn(),gte=e0(),dl=ct(),yte=yb(),ir=zd(),mi=UL(),cl=Q(),Pb=oe(),_b=Co(),HL=sa(),bte={[Et.FormType.Main]:"Main",[Et.FormType.QuickCreate]:"QuickCreate",[Et.FormType.QuickViewForm]:"QuickView",[Et.FormType.Card]:"Card"},vp={Main:Et.FormType.Main,QuickCreate:Et.FormType.QuickCreate,QuickView:Et.FormType.QuickViewForm,Card:Et.FormType.Card},vte=new Map(Object.entries(ot.ControlClassId).map(([e,t])=>[String(t).toUpperCase(),e]));function Rb(e){var t;return e&&(t=vte.get(e.toUpperCase()))!==null&&t!==void 0?t:"Unknown"}function dc(e){return e.getAllProperties().map(t=>[t.key,t.value])}function Da(e){let t=new Map;for(let r of e.getAllProperties())t.has(r.key)||t.set(r.key,r.value);return t}function KL(e,t){return e.getAllChildren().find(r=>r.getNodeName()===t)}function Lb(e,t){var r,n;let i=KL(e,"labels");if(!i)return"";let o=i.getAllChildren().filter(s=>s.getNodeName()==="label"),a=(r=o.find(s=>Da(s).get("languagecode")===String(t)))!==null&&r!==void 0?r:o[0];return a&&(n=Da(a).get("description"))!==null&&n!==void 0?n:""}function wte(e){let t=KL(e,"parameters"),r={};if(!t)return r;for(let n of t.getAllChildren()){let i=n.getNodeName();if(i.charAt(0)==="<"||i.charAt(0)==="#")continue;let o=n.getAllChildren()[0],a=o?o.getNodeName():"";a.charAt(0)==="<"&&(a=a.substring(1)),r[i]=a}return r}function JL(e){return/^1+$/.test(e)&&e.length>=1&&e.length<=4?e.length:1}function Tb(e){let t=Math.min(Math.max(Math.trunc(e),1),4);return"1".repeat(t)}function fc(e){return String(e??"").replace(/[{}]/g,"")}function Db(e){return`{${fc(e)}}`}function Ib(e,t){if(e===void 0||e==="")return t;let r=Number(e);return Number.isNaN(r)?t:r}function Cp(e,t,r){let n=e.getAllChildren(),i=n.findIndex(u=>u.getNodeName()===t),o=[];if(n.forEach((u,c)=>{c!==i&&o.push({i:c,node:(0,At.rawFromNode)(u)})}),i<0)return{modeled:[],bag:{a:dc(e),c:o}};let a=n[i],s=[],l=[];return a.getAllChildren().forEach((u,c)=>{u.getNodeName()===r?s.push(u):l.push({i:c,node:(0,At.rawFromNode)(u)})}),{modeled:s,bag:{a:dc(e),c:o,w:{n:a.getNodeName(),a:dc(a),c:l}}}}function YL(e,t,r){let n=[],i=[];return e.getAllChildren().forEach((o,a)=>{o.getNodeName()===t&&(!r||n.length===0)?n.push(o):i.push({i:a,node:(0,At.rawFromNode)(o)})}),{modeled:n,bag:{a:dc(e),c:i}}}function VL(e,t){let{modeled:r,bag:n}=Cp(e,"tabs","tab");return{tabs:r.map(i=>Cte(i,t)),bag:n}}function Cte(e,t){var r,n;let i=Da(e),{modeled:o,bag:a}=Cp(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:Lb(e,t),expanded:i.get("expanded")==="true",visible:i.has("visible")?i.get("visible")==="true":!0,columns:o.map(s=>Ete(s,t)),bag:a}}function Ete(e,t){let r=Da(e),{modeled:n,bag:i}=Cp(e,"sections","section");return{width:r.get("width"),sections:n.map(o=>Ate(o,t)),bag:i}}function Ate(e,t){var r,n,i;let o=Da(e),{modeled:a,bag:s}=Cp(e,"rows","row");return{id:(r=o.get("id"))!==null&&r!==void 0?r:"",name:(n=o.get("name"))!==null&&n!==void 0?n:"",label:Lb(e,t),visible:o.has("visible")?o.get("visible")==="true":!0,showLabel:o.get("showlabel")==="true",columns:JL((i=o.get("columns"))!==null&&i!==void 0?i:"1"),rows:a.map(l=>Ste(l,t)),bag:s}}function Ste(e,t){let{modeled:r,bag:n}=YL(e,"cell",!1);return{cells:r.map(i=>Nte(i,t)),bag:n}}function Nte(e,t){var r;let n=Da(e),{modeled:i,bag:o}=YL(e,"control",!0),a=Lb(e,t),s=n.get("showlabel")==="true",l=i[0]?_te(i[0],a,s):null;return{id:(r=n.get("id"))!==null&&r!==void 0?r:"",visible:n.has("visible")?n.get("visible")==="true":!0,colspan:Ib(n.get("colspan"),1),rowspan:Ib(n.get("rowspan"),1),control:l,bag:o}}function _te(e,t,r){var n,i;let o=Da(e),a=fc((n=o.get("classid"))!==null&&n!==void 0?n:""),s=o.get("datafieldname");return{id:(i=o.get("id"))!==null&&i!==void 0?i:"",classId:a,fieldName:s||null,type:Rb(a),isRequired:o.get("isrequired")==="true",isReadOnly:o.get("disabled")==="true",label:t,showLabel:r,parameters:wte(e),bag:{a:dc(e),c:e.getAllChildren().map((l,u)=>({i:u,node:(0,At.rawFromNode)(l)}))}}}function Uo(e){return e.a.length===0&&e.c.length===0&&!e.w}function QL(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function Ia(e,t){var r;let n=new Set(e.a.map(a=>a[0])),i=Uo(e),o=[];for(let a of t)if(n.has(a.key)){let s=(r=QL(e,a.key))!==null&&r!==void 0?r:"";a.matches(s)||o.push([a.key,a.render()])}else i?o.push([a.key,a.render()]):a.matches(a.absentDefault)||o.push([a.key,a.render()]);return(0,At.mergeAttrs)(e.a,o)}var Fo=(e,t)=>({key:e,matches:r=>r===t,render:()=>t,absentDefault:""}),Mo=(e,t,r=!1)=>({key:e,matches:n=>n==="true"===t,render:()=>String(t),absentDefault:String(r)}),GL=(e,t,r=1)=>({key:e,matches:n=>Ib(n,r)===t,render:()=>String(t),absentDefault:String(r)});function kb(e,t){return{n:"labels",a:[],c:[{n:"label",a:[["description",e],["languagecode",String(t)]],c:[]}]}}function Ob(e){return{n:"parameters",a:[],c:Object.keys(e).map(t=>{var r;return{n:(0,Pb.assertXmlName)(t,"Form control parameter name"),a:[],c:[{n:`<${(r=e[t])!==null&&r!==void 0?r:""}`,a:[],c:[]}]}})}}function Tte(e,t){var r,n;let i=e.c.find(a=>a.n==="label"&&a.a.some(s=>s[0]==="languagecode"&&s[1]===String(t))),o=i??e.c.find(a=>a.n==="label");return(n=(r=o?.a.find(a=>a[0]==="description"))===null||r===void 0?void 0:r[1])!==null&&n!==void 0?n:""}function Dte(e,t,r){let n=!1,i=e.c.map(o=>o.n!=="label"||!o.a.some(s=>s[0]==="languagecode"&&s[1]===String(r))?o:(n=!0,{...o,a:o.a.map(s=>s[0]==="description"?["description",t]:s)}));return n||i.push({n:"label",a:[["description",t],["languagecode",String(r)]],c:[]}),{...e,c:i}}function $b(e,t,r){let n=e.c.findIndex(o=>o.node.n==="labels");if(n<0){if(!t||Uo(e))return e;let a=e.c.some(s=>s.i===0)?e.c.map(s=>({...s,i:s.i+1})):e.c;return{...e,c:[{i:0,node:kb(t,r)},...a]}}if(Tte(e.c[n].node,r)===t)return e;let i=Dte(e.c[n].node,t,r);return{...e,c:e.c.map((o,a)=>a===n?{...o,node:i}:o)}}function Ite(e){let t={};for(let r of e.c){let n=r.n;if(n.charAt(0)==="<"||n.charAt(0)==="#")continue;let i=r.c[0],o=i?i.n:"";o.charAt(0)==="<"&&(o=o.substring(1)),t[n]=o}return t}function Ote(e,t){let r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every(i=>e[i]===t[i])}function Pte(e,t){return e.a.some(r=>r[0]===t)?{...e,a:e.a.filter(r=>r[0]!==t)}:e}function Rte(e,t){let r=e.c.findIndex(i=>i.node.n==="parameters");if(r<0){if(Object.keys(t).length===0||Uo(e))return e;let i=e.c.reduce((o,a)=>a.i>o?a.i:o,-1);return{...e,c:[...e.c,{i:i+1,node:Ob(t)}]}}if(Ote(Ite(e.c[r].node),t))return e;let n=Ob(t);return{...e,c:e.c.map((i,o)=>o===r?{...i,node:n}:i)}}function Ep(e,t,r,n){if(e.w){let a={n:e.w.n,a:e.w.a.map(s=>[s[0],s[1]]),c:(0,At.spliceChildren)(e.w.c,r)};return(0,At.spliceChildren)(e.c,[a])}let i=n(),o={n:t,a:[],c:r};return e.c.length===0?[...i,o]:(0,At.spliceChildren)(e.c,[...i,o])}function Lte(e,t){let r=e.tabs.map(n=>kte(n,t));return{n:"form",a:Ia(e.bag,[]),c:e.tabs.length===0&&Uo(e.bag)?[]:Ep(e.bag,"tabs",r,()=>[])}}function XL(e,t,r){return t&&!e.c.some(n=>n.node.n==="labels")?[kb(t,r)]:[]}function kte(e,t){let r=[Fo("id",e.id),Fo("name",e.name),Mo("expanded",e.expanded),Mo("visible",e.visible,!0)],n=e.columns.map(o=>$te(o,t)),i=$b(e.bag,e.label,t);return{n:"tab",a:Ia(i,r),c:Ep(i,"columns",n,()=>XL(i,e.label,t))}}function $te(e,t){let r=e.width!==void 0?[Fo("width",e.width)]:[],n=e.sections.map(i=>xte(i,t));return{n:"column",a:Ia(e.bag,r),c:Ep(e.bag,"sections",n,()=>[])}}function xte(e,t){let r=[Fo("id",e.id),Fo("name",e.name),Mo("showlabel",e.showLabel),Mo("visible",e.visible,!0),{key:"columns",matches:o=>JL(o)===e.columns,render:()=>Tb(e.columns),absentDefault:Tb(1)}],n=e.rows.map(o=>Fte(o,t)),i=$b(e.bag,e.label,t);return{n:"section",a:Ia(i,r),c:Ep(i,"rows",n,()=>XL(i,e.label,t))}}function Fte(e,t){let r=e.cells.map(n=>Mte(n,t));return{n:"row",a:Ia(e.bag,[]),c:Uo(e.bag)?r:(0,At.assembleChildren)(e.bag,r)}}function Mte(e,t){let r=e.control?e.control.showLabel:QL(e.bag,"showlabel")==="true",n=[Fo("id",e.id),Mo("showlabel",r),Mo("visible",e.visible,!0),GL("colspan",e.colspan),GL("rowspan",e.rowspan)],i=e.control?[Ute(e.control)]:[],o;if(Uo(e.bag))o=[...e.control&&e.control.label?[kb(e.control.label,t)]:[],...i];else{let a=e.control?$b(e.bag,e.control.label,t):e.bag;o=(0,At.assembleChildren)(a,i)}return{n:"cell",a:Ia(e.bag,n),c:o}}function Ute(e){let t=[Fo("id",e.id),{key:"classid",matches:i=>fc(i)===e.classId,render:()=>Db(e.classId||String(ot.ControlClassId.TextboxControl)),absentDefault:""}];e.fieldName!==null&&t.push(Fo("datafieldname",e.fieldName)),t.push(Mo("disabled",e.isReadOnly)),t.push(Mo("isrequired",e.isRequired));let r=e.fieldName===null?Pte(e.bag,"datafieldname"):e.bag,n;return Uo(r)?n=Object.keys(e.parameters).length>0?[Ob(e.parameters)]:[]:n=(0,At.assembleChildren)(Rte(r,e.parameters),[]),{n:"control",a:Ia(r,t),c:n}}var Bte={make:(e,t)=>new pte.FormElementNode(e,t),setProp:(e,t,r)=>e.setProperty(t,r),addChild:(e,t)=>e.addChild(t)};function WL(e,t,r,n){(0,_b.installDomShim)();let i=Vte(e,r);(0,ir.reconcileEmbedDescriptions)(i,n),(0,mi.reconcilePcfDescriptions)(i,n,r?.pcf);let o=(0,At.rebuildRaw)(Lte(i,t),Bte,null);return new hte.SerializationService(t).serializeFormXmlNode(o)}function qte(e){return JSON.parse(JSON.stringify(e))}function Vte(e,t){let r=qte(e);r.bag||(r.bag=(0,At.emptyBag)()),r.tabs||(r.tabs=[]),Yte(r.bag),t&&Gte(r,t);for(let n of r.tabs)Wte(n);return r}function Gte(e,t){var r;let n=(r=e.entityLogicalName)!==null&&r!==void 0?r:"";xb(e,i=>{let o=i.fieldName,a=i;if(!o||a.label!==void 0&&a.classId!==void 0)return;let s=t.resolveField(n,o);s&&(a.label===void 0&&s.displayName&&(a.label=s.displayName),a.classId===void 0&&s.attributeType&&(a.classId=ek(s.attributeType)))})}function zL(e){let t=[];return xb(e,r=>t.push(r)),t}function xb(e,t){var r,n,i,o,a;for(let s of(r=e.tabs)!==null&&r!==void 0?r:[])for(let l of(n=s.columns)!==null&&n!==void 0?n:[])for(let u of(i=l.sections)!==null&&i!==void 0?i:[])for(let c of(o=u.rows)!==null&&o!==void 0?o:[])for(let d of(a=c.cells)!==null&&a!==void 0?a:[])d.control&&t(d.control)}function Wte(e){e.id||(e.id=Xi.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)zte(t);e.bag||(e.bag=(0,At.emptyBag)())}function zte(e){e.sections||(e.sections=[]);for(let t of e.sections)jte(t);e.bag||(e.bag=(0,At.emptyBag)()),e.width===void 0&&Uo(e.bag)&&(e.width="100%")}function jte(e){e.id||(e.id=Xi.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)Hte(t);e.bag||(e.bag=(0,At.emptyBag)())}function Hte(e){e.cells||(e.cells=[]);for(let t of e.cells)Kte(t);e.bag||(e.bag=(0,At.emptyBag)())}function Kte(e){(0,ir.hasGenPage)(e.control)&&(0,ir.applyEmbedCellDefaults)(e),e.id||(e.id=Xi.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&&Jte(e.control),e.bag||(e.bag=(0,At.emptyBag)())}function Jte(e){var t;(0,ir.hasGenPage)(e)&&(0,ir.applyEmbedControlDefaults)(e),e.id||(e.id=Xi.Guid.NewGuid()),(e.classId===void 0||e.classId===null)&&(e.classId=String(ot.ControlClassId.TextboxControl)),e.fieldName===void 0&&(e.fieldName=null),e.type===void 0&&(e.type=e.fieldName?"Field":Rb(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,Pb.assertXmlName)(r,"Form control parameter name");e.bag||(e.bag=(0,At.emptyBag)())}function Yte(e){for(let t of e.c){let r=t.node;if(r.n==="events"){for(let n of r.c)if(n.n==="event"){for(let i of n.c)if(i.n==="Handlers")for(let o of i.c)o.n==="Handler"&&!jL(o,"handlerUniqueId")&&o.a.push(["handlerUniqueId",Db(Xi.Guid.NewGuid())])}}else if(r.n==="formLibraries")for(let n of r.c)n.n==="Library"&&!jL(n,"libraryUniqueId")&&n.a.push(["libraryUniqueId",Db(Xi.Guid.NewGuid())])}}var wp=class{constructor(t=HL.DEFAULT_LCID){this.lcid=t}toArtifact(t,r){var n,i,o;let{tabs:a,bag:s}=VL(t,this.lcid),l={id:t.formId?t.formId.guidString:"",name:(n=t.formName)!==null&&n!==void 0?n:"",entityLogicalName:(i=t.entityName)!==null&&i!==void 0?i:"",formType:(o=bte[t.formType])!==null&&o!==void 0?o:"Main",status:this.readActivationStatus(t),...r!==void 0&&r!==""?{description:r}:{},tabs:a,bag:s};return(0,ir.projectGenPageEmbeds)(l),(0,mi.projectPcfBindings)(l),l}fromArtifact(t){var r;return this.deserialize({formxml:WL(t,this.lcid),formid:t.id||(0,dl.newId)(),objecttypecode:t.entityLogicalName,type:vp[t.formType],name:t.name,uniquename:t.name,description:(r=t.description)!==null&&r!==void 0?r:"",formpresentation:Et.FormPresentation.AirForm,formactivationstate:t.status==="Active"?Et.FormActivationState.Active:Et.FormActivationState.InActive})}fromApiResponse(t){var r,n,i,o,a,s,l;let u=t,c=(r=u.formxml)!==null&&r!==void 0?r:"",d={formxml:c,formid:(n=u.formid)!==null&&n!==void 0?n:(0,dl.newId)(),objecttypecode:(i=u.objecttypecode)!==null&&i!==void 0?i:"",type:u.type,name:(o=u.name)!==null&&o!==void 0?o:"",uniquename:(a=u.uniquename)!==null&&a!==void 0?a:"",description:(s=u.description)!==null&&s!==void 0?s:"",formpresentation:u.formpresentation,formactivationstate:u.formactivationstate};(0,_b.installDomShim)();let f=BL.ScriptUtilities.ParseXml(c),m=Qte(f),p=this.deserializeDocument(d,f);return Xte(this.toArtifact(p,(l=u.description)!==null&&l!==void 0?l:void 0),m)}toApiPayload(t,r,n){let i=(0,ir.genPageEmbedIssues)(t);if(i.length>0)throw new cl.ValidationError("form",t.id,i);let o=(0,mi.pcfBindingIssues)(t,r,{atPush:!0});if(o.length>0)throw new cl.ValidationError("form",t.id,o);let a=(0,mi.pcfReadIssues)(t,n?.pcf,r);if(a.unavailable)throw(0,cl.attachCause)(new cl.SdkError(a.unavailable.code,a.unavailable.message),a.unavailable.cause);if(a.issues.length>0)throw new cl.ValidationError("form",t.id,a.issues);return{formxml:WL(t,this.lcid,n,r),name:t.name,type:vp[t.formType],objecttypecode:t.entityLogicalName,...t.description!==void 0?{description:t.description}:{}}}metadataNeeds(t){let r=t.entityLogicalName;if(!r)return[];let n=new Map;return xb(t,i=>{var o;let a=i.fieldName,s=i;if(!a||s.label!==void 0&&s.classId!==void 0)return;let l=(o=n.get(a))!==null&&o!==void 0?o:{entityLogicalName:r,fieldName:a};s.label===void 0&&(l.needsLabel=!0),n.set(a,l)}),[...n.values()]}customControlNeeds(t,r){var n;return{entityLogicalName:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",...(0,mi.customControlNeeds)(t,r)}}createDefault(t){var r,n,i,o,a,s,l,u,c,d,f,m;let p=[...(0,ir.genPageEmbedIssues)(t),...(0,mi.pcfBindingIssues)(t)];if(p.length>0)throw new cl.ValidationError("form",t.id||"(new)",p);let h=t.tabs&&t.tabs.length>0?void 0:lre(this.lcid),g=h!==void 0?h:t.tabs.map(C=>Zte(C,this.lcid)).join(""),b=this.deserialize({formxml:`<form><tabs>${g}</tabs></form>`,formid:t.id||(0,dl.newId)(),objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",type:vp[(n=t.formType)!==null&&n!==void 0?n:"Main"],name:(i=t.name)!==null&&i!==void 0?i:"New Form",uniquename:(o=t.name)!==null&&o!==void 0?o:"New Form",description:(a=t.description)!==null&&a!==void 0?a:"",formpresentation:Et.FormPresentation.AirForm,formactivationstate:((s=t.status)!==null&&s!==void 0?s:"Active")==="Active"?Et.FormActivationState.Active:Et.FormActivationState.InActive});(l=b.displayCondition)===null||l===void 0||l.removeProperty(Et.ElementProperties.Order);let w=this.toArtifact(b,t.description);if(t.tabs&&t.tabs.length>0){let C=zL(t);zL(w).forEach((S,O)=>{C[O]&&C[O].label===void 0&&delete S.label,C[O]&&C[O].genPage!==void 0&&(S.genPage=JSON.parse(JSON.stringify(C[O].genPage))),C[O]&&C[O].customControl!==void 0&&(S.customControl=JSON.parse(JSON.stringify(C[O].customControl)))})}return{id:(u=t.id)!==null&&u!==void 0?u:w.id,name:(c=t.name)!==null&&c!==void 0?c:"New Form",entityLogicalName:(d=t.entityLogicalName)!==null&&d!==void 0?d:"",formType:(f=t.formType)!==null&&f!==void 0?f:"Main",status:(m=t.status)!==null&&m!==void 0?m:"Active",...t.description!==void 0?{description:t.description}:{},tabs:w.tabs,bag:w.bag}}assignMissingIds(t){return(0,dl.assignMissingIds)(t)}completeAsStored(t,r){return(0,yte.completeRecordAsStored)(t,r,this.lcid)}normalize(t){return(0,mi.mintPcfIdentity)((0,ir.mintEmbedIdentity)(t))}committed(t,r){var n,i,o,a,s,l;let u=r?.formxml;if(typeof u!="string"||!((0,ir.mayCommitEmbedState)(t)||(0,mi.mayCommitPcfState)(t)))return{artifact:t,baseline:t};let c=this.deserialize({formxml:u,formid:t.id||(0,dl.newId)(),objecttypecode:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",type:vp[(i=t.formType)!==null&&i!==void 0?i:"Main"],name:(o=t.name)!==null&&o!==void 0?o:"",uniquename:(a=t.name)!==null&&a!==void 0?a:"",description:(s=t.description)!==null&&s!==void 0?s:"",formpresentation:Et.FormPresentation.AirForm,formactivationstate:Et.FormActivationState.Active}),{bag:d}=VL(c,this.lcid),f=(0,mi.commitPcfState)((0,ir.commitEmbedState)(t,(l=(0,ir.descriptionsRegion)(d))===null||l===void 0?void 0:l.node),Rb);return{artifact:f,baseline:f}}validate(t){return yre(t)}deserialize(t){return(0,_b.installDomShim)(),this.deserializeDocument(t,BL.ScriptUtilities.ParseXml(t.formxml))}deserializeDocument(t,r){let n=new mte.DeserializationService(this.lcid).deSerializeFormXml(r,new Xi.Guid(t.formid),t.objecttypecode,Et.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===Et.FormActivationState.InActive?"Inactive":"Active"}};Mr.FormAdapter=wp;var ZL=["header","footer","DisplayConditions"];function Qte(e){var t;let r=e?.getElementsByTagName("form")[0],n=new Set;for(let i=(t=r?.firstChild)!==null&&t!==void 0?t:null;i;i=i.nextSibling)i.nodeType===1&&ZL.includes(i.nodeName)&&n.add(i.nodeName);return n}function Xte(e,t){var r;if(!(!((r=e.bag)===null||r===void 0)&&r.c))return e;let n=ZL.filter(o=>!t.has(o)),i=e.bag.c.filter(o=>{var a;return n.includes((a=o?.node)===null||a===void 0?void 0:a.n)}).map(o=>o.i);return i.length>0&&(e.bag.c=e.bag.c.filter(o=>{var a;return!n.includes((a=o?.node)===null||a===void 0?void 0:a.n)}).map(o=>({...o,i:o.i-i.filter(a=>a<o.i).length}))),e}function Un(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Fb(e,t){return e?`<labels><label description="${Un(e)}" languagecode="${t}" /></labels>`:""}function Mb(e){return e&&e.length>0?fc(e):(0,dl.newId)()}function Zte(e,t){var r,n,i,o;let a=(r=e.columns)!==null&&r!==void 0?r:[],s=(a.length>0?a:[sre()]).map(l=>ere(l,t)).join("");return`<tab id="{${Un(Mb(e.id))}}" name="${Un((n=e.name)!==null&&n!==void 0?n:"")}" expanded="${(i=e.expanded)!==null&&i!==void 0?i:!0}" visible="${(o=e.visible)!==null&&o!==void 0?o:!0}">${Fb(e.label,t)}<columns>${s}</columns></tab>`}function ere(e,t){var r,n;let i=((r=e.sections)!==null&&r!==void 0?r:[]).map(o=>tre(o,t)).join("");return`<column width="${Un((n=e.width)!==null&&n!==void 0?n:"100%")}"><sections>${i}</sections></column>`}function tre(e,t){var r,n,i,o,a;let s=((r=e.rows)!==null&&r!==void 0?r:[]).map(l=>rre(l,t)).join("");return`<section id="{${Un(Mb(e.id))}}" name="${Un((n=e.name)!==null&&n!==void 0?n:"")}" showlabel="${(i=e.showLabel)!==null&&i!==void 0?i:!1}" visible="${(o=e.visible)!==null&&o!==void 0?o:!0}" columns="${Tb((a=e.columns)!==null&&a!==void 0?a:1)}">${Fb(e.label,t)}<rows>${s}</rows></section>`}function rre(e,t){var r;return`<row>${((r=e.cells)!==null&&r!==void 0?r:[]).map(n=>nre(n,t)).join("")}</row>`}function nre(e,t){var r,n,i,o,a;let s=ire(e),l=s.control,u=l?Fb((r=l.label)!==null&&r!==void 0?r:"",t):"",c=l?ore(l):"";return`<cell id="{${Un(Mb(s.id))}}" showlabel="${l?(n=l.showLabel)!==null&&n!==void 0?n:!0:!1}" visible="${(i=s.visible)!==null&&i!==void 0?i:!0}" colspan="${(o=s.colspan)!==null&&o!==void 0?o:1}" rowspan="${(a=s.rowspan)!==null&&a!==void 0?a:1}">${u}${c}</cell>`}function ire(e){if(!(0,ir.hasGenPage)(e.control))return e;let t={...e.control};(0,ir.applyEmbedControlDefaults)(t);let r={...e,control:t};return(0,ir.applyEmbedCellDefaults)(r),r}function ore(e){var t,r,n;let i=e.fieldName?` datafieldname="${Un(e.fieldName)}"`:"",o=are(e.parameters),a=e.classId?fc(e.classId):String(ot.ControlClassId.TextboxControl);return`<control id="${Un((t=e.id)!==null&&t!==void 0?t:"")}" classid="{${Un(a)}}"${i} disabled="${(r=e.isReadOnly)!==null&&r!==void 0?r:!1}" isrequired="${(n=e.isRequired)!==null&&n!==void 0?n:!1}">${o}</control>`}function are(e){let t=Object.keys(e??{});return t.length===0?"":(t.forEach(n=>(0,Pb.assertXmlName)(n,"Form control parameter name")),`<parameters>${t.map(n=>`<${n}>${Un(e[n])}</${n}>`).join("")}</parameters>`)}function sre(){return{width:"100%",sections:[],bag:{a:[],c:[]}}}function lre(e){return`<tab id="{${Xi.Guid.NewGuid()}}" name="tab_general" expanded="true" visible="true"><labels><label description="General" languagecode="${e}" /></labels><columns><column width="100%"><sections><section id="{${Xi.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 ure(e=HL.DEFAULT_LCID){return{adapter:new wp(e),api:gte.formApi,languageSensitive:!0,publish:(t,r,n)=>(0,qL.publishBoundEntity)(t,n),publishScope:(t,r)=>(0,qL.boundEntityPublishScope)(r),rebaselineAfterPublish:"bracket"}}Mr.formRegistration=ure;var cre=new Set(["id","name","label","expanded","visible","columns","bag"]),dre=new Set(["id","width","sections","bag"]),fre=new Set(["id","name","label","visible","showLabel","columns","rows","bag"]),pre=new Set(["id","cells","bag"]),mre=new Set(["id","visible","colspan","rowspan","control","bag"]),hre=new Set(["id","classId","fieldName","type","isRequired","isReadOnly","label","showLabel","parameters","genPage","customControl","bag"]),gre={elsewhere:{isReadOnly:"control",isRequired:"control",fieldName:"control",classId:"control",label:"control",showLabel:"control",parameters:"control"},unsupported:{createOnly:"FormXml has no create-only concept; gate the field with a business rule instead. Raise it with the SDK owners if you need it modeled.",updateOnly:"FormXml has no update-only concept; gate the field with a business rule instead. Raise it with the SDK owners if you need it modeled."}};function yre(e){let t=[];return(0,Fr.childObjects)(e,"tabs","","tab",t).forEach(({node:n,index:i})=>{let o=`/tabs/${i}`;(0,Fr.rejectUnknownKeys)(n,cre,o,"tab",t),(0,Fr.childObjects)(n,"columns",o,"column",t).forEach(({node:s,index:l})=>{let u=`${o}/columns/${l}`;(0,Fr.rejectUnknownKeys)(s,dre,u,"column",t),(0,Fr.childObjects)(s,"sections",u,"section",t).forEach(({node:d,index:f})=>{let m=`${u}/sections/${f}`;(0,Fr.rejectUnknownKeys)(d,fre,m,"section",t),(0,Fr.childObjects)(d,"rows",m,"row",t).forEach(({node:h,index:g})=>{let b=`${m}/rows/${g}`;(0,Fr.rejectUnknownKeys)(h,pre,b,"row",t),(0,Fr.childObjects)(h,"cells",b,"cell",t).forEach(({node:C,index:S})=>{let O=`${b}/cells/${S}`;(0,Fr.rejectUnknownKeys)(C,mre,O,"cell",t,gre);let L=C.control;L!=null&&!(0,Fr.isJsonObject)(L)?t.push((0,Fr.issue)(`${O}/control`,"control-must-be-object-or-null",`a cell control must be a JSON object or null, got ${typeof L}`)):(0,Fr.isJsonObject)(L)&&(0,Fr.rejectUnknownKeys)(L,hre,`${O}/control`,"control",t)})})})})}),t.push(...(0,ir.genPageEmbedIssues)(e)),t.push(...(0,mi.pcfBindingIssues)(e)),t}Mr.SUBGRID_CLASS_ID=ot.ControlClassId.SubgridControl;Mr.NOTES_CLASS_ID=ot.ControlClassId.TimelineControl;Mr.QUICK_VIEW_CLASS_ID=ot.ControlClassId.QuickViewControl;var bre={Lookup:String(ot.ControlClassId.LookupControl),Customer:String(ot.ControlClassId.LookupControl),Owner:String(ot.ControlClassId.LookupControl),PartyList:String(ot.ControlClassId.PartyListControl),Boolean:String(ot.ControlClassId.BooleanControl),DateTime:String(ot.ControlClassId.DateTimeControl),Decimal:String(ot.ControlClassId.DecimalControl),Double:String(ot.ControlClassId.FloatingNumberControl),Money:String(ot.ControlClassId.CurrencyControl),Integer:String(ot.ControlClassId.IntegerControl),BigInt:String(ot.ControlClassId.IntegerControl),Memo:String(ot.ControlClassId.TextAreaControl),String:String(ot.ControlClassId.TextboxControl)},vre="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE";function ek(e){return e==="Picklist"||e==="State"||e==="Status"?vre:e&&bre[e]||String(ot.ControlClassId.TextboxControl)}Mr.classIdForAttributeType=ek;function jL(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}});var Ub=v(fl=>{"use strict";Object.defineProperty(fl,"__esModule",{value:!0});fl.viewApi=fl.findDefaultViews=void 0;var ok=Tt(),yr=fe(),Bn=oe(),wre=ys(),rk="savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault",Cre="savedqueryid,name,returnedtypecode,querytype,isdefault",Ere=60*1e3;function Ap(e){return(e.localName||e.nodeName).toLowerCase()}function pc(e,t){let r;for(let n=0;n<e.attributes.length;n+=1){let i=e.attributes[n];i.nodeName.toLowerCase()===t&&(r=r===void 0?i.value:null)}return r}function Are(e){if(!e)return;let t=!0,r=()=>{t=!1},n=new wre.DOMParser({errorHandler:{warning:r,error:r,fatalError:r}}).parseFromString(e,"text/xml").documentElement;return t&&n&&Ap(n)==="fetch"?n:void 0}function Sre(e){for(let t=e.parentNode;t;t=t.parentNode)if(Ap(t)==="link-entity")return!0;return!1}function nk(e,t){var r,n,i;if(((r=e.canbedeleted)===null||r===void 0?void 0:r.Value)!==!1)return!1;let o=Are(e.fetchxml);if(!o)return!1;let a=Array.from(o.getElementsByTagName("*")),s=a.filter(u=>Ap(u)==="condition"),l=s.length===1?s[0]:void 0;return l!==void 0&&a.filter(u=>Ap(u)==="link-entity").every(u=>{var c;return((c=pc(u,"link-type"))===null||c===void 0?void 0:c.toLowerCase())==="outer"})&&!Sre(l)&&pc(l,"entityname")===void 0&&((n=pc(l,"attribute"))===null||n===void 0?void 0:n.toLowerCase())==="statecode"&&((i=pc(l,"operator"))===null||i===void 0?void 0:i.toLowerCase())==="eq"&&pc(l,"value")===String(t)}function Nre(e,t){let r=String(e??"").trim().toLowerCase().split(/\s+/).filter(i=>i!==""),n=String(t??"").trim().toLowerCase().split(/\s+/).filter(i=>i!=="");return r.length===n.length&&r.filter((i,o)=>i!==n[o]).length===1}function _re(e){var t,r;let n=e.filter(a=>nk(a,0)),i=e.filter(a=>nk(a,1)),o=[];for(let a of n)for(let s of i)Math.abs(Date.parse(String((t=s.createdon)!==null&&t!==void 0?t:""))-Date.parse(String((r=a.createdon)!==null&&r!==void 0?r:"")))<=Ere&&Nre(a.name,s.name)&&o.push({active:a,inactive:s});return o.length===1?o[0]:void 0}async function Tre(e,t,r={}){var n;let i=new Set(((n=r.excludeViewIds)!==null&&n!==void 0?n:[]).filter(Boolean)),o=`returnedtypecode eq '${(0,Bn.odataLiteral)(t)}' and querytype eq 0`,a=`/savedqueries${(0,Bn.odataQuery)([["$select","savedqueryid,name,canbedeleted,fetchxml,createdon"],["$filter",o]])}`,s=await(0,ok.collectPages)(e,a,`findDefaultViews('${t}')`),l=_re(s),u=new Set(l?[l.active,l.inactive]:[]);return s.filter(c=>c.savedqueryid&&!i.has(c.savedqueryid)&&u.has(c)).map(c=>{var d;return{id:String(c.savedqueryid),name:String((d=c.name)!==null&&d!==void 0?d:"")}})}fl.findDefaultViews=Tre;async function Dre(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,Bn.odataPathLiteral)(t)}')${(0,Bn.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status>=200&&i.status<300){let o=(r=i.body)===null||r===void 0?void 0:r.ObjectTypeCode;return typeof o=="number"?o:void 0}}async function ik(e,t,r){if(!r||!/<grid\b/.test(t)||/<grid[^>]*\bobject=/.test(t))return t;let n=await Dre(e,r);return n===void 0?t:t.replace(/<grid\b/,`<grid object="${n}"`)}fl.viewApi={async get(e,t){let r=(0,Bn.normalizeGuid)(t,"id"),n=await(0,yr.readRowEtag)(e,"savedqueries","savedqueryid",r),i=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Bn.odataQuery)([["$select",rk]]);return{raw:(0,yr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},async readContentThenToken(e,t){let r=(0,Bn.normalizeGuid)(t,"id"),n=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Bn.odataQuery)([["$select",rk]]),i=(0,yr.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=await(0,yr.readRowEtag)(e,"savedqueries","savedqueryid",r);return{raw:i.body,etag:o}},async list(e,t){let r=`/savedqueries${(0,Bn.odataQuery)([["$select",Cre],["$filter",t?.entityLogicalName?`returnedtypecode eq '${(0,Bn.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,ok.collectPages)(e,r,"listArtifacts('view')")).map(i=>{var o,a;return{type:"view",id:(o=i.savedqueryid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",entityLogicalName:i.returnedtypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,yr.echoWrite)("savedqueryid"),o=`/savedqueries${i.query}`,a=await ik(e,n.layoutxml,n.returnedtypecode),s=Object.freeze((0,yr.withClientMintedId)({name:n.name,description:n.description,fetchxml:n.fetchxml,layoutxml:a,returnedtypecode:n.returnedtypecode,querytype:n.querytype,isdefault:n.isdefault},"savedqueryid",r)),l=(0,yr.ensureSuccess)(await(0,yr.resendDeadlockVictim)(()=>e.post(o,{...s},i.options)),e.apiUrl(o));return{id:(0,yr.resolveCreatedId)(l,"savedqueryid","view",r),etag:(0,yr.readEtag)(l)}},async update(e,t,r,n){let i=r,o=(0,Bn.normalizeGuid)(t,"id"),a=(0,yr.echoWrite)("savedqueryid",{"If-Match":(0,yr.requireEtag)(n,"view",o)}),s=`/savedqueries(${o})${a.query}`,l=await ik(e,i.layoutxml,i.returnedtypecode),u=(0,yr.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,fetchxml:i.fetchxml,layoutxml:l},a.options),e.apiUrl(s));return{id:o,etag:(0,yr.readEtag)(u)}},delete(e,t){return(0,yr.deleteRecord)(e,"savedqueries",t)}}});var Ck=v(pl=>{"use strict";Object.defineProperty(pl,"__esModule",{value:!0});pl.viewRegistration=pl.ViewAdapter=void 0;var fk=Q(),en=cn(),Bb=wo(),Oa=Eo(),ak=jr(),Ire=Ub(),qb=Co(),Ore=ct(),pk=100,Np=class{toArtifact(t){var r,n,i,o,a,s,l,u;(0,qb.installDomShim)();let c=(r=t.fetchxml)!==null&&r!==void 0?r:"",d=(n=t.layoutxml)!==null&&n!==void 0?n:"",f=(0,Oa.parseXmlRoot)(c,"<fetch/>"),m=(0,Oa.parseXmlRoot)(d,"<grid/>"),p=hk(f);return{id:(i=t.savedqueryid)!==null&&i!==void 0?i:"",name:(o=t.name)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",entityLogicalName:(s=t.returnedtypecode)!==null&&s!==void 0?s:Rre(f),queryType:(l=t.querytype)!==null&&l!==void 0?l:0,isDefault:(u=t.isdefault)!==null&&u!==void 0?u:!1,columns:mk(m,f),filters:yk(f),sort:gk(f),...p.length>0?{linkEntities:p}:{},fetchBag:c?(0,Oa.projectElementBag)(f):void 0,layoutBag:d?(0,Oa.projectElementBag)(m):void 0}}fromArtifact(t){(0,qb.installDomShim)();let{fetchxml:r,layoutxml:n}=sk(t);return{savedqueryid:t.id,name:t.name,description:t.description,returnedtypecode:t.entityLogicalName,querytype:t.queryType,isdefault:t.isDefault,fetchxml:r,layoutxml:n}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){var r,n,i,o,a;(0,qb.installDomShim)();let{fetchxml:s,layoutxml:l}=sk(t);return{name:(r=t.name)!==null&&r!==void 0?r:"",description:(n=t.description)!==null&&n!==void 0?n:"",fetchxml:s,layoutxml:l,returnedtypecode:(i=t.entityLogicalName)!==null&&i!==void 0?i:"",querytype:(o=t.queryType)!==null&&o!==void 0?o:0,isdefault:(a=t.isDefault)!==null&&a!==void 0?a:!1}}createDefault(t){var r,n,i,o,a,s,l,u;let c=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,Ore.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New View",description:(o=t.description)!==null&&o!==void 0?o:"",entityLogicalName:c,queryType:(a=t.queryType)!==null&&a!==void 0?a:0,isDefault:(s=t.isDefault)!==null&&s!==void 0?s:!1,columns:t.columns&&t.columns.length>0?t.columns:[{name:`${c}id`,width:300,order:0}],filters:(l=t.filters)!==null&&l!==void 0?l:{type:"and",conditions:[],groups:[]},sort:(u=t.sort)!==null&&u!==void 0?u:[],...t.linkEntities&&t.linkEntities.length>0?{linkEntities:t.linkEntities}:{}}}assignMissingIds(t){return t}validate(t){let r=[],n=t;(0,en.childObjects)(n,"columns","","column",r),(0,en.childObjects)(n,"sort","","sort",r),(0,en.childObjects)(n,"linkEntities","","linkEntity",r),Pre(n.linkEntities,r);let i=n.filters;return i!=null&&((0,en.isJsonObject)(i)?Vb(i,"/filters",r):r.push((0,en.issue)("/filters","filters-must-be-object",`filters must be a JSON object, got ${typeof i}`))),r}};pl.ViewAdapter=Np;function Pre(e,t){Array.isArray(e)&&e.forEach((r,n)=>{if(!(0,en.isJsonObject)(r))return;for(let o of["name","from","to"]){let a=r[o];(typeof a!="string"||a.trim()==="")&&t.push((0,en.issue)(`/linkEntities/${n}/${o}`,"linkentity-needs-keys",`a join needs a non-empty '${o}' \u2014 'from'/'to' are what DEFINE the relationship, and a link without them is unresolvable. Got ${JSON.stringify(a)}.`))}let i=r.filters;i!=null&&((0,en.isJsonObject)(i)?Vb(i,`/linkEntities/${n}/filters`,t):t.push((0,en.issue)(`/linkEntities/${n}/filters`,"filters-must-be-object",`filters must be a JSON object, got ${typeof i}`)))})}function Vb(e,t,r){(0,en.childObjects)(e,"conditions",t,"condition",r),(0,en.childObjects)(e,"groups",t,"filterGroup",r).forEach(({node:i,index:o})=>Vb(i,`${t}/groups/${o}`,r))}function Rre(e){var t;let r=e.getElementsByTagName("entity")[0];return(t=r?.getAttribute("name"))!==null&&t!==void 0?t:""}function mk(e,t){var r;let n=_p(t),i=e.getElementsByTagName("cell"),o=[],a=0;for(let s=0;s<i.length;s+=1){let l=i[s];if(l.getAttribute("ishidden")==="1")continue;let u=l.getAttribute("name");if(!u)continue;let c=parseInt((r=l.getAttribute("width"))!==null&&r!==void 0?r:"",10),d={name:u,width:Number.isNaN(c)?pk:c,order:a},f=n.get(u);f&&(d.relatedEntity=f.linkKey,f.attributeName&&f.attributeName!==u&&(d.sourceAttribute=f.attributeName)),a+=1,o.push(d)}return o}function _p(e){let t=new Map,r=e.getElementsByTagName("link-entity");for(let n=0;n<r.length;n+=1){let i=r[n],o=i.getAttribute("name");if(!o)continue;let a=i.getElementsByTagName("attribute");for(let s=0;s<a.length;s+=1){let l=a[s],u=l.getAttribute("name")||"",c=l.getAttribute("alias")||u;c&&t.set(c,{linkKey:i.getAttribute("alias")||o,linkName:o,attributeName:u,link:i})}}return t}function hk(e){let t=e.getElementsByTagName("entity")[0];if(!t)return[];let r=[];for(let n of Wt(t,"link-entity")){let i=n.getAttribute("name"),o=n.getAttribute("from"),a=n.getAttribute("to");if(!i||!o||!a)continue;let s=n.getAttribute("alias"),l=n.getAttribute("link-type"),u=Wt(n,"filter").find(c=>!Tp(c));r.push({name:i,from:o,to:a,...s?{alias:s}:{},...l==="inner"||l==="outer"?{linkType:l}:{},...u?{filters:Gb(u)}:{}})}return r}function gk(e){var t;let r=e.getElementsByTagName("entity")[0];if(!r)return[];let n=[],i=r.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];if(a.nodeType===1&&a.tagName==="order"){let s=a.getAttribute("attribute");s&&n.push({attribute:s,descending:((t=a.getAttribute("descending"))!==null&&t!==void 0?t:"").toLowerCase()==="true",entityname:a.getAttribute("entityname")||""})}}return n}function yk(e){let t=e.getElementsByTagName("entity")[0],r={type:"and",conditions:[],groups:[]};if(!t)return r;let n=Wt(t,"filter").filter(i=>!Tp(i)).map(Gb);return n.length===0?r:n.length===1?n[0]:{type:"and",conditions:[],groups:n}}function Tp(e){if(e.getAttribute("isquickfindfields")==="1"||bk(e))return!0;if(Wt(e,"filter").length>0)return!1;let t=Wt(e,"condition");return t.length===0?!1:t.some(r=>r.getAttribute("isquickfindfields")==="1"||Wt(r,"value").length>0||kre(r))}function bk(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r];if(n.nodeType===1&&(n.tagName==="filter"?bk(n):n.tagName!=="condition"))return!0}return!1}var Lre=new Set(["attribute","operator","value","entityname","uiname","uitype"]);function kre(e){var t;let r=e.attributes;for(let n=0;n<r.length;n+=1){let i=(t=r[n])===null||t===void 0?void 0:t.name;if(i&&!Lre.has(i))return!0}return!1}function Gb(e){var t,r;let n=((t=e.getAttribute("type"))!==null&&t!==void 0?t:"and").toLowerCase()==="or"?"or":"and",i=[],o=[],a=e.childNodes;for(let s=0;s<a.length;s+=1){let l=a[s];if(l.nodeType===1)if(l.tagName==="condition"){if(l.getAttribute("isquickfindfields")==="1")continue;let u=l.getAttribute("attribute");if(!u)continue;let c={attribute:u,operator:(r=l.getAttribute("operator"))!==null&&r!==void 0?r:""};l.hasAttribute("value")&&(c.value=l.getAttribute("value")||"");let d=l.getAttribute("entityname")||"";d&&(c.entityname=d),i.push(c)}else l.tagName==="filter"&&o.push(Gb(l))}return{type:n,conditions:i,groups:o}}function Wt(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName===t&&r.push(o)}return r}var Wb=e=>{var t,r;return`${(t=e.relatedEntity)!==null&&t!==void 0?t:""}::${(r=e.sourceAttribute)!==null&&r!==void 0?r:e.name}`};function $re(e,t){let r=_p(e),n=new Map;for(let i of t){if(!i.relatedEntity)continue;let o=r.get(i.name);if(o){let a=Wb(i),s=n.get(a);s?s.push(o.link):n.set(a,[o.link])}}return n}function xre(e,t,r,n){if(!n||n.size===0)return;let i=new Set,o=t.getElementsByTagName("link-entity");for(let s=0;s<o.length;s+=1)i.add(o[s]);let a=r.filter(s=>{if(!s.relatedEntity)return!1;let l=n.get(Wb(s));return!!l&&l.some(u=>!i.has(u))});if(a.length!==0)throw new fk.ValidationError("view",e.id,a.map(s=>(0,en.issue)(`/columns/${r.indexOf(s)}`,"view-column-orphaned-by-join-removal",`column '${s.name}' came from a join this push REMOVED. Another join matching '${s.relatedEntity}' still exists, but nothing can say whether it is the one the column belonged to \u2014 re-attaching it there would silently change the data the column shows. Remove the column too, keep the join it came from, or point the column at the join you want by setting relatedEntity to that join's alias.`)))}function sk(e){var t,r;let n=Fre(e.columns),i=(t=e.sort)!==null&&t!==void 0?t:[],o=(r=e.filters)!==null&&r!==void 0?r:{type:"and",conditions:[],groups:[]};if(!lk(e.fetchBag)||!lk(e.layoutBag))return{fetchxml:Yre({...e,columns:n,sort:i,filters:o}),layoutxml:Qre({...e,columns:n},`${e.entityLogicalName}id`)};let a=new DOMParser().parseFromString("<root/>","text/xml"),s=uk(e.fetchBag,"fetch",a),l=uk(e.layoutBag,"grid",a),u=mk(l,s),c=!Sp(n,u),d=!Sp(i,gk(s)),f=!Sp(o,yk(s)),m=e.linkEntities,p=m!==void 0&&!Sp(m,hk(s)),h=p?$re(s,u):void 0;return p&&Hre(a,s,m),p&&(Jre(e,s,n,h),xre(e,s,n,h)),c?(ck(a,s,n,u),Vre(a,l,n)):p&&ck(a,s,n,u),d&&zre(a,s,i),f&&jre(a,s,o),{fetchxml:(0,Oa.serializeNode)(s),layoutxml:(0,Oa.serializeNode)(l)}}function Fre(e){return(e??[]).map((t,r)=>{var n,i;return{name:String(t.name).toLowerCase(),width:(n=t.width)!==null&&n!==void 0?n:pk,order:(i=t.order)!==null&&i!==void 0?i:r,...t.relatedEntity?{relatedEntity:t.relatedEntity}:{},...t.sourceAttribute?{sourceAttribute:String(t.sourceAttribute).toLowerCase()}:{}}})}function lk(e){return!!e&&(e.c.length>0||e.a.length>0)}function uk(e,t,r){let n={n:t,a:(0,Bb.mergeAttrs)(e.a,[]),c:(0,Bb.spliceChildren)(e.c,[])};return(0,Bb.rebuildRaw)(n,(0,Oa.domEngine)(r),null)}function ck(e,t,r,n){var i,o,a;let s=t.getElementsByTagName("entity")[0];if(!s)return;let l=p=>{var h,g;return`${(h=p.relatedEntity)!==null&&h!==void 0?h:""}:${p.name}:${(g=p.sourceAttribute)!==null&&g!==void 0?g:p.name}`},u=new Set(r.map(l)),c=new Set(r.map(p=>p.name)),d=_p(t);for(let p of n)u.has(l(p))||(Ure(s,p),p.relatedEntity&&c.has(p.name)&&Mre((i=d.get(p.name))===null||i===void 0?void 0:i.link,p.name));let f=_p(t),m=new Set(Wt(s,"attribute").map(p=>p.getAttribute("name")).filter(p=>!!p));for(let p of[...r].sort((h,g)=>h.order-g.order))if(p.relatedEntity){let h=f.get(p.name);if(h&&h.attributeName===((o=p.sourceAttribute)!==null&&o!==void 0?o:p.name)&&(h.linkKey===p.relatedEntity||h.linkName===p.relatedEntity||!wk(s,p.relatedEntity)))continue;let g=Bre(e,s,p.relatedEntity),b=e.createElement("attribute");vk(b,p),g.appendChild(b),f.set(p.name,{linkKey:p.relatedEntity,linkName:g.getAttribute("name")||p.relatedEntity,attributeName:(a=p.sourceAttribute)!==null&&a!==void 0?a:p.name,link:g})}else{if(m.has(p.name))continue;let h=e.createElement("attribute");h.setAttribute("name",p.name),qre(s,h),m.add(p.name)}}function vk(e,t){if(t.sourceAttribute&&t.sourceAttribute!==t.name){e.setAttribute("name",t.sourceAttribute),e.setAttribute("alias",t.name);return}e.setAttribute("name",t.name)}function Mre(e,t){if(e){for(let r of Wt(e,"attribute"))if((r.getAttribute("alias")||r.getAttribute("name"))===t){e.removeChild(r);return}}}function Ure(e,t){if(t.relatedEntity){for(let r of Wt(e,"link-entity"))if(!(r.getAttribute("alias")!==t.relatedEntity&&r.getAttribute("name")!==t.relatedEntity)){for(let n of Wt(r,"attribute"))if((n.getAttribute("alias")||n.getAttribute("name"))===t.name){r.removeChild(n);return}}return}for(let r of Wt(e,"attribute"))if(r.getAttribute("name")===t.name){e.removeChild(r);return}}function wk(e,t,r=!1){let n=o=>o.getAttribute("alias")===t||o.getAttribute("name")===t;for(let o of Wt(e,"link-entity"))if(n(o))return o;if(r)return;let i=e.getElementsByTagName("link-entity");for(let o=0;o<i.length;o+=1)if(n(i[o]))return i[o]}function Bre(e,t,r){let n=wk(t,r);if(n)return n;let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function qre(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 Vre(e,t,r){let n=t.getElementsByTagName("row")[0];if(!n)return;let i=[...r].sort((s,l)=>s.order-l.order),o=Gre(n);if(Wre(o,i)){for(let s=0;s<i.length;s+=1){let l=String(i[s].width);o[s].getAttribute("width")!==l&&o[s].setAttribute("width",l)}return}let a=new Map;for(let s of o){let l=s.getAttribute("name");l&&a.set(l,s),n.removeChild(s)}for(let s of i){let l=a.get(s.name);l||(l=e.createElement("cell"),l.setAttribute("name",s.name)),l.setAttribute("width",String(s.width)),n.appendChild(l)}}function Gre(e){return Wt(e,"cell").filter(t=>!!t.getAttribute("name")&&t.getAttribute("ishidden")!=="1")}function Wre(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 zre(e,t,r){let n=t.getElementsByTagName("entity")[0];if(!n)return;let i=(m,p)=>`${m.toLowerCase()}\0${p.toLowerCase()}`,o=new Map,a=new Map,s=(m,p,h)=>{let g=m.get(p);g?g.push(h):m.set(p,[h])},l=null;for(let m of Wt(n,"order")){let p=m.getAttribute("attribute")||"";p&&(l||(l=e.createTextNode(""),n.insertBefore(l,m)),s(o,i(m.getAttribute("entityname")||"",p),m),s(a,p.toLowerCase(),m),n.removeChild(m))}let u=new Set,c=(m,p)=>{let h=m.get(p);for(;h&&h.length>0;){let g=h.shift();if(!u.has(g))return u.add(g),g}},d=m=>{var p;let h=a.get(m.toLowerCase());if(!h)return;let g=h.filter(w=>!u.has(w)),b=(p=g.find(w=>!w.getAttribute("entityname")))!==null&&p!==void 0?p:g[0];return b&&u.add(b),b},f=r.map(m=>{let p=String(m.attribute);return m.entityname===void 0?{expression:m,element:void 0}:{expression:m,element:c(o,i(m.entityname,p))}});for(let m of f)m.expression.entityname===void 0&&(m.element=d(String(m.expression.attribute)));for(let{expression:m,element:p}of f){let h=p??e.createElement("order");h.setAttribute("attribute",m.attribute),h.setAttribute("descending",String(m.descending)),m.entityname?h.setAttribute("entityname",m.entityname):m.entityname===""&&h.removeAttribute("entityname"),n.insertBefore(h,l)}l&&n.removeChild(l)}function jre(e,t,r){let n=t.getElementsByTagName("entity")[0];if(n){for(let i of Wt(n,"filter"))Tp(i)||n.removeChild(i);(r.conditions.length>0||r.groups.length>0)&&n.appendChild(mc(e,r))}}function Sp(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Hre(e,t,r){var n;let i=t.getElementsByTagName("entity")[0];if(!i)return;let o=Wt(i,"link-entity").filter(p=>p.getAttribute("name")&&p.getAttribute("from")&&p.getAttribute("to")),a=(p,h)=>p.getAttribute(h)||"",s=new Array(r.length),l=new Set,u=p=>{r.forEach((h,g)=>{if(s[g])return;let b=o.filter(S=>!l.has(S)&&p(S,h));if(b.length!==1)return;let w=b[0];r.some((S,O)=>O!==g&&!s[O]&&p(w,S))||(s[g]=w,l.add(w))})};u((p,h)=>!!h.alias&&a(p,"name")===h.name&&a(p,"alias")===h.alias),u((p,h)=>a(p,"name")===h.name&&a(p,"from")===h.from&&a(p,"to")===h.to),u((p,h)=>a(p,"name")===h.name&&a(p,"from")===h.from),u((p,h)=>a(p,"name")===h.name&&a(p,"to")===h.to),u((p,h)=>a(p,"name")===h.name);let c=r.map((p,h)=>h).filter(p=>!s[p]),d=o.filter(p=>!l.has(p)),f=new Map;for(let p of d){let h=f.get(a(p,"name"));h?h.push(p):f.set(a(p,"name"),[p])}let m=new Map;for(let p of c){let h=m.get(r[p].name);h?h.push(p):m.set(r[p].name,[p])}for(let[p,h]of m){let g=(n=f.get(p))!==null&&n!==void 0?n:[];g.length===h.length&&h.forEach((b,w)=>{s[b]=g[w],l.add(g[w])})}r.forEach((p,h)=>{let g=s[h];if(g){dk(e,g,p);return}let b=e.createElement("link-entity");dk(e,b,p),i.appendChild(b)});for(let p of o)l.has(p)||i.removeChild(p)}var Kre=new Set(["inner","outer"]);function Jre(e,t,r,n){if(!t.getElementsByTagName("entity")[0])return;let o=new Set,a=t.getElementsByTagName("link-entity");for(let c=0;c<a.length;c+=1){let d=a[c],f=d.getAttribute("name"),m=d.getAttribute("alias");f&&o.add(f),m&&o.add(m)}let s=new Set;for(let c=0;c<a.length;c+=1)s.add(a[c]);let l=c=>{let d=n?.get(Wb(c));return!!d&&d.every(f=>s.has(f))},u=r.filter(c=>c.relatedEntity&&!o.has(c.relatedEntity)&&!l(c));if(u.length!==0)throw new fk.ValidationError("view",e.id,u.map(c=>{var d;let f=((d=e.linkEntities)!==null&&d!==void 0?d:[]).some(m=>m.name===c.relatedEntity||m.alias===c.relatedEntity);return(0,en.issue)(`/columns/${r.indexOf(c)}`,"view-column-dangling-link",`column '${c.name}' has relatedEntity '${c.relatedEntity}', but no matching join remains in linkEntities. `+(f?"Remove the column too, or keep the join.":"That join is NESTED (a join off a join), which the typed layer does not model, so it cannot be re-declared in linkEntities \u2014 it only survives while the join above it does. Remove the column, or restore the parent join this push replaced."))}))}function dk(e,t,r){t.setAttribute("name",r.name),t.setAttribute("from",r.from),t.setAttribute("to",r.to),r.alias?t.setAttribute("alias",r.alias):t.removeAttribute("alias"),r.linkType?t.setAttribute("link-type",r.linkType):Kre.has(t.getAttribute("link-type")||"")&&t.removeAttribute("link-type");let n=Wt(t,"filter").find(o=>!Tp(o)),i=r.filters&&(r.filters.conditions.length>0||r.filters.groups.length>0)?mc(e,r.filters):null;n&&i?t.replaceChild(i,n):n?t.removeChild(n):i&&t.appendChild(i)}function Yre(e){var t;let r=new DOMParser().parseFromString("<fetch/>","text/xml"),n=r.documentElement;n.setAttribute("version","1.0"),n.setAttribute("mapping","logical");let i=r.createElement("entity");i.setAttribute("name",e.entityLogicalName),n.appendChild(i);let o=new Map;for(let a of(t=e.linkEntities)!==null&&t!==void 0?t:[]){let s=r.createElement("link-entity");s.setAttribute("name",a.name),s.setAttribute("from",a.from),s.setAttribute("to",a.to),a.alias&&s.setAttribute("alias",a.alias),a.linkType&&s.setAttribute("link-type",a.linkType),a.filters&&(a.filters.conditions.length>0||a.filters.groups.length>0)&&s.appendChild(mc(r,a.filters)),i.appendChild(s);for(let l of[a.alias||a.name,a.name])o.has(l)||o.set(l,s)}for(let a of[...e.columns].sort((s,l)=>s.order-l.order)){let s=r.createElement("attribute");if(a.relatedEntity){vk(s,a);let l=o.get(a.relatedEntity);l||(l=r.createElement("link-entity"),l.setAttribute("name",a.relatedEntity),i.appendChild(l),o.set(a.relatedEntity,l)),l.appendChild(s)}else s.setAttribute("name",a.name),i.appendChild(s)}for(let a of e.sort){let s=r.createElement("order");s.setAttribute("attribute",a.attribute),s.setAttribute("descending",String(a.descending)),a.entityname&&s.setAttribute("entityname",a.entityname),i.appendChild(s)}return(e.filters.conditions.length>0||e.filters.groups.length>0)&&i.appendChild(mc(r,e.filters)),new XMLSerializer().serializeToString(r)}function mc(e,t){let r=e.createElement("filter");r.setAttribute("type",t.type);for(let n of t.conditions){let i=e.createElement("condition");i.setAttribute("attribute",n.attribute),i.setAttribute("operator",n.operator),n.entityname&&i.setAttribute("entityname",n.entityname),n.value!==void 0&&i.setAttribute("value",n.value),r.appendChild(i)}for(let n of t.groups)r.appendChild(mc(e,n));return r}function Qre(e,t){var r;let n=new DOMParser().parseFromString("<grid/>","text/xml"),i=n.documentElement,o=[...e.columns].sort((s,l)=>s.order-l.order);i.setAttribute("name","resultset"),i.setAttribute("jump",((r=o[0])===null||r===void 0?void 0:r.name)||t||`${e.entityLogicalName}id`),i.setAttribute("select","1"),i.setAttribute("icon","1"),i.setAttribute("preview","1");let a=n.createElement("row");a.setAttribute("name","result"),a.setAttribute("id",t||`${e.entityLogicalName}id`),i.appendChild(a);for(let s of o){let l=n.createElement("cell");l.setAttribute("name",s.name),l.setAttribute("width",String(s.width)),a.appendChild(l)}return new XMLSerializer().serializeToString(n)}function Xre(){return{adapter:new Np,api:Ire.viewApi,publish:(e,t,r)=>(0,ak.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,ak.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}pl.viewRegistration=Xre});function Dp(e,t){return e==="SetFieldValue"&&t!==void 0&&Zre.has(t.attributeType)&&(t.requiredLevel==="None"||t.requiredLevel==="Recommended")}var Zre,zb=k(()=>{"use strict";Zre=new Set(["Integer","Double","Decimal","Money","String","Memo","DateTime","Picklist","Lookup"])});function Ek(e){return e!=="Entity"&&e!=="AllForms"&&typeof e=="string"&&e.trim()!==""}function jb(e){return e==="AllForms"||Ek(e)?1:2}function Hb(e){return Ek(e)?e:null}function Ak(e,t){return{"@odata.type":"#Microsoft.Dynamics.CRM.workflow",name:e.name,description:e.description,workflowid:t,ondemand:!1,subprocess:!1,triggeroncreate:!1,triggerondelete:!1,category:ml.WorkflowCategory.BusinessRule,type:ml.WorkflowTypeCode.Definition,mode:1,scope:ml.WorkflowScope.Organization,primaryentity:e.entityLogicalName,iscrmuiworkflow:!0,processtriggerscope:jb(e.scope),processtriggerformid:Hb(e.scope)}}var ml,Sk=k(()=>{"use strict";ml=Ce(lo());});function Nk(e,t=0){return(zt[e[t+0]]+zt[e[t+1]]+zt[e[t+2]]+zt[e[t+3]]+"-"+zt[e[t+4]]+zt[e[t+5]]+"-"+zt[e[t+6]]+zt[e[t+7]]+"-"+zt[e[t+8]]+zt[e[t+9]]+"-"+zt[e[t+10]]+zt[e[t+11]]+zt[e[t+12]]+zt[e[t+13]]+zt[e[t+14]]+zt[e[t+15]]).toLowerCase()}var zt,_k=k(()=>{zt=[];for(let e=0;e<256;++e)zt.push((e+256).toString(16).slice(1))});function Kb(){return Ip>Op.length-16&&((0,Tk.randomFillSync)(Op),Ip=0),Op.slice(Ip,Ip+=16)}var Tk,Op,Ip,Dk=k(()=>{Tk=require("crypto"),Op=new Uint8Array(256),Ip=Op.length});var Ik,Jb,Ok=k(()=>{Ik=require("crypto"),Jb={randomUUID:Ik.randomUUID}});function ene(e,t,r){if(Jb.randomUUID&&!t&&!e)return Jb.randomUUID();e=e||{};let n=e.random??e.rng?.()??Kb();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 Nk(n)}var br,Pk=k(()=>{Ok();Dk();_k();br=ene});var Yb=k(()=>{Pk()});var Rk=k(()=>{"use strict";});function Lk(e){return e!=null&&tne.has(e)}function Pp(e){if(e==null)return!1;let t=e.trim();if(!/^[+-]?\d+$/.test(t))return!1;let r=Number(t);return Number.isInteger(r)&&r>=-2147483648&&r<=2147483647}var tne,Qb=k(()=>{"use strict";tne=new Set(["Picklist","State","Status"])});var Rp=v(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.WorkflowConditionOperator=wn.WorkflowAttributeType=wn.SystemStep=wn.FieldRequiredLevelTypes=wn.AttributeDateTimeBehavior=void 0;wn.AttributeDateTimeBehavior={None:0,Dynamic:1,DateOnly:2,StaticTimeZoneInvariant:3,UserLocal:4};wn.FieldRequiredLevelTypes={None:"0",Required:"1",Recommended:"2"};wn.SystemStep={IdentifyContact:"IdentifyContact",IdentifyAccount:"IdentifyAccount",IdentifyCustomer:"IdentifyCustomer",IdentifyCase:"IdentifyCase",Solution:"Solution",Resolve:"Resolve"};wn.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"};wn.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 Lp(e){return e!=null&&$k.includes(e)}function Xb(e){return e===ae.WorkflowAttributeType.Integer}function Zb(e,t){return t===ae.WorkflowConditionOperator.Equal||t===ae.WorkflowConditionOperator.NotEqual?e:rne.includes(t)?$k.includes(e)||e===ae.WorkflowAttributeType.DateTime?e:ae.WorkflowAttributeType.String:t===ae.WorkflowConditionOperator.On||t===ae.WorkflowConditionOperator.NotOn?e===ae.WorkflowAttributeType.DateTime?e:ae.WorkflowAttributeType.String:ae.WorkflowAttributeType.String}function xk(e){let t=e.leftWorkflowType??e.valueWorkflowType??ae.WorkflowAttributeType.String,r=hc[e.operator]??ae.WorkflowConditionOperator.Equal;return Zb(t,r)}function Fk(e,t){let r=e.trim(),i=(r.startsWith("+")||r.startsWith("-")?r.slice(1):r).split(".");if(i.length>2)return!1;let[o,a=""]=i;return o.length===0&&a.length===0||!kk.test(o)||!kk.test(a)||o.length>1&&o.startsWith("0")||o.length>nne?!1:t!==ae.WorkflowAttributeType.Integer||i.length===1}var ae,hc,$k,rne,kk,nne,ev=k(()=>{"use strict";ae=Ce(Rp());hc={Equals:ae.WorkflowConditionOperator.Equal,DoesNotEqual:ae.WorkflowConditionOperator.NotEqual,IsGreaterThan:ae.WorkflowConditionOperator.GreaterThan,IsLessThan:ae.WorkflowConditionOperator.LessThan,IsGreaterThanEqualTo:ae.WorkflowConditionOperator.GreaterThanOrEqual,IsLessThanEqualTo:ae.WorkflowConditionOperator.LessThanOrEqual,Contains:ae.WorkflowConditionOperator.Contains,DoesNotContain:ae.WorkflowConditionOperator.DoesNotContain,BeginsWith:ae.WorkflowConditionOperator.BeginsWith,DoesNotBeginWith:ae.WorkflowConditionOperator.DoesNotBeginWith,EndsWith:ae.WorkflowConditionOperator.EndsWith,DoesNotEndWith:ae.WorkflowConditionOperator.DoesNotEndWith,On:ae.WorkflowConditionOperator.On,NotOn:ae.WorkflowConditionOperator.NotOn,ContainsData:ae.WorkflowConditionOperator.NotNull,DoesNotContainData:ae.WorkflowConditionOperator.IsNull},$k=[ae.WorkflowAttributeType.Decimal,ae.WorkflowAttributeType.Float,ae.WorkflowAttributeType.Integer,ae.WorkflowAttributeType.Money],rne=[ae.WorkflowConditionOperator.GreaterThan,ae.WorkflowConditionOperator.GreaterThanOrEqual,ae.WorkflowConditionOperator.LessThan,ae.WorkflowConditionOperator.LessThanOrEqual];kk=/^\d*$/,nne=28});var Mk=k(()=>{"use strict";});function qn(e){return!ine.has(e)}function tv(e){return e==="Equals"||e==="DoesNotEqual"}function kp(e){return Bk.has(e)?one:cne.has(e)?ane:qk.has(e)?sne:fne.has(e)?une:lne}function Vk(e){return kp(e)[0]}function Gk(e,t){return kp(t).includes(e)}function Uk(e){return Bk.has(e)?"string":e==="Money"?"money":e==="Integer"||e==="BigInt"?"integer":e==="Decimal"||e==="Double"?"decimal":qk.has(e)?"date":dne.has(e)?"boolean":"other"}function $p(e,t){let r=Uk(e),n=Uk(t);return r==="other"||n==="other"?e===t:r===n}var ine,one,ane,sne,lne,une,Bk,cne,qk,dne,fne,xp=k(()=>{"use strict";Mk();ine=new Set(["ContainsData","DoesNotContainData"]);one=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],ane=["Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],sne=["On","NotOn","Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],lne=["Equals","DoesNotEqual","ContainsData","DoesNotContainData"],une=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],Bk=new Set(["String","Memo","EntityName"]),cne=new Set(["Integer","BigInt","Money","Decimal","Double"]),qk=new Set(["DateTime"]),dne=new Set(["Boolean"]),fne=new Set(["Lookup","Owner","Customer"])});function Hk(e){switch(e){case"Boolean":return Me.WorkflowAttributeType.Boolean;case"Customer":return Me.WorkflowAttributeType.Customer;case"DateTime":return Me.WorkflowAttributeType.DateTime;case"Decimal":return Me.WorkflowAttributeType.Decimal;case"Double":return Me.WorkflowAttributeType.Float;case"Integer":return Me.WorkflowAttributeType.Integer;case"Lookup":return Me.WorkflowAttributeType.Lookup;case"Money":return Me.WorkflowAttributeType.Money;case"Owner":return Me.WorkflowAttributeType.Owner;case"Picklist":return Me.WorkflowAttributeType.Picklist;case"State":return Me.WorkflowAttributeType.State;case"Status":return Me.WorkflowAttributeType.Status;case"Uniqueidentifier":case"UniqueIdentifier":return Me.WorkflowAttributeType.UniqueIdentifier;case"BigInt":return Me.WorkflowAttributeType.BigType;default:return Me.WorkflowAttributeType.String}}function e$(e){return e&&e!==Me.WorkflowAttributeType.String?e:void 0}function hne(e){return{__class:Zk,parameterName:"primaryEntity",entityName:e}}function Wk(e){return{__class:nv,type:rv,typeSet:!1,behavior:Me.AttributeDateTimeBehavior.None,method:Kk,parameters:[e]}}function zk(e,t,r=Me.WorkflowAttributeType.String){return{__class:Yk,type:r,behavior:Me.AttributeDateTimeBehavior.None,typeSet:!1,entity:hne(t),attributeName:e}}function gne(e,t=Me.WorkflowAttributeType.String){return{__class:Qk,type:t,behavior:Me.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function yne(e){return{__class:Xk,type:rv,typeSet:!1,behavior:Me.AttributeDateTimeBehavior.None,days:e,hours:"0",minutes:"0",months:"0",years:"0"}}function t$(e,t){let r=pne[e.operator],n=Wk(zk(e.leftField,t,e.leftWorkflowType)),i;e.dateArithmetic?i=yne(e.right.value??"0"):e.right.kind==="field"?i=zk(e.right.field??"",t,e.right.workflowType):i=gne(e.right.value??"",e.right.workflowType??e.leftWorkflowType);let o=Wk(i);return{__class:nv,type:rv,typeSet:!1,behavior:Me.AttributeDateTimeBehavior.None,method:Jk,parameters:[r,n,o]}}function r$(e){return typeof e=="object"&&e.__class===nv}function bne(e){return typeof e=="object"&&e.__class===Xk}function Fp(e){return r$(e)&&e.method===Kk&&e.parameters.length>0?Fp(e.parameters[0]):e}function jk(e){if(typeof e!="object"||e.__class!==Yk)return null;let t=e.entity;if(t&&t.__class&&t.__class!==Zk)return null;let r=e.attributeName;return r?{field:r,workflowType:e$(e.type)}:null}function n$(e){if(!e)return null;let t=Fp(e);if(!r$(t)||t.method!==Jk||t.parameters.length!==3)return null;let r=t.parameters[0],n=mne[String(r)];if(!n)return null;let i=jk(Fp(t.parameters[1]));if(!i)return null;let o=Fp(t.parameters[2]);if(bne(o))return n!=="+"&&n!=="-"?null:{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:String(o.days??"")},dateArithmetic:!0};let a=jk(o);if(a)return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"field",field:a.field,workflowType:a.workflowType}};if(typeof o=="object"&&o.__class===Qk){let s=o.primitiveValue;return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:s!=null?String(s):"",workflowType:e$(o.type)}}}return null}function ov(e){let t=(e??"").trim();if(!/^\d+$/.test(t))return!1;let r=Number(t);return Number.isSafeInteger(r)&&r>=iv&&r<=hl}function Pa(e){if(!e||!e.leftField)return"incomplete";if(e.right.kind==="field")return e.right.field&&e.right.field.trim()?null:"incomplete";let t=e.right.value;return!t||!t.trim()?"incomplete":e.dateArithmetic&&!ov(t)?"invalidDayCount":null}function gl(e){return Pa(e)===null}var Me,Kk,Jk,rv,Yk,Qk,nv,Xk,Zk,pne,mne,iv,hl,gc=k(()=>{"use strict";Me=Ce(Rp());xp();Kk="0",Jk="3",rv="0",Yk="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",Qk="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",nv="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",Xk="TimeSpanExpression:#Microsoft.Crm.Workflow.Expressions",Zk="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions";pne={"+":0,"-":1,"*":2,"/":3},mne={0:"+",1:"-",2:"*",3:"/"};iv=0,hl=2147483647});function wne(e){return e.startsWith("__")&&!vne.has(e)}function Cne(e){let t=Object.create(null);return Object.keys(e).forEach(r=>{wne(r)&&(t[r]=e[r])}),Object.keys(t).length>0?t:void 0}function y$(e){return e.__class==="BinaryExpression:#Microsoft.Crm.Workflow.Expressions"}function La(e){return e.__class==="UnaryExpression:#Microsoft.Crm.Workflow.Expressions"}function Mp(e){return y$(e)||La(e)}function Ene(e){return e.__class==="ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel"}function yc(){return{list:[]}}function av(e,t,r){return e&&e.list.length>0?{list:[{...e.list[0],description:t},...e.list.slice(1)]}:{list:[{labelId:br(),languageCode:r,description:t}]}}function lv(e){return{__class:"PrimaryEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:"primaryEntity",entityName:e}}function Vp(e,t,r,n=z.AttributeDateTimeBehavior.None){return{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:n,typeSet:!1,entity:lv(t),attributeName:e}}function Ra(e,t,r=z.AttributeDateTimeBehavior.None){return{__class:"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",type:t,behavior:r,typeSet:!1,primitiveValue:e}}function Nne(e){return e.bpfField==="StageCategory"?e.stageType==="SelectedStage"?w$:v$:b$}function C$(e){return e.bpfField==="StageCategory"?z.WorkflowAttributeType.BpfStageCategory:z.WorkflowAttributeType.BpfProcess}function _ne(e,t){let r=C$(e),n=e.bpfField==="StageCategory"?{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,entity:{__class:"RelatedEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:`related_${o$}_${i$}`,entityName:i$,relatedAttributeName:o$},attributeName:Sne}:Vp(Ane,t,r);return{__class:"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,method:dv,parameters:[Nne(e),n]}}function E$(e){let t=e;if(t.__class!=="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"||String(t.method)!==dv)return null;let r=(t.parameters??[])[0];if(typeof r!="string")return null;let n=r.replace(/^"+|"+$/g,"");return n===v$?{bpfField:"StageCategory",stageType:"ActiveStage"}:n===w$?{bpfField:"StageCategory",stageType:"SelectedStage"}:n===b$?{bpfField:"ProcessName"}:null}function Up(e){if(!e)return!1;let t=e;if(t.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"&&String(t.method)===dv){let r=(t.parameters??[])[0];if(typeof r=="string"&&Tne.has(r.replace(/^"+|"+$/g,"")))return!0}return La(e)?Up(e.operand):y$(e)?Up(e.left)||(e.right??[]).some(Up):!1}function A$(e){if(e?.__class!=="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions")return!1;let t=e.entity;return t==null||t.__class==="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions"}function Dne(e){if(e?.__class!=="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions")return!1;let t=e.primitiveValue;return t===!0||typeof t=="string"&&t.toLowerCase()==="true"}function a$(e){if(!e)return!1;switch(e.__class){case"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions":return A$(e);case"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions":return e.primitiveValue!=null||e.type!==void 0;case"LookupExpression:#Microsoft.Crm.Workflow.Expressions":case"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions":return!0;default:return!1}}function Ine(e){let t=cv[e.conditionOperatoroperator];if(!t)return!1;let r=t==="ContainsData"||t==="DoesNotContainData";if(La(e))return r&&s$(e.operand,!0);let n=e.right??[];return n.length!==(r?0:1)?!1:s$(e.left,r,n[0])}function s$(e,t,r){return E$(e)||A$(e)?t||a$(r):!1}function uv(e){if(!e||!Mp(e))return!1;let t=e.conditionOperatoroperator;if(!La(e)&&(t===z.WorkflowConditionOperator.LogicalAnd||t===z.WorkflowConditionOperator.LogicalOr)){let r=e.right??[];return r.length>0&&uv(e.left)&&r.every(uv)}return Ine(e)}function l$(e){return!e||Dne(e)?!1:Up(e)||!uv(e)}function S$(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:Ra(e.id.replace(/[{}]/g,""),z.WorkflowAttributeType.UniqueIdentifier)}}function Pne(e){return e===z.WorkflowAttributeType.DateTime?z.AttributeDateTimeBehavior.DateOnly:z.AttributeDateTimeBehavior.None}function Rne(e,t){if(t!==z.WorkflowAttributeType.DateTime)return z.AttributeDateTimeBehavior.None;let r=e.leftDateTimeBehavior;return r!==void 0&&r!==z.AttributeDateTimeBehavior.None?r:Pne(t)}function Lne(e,t,r){if(t!==z.WorkflowAttributeType.DateTime)return z.AttributeDateTimeBehavior.None;let n=e.valueFieldDateTimeBehavior;return n!==void 0&&n!==z.AttributeDateTimeBehavior.None?n:r}function $ne(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return"1";if(t==="false"||t==="0")return"0"}function Gne(e){let t=Vne.exec(e);if(t)return`${t[1]}T${t[2]}`;let r=qne.exec(e);if(!r)return;let[,n,i,o,a,s,l]=r,u=Bne.indexOf(i.toLowerCase());if(u<0)return;let c=String(u+1).padStart(2,"0");return`${o}-${c}-${n}T${a}:${s}:${l}`}function Wne(e){let t=Gne(e.trim());return t!==void 0&&N$(t)?t:e}function N$(e){let t=e.trim(),r=t.indexOf("T")>=0?"T":" ",n=t.indexOf(r),i=n>=0?t.slice(0,n):t,o=n>=0?t.slice(n+1):"";if(!xne.test(i)||o.length>0&&!Fne.test(o)&&!Mne.test(o)&&!Une.test(o))return!1;let[a,s,l]=i.split("-"),u=new Date(`${a}-${s}-${l}T00:00:00Z`);return!Number.isNaN(u.getTime())&&u.getUTCFullYear()===Number(a)&&u.getUTCMonth()+1===Number(s)&&u.getUTCDate()===Number(l)}function zne(e,t){let r={value:e,type:z.WorkflowAttributeType.String};if(t===z.WorkflowAttributeType.String||kne.includes(t)||e.trim().length===0)return r;if(t===z.WorkflowAttributeType.Boolean){let n=$ne(e);return n==null?r:{value:n,type:t}}return One.includes(t)?Pp(e)?{value:e.trim(),type:t}:r:Lp(t)?{value:e.trim(),type:t}:t===z.WorkflowAttributeType.DateTime&&N$(e)?{value:e.trim(),type:t}:r}function u$(e){return e==="ContainsData"||e==="DoesNotContainData"}function c$(e){return jne.has(e)}function d$(e,t){return{__class:"UnaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:t,operand:e}}function f$(e,t){let r=e.leftWorkflowType??e.valueWorkflowType??z.WorkflowAttributeType.String,n=hc[e.operator]??z.WorkflowConditionOperator.Equal,i=Rne(e,r),o=Zb(r,n);if(e.source==="BusinessProcess"){let l=_ne(e,t);if(u$(e.operator))return d$(l,n);let u=C$(e);return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:l,right:[Ra(e.value??"",u)]}}let a=Vp(e.field,t,r,i);if(u$(e.operator))return d$(a,n);let s;if(e.valueType==="Field"&&e.valueField){let l=c$(o)&&c$(e.valueFieldWorkflowType??"")?e.valueFieldWorkflowType:o;s=[Vp(e.valueField,t,l,Lne(e,l,i))]}else if(e.valueType==="Lookup"){if(!e.lookupValue)throw new Error("Lookup condition is missing its record value.");s=[S$(e.lookupValue)]}else if(e.valueType==="Clear")s=[Ra(null,z.WorkflowAttributeType.String,i)];else if(e.valueType==="Expression")s=[qp(e.valueType,e.value,e.valueField,t,e.expression,e.rawExpression)];else{let l=zne(e.value??"",o);s=[Ra(l.value,l.type,i)]}return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:a,right:s}}function Hne(){return Ra(!0,z.WorkflowAttributeType.Boolean)}function Kne(e,t,r){if(e.length===0)return null;let n=f$(e[0],r);for(let i=1;i<e.length;i++){let o=e[i].connector??t;n={__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:o==="AND"?z.WorkflowConditionOperator.LogicalAnd:z.WorkflowConditionOperator.LogicalOr,left:n,right:[f$(e[i],r)]}}return n}function Bp(e){if(!e)return{valueType:"Value",value:""};if(e.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions")return{valueType:"Field",valueField:e.attributeName,valueFieldWorkflowType:e.type};if(e.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"){if(e.primitiveValue==null)return{valueType:"Clear",valueWorkflowType:e.type};let t=String(e.primitiveValue);if(e.type===z.WorkflowAttributeType.Boolean){let r=t.trim().toLowerCase();if(r==="1"||r==="true")return{valueType:"Value",value:"true",valueWorkflowType:e.type};if(r==="0"||r==="false")return{valueType:"Value",value:"false",valueWorkflowType:e.type}}return e.type===z.WorkflowAttributeType.DateTime?{valueType:"Value",value:Wne(t),valueWorkflowType:e.type}:{valueType:"Value",value:t,valueWorkflowType:e.type}}if(e.__class==="LookupExpression:#Microsoft.Crm.Workflow.Expressions"){let t=e.staticValue,r=typeof t=="object"&&t?.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"?t.primitiveValue:t;return{valueType:"Lookup",lookupValue:{entityType:e.entityType,id:String(r??""),label:e.label,...e.type!==z.WorkflowAttributeType.Lookup?{workflowType:e.type}:{}}}}if(e.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"){let t=n$(e);return t?{valueType:"Expression",expression:t}:{valueType:"Expression",rawExpression:e}}return{valueType:"Value",value:""}}function Jne(e){let t=cv[e.conditionOperatoroperator]??"Equals",r=t==="ContainsData"||t==="DoesNotContainData",n=La(e)?e.operand:e.left,i=La(e)?[]:e.right??[],o=E$(n);if(o){let g=i[0];return{id:br(),field:"",fieldDisplayName:"",source:"BusinessProcess",bpfField:o.bpfField,...o.stageType?{stageType:o.stageType}:{},operator:t,valueType:"Value",value:g?.primitiveValue!=null&&!r?String(g.primitiveValue):""}}let a=n.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",s=n.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"?n.attributeName:"",l=a?n.type:void 0,u=r?{valueType:"Value"}:Bp(i[0]),c=l,d=a&&n.type===z.WorkflowAttributeType.DateTime&&n.behavior!==z.AttributeDateTimeBehavior.None?n.behavior:void 0,f=u.valueWorkflowType??l,m=r?void 0:i[0],h=m?.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"&&m.type===z.WorkflowAttributeType.DateTime&&m.behavior!==z.AttributeDateTimeBehavior.None?m.behavior:void 0;return{id:br(),field:s,fieldDisplayName:s,operator:t,...u,...f?{valueWorkflowType:f}:{},...c?{leftWorkflowType:c}:{},...d!==void 0?{leftDateTimeBehavior:d}:{},...h!==void 0?{valueFieldDateTimeBehavior:h}:{}}}function p$(e){if(!e||!Mp(e))return{clauses:[],logic:"AND"};let t=[],r=(o,a)=>{let s=o.conditionOperatoroperator;if(La(o)||s!==z.WorkflowConditionOperator.LogicalAnd&&s!==z.WorkflowConditionOperator.LogicalOr){t.push({...Jne(o),...a?{connector:a}:{}});return}let l=s===z.WorkflowConditionOperator.LogicalAnd?"AND":"OR";Mp(o.left)&&r(o.left,a),(o.right??[]).filter(Mp).forEach(u=>r(u,l))};r(e,void 0);let i=t.slice(1).map(o=>o.connector??"AND")[0]??"AND";return{clauses:t,logic:i}}function qp(e,t,r,n,i,o,a,s){if(e==="Field"&&r)return Vp(r,n,z.WorkflowAttributeType.String);if(e==="Expression"){if(i)return t$(i,n);if(o!=null)return o}return e==="Lookup"&&a?S$(a):e==="Clear"?Ra(null,s??z.WorkflowAttributeType.String):Ra(t??"",z.WorkflowAttributeType.String)}function sv(e,t){return{propertyName:e,propertyValueExpr:t}}function yl(e){return`Step_${e.value++}`}function Cn(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 m$(e,t,r){return e&&!r.used.has(e)?(r.used.add(e),e):Cn(t,r)}function Yne(e){return e===g$.StateCode.Activated?"Active":"Draft"}function Qne(e){let t={},r=e;typeof r.ismanaged=="boolean"&&(t.isManaged=r.ismanaged);let n=r.iscustomizable;return typeof n=="boolean"?t.isCustomizable=n:n!==null&&typeof n=="object"&&typeof n.Value=="boolean"&&(t.isCustomizable=n.Value),t}function Xne(e,t){let r=e.processtriggerscope,n=e.processtriggerformid;return r===1?n&&n.trim()!==""?n:"AllForms":r===2?"Entity":t??"Entity"}function _$(e,t=1033){return new bl({languageCode:t}).serialize(e)}function T$(e){return new bl().deserialize(e)}var g$,z,vne,cv,dv,b$,v$,w$,Ane,Sne,i$,o$,Tne,One,kne,xne,Fne,Mne,Une,Bne,qne,Vne,jne,fv,bl,pv=k(()=>{"use strict";Yb();g$=Ce(lo());Rk();Qb();ev();gc();z=Ce(Rp());vne=new Set(["__class"]);cv={};for(let e of Object.keys(hc))cv[hc[e]]=e;dv="23",b$="BpfProcess",v$="ActiveStageCategory",w$="SelectedStageCategory",Ane="processid",Sne="stagecategory",i$="processstage",o$="stageid";Tne=new Set(["ActiveStage","SelectedStage","Stage"]);One=[z.WorkflowAttributeType.Picklist,z.WorkflowAttributeType.State,z.WorkflowAttributeType.Status];kne=[z.WorkflowAttributeType.Lookup,z.WorkflowAttributeType.Customer,z.WorkflowAttributeType.Owner];xne=/^\d{4}-\d{2}-\d{2}$/,Fne=/^\d{2}:\d{2}$/,Mne=/^\d{2}:\d{2}:\d{2}$/,Une=/^\d{2}:\d{2}:\d{2}\.\d{1,7}$/,Bne=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],qne=/^[A-Za-z]{3}, (\d{2}) ([A-Za-z]{3}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/,Vne=/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}:\d{2}\.\d{1,7}|\d{2}:\d{2}:\d{2}|\d{2}:\d{2})Z$/;jne=new Set([z.WorkflowAttributeType.Lookup,z.WorkflowAttributeType.Owner,z.WorkflowAttributeType.Customer]);fv={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"};bl=class{resolveLabel;languageCode;entityName="";stepCounter={value:0};idCounter={counts:{},used:new Set};constructor(t={}){this.resolveLabel=t.resolveLabel??(r=>fv[r]),this.languageCode=t.languageCode??1033}label(t){return this.resolveLabel(t)}serialize(t){let r=t.wfomRoot;this.entityName=t.entityLogicalName,this.stepCounter={value:r?Number(r.nextStepIndex):1},this.idCounter={counts:{},used:new Set};let n=t.scope!=="Entity"&&t.scope!=="AllForms"?t.scope:null,i=t.rootCondition?[this.serializeConditionNode(t.rootCondition)]:[],o={...r?.reservedProperties??{},__class:"WorkflowStep:#Microsoft.Crm.Workflow.ObjectModel",id:r?.id??t.ruleId??br(),name:r?.name??"Step_0",description:r!==void 0?r.description:t.description||null,stepLabels:yc(),argumentsArray:[],primaryEntityName:r?.primaryEntityName??this.entityName,nextStepIndex:String(this.stepCounter.value),isCrmUIWorkflow:!0,category:r?.category??"2",businessProcessType:r?.businessProcessType??"0",mode:r?.mode??"0",title:r?.title??t.name,formId:n,workflowEntityId:r?.workflowEntityId??t.ruleId??"",variables:r?.variables??[],inputs:r?.inputs??[],steps:{list:i}};return JSON.stringify(o)}makeApplyActionStep(t){return{__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",id:Cn("SetAttributeValueStep",this.idCounter),description:t.displayName||"New Action",name:t.stepName??yl(this.stepCounter),stepLabels:{list:[]},specification:sv(t.field,qp(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType)),entity:lv(this.entityName)}}makeRecommendationActionStep(t,r,n){let i=r.map(l=>this.makeApplyActionStep(l)),o=t??"",a=n?.stepLabels,s=av(a,o,this.languageCode);return{__class:"ActionStep:#Microsoft.Crm.Workflow.ObjectModel",id:m$(n?.id,"ActionStep",this.idCounter),name:n?.name??yl(this.stepCounter),description:n?.description??"Action step",stepLabels:s,steps:{list:i},actionId:null,actionType:n?.actionType??"4",processId:n?.processId??br(),uniqueName:n?.uniqueName??`id_${br().replace(/-/g,"")}ActionStep`}}serializeAction(t){let r=lv(this.entityName),n=t.stepName??yl(this.stepCounter),i=t.stepLabels??yc(),o={name:n,stepLabels:i,description:t.displayName},a=t.type;switch(a){case"SetFieldValue":return{...o,id:Cn("SetAttributeValueStep",this.idCounter),__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:sv(t.field,qp(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"SetDefaultValue":return{...o,id:Cn("SetDefaultValueStep",this.idCounter),__class:"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:sv(t.field,qp(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"LockUnlock":return{...o,id:Cn("SetDisplayModeStep",this.idCounter),__class:"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isReadOnly:t.lock,entity:r};case"SetBusinessRequired":return{...o,id:Cn("SetFieldRequiredLevelStep",this.idCounter),__class:"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",requiredLevel:t.required?z.FieldRequiredLevelTypes.Required:z.FieldRequiredLevelTypes.None,entity:r};case"SetVisibility":return{...o,id:Cn("SetVisibilityStep",this.idCounter),__class:"SetVisibilityStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isVisible:t.visible,entity:r};case"ShowErrorMessage":{let s=t.errorMessage||t.displayName,l=av(t.stepLabels,s,this.languageCode);return{...o,id:Cn("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=av(t.stepLabels,s,this.languageCode),u={list:[this.makeRecommendationActionStep(t.acceptanceText,t.applyActions??[],t.recommendationActionStepMeta)]};return{...o,id:Cn("SetMessageStep",this.idCounter),__class:"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel",stepLabels:l,description:t.recommendationTitle||t.displayName,controlId:t.field,entity:r,level:"RECOMMENDATION",actionSteps:u}}default:throw new Error(`Unsupported action type: ${a}`)}}serializeConditionNode(t){let r=t.stepName??yl(this.stepCounter),n=Cn("ConditionStep",this.idCounter),i=[],o=t,a=!0;for(;o;){let s=o.rawConditionExpression??Kne(o.clauses,o.logic,this.entityName),l=a?o.branchName??yl(this.stepCounter):yl(this.stepCounter),c={__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:a?m$(o.branchId,"ConditionBranchStep",this.idCounter):Cn("ConditionBranchStep",this.idCounter),name:l,description:o.displayName,stepLabels:yc(),conditionExpression:s??(a?Hne():void 0),steps:{list:o.trueBranch.map(f=>this.serializeBranchItem(f))}};i.push(c);let d=o.falseBranch;if(d.length===1&&d[0].kind==="condition"){o=d[0],a=!1;continue}d.length>0&&i.push(this.makeTerminalElseBranch(d)),o=void 0}return{__class:"ConditionStep:#Microsoft.Crm.Workflow.ObjectModel",id:n,name:r,description:"",stepLabels:yc(),containsElsebranch:i.length>1,steps:{list:i}}}makeTerminalElseBranch(t){return{__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:Cn("ConditionBranchStep",this.idCounter),name:"Else",description:null,stepLabels:yc(),conditionExpression:void 0,steps:{list:t.map(r=>this.serializeBranchItem(r))}}}serializeBranchItem(t){return t.kind==="condition"?this.serializeConditionNode(t):this.serializeAction(t)}deserialize(t){let r=t,n=null,i;if(t.wfomJson)try{let o=JSON.parse(t.wfomJson);i={id:o.id==="WorkflowStep0"||!o.id?t.workflowid??br():o.id,name:o.name,description:o.description,nextStepIndex:o.nextStepIndex,category:o.category==="0"||o.category===0?"2":o.category,businessProcessType:o.businessProcessType,mode:o.mode,title:o.title||t.name||"",primaryEntityName:o.primaryEntityName==="1"||!o.primaryEntityName?t.primaryentity??"":o.primaryEntityName,workflowEntityId:o.workflowEntityId==="00000000-0000-0000-0000-000000000000"||!o.workflowEntityId?t.workflowid??"":o.workflowEntityId,formId:o.formId,variables:o.variables,inputs:o.inputs,reservedProperties:Cne(o)};let s=(o.steps?.list??[]).find(l=>l.__class==="ConditionStep:#Microsoft.Crm.Workflow.ObjectModel");s&&(n=this.deserializeConditionStep(s))}catch{}return{ruleId:t.workflowid??null,name:t.name??"",description:t.description??"",entityLogicalName:t.primaryentity??"",scope:Xne(r,i?.formId),status:Yne(t.statecode),rootCondition:n,wfomRoot:i,...Qne(t)}}deserializeConditionStep(t){let r=(t.steps?.list??[]).filter(Ene);return this.buildConditionNodeFromBranches(r,t,!0)}buildConditionNodeFromBranches(t,r,n){let[i,...o]=t,{clauses:a,logic:s}=p$(i?.conditionExpression),l=this.deserializeBranch(i?.steps?.list??[]),u=this.deserializeElseChain(o,r),c=i?.description||i?.name||r.description||r.name||this.label("condition");return{kind:"condition",id:(n?r.id:i?.id)??br(),displayName:c,clauses:a,logic:s,trueBranch:l,falseBranch:u,isCollapsed:!1,stepName:n?r.name:void 0,branchId:n?i?.id:void 0,branchName:n?i?.name:void 0,...l$(i?.conditionExpression)?{rawConditionExpression:i?.conditionExpression}:{}}}deserializeElseChain(t,r){if(t.length===0)return[];let[n]=t,{clauses:i}=p$(n.conditionExpression);return i.length===0&&!l$(n.conditionExpression)?this.deserializeBranch(n.steps?.list??[]):[this.buildConditionNodeFromBranches(t,r,!1)]}deserializeBranch(t){return t.map(r=>r.__class==="ConditionStep:#Microsoft.Crm.Workflow.ObjectModel"?this.deserializeConditionStep(r):this.deserializeAction(r)).filter(r=>r!==null)}parseRecommendationApplyActions(t){let n=(t?.list??[])[0];if(!n)return{applyActions:[]};let i={id:n.id,name:n.name,description:n.description??void 0,stepLabels:n.stepLabels,processId:n.processId,uniqueName:n.uniqueName,actionType:n.actionType},o=n.stepLabels?.list,a=o&&o.length>0?o[0].description??"":"";return{applyActions:(n.steps?.list??[]).filter(l=>l.__class==="SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel").map(l=>{let u=l.specification;return{id:l.id||br(),field:u?.propertyName??"",stepName:l.name??void 0,displayName:l.description??void 0,...Bp(u?.propertyValueExpr)}}),meta:i,acceptanceText:a}}deserializeAction(t){switch(t.__class){case"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=Bp(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=Bp(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:o,acceptanceText:a}=this.parseRecommendationApplyActions(t.actionSteps);return{kind:"action",id:t.id,type:"Recommendation",displayName:t.description||this.label("recommendation"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,recommendationTitle:t.description||"",messageText:n,acceptanceText:a,applyActions:i,recommendationActionStepMeta:o}}return{kind:"action",id:t.id,type:"ShowErrorMessage",displayName:t.description||this.label("showErrorMessage"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,errorMessage:n||t.name||"",messageLevel:t.level??void 0,messageActionSteps:t.actionSteps}}case"ActionStep:#Microsoft.Crm.Workflow.ObjectModel":{let{applyActions:r,meta:n,acceptanceText:i}=this.parseRecommendationApplyActions({list:[t]});return{kind:"action",id:t.id,type:"Recommendation",displayName:t.name||this.label("recommendation"),stepName:t.name,stepLabels:t.stepLabels,field:t.actionControl?.controlId??"",recommendationTitle:t.name||"",messageText:t.description||"",acceptanceText:i,applyActions:r,recommendationActionStepMeta:n}}default:return null}}}});var D$=k(()=>{"use strict";});function nie(e){return typeof e=="object"&&e!==null?e:null}function vl(e){let t=nie(e);if(!t)return!1;if(t.__class===tie){let r=t;return String(r.method)===rie?!0:Array.isArray(r.parameters)&&r.parameters.some(vl)}if(t.__class===eie)return vl(t.operand);if(t.__class===Zne){let r=t;return vl(r.left)||Array.isArray(r.right)&&r.right.some(vl)}return!1}var Zne,eie,tie,rie,I$=k(()=>{"use strict";D$();Zne="BinaryExpression:#Microsoft.Crm.Workflow.Expressions",eie="UnaryExpression:#Microsoft.Crm.Workflow.Expressions",tie="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",rie="23"});function yv(e){return iie.has(e.type)}function mv(e,t,r,n,i,o,a){let s=i.get(r);!s||!R$.has(s.attributeType)||n!=="Value"||a?.operator&&!tv(a.operator)||o.push({nodeId:e,kind:"INVALID_VALUE_TYPE_FOR_FIELD",message:`${t}: please select a record for this lookup field; a typed text value cannot be saved.`,target:a?.target,itemId:a?.itemId,messageKey:"Validation.InvalidValueTypeForField",messageParams:{label:t}})}function oie(e,t){let r=t.get(e.field);return!!r&&R$.has(r.attributeType)&&tv(e.operator)}function hv(e){return!!(e?.entityType?.trim()&&e.id?.trim())}function gv(e,t,r){return{nodeId:e,kind:"INVALID_DAY_COUNT",message:`Please enter a whole number of days between 0 and ${hl}.`,target:t,itemId:r,messageKey:"Validation.InvalidDayCount",messageParams:{max:hl}}}function O$(e,t,r,n,i,o,a,s){if(i!=="Clear")return;let l=o.get(n);Dp(r,l)||a.push({nodeId:e,kind:"INVALID_CLEAR_FOR_FIELD",message:`${t}: Clear is only supported for optional fields with a legacy-compatible type.`,target:s?.target,itemId:s?.itemId,messageKey:"Validation.InvalidClearForField",messageParams:{label:t}})}function Wp(e){if(!e)return!1;for(let t of[...e.trueBranch,...e.falseBranch])if(t.kind==="action"){if(yv(t))return!0}else if(Wp(t))return!0;return!1}function bv(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=bv(r,t);if(n)return n}}return null}function aie(e){if(!e||typeof e!="object")return!1;let{__class:t,primitiveValue:r}=e;return t!=="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"?!1:r===!0||typeof r=="string"&&r.toLowerCase()==="true"}function sie(e){return e.clauses.length===0&&(e.rawConditionExpression===void 0||aie(e.rawConditionExpression))}function uie(e){return!!e.clauses?.some(t=>t.source==="BusinessProcess")||vl(e.rawConditionExpression)}function wl(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=wl(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=wl(n,t);if(i)return i}}return null}function vv(e,t){return{...e,trueBranch:P$(e.trueBranch,t),falseBranch:P$(e.falseBranch,t)}}function P$(e,t){return e.filter(r=>r.id!==t).map(r=>r.kind==="condition"?vv(r,t):r)}function Bo(e,t,r){return e.id===t?r(e):{...e,trueBranch:e.trueBranch.map(n=>n.kind==="condition"?Bo(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="condition"?Bo(n,t,r):n)}}function Gp(e,t,r){return{...e,trueBranch:e.trueBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?Gp(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?Gp(n,t,r):n)}}function L$(e,t,r,n){return Bo(e,t,i=>({...i,trueBranch:r==="true"?[...i.trueBranch,n]:i.trueBranch,falseBranch:r==="false"?[...i.falseBranch,n]:i.falseBranch}))}function wv(e){return e.length===1&&e[0].kind==="condition"}function die(e){let t=0,r=e??void 0;for(;r;){t+=1;let{falseBranch:n}=r;if(wv(n)){r=n[0];continue}n.length>0&&(t+=1),r=void 0}return t}function fie(e){return!!e&&die(e)<cie}function pie(e,t){if(!e)return;let r=(n,i)=>{if(n.id===t)return i;let o=[];if(wv(n.falseBranch)){let a=r(n.falseBranch[0],i);if(a)return a}else o.push(...n.falseBranch.filter(a=>a.kind==="condition"));o.push(...n.trueBranch.filter(a=>a.kind==="condition"));for(let a of o){let s=r(a,a);if(s)return s}};return r(e,e)}function k$(e,t,r){let n=pie(e,t);return!n||!fie(n)?e:Bo(e,t,i=>$$(i,r))}function $$(e,t){if(wv(e.falseBranch))return{...e,falseBranch:[$$(e.falseBranch[0],t)]};let r=Cv(t);return r.falseBranch=e.falseBranch,{...e,falseBranch:[r]}}function x$(e,t){let r=wl(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 Bo(e,r.node.id,o=>({...o,falseBranch:i}))}function F$(e,t,r){let n=wl(e,t);if(!n)return e;let i=o=>{let a=[...o],s=a[n.index+r];return s?(a[n.index+r]=a[n.index],a[n.index]=s,a):o};return Bo(e,n.node.id,o=>({...o,trueBranch:n.branch==="true"?i(o.trueBranch):o.trueBranch,falseBranch:n.branch==="false"?i(o.falseBranch):o.falseBranch}))}function Cv(e){return{kind:"condition",id:br(),displayName:e??"New Condition",clauses:[],logic:"AND",trueBranch:[],falseBranch:[],isCollapsed:!1}}function M$(e,t){let r={kind:"action",id:br(),type:e,displayName:t??`New ${e}`};switch(e){case"Recommendation":return{...r,type:"Recommendation",field:"",recommendationTitle:"",messageText:"",applyActions:[{id:br(),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 U$(e){if(!e)return[];let t=[];return B$(e,t),[...new Set(t)]}function B$(e,t){e.clauses.forEach(r=>{r.field&&t.push(r.field)}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"?B$(r,t):"field"in r&&r.field&&t.push(r.field)})}function q$(e,t=[],r){if(!e)return[{nodeId:"root",kind:"NO_CONDITION",message:"A business rule must include at least one condition.",target:"node"}];let n=[],i=new Map(t.map(o=>[o.logicalName,o]));return G$(e,n,i,!0),r==="Entity"&&V$(e,n),Wp(e)||n.push({nodeId:"root",kind:"NO_ACTION",message:"A business rule must include at least one action step.",target:"node"}),n}function V$(e,t){uie(e)&&t.push({nodeId:e.id,kind:"BPF_IN_ENTITY_SCOPE",message:"Process based conditions are not allowed in Entity scope.",target:"node",messageKey:"Validation.ProcessConditionNotAllowedInEntityScope"}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"&&V$(r,t)})}function G$(e,t,r,n=!1){let i=n&&sie(e),o=!!e.rawConditionExpression;e.clauses.length===0&&!n&&!o&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Add at least one clause to this condition.",target:"node",messageKey:"Validation.AddClause"}),i&&e.falseBranch.length>0&&t.push({nodeId:e.id,kind:"UNREACHABLE_ELSE",message:"Add a condition to the IF clause, or delete the ELSE clause it can never reach.",target:"node",messageKey:"Validation.UnreachableElse"}),e.clauses.forEach(a=>{if(o)return;if(a.source==="BusinessProcess"){a.bpfField?a.value||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:a.id}):t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a business process field for this clause.",target:"clauseField",itemId:a.id,messageKey:"Validation.SelectBusinessProcessField"});return}let s=a.valueType==="Expression"&&!a.rawExpression?Pa(a.expression):null;if(!a.field)t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a field for this clause.",target:"clauseField",itemId:a.id});else if(qn(a.operator)&&a.valueType==="Value"&&!a.value&&!oie(a,r))t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:a.id});else if(qn(a.operator)&&a.valueType==="Value"&&a.value){let u=r.get(a.field);u?.maxLength&&a.value.length>u.maxLength&&t.push({nodeId:e.id,kind:"CLAUSE_VALUE_TOO_LONG",message:`Value exceeds the field's maximum length of ${u.maxLength} characters.`,target:"clauseValue",itemId:a.id,messageParams:{maxLength:u.maxLength}})}else qn(a.operator)&&a.valueType==="Expression"&&!a.rawExpression&&!gl(a.expression)?t.push(s==="invalidDayCount"?gv(e.id,"clauseValue",a.id):{nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please complete the formula for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.CompleteClauseFormula"}):qn(a.operator)&&a.valueType==="Field"&&!a.valueField&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a field to compare to for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.EmptyClauseCompareField"});qn(a.operator)&&a.valueType==="Value"&&a.value&&Lk(r.get(a.field)?.attributeType)&&!Pp(a.value)&&t.push({nodeId:e.id,kind:"INVALID_CLAUSE_OPTION_VALUE",message:"Please enter a whole number option value for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.InvalidClauseOptionValue"});let l=xk(a);qn(a.operator)&&a.valueType==="Value"&&a.value&&Lp(l)&&!Fk(a.value,l)&&t.push({nodeId:e.id,kind:"INVALID_CLAUSE_NUMERIC_VALUE",message:Xb(l)?"Please enter a whole number for this clause.":"Please enter a valid number for this clause.",target:"clauseValue",itemId:a.id,messageKey:Xb(l)?"Validation.InvalidClauseWholeNumberValue":"Validation.InvalidClauseNumericValue"}),qn(a.operator)&&a.valueType==="Lookup"&&(hv(a.lookupValue)||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a lookup record for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.EmptyClauseLookupValue"})),qn(a.operator)&&mv(e.id,"Condition",a.field,a.valueType,r,t,{operator:a.operator,target:"clauseValue",itemId:a.id})}),i&&e.trueBranch.forEach(a=>{a.kind==="action"&&lie.has(a.type)&&t.push({nodeId:a.id,kind:"ACTION_REQUIRES_CONDITION",message:"Set field value, Show error message, and Recommendation actions require a condition. Add a condition to the IF clause, or use a different action.",target:"node",messageKey:"Validation.ActionRequiresCondition",messageParams:{actionType:a.type}})}),[...e.trueBranch,...e.falseBranch].forEach(a=>{if(a.kind==="condition")G$(a,t,r);else{if(!("field"in a)||!a.field)t.push({nodeId:a.id,kind:"EMPTY_ACTION_FIELD",message:`${a.type}: a target field is required.`,target:"actionField",messageParams:{actionType:a.type}});else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&(a.valueType??"Value")==="Value"&&!a.value?.trim())t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please provide a value.`,target:"actionValue",messageParams:{actionType:a.type}});else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Value"&&a.value){let s=r.get(a.field);s?.maxLength&&a.value.length>s.maxLength&&t.push({nodeId:a.id,kind:"ACTION_VALUE_TOO_LONG",message:`${a.type}: value exceeds the field's maximum length of ${s.maxLength} characters.`,target:"actionValue",messageParams:{actionType:a.type,maxLength:s.maxLength}})}else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Field"){if(!a.valueField)t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please select a field to copy from.`,target:"actionValue",messageKey:"Validation.SelectActionSourceField",messageParams:{actionType:a.type}});else if(r.size>0){let s=r.get(a.field),l=r.get(a.valueField);s&&l&&!$p(s.attributeType,l.attributeType)&&t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: the source field's type is not compatible with the target field.`,target:"actionValue",messageKey:"Validation.IncompatibleActionSourceField",messageParams:{actionType:a.type}})}}else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Expression"){let s=a.rawExpression?null:Pa(a.expression);!a.rawExpression&&!gl(a.expression)&&t.push(s==="invalidDayCount"?gv(a.id,"actionValue"):{nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please complete the formula.`,target:"actionValue",messageKey:"Validation.CompleteActionFormula",messageParams:{actionType:a.type}})}else(a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Lookup"&&!hv(a.lookupValue)&&t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please complete the lookup record.`,target:"actionValue",messageKey:"Validation.EmptyActionLookupValue",messageParams:{actionType:a.type}});if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.field&&(mv(a.id,a.type,a.field,a.valueType,r,t,{target:"actionValue"}),O$(a.id,a.type,a.type,a.field,a.valueType,r,t,{target:"actionValue"})),a.type==="ShowErrorMessage"&&!a.errorMessage?.trim()&&t.push({nodeId:a.id,kind:"EMPTY_ACTION_MESSAGE",message:"Show error message: please enter an error message.",target:"actionMessage"}),a.type==="Recommendation"){let s=a.applyActions??[];a.recommendationTitle?.trim()||t.push({nodeId:a.id,kind:"EMPTY_RECOMMENDATION_TITLE",message:"Recommendation: please enter a recommendation title.",target:"recommendationTitle"}),a.messageText?.trim()||t.push({nodeId:a.id,kind:"EMPTY_RECOMMENDATION_MESSAGE",message:"Recommendation: please enter a recommendation message.",target:"recommendationMessage"}),s.length===0&&t.push({nodeId:a.id,kind:"RECOMMENDATION_NO_APPLY_ACTION",message:"Recommendation: add at least one action to apply.",target:"node"}),s.forEach(l=>{if(!l.field)t.push({nodeId:a.id,kind:"EMPTY_ACTION_FIELD",message:"Recommendation: a target field is required for each action to apply.",target:"applyActionField",itemId:l.id,messageKey:"Validation.RecommendationApplyField"});else if(l.valueType==="Field")l.valueField||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please select a field to copy from.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplySourceField"});else if(l.valueType==="Expression"){let u=l.rawExpression?null:Pa(l.expression);!l.rawExpression&&!gl(l.expression)&&t.push(u==="invalidDayCount"?gv(a.id,"applyActionValue",l.id):{nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the formula.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplyFormula"})}else l.valueType==="Lookup"?hv(l.lookupValue)||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the lookup record.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplyLookupValue"}):l.valueType==="Clear"||l.value?.trim()||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please enter a value for each action to apply.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplyValue"});l.field&&(mv(a.id,"Recommendation",l.field,l.valueType,r,t,{target:"applyActionValue",itemId:l.id}),O$(a.id,"Recommendation","SetFieldValue",l.field,l.valueType,r,t,{target:"applyActionValue",itemId:l.id}))})}}})}var iie,R$,lie,cie,Ev=k(()=>{"use strict";Yb();zb();xp();gc();I$();ev();Qb();iie=new Set(["LockUnlock","ShowErrorMessage","Recommendation","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]);R$=new Set(["Lookup","Customer","Owner"]);lie=new Set(["SetFieldValue","ShowErrorMessage","Recommendation"]);cie=10});var W$={};nn(W$,{DAY_COUNT_MAX:()=>hl,DAY_COUNT_MIN:()=>iv,DEFAULT_DESERIALIZE_LABELS:()=>fv,WorkflowJsonMapper:()=>bl,addElseIfInTree:()=>k$,appendToBranch:()=>L$,areFieldKindsCompatible:()=>$p,attributeTypeToWorkflowType:()=>Hk,buildWorkflowEntity:()=>Ak,collectUsedFields:()=>U$,createEmptyAction:()=>M$,createEmptyCondition:()=>Cv,deserializeWorkflowJson:()=>T$,findNode:()=>bv,findParent:()=>wl,getDefaultOperatorForFieldType:()=>Vk,getExpressionModelIssue:()=>Pa,getOperatorsForFieldType:()=>kp,hasAnyTriggerGeneratingAction:()=>Wp,isDayCountValid:()=>ov,isExpressionModelComplete:()=>gl,isOperatorCompatible:()=>Gk,isTriggerGeneratingAction:()=>yv,moveBranchItemInTree:()=>F$,operatorNeedsValue:()=>qn,processTriggerFormIdFromScope:()=>Hb,processTriggerScopeFromScope:()=>jb,removeElseIfInTree:()=>x$,removeNodeFromTree:()=>vv,serializeToWorkflowJson:()=>_$,supportsClearForActionType:()=>Dp,updateActionInTree:()=>Gp,updateConditionInTree:()=>Bo,validateBusinessRule:()=>q$});var z$=k(()=>{"use strict";zb();Sk();pv();pv();Ev();Ev();xp();gc();gc();});var Av=v(zp=>{"use strict";Object.defineProperty(zp,"__esModule",{value:!0});zp.cloneJson=void 0;function mie(e){return JSON.parse(JSON.stringify(e))}zp.cloneJson=mie});var nx=v(qo=>{"use strict";Object.defineProperty(qo,"__esModule",{value:!0});qo.BUSINESS_RULE_NULL_GUID=qo.businessRuleRegistration=qo.BusinessRuleAdapter=void 0;var j$=ct(),bc=(z$(),zr(W$)),H$=jr(),K$=Q(),hie=Av(),hi=cn(),gie=dh(),yie=ct(),bie=sa(),vie=new Set(["ShowErrorMessage","Recommendation"]);function X$(e){var t,r;return e?[...(t=e.trueBranch)!==null&&t!==void 0?t:[],...(r=e.falseBranch)!==null&&r!==void 0?r:[]].some(n=>Array.isArray(n.trueBranch)||Array.isArray(n.falseBranch)?X$(n):vie.has(String(n.type))):!1}function wie(e){return Z$((0,hie.cloneJson)(e))}function Z$(e){var t,r;let n=i=>(i??[]).map(o=>Cie(o)?Z$(o):o);return{...e,logic:(t=e.logic)!==null&&t!==void 0?t:"AND",clauses:(r=e.clauses)!==null&&r!==void 0?r:[],trueBranch:n(e.trueBranch),falseBranch:n(e.falseBranch)}}function Cie(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 Eie(e){var t;if(e===null||typeof e!="object"||Array.isArray(e))throw new K$.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 K$.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 Aie="00000000-0000-0000-0000-000000000000";qo.BUSINESS_RULE_NULL_GUID=Aie;var Sie=new Set(["Recommendation","LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]),Nie=["ruleId","name","description","entityLogicalName","scope","status","rootCondition"],_ie=["kind","id","displayName","logic","clauses","trueBranch","falseBranch"],Tie=["id","field","fieldDisplayName","operator","valueType","value","valueField","lookupValue","expression","rawExpression","valueWorkflowType"];function Vn(e,t){return e===void 0?t:{...e,...t}}var ka=["kind","id","type","displayName","field","stepName","stepLabels"],J$=["valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression"],Die={Recommendation:[...ka,"recommendationTitle","messageText","acceptanceText","applyActions","recommendationActionStepMeta"],LockUnlock:[...ka,"lock"],ShowErrorMessage:[...ka,"errorMessage","messageLevel","messageActionSteps"],SetFieldValue:[...ka,...J$],SetDefaultValue:[...ka,...J$],SetBusinessRequired:[...ka,"required"],SetVisibility:[...ka,"visible"]};function ne(e,t){return t===void 0?{}:{[e]:t}}function ex(e){var t;return e==null?void 0:{...e,label:(t=e.label)!==null&&t!==void 0?t:""}}function Sv(e){return{valueType:e.valueType,...ne("valueWorkflowType",e.valueWorkflowType),...ne("value",e.value),...ne("valueField",e.valueField),...ne("lookupValue",ex(e.lookupValue)),...ne("expression",e.expression),...ne("rawExpression",e.rawExpression)}}function tx(e,t){let r=new Set(t),n={};for(let[i,o]of Object.entries(e))r.has(i)||o!==void 0&&(n[i]=o);return Object.keys(n).length>0?n:void 0}var Iie=["id","field","valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression","stepName","displayName"];function Oie(e){return Vn(e.bag,{id:e.id,field:e.field,...Sv(e),...ne("stepName",e.stepName),...ne("displayName",e.displayName)})}function Pie(e){let t=tx(e,Iie);return{id:e.id,field:e.field,valueType:e.valueType,...ne("valueWorkflowType",e.valueWorkflowType),...ne("value",e.value),...ne("valueField",e.valueField),...ne("lookupValue",e.lookupValue),...ne("expression",e.expression),...ne("rawExpression",e.rawExpression),...ne("stepName",e.stepName),...ne("displayName",e.displayName),...ne("bag",t)}}function Y$(e){return{valueType:e.valueType,...ne("valueWorkflowType",e.valueWorkflowType),...ne("value",e.value),...ne("valueField",e.valueField),...ne("lookupValue",e.lookupValue),...ne("expression",e.expression),...ne("rawExpression",e.rawExpression)}}function Q$(e){throw new Error(`Unsupported business-rule action type: ${e.type}`)}var Rie=new Set(["INVALID_CLEAR_FOR_FIELD","INVALID_VALUE_TYPE_FOR_FIELD","CLAUSE_VALUE_TOO_LONG","ACTION_VALUE_TOO_LONG"]),Lie=new Set,kie="INVALID_CLEAR_FOR_FIELD";function $ie(e){let t=n=>{var i;return(0,hi.isJsonObject)(n)&&(n.label===""||n.label===void 0)?{...n,label:String((i=n.id)!==null&&i!==void 0?i:"")}:n},r=n=>{if(!(0,hi.isJsonObject)(n))return n;let i={...n};"lookupValue"in i&&(i.lookupValue=t(i.lookupValue)),Array.isArray(i.applyActions)&&(i.applyActions=i.applyActions.map(r));for(let o of["clauses","trueBranch","falseBranch"])Array.isArray(i[o])&&(i[o]=i[o].map(r));return i};return r(e)}var jp=class{toArtifact(t){let r=this.residualBag(t,Nie),n={id:t.ruleId,name:t.name,description:t.description,entityLogicalName:t.entityLogicalName,scope:t.scope,status:t.status,rootCondition:t.rootCondition?this.conditionToJson(t.rootCondition):null};return r&&(n.bag=r),n}fromArtifact(t){let r=t.rootCondition?this.conditionFromJson(t.rootCondition):null;return Vn(t.bag,{ruleId:t.id,name:t.name,description:t.description,entityLogicalName:t.entityLogicalName,scope:t.scope,status:t.status,rootCondition:r})}fromApiResponse(t){var r;let n=t??{},i={...(r=n.Entity)!==null&&r!==void 0?r:{},wfomJson:n.WfomJson},o=(0,bc.deserializeWorkflowJson)(i);return this.toArtifact(o)}needsBaseLanguage(t){return X$(t.rootCondition)}toApiPayload(t,r,n){var i,o;let a=this.fromArtifact(t);a.wfomRoot&&(a.wfomRoot={...a.wfomRoot,name:t.name,title:t.name,primaryEntityName:t.entityLogicalName||a.wfomRoot.primaryEntityName},a.entityLogicalName=a.wfomRoot.primaryEntityName);let s=(0,bc.serializeToWorkflowJson)(a,(i=n?.baseLanguageCode)!==null&&i!==void 0?i:bie.DEFAULT_LCID),l=(o=a.ruleId)!==null&&o!==void 0?o:(0,j$.newId)();return{Entity:this.buildWorkflowEntity(a,l),WfomJson:s,status:t.status}}createDefault(t){var r,n,i,o,a,s;let l={ruleId:(r=t.id)!==null&&r!==void 0?r:null,name:(n=t.name)!==null&&n!==void 0?n:"New business rule",description:(i=t.description)!==null&&i!==void 0?i:"",entityLogicalName:(o=t.entityLogicalName)!==null&&o!==void 0?o:"",scope:(a=t.scope)!==null&&a!==void 0?a:"Entity",status:(s=t.status)!==null&&s!==void 0?s:"Draft",rootCondition:t.rootCondition===void 0?(0,bc.createEmptyCondition)():t.rootCondition===null?null:this.conditionFromJson(wie(Eie(t.rootCondition)))},u=this.toArtifact(l);return u.id||(u.id=(0,j$.newId)()),u}assignMissingIds(t){return(0,yie.assignMissingIds)(t)}validate(t){let r=[],n=t.rootCondition;return n==null?r:(0,hi.isJsonObject)(n)?(rx(n,"/rootCondition",r),r):(r.push((0,hi.issue)("/rootCondition","condition-must-be-object",`rootCondition must be a JSON object or null, got ${typeof n}`)),r)}semanticIssues(t,r=[]){let n;try{n=this.fromArtifact(t)}catch(a){return[(0,hi.issue)("/rootCondition","rule-not-representable",a instanceof Error?a.message:String(a))]}let i=n.rootCondition===null?null:$ie(n.rootCondition),o;return r.length===0?o=Rie:r.some(a=>a.requiredLevel!==void 0)?o=Lie:o=new Set([kie]),(0,bc.validateBusinessRule)(i,r).filter(a=>!o.has(a.kind)).map(a=>(0,hi.issue)(`/rootCondition (${a.nodeId})`,`business-rule-${a.kind}`,a.message))}issuesBlockingPush(t,r=[],n){return this.semanticIssues(t,r)}columnsCheckedAtPush(t){let r;try{r=this.fromArtifact(t)}catch{return[]}let n=new Set,i=a=>{a&&n.add(a)},o=a=>{var s;for(let l of a.clauses)i(l.field),i(l.valueField);for(let l of[...a.trueBranch,...a.falseBranch]){if(l.kind==="condition"){o(l);continue}if(i(l.field),l.type==="SetFieldValue"||l.type==="SetDefaultValue")i(l.valueField);else if(l.type==="Recommendation")for(let u of(s=l.applyActions)!==null&&s!==void 0?s:[])i(u.field),i(u.valueField)}};return r.rootCondition&&o(r.rootCondition),[...n]}residualBag(t,r){return tx(t,r)}buildWorkflowEntity(t,r){return(0,bc.buildWorkflowEntity)(t,r)}conditionToJson(t){let r=this.residualBag(t,_ie),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,Tie),n={id:t.id,field:t.field,fieldDisplayName:t.fieldDisplayName,operator:t.operator,valueType:t.valueType,...t.value!==void 0?{value:t.value}:{},...t.valueField!==void 0?{valueField:t.valueField}:{},...t.lookupValue!==void 0?{lookupValue:t.lookupValue}:{},...t.expression!==void 0?{expression:t.expression}:{},...t.rawExpression!==void 0?{rawExpression:t.rawExpression}:{},...t.valueWorkflowType!==void 0?{valueWorkflowType:t.valueWorkflowType}:{}};return r&&(n.bag=r),n}branchItemToJson(t){return t.kind==="condition"?this.conditionToJson(t):this.actionToJson(t)}actionToJson(t){let r=this.residualBag(t,Die[t.type]),n={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...ne("stepName",t.stepName),...ne("stepLabels",t.stepLabels),...ne("bag",r)};switch(t.type){case"Recommendation":return{...n,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...ne("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(Pie),...ne("recommendationActionStepMeta",t.recommendationActionStepMeta)};case"LockUnlock":return{...n,type:"LockUnlock",lock:t.lock};case"ShowErrorMessage":return{...n,type:"ShowErrorMessage",errorMessage:t.errorMessage,...ne("messageLevel",t.messageLevel),...ne("messageActionSteps",t.messageActionSteps)};case"SetFieldValue":return{...n,type:"SetFieldValue",...Y$(t)};case"SetDefaultValue":return{...n,type:"SetDefaultValue",...Y$(t)};case"SetBusinessRequired":return{...n,type:"SetBusinessRequired",required:t.required};case"SetVisibility":return{...n,type:"SetVisibility",visible:t.visible};default:return Q$(t)}}conditionFromJson(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:{};return Vn(n,{kind:"condition",isCollapsed:typeof n.isCollapsed=="boolean"?n.isCollapsed:!1,id:t.id,displayName:t.displayName,logic:t.logic,clauses:t.clauses.map(i=>this.clauseFromJson(i)),trueBranch:t.trueBranch.map(i=>this.branchItemFromJson(i)),falseBranch:t.falseBranch.map(i=>this.branchItemFromJson(i))})}clauseFromJson(t){var r;return Vn(t.bag,{id:t.id,field:t.field,fieldDisplayName:(r=t.fieldDisplayName)!==null&&r!==void 0?r:t.field,operator:t.operator,valueType:t.valueType,...ne("value",t.value),...ne("valueField",t.valueField),...ne("lookupValue",ex(t.lookupValue)),...ne("expression",t.expression),...ne("rawExpression",t.rawExpression),...ne("valueWorkflowType",t.valueWorkflowType)})}branchItemFromJson(t){return this.isConditionJson(t)?this.conditionFromJson(t):this.actionFromJson(t)}actionFromJson(t){if(!Sie.has(t.type))throw new Error(`Unsupported business-rule action type: ${t.type}`);Fie(t);let r={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...ne("stepName",t.stepName),...ne("stepLabels",t.stepLabels)};switch(t.type){case"Recommendation":return Vn(t.bag,{...r,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...ne("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(Oie),...ne("recommendationActionStepMeta",t.recommendationActionStepMeta)});case"LockUnlock":return Vn(t.bag,{...r,type:"LockUnlock",lock:t.lock});case"ShowErrorMessage":return Vn(t.bag,{...r,type:"ShowErrorMessage",errorMessage:t.errorMessage,...ne("messageLevel",t.messageLevel),...ne("messageActionSteps",t.messageActionSteps)});case"SetFieldValue":return Vn(t.bag,{...r,type:"SetFieldValue",...Sv(t)});case"SetDefaultValue":return Vn(t.bag,{...r,type:"SetDefaultValue",...Sv(t)});case"SetBusinessRequired":return Vn(t.bag,{...r,type:"SetBusinessRequired",required:t.required});case"SetVisibility":return Vn(t.bag,{...r,type:"SetVisibility",visible:t.visible});default:return Q$(t)}}isConditionJson(t){return Object.prototype.hasOwnProperty.call(t,"clauses")&&Object.prototype.hasOwnProperty.call(t,"logic")&&!Object.prototype.hasOwnProperty.call(t,"type")}};qo.BusinessRuleAdapter=jp;function rx(e,t,r){(0,hi.optionalEnum)(e,"logic",["AND","OR"],t,"condition-logic-invalid",r),(0,hi.childObjects)(e,"clauses",t,"clause",r);for(let n of["trueBranch","falseBranch"])(0,hi.childObjects)(e,n,t,"branchItem",r).forEach(({node:o,index:a})=>{"clauses"in o||"trueBranch"in o||"falseBranch"in o?rx(o,`${t}/${n}/${a}`,r):xie(o,`${t}/${n}/${a}`,r)})}function xie(e,t,r){e.type==="SetDefaultValue"&&e.valueType==="Clear"&&r.push((0,hi.issue)(`${t}/valueType`,"clear-only-set-field-value","Clear is only supported for SetFieldValue actions."))}function Fie(e){if(e.type==="SetDefaultValue"&&e.valueType==="Clear")throw new Error("Clear is only supported for SetFieldValue actions.")}function Mie(){return{adapter:new jp,api:gie.businessRuleApi,publish:(e,t,r)=>(0,H$.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,H$.boundEntityPublishScope)(t)}}qo.businessRuleRegistration=Mie});var Cx=v(Vo=>{"use strict";Object.defineProperty(Vo,"__esModule",{value:!0});Vo.appRegistration=Vo.AppAdapter=Vo.HEADER_NAV_BOOLEAN_RULE=void 0;var Zi=cn(),$t=wo(),wc=Eo(),Uie=jr(),px=Af(),Nv=tf(),_v=Co(),Bie=ct(),qie=oe(),mx=sa(),hx=Q(),gx=nf();Object.defineProperty(Vo,"HEADER_NAV_BOOLEAN_RULE",{enumerable:!0,get:function(){return gx.HEADER_NAV_BOOLEAN_RULE}});var Yp="7.0.0.0",ix=`<SiteMap IntroducedVersion="${Yp}"></SiteMap>`,ox="/_imgs/imagestrips/transparent_spacer.gif",ax="/_imgs/TableIconsFluentV9/document_one_page_sparkle.svg",yx=["Entity","Url","DefaultDashboard","Page","GenPageId"],vc="sitemapId",sx="sitemapName",Vie="sitemapNameUnique",lx="aiDescription",ux="[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}",Gie=new RegExp(`^(?:\\{${ux}\\}|${ux})$`);function cx(e,t){if(!Gie.test(e.trim()))throw new hx.ValidationError("app",t,[{pointer:"/sitemapId",rule:"app-sitemapid-guid",message:`sitemapId must be a GUID; received '${e}'.`}]);return e.trim()}function dx(e,t,r){if(e===void 0)return r;if(typeof e!="boolean")throw new hx.ValidationError("app",t,[bx(e)]);return e}function bx(e){return(0,Zi.issue)("/headerAndNavigationRefresh",gx.HEADER_NAV_BOOLEAN_RULE,`headerAndNavigationRefresh must be a boolean, got ${typeof e}`)}function Wie(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,qie.normalizeGuid)(i,n)}catch{return}};switch(e.type){case"Entity":return t("entity")&&`Entity:${t("entity").toLowerCase()}`;case"URL":return t("url")&&`URL:${t("url").toLowerCase()}`;case"DashBoard":return r("dashboardId")&&`DashBoard:${r("dashboardId")}`;case"CustomPage":return t("page")&&`CustomPage:${t("page").toLowerCase()}`;case"GenPage":return r("genPageId")&&`GenPage:${r("genPageId")}`;default:return}}function zie(e){var t,r,n,i;let o=[];for(let a of(r=(t=e.siteMap)===null||t===void 0?void 0:t.areas)!==null&&r!==void 0?r:[])for(let s of(n=a.groups)!==null&&n!==void 0?n:[])for(let l of(i=s.subAreas)!==null&&i!==void 0?i:[])l.type==="Entity"&&l.entity&&o.push(l.entity);return o}var Qp=class{constructor(t=mx.DEFAULT_LCID){this.lcid=t}toArtifact(t){let{bag:r,modeledEls:n}=Hp(t,"Area");return{id:"",name:"",uniqueName:"",description:"",siteMap:{areas:n.map(i=>this.areaToJson(i)),bag:r},bag:(0,$t.emptyBag)()}}fromArtifact(t){(0,_v.installDomShim)();let r=this.assignMissingIds(JSON.parse(JSON.stringify(t))),n=new DOMParser().parseFromString("<root/>","text/xml"),i=this.rootToRaw(r);return(0,$t.rebuildRaw)(i,(0,wc.domEngine)(n),null)}fromApiResponse(t){var r,n,i,o,a,s,l,u,c,d,f;(0,_v.installDomShim)();let m=t??{},p=(r=m.$sitemap)!==null&&r!==void 0?r:m,h=(0,wc.parseXmlRoot)((n=p.sitemapxml)!==null&&n!==void 0?n:ix,ix),g=this.toArtifact(h);return g.id=(i=m.appmoduleid)!==null&&i!==void 0?i:"",g.name=(o=m.name)!==null&&o!==void 0?o:"",g.uniqueName=(a=m.uniquename)!==null&&a!==void 0?a:"",g.description=(s=m.description)!==null&&s!==void 0?s:"",m.aiappdescription&&(g.aiDescription=m.aiappdescription),g.bag={a:[[vc,(u=(l=p.sitemapid)!==null&&l!==void 0?l:m._sitemapid_value)!==null&&u!==void 0?u:""],[sx,(c=p.sitemapname)!==null&&c!==void 0?c:""],[Vie,(d=p.sitemapnameunique)!==null&&d!==void 0?d:""],[lx,(f=m.aiappdescription)!==null&&f!==void 0?f:""]],c:[]},g}toApiPayload(t,r){var n,i,o,a,s,l,u,c,d,f,m,p,h,g,b;(0,_v.installDomShim)();let w=(0,wc.serializeNode)(this.fromArtifact(t)),C=[],S=[];for(let L of(i=(n=t.siteMap)===null||n===void 0?void 0:n.areas)!==null&&i!==void 0?i:[])for(let I of(o=L.groups)!==null&&o!==void 0?o:[])for(let D of(a=I.subAreas)!==null&&a!==void 0?a:[])D.type==="Entity"&&D.entity?C.push(D.entity):D.type==="DashBoard"&&D.dashboardId&&S.push(D.dashboardId);let O=(s=t.bag)!==null&&s!==void 0?s:(0,$t.emptyBag)();return{sitemapId:Dv(O,vc)||(t.sitemapId?cx(t.sitemapId,t.id):""),sitemapxml:w,sitemapname:Dv(O,sx)||t.name,appModuleId:t.id,appModuleName:t.name,appModuleDescription:t.description,...t.aiDescription!==void 0&&t.aiDescription!==(r?r.aiDescription:Dv(O,lx))?{appModuleAiDescription:t.aiDescription}:{},appModuleUniqueName:t.uniqueName,...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},...t.headerAndNavigationRefresh===void 0?{}:{appSettings:{[Nv.HEADER_AND_NAVIGATION_REFRESH]:dx(t.headerAndNavigationRefresh,(l=t.id)!==null&&l!==void 0?l:"(unknown)",!0)?Nv.APP_SETTING_ON:Nv.APP_SETTING_OFF}},...typeof t.published=="boolean"?{published:t.published}:{},entities:C,components:{forms:(c=(u=t.components)===null||u===void 0?void 0:u.forms)!==null&&c!==void 0?c:[],views:(f=(d=t.components)===null||d===void 0?void 0:d.views)!==null&&f!==void 0?f:[],charts:(p=(m=t.components)===null||m===void 0?void 0:m.charts)!==null&&p!==void 0?p:[],dashboards:[...(g=(h=t.components)===null||h===void 0?void 0:h.dashboards)!==null&&g!==void 0?g:[],...S],...((b=t.components)===null||b===void 0?void 0:b.mainFormsByTable)!==void 0?{mainFormsByTable:t.components.mainFormsByTable}:{}}}}createDefault(t){var r,n,i,o,a,s;let l=!((r=t.siteMap)===null||r===void 0)&&r.areas&&t.siteMap.areas.length>0?t.siteMap.areas:[{id:"",title:"Area",groups:[{id:"",title:"Group",subAreas:[]}]}],u=(n=t.id)!==null&&n!==void 0?n:(0,Bie.newId)();return{id:u,name:(i=t.name)!==null&&i!==void 0?i:"New App",uniqueName:(o=t.uniqueName)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",...t.aiDescription?{aiDescription:t.aiDescription}:{},siteMap:{areas:l},...t.sitemapId?{sitemapId:cx(t.sitemapId,u)}:{},...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},headerAndNavigationRefresh:dx(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(Ov):Array.isArray(r.areas)?r.areas.forEach(Ov):Array.isArray(r.groups)?Ov(r):Array.isArray(r.subAreas)?wx(r):"type"in r&&Xp(r,"subarea"),t}validate(t){let r=[],n=t.published;n!==void 0&&typeof n!="boolean"&&r.push((0,Zi.issue)("/published","published-must-be-boolean",`published must be a boolean, got ${typeof n}`));let i=t.siteMap,o=t.headerAndNavigationRefresh;if(o!==void 0&&typeof o!="boolean"&&r.push(bx(o)),i==null)return r;if(!(0,Zi.isJsonObject)(i))return r.push((0,Zi.issue)("/siteMap","sitemap-must-be-object",`siteMap must be a JSON object, got ${typeof i}`)),r;let a=(0,Zi.childObjects)(i,"areas","/siteMap","area",r),s=new Map;return a.forEach(({node:l,index:u})=>{let c=`/siteMap/areas/${u}`;(0,Zi.childObjects)(l,"groups",c,"group",r).forEach(({node:f,index:m})=>{let p=`${c}/groups/${m}`;(0,Zi.childObjects)(f,"subAreas",p,"subArea",r).forEach(({node:g,index:b})=>{let w=`${p}/subAreas/${b}`;(0,Zi.optionalEnum)(g,"type",["Entity","URL","DashBoard","CustomPage","GenPage"],w,"subarea-type-invalid",r);let C=Wie(g);if(!C)return;let S=s.get(C);if(S===void 0){s.set(C,w);return}r.push((0,Zi.issue)(w,"subarea-duplicate-target",`the sitemap already navigates to this target at ${S}; a duplicate SubArea would pin it twice and a single removeElement would leave one behind`))})})}),r}issuesBlockingPush(t){var r;return(0,px.mainFormSetShapeIssues)((r=t.components)===null||r===void 0?void 0:r.mainFormsByTable,zie(t))}applyServerIdentity(t,r){let n=r[vc];if(!n)return;t.bag||(t.bag=(0,$t.emptyBag)());let i=t.bag.a.find(o=>o[0]===vc);i?i[1]=n:t.bag.a.push([vc,n])}areaToJson(t){var r;let{bag:n,modeledEls:i}=Hp(t,"Group"),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:Tv(t,this.lcid),groups:i.map(l=>this.groupToJson(l)),bag:n},a=t.getAttribute("Icon");a&&(o.icon=a);let s=t.getAttribute("VectorIcon");return s&&(o.vectorIcon=s),o}groupToJson(t){var r;let{bag:n,modeledEls:i}=Hp(t,"SubArea");return{id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:Tv(t,this.lcid),subAreas:i.map(o=>this.subAreaToJson(o)),bag:n}}subAreaToJson(t){var r;let{bag:n}=Hp(t,null),i=jie(t),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",type:i,title:Tv(t,this.lcid),bag:n};if(i==="Entity"){let l=t.getAttribute("Entity");l&&(o.entity=l)}else if(i==="DashBoard"){let l=t.getAttribute("DefaultDashboard");l&&(o.dashboardId=l);let u=t.getAttribute("Url");u&&(o.dashboardUrl=u)}else if(i==="CustomPage"){let l=t.getAttribute("Page");l&&(o.page=l)}else if(i==="GenPage"){let l=t.getAttribute("GenPageId");l&&(o.genPageId=l)}else{let l=t.getAttribute("Url");l&&(o.url=l)}let a=t.getAttribute("Icon");a&&a!==ox&&(o.icon=a);let s=t.getAttribute("VectorIcon");return s&&(o.vectorIcon=s),o}rootToRaw(t){var r,n,i,o;let a=(n=(r=t.siteMap)===null||r===void 0?void 0:r.bag)!==null&&n!==void 0?n:(0,$t.emptyBag)(),l=Kp(a)?[["IntroducedVersion",Yp]]:[],u=((o=(i=t.siteMap)===null||i===void 0?void 0:i.areas)!==null&&o!==void 0?o:[]).map(c=>this.areaToRaw(c));return{n:"SiteMap",a:(0,$t.mergeAttrs)(a.a,l),c:(0,$t.spliceChildren)(a.c,u)}}areaToRaw(t){var r,n;let i=(r=t.bag)!==null&&r!==void 0?r:(0,$t.emptyBag)(),o=Kp(i),a=[],s=[];t.id&&a.push(["Id",t.id]),o&&a.push(["ShowGroups","true"],["ResourceId","SitemapDesigner.NewTitle"],["DescriptionResourceId","SitemapDesigner.NewTitle"],["IntroducedVersion",Yp]),t.icon!==void 0?a.push(["Icon",t.icon]):Jp(i.a,"Icon")&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):Jp(i.a,"VectorIcon")&&s.push("VectorIcon");let l=((n=t.groups)!==null&&n!==void 0?n:[]).map(c=>this.groupToRaw(c)),u=Iv((0,$t.spliceChildren)(i.c,l),t.title,o,this.lcid);return{n:"Area",a:(0,$t.mergeAttrs)(i.a,a,s),c:u}}groupToRaw(t){var r,n;let i=(r=t.bag)!==null&&r!==void 0?r:(0,$t.emptyBag)(),o=Kp(i),a=[];t.id&&a.push(["Id",t.id]),o&&a.push(["ResourceId","SitemapDesigner.NewGroup"],["DescriptionResourceId","SitemapDesigner.NewGroup"],["ToolTipResourseId","SitemapDesigner.Unknown"],["IntroducedVersion",Yp],["IsProfile","false"]);let s=((n=t.subAreas)!==null&&n!==void 0?n:[]).map(u=>this.subAreaToRaw(u)),l=Iv((0,$t.spliceChildren)(i.c,s),t.title,o,this.lcid);return{n:"Group",a:(0,$t.mergeAttrs)(i.a,a),c:l}}subAreaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,$t.emptyBag)(),i=Kp(n),o=Kie(n.a,t.type),a=[],s=[];t.id&&a.push(["Id",t.id]);let l=!i&&!n.a.some(([c])=>yx.includes(c));Yie(a,t,l),i?(a.push(["ResourceId","SitemapDesigner.NewSubArea"],["Client","All,Outlook,OutlookLaptopClient,OutlookWorkstationClient,Web"],["Sku","All,OnPremise,Live,SPLA"],["AvailableOffline","true"],["PassParams","false"]),t.icon&&a.push(["Icon",t.icon])):t.icon!==void 0?a.push(["Icon",t.icon]):Jp(o,"Icon",ox)&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):Jp(o,"VectorIcon")?t.type==="GenPage"?a.push(["VectorIcon",ax]):s.push("VectorIcon"):t.type==="GenPage"&&!Hie(o,"VectorIcon")&&a.push(["VectorIcon",ax]);let u=Iv((0,$t.spliceChildren)(n.c,[]),t.title,i,this.lcid);return{n:"SubArea",a:(0,$t.mergeAttrs)(o,a,s),c:u}}};Vo.AppAdapter=Qp;function Hp(e,t){let r=(0,wc.nodeLikeFromDom)(e).getAllProperties().map(s=>[s.key,s.value]),n=[],i=[],o=e.childNodes,a=0;for(let s=0;s<o.length;s+=1){let l=o[s];l.nodeType!==1&&l.nodeType!==3||(l.nodeType===1&&t!==null&&l.tagName===t?i.push(l):n.push({i:a,node:(0,$t.rawFromNode)((0,wc.nodeLikeFromDom)(l))}),a+=1)}return{bag:{a:r,c:n},modeledEls:i}}function fx(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName===t&&r.push(o)}return r}function Tv(e,t){var r;let n=fx(e,"Titles")[0];if(!n)return"";let o=fx(n,"Title").find(a=>a.getAttribute("LCID")===String(t));return o&&(r=o.getAttribute("Title"))!==null&&r!==void 0?r:""}function jie(e){return e.getAttribute("GenPageId")?"GenPage":e.getAttribute("Entity")?"Entity":e.getAttribute("Page")?"CustomPage":e.getAttribute("DefaultDashboard")?"DashBoard":"URL"}function Kp(e){return e.a.length===0&&e.c.length===0}function Hie(e,t){return e.some(([r])=>r===t)}function Jp(e,t,r){let n=e.find(([o])=>o===t),i=n?.[1];return!!i&&i!==r}function Dv(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function Kie(e,t){let r=Jie(t);return e.filter(([n])=>!yx.includes(n)||r.has(n)).map(n=>[n[0],n[1]])}function Jie(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 Yie(e,t,r){var n,i,o,a,s;switch(t.type){case"Entity":e.push(["Entity",(n=t.entity)!==null&&n!==void 0?n:""]);break;case"URL":(t.url!==void 0||!r)&&e.push(["Url",(i=t.url)!==null&&i!==void 0?i:""]);break;case"DashBoard":e.push(["DefaultDashboard",(o=t.dashboardId)!==null&&o!==void 0?o:""]),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",(s=t.genPageId)!==null&&s!==void 0?s:""]);break;default:break}}function Iv(e,t,r,n){if(!t)return e;let i=e.findIndex(o=>o.n==="Titles");if(i>=0){let o=e.slice();return o[i]=Qie(e[i],t,n),o}return r?[Xie(t,n),...e]:e}function Qie(e,t,r){let n=!1,i=e.c.map(o=>!n&&o.n==="Title"&&Zie(o,"LCID")===String(r)?(n=!0,{n:o.n,a:(0,$t.mergeAttrs)(o.a,[["Title",t]]),c:o.c}):o);return n||i.unshift(vx(t,r)),{n:e.n,a:e.a.map(o=>[o[0],o[1]]),c:i}}function Xie(e,t){return{n:"Titles",a:[],c:[vx(e,t)]}}function vx(e,t){return{n:"Title",a:[["LCID",String(t)],["Title",e]],c:[]}}function Zie(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function eoe(e){let t="0123456789abcdef",r="";for(let n=0;n<e;n+=1)r+=t[Math.floor(Math.random()*t.length)];return r}function Xp(e,t){e&&(typeof e.id!="string"||e.id.length===0)&&(e.id=`${t}_${eoe(8)}`)}function Ov(e){var t;Xp(e,"area");for(let r of(t=e.groups)!==null&&t!==void 0?t:[])wx(r)}function wx(e){var t;Xp(e,"group");for(let r of(t=e.subAreas)!==null&&t!==void 0?t:[])Xp(r,"subarea")}function toe(e=mx.DEFAULT_LCID){return{adapter:new Qp(e),api:px.appApi,languageSensitive:!0,publish:(t,r)=>(0,Uie.publishAppModule)(t,r),publishScope:t=>({envelope:"appmodule",targetIds:[t]}),rebaselineAfterPublish:"bracket"}}Vo.appRegistration=toe});var Ex={};nn(Ex,{ActionType:()=>Rv,AppActionOrigin:()=>Bv,AppActionVisibilityType:()=>Uv,ButtonType:()=>kv,CannotUpdateAppActionColumns:()=>roe,Context:()=>xv,IconType:()=>Lv,Location:()=>$v,OnClickEventType:()=>Mv,Scope:()=>Fv,VisibilityType:()=>Pv});var Pv,Rv,Lv,kv,$v,xv,Fv,Mv,Uv,Bv,roe,Ax=k(()=>{"use strict";(function(e){e[e.NotSupported=0]="NotSupported",e[e.Show=1]="Show",e[e.ClassicRules=2]="ClassicRules",e[e.Expression=3]="Expression"})(Pv||(Pv={}));(function(e){e[e.NotSupported=0]="NotSupported",e[e.None=1]="None",e[e.JavaScript=2]="JavaScript",e[e.Expression=3]="Expression"})(Rv||(Rv={}));(function(e){e[e.NoIcon=0]="NoIcon",e[e.UseIcon=1]="UseIcon",e[e.UseWebResource=2]="UseWebResource"})(Lv||(Lv={}));(function(e){e[e.Standard=0]="Standard",e[e.Dropdown=1]="Dropdown",e[e.Split=2]="Split",e[e.Group=3]="Group"})(kv||(kv={}));(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"})($v||($v={}));(function(e){e[e.All=0]="All",e[e.Entity=1]="Entity"})(xv||(xv={}));(function(e){e[e.App=0]="App",e[e.Entity=1]="Entity",e[e.Global=2]="Global"})(Fv||(Fv={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.JavaScript=2]="JavaScript"})(Mv||(Mv={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.ClassicRules=2]="ClassicRules"})(Uv||(Uv={}));(function(e){e[e.Default=0]="Default",e[e.Migrated=1]="Migrated",e[e.MigratedClone=2]="MigratedClone"})(Bv||(Bv={}));roe=["appactionid","appmoduleid","context","contextvalue","location","name","type","uniquename","isdisabled","origin"]});var Ox=v(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.assertOneWritePerRow=xt.commandApi=xt.COMMAND_DUPLICATE_ROW_CODE=xt.COMMAND_ROW_NOT_IN_BAR_CODE=xt.COMMAND_TABLE_MISMATCH_CODE=void 0;var qv=Tt(),Ur=fe(),eo=Q(),Br=oe();xt.COMMAND_TABLE_MISMATCH_CODE="COMMAND_TABLE_MISMATCH";xt.COMMAND_ROW_NOT_IN_BAR_CODE="COMMAND_ROW_NOT_IN_BAR";xt.COMMAND_DUPLICATE_ROW_CODE="COMMAND_DUPLICATE_ROW";var noe="OnClickEventJavaScriptWebResourceId($select=name,webresourceid),IconWebResourceId($select=name,webresourceid)";async function Vv(e,t){let r=`/EntityDefinitions(LogicalName='${(0,Br.odataPathLiteral)(t)}')${(0,Br.odataQuery)([["$select","MetadataId"]])}`,i=(0,Ur.ensureSuccess)(await e.get(r),e.apiUrl(r)).body,o=i?.MetadataId;return o?(0,Br.normalizeGuid)(o,"entityMetadataId"):""}function Gv(e,t){return t?`_contextentity_value eq ${t}`:`contextvalue eq '${(0,Br.odataLiteral)(e)}'`}function Cc(e){return`Nothing was written. Re-fetch the command with fetchArtifact('command', '${e}', { overwrite: true }) \u2014 this discards local edits \u2014 and re-apply the change.`}function Sx(e,t){let r=e.entityLogicalName;if(t===void 0)return r;if(typeof r!="string"||r.toLowerCase()!==t.toLowerCase())throw new eo.SdkError(xt.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': its JSON names table '${String(r)}'. A command's id is its table, so the push would write another table's command bar. Nothing was written. Fix its entityLogicalName, or push it under that table's id.`);return t}async function Nx(e,t,r){let n=await Vv(e,t);if(r){let i=(0,Br.normalizeGuid)(r,"entityMetadataId");if(i!==n)throw new eo.SdkError(xt.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': it was fetched for table id ${i}, but table '${t}' is ${n||"not resolvable"} on the server \u2014 the table was re-created, or the local copy edited. `+Cc(t))}return n}xt.commandApi={async get(e,t){let r=t,n=await Vv(e,r),i=Gv(r,n),o=`/appactions${(0,Br.odataQuery)([["$expand",noe],["$filter",i]])}`,a,s=await(0,qv.collectPages)(e,o,"fetchArtifact('command')",c=>{a=c}),l={entityLogicalName:r,entityMetadataId:n,appActions:s},u={};for(let c of s){let d=typeof c.appactionid=="string"?c.appactionid:void 0;if(d){let f=c["@odata.etag"];u[(0,Br.normalizeGuid)(d,"appactionid")]=typeof f=="string"?f:null}}return{raw:l,etag:a?(0,Ur.readEtag)(a):null,memberEtags:u}},async list(e,t){let r=t?.entityLogicalName;return r?[{type:"command",id:r,name:`${r} commands`,entityLogicalName:r,isDirty:!1}]:[]},async create(e,t,r){let n=t,i=Sx(n,r),o=await Nx(e,i,n.entityMetadataId);return _x(e,i,{...n,entityMetadataId:o},!1)},async update(e,t,r,n,i){let o=r,a=Sx(o,t),s=await Nx(e,a,o.entityMetadataId);return _x(e,a,{...o,entityMetadataId:s},!0,i)},async delete(e,t){let r=await Vv(e,t),n=`/appactions${(0,Br.odataQuery)([["$select","appactionid"],["$filter",Gv(t,r)]])}`,i=await(0,qv.collectPages)(e,n,"deleteArtifact('command')");for(let o of i)o.appactionid&&await(0,Ur.deleteRecord)(e,"appactions",o.appactionid)}};async function _x(e,t,r,n,i){let o=r.entityMetadataId?(0,Br.normalizeGuid)(r.entityMetadataId,"entityMetadataId"):"",a=await ooe(e,t,r,o,n,i),s={};try{await soe(e,a,o,s)}catch(l){throw(0,eo.withPartialTokens)(l,{memberEtags:s})}return{id:r.entityLogicalName,etag:null,memberEtags:s}}function Wv(e){return e.replace(/[{}]/g,"").toLowerCase()}function Ix(e,t){var r;let n=new Map,i=[...t.rows.map(o=>[o.appactionid,"written"]),...((r=t.deletedRowIds)!==null&&r!==void 0?r:[]).map(o=>[o,"deleted"])];for(let[o,a]of i){let s=Wv(o),l=n.get(s);if(l===void 0){n.set(s,a);continue}throw new eo.SdkError(xt.COMMAND_DUPLICATE_ROW_CODE,l===a?`Refusing to push command '${e}': app action '${s}' appears twice in it \u2014 two of its controls or groups carry that id, as one copied together with its id or bag does \u2014 so one would silently replace or remove the other. Nothing was written. Remove the id and the bag from the copy, so it is created as a new one, and push again.`:`Refusing to push command '${e}': app action '${s}' would be both written and deleted \u2014 one of its controls or groups spells that id differently (case or braces) than the copy last fetched or pushed \u2014 so the delete would remove what the write saved. Nothing was written. Spell the id as it was, and push again.`)}}xt.assertOneWritePerRow=Ix;var ioe={entities:/^\/entities\(([^()]+)\)$/,appactions:/^\/appactions\(([^()]+)\)$/};function Tx(e,t){let r=ioe[t].exec(e);return r?Wv(r[1]):void 0}async function ooe(e,t,r,n,i,o){var a,s;Ix(t,r);let l=loe(r.rows),u=new Set(l.map(f=>Wv(f.appactionid))),c={writes:[],deletes:[]};for(let f of l){let m=f.body["[email protected]"];if(m!==void 0&&!(typeof m=="string"&&n!==""&&Tx(m,"entities")===n))throw new eo.SdkError(xt.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': app action '${f.appactionid}' binds to ${typeof m=="string"?`'${m}'`:String(m)}, not to table '${t}' (${n?`/entities(${n})`:"whose id is not resolvable"}). `+Cc(t));let p=f.body["[email protected]"];if(typeof p=="string"){let h=Tx(p,"appactions");if(h===void 0||!u.has(h))throw new eo.SdkError(xt.COMMAND_ROW_NOT_IN_BAR_CODE,`Refusing to push command '${t}': app action '${f.appactionid}' would be placed under '${p}', which is not a row of this command. `+Cc(t))}if(i&&f.exists){let h=(0,Br.normalizeGuid)(f.appactionid,"id"),g=(a=o?.[h])!==null&&a!==void 0?a:f.etag;if(!(0,Ur.isVersionToken)(g))throw Dx(t,h,"update",g);c.writes.push({kind:"patch",row:f,id:h,token:g})}else{if(m===void 0&&!n)throw new eo.SdkError("COMMAND_CONTEXT_ENTITY_UNRESOLVED",`Cannot create app action '${f.appactionid}' for entity '${r.entityLogicalName}': the entity MetadataId could not be resolved, so the required ContextEntity bind cannot be set. A row written without it is created but is permanently unreadable \u2014 commandApi.get filters on _contextentity_value. Verify the entity logical name exists and is readable, then retry.`);c.writes.push({kind:"post",row:f})}}for(let f of(s=r.deletedRowIds)!==null&&s!==void 0?s:[]){let m=(0,Br.normalizeGuid)(f,"id"),p=o?.[m];if(!(0,Ur.isVersionToken)(p))throw Dx(t,m,"delete",p);c.deletes.push({id:m,token:p})}let d=[...c.writes.flatMap(f=>f.kind==="patch"?[{id:f.id,verb:"update"}]:[]),...c.deletes.map(f=>({id:f.id,verb:"delete"}))];if(d.length>0){let f=await aoe(e,t,n),m=d.find(p=>!f.has(p.id));if(m)throw new eo.SdkError(xt.COMMAND_ROW_NOT_IN_BAR_CODE,`Refusing to push command '${t}': it would ${m.verb} app action '${m.id}', which is not in table '${t}''s command bar on the server \u2014 a row of another table, or one deleted since the fetch. `+Cc(t))}return c}function Dx(e,t,r,n){return new eo.SdkError(Ur.UPDATE_NO_ETAG_CODE,`Refusing to push command '${e}': ${typeof n=="string"&&n!==""?`the token held for app action '${t}' ('${n}') is not a version`:`no token is held for app action '${t}'`}, so its ${r} could not be made conditional and would overwrite or remove a concurrent edit. `+Cc(e))}async function aoe(e,t,r){let n=`/appactions${(0,Br.odataQuery)([["$select","appactionid"],["$filter",Gv(t,r)]])}`,i=await(0,qv.collectPages)(e,n,"pushArtifact('command') bar membership"),o=new Set;for(let a of i)typeof a.appactionid=="string"&&o.add((0,Br.normalizeGuid)(a.appactionid,"appactionid"));return o}async function soe(e,t,r,n){for(let i of t.writes)if(i.kind==="patch"){let o=(0,Ur.echoWrite)("appactionid",{"If-Match":i.token}),a=`/appactions(${i.id})${o.query}`,s=(0,Ur.ensureSuccess)(await e.patch(a,i.row.body,o.options),e.apiUrl(a));n[i.id]=(0,Ur.readEtag)(s)}else{let o=(0,Ur.echoWrite)("appactionid"),a=`/appactions${o.query}`,s={...i.row.body};s["[email protected]"]===void 0&&(s["[email protected]"]=`/entities(${r})`);let l=(0,Ur.ensureSuccess)(await e.post(a,s,o.options),e.apiUrl(a)),u=(0,Ur.readCreatedId)(l,"appactionid");u&&(n[(0,Br.normalizeGuid)(u,"appactionid")]=(0,Ur.readEtag)(l))}for(let{id:i,token:o}of[...t.deletes].reverse())await(0,Ur.deleteRecord)(e,"appactions",i,o),delete n[i]}function loe(e){let t=new Map(e.map(o=>[o.appactionid,o])),r=new Set,n=[],i=o=>{if(r.has(o.appactionid))return;let a=o.body["[email protected]"];if(typeof a=="string"){let s=/\(([^)]+)\)/.exec(a),l=s?t.get(s[1]):void 0;l&&i(l)}r.add(o.appactionid),n.push(o)};return e.forEach(i),n}});var jx=v(Cl=>{"use strict";Object.defineProperty(Cl,"__esModule",{value:!0});Cl.commandRegistration=Cl.CommandAdapter=void 0;var mt=(Ax(),zr(Ex)),Px=jr(),St=cn(),kx=Ox(),$x=ct(),El=oe(),xx=Q(),Hv="$ClientSvg:",Kv=".svg",uoe=2,coe=1,doe=1,Fx="entityMetadataId",foe=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"]),Zp=class{toArtifact(t){var r,n,i,o,a,s,l;let u=(r=t.appActions)!==null&&r!==void 0?r:[],c=(n=t.entityLogicalName)!==null&&n!==void 0?n:"",d=u.find(h=>typeof h.appactionid!="string"||h.appactionid==="");if(d)throw new xx.InvalidArgumentError(`Cannot read the command bar of '${c}': app action row '${String((i=d.name)!==null&&i!==void 0?i:"")}' has no appactionid (its primary key), so it cannot be placed in the bar or written back.`);let f=new Map;for(let h of u){let g=typeof h._parentappactionid_value=="string"&&h._parentappactionid_value?h._parentappactionid_value:"",b=(o=f.get(g))!==null&&o!==void 0?o:[];b.push(h),f.set(g,b)}let m=new Map;for(let h of(a=f.get(""))!==null&&a!==void 0?a:[]){let g=yoe(h.location),b=(s=m.get(g))!==null&&s!==void 0?s:[];b.push(h),m.set(g,b)}let p=[];for(let[h,g]of m)p.push({location:h,groups:moe(g,f,qx(h),c)});return{id:c,entityLogicalName:c,commandBars:goe(p),bag:{a:[[Fx,(l=t.entityMetadataId)!==null&&l!==void 0?l:""]]}}}fromArtifact(t){return{entityLogicalName:t.entityLogicalName,entityMetadataId:Yv(t),appActions:zv(t).map(r=>r.row)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t,r){let n=new Set(r?zv(r).map(l=>l.appactionid):[]),i=zv(t,new Set([...n].map(l=>l.toLowerCase()))),o=new Set(i.map(l=>l.appactionid)),a=i.map(l=>{let u=l.exists||n.has(l.appactionid);return{appactionid:l.appactionid,exists:u,etag:l.etag,body:u?Ooe(l.row):zx(l.row)}}),s=[...n].filter(l=>!o.has(l));return(0,kx.assertOneWritePerRow)(t.entityLogicalName,{rows:a,deletedRowIds:s}),{entityLogicalName:t.entityLogicalName,entityMetadataId:Yv(t),rows:a,...s.length>0?{deletedRowIds:s}:{}}}createDefault(t){var r,n,i,o;let a=(n=(r=t.entityLogicalName)!==null&&r!==void 0?r:t.id)!==null&&n!==void 0?n:"";return{id:(i=t.id)!==null&&i!==void 0?i:a,entityLogicalName:a,commandBars:(o=t.commandBars)!==null&&o!==void 0?o:[]}}assignMissingIds(t){return(0,$x.assignMissingIds)(t)}normalize(t){let r=Coe(t),n=!1,i=(Array.isArray(t.commandBars)?t.commandBars:[]).map(o=>{let a=(0,St.isJsonObject)(o)&&Array.isArray(o.groups)?o.groups:void 0;if(!a)return o;let s=!1,l=a.map(u=>{let c=(0,St.isJsonObject)(u)&&Array.isArray(u.controls)?u.controls:void 0;if(!c)return u;let d=c.map(f=>Gx(f,r));return d.every((f,m)=>f===c[m])?u:(s=!0,{...u,controls:d})});return s?(n=!0,{...o,groups:l}):o});return n?{...t,commandBars:i}:t}validate(t){let r=[];return(0,St.childObjects)(t,"commandBars","","commandBar",r).forEach(({node:i,index:o})=>{let a=`/commandBars/${o}`;(0,St.optionalEnum)(i,"location",["MainTab","ContextualTab","HomeTab"],a,"bar-location-invalid",r),(0,St.childObjects)(i,"groups",a,"group",r).forEach(({node:l,index:u})=>{let c=`${a}/groups/${u}`;rm(l.bag)||((0,St.optionalGuidId)(l,"id",c,"group-id-invalid",r),typeof l.title=="string"&&l.title.length>0&&r.push({pointer:`${c}/title`,rule:"group-toplevel-title-unsupported",message:"a new top-level command group cannot have a title: Dataverse rejects a Group row with no parent (0x80040265). Leave the title empty to hold the commands without creating a group row, or nest them under a FlyoutAnchor control, which supplies the parent a group needs."})),Mx((0,St.childObjects)(l,"controls",c,"control",r),`${c}/controls`,r)})}),r}};Cl.CommandAdapter=Zp;function rm(e){let t=e?.a;return Array.isArray(t)&&t.length>0}function Mx(e,t,r){e.forEach(({node:n,index:i})=>{let o=`${t}/${i}`;rm(n.bag)||(0,St.optionalGuidId)(n,"id",o,"control-id-invalid",r),(0,St.optionalEnum)(n,"type",["Button","FlyoutAnchor","SplitButton"],o,"control-type-invalid",r);let a=n.location;a!==void 0&&(typeof a!="number"||!Number.isInteger(a)||a<0||a>6)&&r.push((0,St.issue)(`${o}/location`,"control-location-invalid",`location must be an integer 0-6 when present, got ${JSON.stringify(a)}`)),n.action!==void 0&&n.action!==null&&((0,St.isJsonObject)(n.action)?(0,St.optionalEnum)(n.action,"type",["javascript"],`${o}/action`,"action-type-invalid",r):r.push((0,St.issue)(`${o}/action`,"control-action-must-be-object",`a control action must be a JSON object when present, got ${typeof n.action}`)));let s=(0,St.childObjects)(n,"children",o,"control",r);s.length>0&&Mx(s,`${o}/children`,r)})}function Jv(e){return{a:Object.entries(e)}}function poe(e){return Object.fromEntries(e.a)}function Ec(e,t){if(e){for(let[r,n]of e.a)if(r===t)return n}}function Yv(e){let t=Ec(e.bag,Fx);return typeof t=="string"?t:""}function moe(e,t,r,n){var i,o;let a=[],s=[];for(let l of tm(e))l.type===mt.ButtonType.Group?a.push({id:Bx(l.name,n),title:typeof l.grouptitle=="string"?l.grouptitle:"",controls:tm((o=t.get((i=l.appactionid)!==null&&i!==void 0?i:""))!==null&&o!==void 0?o:[]).map(u=>em(u,t,r,n)),bag:Jv(l)}):s.push(em(l,t,r,n));return s.length>0&&a.unshift({id:Ioe(n,r),title:"",controls:s}),a}function Qv(e){let t=e.bag?Ec(e.bag,"appactionid"):void 0;return typeof t=="string"&&t.trim()!==""?t:e.id}function em(e,t,r,n){var i,o,a,s,l;let u=Bx(e.name,n),c={id:u,type:boe(e.type),label:typeof e.buttonlabeltext=="string"?e.buttonlabeltext:"",command:typeof e.appactionid=="string"?e.appactionid:u,bag:Jv(e)},d=Ux(e);d&&(c.icon=d);let f=hoe(e);f&&(c.action=f),typeof e.hidden=="boolean"&&(c.hidden=e.hidden),typeof e.isdisabled=="boolean"&&(c.disabled=e.isdisabled),typeof e.location=="number"&&e.location!==r&&(c.location=e.location);let m=t.get((i=e.appactionid)!==null&&i!==void 0?i:"");if(m&&m.length>0){let p=[],h=[];for(let g of tm(m))if(g.type===mt.ButtonType.Group){let b=(o=g.appactionid)!==null&&o!==void 0?o:"",w=Jv(g);c.flyoutGroupId===void 0&&(c.flyoutGroupId=(a=g.appactionid)!==null&&a!==void 0?a:void 0,c.flyoutGroupBag=w);let C=[];for(let S of tm((l=t.get((s=g.appactionid)!==null&&s!==void 0?s:""))!==null&&l!==void 0?l:[])){let O=em(S,t,r,n);p.push(O),C.push(Qv(O))}h.push({id:b,bag:w,childIds:C})}else p.push(em(g,t,r,n));c.children=p,h.length>1&&(c.flyoutGroups=h)}return c}function Ux(e){var t;if(!((t=e.IconWebResourceId)===null||t===void 0)&&t.name)return e.IconWebResourceId.name;if(e.fonticon)return e.fonticon.startsWith(Hv)?e.fonticon.slice(Hv.length)+Kv:e.fonticon}function hoe(e){var t;let r=e.onclickeventjavascriptfunctionname;if(typeof r!="string"||!r)return;let n=e.OnClickEventJavaScriptWebResourceId,i=e._onclickeventjavascriptwebresourceid_value,o={type:"javascript",webResourceId:(t=typeof i=="string"?i:n?.webresourceid)!==null&&t!==void 0?t:"",functionName:r};n?.name&&(o.libraryName=n.name);let a=e.onclickeventjavascriptparameters;return typeof a=="string"&&a&&(o.parameters=a),o}function Rx(e){return typeof e.sequence=="number"?e.sequence:typeof e.buttonsequencepriority=="number"?e.buttonsequencepriority:0}function tm(e){return[...e].sort((t,r)=>Rx(t)-Rx(r))}function goe(e){let t={MainTab:0,ContextualTab:1,HomeTab:2};return[...e].sort((r,n)=>{var i,o;return((i=t[r.location])!==null&&i!==void 0?i:9)-((o=t[n.location])!==null&&o!==void 0?o:9)})}function Bx(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 yoe(e){switch(e){case mt.Location.Form:case mt.Location.QuickForm:return"MainTab";case mt.Location.HomePageGrid:case mt.Location.Dashboard:return"HomeTab";default:return"ContextualTab"}}function qx(e){switch(e){case"MainTab":return mt.Location.Form;case"HomeTab":return mt.Location.HomePageGrid;default:return mt.Location.SubGridStandard}}function boe(e){switch(e){case mt.ButtonType.Dropdown:return"FlyoutAnchor";case mt.ButtonType.Split:return"SplitButton";default:return"Button"}}function voe(e){switch(e){case"FlyoutAnchor":return mt.ButtonType.Dropdown;case"SplitButton":return mt.ButtonType.Split;default:return mt.ButtonType.Standard}}function woe(e){var t;return e.bag&&e.bag.a.length>0?!0:((t=e.title)!==null&&t!==void 0?t:"").length>0}function Vx(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 zv(e,t=new Set){var r,n,i,o;let a=[],s=Yv(e);for(let l of(r=e.commandBars)!==null&&r!==void 0?r:[]){let u=qx(l.location),c=((n=l.groups)!==null&&n!==void 0?n:[]).flatMap(m=>{var p;return(p=m.controls)!==null&&p!==void 0?p:[]}),d=c.length>0&&c.every(m=>!Vx(m,t)),f=0;for(let m of(i=l.groups)!==null&&i!==void 0?i:[]){let p;if(woe(m)){let h=Aoe(m,u,void 0,e,s);a.push(h),p=h.appactionid}for(let h of(o=m.controls)!==null&&o!==void 0?o:[])Wx(h,u,p,e,s,a,d?f:void 0,t),f+=1}}return a}function Gx(e,t){if(!(0,St.isJsonObject)(e))return e;let r=e.children,n=r,i=!1;Array.isArray(r)&&(n=r.map(s=>Gx(s,t)),i=n.some((s,l)=>s!==r[l]));let o=!rm(e.bag)&&(typeof e.id!="string"||e.id.trim()==="");if(!o&&!i)return e;let a;if(o){do a=(0,$x.newId)();while(t.has(a));t.add(a)}return{...e,...a!==void 0?{id:a}:{},...i?{children:n}:{}}}function Coe(e){let t=new Set,r=(o,...a)=>{if((0,St.isJsonObject)(o))for(let s of[...a.map(l=>o[l]),rm(o.bag)?Ec(o.bag,"appactionid"):void 0])typeof s=="string"&&s.trim()!==""&&t.add(s.toLowerCase())},n=o=>{(0,St.isJsonObject)(o)&&(r(o,"id","flyoutGroupId"),r({bag:o.flyoutGroupBag}),(Array.isArray(o.flyoutGroups)?o.flyoutGroups:[]).forEach(a=>r(a,"id")),(Array.isArray(o.children)?o.children:[]).forEach(n))},i=e.commandBars;return(Array.isArray(i)?i:[]).forEach(o=>{let a=(0,St.isJsonObject)(o)?o.groups:void 0;(Array.isArray(a)?a:[]).forEach(s=>{r(s,"id");let l=(0,St.isJsonObject)(s)?s.controls:void 0;(Array.isArray(l)?l:[]).forEach(n)})}),t}function Wx(e,t,r,n,i,o,a,s=new Set){var l;let u=Eoe(e,t,r,n,i,a);o.push(u);let c=(l=e.children)!==null&&l!==void 0?l:[];if(c.length===0&&!(e.flyoutGroups&&e.flyoutGroups.length>0))return;let d=c.every(h=>!Vx(h,s)),f=(h,g,b)=>{Wx(h,t,g,n,i,o,d?b:void 0,s)},m=e.flyoutGroups;if(m&&m.length>0){let h=new Map(c.map(S=>[Qv(S),S])),g=new Set,b=0,w;for(let[S,O]of m.entries()){let L=O.id||(S===0?jv(u.appactionid):Zv("flyout-group",`${u.appactionid}#${S}`)),I=Lx(L,t,u.appactionid,n,i,O.bag);o.push(I);let D=I.appactionid;w===void 0&&(w=D);for(let P of O.childIds){let x=h.get(P);!x||g.has(P)||(g.add(P),f(x,D,b),b+=1)}}let C=w??jv(u.appactionid);for(let S of c){let O=Qv(S);g.has(O)||(g.add(O),f(S,C,b),b+=1)}return}let p=e.flyoutGroupId||jv(u.appactionid);o.push(Lx(p,t,u.appactionid,n,i,e.flyoutGroupBag));for(let[h,g]of c.entries())f(g,p,h)}function Eoe(e,t,r,n,i,o){let a=Xv(e,t,r,n,i),s=a.row;o!==void 0&&typeof s.sequence!="number"&&(s.sequence=o);let l=Ux(s);return e.location!==void 0&&(s.location=e.location),s.type=voe(e.type),s.buttonlabeltext=e.label,Noe(s,e.icon,l),Toe(s,e.action),_oe(s),e.hidden!==void 0&&(s.hidden=e.hidden),e.disabled!==void 0&&(s.isdisabled=e.disabled),{...a,row:s}}function Aoe(e,t,r,n,i){let o=Xv(e,t,r,n,i);return o.row.type=mt.ButtonType.Group,o.row.grouptitle=e.title,o}function Lx(e,t,r,n,i,o){let a=Xv({id:e,bag:o},t,r,n,i),s=a.row;return s["[email protected]"]=`/appactions(${(0,El.normalizeGuid)(r,"Command flyout group id")})`,s.type=mt.ButtonType.Group,s.grouptitle===void 0&&(s.grouptitle=""),s.isgrouptitlehidden===void 0&&(s.isgrouptitlehidden=!0),a}function Xv(e,t,r,n,i){let o,a,s,l;if(e.bag&&e.bag.a.length>0){o=poe(e.bag),a=!0;let u=Ec(e.bag,"@odata.etag");s=typeof u=="string"?u:null;let c=Ec(e.bag,"appactionid");l=typeof c=="string"&&c?c:e.id}else{if(typeof e.id!="string"||e.id.trim()==="")throw new xx.InvalidArgumentError(`Cannot serialize command '${n.entityLogicalName}': a new control has no id. Its primary key is minted once, before the first push, by normalize() \u2014 serialize the normalized artifact.`);l=e.id,o=Soe(l,t,n,i),a=!1,s=null}return r?o["[email protected]"]=`/appactions(${(0,El.normalizeGuid)(r,"Command parent appaction id")})`:a&&typeof o._parentappactionid_value=="string"&&o._parentappactionid_value&&o.type!==mt.ButtonType.Group&&(o["[email protected]"]=null),delete o._parentappactionid_value,{appactionid:l,exists:a,etag:s,row:o}}function Soe(e,t,r,n){let i={appactionid:e,name:`${e}!${e.replace(/-/g,"").slice(0,32)}`,uniquename:"",location:t,context:mt.Context.Entity,contextvalue:r.entityLogicalName,scope:mt.Scope.Entity};return n&&(i["[email protected]"]=`/entities(${(0,El.normalizeGuid)(n,"Command context entity metadata id")})`),i}function Noe(e,t,r){if(t===r){let n=e._iconwebresourceid_value;typeof n=="string"&&n&&!e.fonticon&&(e["[email protected]"]=`/webresourceset(${(0,El.normalizeGuid)(n,"Command icon web resource id")})`);return}if(t===void 0){e.fonticon="",e.IconWebResourceId=null;return}e.fonticon=t.toLowerCase().endsWith(Kv)?Hv+t.slice(0,t.length-Kv.length):t,e.IconWebResourceId=null}function _oe(e){let t=(n,i)=>{let o=e[n];if(typeof o!="string"||o.length===0||e[`${i}@odata.bind`]!==void 0)return;let a=(0,El.normalizeGuid)(o,`Command ${i}`);e[`${i}@odata.bind`]=`/canvasapps(${a})`};e.onclickeventtype===coe&&t("_onclickeventformulacomponentlibraryid_value","OnClickEventFormulaComponentLibraryId");let r=e.visibilitytype;(!r||r===doe)&&t("_visibilityformulacomponentlibraryid_value","VisibilityFormulaComponentLibraryId")}function Toe(e,t){if(!(!t||t.type!=="javascript")){if(e.onclickeventtype=uoe,t.webResourceId){let r=(0,El.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 Doe(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 Zv(e,t){let r="";for(let n=0;n<4;n+=1)r+=Doe(`${n}:${e}:${t}`).toString(16).padStart(8,"0");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`}function jv(e){return Zv("flyout-group",e)}function Ioe(e,t){return Zv("loose-group",`${e}|${t}`)}function zx(e){let t={...e};for(let r of foe)delete t[r];return t}function Ooe(e){let t=zx(e);for(let r of mt.CannotUpdateAppActionColumns)delete t[r];return t}function Poe(){return{adapter:new Zp,api:kx.commandApi,publish:(e,t,r)=>(0,Px.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,Px.boundEntityPublishScope)(t)}}Cl.commandRegistration=Poe});var Kx=v(nm=>{"use strict";Object.defineProperty(nm,"__esModule",{value:!0});nm.chartApi=void 0;var Roe=Tt(),qr=fe(),$a=oe(),Hx="savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault",Loe="savedqueryvisualizationid,name,primaryentitytypecode,charttype,isdefault";nm.chartApi={async get(e,t){let r=(0,$a.normalizeGuid)(t,"id"),n=await(0,qr.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r),i=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,$a.odataQuery)([["$select",Hx]]);return{raw:(0,qr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},async readContentThenToken(e,t){let r=(0,$a.normalizeGuid)(t,"id"),n=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,$a.odataQuery)([["$select",Hx]]),i=(0,qr.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=await(0,qr.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r);return{raw:i.body,etag:o}},async list(e,t){let r=`/savedqueryvisualizations${(0,$a.odataQuery)([["$select",Loe],["$filter",t?.entityLogicalName?`primaryentitytypecode eq '${(0,$a.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,Roe.collectPages)(e,r,"listArtifacts('chart')")).map(i=>{var o,a;return{type:"chart",id:(o=i.savedqueryvisualizationid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",entityLogicalName:i.primaryentitytypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,qr.echoWrite)("savedqueryvisualizationid"),o=`/savedqueryvisualizations${i.query}`,a=(0,qr.ensureSuccess)(await e.post(o,(0,qr.withClientMintedId)({name:n.name,description:n.description,datadescription:n.datadescription,presentationdescription:n.presentationdescription,primaryentitytypecode:n.primaryentitytypecode,charttype:n.charttype,isdefault:n.isdefault},"savedqueryvisualizationid",r),i.options),e.apiUrl(o));return{id:(0,qr.resolveCreatedId)(a,"savedqueryvisualizationid","chart",r),etag:(0,qr.readEtag)(a)}},async update(e,t,r,n){let i=r,o=(0,$a.normalizeGuid)(t,"id"),a=(0,qr.echoWrite)("savedqueryvisualizationid",{"If-Match":(0,qr.requireEtag)(n,"chart",o)}),s=`/savedqueryvisualizations(${o})${a.query}`,l=(0,qr.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,datadescription:i.datadescription,presentationdescription:i.presentationdescription},a.options),e.apiUrl(s));return{id:o,etag:(0,qr.readEtag)(l)}},delete(e,t){return(0,qr.deleteRecord)(e,"savedqueryvisualizations",t)}}});var dF=v(Sl=>{"use strict";Object.defineProperty(Sl,"__esModule",{value:!0});Sl.chartRegistration=Sl.ChartAdapter=void 0;var ew=wo(),Jx=cn(),gi=Eo(),Yx=jr(),koe=Kx(),tw=Co(),$oe=ct(),xoe=["Column","StackedColumn","StackedColumn100","Bar","StackedBar","StackedBar100","Area","StackedArea","StackedArea100","Line","Pie","Doughnut","Funnel","Tag"],Foe=new Map(xoe.map(e=>[e.toLowerCase(),e]));function tF(e){var t;return e&&(t=Foe.get(e.toLowerCase()))!==null&&t!==void 0?t:"Column"}function Moe(){return'<Chart Palette="BrightPastel"><Series><Series ChartType="Column" ChartArea="Default" /></Series><ChartAreas><ChartArea Name="Default" /></ChartAreas><Legends><Legend Name="Default" /></Legends></Chart>'}function Uoe(e){var t,r;let n=e.entityLogicalName,i=e.series.map((h,g)=>({alias:`agg_${g}`,series:h})),o=e.categories.map((h,g)=>({alias:`grp_${g}`,category:h})),a=h=>`<attribute alias="${h.alias}" name="${Al(h.series.attribute)}" aggregate="${Al(h.series.aggregate)}" />`,s=h=>`<attribute alias="${h.alias}" name="${Al(h.category.attribute)}" groupby="true"${h.category.dateGrouping?` dategrouping="${Al(h.category.dateGrouping)}"`:""} />`,l=[],u=new Map,c=(h,g)=>{if(!h){l.push(g);return}let b=u.get(h);b?b.push(g):u.set(h,[g])};i.forEach(h=>c(h.series.relatedEntity,a(h))),o.forEach(h=>c(h.category.relatedEntity,s(h)));let d=[...u.entries()].map(([h,g])=>`<link-entity name="${Al(h)}">${g.join("")}</link-entity>`).join(""),f=l.join("")+d,m=i.map(h=>`<measurecollection><measure alias="${h.alias}" /></measurecollection>`).join(""),p=(r=(t=o[0])===null||t===void 0?void 0:t.alias)!==null&&r!==void 0?r:"";return`<datadefinition><fetchcollection><fetch mapping="logical" aggregate="true"><entity name="${Al(n)}">${f}</entity></fetch></fetchcollection><categorycollection><category alias="${p}">${m}</category></categorycollection></datadefinition>`}var im=class{toArtifact(t){var r,n,i,o,a,s,l;(0,tw.installDomShim)();let u=(r=t.datadescription)!==null&&r!==void 0?r:"",c=(n=t.presentationdescription)!==null&&n!==void 0?n:"",d=(0,gi.parseXmlRoot)(u,"<datadefinition/>"),f=(0,gi.parseXmlRoot)(c,"<Chart/>");return{id:(i=t.savedqueryvisualizationid)!==null&&i!==void 0?i:"",name:(o=t.name)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",entityLogicalName:(s=t.primaryentitytypecode)!==null&&s!==void 0?s:"",chartType:om(f),isDefault:(l=t.isdefault)!==null&&l!==void 0?l:!1,series:iF(d),categories:oF(d),presentation:rF(f),dataBag:u?(0,gi.projectElementBag)(d):void 0,presentationBag:c?(0,gi.projectElementBag)(f):void 0,rowBag:Boe(t.charttype,t.type)}}fromArtifact(t){(0,tw.installDomShim)();let{datadescription:r,presentationdescription:n}=qoe(t);return{savedqueryvisualizationid:t.id,name:t.name,description:t.description,primaryentitytypecode:t.entityLogicalName,datadescription:r,presentationdescription:n,charttype:Qx(t.rowBag,"charttype"),type:Qx(t.rowBag,"type"),isdefault:t.isDefault}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){var r,n,i,o,a,s,l;let u=this.fromArtifact(t);return{name:(r=u.name)!==null&&r!==void 0?r:"",description:(n=u.description)!==null&&n!==void 0?n:"",datadescription:(i=u.datadescription)!==null&&i!==void 0?i:"",presentationdescription:(o=u.presentationdescription)!==null&&o!==void 0?o:"",primaryentitytypecode:(a=u.primaryentitytypecode)!==null&&a!==void 0?a:"",charttype:(s=u.charttype)!==null&&s!==void 0?s:0,isdefault:(l=u.isdefault)!==null&&l!==void 0?l:!1}}createDefault(t){var r,n,i,o,a,s,l;(0,tw.installDomShim)();let u=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,$oe.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New Chart",description:(o=t.description)!==null&&o!==void 0?o:"",entityLogicalName:u,chartType:(a=t.chartType)!==null&&a!==void 0?a:"Column",isDefault:(s=t.isDefault)!==null&&s!==void 0?s:!1,series:t.series&&t.series.length>0?t.series:[{attribute:"createdon",aggregate:"count"}],categories:t.categories&&t.categories.length>0?t.categories:[{attribute:"createdon",dateGrouping:"month"}],presentation:(l=t.presentation)!==null&&l!==void 0?l:{palette:"BrightPastel",showLegend:!0}}}assignMissingIds(t){return t}validate(t){let r=[],n=t;return(0,Jx.childObjects)(n,"series","","series",r),(0,Jx.childObjects)(n,"categories","","category",r),r}};Sl.ChartAdapter=im;function Boe(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 Qx(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 om(e){let t=e.getElementsByTagName("Series");for(let r=0;r<t.length;r+=1)if(t[r].getAttribute("ChartType"))return tF(t[r].getAttribute("ChartType"));return"Column"}function rF(e){var t;let r={showLegend:e.getElementsByTagName("Legend").length>0},n=e.getAttribute("Palette");n&&(r.palette=n);let i=e.getElementsByTagName("Title")[0],o=((t=i?.textContent)!==null&&t!==void 0?t:"").trim();return o&&(r.title=o),r}function am(e){return e.getElementsByTagName("fetch")[0]}function nF(e){let t=new Map;if(!e)return t;let r=e.getElementsByTagName("link-entity");for(let n=0;n<r.length;n+=1){let i=r[n],o=i.getAttribute("name");if(!o)continue;let a=i.getElementsByTagName("attribute");for(let s=0;s<a.length;s+=1){let l=a[s],u=l.getAttribute("alias")||l.getAttribute("name");u&&t.set(u,o)}}return t}function iF(e){let t=am(e);if(!t)return[];let r=nF(t),n=t.getElementsByTagName("attribute"),i=[];for(let o=0;o<n.length;o+=1){let a=n[o],s=a.getAttribute("aggregate");if(!s)continue;let l=a.getAttribute("name");if(!l)continue;let u={attribute:l,aggregate:s},c=a.getAttribute("charttype");c&&(u.seriesType=tF(c));let d=a.getAttribute("alias");d&&(u.alias=d);let f=d||l,m=r.get(f);m&&(u.relatedEntity=m),i.push(u)}return i}function oF(e){var t;let r=am(e);if(!r)return[];let n=nF(r),i=r.getElementsByTagName("attribute"),o=[];for(let a=0;a<i.length;a+=1){let s=i[a];if(((t=s.getAttribute("groupby"))!==null&&t!==void 0?t:"").toLowerCase()!=="true")continue;let l=s.getAttribute("name");if(!l)continue;let u={attribute:l},c=s.getAttribute("dategrouping");c&&(u.dateGrouping=c);let d=s.getAttribute("alias");d&&(u.alias=d);let f=d||l,m=n.get(f);m&&(u.relatedEntity=m),o.push(u)}return o}function qoe(e){var t,r;let n=(t=e.series)!==null&&t!==void 0?t:[],i=(r=e.categories)!==null&&r!==void 0?r:[];if(!Xx(e.dataBag)||!Xx(e.presentationBag)){let c=Uoe({...e,series:n,categories:i});return{datadescription:c,presentationdescription:aae(e,c)}}let o=new DOMParser().parseFromString("<root/>","text/xml"),a=Zx(e.dataBag,"datadefinition",o),s=Zx(e.presentationBag,"Chart",o),l=e.chartType||om(s),u=iF(a);if(!rw(n,u)){let c=nw(a);Voe(o,a,n);let d=nw(a),f=d.length>0?d:n.map(()=>"");aF(o,s,f,c,l)}return rw(i,oF(a))||Goe(o,a,i),e.chartType&&e.chartType!==om(s)&&uF(s,e.chartType),e.presentation&&!rw(e.presentation,rF(s))&&cF(s,e.presentation),{datadescription:(0,gi.serializeNode)(a),presentationdescription:(0,gi.serializeNode)(s)}}function Xx(e){return!!e&&(e.c.length>0||e.a.length>0)}function aF(e,t,r,n,i){let o,a=t.childNodes;for(let d=0;d<a.length;d+=1)if(a[d].nodeType===1&&a[d].tagName==="Series"){o=a[d];break}o||(o=e.createElement("Series"),t.insertBefore(o,t.firstChild));let s=[],l=o.childNodes;for(let d=0;d<l.length;d+=1)l[d].nodeType===1&&l[d].tagName==="Series"&&s.push(l[d]);let u=new Map;n.forEach((d,f)=>{let m=s[f];if(!m)return;let p=u.get(d);p?p.push(m):u.set(d,[m])});let c=r.map(d=>{let f=u.get(d),m=f&&f.length>0?f.shift():void 0;if(m)return m;let p=e.createElement("Series");p.setAttribute("ChartType",i);let h=s.length>0?s[0].getAttribute("ChartArea"):null;return h&&p.setAttribute("ChartArea",h),p});for(let d of s)o.removeChild(d);for(let d of c)o.appendChild(d)}function nw(e){let t=[],r=e.getElementsByTagName("measure");for(let n=0;n<r.length;n+=1)t.push(r[n].getAttribute("alias")||"");return t}function Zx(e,t,r){let n={n:t,a:(0,ew.mergeAttrs)(e.a,[]),c:(0,ew.spliceChildren)(e.c,[])};return(0,ew.rebuildRaw)(n,(0,gi.domEngine)(r),null)}function Voe(e,t,r){let n=am(t),i=n?.getElementsByTagName("entity")[0];!n||!i||sF(e,t,i,Yoe(n),r,Xoe,{aliasPrefix:"aggregate_column",addRef:joe,removeRef:Joe})}function Goe(e,t,r){let n=am(t),i=n?.getElementsByTagName("entity")[0];!n||!i||sF(e,t,i,Qoe(n),r,Zoe,{aliasPrefix:"groupby_column",addRef:Hoe,removeRef:Koe})}function sF(e,t,r,n,i,o,a){let s=new Map;for(let m of n){let p=m.getAttribute("alias");p&&s.set(p,m)}let l=new Set,u=[],c=(m,p)=>{var h;let g=eae(r,m),b=p.relatedEntity;(g??void 0)!==(b??void 0)&&((h=m.parentNode)===null||h===void 0||h.removeChild(m),eF(e,r,m,b))};for(let m of i){let p=m.alias?s.get(m.alias):void 0;p&&!l.has(p)?(o(p,m),c(p,m),l.add(p)):u.push(m)}let d=n.filter(m=>!l.has(m)),f=0;for(let m of u)if(f<d.length){let p=d[f];o(p,m),c(p,m),l.add(p),f+=1}else{let p=e.createElement("attribute"),h=m.alias||zoe(t,a.aliasPrefix);p.setAttribute("alias",h),o(p,m),eF(e,r,p,m.relatedEntity),a.addRef(e,t,h)}for(let m of n)if(!l.has(m)){let p=m.getAttribute("alias");p&&a.removeRef(t,p),rae(m)}}function Woe(e){let t=new Set;for(let r of["attribute","measure","category"]){let n=e.getElementsByTagName(r);for(let i=0;i<n.length;i+=1){let o=n[i].getAttribute("alias");o&&t.add(o)}}return t}function zoe(e,t){let r=Woe(e);if(!r.has(t))return t;for(let n=2;;n+=1){let i=`${t}_${n}`;if(!r.has(i))return i}}function lF(e,t){let r=t.getElementsByTagName("categorycollection")[0];if(r)return r;let n=e.createElement("categorycollection");return t.appendChild(n),n}function joe(e,t,r){let n=lF(e,t),i=n.getElementsByTagName("category")[0];i||(i=e.createElement("category"),n.appendChild(i));let o=e.createElement("measurecollection"),a=e.createElement("measure");a.setAttribute("alias",r),o.appendChild(a),i.appendChild(o)}function Hoe(e,t,r){let n=lF(e,t),i=e.createElement("category");i.setAttribute("alias",r),n.appendChild(i)}function Koe(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 Joe(e,t){var r;let n=e.getElementsByTagName("measure"),i=[];for(let o=0;o<n.length;o+=1)n[o].getAttribute("alias")===t&&i.push(n[o]);for(let o of i){let a=o.parentNode;a?.removeChild(o),a&&a.tagName==="measurecollection"&&!iae(a)&&((r=a.parentNode)===null||r===void 0||r.removeChild(a))}}function Yoe(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 Qoe(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 Xoe(e,t){e.setAttribute("name",t.attribute),e.setAttribute("aggregate",t.aggregate),t.seriesType&&e.setAttribute("charttype",t.seriesType)}function Zoe(e,t){e.setAttribute("name",t.attribute),e.setAttribute("groupby","true"),t.dateGrouping?e.setAttribute("dategrouping",t.dateGrouping):e.hasAttribute("dategrouping")&&e.removeAttribute("dategrouping")}function eae(e,t){let r=t.parentNode;for(;r&&r!==e;){let n=r;if(n.nodeType===1&&n.tagName==="link-entity")return n.getAttribute("name")||void 0;r=n.parentNode}}function eF(e,t,r,n){n?tae(e,t,n).appendChild(r):t.appendChild(r)}function tae(e,t,r){let n=t.getElementsByTagName("link-entity");for(let o=0;o<n.length;o+=1)if(n[o].getAttribute("name")===r)return n[o];let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function rae(e){let t=e.parentNode;if(t&&(t.removeChild(e),t.tagName==="link-entity"&&!nae(t))){let r=t.parentNode;r&&r.removeChild(t)}}function nae(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 iae(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1)if(t[r].nodeType===1)return!0;return!1}function uF(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(!oae(r[i])){r[i].setAttribute("ChartType",t);return}}}function oae(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 cF(e,t){var r;let n=e.ownerDocument;if(t.palette!==void 0&&e.setAttribute("Palette",t.palette),t.showLegend!==void 0){let i=e.getElementsByTagName("Legend").length>0;if(t.showLegend&&!i){let o=e.getElementsByTagName("Legends")[0];o||(o=n.createElement("Legends"),e.appendChild(o));let a=n.createElement("Legend");a.setAttribute("Name","Default"),o.appendChild(a)}else if(!t.showLegend)for(let o of["Legends","Legend"]){let a=[],s=e.getElementsByTagName(o);for(let l=0;l<s.length;l+=1)a.push(s[l]);for(let l of a)(r=l.parentNode)===null||r===void 0||r.removeChild(l)}}if(t.title!==void 0){let i=e.getElementsByTagName("Title")[0];i&&(i.textContent=t.title)}}function aae(e,t){let r=(0,gi.parseXmlRoot)(Moe(),"<Chart/>"),n=e.chartType||om(r);uF(r,n),e.presentation&&cF(r,e.presentation);let i=nw((0,gi.parseXmlRoot)(t,"<datadefinition/>"));return i.length>0&&aF(r.ownerDocument,r,i,i.slice(0,1),n),(0,gi.serializeNode)(r)}function rw(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Al(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function sae(){return{adapter:new im,api:koe.chartApi,publish:(e,t,r)=>(0,Yx.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,Yx.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}Sl.chartRegistration=sae});var hF=v(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.dashboardApi=xa.dashboardEntity=void 0;var lae=Tt(),Go=fe(),Nl=oe(),uae=Jg(),fF=vu();function pF(e){return e&&e.toLowerCase()!=="none"?e:void 0}xa.dashboardEntity=pF;var mF="formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber",cae={select:mF,required:["name","type","objecttypecode","istabletenabled"]},dae="formid,name,type,objecttypecode",fae=0,pae=10;xa.dashboardApi={async get(e,t){let r=(0,Nl.normalizeGuid)(t,"id"),n=`/systemforms(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Nl.odataQuery)([["$select",mF]]),i=(0,Go.ensureSuccess)(await e.get(n),e.apiUrl(n));return(0,fF.assertSystemFormRecordKind)(i.body,r,"dashboard","fetch"),{raw:i.body,etag:(0,Go.readEtag)(i)}},async list(e,t){let r=[`(type eq ${fae} or type eq ${pae})`];t?.entityLogicalName&&r.push(`objecttypecode eq '${(0,Nl.odataLiteral)(t.entityLogicalName)}'`);let n=`/systemforms${(0,Nl.odataQuery)([["$select",dae],["$filter",r.join(" and ")]])}`;return(await(0,lae.collectPages)(e,n,"listArtifacts('dashboard')")).map(o=>{var a,s;let l=pF(o.objecttypecode);return{type:"dashboard",id:(a=o.formid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",...l?{entityLogicalName:l}:{},isDirty:!1}})},async create(e,t,r){let n=t,i=(0,Go.echoWrite)("formid"),o=`/systemforms${i.query}`,a={name:n.name,description:n.description,formxml:n.formxml,istabletenabled:n.istabletenabled,type:n.type};n.objecttypecode&&(a.objecttypecode=n.objecttypecode);let s=(0,Go.ensureSuccess)(await e.post(o,(0,Go.withClientMintedId)(a,"formid",r),i.options),e.apiUrl(o));return{id:(0,Go.resolveCreatedId)(s,"formid","dashboard",r),etag:(0,Go.readEtag)(s)}},async update(e,t,r,n){let i=r;return(0,uae.patchSystemForm)(e,(0,Nl.normalizeGuid)(t,"id"),"dashboard",{name:i.name,description:i.description,formxml:i.formxml,istabletenabled:i.istabletenabled},n,cae)},readContentThenToken(e,t){return xa.dashboardApi.get(e,t)},async delete(e,t){let r=(0,Nl.normalizeGuid)(t,"id");return await(0,fF.assertSystemFormKind)(e,r,"dashboard"),(0,Go.deleteRecord)(e,"systemforms",r)}}});var DF=v(yi=>{"use strict";Object.defineProperty(yi,"__esModule",{value:!0});yi.dashboardRegistration=yi.TILE_CLASS_ID=yi.DashboardAdapter=void 0;var Sc=wo(),En=Eo(),iw=jr(),Ac=cn(),CF=hF(),ow=Co(),Fa=ct(),EF=oe(),AF=sa(),mae=yb(),gF="0",aw="10",hae=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"]]),gae="{3FF9A528-DD50-4ACA-8F10-2E5ED73513AD}",lm=class{constructor(t=AF.DEFAULT_LCID){this.lcid=t}toArtifact(t){var r,n,i,o,a;(0,ow.installDomShim)();let s=(r=t.formxml)!==null&&r!==void 0?r:"",l=(0,En.parseXmlRoot)(s,"<form/>");return{id:(n=t.formid)!==null&&n!==void 0?n:"",name:(i=t.name)!==null&&i!==void 0?i:"",description:(o=t.description)!==null&&o!==void 0?o:"",dashboardType:yae(t.type),entityLogicalName:(a=(0,CF.dashboardEntity)(t.objecttypecode))!==null&&a!==void 0?a:null,enabledForMobile:!!t.istabletenabled,layoutType:bae(l),components:yF(l,this.lcid),bag:(0,En.projectElementBag)(l)}}fromArtifact(t){var r;return(0,ow.installDomShim)(),{formid:t.id,name:t.name,description:t.description,type:t.dashboardType==="Interactive"?aw:gF,objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",istabletenabled:t.enabledForMobile,formxml:bF(t,this.lcid)}}fromApiResponse(t){return this.toArtifact(t??{})}completeAsStored(t,r){return(0,mae.completeRecordAsStored)(t,r,this.lcid)}toApiPayload(t){return{name:t.name,description:t.description,formxml:bF(t,this.lcid),istabletenabled:t.enabledForMobile,type:t.dashboardType==="Interactive"?aw:gF,objecttypecode:t.entityLogicalName}}createDefault(t){var r,n,i,o,a,s,l,u;(0,ow.installDomShim)();let c=(0,En.parseXmlRoot)(Pae(),"<form/>");return{id:(r=t.id)!==null&&r!==void 0?r:(0,Fa.newId)(),name:(n=t.name)!==null&&n!==void 0?n:"New Dashboard",description:(i=t.description)!==null&&i!==void 0?i:"",dashboardType:(o=t.dashboardType)!==null&&o!==void 0?o:"Standard",entityLogicalName:(a=t.entityLogicalName)!==null&&a!==void 0?a:null,enabledForMobile:(s=t.enabledForMobile)!==null&&s!==void 0?s:!1,layoutType:(l=t.layoutType)!==null&&l!==void 0?l:0,components:(u=t.components)!==null&&u!==void 0?u:yF(c,this.lcid),bag:(0,En.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,Fa.newId)())}return t}validate(t){let r=[],n=(0,Ac.childObjects)(t,"components","","component",r),i=new Set;return n.forEach(({node:o,index:a})=>{let s=`/components/${a}`;for(let l of["position","parameters"]){let u=o[l];u!==void 0&&!(0,Ac.isJsonObject)(u)&&r.push((0,Ac.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,Ac.isJsonObject)(o.position)){let l=Nc(o.position);i.has(l)?r.push((0,Ac.issue)(`${s}/position`,"component-position-collision",`two components occupy the same dashboard position (${l}); move one to a free cell`)):i.add(l)}}),r}};yi.DashboardAdapter=lm;function yae(e){return String(e??"")===aw?"Interactive":"Standard"}function bae(e){let t=e?.getAttribute("formLayout")||e?.getAttribute("layoutType"),r=parseInt(t??"",10);return Number.isNaN(r)?0:r}function se(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName.toLowerCase()===t&&r.push(o)}return r}function yF(e,t){let r=[];return se(e,"tabs").flatMap(i=>se(i,"tab")).forEach((i,o)=>{se(i,"columns").flatMap(s=>se(s,"column")).forEach((s,l)=>{se(s,"sections").flatMap(c=>se(c,"section")).forEach((c,d)=>{vae(c,{tabIndex:o,columnIndex:l,sectionIndex:d},r,t)})})}),r}function vae(e,t,r,n){se(e,"rows").flatMap(o=>se(o,"row")).forEach((o,a)=>{se(o,"cell").forEach((s,l)=>{let u=wae(s,{...t,rowIndex:a,cellIndex:l},n);u&&r.push(u)})})}function wae(e,t,r){var n,i;let o=_F((n=e.getAttribute("id"))!==null&&n!==void 0?n:"");if(o.toLowerCase().startsWith("spacer"))return null;let a=se(e,"control")[0];if(!a)return null;let s=(i=a.getAttribute("classid"))!==null&&i!==void 0?i:"",l=Aae(a),u=Sae(s,l,a),c=Cae(a);return{id:a.getAttribute("id")||o,type:u,name:NF(e,r),classId:s,position:t,colspan:um(e,"colspan",1),rowspan:um(e,"rowspan",1),parameters:l,bag:(0,En.projectElementBag)(e),...c?{icProperties:c}:{}}}function SF(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 Cae(e){let t=SF(e);return t?(0,En.serializeNode)(t):void 0}function Eae(e,t,r){let n=SF(t);if(!r){n&&t.removeChild(n);return}let i=new DOMParser().parseFromString(r,"text/xml").documentElement,o=(0,Sc.rebuildRaw)((0,Sc.rawFromNode)((0,En.nodeLikeFromDom)(i)),(0,En.domEngine)(e),null);n&&(0,En.serializeNode)(n)===(0,En.serializeNode)(o)||(n?t.replaceChild(o,n):t.appendChild(o))}function NF(e,t){var r,n;let i=se(e,"labels")[0];if(!i)return"";let o=se(i,"label"),a=(r=o.find(s=>s.getAttribute("languagecode")===String(t)))!==null&&r!==void 0?r:o[0];return(n=a?.getAttribute("description"))!==null&&n!==void 0?n:""}function Aae(e){var t;let r={},n=se(e,"parameters")[0];if(!n)return r;let i=n.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];a.nodeType===1&&(r[a.tagName]=((t=a.textContent)!==null&&t!==void 0?t:"").trim())}return r}function Sae(e,t,r){var n;let i=hae.get(e.toUpperCase());return i?i==="chart"?t.ChartGridMode==="Chart"?"chart":"list":i==="assistant"?((n=r.getAttribute("uniqueid"))!==null&&n!==void 0?n:"").toUpperCase()===gae?"assistant":t.ChartGridMode!==void 0||r.getAttribute("indicationOfSubgrid")==="true"?t.ChartGridMode==="Chart"?"chart":"list":"unknown":i:"unknown"}function um(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 _F(e){return e.replace(/^\{/,"").replace(/\}$/,"")}function Nae(e,t){let r={n:"form",a:(0,Sc.mergeAttrs)(e.bag.a,[]),c:(0,Sc.spliceChildren)(e.bag.c,[])};return(0,Sc.rebuildRaw)(r,(0,En.domEngine)(t),null)}function bF(e,t){let r=new DOMParser().parseFromString("<root/>","text/xml"),n=Nae(e,r);return Dae(r,n,e.components,t),_ae(r,n,e.components,t),(0,En.serializeNode)(n)}function _ae(e,t,r,n){let i=TF(t);for(let o of r)i.has(Nc(o.position))||Tae(e,t,o,n)}function Tae(e,t,r,n){var i,o,a,s;let l=(o=(i=r.position)===null||i===void 0?void 0:i.sectionIndex)!==null&&o!==void 0?o:0,u=Rae(t,e,l);for(let x of se(u,"row"))se(x,"cell").some(K=>se(K,"control").length>0)||u.removeChild(x);let c=r.classId||yi.TILE_CLASS_ID[r.type]||yi.TILE_CLASS_ID.iframe,d=r.rowspan&&r.rowspan>0?r.rowspan:4,f=r.bag&&vF(r.bag,"id")?String(vF(r.bag,"id")):sm((0,Fa.newId)()),m=r.id?sm(r.id):sm((0,Fa.newId)()),p=u.parentNode,h=Math.max(1,parseInt(p&&p.getAttribute&&p.getAttribute("columns")||"1",10)||1),g=Math.min(Math.max(1,r.colspan&&r.colspan>0?r.colspan:1),h),b=se(u,"row"),w=b[b.length-1],C=w?se(w,"cell").reduce((x,K)=>x+um(K,"colspan",1),0):0;(!w||C+g>h)&&(w=e.createElement("row"),u.appendChild(w));let S=e.createElement("cell");S.setAttribute("id",f),S.setAttribute("colspan",String(g)),S.setAttribute("rowspan",String(d)),S.setAttribute("showlabel","true");let O=e.createElement("labels"),L=e.createElement("label");L.setAttribute("description",(a=r.name)!==null&&a!==void 0?a:""),L.setAttribute("languagecode",String(n)),O.appendChild(L),S.appendChild(O);let I=e.createElement("control");I.setAttribute("id",m),I.setAttribute("classid",sm(c));let D=e.createElement("parameters"),P=(s=r.parameters)!==null&&s!==void 0?s:{};for(let x of Object.keys(P)){let K=(0,EF.createSafeXmlElement)(e,x,"dashboard tile parameter");K.textContent=P[x],D.appendChild(K)}I.appendChild(D),S.appendChild(I),w.appendChild(S)}function vF(e,t){if(!e)return;let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function Dae(e,t,r,n){var i;let o=TF(t),a=new Set(r.map(s=>Nc(s.position)));for(let s of r){let l=o.get(Nc(s.position));if(!l)continue;let u=se(l,"control")[0];u&&(Iae(e,l,s.name,n),Oae(e,u,s.parameters),wF(l,"colspan",s.colspan),wF(l,"rowspan",s.rowspan),s.icProperties!==void 0&&Eae(e,u,s.icProperties))}for(let[s,l]of o)a.has(s)||(i=l.parentNode)===null||i===void 0||i.removeChild(l)}function TF(e){let t=new Map;return se(e,"tabs").flatMap(n=>se(n,"tab")).forEach((n,i)=>{se(n,"columns").flatMap(a=>se(a,"column")).forEach((a,s)=>{se(a,"sections").flatMap(u=>se(u,"section")).forEach((u,c)=>{se(u,"rows").flatMap(f=>se(f,"row")).forEach((f,m)=>{se(f,"cell").forEach((p,h)=>{var g;_F((g=p.getAttribute("id"))!==null&&g!==void 0?g:"").toLowerCase().startsWith("spacer")||se(p,"control")[0]&&t.set(Nc({tabIndex:i,columnIndex:s,sectionIndex:c,rowIndex:m,cellIndex:h}),p)})})})})}),t}function Nc(e){let t=e??{};return`${t.tabIndex}.${t.columnIndex}.${t.sectionIndex}.${t.rowIndex}.${t.cellIndex}`}function Iae(e,t,r,n){if(r===NF(t,n))return;let i=se(t,"labels")[0];i||(i=e.createElement("labels"),t.appendChild(i));let o=se(i,"label").find(a=>a.getAttribute("languagecode")===String(n));o||(o=e.createElement("label"),o.setAttribute("languagecode",String(n)),i.appendChild(o)),o.setAttribute("description",r)}function Oae(e,t,r){var n;if(!r)return;let i=Object.keys(r);if(i.length===0)return;let o=se(t,"parameters")[0];o||(o=e.createElement("parameters"),t.appendChild(o));let a=new Map,s=o.childNodes;for(let l=0;l<s.length;l+=1){let u=s[l];u.nodeType===1&&a.set(u.tagName,u)}for(let l of i){let u=r[l],c=a.get(l);if(c)((n=c.textContent)!==null&&n!==void 0?n:"")!==u&&(c.textContent=u);else{let d=(0,EF.createSafeXmlElement)(e,l,"dashboard component parameter");d.textContent=u,o.appendChild(d)}}}function wF(e,t,r){um(e,t,1)!==r&&e.setAttribute(t,String(r))}function Pae(e=2){let t=`{${(0,Fa.newId)()}}`,r=`{${(0,Fa.newId)()}}`,n=`{${(0,Fa.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>`}yi.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 sm(e){return`{${e.replace(/[{}]/g,"")}}`}function Rae(e,t,r){var n;let i=se(e,"tabs").flatMap(u=>se(u,"tab"))[0];if(!i)throw new Error("addDashboardTile: dashboard formxml has no <tab>");let o=se(i,"columns").flatMap(u=>se(u,"column"))[0];if(!o)throw new Error("addDashboardTile: dashboard formxml has no <column>");let a=se(o,"sections").flatMap(u=>se(u,"section")),s=(n=a[r])!==null&&n!==void 0?n:a[0];if(!s)throw new Error("addDashboardTile: dashboard formxml has no <section>");let l=se(s,"rows")[0];return l||(l=t.createElement("rows"),s.appendChild(l)),l}function Lae(e=AF.DEFAULT_LCID){return{adapter:new lm(e),api:CF.dashboardApi,languageSensitive:!0,publish:(t,r,n)=>n?.entityLogicalName?(0,iw.publishBoundEntity)(t,n):(0,iw.publishDashboardById)(t,r),publishScope:(t,r)=>r?.entityLogicalName?(0,iw.boundEntityPublishScope)(r):{envelope:"dashboard",targetIds:[t]},rebaselineAfterPublish:"bracket"}}yi.dashboardRegistration=Lae});var lw=v(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.readEveryInOrder=Vr.readInOrder=Vr.plainRead=Vr.resolveReadConcurrency=Vr.MAX_READ_CONCURRENCY=void 0;var IF=Q();Vr.MAX_READ_CONCURRENCY=8;function kae(e){if(e===void 0)return 1;if(typeof e!="number"||!Number.isInteger(e)||e<1||e>Vr.MAX_READ_CONCURRENCY)throw new IF.InvalidArgumentError(`readConcurrency must be a whole number from 1 to ${Vr.MAX_READ_CONCURRENCY} (got ${typeof e=="string"?`'${e}'`:String(e)})`);return e}Vr.resolveReadConcurrency=kae;var $ae=e=>({ok:!0,value:e}),sw=e=>({ok:!1,error:e});function xae(e){let t=(async()=>e())().then($ae,sw);return{outcome:t,finish:async r=>{await r()},discard:async()=>{await t}}}Vr.plainRead=xae;async function OF(e,t,r,n,i){if(!Number.isInteger(t)||t<1)throw new IF.InvalidArgumentError(`a read window holds a whole number of reads, at least 1 (got ${String(t)})`);let o=new Map,a=0,s=Promise.resolve(),l=!1,u=0,c,d=async f=>{if(l)return{refusal:new Error("The read was not started: an earlier read had already failed.")};try{let m=await r(e[f],f),p=m.outcome.catch(sw);return i==="stop"&&p.then(h=>{l=l||!h.ok}),{read:m,outcome:p}}catch(m){return l=l||i==="stop",{refusal:m}}};try{for(let f=0;f<e.length;f+=1){for(;a<e.length&&a<f+t;){let g=a;a+=1;let b=s.then(()=>d(g));o.set(g,b),s=b}let m=await o.get(f),p="read"in m?await m.outcome:sw(m.refusal);if(!p.ok&&i==="stop"){c={error:p.error};break}u=f+1,o.delete(f);let h=()=>n(p,e[f],f);"read"in m?await m.read.finish(h):await h()}}finally{l=!0;for(let f=u;f<a;f+=1){let m=await o.get(f);"read"in m&&await m.read.discard().catch(()=>{})}}if(c)throw c.error}function Fae(e,t,r,n){return OF(e,t,r,(i,o,a)=>n(i.value,o,a),"stop")}Vr.readInOrder=Fae;function Mae(e,t,r,n){return OF(e,t,r,n,"continue")}Vr.readEveryInOrder=Mae});var HF=v(dm=>{"use strict";Object.defineProperty(dm,"__esModule",{value:!0});dm.genPageApi=void 0;var cm=Tt(),VF=Es(),Ve=fe(),be=oe(),Gn=pa(),Qe=Q(),GF=ct(),PF=lw();function Uae(e){if(ArrayBuffer.isView(e)){let r=e;return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}if(Object.prototype.toString.call(e)==="[object ArrayBuffer]")return new Uint8Array(e);let t=globalThis;if(t.Buffer&&t.Buffer.isBuffer(e)){let r=e;return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}}var bi="uxagentprojects",Ua="uxagentprojectfiles",Dc="agentconversationmessages",Ic="uxagentprojectid",jt="uxagentprojectfileid",Ba="agentconversationmessageid",_c=`${Ic},name`,Bae=`${jt},filename,filetype`,WF=2e8,zF=200000001,qa={"MSCRM.IncludeUnpublished":"true"},uw={};function Ma(e,t){return{"MSCRM.VersioningChangeset":e,...qa,...t}}async function fw(e,t,r,n){var i;let o=`/${t}(${r})`+(0,be.odataQuery)([["$select",n]]),a=(0,Ve.ensureSuccess)(await e.get(o,{headers:{...qa}}),e.apiUrl(o));return{row:(i=a.body)!==null&&i!==void 0?i:{},etag:(0,Ve.readEtag)(a)}}async function Oc(e,t,r=qa){let n=`/${Ua}(${t})/filecontent/$value`,i=await e.get(n,{headers:{...r}});if(i.status===404)return{status:"unavailable",reason:"missing"};(0,Ve.ensureSuccess)(i,e.apiUrl(n));let o=i.body,a=Uae(o);if(a)return{status:"available",data:(0,Gn.bytesToBase64)(a)};if(typeof o=="string")return{status:"available",data:(0,Gn.utf8ToBase64)(o)};throw new Qe.SdkError("GENPAGE_CONTENT_UNREADABLE",`Read the content of file '${t}' but the injected HttpClient returned a body this SDK cannot encode (${typeof o}). Return the response as a string, Uint8Array, Buffer, or ArrayBuffer; a byte-returning transport is required to round-trip non-UTF8 assets.`)}function jF(e){let t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}async function qae(e,t,r,n,i,o){if(!e.supportsBinaryPatch)throw new Qe.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED",`Refusing to push generative-page file '${t}': its content cannot be written because the injected HttpClient does not implement patchRaw(). A Dataverse File column is not writable through a JSON body, so saving the row without its bytes would report success for a page whose source never uploaded.`);let a=`/${Ua}(${t})/filecontent`,s=(0,Gn.base64ToBytes)(n);(0,be.assertNoControlChars)(r,"generative-page file name"),(0,Ve.ensureSuccess)(await e.patchRaw(a,s,{headers:Ma(i,{"Content-Type":"application/octet-stream","Content-Length":String(s.byteLength),"x-ms-file-name":jF(r),...o?{"If-Match":"*"}:{}})}),e.apiUrl(a))}async function Tc(e,t,r=qa){let n=`/${Ua}`+(0,be.odataQuery)([["$select",Bae],["$filter",`_${Ic}_value eq ${t}`]]);return(await(0,cm.collectPages)(e,n,"fetchArtifact('genPage')",void 0,{headers:{...r}})).map(o=>({row:o,etag:typeof o["@odata.etag"]=="string"?o["@odata.etag"]:null}))}async function cw(e,t){let r=`/${Dc}`+(0,be.odataQuery)([["$select",`${Ba},message,messagesender,createdon`],["$filter",`_regardingobjectid_value eq ${t}`],["$orderby","createdon asc,versionnumber asc"]]);return(0,cm.collectPages)(e,r,"fetchArtifact('genPage')",void 0,{headers:{...qa}})}async function RF(e,t){var r,n,i;let{row:o,etag:a}=await fw(e,bi,t,_c),s=new Map;for(let{row:l,etag:u}of await Tc(e,t))s.set((0,be.normalizeGuid)(String((r=l[jt])!==null&&r!==void 0?r:""),jt),{filename:String((n=l.filename)!==null&&n!==void 0?n:""),filetype:Number(l.filetype),etag:u});return{name:String((i=o.name)!==null&&i!==void 0?i:""),etag:a,rows:s}}function LF(e,t,r){var n,i,o,a,s;let l=[];r||l.push({kind:"createProject",name:t.name});let u=new Set;for(let c of(n=t.files)!==null&&n!==void 0?n:[]){let d=(0,be.normalizeGuid)(c.id,"file id");u.add(d);let f=r?.rows.get(d);if(c.content.status==="retain"){if(!r)throw new Qe.SdkError("GENPAGE_RETAIN_ON_CREATE",`Refusing to create generative page '${e}': file '${c.name}' asks to keep content the page does not have yet. This is an SDK defect \u2014 the page's rows were not written.`);if(!f)throw new Qe.SdkError("GENPAGE_RETAINED_ROW_MISSING",`Refusing to write generative page '${e}': file '${c.name}' was to be kept unchanged but is not on the server. Re-fetch the page and retry.`);continue}f&&c.unchanged||(f?(f.filename!==c.name||f.filetype!==c.fileType)&&l.push({kind:"renameRow",file:c}):l.push({kind:"createRow",file:c}),c.content.status==="available"&&l.push({kind:"content",file:c,data:c.content.data,existing:f!==void 0}))}for(let c of(i=r?.rows.keys())!==null&&i!==void 0?i:[])u.has(c)||l.push({kind:"deleteRow",fileId:c});(!r||l.length>0||r.name!==t.name||((a=(o=t.messages)===null||o===void 0?void 0:o.length)!==null&&a!==void 0?a:0)>0)&&l.push({kind:"patchProject",name:t.name});for(let c of(s=t.messages)!==null&&s!==void 0?s:[])l.push({kind:"message",turn:c});return l}function pw(e){let t=(0,Gn.base64ToUtf8)(e);return(0,Gn.utf8ToBase64)(t)===(0,Gn.bytesToBase64)((0,Gn.base64ToBytes)(e))?t:void 0}function Vae(e,t,r,n){var i,o,a,s,l,u,c,d;let f=t.sender==="user"?{changeSet:n,dataSources:(o=(i=r.messageContext)===null||i===void 0?void 0:i.dataSources)!==null&&o!==void 0?o:[],model:(s=(a=r.messageContext)===null||a===void 0?void 0:a.model)!==null&&s!==void 0?s:"",enabledTools:(u=(l=r.messageContext)===null||l===void 0?void 0:l.enabledTools)!==null&&u!==void 0?u:[],configurableTools:(d=(c=r.messageContext)===null||c===void 0?void 0:c.configurableTools)!==null&&d!==void 0?d:[]}:{changeSet:n};return{...t.id?{[Ba]:(0,be.normalizeGuid)(t.id,"message id")}:{},"[email protected]":`/${bi}(${e})`,message:t.message,messagecontext:JSON.stringify(f),messagesender:t.sender==="user"?WF:zF}}async function Gae(e,t,r){var n,i,o,a;let s=((n=r.messages)!==null&&n!==void 0?n:[]).map(f=>f.id).filter(f=>typeof f=="string"&&f!=="").map(f=>(0,be.normalizeGuid)(f,"message id"));if(s.length===0)return r;let l=`/${Dc}`+(0,be.odataQuery)([["$select",`${Ba},message,messagesender,_regardingobjectid_value`],["$filter",s.map(f=>`${Ba} eq ${f}`).join(" or ")]]),u=await(0,cm.collectPages)(e,l,"pushArtifact('genPage')",void 0,{headers:{...qa}});if(u.length===0)return r;let c=new Map(u.map(f=>{var m;return[String((m=f[Ba])!==null&&m!==void 0?m:"").toLowerCase(),f]})),d=[];for(let f of(i=r.messages)!==null&&i!==void 0?i:[]){let m=f.id?c.get((0,be.normalizeGuid)(f.id,"message id")):void 0;if(!m){d.push(f);continue}if(!(String((o=m.message)!==null&&o!==void 0?o:"")===f.message&&Number(m.messagesender)===(f.sender==="user"?WF:zF)&&String((a=m._regardingobjectid_value)!==null&&a!==void 0?a:"").toLowerCase()===t))throw new Qe.SdkError("GENPAGE_TURN_CONFLICT",`Refusing to push generative page '${t}': its pending turn's identity is already recorded \u2014 as a DIFFERENT ${f.sender} message. An earlier push of this turn did commit (its response was lost), and the turn was changed since. Nothing was written, and the turn is still pending. To record it as a new turn, remove '/newTurn/id' (a new identity is minted on the next push); to keep only what was recorded, remove '/newTurn'.`)}return{...r,messages:d}}function dw(e,t,r,n){switch(t.kind){case"createProject":return{method:"POST",path:`/${bi}`,body:(0,Ve.withClientMintedId)({name:t.name},Ic,e),headers:Ma(n)};case"createRow":return{method:"POST",path:`/${Ua}`,body:(0,Ve.withClientMintedId)({filename:t.file.name,filetype:t.file.fileType,[`${Ic}@odata.bind`]:`/${bi}(${e})`},jt,(0,be.normalizeGuid)(t.file.id,"file id")),headers:Ma(n)};case"renameRow":return{method:"PATCH",path:`/${Ua}(${(0,be.normalizeGuid)(t.file.id,"file id")})`,body:{filename:t.file.name,filetype:t.file.fileType},headers:Ma(n,{"If-Match":"*"})};case"content":{let i=pw(t.data);if(i===void 0)throw new Qe.SdkError("GENPAGE_CONTENT_NOT_TEXT",`File '${t.file.name}' is not UTF-8 text and cannot ride in a change set.`);return(0,be.assertNoControlChars)(t.file.name,"generative-page file name"),{method:"PATCH",path:`/${Ua}(${(0,be.normalizeGuid)(t.file.id,"file id")})/filecontent`,rawBody:i,contentType:"application/octet-stream; charset=utf-8",headers:Ma(n,{"x-ms-file-name":jF(t.file.name),...t.existing?{"If-Match":"*"}:{}})}}case"deleteRow":return{method:"DELETE",path:`/${Ua}(${t.fileId})`,headers:Ma(n,{"If-Match":"*"})};case"patchProject":return{method:"PATCH",path:`/${bi}(${e})`,body:{name:t.name},headers:Ma(n,{"If-Match":"*"})};case"message":return{method:"POST",path:`/${Dc}`,body:Vae(e,t.turn,r,n)};default:{let i=t;throw new Qe.SdkError("GENPAGE_WRITE_UNKNOWN",`Unknown generative-page write: ${JSON.stringify(i)}`)}}}function kF(e,t){return e.supportsAtomicBatch&&t.every(r=>r.kind!=="content"||pw(r.data)!==void 0)}async function $F(e,t,r,n,i){await(0,VF.postChangeSet)(e,r.map(o=>dw(t,o,n,i)),`generative page '${t}' (${r.length} operation(s))`)}async function xF(e,t,r,n,i){var o;let a=[];for(let s of r){if(s.kind==="message"){a.push(s);continue}if(s.kind==="content"){await qae(e,(0,be.normalizeGuid)(s.file.id,"file id"),s.file.name,s.data,i,s.existing);continue}let l=dw(t,s,n,i),u={headers:(o=l.headers)!==null&&o!==void 0?o:{}},c=l.method==="POST"?await e.post(l.path,l.body,u):l.method==="PATCH"?await e.patch(l.path,l.body,u):await e.delete(l.path,u);(0,Ve.ensureSuccess)(c,e.apiUrl(l.path))}if(a.length===0)return{warnings:[],turnRecorded:!0};try{let s=a.map(l=>dw(t,l,n,i));if(e.supportsAtomicBatch)await(0,VF.postChangeSet)(e,s,`the conversation turn of generative page '${t}'`);else for(let l of s)(0,Ve.ensureSuccess)(await e.post(l.path,l.body),e.apiUrl(l.path));return{warnings:[],turnRecorded:!0}}catch(s){return{warnings:[`Generative page '${t}' was saved, but its conversation turn could not be recorded (${s instanceof Error?s.message:String(s)}). The turn is kept: the next push of the page records it.`],turnRecorded:!1}}}async function FF(e,t,r,n,i,o,a){var s;let l=u=>({id:t,etag:null,memberEtags:{},warnings:[...a,u]});try{let u=await RF(e,t),c=new Map;for(let C of r)(C.kind==="createRow"||C.kind==="renameRow"||C.kind==="content")&&c.set((0,be.normalizeGuid)(C.file.id,"file id"),C.file);let d=[];u.name!==n.name&&d.push(`the page is named '${u.name}', not '${n.name}'`);for(let[C,S]of c){let O=u.rows.get(C);O&&(O.filename!==S.name||O.filetype!==S.fileType)&&d.push(`file '${S.name}' is stored as '${O.filename}' (type ${O.filetype})`)}for(let C of r){if(C.kind!=="content")continue;let S=await Oc(e,(0,be.normalizeGuid)(C.file.id,"file id")),O=(0,Gn.bytesToBase64)((0,Gn.base64ToBytes)(C.data));(S.status!=="available"||S.data!==O)&&d.push(S.status==="available"?`file '${C.file.name}' holds ${(0,Gn.base64ToBytes)(S.data).byteLength} byte(s) that differ from the ${(0,Gn.base64ToBytes)(O).byteLength} written`:`file '${C.file.name}' holds no content`)}let f=new Set(r.filter(C=>C.kind==="content").map(C=>(0,be.normalizeGuid)(C.file.id,"file id")));for(let[C,S]of c)!f.has(C)&&(await Oc(e,C)).status==="available"&&d.push(`file '${S.name}' holds content this push did not write`);if(d.length>0)return l(`Generative page '${t}' was written, but reading it back does not match what was sent: ${d.join("; ")}. The local baseline is now unusable: re-fetch the page to see what the server holds \u2014 the next push will refuse rather than overwrite blind.`);let m=await RF(e,t),p=[...m.rows.keys()],h=m.etag!==u.etag||m.rows.size!==u.rows.size||p.some(C=>{var S,O;return((S=u.rows.get(C))===null||S===void 0?void 0:S.etag)!==((O=m.rows.get(C))===null||O===void 0?void 0:O.etag)}),g=p.length!==i.size||p.some(C=>!i.has(C)),b={},w=[];for(let[C,S]of m.rows){let O=c.has(C)||!o?S.etag:(s=o.get(C))!==null&&s!==void 0?s:null;b[C]=O,O!==S.etag&&w.push(S.filename)}return h||g||!m.etag||Object.values(b).some(C=>!C)?l(`Generative page '${t}' was written, but its files changed on the server while the write was in progress, so the new concurrency tokens cannot be trusted. The local baseline is now unusable: re-fetch the page before editing it again \u2014 the next push will refuse rather than overwrite blind.`):Wae({id:t,etag:m.etag,memberEtags:b},[...a,...w.map(C=>`Generative page '${t}' was written, but its file '${C}' changed on the server while this push ran \u2014 another writer edited it. This push did not touch that file, so the next one refuses until you re-fetch the page and see their change.`)])}catch(u){return l(`The generative page was written, but reading it back failed (${u instanceof Error?u.message:String(u)}). The local baseline is unusable: re-fetch the page before editing it \u2014 the next push will refuse rather than overwrite blind.`)}}async function MF(e,t,r,n=e.readConcurrency){var i;let o=(0,be.normalizeGuid)(t,"id"),{row:a,etag:s}=await fw(e,bi,o,_c),l=await Tc(e,o),u={},c=[];if(n>1)await(0,PF.readInOrder)(l,n,({row:f})=>{var m;let p=(0,be.normalizeGuid)(String((m=f[jt])!==null&&m!==void 0?m:""),jt);return(0,PF.plainRead)(async()=>({fileId:p,content:await Oc(e,p)}))},({fileId:f,content:m},{row:p,etag:h})=>{u[f]=h,c.push({...p,content:m})});else for(let{row:f,etag:m}of l){let p=(0,be.normalizeGuid)(String((i=f[jt])!==null&&i!==void 0?i:""),jt);u[p]=m;let h=await Oc(e,p);c.push({...f,content:h})}return{raw:r?{project:a,files:c,conversation:await cw(e,o)}:{project:a,files:c},etag:s,memberEtags:u}}dm.genPageApi={get(e,t,r){return MF(e,t,!0,r?.fileConcurrency)},getForRebaseline(e,t){return MF(e,t,!1)},async getPublished(e,t){var r,n;let i=(0,be.normalizeGuid)(t,"id"),o=`/${bi}(${i})`+(0,be.odataQuery)([["$select",_c]]),a=await e.get(o);if(a.status===404)return null;(0,Ve.ensureSuccess)(a,e.apiUrl(o));let s=(r=a.body)!==null&&r!==void 0?r:{},l={},u=[],c=await Tc(e,i,uw);for(let{row:g,etag:b}of c){let w=(0,be.normalizeGuid)(String((n=g[jt])!==null&&n!==void 0?n:""),jt);l[w]=b,u.push({...g,content:await Oc(e,w,uw)})}let d=g=>g.map(({row:b,etag:w})=>`${String(b[jt])}@${String(w)}`).sort().join("|"),f=()=>new Qe.SdkError("GENPAGE_PUBLISHED_READ_MOVED",`The published projection of generative page '${i}' changed while it was being read, so what was read is not one published state. PublishXml is asynchronous \u2014 re-read shortly.`),m=await e.get(o);if(m.status===404)throw f();(0,Ve.ensureSuccess)(m,e.apiUrl(o));let p=await Tc(e,i,uw);if([(0,Ve.readEtag)(a),(0,Ve.readEtag)(m),...[...c,...p].map(g=>g.etag)].some(g=>!g))throw new Qe.SdkError("GENPAGE_PUBLISHED_READ_UNVERSIONED",`The published projection of generative page '${i}' answered without a version token for the page or one of its rows, so what was read cannot be proven to be one published state.`);if((0,Ve.readEtag)(m)!==(0,Ve.readEtag)(a)||d(p)!==d(c))throw f();return{raw:{project:s,files:u,conversation:[]},etag:(0,Ve.readEtag)(a),memberEtags:l}},async list(e,t){let r=`/${bi}`+(0,be.odataQuery)([["$select",_c]]);return(await(0,cm.collectPages)(e,r,"listArtifacts('genPage')",void 0,{headers:{...qa}})).map(i=>{var o,a;return{type:"genPage",id:String((o=i[Ic])!==null&&o!==void 0?o:""),name:String((a=i.name)!==null&&a!==void 0?a:""),isDirty:!1}})},async create(e,t,r){var n;let i=t,o=r?(0,be.normalizeGuid)(r,"id"):(0,GF.newId)(),a=LF(o,i,void 0);qF(e,a),BF(e,o,i);let s=UF(),l=[],u=!0;kF(e,a)?await $F(e,o,a,i,s):{warnings:l,turnRecorded:u}=await xF(e,o,a,i,s);let c=new Set(((n=i.files)!==null&&n!==void 0?n:[]).map(f=>(0,be.normalizeGuid)(f.id,"file id"))),d=await FF(e,o,a,i,c,void 0,l);return u?d:{...d,intentPending:!0}},async update(e,t,r,n,i){var o,a;let s=r,l=(0,be.normalizeGuid)(t,"id");if(!Array.isArray(s.files))throw new Qe.SdkError("GENPAGE_FILES_REQUIRED",`Refusing to update generative page '${l}': its payload has no files list. A page's files are its complete set of rows \u2014 a row the list omits is deleted \u2014 so an omitted list would delete every row of the page. Nothing was written.`);let u=await Gae(e,l,s);BF(e,l,u);let c=await Tc(e,l),{row:d,etag:f}=await fw(e,bi,l,_c);if(n&&f&&n!==f)throw new Qe.SdkError(Ve.VERSION_CONFLICT_CODE,`Generative page '${l}' changed on the server after it was fetched (baseline ${n}, server ${f}) \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||!f)throw new Qe.SdkError(Ve.VERSION_CONFLICT_CODE,`Cannot verify generative page '${l}' before writing: ${n?"the server did not return the page's current token":"no baseline token was recorded"}. This entity accepts no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let m=new Map(c.map(({row:I})=>{var D,P;return[(0,be.normalizeGuid)(String((D=I[jt])!==null&&D!==void 0?D:""),jt),{filename:String((P=I.filename)!==null&&P!==void 0?P:""),filetype:Number(I.filetype)}]})),p=new Set(m.keys()),h=new Set(((o=u.files)!==null&&o!==void 0?o:[]).map(I=>(0,be.normalizeGuid)(I.id,"file id")));if(!i)throw new Qe.SdkError(Ve.VERSION_CONFLICT_CODE,`Cannot verify the files of generative page '${l}' before writing: no child baseline was recorded. These rows accept no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let g=new Set(Object.keys(i).map(I=>I.toLowerCase()));for(let I of h)if(!p.has(I)&&g.has(I))throw new Qe.SdkError(Ve.VERSION_CONFLICT_CODE,`Generative-page file '${I}' existed when this page was fetched but is gone from the server now \u2014 another writer deleted it. Refusing to recreate it, because a blind re-create would undo that delete. Re-fetch the page and re-apply the edit.`);for(let I of p)if(!g.has(I))throw new Qe.SdkError(Ve.VERSION_CONFLICT_CODE,`Generative-page file '${I}' is on the server but absent from this page's baseline \u2014 another writer added it after the page was fetched, so its contents cannot be verified. Refusing to write over or delete it. Re-fetch the page so the addition is part of your baseline.`);let b=new Map(c.map(({row:I,etag:D})=>{var P;return[(0,be.normalizeGuid)(String((P=I[jt])!==null&&P!==void 0?P:""),jt),D]}));for(let[I,D]of Object.entries(i)){let P=I.toLowerCase();if(!p.has(P))continue;let x=b.get(P);if(!D||!x)throw new Qe.SdkError(Ve.VERSION_CONFLICT_CODE,`Cannot verify generative-page file '${P}' before writing: ${D?"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(D!==x)throw new Qe.SdkError(Ve.VERSION_CONFLICT_CODE,`Generative-page file '${P}' changed on the server after this page was fetched (baseline ${D}, server ${x}) \u2014 another writer edited it. A file row accepts no If-Match validator, so this push would silently overwrite that change. Re-fetch the page and re-apply the edit.`)}let w=LF(l,u,{rows:m,name:String((a=d.name)!==null&&a!==void 0?a:"")});if(qF(e,w),w.length===0)return{id:l,etag:f,memberEtags:Object.fromEntries(c.map(({row:I,etag:D})=>{var P;return[(0,be.normalizeGuid)(String((P=I[jt])!==null&&P!==void 0?P:""),jt),D]}))};let C=UF(),S=[],O=!0;kF(e,w)?await $F(e,l,w,u,C):{warnings:S,turnRecorded:O}=await xF(e,l,w,u,C);let L=await FF(e,l,w,u,h,b,S);return O?L:{...L,intentPending:!0}},async delete(e,t){var r;let n=(0,be.normalizeGuid)(t,"id"),i=await cw(e,n);await(0,Ve.deleteRecord)(e,bi,n);let o=new Set(i.map(l=>{var u;return String((u=l[Ba])!==null&&u!==void 0?u:"")}).filter(l=>l!=="")),a=!1;try{for(let l of await cw(e,n)){let u=String((r=l[Ba])!==null&&r!==void 0?r:"");u!==""&&o.add(u)}}catch{a=!0}let s=[];for(let l of o)try{await(0,Ve.deleteRecord)(e,Dc,l)}catch(u){u instanceof Qe.ConnectionError&&u.statusCode===404||s.push(l)}if(s.length>0||a)throw new Qe.SdkError("GENPAGE_HISTORY_NOT_DELETED",`Generative page '${n}' was deleted, but its conversation history was not fully removed`+(s.length>0?` \u2014 ${s.length} of ${o.size} message(s) could not be (${s.join(", ")})`:"")+(a?" \u2014 and re-reading it after the delete failed, so a late turn may remain":"")+`. They no longer belong to any page; delete them as ${Dc} rows regarding '${n}'.`)}};function UF(){return`uxagentproject_${(0,GF.newId)()}`}function Wae(e,t){var r;return t.length===0?e:{...e,warnings:[...(r=e.warnings)!==null&&r!==void 0?r:[],...t]}}function BF(e,t,r){var n,i;if(((i=(n=r.messages)===null||n===void 0?void 0:n.length)!==null&&i!==void 0?i:0)>1&&!e.supportsAtomicBatch)throw new Qe.SdkError("GENPAGE_TURN_NOT_ATOMIC",`Refusing to write generative page '${t}': its new turn has a prompt AND a reply, which must be recorded together, and the injected HttpClient does not implement postRaw() \u2014 one request at a time, a failure between the two would leave half a turn. Implement postRaw(), or record the prompt alone (omit newTurn.agentMessage). Nothing was written.`)}function qF(e,t){let r=t.filter(i=>i.kind==="content");if(r.length>0&&!e.supportsBinaryPatch&&!e.supportsAtomicBatch)throw new Qe.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: it has file content to upload, but the injected HttpClient implements neither patchRaw() nor postRaw(). A Dataverse File column is not writable through a JSON body, so proceeding would create the page and its rows and then fail, leaving a page whose source never uploaded.");if(r.some(i=>pw(i.data)===void 0)&&!e.supportsBinaryPatch)throw new Qe.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: a file's content is not UTF-8 text, which only the binary channel can carry, and the injected HttpClient does not implement patchRaw().")}});var cM=v(Tl=>{"use strict";Object.defineProperty(Tl,"__esModule",{value:!0});Tl.genPageRegistration=Tl.GenPageAdapter=void 0;var zae=HF(),jae=jr(),Ie=cn(),gm=ct(),ym=pa(),Hae=oe(),Va=Q(),iM=v0(),mw=Oh(),Wo=2e8,oM=200000001,ro={source:{name:"src/pages/page.tsx",fileType:Wo},output:{name:"src/pages/page.compiled",fileType:oM},config:{name:"config.json",fileType:Wo},prompt:{name:"firstPrompt.json",fileType:Wo}},aM=Object.keys(ro),Kae=["dataSources","model","connectorBindings","actionBindings"],Jae=["userMessage","agentMessage"],KF=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Yae={source:"6f1c2a4e9b3d47a1b85c0e2f7d914a63",output:"a8e53d17c2f64b09a1d7e4b8c3f2069d",config:"3b97f0c64e2a4d8f95b1c7a0e6d3f814",prompt:"d24e8b51f7a34c6e8b09d5f1a2c7e3b6"},Qae="9c3e7a15d2b84f6e8a01c5d7b3f9e240";function sM(e,t,r){let n=(0,Hae.normalizeGuid)(e,r).replace(/-/g,""),i=[];for(let a=0;a<32;a+=1)i.push(parseInt(n[a],16)^parseInt(t[a],16));i[12]=4,i[16]=i[16]&3|8;let o=i.map(a=>a.toString(16)).join("");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}function fm(e,t){return sM(e,Yae[t],"id")}function Xae(e,t){let r=sM(e,Qae,"newTurn.id"),n=parseInt(r.slice(24),16)%2**47+(t==="agent"?1:0);return`${r.slice(0,24)}${n.toString(16).padStart(12,"0")}`}function JF(e){return typeof e=="string"&&e.trim()!==""?e:(0,gm.newId)()}function to(e){return(0,Ie.isJsonObject)(e)?e:{}}function _l(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function pm(e){return JSON.parse(JSON.stringify(e))}function Zae(e){let t=to(e);return t.status==="available"&&typeof t.data=="string"?{status:"available",data:t.data}:{status:"unavailable",reason:t.reason==="unpublished"?"unpublished":"missing"}}function Rc(e){if(!e||e.status!=="available")return;let t=(0,ym.base64ToUtf8)(e.data);return(0,ym.utf8ToBase64)(t)===e.data?t:void 0}function lM(e,t,r){var n,i,o,a;return e.source!==void 0&&t!==void 0&&t?.source===e.source&&_l((n=t?.dataSources)!==null&&n!==void 0?n:[],(i=e.dataSources)!==null&&i!==void 0?i:[])&&((a=(o=e.bag)===null||o===void 0?void 0:o.rows)!==null&&a!==void 0?a:{}).output!==void 0&&(0,iM.isLoadableGenPageOutput)(r)}function ese(e,t){var r;try{return lM(e,t,Rc((r=e.bag)===null||r===void 0?void 0:r.output))}catch{return!1}}function mm(e){if(e!==void 0)try{let t=JSON.parse(e.replace(/^\uFEFF/,""));return(0,Ie.isJsonObject)(t)?t:void 0}catch{return}}function YF(e,t){if(t===Wo&&e.includes("page.tsx"))return"source";if(t===oM&&e.includes(".compiled"))return"output";if(t===Wo&&e===ro.config.name)return"config";if(t===Wo&&e===ro.prompt.name)return"prompt"}function QF(e){let t=e.toLowerCase();return aM.some(r=>ro[r].name.toLowerCase()===t)}function hw(e){return Object.fromEntries(e)}function uM(e,t,r,n){let i=[],o=new Set,a=new Set(t),s=l=>{if(o.has(l))return;let u=a.has(l)?e[l]:r&&Object.prototype.hasOwnProperty.call(r,l)?r[l]:void 0;u!==void 0&&(o.add(l),i.push([l,u]))};return(n??[]).forEach(s),t.forEach(s),Object.keys(r??{}).forEach(s),hw(i)}function XF(e){var t,r,n;return uM({dataSources:(t=e.dataSources)!==null&&t!==void 0?t:[],model:e.model,connectorBindings:e.connectorBindings,actionBindings:e.actionBindings},Kae,(r=e.bag)===null||r===void 0?void 0:r.config,(n=e.bag)===null||n===void 0?void 0:n.configKeys)}function ZF(e){var t,r;return uM({userMessage:e.firstPrompt,agentMessage:e.firstAgentMessage},Jae,(t=e.bag)===null||t===void 0?void 0:t.prompt,(r=e.bag)===null||r===void 0?void 0:r.promptKeys)}function eM(e,t,r){let n=[];for(let[i,o]of Object.entries(r))if(i==="dataSources"){if(!Array.isArray(o)||!o.every(a=>typeof a=="string"))return!1;e.dataSources=o}else if(i==="model"){if(typeof o!="string")return!1;e.model=o}else i==="connectorBindings"?e.connectorBindings=o:i==="actionBindings"?e.actionBindings=o:n.push([i,o]);return t.configKeys=Object.keys(r),n.length>0&&(t.config=hw(n)),!0}function tM(e,t,r){let n=[];for(let[i,o]of Object.entries(r))if(i==="userMessage"||i==="agentMessage"){if(typeof o!="string")return!1;i==="userMessage"?e.firstPrompt=o:e.firstAgentMessage=o}else n.push([i,o]);return t.promptKeys=Object.keys(r),n.length>0&&(t.prompt=hw(n)),!0}function Lc(e){var t,r;return e.source!==void 0||Object.keys((r=(t=e.bag)===null||t===void 0?void 0:t.rows)!==null&&r!==void 0?r:{}).length>0}var tse=["dataSources","model","connectorBindings","actionBindings","firstPrompt","firstAgentMessage"];function rM(e){return Lc(e)?[]:tse.filter(t=>e[t]!==void 0).map(t=>(0,Ie.issue)(`/${t}`,"genpage-raw-structured-field",`${t} cannot be applied: this page is in raw-file mode \u2014 it has no source and no managed rows, so a push writes its files[] exactly as they are, and ${t} nowhere. Set source to make the page managed (the SDK then writes config.json and firstPrompt.json from the typed fields; a file in files[] holding one of those names must be removed first), or change the file that stores the value in files[] directly.`))}function nM(){return(0,Ie.issue)("/source","genpage-source-required","the page's source cannot be removed: its source row still exists, and a page without one cannot run. Set a new source, or delete the page with deleteRemoteArtifact.")}function hm(e){return{status:"available",data:(0,ym.utf8ToBase64)(e)}}function Pc(e,t){var r,n;return{id:String((r=e.uxagentprojectid)!==null&&r!==void 0?r:""),name:String((n=e.name)!==null&&n!==void 0?n:""),files:t}}var bm=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){let r=t,n=to(r?.project),i=(Array.isArray(r?.files)?r.files:[]).map(g=>{var b,w,C;let S=to(g);return{id:String((b=S.uxagentprojectfileid)!==null&&b!==void 0?b:""),name:String((w=S.filename)!==null&&w!==void 0?w:""),fileType:Number((C=S.filetype)!==null&&C!==void 0?C:Wo),content:Zae(S.content)}}),o=Array.isArray(r?.conversation)?r.conversation.map(g=>{var b,w;let C=to(g);return{sender:Number(C.messagesender)===200000001?"agent":"user",message:String((b=C.message)!==null&&b!==void 0?b:""),createdOn:String((w=C.createdon)!==null&&w!==void 0?w:"")}}):void 0,a=g=>o?{...g,conversation:o}:g,s=new Map,l=[],u=!0;for(let g of i){let b=YF(g.name,g.fileType);b?((s.has(b)||g.name!==ro[b].name)&&(u=!1),s.set(b,g)):(QF(g.name)&&(u=!1),l.push(g))}if(!u||s.size===0)return a(Pc(n,i));let c=Pc(n,l),d={rows:{}};for(let[g,b]of s)d.rows[g]=b.id;let f=s.get("source");if(f){let g=Rc(f.content);if(g===void 0)return a(Pc(n,i));c.source=g}let m=s.get("output");m&&(d.output=m.content);let p=s.get("config");if(p){let g=mm(Rc(p.content));if(!g||!eM(c,d,g))return a(Pc(n,i))}let h=s.get("prompt");if(h){let g=mm(Rc(h.content));if(!g||!tM(c,d,g))return a(Pc(n,i))}return c.bag=d,a(c)}async toApiPayload(t,r,n){var i,o,a,s,l,u,c,d,f,m,p,h,g;if(r&&!_l((i=t.conversation)!==null&&i!==void 0?i:[],(o=r.conversation)!==null&&o!==void 0?o:[]))throw new Va.ValidationError("genPage",t.id,[(0,Ie.issue)("/conversation","genpage-conversation-read-only","conversation is the page's recorded history and cannot be edited. Record a new turn with newTurn; revert the edit to conversation before pushing.")]);let b=rM(t);if(b.length>0)throw new Va.ValidationError("genPage",t.id,b);let w=[],C=r===void 0,S=C&&t.firstPrompt===void 0&&t.newTurn?{...t,firstPrompt:t.newTurn.prompt,...t.newTurn.agentMessage!==void 0?{firstAgentMessage:t.newTurn.agentMessage}:{}}:t;if(Lc(S)){let I=(s=(a=S.bag)===null||a===void 0?void 0:a.rows)!==null&&s!==void 0?s:{},D=Ge=>{var Ut;return(Ut=I[Ge])!==null&&Ut!==void 0?Ut:fm(S.id,Ge)},P=(Ge,Ut,de)=>{w.push({id:D(Ge),name:ro[Ge].name,fileType:ro[Ge].fileType,content:Ut,unchanged:de})};if(S.source!==void 0){P("source",hm(S.source),!C&&r?.source===S.source&&I.source!==void 0);let Ge=Rc((l=S.bag)===null||l===void 0?void 0:l.output);lM(S,r,Ge)?P("output",{status:"retain"},!0):P("output",hm(await this.compile(S,S.source,n)),!1)}else{if(I.source!==void 0)throw new Va.ValidationError("genPage",S.id,[nM()]);if(I.output!==void 0){if(!C&&!_l((u=r?.dataSources)!==null&&u!==void 0?u:[],(c=S.dataSources)!==null&&c!==void 0?c:[]))throw new Va.ValidationError("genPage",S.id,[(0,Ie.issue)("/dataSources","genpage-source-required","the page has no source row, so its output cannot be recompiled for new data sources; set a source to change them.")]);P("output",{status:"retain"},!0)}}let x=XF(S),K=!C&&r!==void 0&&_l(XF(r),x);(C||I.config!==void 0||!K)&&P("config",hm(JSON.stringify(x)),K&&I.config!==void 0);let Le=ZF(S),lr=!C&&r!==void 0&&_l(ZF(r),Le);(I.prompt!==void 0||Object.keys(Le).length>0&&!lr)&&P("prompt",hm(JSON.stringify(Le)),lr&&I.prompt!==void 0)}for(let I of(d=S.files)!==null&&d!==void 0?d:[]){let D=(f=r?.files)===null||f===void 0?void 0:f.find(P=>P.id===I.id);w.push({id:I.id,name:I.name,fileType:I.fileType,content:I.content,unchanged:D!==void 0&&_l(D,I)})}let O=[];if(S.newTurn){let I=S.newTurn.id,D=P=>I?{id:Xae(I,P)}:{};O.push({...D("user"),sender:"user",message:S.newTurn.prompt}),S.newTurn.agentMessage&&O.push({...D("agent"),sender:"agent",message:S.newTurn.agentMessage})}let L=(p=(m=S.bag)===null||m===void 0?void 0:m.config)!==null&&p!==void 0?p:{};return{name:S.name,files:w,...O.length>0?{messages:O,messageContext:{dataSources:(h=S.dataSources)!==null&&h!==void 0?h:[],model:(g=S.model)!==null&&g!==void 0?g:"",enabledTools:Array.isArray(L.enabledTools)?L.enabledTools:[],configurableTools:Array.isArray(L.configurableTools)?L.configurableTools:[]}}:{}}}committed(t,r,n={intentPending:!1}){let i=this.serverState(t,r);return n.intentPending&&t.newTurn!==void 0?{artifact:{...i,newTurn:pm(t.newTurn)},baseline:i}:{artifact:i,baseline:i}}serverState(t,r){var n,i,o,a,s,l;if(!Lc(t)&&!t.newTurn)return t;let u=pm(t);if(delete u.newTurn,!Lc(t))return u;let c={...(n=u.bag)!==null&&n!==void 0?n:{},rows:{...(o=(i=u.bag)===null||i===void 0?void 0:i.rows)!==null&&o!==void 0?o:{}}};for(let d of(a=r.files)!==null&&a!==void 0?a:[]){let f=aM.find(p=>ro[p].name===d.name&&ro[p].fileType===d.fileType);if(!f||u.files.some(p=>p.id===d.id)||(c.rows[f]=d.id,d.content.status!=="available"))continue;let m=(0,ym.base64ToUtf8)(d.content.data);f==="output"?c.output={status:"available",data:d.content.data}:f==="config"?(delete c.config,delete u.dataSources,delete u.model,delete u.connectorBindings,delete u.actionBindings,eM(u,c,(s=mm(m))!==null&&s!==void 0?s:{})):f==="prompt"&&(delete c.prompt,delete u.firstPrompt,delete u.firstAgentMessage,tM(u,c,(l=mm(m))!==null&&l!==void 0?l:{}))}return u.bag=c,u}baselineContent(t){var r;let n={...t};return delete n.conversation,delete n.newTurn,n.files=[...(r=t.files)!==null&&r!==void 0?r:[]].sort((i,o)=>i.id<o.id?-1:i.id>o.id?1:0),n}normalize(t){let r=t.newTurn;return!(0,Ie.isJsonObject)(r)||typeof r.id=="string"&&KF.test(r.id)?t:{...t,newTurn:{...r,id:(0,gm.newId)()}}}async compile(t,r,n){var i;let o=(i=t.dataSources)!==null&&i!==void 0?i:[],a=[],s=[];if(o.forEach((f,m)=>{var p;let h=(p=n?.resolveEntity)===null||p===void 0?void 0:p.call(n,f);h&&h.columnDetailComplete===!0?a.push(h):s.push((0,Ie.issue)(`/dataSources/${m}`,h?"genpage-data-source-incomplete":"genpage-data-source-unresolved",h?`the column metadata of data source '${f}' could not be read completely (a choice or lookup read failed, or returned options with no label), so the page cannot be compiled with its enums. Retry the push.`:`the metadata of data source '${f}' could not be read, so the page cannot be compiled with its enums. Check the table's logical name and that it exists in this environment.`))}),s.length>0)throw new Va.ValidationError("genPage",t.id,s);if(!n?.loadTypeScript)throw new Va.ValidationError("genPage",t.id,[(0,Ie.issue)("/source","genpage-compiler-unavailable","no TypeScript compiler is available to compile the page")]);let l=await n.loadTypeScript(),u=a.length>0?(0,mw.buildGenPageRuntimeTypes)(a):void 0,c=a.length>0?(0,mw.buildGenPageLegacyEnums)(a):void 0,d=(0,iM.compileGenPage)(l,r,u,c);if(d.diagnostics.length>0)throw new Va.ValidationError("genPage",t.id,d.diagnostics.map(rse));return d.code}metadataNeeds(t,r){if(t.source===void 0||!Array.isArray(t.dataSources))return[];let n=ese(t,r)?{fetchRequired:!1}:{};return t.dataSources.filter(i=>typeof i=="string"&&i!=="").map(i=>({entityLogicalName:i,fieldName:"",needsColumnDetail:!0,...n}))}createDefault(t){var r,n;let i=JF(t.id),o={id:i,name:(r=t.name)!==null&&r!==void 0?r:"New page",files:((n=t.files)!==null&&n!==void 0?n:[]).map(a=>{var s,l,u;return{id:JF(a.id),name:(s=a.name)!==null&&s!==void 0?s:"index.tsx",fileType:(l=a.fileType)!==null&&l!==void 0?l:Wo,content:(u=a.content)!==null&&u!==void 0?u:{status:"available",data:""}}})};t.source!==void 0&&(o.source=t.source),t.dataSources!==void 0&&(o.dataSources=[...t.dataSources]);for(let a of["model","firstPrompt","firstAgentMessage"])t[a]!==void 0&&(o[a]=t[a]);return t.newTurn!==void 0&&(o.newTurn={...t.newTurn}),t.connectorBindings!==void 0&&(o.connectorBindings=pm(t.connectorBindings)),t.actionBindings!==void 0&&(o.actionBindings=pm(t.actionBindings)),o.source!==void 0&&(o.bag={rows:{source:fm(i,"source"),output:fm(i,"output"),config:fm(i,"config")}}),o}assignMissingIds(t){if(t==null)return{id:(0,gm.newId)()};if(!(0,Ie.isJsonObject)(t))return t;let r=t;return(Object.keys(r).length===0||"id"in r||"content"in r||"fileType"in r||Array.isArray(r.files))&&(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,gm.newId)()),r}validate(t){let r=[],n=t;for(let s of["source","model","firstPrompt","firstAgentMessage"])n[s]!==void 0&&typeof n[s]!="string"&&r.push((0,Ie.issue)(`/${s}`,"genpage-field-type",`${s} must be a string, got ${typeof n[s]}`));if(n.source===void 0&&to(to(n.bag).rows).source!==void 0&&r.push(nM()),r.push(...rM(t)),n.newTurn!==void 0){let s=to(n.newTurn);(!(0,Ie.isJsonObject)(n.newTurn)||typeof s.prompt!="string"||s.prompt.trim()==="")&&r.push((0,Ie.issue)("/newTurn/prompt","genpage-turn-prompt","newTurn needs a non-empty prompt")),s.agentMessage!==void 0&&typeof s.agentMessage!="string"&&r.push((0,Ie.issue)("/newTurn/agentMessage","genpage-field-type","newTurn.agentMessage must be a string")),s.id!==void 0&&(typeof s.id!="string"||!KF.test(s.id))&&r.push((0,Ie.issue)("/newTurn/id","genpage-turn-id","newTurn.id is the turn's identity, which the SDK mints \u2014 remove it, or keep the GUID it minted"))}if(n.dataSources!==void 0)if(!Array.isArray(n.dataSources))r.push((0,Ie.issue)("/dataSources","genpage-data-sources-array","dataSources must be an array of table logical names"));else{let s=new Set;n.dataSources.forEach((l,u)=>{typeof l!="string"||!mw.TABLE_LOGICAL_NAME.test(l)?r.push((0,Ie.issue)(`/dataSources/${u}`,"genpage-data-source-name",`a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(l)}'`)):s.has(l)?r.push((0,Ie.issue)(`/dataSources/${u}`,"genpage-data-source-duplicate",`data source '${l}' is listed twice`)):s.add(l)})}n.conversation!==void 0&&!Array.isArray(n.conversation)&&r.push((0,Ie.issue)("/conversation","genpage-conversation-array","conversation must be an array"));let i=n.files;if(i!==void 0&&!Array.isArray(i))return r.push((0,Ie.issue)("/files","files-must-be-array",`files must be an array, got ${typeof i}`)),r;let o=Lc(t),a=new Map;return(Array.isArray(i)?i:[]).forEach((s,l)=>{let u=`/files/${l}`,c=to(s),d=typeof c.id=="string"?c.id.trim().toLowerCase():"";if(d==="")r.push((0,Ie.issue)(u,"file-id-required","a generative-page file needs an id"));else{let g=a.get(d);g!==void 0?r.push((0,Ie.issue)(u,"file-id-duplicate",`two files share the id '${c.id}' (also at /files/${g}); a file's id is its identity, so a duplicate makes an edit ambiguous`)):a.set(d,l)}let f=typeof c.name=="string"?c.name:"",m=f.split("/");f===""||/[\u0000-\u001F\u007F]/.test(f)||f.includes("\\")||m.some(g=>g===""||g==="."||g==="..")?r.push((0,Ie.issue)(u+"/name","file-name-invalid",`a file name must be a relative path of non-empty '/'-separated segments (no '.', '..', backslash or control character \u2014 its last segment is sent as an HTTP header); got '${f}'`)):o&&(QF(f)||YF(f,Number(c.fileType))!==void 0)&&r.push((0,Ie.issue)(u+"/name","file-name-reserved",`'${f}' would be read by the maker portal as one of the page's managed rows (its source, output, config or first prompt), which the SDK writes from source and the configuration fields; it cannot also be a file in files[]`));let p=c.content;if(p===void 0){r.push((0,Ie.issue)(u+"/content","file-content-required","content is required: omitting it is indistinguishable from an empty file, and the two have opposite effects on the next push"));return}let h=to(p);h.status==="available"?typeof h.data!="string"&&r.push((0,Ie.issue)(u+"/content/data","file-content-data-invalid","available content needs base64 `data`")):h.status!=="unavailable"&&r.push((0,Ie.issue)(u+"/content/status","file-content-status-invalid",`content.status must be 'available' or 'unavailable', got ${String(h.status)}`))}),r}};Tl.GenPageAdapter=bm;function rse(e){let t=`line ${e.line}, column ${e.column}`;return e.rule==="genpage-source-syntax"?(0,Ie.issue)("/source",e.rule,`${t}: ${e.message} (TS${e.code}) \u2014 the page cannot run, so it was not pushed`):(0,Ie.issue)("/source",e.rule,`${t}: ${e.message}`)}function nse(){return{adapter:new bm,api:zae.genPageApi,publish:(e,t)=>(0,jae.publishGenPageById)(e,t),publishScope:e=>({envelope:"uxagentproject",targetIds:[e]}),rebaselineAfterPublish:"snapshot"}}Tl.genPageRegistration=nse});var fM=v(wm=>{"use strict";Object.defineProperty(wm,"__esModule",{value:!0});wm.reconcileBpfSecurityRoles=void 0;var dM=Tt(),yw=Q(),vm=fe(),kc=oe(),ise="Global",gw={create:"Create",read:"Read",write:"Write",delete:"Delete"};async function ose(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,kc.odataPathLiteral)(t)}')?$select=LogicalName,Privileges`,i=(0,vm.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.Privileges;if(!Array.isArray(o))throw new yw.ConnectionError(e.apiUrl(n),i.status,`reading the privileges of business process flow table '${t}' returned no 'Privileges' array (got ${(0,dM.describeMalformedValue)(o)}), so which access it can grant is unknown.`);let a=o,s={},l=new Set;return Object.keys(gw).forEach(u=>{let c=a.find(d=>d.PrivilegeType===gw[u]);if(c){let d=(0,kc.normalizeGuid)(c.PrivilegeId,"PrivilegeId");s[u]=d,l.add(d)}}),{byAccess:s,all:l}}async function ase(e,t){var r;let n=`/RetrieveRolePrivilegesRole(RoleId=${t})`,i=(0,vm.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.RolePrivileges;if(!Array.isArray(o))throw new yw.ConnectionError(e.apiUrl(n),i.status,`reading the privileges of role '${t}' returned no 'RolePrivileges' array (got ${(0,dM.describeMalformedValue)(o)}), so what it holds is unknown.`);return new Set(o.map(a=>(0,kc.normalizeGuid)(a.PrivilegeId,"PrivilegeId")))}async function sse(e,t,r){if(r.length===0)return;let n={Privileges:r.map(o=>({Depth:ise,PrivilegeId:o}))},i=`/roles(${t})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;(0,vm.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function lse(e,t,r){let n={Privilege:{"@odata.type":"Microsoft.Dynamics.CRM.privilege",privilegeid:r}},i=`/roles(${t})/Microsoft.Dynamics.CRM.RemovePrivilegeRole`;(0,vm.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function use(e,t,r){var n,i,o;if(!r||r.length===0)return;let a=await ose(e,t.toLowerCase());for(let s of r){let l=(0,kc.normalizeGuid)(s.roleId,"roleId"),u=((n=s.access)!==null&&n!==void 0?n:[]).find(c=>!a.byAccess[c]);if(u!==void 0)throw new yw.InvalidArgumentError(`Cannot grant '${u}' access to role '${l}' on business process flow table '${t.toLowerCase()}': its metadata lists no '${(i=gw[u])!==null&&i!==void 0?i:u}' privilege. No security role was changed.`)}for(let s of r){let l=(0,kc.normalizeGuid)(s.roleId,"roleId"),u=new Set(((o=s.access)!==null&&o!==void 0?o:[]).map(p=>a.byAccess[p]).filter(p=>!!p)),c=await ase(e,l),d=new Set([...c].filter(p=>a.all.has(p))),f=[...u].filter(p=>!d.has(p)),m=[...d].filter(p=>!u.has(p));await sse(e,l,f);for(let p of m)await lse(e,l,p)}}wm.reconcileBpfSecurityRoles=use});var NM=v(Em=>{"use strict";Object.defineProperty(Em,"__esModule",{value:!0});Em.bpfApi=void 0;var vr=lo(),pM=Es(),cse=Tt(),Xe=Q(),ht=fe(),An=oe(),dse=fM(),fse=lh(),$c=ch(),pse={"Content-Type":"application/json",Accept:"application/json"},vw={...pse,Prefer:"return=representation"},mse=`category eq ${vr.WorkflowCategory.BusinessProcessFlow} and type eq ${vr.WorkflowTypeCode.Definition} and businessprocesstype eq ${vr.BusinessProcessType.BusinessFlow}`,hse="workflowid,name,description,primaryentity,statecode,category,type,businessprocesstype,processorder",gse="workflowid,name,uniquename,description,primaryentity,statecode,statuscode,category,type,businessprocesstype,processorder,xaml,clientdata",yse=["xaml","name","description","processorder"];async function bw(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,dse.reconcileBpfSecurityRoles)(e,n,t.securityRoles)}async function Cw(e,t,r){let n={statecode:vr.StateCode.Activated,statuscode:vr.StatusCode.Activated},i=`/workflows(${t})`,{response:o,resent:a}=await SM(e,i,n,r,null);try{return(0,ht.ensureSuccess)(o,e.apiUrl(i))}catch(s){throw a?EM(s):s}}var CM=new WeakSet;function EM(e){return typeof e=="object"&&e!==null&&CM.add(e),e}function AM(e){return typeof e=="object"&&e!==null&&CM.has(e)}function mM(e){return e instanceof Xe.ConnectionError&&(e.statusCode===0||ht.AMBIGUOUS_WRITE_STATUSES.has(e.statusCode))}async function SM(e,t,r,n,i){let o=n??i,a=0;try{return{response:await(0,ht.resendWhile)(ht.isConcurrencyLockRefusal,()=>{a+=1;let l=a===1?n:o,u={...vw};return l&&(u["If-Match"]=l),e.patch(t,r,{headers:u})},o?ht.LOCK_BACKOFF_MS:[]),resent:a>1}}catch(s){throw a>1?EM(s):s}}async function hM(e,t,r){return(0,ht.readEtag)(await Cw(e,t,r))}function gM(e,t){return new Xe.SdkError("BPF_WRITE_NOT_ECHOED",`The ${t} of business process flow '${e}' was applied, but the server returned no concurrency token for it (this environment did not honour 'Prefer: return=representation'), so the next step could not be conditioned on a token this push produced and was NOT sent. `+Cm(e))}async function xc(e,t){var r;let n=`/workflows(${t})${(0,An.odataQuery)([["$select","statecode"]])}`,i=(0,ht.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.statecode,a=Number(o);if(o==null||o===""||!Number.isFinite(a))throw new Xe.SdkError("BPF_STATE_UNREADABLE",`Reading the state of business process flow '${t}' answered HTTP ${i.status} without a usable statecode, so whether it is Active cannot be decided.`);return a}async function ww(e,t,r,n,i=null){if((n??await xc(e,t))!==vr.StateCode.Activated)return{deactivated:!1,etag:null};let o={statecode:vr.StateCode.Draft,statuscode:vr.StatusCode.Draft},a=`/workflows(${t})`,s,l;try{({response:s,resent:l}=await SM(e,a,o,r,i))}catch(c){return await yM(e,t,c,AM(c))}if(ht.AMBIGUOUS_WRITE_STATUSES.has(s.status))return await yM(e,t,new Xe.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",`Deactivating business process flow '${t}' answered HTTP ${s.status} from an intermediary, so whether it committed is unknown.`),l);let u=(0,ht.ensureSuccess)(s,e.apiUrl(a));return{deactivated:!0,etag:(0,ht.readEtag)(u)}}async function yM(e,t,r,n){let i;try{i=await xc(e,t)}catch{i=void 0}if(i===vr.StateCode.Draft&&!n)return{deactivated:!0,etag:null,uncertainCause:r};if(i===vr.StateCode.Activated)throw r;let o=new Xe.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",i===vr.StateCode.Draft?`Deactivating business process flow '${t}' waited for the platform's concurrency lock, and its last attempt ended without a definitive answer. The process now reads Draft, but whether this deactivate or another writer's change put it there is unknown \u2014 the row may even have been replaced at the same id \u2014 so nothing more was sent: no edit, no re-activation, no delete. It MAY be left DISABLED: read it before retrying. Original failure: ${r instanceof Error?r.message:String(r)}`:`Deactivating business process flow '${t}' did not complete, and its state could not be re-read \u2014 it MAY be left DISABLED and needs reconciling. Original failure: ${r instanceof Error?r.message:String(r)}`);throw(0,Xe.attachCause)(o,r),o}async function bse(e,t){let r=(0,An.normalizeGuid)(t,"workflowid");try{return await Cw(e,r,null),"restored"}catch{return Ew(e,r)}}async function vse(e,t,r){let n=(0,An.normalizeGuid)(t,"workflowid");try{return await Cw(e,n,r),"restored"}catch(i){return i instanceof Xe.SdkError&&i.code===ht.VERSION_CONFLICT_CODE?"changed":Ew(e,n)}}async function Ew(e,t){try{let r=await xc(e,t);return r===vr.StateCode.Activated?"restored":r===vr.StateCode.Draft?"disabled":"unknown"}catch{return"unknown"}}async function bM(e,t,r,n){return r?{outcome:await vse(e,t,r),attempted:!0}:n?{outcome:await Ew(e,(0,An.normalizeGuid)(t,"workflowid")),attempted:!1}:{outcome:await bse(e,t),attempted:!0}}function wse(e,t){let r=new Xe.SdkError($c.WORKFLOW_DELETE_UNSETTLED_CODE,`Deleting business process flow '${e}' failed${(0,$c.failedAfterResend)(t)?" after it was re-sent":""}, and re-activating the process this delete had deactivated was refused (HTTP 412): the row at that id is no longer the version this delete deactivated \u2014 it was edited, or deleted and re-created at the same id \u2014 so it was NOT re-activated, and it MAY be left DISABLED. Read the row before deleting it again. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Xe.attachCause)(r,t),r}function vM(e,t,r,n,i=!0){let o=`Original failure: ${n instanceof Error?n.message:String(n)}`,a="it was NOT re-activated: it waited for the platform's concurrency lock, and no write of this operation proves the row is still its own, so a re-activation could have enabled another writer's edit",s;return r==="changed"?s=new Xe.SdkError("BPF_REACTIVATE_OUTCOME_UNKNOWN",`Business process flow '${e}' was deactivated ${t}, and re-activating it was refused (HTTP 412): the row is no longer the version this operation last wrote \u2014 another writer changed it, or replaced it at the same id \u2014 so it was NOT re-activated, and it MAY be left DISABLED. Read it before retrying. ${o}`):r==="disabled"?s=new Xe.SdkError("BPF_LEFT_DEACTIVATED",i?`Business process flow '${e}' was deactivated ${t}, and it could NOT be reactivated \u2014 it is left DISABLED. ${o}`:`Business process flow '${e}' was deactivated ${t}, and ${a} \u2014 it is left DISABLED. ${o}`):s=new Xe.SdkError("BPF_REACTIVATE_OUTCOME_UNKNOWN",i?`Business process flow '${e}' was deactivated ${t}, and whether it was reactivated could not be confirmed \u2014 it MAY be left DISABLED and needs checking. ${o}`:`Business process flow '${e}' was deactivated ${t}, and ${a}; its state could not be read \u2014 it MAY be left DISABLED and needs checking. ${o}`),(0,Xe.attachCause)(s,n),s}async function Cse(e,t){try{return await xc(e,t),"survived"}catch(r){return r instanceof Xe.ConnectionError&&r.statusCode===404?"removed":"unknown"}}async function Ese(e,t,r){if(r)try{let{deactivated:n,etag:i}=await ww(e,t,r),o=n?i:r;if(o)return await(0,$c.deleteWorkflowResending)(e,t,{bindingToken:o,kindName:"business process flow",resendDeadlockVictim:!0,ifMatchOnFirst:!0}),"removed"}catch{}return Cse(e,t)}function Cm(e){return`Adopt the server's copy with fetchArtifact('bpf', '${e}', { overwrite: true }) \u2014 it REPLACES the local copy, so keep any outstanding local changes aside first \u2014 then re-apply them and push.`}function wM(e,t){return new Xe.SdkError("BPF_CREATE_NO_TOKEN",`Created business process flow '${e}' but the server returned no concurrency token for it (this environment did not honour 'Prefer: return=representation'), so the next push would have nothing to condition on. ${t} It was NOT rolled back: deleting it without a token could remove an edit made since. ${Cm(e)}`)}function Ase(e,t){let r=new Xe.SdkError("BPF_CREATE_NOT_ROLLED_BACK",`Creating business process flow '${e}' failed part-way, and the rollback could NOT remove it \u2014 it still EXISTS, possibly Active and half-configured. (The rollback deletes only on a token this create produced, so a row somebody has since edited is left in place on purpose; a delete the platform refused or failed leaves it too.) ${Cm(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Xe.attachCause)(r,t),r}function Sse(e,t){let r=new Xe.SdkError("BPF_CREATE_ROLLBACK_OUTCOME_UNKNOWN",`Creating business process flow '${e}' failed part-way, and whether its rollback removed the process could not be confirmed \u2014 it MAY still exist, possibly Active and half-configured. ${Cm(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Xe.attachCause)(r,t),r}function Nse(e,t){let r=new Xe.SdkError("BPF_CREATE_REMOVED_AFTER_CONFLICT",`Creating business process flow '${e}' was interrupted: another writer changed it right after it was created, so this push's next step was refused rather than overwrite or activate their edit \u2014 and the process has since been removed. Nothing is left behind and there is nothing to fetch. If the removal was deliberate, stop here; otherwise push again to re-create it at the same id. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Xe.attachCause)(r,t),r}function Aw(e){let t={};for(let r of yse)e[r]!==void 0&&(t[r]=e[r]);return t}var _se=["name,processorder","description,name,processorder"];function Tse(e){let{xaml:t,...r}=Aw(e);return typeof t=="string"&&_se.includes(Object.keys(r).sort().join(","))}async function Dse(e,t,r,n){let{xaml:i,...o}=Aw(r),[,a]=await(0,pM.sendChangeSet)(e,[{method:"PATCH",path:`/workflows(${t})`,body:o,etag:n},{method:"PATCH",path:`/workflows(${t})${(0,An.odataQuery)([["$select","workflowid"]])}`,body:{xaml:i},headers:{Prefer:"return=representation"}}],`business process flow '${t}'`);return(0,ht.readEtag)((0,pM.partResponse)(a))}Em.bpfApi={async get(e,t){let n=`/workflows(${(0,An.normalizeGuid)(t,"id")})${(0,An.odataQuery)([["$select",gse]])}`,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=[mse];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,An.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,An.odataQuery)([["$select",hse],["$filter",r.join(" and ")]])}`;return(await(0,cse.collectPages)(e,n,"listArtifacts('bpf')")).map(o=>{var a,s;return{type:"bpf",id:(a=o.workflowid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",entityLogicalName:o.primaryentity,isDirty:!1}})},async create(e,t){let r=t,n=(0,An.normalizeGuid)(r.record.workflowid,"workflowid"),i="/workflows",o=(0,ht.ensureSuccess)(await e.post(i,r.record,{headers:vw}),e.apiUrl(i)),a=(0,ht.readEtag)(o);if(!a)throw wM(n,r.status==="Active"?"The process EXISTS as Draft and was NOT activated \u2014 an activation that cannot be conditioned on our own write could activate somebody else's edit.":"The process EXISTS as Draft.");let s=a;try{r.status==="Active"&&(s=await hM(e,n,a)),await bw(e,r)}catch(l){let u=await Ese(e,n,s);throw u==="survived"?Ase(n,l):u==="unknown"?Sse(n,l):l instanceof Xe.SdkError&&l.code===ht.VERSION_CONFLICT_CODE?Nse(n,l):l}if(!s)throw wM(n,"The process EXISTS and IS Active, but its activation returned no token.");return{id:n,etag:s}},async update(e,t,r,n){let i=r,o=(0,An.normalizeGuid)(t,"id"),a=(0,ht.requireEtag)(n,"bpf",o),s=await xc(e,o);if(s===vr.StateCode.Activated&&i.status==="Active"&&e.supportsAtomicBatch&&Tse(i.record)){let m=await Dse(e,o,i.record,a);return await bw(e,i),{id:o,etag:m}}let{deactivated:l,etag:u,uncertainCause:c}=await ww(e,o,a,s),d=u,f=!1;try{if(c!==void 0)throw c;let m=a;if(l){if(!u)throw gM(o,"deactivation");m=u}let p=`/workflows(${o})`,h;try{h=(0,ht.ensureSuccess)(await e.patch(p,Aw(i.record),{headers:{...vw,"If-Match":m}}),e.apiUrl(p))}catch(b){throw mM(b)&&(d=null),b}let g=(0,ht.readEtag)(h);if(d=g,i.status==="Active"){if(!g)throw gM(o,"definition write");try{g=await hM(e,o,g)}catch(b){throw mM(b)&&(d=null),b}f=!0}return await bw(e,i),{id:o,etag:g}}catch(m){if(l&&!f){let{outcome:p,attempted:h}=await bM(e,o,d,AM(m));if(p!=="restored")throw vM(o,"to apply an edit, the edit failed",p,m,h)}throw m}},async delete(e,t){let r=(0,An.normalizeGuid)(t,"id"),n=await(0,fse.assertWorkflowKind)(e,r,vr.WorkflowCategory.BusinessProcessFlow),{deactivated:i,etag:o}=await ww(e,r,null,void 0,n);try{await(0,$c.deleteWorkflowResending)(e,r,{bindingToken:i?o:n,kindName:"business process flow",deactivated:i,resendDeadlockVictim:!0})}catch(a){if(i&&!(0,$c.isWorkflowDeleteUnsettled)(a)){let{outcome:s,attempted:l}=await bM(e,r,o,!1);if(s==="changed")throw wse(r,a);if(s!=="restored")throw vM(r,"so it could be deleted, the delete failed",s,a,l)}throw a}}}});var lU=v(Il=>{"use strict";Object.defineProperty(Il,"__esModule",{value:!0});Il.bpfRegistration=Il.BpfAdapter=void 0;var Am=lo(),Ise=NM(),Sw=wo(),Ga=Eo(),MM=Co(),tn=cn(),Gr=ct(),Wn=Q(),Ose=100,Nw='<?xml version="1.0" encoding="utf-16"?>',_M=1033,UM="mxswa:Workflow",Pse="mxswa:ActivityReference.Properties",Rse="mcwo:StepLabel",Lse="mcwb:Control",TM="mcwb:Control.ControlDisplayName",BM="mcwb:Control.DataFieldName",qM="DataFieldName",DM="ControlDisplayName",VM="Literal",Nm="x:Null",IM="x:String",_w="x:Key",Tw="DisplayName",Tm="Activities",kse="StepLabels",GM="StageId",WM="StageCategory",zM="NextStageId",jM="ProcessStepId",Sm="IsProcessRequired",HM="EntityComposite",KM="StageComposite",JM="StepComposite";function Fc(e){return(0,tn.isJsonObject)(e)?e:{}}function wi(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 Wa(e,t){var r;return(r=wi(e).find(n=>n.tagName===t))!==null&&r!==void 0?r:null}function Ei(e){return Wa(e,Pse)}function wr(e,t){var r;return(r=wi(e).find(n=>n.getAttribute(_w)===t))!==null&&r!==void 0?r:null}function Dl(e,t){var r;return((r=e.getAttribute("AssemblyQualifiedName"))!==null&&r!==void 0?r:"").includes(t)}function Ci(e){var t;return!e||!e.firstChild?"":(t=e.firstChild.nodeValue)!==null&&t!==void 0?t:""}function YM(e,t,r){e.firstChild?e.firstChild.nodeValue=r:e.appendChild(t.createTextNode(r))}function Mc(e){var t;let r=(t=e.getAttribute(Tw))!==null&&t!==void 0?t:"",n=r.indexOf(": ");return n>=0?r.slice(n+2):r}function QM(e,t){var r;let n=(r=e.getAttribute(Tw))!==null&&r!==void 0?r:"",i=n.indexOf(": ");e.setAttribute(Tw,i>=0?n.slice(0,i+2)+t:t)}function XM(e,t){let r=wr(e,kse),n=Wa(r,Rse);n&&n.setAttribute("Description",t)}function $se(e){let t=wr(e,WM);if(!t||t.tagName===Nm)return;let r=Ci(t).trim();return r===""?void 0:Number(r)}function xse(e){let t=wr(e,zM);if(!t||t.tagName===Nm)return;let r=Ci(t).trim();return r===""?void 0:r}function ZM(e){let t=eU(e);if(!t)return;let r=rU(t,qM,BM);return r===""?void 0:r}function Dw(e,t){let r=wi(e);for(;r.length>0;){let n=r.pop();if(n.tagName===t)return n;for(let i of wi(n))r.push(i)}return null}function eU(e){let t=wr(Ei(e),Tm);return t?Dw(t,Lse):null}function tU(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 rU(e,t,r){var n;return tU(e,t)?(n=e.getAttribute(t))!==null&&n!==void 0?n:"":qse(e,r)}function OM(e,t,r,n){if(tU(e,t)){e.setAttribute(t,n);return}if(Wa(e,r)){Fse(e,r,n);return}throw new Wn.InvalidArgumentError(`BPF step control exposes neither a '${t}' attribute nor a <${r}> wrapper to bind a column`)}function Fse(e,t,r){let n=Wa(e,t),i=n?Dw(n,VM):null;if(!i)throw new Wn.InvalidArgumentError(`BPF step control's <${t}> wrapper holds no <Literal> to bind a column`);i.setAttribute("Value",r)}function nU(e){return Mc(e)}function Dm(e){let t=Wa(e,UM),r=[];for(let n of wi(t).filter(i=>Dl(i,HM))){let i=wr(Ei(n),Tm);for(let o of wi(i).filter(a=>Dl(a,KM)))r.push({el:o,entity:nU(n)})}return r}function Iw(e){let t=wr(Ei(e),Tm);return wi(t).filter(r=>Dl(r,JM))}function Mse(e){let t=Ei(e),r=Ci(wr(t,Sm)).trim().toLowerCase(),n=ZM(e),i={id:Ci(wr(t,jM)),name:Mc(e)};return n!==void 0&&(i.fieldName=n),r==="true"&&(i.required=!0),i}function Use(e,t){let r=Ei(e),n=$se(r),i=xse(r),o={id:Ci(wr(r,GM)),name:Mc(e),entityLogicalName:t,steps:Iw(e).map(Mse)};return n!==void 0&&(o.category=n),i!==void 0&&(o.nextStageId=i),o}function Bse(e){return Dm(e).map(({el:t,entity:r})=>Use(t,r))}function vi(e){return new Wn.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 qse(e,t){var r;let n=Wa(e,t),i=n?Dw(n,VM):null;return(r=i?.getAttribute("Value"))!==null&&r!==void 0?r:""}function Ow(e,t){var r;let n=e.createElement(t.tagName),i=t.attributes;for(let a=0;a<i.length;a+=1)n.setAttribute(i[a].name,i[a].value);let o=t.childNodes;for(let a=0;a<o.length;a+=1){let s=o[a];s.nodeType===1?n.appendChild(Ow(e,s)):s.nodeType===3&&n.appendChild(e.createTextNode((r=s.nodeValue)!==null&&r!==void 0?r:""))}return n}function iU(e){return wr(Ei(e),Tm)}function Vse(e,t,r){var n;let i=t.entityLogicalName&&t.entityLogicalName.trim()!==""?t.entityLogicalName:r,o=!((n=t.steps[0])===null||n===void 0)&&n.id&&t.steps[0].id.trim()!==""?t.steps[0].id:(0,Gr.newId)(),{body:a}=Im(Pw(i,(0,Gr.newId)(),t.id,o));return Ow(e,Dm((0,Ga.parseXmlRoot)(a,"<Activity/>"))[0].el)}function Gse(e,t){let{body:r}=Im(Pw("account",(0,Gr.newId)(),(0,Gr.newId)(),t.id));return Ow(e,Iw(Dm((0,Ga.parseXmlRoot)(r,"<Activity/>"))[0].el)[0])}function oU(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);for(let r of t)e.appendChild(r)}function aU(e,t,r,n){let i=wr(e,r);if(!i||!i.parentNode){if(n!==void 0&&n!=="")throw vi(`setting '${r}' on a stage whose xaml does not expose that slot`);return}let o=i.parentNode;if(n===void 0||n===""){if(i.tagName!==Nm&&Ci(i).trim()!==""){let s=t.createElement(Nm);s.setAttribute(_w,r),o.replaceChild(s,i)}return}if(i.tagName===IM){Ci(i).trim()!==n&&YM(i,t,n);return}let a=t.createElement(IM);a.setAttribute(_w,r),a.appendChild(t.createTextNode(n)),o.replaceChild(a,i)}function Wse(e,t,r){aU(e,t,WM,r===void 0?void 0:String(r))}function zse(e,t,r){aU(e,t,zM,r)}function sU(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 PM(e){return Ci(wr(Ei(e),GM))}function RM(e){return Ci(wr(Ei(e),jM))}function LM(e,t,r){var n,i,o,a;let s=Ei(e);r.name!==Mc(e)&&(QM(e,r.name),XM(s,r.name));let l=Ci(wr(s,Sm)).trim().toLowerCase()==="true";if(((n=r.required)!==null&&n!==void 0?n:!1)!==l){let u=wr(s,Sm);if(!u)throw vi(`setting '${Sm}' on a step whose xaml does not expose that slot`);YM(u,t,r.required?"True":"False")}if(((i=r.fieldName)!==null&&i!==void 0?i:"")!==((o=ZM(e))!==null&&o!==void 0?o:"")){let u=eU(e);if(!u)throw new Wn.InvalidArgumentError("BPF step has no <mcwb:Control> element to bind a column to");let c=(a=r.fieldName)!==null&&a!==void 0?a:"";OM(u,qM,BM,c),c!==""&&rU(u,DM,TM)===""&&OM(u,DM,TM,c)}}function kM(e,t,r,n){var i;let o=Ei(e);if(!o)throw new Wn.InvalidArgumentError("BPF stage composite has no <\u2026ActivityReference.Properties>");if(r.name!==Mc(e)&&(QM(e,r.name),XM(o,r.name)),Wse(o,t,r.category),zse(o,t,n),r.relationshipName&&r.relationshipName.trim()!=="")throw vi("a stage relationship / table change (multi-table authoring)");if(r.actions&&r.actions.length>0||r.branch)throw vi("stage actions or conditional branching");let a=iU(e);if(!a)throw new Wn.InvalidArgumentError("BPF stage has no [Activities] collection");let s=(i=r.steps)!==null&&i!==void 0?i:[];if(s.length===0)throw new Wn.InvalidArgumentError(`BPF stage '${r.name}' must have at least one step`);let l=Iw(e);if(sU(l,s.map(d=>d.id),RM)){l.forEach((d,f)=>LM(d,t,s[f]));return}let u=new Map(l.map(d=>[RM(d),d]));if(wi(a).some(d=>!Dl(d,JM)))throw vi("adding, removing or reordering steps on a stage that also contains branching or actions");let c=s.map(d=>{var f;return(f=u.get(d.id))!==null&&f!==void 0?f:Gse(t,d)});oU(a,c),c.forEach((d,f)=>LM(d,t,s[f]))}function jse(e,t,r){let n=Wa(e,UM);if(!n)throw new Wn.InvalidArgumentError("BPF xaml has no <mxswa:Workflow> root activity");if(r.globalActions&&r.globalActions.length>0)throw vi("global (process-completed/abandoned) actions");if(!r.stages||r.stages.length===0)throw new Wn.InvalidArgumentError("a BPF must have at least one stage");let i=Dm(e),o=i.map(f=>f.el);if(sU(o,r.stages.map(f=>f.id),PM)){i.forEach(({el:f,entity:m},p)=>{let h=r.stages[p];if(h.entityLogicalName&&h.entityLogicalName.trim()!==""&&h.entityLogicalName!==m)throw vi(`changing a stage's table ('${h.entityLogicalName}' vs the process's '${m}')`);kM(f,t,h,h.nextStageId)});return}let a=wi(n).filter(f=>Dl(f,HM));if(a.length!==1)throw vi("adding, removing or reordering stages on a multi-table process");let s=a[0],l=nU(s),u=iU(s);if(!u)throw new Wn.InvalidArgumentError("BPF primary entity composite has no [Activities] collection");if(wi(u).some(f=>!Dl(f,KM)))throw vi("adding, removing or reordering stages on a process whose primary composite holds non-stage activities (multi-table nesting or advanced constructs)");for(let f of r.stages)if(f.entityLogicalName&&f.entityLogicalName.trim()!==""&&f.entityLogicalName!==l)throw vi(`a stage on a different table ('${f.entityLogicalName}') than the process primary ('${l}')`);let c=new Map(o.map(f=>[PM(f),f])),d=r.stages.map(f=>{var m;return(m=c.get(f.id))!==null&&m!==void 0?m:Vse(t,f,l)});oU(u,d),d.forEach((f,m)=>{let p=m<d.length-1?r.stages[m+1].id:void 0;kM(f,t,r.stages[m],p)})}function Im(e){let t=e.match(/^<\?xml[^>]*\?>\s*/),r=t?t[0]:"";return{prolog:r,body:e.slice(r.length)}}function Hse(e){var t,r,n,i,o,a;(0,MM.installDomShim)();let s=(t=e.bag)===null||t===void 0?void 0:t.xaml;if(s){let f=new DOMParser().parseFromString("<root/>","text/xml"),m={n:"Activity",a:(0,Sw.mergeAttrs)(s.a,[]),c:(0,Sw.spliceChildren)(s.c,[])};return{root:(0,Sw.rebuildRaw)(m,(0,Ga.domEngine)(f),null),prolog:(n=(r=e.bag)===null||r===void 0?void 0:r.xamlProlog)!==null&&n!==void 0?n:Nw,eol:(o=(i=e.bag)===null||i===void 0?void 0:i.xamlEol)!==null&&o!==void 0?o:"lf"}}let l=e.stages[0],u=(a=l?.steps)===null||a===void 0?void 0:a[0],c=Pw(e.entityLogicalName,(0,Gr.newId)(),l?.id&&l.id.trim()!==""?l.id:(0,Gr.newId)(),u?.id&&u.id.trim()!==""?u.id:(0,Gr.newId)()),{body:d}=Im(c);return{root:(0,Ga.parseXmlRoot)(d,"<Activity/>"),prolog:Nw,eol:"lf"}}function Kse(e){let{root:t,prolog:r,eol:n}=Hse(e);jse(t,t.ownerDocument,e);let i=(0,Ga.serializeNode)(t);return n==="crlf"&&(i=i.replace(/\n/g,`\r+`)),r+i}function Jse(e){return e.uniqueName&&e.uniqueName.trim()!==""?e.uniqueName:`new_${(e.name||"businessprocessflow").toLowerCase().replace(/[^a-z0-9]/g,"")||"businessprocessflow"}`}var _m=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var r,n;(0,MM.installDomShim)();let i=t,o=typeof i.xaml=="string"?i.xaml:"",a={id:i.workflowid?String(i.workflowid):null,name:String((r=i.name)!==null&&r!==void 0?r:""),entityLogicalName:String((n=i.primaryentity)!==null&&n!==void 0?n:""),status:Number(i.statecode)===1?"Active":"Draft",stages:[]};if(i.uniquename&&(a.uniqueName=String(i.uniquename)),i.description!=null&&i.description!==""&&(a.description=String(i.description)),i.processorder!=null&&i.processorder!==""&&(a.order=Number(i.processorder)),o.trim()!==""){let{prolog:s,body:l}=Im(o),u=(0,Ga.parseXmlRoot)(l,"<Activity/>");a.stages=Bse(u),a.bag={xaml:(0,Ga.projectElementBag)(u),xamlProlog:s,xamlEol:/\r\n/.test(o)?"crlf":"lf"}}return a}toApiPayload(t){var r;let n={workflowid:t.id&&t.id.trim()!==""?t.id:(0,Gr.newId)(),name:t.name,uniquename:Jse(t),primaryentity:t.entityLogicalName,xaml:Kse(t),category:Am.WorkflowCategory.BusinessProcessFlow,type:Am.WorkflowTypeCode.Definition,businessprocesstype:Am.BusinessProcessType.BusinessFlow,scope:Am.WorkflowScope.Organization,processorder:(r=t.order)!==null&&r!==void 0?r:Ose};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 Wn.InvalidArgumentError('securityRoles require the BPF to be Active \u2014 the backing table they grant access to is created on activation; set status to "Active" to wire security roles');i.securityRoles=t.securityRoles}return i}createDefault(t){var r,n,i;let o=t.stages&&t.stages.length>0?t.stages.map(xM):[xM({id:(0,Gr.newId)(),name:"New Stage",steps:[]})],a={id:t.id&&t.id.trim()!==""?t.id:(0,Gr.newId)(),name:(r=t.name)!==null&&r!==void 0?r:"New business process flow",entityLogicalName:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",status:(i=t.status)!==null&&i!==void 0?i:"Draft",stages:o};return t.uniqueName&&(a.uniqueName=t.uniqueName),t.description!==void 0&&(a.description=t.description),t.order!==void 0&&(a.order=t.order),t.globalActions!==void 0&&(a.globalActions=t.globalActions),t.securityRoles!==void 0&&(a.securityRoles=t.securityRoles),a}assignMissingIds(t){let r=Fc(t);(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,Gr.newId)());for(let n of["stages","steps","actions","globalActions"]){let i=r[n];Array.isArray(i)&&i.forEach(o=>this.assignMissingIds(o))}return r}validate(t){let r=[],n=t.stages;if(n!==void 0&&!Array.isArray(n))return r.push((0,tn.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,tn.issue)("/stages","too-many-stages",`a BPF allows at most 30 stages, got ${i.length}`));let o=new Set,a=new Map;i.forEach((l,u)=>{let c=`/stages/${u}`,d=Fc(l),f=typeof d.id=="string"?d.id.trim():"";f===""?r.push((0,tn.issue)(`${c}/id`,"stage-id-required","a stage needs an id")):a.has(f.toLowerCase())?r.push((0,tn.issue)(`${c}/id`,"stage-id-duplicate",`two stages share the id '${d.id}' (also at /stages/${a.get(f.toLowerCase())})`)):a.set(f.toLowerCase(),u),typeof d.entityLogicalName=="string"&&d.entityLogicalName!==""&&o.add(d.entityLogicalName);let m=Array.isArray(d.steps)?d.steps:[];m.length===0&&r.push((0,tn.issue)(`${c}/steps`,"stage-needs-step","a BPF stage must have at least one step")),m.length>30&&r.push((0,tn.issue)(`${c}/steps`,"too-many-steps",`a stage allows at most 30 steps, got ${m.length}`));let p=new Map;m.forEach((h,g)=>{let b=`${c}/steps/${g}`,w=typeof Fc(h).id=="string"?h.id.trim():"";w===""?r.push((0,tn.issue)(`${b}/id`,"step-id-required","a step needs an id")):p.has(w.toLowerCase())?r.push((0,tn.issue)(`${b}/id`,"step-id-duplicate",`two steps in this stage share the id '${h.id}'`)):p.set(w.toLowerCase(),g)}),d.branch&&!$M(i,d.branch.nextStageId)&&r.push((0,tn.issue)(`${c}/branch/nextStageId`,"branch-target-unknown",`branch nextStageId '${d.branch.nextStageId}' does not match any stage id`)),typeof d.nextStageId=="string"&&d.nextStageId!==""&&!$M(i,d.nextStageId)&&r.push((0,tn.issue)(`${c}/nextStageId`,"next-stage-unknown",`nextStageId '${d.nextStageId}' does not match any stage id`))}),o.size>5&&r.push((0,tn.issue)("/stages","too-many-tables",`a BPF spans at most 5 tables, got ${o.size}`));let s=Yse(i);return s>=0&&r.push((0,tn.issue)(`/stages/${s}/nextStageId`,"next-stage-cycle","the stage nextStageId links form a cycle; the flow must be acyclic")),r}};Il.BpfAdapter=_m;function Yse(e){let t=new Map(e.map(r=>[Fc(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 $M(e,t){return e.some(r=>Fc(r).id===t)}function xM(e){var t,r;let n=e.steps&&e.steps.length>0?e.steps.map(FM):[FM({id:(0,Gr.newId)(),name:"New Step"})],i={id:e.id&&e.id.trim()!==""?e.id:(0,Gr.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 FM(e){var t;let r={id:e.id&&e.id.trim()!==""?e.id:(0,Gr.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 Pw(e,t,r,n){return`${Nw}<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="${_M}" /></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="${_M}" /></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 Qse(){return{adapter:new _m,api:Ise.bpfApi,languageSensitive:!0}}Il.bpfRegistration=Qse});var uU=v(Om=>{"use strict";Object.defineProperty(Om,"__esModule",{value:!0});Om.buildRegistrations=void 0;var Xse=tk(),Zse=Ck(),ele=nx(),tle=Cx(),rle=jx(),nle=dF(),ile=DF(),ole=cM(),ale=lU();function sle(e){let t=new Map;return t.set("form",(0,Xse.formRegistration)(e)),t.set("view",(0,Zse.viewRegistration)()),t.set("businessRule",(0,ele.businessRuleRegistration)()),t.set("app",(0,tle.appRegistration)(e)),t.set("command",(0,rle.commandRegistration)()),t.set("chart",(0,nle.chartRegistration)()),t.set("dashboard",(0,ile.dashboardRegistration)(e)),t.set("genPage",(0,ole.genPageRegistration)()),t.set("bpf",(0,ale.bpfRegistration)()),t}Om.buildRegistrations=sle});var AU=v(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE=Te.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE=Te.ROW_SUMMARY_MODEL_NOT_DELETED_CODE=Te.removeRowSummary=Te.configureRowSummary=Te.buildGptDynamicPrompt=Te.setAppAiFeatures=Te.getAiReadiness=Te.saveSettingValue=Te.retrieveSetting=Te.AI_GATE=void 0;var za=Tt(),Sn=fe(),He=oe(),cU=ct(),Ze=Q();Te.AI_GATE={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabled",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"EnableNLGridSearch",nlChart:"NLChartVisualizationSetting",summaries:"EnableFormInsights",m365:"m365copilotmodelappenabled"};var gU={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabledOnByDefault",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"NLGridSearchSetting",nlChart:"NLChartDataVisualizationSetting",m365:"m365copilotmodelappenabled"},lle=new Set(Object.entries(Te.AI_GATE).filter(([e,t])=>gU[e]===t).map(([e])=>e)),ule={formFill:{enabled:"2",disabled:"1"},formFillSuggestions:{enabled:"2",disabled:"1"},formFillSmartPaste:{enabled:"2",disabled:"1"},formFillFiles:{enabled:"2",disabled:"1"}};function Rw(e){return ule[e]}var Pm=1e6;function cle(e,t){let r=Rw(t),n=()=>{throw new Ze.InvalidArgumentError(`setAppAiFeatures: '${t}' must be a boolean or an integer between 0 and ${Pm} (e.g. 0, 1, 2); got '${String(e)}'.`)},i=o=>r?o?r.enabled:r.disabled:o?"1":"0";if(typeof e=="boolean")return i(e);if(typeof e=="number")return!Number.isSafeInteger(e)||e<0||e>Pm?n():String(e);if(typeof e=="string"){let o=e.trim(),a=o.toLowerCase();if(a==="true")return i(!0);if(a==="false")return i(!1);if(/^[0-9]+$/.test(o)){let s=o.replace(/^0+(?=[0-9])/,"");return s.length>String(Pm).length||Number(s)>Pm?n():s}}return n()}function dle(e,t){let r=Rw(t);return r?e===r.enabled:e!=="0"}async function fle(e,t){var r,n;let i=`/appmodules${(0,He.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,He.odataLiteral)(t)}'`]])}`,o=await e.get(i);if(o.status<200||o.status>=300)return;let a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new Ze.ConnectionError(e.apiUrl(i),o.status,`the app lookup for '${t}' returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,za.describeMalformedValue)(a)}`);return(n=a[0])===null||n===void 0?void 0:n.appmoduleid}async function ple(e,t){var r,n;let i=`/appmodules${(0,He.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,He.odataLiteral)(t)}'`]])}`,o;try{o=await e.get(i)}catch(l){throw new Ze.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup failed (${l.message}). Retry, or omit appModuleId to verify by name.`)}if(o.status<200||o.status>=300)throw new Ze.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned HTTP ${o.status}. Retry, or omit appModuleId to verify by name.`);let a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new Ze.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a malformed body.`);if(a.length===0)return;let s=(n=a[0])===null||n===void 0?void 0:n.appmoduleid;if(!s)throw new Ze.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a row with no appmoduleid.`);return s}var dU=new WeakMap;async function mle(e,t){var r,n;let i=dU.get(e);if(i||(i=new Map,dU.set(e,i)),i.has(t))return i.get(t);let o=`/settingdefinitions${(0,He.odataQuery)([["$select","settingdefinitionid"],["$filter",`uniquename eq '${(0,He.odataLiteral)(t)}'`]])}`,a=await e.get(o);if(a.status<200||a.status>=300)return;let s=(r=a.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(s))throw new Ze.ConnectionError(e.apiUrl(o),a.status,`the setting definition lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,za.describeMalformedValue)(s)}`);let l=(n=s[0])===null||n===void 0?void 0:n.settingdefinitionid;return l&&i.set(t,l),l}async function hle(e,t,r){var n,i;let o=await mle(e,r);if(!t||!o)return;let a=`/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()${(0,He.odataQuery)([["$select","value,componentstate"],["$filter",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${o}`]])}`,s=await e.get(a);if(s.status<200||s.status>=300)return;let l=(n=s.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(l))throw new Ze.ConnectionError(e.apiUrl(a),s.status,`the app-scope override read returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,za.describeMalformedValue)(l)}`);let u=l;if(u.length===0)return{exists:!1};let c=(i=u.find(d=>d?.componentstate===1))!==null&&i!==void 0?i:u[0];return{exists:!0,value:c.value,pendingPublish:c.componentstate===1}}var gle=4,yle=500,fU=20,pU=3e4;function ble(e){if(e===void 0)return gle;if(!Number.isFinite(e))throw new Ze.InvalidArgumentError(`setAppAiFeatures: verifyAttempts must be a finite integer between 1 and ${fU}; got ${e}.`);return Math.min(fU,Math.max(1,Math.floor(e)))}function vle(e){if(e===void 0)return yle;if(!Number.isFinite(e))throw new Ze.InvalidArgumentError(`setAppAiFeatures: verifyDelayMs must be a finite number between 0 and ${pU}; got ${e}.`);return Math.min(pU,Math.max(0,Math.floor(e)))}async function wle(e,t,r,n,i,o,a){let s,l,u,c=!1;for(let d=0;d<o;d+=1){d>0&&await new Promise(m=>setTimeout(m,a*d));let f;try{let m=await t();m?(f=await hle(e,m,n),f===void 0&&(u="the app-scope override row could not be read (insufficient access or unresolvable ids)")):u=`the app '${r}' could not be resolved to an appmoduleid \u2014 a newly created app is not readable until it is published, so either publish it first or pass \`appModuleId\` in the options to verify without the lookup`}catch(m){f=void 0,u=m.message}c=f!==void 0,l=f?.exists;try{s=(await Rm(e,n,{appUniqueName:r})).value}catch{}if(f?.exists&&f.value===i)return{result:"proven",effectiveValue:f.value,appOverrideExists:!0,...f.pendingPublish?{pendingPublish:!0}:{}}}return c?{result:"absent",effectiveValue:s,appOverrideExists:l}:{result:"unverifiable",effectiveValue:s,appOverrideExists:void 0,reason:u}}function yU(e,t,r){if(t===2)return String(e).toLowerCase()==="true";let n=r?Rw(r):void 0;return n?e===n.enabled:e!=null&&e!=="0"&&e!==""}async function Rm(e,t,r={}){var n;let i=[`SettingName='${(0,He.odataPathLiteral)(t)}'`];r.appUniqueName&&i.push(`AppUniqueName='${(0,He.odataPathLiteral)(r.appUniqueName)}'`);let o=`/RetrieveSetting(${i.join(",")})`,a=(0,Sn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(n=a.body)===null||n===void 0?void 0:n.SettingDetail;if(s===null||typeof s!="object"||Array.isArray(s)||!("Value"in s))throw new Ze.ConnectionError(e.apiUrl(o),a.status,`RetrieveSetting for '${t}' returned a malformed answer \u2014 expected a SettingDetail with a Value`);let{Value:l,DataType:u}=s;return{value:l,dataType:u}}Te.retrieveSetting=Rm;async function bU(e,t,r,n={}){let i={SettingName:t,Value:r};n.appUniqueName&&(i.AppUniqueName=n.appUniqueName),n.solutionUniqueName&&(i.SolutionUniqueName=n.solutionUniqueName),(0,Sn.ensureSuccess)(await e.post("/SaveSettingValue",i),e.apiUrl("/SaveSettingValue"))}Te.saveSettingValue=bU;async function Cle(e,t={}){let r={};for(let[n,i]of Object.entries(Te.AI_GATE)){let{value:o,dataType:a}=await Rm(e,i,t);r[n]={enabled:yU(o,a,n),setting:i,value:o}}return r}Te.getAiReadiness=Cle;async function Ele(e,t,r,n={}){var i;if(!t||!t.trim())throw new Ze.InvalidArgumentError("setAppAiFeatures: a non-empty appUniqueName is required (an empty value would write the setting at organization scope, affecting every app).");let o=ble(n.verifyAttempts),a=vle(n.verifyDelayMs),s=[];for(let[p,h]of Object.entries(r)){if(h===void 0)continue;let g=gU[p];g&&s.push({feature:p,setting:g,requestedValue:cle(h,p)})}let l=[],u=n.appModuleId?(0,He.normalizeGuid)(n.appModuleId,"appModuleId"):void 0;if(u){let p=await ple(e,t);if(p&&(0,He.normalizeGuid)(p,"appModuleId")!==u)throw new Ze.InvalidArgumentError(`setAppAiFeatures: appModuleId '${u}' does not belong to app '${t}' (which resolves to '${p}'). Settings are written by unique name, so verifying against a different app would report success for a write that never landed.`)}let c,d=async()=>u||(c||(c=await fle(e,t)),c),f=new Map,m=async p=>{if(lle.has(p))return;let h=Te.AI_GATE[p];if(h){if(!f.has(h))try{let{value:g,dataType:b}=await Rm(e,h);f.set(h,{enabled:yU(g,b,p),setting:h,value:g})}catch{f.set(h,void 0)}return f.get(h)}};for(let{feature:p,setting:h,requestedValue:g}of s)try{await bU(e,h,g,{appUniqueName:t,solutionUniqueName:n.solutionUniqueName});let b=await wle(e,d,t,h,g,o,a),w={feature:p,setting:h,requestedValue:g,effectiveValue:b.effectiveValue,appOverrideExists:b.appOverrideExists};if(b.result==="proven")l.push({...w,status:"applied",...b.pendingPublish?{pendingPublish:!0}:{}});else if(b.result==="absent"){let C=dle(g,p)?await m(p):void 0;C&&!C.enabled?l.push({...w,status:"skipped",reason:`the write was issued and no app-scope override holding '${g}' was observed for '${h}' after ${o} attempt(s); the org readiness gate '${C.setting}' reads '${C.value}', so an environment admin must enable it before this app can turn the feature on`}):l.push({...w,status:"notPersisted",reason:`the write reported success but no app-scope override holding '${g}' was observed for '${h}' after ${o} attempt(s) \u2014 ${b.effectiveValue===void 0?"the value in effect for this app could not be read":`it reads '${b.effectiveValue}' for this app`} (Dataverse can accept an app-scope write without storing it)`})}else l.push({...w,status:"unverified",reason:`the write was issued but could not be confirmed: ${(i=b.reason)!==null&&i!==void 0?i:"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(b){l.push({feature:p,setting:h,requestedValue:g,status:"failed",reason:b.message})}return{applied:l.filter(p=>p.status==="applied").map(p=>p.feature),skipped:l.filter(p=>p.status==="skipped").map(p=>p.feature),notPersisted:l.filter(p=>p.status==="notPersisted").map(p=>p.feature),unverified:l.filter(p=>p.status==="unverified").map(p=>p.feature),failed:l.filter(p=>p.status==="failed").map(p=>p.feature),outcomes:l}}Te.setAppAiFeatures=Ele;var vU="GptPowerPrompt",Ale='{ "consumptionSource": "Api", "partnerSource": "AIBuilder", "consumptionSourceVersion": "GptApiClient"}';function wU(e){var t,r,n,i;let o=e.entityLogicalName,a=[{type:"literal",text:e.instruction.replace(/\s*$/,"")+" "}];return e.columns.forEach((s,l)=>{a.push({type:"data",id:`${o}.${s.logical}`,text:s.display}),l<e.columns.length-1&&a.push({type:"literal",text:", "})}),{version:"GptDynamicPrompt-2",prompt:a,definitions:{inputs:[{id:"RecordId",text:"RecordId",type:"text"},{id:"LanguageCode",text:"LanguageCode",type:"text"}],formulas:[],data:[{id:o,displayName:o,type:"dataverseTable",filters:[{filterType:"equal",attribute:e.primaryKey,valueType:"inputVariable",value:"RecordId"}]}],output:{formats:[(t=e.outputFormat)!==null&&t!==void 0?t:"text"]}},modelParameters:{modelType:"default",gptParameters:{temperature:(r=e.temperature)!==null&&r!==void 0?r:0}},settings:{recordRetrievalLimit:(n=e.recordRetrievalLimit)!==null&&n!==void 0?n:30,shouldPreserveRecordLinks:null,runtime:null,enableReasoning:(i=e.enableReasoning)!==null&&i!==void 0?i:!0},code:"",signature:""}}Te.buildGptDynamicPrompt=wU;async function Sle(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,He.odataPathLiteral)(t)}')${(0,He.odataQuery)([["$select","MetadataId"]])}`,i=(0,Sn.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.MetadataId;if(typeof o!="string"||o==="")throw new Ze.ConnectionError(e.apiUrl(n),i.status,`the table metadata read for '${t}' returned a malformed answer \u2014 expected a MetadataId but got ${o===""?"an empty string":(0,za.describeMalformedValue)(o)}`);return o}async function CU(e){var t,r;let n=`/msdyn_aitemplates${(0,He.odataQuery)([["$select","msdyn_aitemplateid"],["$filter",`msdyn_uniquename eq '${vU}'`],["$top",1]])}`,i=(0,Sn.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(t=i.body)===null||t===void 0?void 0:t.value;if(!Array.isArray(o))throw new Ze.ConnectionError(e.apiUrl(n),i.status,`the row-summary template lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,za.describeMalformedValue)(o)}`);return((r=o[0])!==null&&r!==void 0?r:{}).msdyn_aitemplateid}function EU(e){return`${e} row summary`}async function Nle(e,t,r){var n;let i=`/msdyn_aimodels(${t})${(0,He.odataQuery)([["$select","msdyn_name,_msdyn_templateid_value"]])}`,o=await e.get(i);if(o.status===404)return!1;let a=(n=(0,Sn.ensureSuccess)(o,e.apiUrl(i)).body)!==null&&n!==void 0?n:{},s=await CU(e);return typeof a.msdyn_name=="string"&&a.msdyn_name.toLowerCase()===EU(r).toLowerCase()&&typeof a._msdyn_templateid_value=="string"&&s!==void 0&&a._msdyn_templateid_value.toLowerCase()===s.toLowerCase()}async function _le(e,t,r={}){var n;let i=`ais_RowSummary_${t.entityLogicalName}`,o=`/aiskillconfigs${(0,He.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,He.odataLiteral)(i)}'`],["$top",1]])}`,a=(0,Sn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(n=a.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(s))throw new Ze.ConnectionError(e.apiUrl(o),a.status,`the existing row-summary skill lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,za.describeMalformedValue)(s)}`);let l=s[0];if(l)return{modelId:l._aimodel_value,aiSkillConfigId:l.aiskillconfigid};let u=await Sle(e,t.entityLogicalName),c=await CU(e);if(c===void 0)throw new Ze.SdkError(Te.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE,`Cannot configure the row summary of '${t.entityLogicalName}': this org has no AI template '${vU}' (msdyn_aitemplates), which a row-summary model is built from. Nothing was written.`);let d=(0,cU.newId)(),f=(0,cU.newId)(),m=JSON.stringify(wU(t)),p={ModelId:d,RunConfigurationId:f,ModelName:EU(t.entityLogicalName),TemplateId:c,CustomConfiguration:m,Source:Ale,RunConfiguration:""};(0,Sn.ensureSuccess)(await e.post("/AIModelPublish",p),e.apiUrl("/AIModelPublish"));try{let h={uniquename:i,description:`${t.entityLogicalName} row summary`,"[email protected]":`/entities(${u})`,"[email protected]":`/msdyn_aimodels(${d})`,aiskill:"RowSummary"},g=(0,Sn.ensureSuccess)(await e.post("/aiskillconfigs",h),e.apiUrl("/aiskillconfigs")),b=(0,Sn.requireCreatedId)(g,"aiskillconfigid","row-summary skill");return{modelId:d,aiSkillConfigId:b}}catch(h){try{await e.delete(`/msdyn_aimodels(${d})`)}catch{}throw h}}Te.configureRowSummary=_le;async function Tle(e,t){var r;let n=`ais_RowSummary_${t.entityLogicalName}`,i=`/aiskillconfigs${(0,He.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,He.odataLiteral)(n)}'`],["$top",1]])}`,o=(0,Sn.ensureSuccess)(await e.get(i),e.apiUrl(i)),a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new Ze.ConnectionError(e.apiUrl(i),o.status,`the row-summary skill lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,za.describeMalformedValue)(a)}`);let s=a[0];if(!s)return;let l=(0,He.normalizeGuid)(s.aiskillconfigid,"aiskillconfigid"),u=s._aimodel_value?(0,He.normalizeGuid)(s._aimodel_value,"_aimodel_value"):void 0,c=u?await Nle(e,u,t.entityLogicalName):!1,d=t.entityLogicalName,f=`/aiskillconfigs(${l})`,m=await mU(e,f,`${f}${(0,He.odataQuery)([["$select","aiskillconfigid"]])}`);if(m.kind==="failed")throw m.stillThere===void 0&&u&&c?(0,Ze.attachCause)(new Ze.SdkError(Te.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE,`Removing the row summary of '${d}' could not be confirmed: deleting its skill row failed (${hU(m.failure)}) and the row could not be read back. If it is gone, its AI model '${u}' is left behind, unreferenced. Retry removeRowSummary: while the skill row exists it removes both; once it is gone, delete that model.`),m.failure):m.failure;if(u&&c){let p=`/msdyn_aimodels(${u})`,h=await mU(e,p,`${p}${(0,He.odataQuery)([["$select","msdyn_aimodelid"]])}`,Ile);if(h.kind==="failed")throw(0,Ze.attachCause)(new Ze.SdkError(Te.ROW_SUMMARY_MODEL_NOT_DELETED_CODE,`The row summary of '${d}' was removed, but its AI model '${u}' ${h.stillThere?"was not deleted":"could not be confirmed deleted"} (${hU(h.failure)}). The model is no longer used by the row summary; delete it before configuring a row summary for '${d}' again, which needs its name.`),h.failure)}}Te.removeRowSummary=Tle;Te.ROW_SUMMARY_MODEL_NOT_DELETED_CODE="ROW_SUMMARY_MODEL_NOT_DELETED";Te.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE="ROW_SUMMARY_REMOVAL_UNCONFIRMED";Te.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE="ROW_SUMMARY_TEMPLATE_NOT_FOUND";var Dle="0x8004f01f";function Ile(e){var t,r;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return e.status===400&&typeof n=="string"&&n.toLowerCase()===Dle}function Ole(e){if(e.status!==400&&e.status!==500||e.body===void 0||e.body===null)return!1;let t=typeof e.body=="string"?e.body:JSON.stringify(e.body);return/chosen as the deadlock victim|\bSql Number:\s*1205\b/i.test(t)}async function mU(e,t,r,n=()=>!1){let i;try{let o=await(0,Sn.resendWhile)(Ole,()=>e.delete(t));if(o.status>=200&&o.status<300||o.status===404)return{kind:"gone"};if(n(o))return{kind:"kept"};try{(0,Sn.ensureSuccess)(o,e.apiUrl(t))}catch(a){i=a}}catch(o){i=o}try{let o=await e.get(r);return o.status===404?{kind:"gone"}:{kind:"failed",failure:i,stillThere:o.status>=200&&o.status<300?!0:void 0}}catch{return{kind:"failed",failure:i,stillThere:void 0}}}function hU(e){return e instanceof Error?e.message:String(e)}});var _U=v(Ol=>{"use strict";Object.defineProperty(Ol,"__esModule",{value:!0});Ol.findArtifact=Ol.resolveArtifact=void 0;var Ht=oe(),no=Zd(),Ple=Af(),Rle=Tt(),Lle=fe(),SU=Q();async function NU(e,t,r){let n="/uxagentprojects"+(0,Ht.odataQuery)([["$select","uxagentprojectid,name"],["$filter",`name eq '${(0,Ht.odataLiteral)(t)}'`],...r!==void 0?[["$top",String(r)]]:[]]);return(await(0,Rle.collectPages)(e,n,"resolveArtifact('genPage')",void 0,{headers:{"MSCRM.IncludeUnpublished":"true"}})).map(o=>({id:String(o.uxagentprojectid),name:String(o.name)}))}async function kle(e,t,r){var n,i,o,a,s,l,u,c,d,f,m,p;switch(t){case"app":{let h=(0,Ple.unpublishedAppModulesQuery)("appmoduleid,name,appmoduleidunique",`uniquename eq '${(0,Ht.odataLiteral)((n=r.uniqueName)!==null&&n!==void 0?n:"")}'`,1),b=(i=(0,Lle.ensureSuccess)(await e.get(h),e.apiUrl(h)).body)===null||i===void 0?void 0:i.value,w=b&&b[0];return w?[{id:String(w.appmoduleid),name:String(w.name),appModuleIdUnique:String(w.appmoduleidunique)}]:[]}case"dashboard":return(await(0,no.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,Ht.odataLiteral)((o=r.name)!==null&&o!==void 0?o:"")}' and type eq 0`,top:10})||[]).map(g=>({id:String(g.formid),name:String(g.name)}));case"command":{if(!r.entity)return[];let h=await(0,no.queryRecords)(e,"appaction",{select:["appactionid","buttonlabeltext"],filter:`contextvalue eq '${(0,Ht.odataLiteral)(r.entity)}'`,top:1});return h&&h.length?[{id:r.entity,entity:r.entity}]:[]}case"form":return(await(0,no.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,Ht.odataLiteral)((a=r.name)!==null&&a!==void 0?a:"")}' and objecttypecode eq '${(0,Ht.odataLiteral)((s=r.entity)!==null&&s!==void 0?s:"")}'`,top:10})||[]).map(g=>({id:String(g.formid),name:String(g.name)}));case"chart":return(await(0,no.queryRecords)(e,"savedqueryvisualization",{select:["savedqueryvisualizationid","name"],filter:`name eq '${(0,Ht.odataLiteral)((l=r.name)!==null&&l!==void 0?l:"")}' and primaryentitytypecode eq '${(0,Ht.odataLiteral)((u=r.entity)!==null&&u!==void 0?u:"")}'`,top:10})||[]).map(g=>({id:String(g.savedqueryvisualizationid),name:String(g.name)}));case"view":return(await(0,no.queryRecords)(e,"savedquery",{select:["savedqueryid","name"],filter:`name eq '${(0,Ht.odataLiteral)((c=r.name)!==null&&c!==void 0?c:"")}' and returnedtypecode eq '${(0,Ht.odataLiteral)((d=r.entity)!==null&&d!==void 0?d:"")}'`,top:10})||[]).map(g=>({id:String(g.savedqueryid),name:String(g.name)}));case"webResource":return(await(0,no.queryRecords)(e,"webresource",{select:["webresourceid","name"],filter:`name eq '${(0,Ht.odataLiteral)((f=r.name)!==null&&f!==void 0?f:"")}'`,top:1})||[]).map(g=>({id:String(g.webresourceid),name:String(g.name)}));case"solution":return(await(0,no.queryRecords)(e,"solution",{select:["solutionid","uniquename"],filter:`uniquename eq '${(0,Ht.odataLiteral)((m=r.uniqueName)!==null&&m!==void 0?m:"")}'`,top:1})||[]).map(g=>({id:String(g.solutionid),name:String(g.uniquename)}));case"genPage":return NU(e,(p=r.name)!==null&&p!==void 0?p:"");default:return[]}}Ol.resolveArtifact=kle;async function $le(e,t,r){var n,i,o,a,s,l;let u=(0,Ht.odataLiteral)((n=r.name)!==null&&n!==void 0?n:""),c=(0,Ht.odataLiteral)((i=r.entity)!==null&&i!==void 0?i:"");if(t==="command"){if(!r.entity)return null;let h=await(0,no.queryRecords)(e,"appaction",{select:["appactionid"],filter:`contextvalue eq '${(0,Ht.odataLiteral)(r.entity)}'`,top:1});return h&&h.length?r.entity:null}if(t==="genPage"){let h=await NU(e,(o=r.name)!==null&&o!==void 0?o:"",2);if(h.length>1)throw new SU.AmbiguousArtifactError(t,(a=r.name)!==null&&a!==void 0?a:"",h.length);return h.length===1?h[0].id:null}let d=xle(t,u,c,r),f=t!=="app",m=await(0,no.queryRecords)(e,d.set,{select:[d.idField],filter:d.filter,top:f?2:1});if(f&&m&&m.length>1)throw new SU.AmbiguousArtifactError(t,(l=(s=r.name)!==null&&s!==void 0?s:r.uniqueName)!==null&&l!==void 0?l:"",m.length);let p=m&&m[0]&&m[0][d.idField];return p!=null?String(p):null}Ol.findArtifact=$le;function xle(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,Ht.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 DU=v(km=>{"use strict";Object.defineProperty(km,"__esModule",{value:!0});km.seedRecordGraph=void 0;var TU=Zd(),Fle=$d(),Lm=oe(),Mle=Q();async function Ule(e,t,r={}){var n,i,o,a,s;let l=(n=r.createdIds)!==null&&n!==void 0?n:{},u=(i=r.entitySetFor)!==null&&i!==void 0?i:(f=>(0,Fle.resolveEntitySetName)(e,f)),c={},d=f=>{var m;return(m=c[f])!==null&&m!==void 0?m:l[f]};for(let f of t){let m=f.entityLogical.toLowerCase(),p=(o=f.matchOn)===null||o===void 0?void 0:o.toLowerCase(),h=[];for(let L of f.records){let I={...L.body};for(let D of(a=L.binds)!==null&&a!==void 0?a:[]){let P=D.parentEntity.toLowerCase(),x=(s=d(P))===null||s===void 0?void 0:s[D.parentIndex];if(!x)throw new Mle.InvalidArgumentError(`Cannot resolve bind '${D.navProperty}' on a '${m}' record: parent '${D.parentEntity}'[${D.parentIndex}] has no created id. Seed the parent group before the child, or supply it via options.createdIds.`);let K=(0,Lm.assertODataName)(await u(P),`entity set for parent '${D.parentEntity}'`),Le=(0,Lm.normalizeGuid)(x,`parent id for bind '${D.navProperty}'`);I[`${D.navProperty}@odata.bind`]=`/${K}(${Le})`}h.push(I)}let g=p?h.map(L=>{let I=L[p];return I!=null&&I!==""?String(I):null}):h.map(()=>null),b=new Map;if(p){let L=(0,Lm.assertODataName)(p,"RecordGraph matchOn key"),I=[...new Set(g.filter(D=>D!==null))];if(I.length){let D=I.map(x=>`${L} eq '${(0,Lm.odataLiteral)(x)}'`).join(" or "),P=await(0,TU.queryRecords)(e,m,{select:[L,`${m}id`],filter:D,top:5e3});for(let x of P??[]){let K=x[L];K!=null&&b.set(String(K).toLowerCase(),String(x[`${m}id`]))}}}let w=[],C=new Map,S=h.map((L,I)=>{let D=g[I];if(D&&b.has(D.toLowerCase()))return null;if(D){let P=D.toLowerCase(),x=C.get(P);if(x!==void 0)return x;let K=w.push(L)-1;return C.set(P,K),K}return w.push(L)-1}),O=w.length?await(0,TU.createRecordsBulk)(e,m,w):[];c[m]=h.map((L,I)=>{let D=g[I];return D&&b.has(D.toLowerCase())?b.get(D.toLowerCase()):O[S[I]]})}return{createdIds:c}}km.seedRecordGraph=Ule});var MU=v(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.getEntityPrivileges=or.addEntityPrivilegesToRole=or.deleteSecurityRole=or.createPersonaRole=or.createSecurityRole=or.SDK_ROLE_MARKER=void 0;var zn=fe(),Ft=oe(),rn=Q(),$m={read:"Read",create:"Create",write:"Write",delete:"Delete",append:"Append",appendTo:"AppendTo",assign:"Assign",share:"Share"},kw={user:"Basic",businessUnit:"Local",parentChild:"Deep",organization:"Global"},IU={user:1,businessUnit:2,parentChild:3,organization:4},Lw={user:"CanBeBasic",businessUnit:"CanBeLocal",parentChild:"CanBeDeep",organization:"CanBeGlobal"};or.SDK_ROLE_MARKER="Authored by @maker-studio/cds-maker-sdk (persona/security role).";function Ble(e){return Object.prototype.hasOwnProperty.call($m,e)?$m[e]:void 0}function qle(e){return Object.prototype.hasOwnProperty.call(kw,e)}var OU=new WeakMap,PU=new WeakMap;async function kU(e,t){var r,n;(0,Ft.assertODataName)(t,"entity logical name");let i=OU.get(e);i||(i=new Map,OU.set(e,i));let o=i.get(t);if(o)return o;let a=`/EntityDefinitions(LogicalName='${(0,Ft.odataPathLiteral)(t)}')${(0,Ft.odataQuery)([["$select","LogicalName,Privileges"]])}`,l=(n=(r=(0,zn.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||r===void 0?void 0:r.Privileges)!==null&&n!==void 0?n:[];if(l.length===0)throw new rn.InvalidArgumentError(`Entity '${t}' exposes no privileges (unknown or non-securable entity).`);return i.set(t,l),l}async function Vle(e){var t,r,n;let i=PU.get(e);if(i)return i;let o=`/businessunits${(0,Ft.odataQuery)([["$select","businessunitid"],["$filter","_parentbusinessunitid_value eq null"],["$top",1]])}`,l=(n=((r=(t=(0,zn.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||t===void 0?void 0:t.value)!==null&&r!==void 0?r:[])[0])===null||n===void 0?void 0:n.businessunitid;if(!l)throw new rn.InvalidArgumentError("Could not resolve the root business unit.");let u=(0,Ft.normalizeGuid)(l,"businessUnitId");return PU.set(e,u),u}async function $U(e,t){var r;let n=new Map;for(let i of t){if(!i.access||i.access.length===0)throw new rn.InvalidArgumentError(`Entity '${i.entity}' privilege request has no access levels.`);let o=(r=i.scope)!==null&&r!==void 0?r:"user";if(!qle(o))throw new rn.InvalidArgumentError(`Unknown privilege scope '${o}' for entity '${i.entity}'.`);let a=await kU(e,i.entity);for(let s of i.access){let l=Ble(s);if(!l)throw new rn.InvalidArgumentError(`Unknown access level '${s}' for entity '${i.entity}'.`);let u=a.find(p=>p.PrivilegeType===l);if(!u)throw new rn.InvalidArgumentError(`Entity '${i.entity}' does not support '${s}' access.`);let c=Lw[o];if(u[c]===!1)throw new rn.InvalidArgumentError(`Privilege '${u.Name}' on '${i.entity}' does not support the '${o}' scope.`);let d=(0,Ft.normalizeGuid)(u.PrivilegeId,"PrivilegeId"),f=n.get(d);if(!f){n.set(d,{privilegeName:u.Name,privilegeType:l,scope:o,entities:new Set([i.entity])});continue}if(f.scope===o){f.entities.add(i.entity);continue}if(!(f.entities.size===1&&f.entities.has(i.entity))){let p=[...f.entities].sort().join(", ");throw new rn.InvalidArgumentError(`Entities '${p}' and '${i.entity}' share the Dataverse privilege '${u.Name}' but request different scopes; a role holds one depth per privilege. Use the same scope for all entities that share this privilege, or split them.`)}f.scope=IU[o]>IU[f.scope]?o:f.scope}}return[...n.entries()].map(([i,o])=>({entity:[...o.entities].sort().join(", "),privilegeId:i,privilegeName:o.privilegeName,privilegeType:o.privilegeType,scope:o.scope}))}async function Gle(e,t,r,n){if(r.length===0&&!n)return;let i={Privileges:r.map(a=>({Depth:kw[a.scope],PrivilegeId:a.privilegeId}))},o=`/roles(${t})/Microsoft.Dynamics.CRM.ReplacePrivilegesRole`;(0,zn.ensureSuccess)(await e.post(o,i),e.apiUrl(o))}async function RU(e,t,r,n,i){var o,a;let s=`/${t}(${r})/${n}${(0,Ft.odataQuery)([["$select","roleid"],["$filter",`roleid eq ${i}`]])}`;return((a=(o=(0,zn.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||o===void 0?void 0:o.value)!==null&&a!==void 0?a:[]).length>0}async function Wle(e,t,r){var n,i;let o=[],a=[],s={"@odata.id":e.apiUrl(`/roles(${t})`)};for(let l of(n=r?.teams)!==null&&n!==void 0?n:[]){let u=(0,Ft.normalizeGuid)(l,"teamId");if(!await RU(e,"teams",u,"teamroles_association",t)){let c=`/teams(${u})/teamroles_association/$ref`;(0,zn.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}o.push(u)}for(let l of(i=r?.users)!==null&&i!==void 0?i:[]){let u=(0,Ft.normalizeGuid)(l,"userId");if(!await RU(e,"systemusers",u,"systemuserroles_association",t)){let c=`/systemusers(${u})/systemuserroles_association/$ref`;(0,zn.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}a.push(u)}return{teams:o,users:a}}async function LU(e,t,r){var n,i;let o=`/roles${(0,Ft.odataQuery)([["$select","roleid,description,ismanaged"],["$filter",`name eq '${(0,Ft.odataLiteral)(t)}' and _businessunitid_value eq ${r}`]])}`,l=((i=(n=(0,zn.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]).filter(d=>!!d.roleid);if(l.length===0)return;let u=d=>{var f;return d.ismanaged!==!0&&((f=d.description)!==null&&f!==void 0?f:"")===or.SDK_ROLE_MARKER};if(l.some(d=>!u(d)))throw new rn.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 rn.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,Ft.normalizeGuid)(c,"roleId"):void 0}function zle(e){var t,r;return{teams:((t=e?.teams)!==null&&t!==void 0?t:[]).map(n=>(0,Ft.normalizeGuid)(n,"teamId")),users:((r=e?.users)!==null&&r!==void 0?r:[]).map(n=>(0,Ft.normalizeGuid)(n,"userId"))}}function xU(e){return e.map(t=>({entity:t.entity,privilegeName:t.privilegeName,privilegeType:t.privilegeType,scope:t.scope}))}async function FU(e,t){var r,n;let i=(r=t.name)===null||r===void 0?void 0:r.trim();if(!i)throw new rn.InvalidArgumentError("createSecurityRole: a non-empty role name is required.");let o=t.businessUnitId?(0,Ft.normalizeGuid)(t.businessUnitId,"businessUnitId"):await Vle(e),a=await $U(e,(n=t.privileges)!==null&&n!==void 0?n:[]),s=zle(t.assignTo),l=await LU(e,i,o),u=l!==void 0;if(!l){let d="/roles",f={name:i,description:or.SDK_ROLE_MARKER,"[email protected]":`/businessunits(${o})`};try{let m=(0,zn.ensureSuccess)(await e.post(d,f),e.apiUrl(d));l=(0,Ft.normalizeGuid)((0,zn.requireCreatedId)(m,"roleid","role"),"roleId")}catch(m){let p;try{p=await LU(e,i,o)}catch{p=void 0}if(!p)throw m;l=p}}await Gle(e,l,a,u);let c=await Wle(e,l,s);return{roleId:l,name:i,reused:u,appliedPrivileges:xU(a),assignedTeams:c.teams,assignedUsers:c.users}}or.createSecurityRole=FU;async function jle(e,t){var r,n;let i=(r=t.persona)===null||r===void 0?void 0:r.trim();if(!i)throw new rn.InvalidArgumentError("createPersonaRole: a non-empty persona name is required.");let o=[...t.jobs.flatMap(a=>{var s;return(s=a.privileges)!==null&&s!==void 0?s:[]}),...(n=t.additionalPrivileges)!==null&&n!==void 0?n:[]];return FU(e,{name:i,businessUnitId:t.businessUnitId,privileges:o,assignTo:t.assignTo})}or.createPersonaRole=jle;async function Hle(e,t){let n=`/roles(${(0,Ft.normalizeGuid)(t,"roleId")})`;(0,zn.ensureSuccess)(await e.delete(n),e.apiUrl(n))}or.deleteSecurityRole=Hle;async function Kle(e,t,r){let n=(0,Ft.normalizeGuid)(t,"roleId");if(r.length===0)throw new rn.InvalidArgumentError("addEntityPrivilegesToRole requires at least one entity privilege (an empty grant would be a silent no-op).");let i=await $U(e,r),o={Privileges:i.map(s=>({Depth:kw[s.scope],PrivilegeId:s.privilegeId}))},a=`/roles(${n})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;return(0,zn.ensureSuccess)(await e.post(a,o),e.apiUrl(a)),xU(i)}or.addEntityPrivilegesToRole=Kle;var Jle=new Map(Object.keys($m).map(e=>[$m[e],e]));async function Yle(e,t){return(await kU(e,t)).map(n=>{let i=Object.keys(Lw).filter(a=>n[Lw[a]]!==!1),o=Jle.get(n.PrivilegeType);return{name:n.Name,privilegeId:n.PrivilegeId,privilegeType:n.PrivilegeType,...o?{access:o}:{},scopes:i}})}or.getEntityPrivileges=Yle});var tB=v(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.createMakerSdk=Er.MakerSdk=Er.PUSH_NOT_ATTEMPTED_CODE=Er.ALREADY_EXISTS_CODE=void 0;var UU=dh(),BU=jr(),Z=Q(),Nn=Xa(),Qle=CE(),QU=DE(),Pl=kE(),Xle=ph(),Zle=tA(),Rl=iA(),eue=bA(),tue=SA(),rue=tS(),qU=QS(),Mt=$d(),$w=e0(),VU=l_(),xm=vu(),io=Zd(),Fm=g_(),Ll=tf(),nue=nf(),ar=Jd(),iue=aT(),oue=v0(),aue=T0(),GU=w0(),sue=uU(),Mm=ct(),lue=sa(),Ai=Av(),_n=bh(),xw=lw(),uue=3e5,Cr=fe(),ja=oe(),kl=AU(),WU=_U(),cue=DU(),due=Ub(),Uc=MU(),XU=Symbol("cds-maker-sdk.committedWrite");function fue(e){return typeof e=="object"&&e!==null&&(e[XU]=!0),e}function pue(e){return typeof e=="object"&&e!==null&&e[XU]===!0}var mue={fileConcurrency:1},Fw="SOLUTION_COMPONENT_UNCLASSIFIED",hue=2,gue=4,yue="This table is in the solution with ALL its subcomponents. Those are members the solution does not list one by one, so fetchSolution did not enumerate or fetch them: none of its forms, views, charts or dashboards were fetched here. To fetch them, read the table's logical name from its metadata (EntityDefinitions(<componentId>), $select=LogicalName), list each kind with fetchArtifactList \u2014 'form' with formTypes Main, QuickView, QuickCreate and Card; 'view'; 'chart'; 'dashboard' \u2014 passing { entityLogicalName }, and fetch each listed id with fetchArtifact: listing returns ids and names only.";function zU(e){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"unsupported",...e.includesAllSubcomponents?{detail:yue}:{}}}function jU(e,t){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"failed",error:zo(t)}}function HU(e,t,r){let n=r;return{type:e,id:t.objectId,name:typeof n.name=="string"?n.name:t.objectId,entityLogicalName:typeof n.entityLogicalName=="string"?n.entityLogicalName:void 0,lastFetched:(0,Cr.nowIso)(),isDirty:!1}}var bue=new Set(["entity","appmodule","dashboard","uxagentproject"]);function vue(e){var t;let r={entity:[],appmodule:[],dashboard:[],uxagentproject:[]},n=new Set,i=(s,l)=>{let u=`${s}\0${l.toLowerCase()}`;n.has(u)||(n.add(u),r[s].push(l))};for(let{scope:s}of e)if(s?.envelope==="entity")s.entityLogicalName&&i("entity",s.entityLogicalName);else if(s&&s.envelope!=="webresource")for(let l of(t=s.targetIds)!==null&&t!==void 0?t:[])i(s.envelope,l);let o=(s,l,u)=>u.length>0?`<${s}>${u.map(c=>`<${l}>${(0,ja.xmlText)(c)}</${l}>`).join("")}</${s}>`:"",a=o("entities","entity",r.entity)+o("appmodules","appmodule",r.appmodule)+o("dashboards","dashboard",r.dashboard)+o("uxagentprojects","uxagentproject",r.uxagentproject);return a?`<importexportxml>${a}</importexportxml>`:void 0}function wue(e){let t=e.workspaceStorage;if(t==null)throw new Error("createMakerSdk requires a workspaceStorage. Node callers can build one with `createNodeWorkspaceStorage(path)` from '@maker-studio/cds-maker-sdk/node'; a host with no filesystem implements WorkspaceStorage directly.");return new QU.WorkspaceManager(Eue,e.instanceUrl,(0,Xle.assertStorageContract)(t))}Er.ALREADY_EXISTS_CODE="ARTIFACT_ALREADY_EXISTS";var Cue="this build answers a replayed create with HTTP 404, and the unpublished read of an existing row is not authoritative after another writer's save on it, so the row cannot be proven to be what this create wrote";Er.PUSH_NOT_ATTEMPTED_CODE="PUSH_NOT_ATTEMPTED";var Eue="<injected workspaceStorage>",Um=class{constructor(t){var r,n;if(this.artifactLocks=new Map,this.observedGenerations=new Map,this.baselineObserved=new Map,this.generationHighWater=new Map,this.entityMetadataLoads=new Map,this.entityMetadataLoadEpochs=new WeakMap,this.schemaWrites=new Map,this.undroppedMetadata=new Set,this.metadataPublications=new Set,t.createRecovery!==void 0&&t.createRecovery!=="adoptExact")throw new Z.InvalidArgumentError(`createRecovery must be 'adoptExact' or omitted (got '${String(t.createRecovery)}').`);this.createRecovery=t.createRecovery,this.readConcurrency=(0,xw.resolveReadConcurrency)(t.readConcurrency),this.languageCode=(r=t.languageCode)!==null&&r!==void 0?r:lue.DEFAULT_LCID,this.cacheStalenessMs=(n=t.cacheStalenessMs)!==null&&n!==void 0?n:uue,this.compiler={load:(0,oue.createGenPageTypeScriptLoader)(t.typescript)},this.workspace=wue(t),this.versions=new Pl.VersionManager(this.workspace),this.dataverse=new Zle.DataverseClient(t.instanceUrl,t.httpClient,t.solutionUniqueName,this.readConcurrency),this.connectivity=new rue.ConnectivityRouter(this.dataverse,t.instanceUrl,{powerAppsServiceClient:t.powerAppsServiceClient,powerPlatformApiClient:t.powerPlatformApiClient,connectorRuntimeClient:t.connectorRuntimeClient}),this.registrations=(0,sue.buildRegistrations)(this.languageCode)}async initWorkspace(){await this.workspace.init()}async getManifest(){return this.workspace.getManifest()}async cleanWorkspace(){await this.workspace.clean()}withArtifactLock(t,r,n){var i;let o=this.artifactKey(t,r),s=((i=this.artifactLocks.get(o))!==null&&i!==void 0?i:Promise.resolve()).then(n,n),l=s.then(()=>{},()=>{});return this.artifactLocks.set(o,l),l.then(()=>{this.artifactLocks.get(o)===l&&this.artifactLocks.delete(o)}),s}async fetchArtifact(t,r,n){return this.withArtifactLock(t,r,async()=>{let i=await this.fetchArtifactUnlocked(t,r,n);return await this.acknowledgeRefresh(t,r),i})}async fetchArtifactUnlocked(t,r,n){let i=this.requireRegistration(t,"fetchArtifact"),o=await i.api.get(this.dataverse,r);return this.applyFetchedArtifactUnlocked(t,r,i,o,n)}async applyFetchedArtifactUnlocked(t,r,n,i,o){var a,s,l;let{raw:u,etag:c,memberEtags:d,siblingEtags:f}=i,m=n.adapter.fromApiResponse(u);if(!o?.overwrite&&await this.versions.isDirty(t,r)){let h=(s=(a=await this.versions.getMeta(t,r))===null||a===void 0?void 0:a.etag)!==null&&s!==void 0?s:null;if(h&&c&&h!==c)throw new Z.LocalEditsWouldBeLostError(t,r,h,c);let g=await this.workspace.readArtifact(t,r);if(g){let b=await this.versions.getMeta(t,r);if(b&&!b.etag&&c){if(!(0,_n.deepEqual)(b.snapshot,m))throw new Z.LocalEditsWouldBeLostError(t,r,h,c);await this.versions.storeMeta(t,r,{...b,etag:c,fetchedAt:(0,Cr.nowIso)()},b)}return(0,Ai.cloneJson)(g)}}await this.workspace.writeArtifact(t,r,m);let p=await this.versions.getMeta(t,r);return await this.versions.storeMeta(t,r,{etag:c,languageCode:this.languageCode,projectionVersion:Pl.PROJECTION_VERSION,fetchedAt:(0,Cr.nowIso)(),snapshot:(0,Ai.cloneJson)(m),...d?{memberEtags:d}:{},...f?{siblingEtags:f}:{},...p?.refreshGeneration?{refreshGeneration:p.refreshGeneration,observedGeneration:(l=p.observedGeneration)!==null&&l!==void 0?l:0}:{}},p),(0,Ai.cloneJson)(m)}async fetchArtifactList(t,r){return this.requireRegistration(t,"fetchArtifactList").api.list(this.dataverse,r)}async fetchSolution(t){await this.workspace.ensureReady();let r=await(0,ar.fetchSolutionComponents)(this.dataverse,t),n=[],i=[];if(this.readConcurrency>1)await this.fetchComponentsOverlapped(r,n,i);else for(let o of r)try{let a=await this.resolveComponentType(o);if(!a){i.push(zU(o));continue}let s=await this.fetchArtifact(a,o.objectId);n.push(HU(a,o,s))}catch(a){i.push(jU(o,a))}return await this.workspace.updateManifest({lastSyncAt:(0,Cr.nowIso)()}),{summaries:n,skipped:i}}async fetchComponentsOverlapped(t,r,n){await(0,xw.readEveryInOrder)(t,this.readConcurrency,i=>this.beginComponentRead(i),async(i,o)=>{try{if(!i.ok)throw i.error;let a=i.value;if(a.kind==="unsupported"){n.push(zU(o));return}let s=await this.applyFetchedArtifactUnlocked(a.type,o.objectId,a.reg,a.fetched);await this.acknowledgeRefresh(a.type,o.objectId),r.push(HU(a.type,o,s))}catch(a){n.push(jU(o,a))}})}async beginComponentRead(t){let r=await this.resolveComponentType(t);return r?this.lockedRead(r,t.objectId,async()=>{let n=this.requireRegistration(r,"fetchArtifact"),i=await n.api.get(this.dataverse,t.objectId,mue);return{kind:"artifact",type:r,reg:n,fetched:i}}):(0,xw.plainRead)(async()=>({kind:"unsupported"}))}lockedRead(t,r,n){let i,o=new Promise(u=>{i=u}),a,s=new Promise(u=>{a=u}),l=this.withArtifactLock(t,r,async()=>{try{i({ok:!0,value:await n()})}catch(c){i({ok:!1,error:c})}let u=await s;await u?.()});return{outcome:o,finish:u=>(a(u),l),discard:async()=>{a(void 0),await l}}}async fetchEntityMetadata(t){let r=t.toLowerCase(),n=this.schemaEpoch(r),i=await(0,Rl.fetchEntityMetadataFromApi)(this.dataverse,t);if(this.schemaEpoch(r)!==n)return i;let o=this.workspace.writeEntityMetadata(t,i),a={key:r,settled:o.then(()=>{},()=>{})};this.metadataPublications.add(a);try{await o}finally{this.metadataPublications.delete(a)}return this.schemaEpoch(r)===n&&this.undroppedMetadata.delete(r),i}schemaEpoch(t){var r,n;return`${(r=this.schemaWrites.get("*"))!==null&&r!==void 0?r:0}:${(n=this.schemaWrites.get(t.toLowerCase()))!==null&&n!==void 0?n:0}`}async schemaWrite(t,r){try{return await r()}finally{await this.forgetEntityMetadata(t)}}async forgetEntityMetadata(t){let r=i=>{var o;this.schemaWrites.set(i,((o=this.schemaWrites.get(i))!==null&&o!==void 0?o:0)+1)};if(t===void 0){r("*"),await this.publicationsSettled(void 0),await this.dropCachedMetadata(void 0);return}let n=[...new Set(t.filter(i=>typeof i=="string"&&i!=="").map(i=>i.toLowerCase()))];n.forEach(r),await this.publicationsSettled(n);for(let i of n)await this.dropCachedMetadata(i)}async publicationsSettled(t){let r=t===void 0?void 0:new Set(t);await Promise.all([...this.metadataPublications].filter(n=>r===void 0||r.has(n.key)).map(n=>n.settled))}async dropCachedMetadata(t){try{await this.workspace.dropEntityMetadata(t)}catch(r){r instanceof Z.WorkspaceNotInitializedError||r instanceof Z.WorkspaceOrgMismatchError||this.undroppedMetadata.add(t??"*");return}t===void 0?this.undroppedMetadata.clear():this.undroppedMetadata.delete(t)}async readCachedEntityMetadata(t){let r=t.toLowerCase();return this.undroppedMetadata.has("*")&&await this.dropCachedMetadata(void 0),this.undroppedMetadata.has(r)&&await this.dropCachedMetadata(r),this.undroppedMetadata.has("*")||this.undroppedMetadata.has(r)?null:this.workspace.readEntityMetadata(t)}loadMissedEntityMetadata(t){let r=this.schemaEpoch(t),n=this.entityMetadataLoads.get(t);if(n&&this.entityMetadataLoadEpochs.get(n)===r)return n;let i=this.fetchEntityMetadata(t).then(()=>{});this.entityMetadataLoads.set(t,i),this.entityMetadataLoadEpochs.set(i,r);let o=()=>{this.entityMetadataLoads.get(t)===i&&this.entityMetadataLoads.delete(t)};return i.then(o,o),i}generateGenPageRuntimeTypes(t,r){return(0,eue.generateGenPageRuntimeTypes)(n=>this.fetchEntityMetadata(n),t,r)}findTables(t,r){return(0,Rl.findTables)(this.dataverse,t,r)}getEnvironmentLanguages(){return(0,tue.getEnvironmentLanguages)(this.dataverse)}listConnections(){return this.connectivity.listConnections()}listConnectorOperations(t){return this.connectivity.listConnectorOperations(t)}getConnectorOperationSchema(t,r){return this.connectivity.getConnectorOperationSchema(t,r)}listConnectorTables(t,r,n){return this.connectivity.listConnectorTables(t,r,n)}getConnectorTableSchema(t,r,n,i){return this.connectivity.getConnectorTableSchema(t,r,n,i)}findColumns(t,r,n){return(0,Rl.findColumns)(this.dataverse,t,r,n)}createTable(t){return this.schemaWrite([t.schemaName],()=>(0,Mt.createTable)(this.dataverse,t))}createColumn(t,r){return this.schemaWrite([t],()=>(0,Mt.createColumn)(this.dataverse,t,r))}createColumns(t,r){return this.schemaWrite([t],()=>(0,Mt.createColumns)(this.dataverse,t,r))}updateColumn(t,r,n){return this.schemaWrite([t],()=>(0,Mt.updateColumn)(this.dataverse,t,r,n))}deleteColumn(t,r){return this.schemaWrite([t],()=>(0,Mt.deleteColumn)(this.dataverse,t,r))}setFormSecurityRoles(t,r){return(0,$w.setFormSecurityRoles)(this.dataverse,t,r)}getFormSecurityRoles(t){return(0,$w.getFormSecurityRoles)(this.dataverse,t)}setColumnVisualization(t,r,n){return(0,Mt.setColumnVisualization)(this.dataverse,t,r,n)}getColumnVisualization(t,r){return(0,Mt.getColumnVisualization)(this.dataverse,t,r)}createCustomerColumn(t,r){return this.schemaWrite([t,"account","contact"],()=>(0,Mt.createCustomerColumn)(this.dataverse,t,r))}insertStatusValue(t,r){return this.schemaWrite([t],()=>(0,Mt.insertStatusValue)(this.dataverse,t,r))}updateTable(t,r){return this.schemaWrite([t],()=>(0,Mt.updateTable)(this.dataverse,t,r))}async setEntityIcon(t,r){if(await this.schemaWrite([t],()=>(0,Mt.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,ja.xmlText)(t)}</entity></entities></importexportxml>`;(0,Cr.ensureSuccess)(await this.dataverse.post("/PublishXml",{ParameterXml:n}),this.dataverse.apiUrl("/PublishXml"))}}createAlternateKey(t,r){return(0,Mt.createAlternateKey)(this.dataverse,t,r)}deleteAlternateKey(t,r){return(0,Mt.deleteAlternateKey)(this.dataverse,t,r)}createRelationship(t){let r=t.type==="ManyToMany"?[t.entity1,t.entity2]:[t.referencedEntity,t.referencingEntity];return this.schemaWrite(r,()=>(0,Mt.createRelationship)(this.dataverse,t))}deleteRelationship(t){return this.schemaWrite(void 0,()=>(0,Mt.deleteRelationship)(this.dataverse,t))}createGlobalOptionSet(t){return(0,Mt.createGlobalOptionSet)(this.dataverse,t)}deleteGlobalOptionSet(t){return(0,Mt.deleteGlobalOptionSet)(this.dataverse,t)}deleteTable(t){return this.schemaWrite(void 0,()=>(0,Mt.deleteTable)(this.dataverse,t))}createSecurityRole(t){return(0,Uc.createSecurityRole)(this.dataverse,t)}createPersonaRole(t){return(0,Uc.createPersonaRole)(this.dataverse,t)}deleteSecurityRole(t){return(0,Uc.deleteSecurityRole)(this.dataverse,t)}addEntityPrivilegesToRole(t,r){return(0,Uc.addEntityPrivilegesToRole)(this.dataverse,t,r)}getEntityPrivileges(t){return(0,Uc.getEntityPrivileges)(this.dataverse,t)}createRecord(t,r){return(0,io.createRecord)(this.dataverse,t,r)}createRecordsBulk(t,r){return(0,io.createRecordsBulk)(this.dataverse,t,r)}updateRecord(t,r,n){return(0,io.updateRecord)(this.dataverse,t,r,n)}upsertRecord(t,r,n){return(0,io.upsertRecord)(this.dataverse,t,r,n)}deleteRecord(t,r){return(0,io.deleteRecord)(this.dataverse,t,r)}getRecord(t,r,n){return(0,io.getRecord)(this.dataverse,t,r,n)}queryRecords(t,r){return(0,io.queryRecords)(this.dataverse,t,r)}seedRecordGraph(t,r){return(0,cue.seedRecordGraph)(this.dataverse,t,r)}resolveArtifact(t,r){return(0,WU.resolveArtifact)(this.dataverse,t,r)}findArtifact(t,r){return(0,WU.findArtifact)(this.dataverse,t,r)}async deleteAppCascade(t,r){await this.workspace.ensureReady();let n=await(0,aue.deleteAppCascade)(this.dataverse,t,r),i=(0,ja.normalizeGuid)(t,"appModuleId");return await this.workspace.readArtifact("app",i)&&await this.workspace.deleteArtifact("app",i),n}associateRecords(t,r,n){return(0,io.associateRecords)(this.dataverse,t,r,n)}disassociateRecords(t,r,n,i){return(0,io.disassociateRecords)(this.dataverse,t,r,n,i)}createWebResource(t){return(0,Fm.createWebResource)(this.dataverse,t)}updateWebResource(t,r){return(0,Fm.updateWebResource)(this.dataverse,t,r)}getWebResource(t){return(0,Fm.getWebResource)(this.dataverse,t)}deleteWebResource(t){return(0,Fm.deleteWebResource)(this.dataverse,t)}getAppSettings(t){return(0,Ll.readAppSettings)(this.dataverse,t)}setAppSetting(t,r,n){return(0,Ll.setAppSetting)(this.dataverse,t,r,n)}setHeaderAndNavigationRefresh(t,r){if(typeof r!="boolean")throw new Z.ValidationError("app",t,[{pointer:"/headerAndNavigationRefresh",rule:nue.HEADER_NAV_BOOLEAN_RULE,message:`enabled must be a boolean, got ${typeof r}`}]);return(0,Ll.setAppSetting)(this.dataverse,t,Ll.HEADER_AND_NAVIGATION_REFRESH,r?Ll.APP_SETTING_ON:Ll.APP_SETTING_OFF)}getSolution(t){return(0,ar.getSolution)(this.dataverse,t)}createPublisher(t){return(0,ar.createPublisher)(this.dataverse,t)}createSolution(t){return(0,ar.createSolution)(this.dataverse,t)}setSolutionVersion(t,r){return(0,ar.setSolutionVersion)(this.dataverse,t,r)}addSolutionComponent(t){return(0,ar.addSolutionComponent)(this.dataverse,t)}removeSolutionComponent(t,r,n){return(0,ar.removeSolutionComponent)(this.dataverse,t,r,n)}exportSolution(t){return(0,ar.exportSolution)(this.dataverse,t)}importSolution(t){return this.schemaWrite(void 0,()=>(0,ar.importSolution)(this.dataverse,t))}getDeploymentSettingsTemplate(t){return(0,ar.getDeploymentSettingsTemplate)(this.dataverse,t)}registerPcfControl(t,r){let n=()=>(0,iue.registerPcfControl)(this.dataverse,t,r);return r?.publishAll===!0?this.schemaWrite(void 0,n):n()}deleteSolution(t){return this.schemaWrite(void 0,()=>(0,ar.deleteSolution)(this.dataverse,t))}async getArtifact(t,r){return this.withArtifactLock(t,r,async()=>{let{artifact:n,meta:i}=await this.readWhole(t,r);return await this.acknowledgeRefresh(t,r,i),n})}async getArtifactUnlocked(t,r){return this.readRaw(t,r)}async readWhole(t,r){let{meta:n}=await this.revalidate(t,r);return{artifact:await this.readLocal(t,r),meta:n}}async acknowledgeRefresh(t,r,n){var i,o,a;let s=this.artifactKey(t,r),l=n===void 0?await this.versions.getMeta(t,r):n;this.baselineObserved.has(s)||this.baselineObserved.set(s,(i=l?.observedGeneration)!==null&&i!==void 0?i:0);let u=(o=l?.refreshGeneration)!==null&&o!==void 0?o:0;this.raiseGenerationHighWater(s,u),l&&u!==((a=l.observedGeneration)!==null&&a!==void 0?a:0)&&await this.versions.storeMeta(t,r,{...l,observedGeneration:u},l),this.observedGenerations.set(s,u)}raiseGenerationHighWater(t,r){var n;r>((n=this.generationHighWater.get(t))!==null&&n!==void 0?n:0)&&this.generationHighWater.set(t,r)}async observedAtInvocation(t,r,n){var i,o;if(n!==void 0)return n;let a=this.baselineObserved.get(this.artifactKey(t,r));return a!==void 0?a:(o=(i=await this.versions.getMeta(t,r))===null||i===void 0?void 0:i.observedGeneration)!==null&&o!==void 0?o:0}artifactKey(t,r){return`${t}\0${(0,QU.canonicalArtifactId)(r)}`}nextRefreshGeneration(t,r,n){var i,o,a;let s=this.artifactKey(t,r),l=Math.max((i=n?.refreshGeneration)!==null&&i!==void 0?i:0,(o=n?.observedGeneration)!==null&&o!==void 0?o:0,(a=this.generationHighWater.get(s))!==null&&a!==void 0?a:0)+1;return this.raiseGenerationHighWater(s,l),l}async readRaw(t,r){return await this.revalidateIfStale(t,r),this.readLocal(t,r)}async readForMutation(t,r,n,i){var o,a;let s=await this.observedAtInvocation(t,r,i);if(((a=(o=await this.versions.getMeta(t,r))===null||o===void 0?void 0:o.refreshGeneration)!==null&&a!==void 0?a:0)>s)throw new Z.StaleArtifactError(t,r,n,"pushed");if(await this.revalidateIfStale(t,r)==="refreshed-changed")throw new Z.StaleArtifactError(t,r,n);return this.readLocal(t,r)}async readLocal(t,r){let n=await this.workspace.readArtifact(t,r);if(!n)throw new Z.ArtifactNotFoundError(t,r);return n}async revalidateIfStale(t,r){return(await this.revalidate(t,r)).outcome}async revalidate(t,r){let n=await this.versions.getMeta(t,r);if(!n)return{outcome:"skipped",meta:null};let i=n.fetchedAt?Date.parse(n.fetchedAt):NaN,o=Date.now()-i;if(!Number.isNaN(i)&&this.cacheStalenessMs>0&&o<=this.cacheStalenessMs)return{outcome:"fresh",meta:n};if(await this.versions.isDirty(t,r,n))return{outcome:"skipped",meta:n};let a=await this.workspace.readArtifact(t,r);await this.fetchArtifactUnlocked(t,r);let s=await this.workspace.readArtifact(t,r);return{outcome:(0,_n.deepEqual)(a,s)?"refreshed-unchanged":"refreshed-changed"}}async queryTree(t,r,n){return this.withArtifactLock(t,r,async()=>{let{artifact:i,meta:o}=await this.readWhole(t,r),a=Nn.JsonPointer.resolve(i,n);if(a===void 0)throw new Z.PathNotFoundError(t,r,n);return n===""&&await this.acknowledgeRefresh(t,r,o),a})}async findElements(t,r,n){return this.withArtifactLock(t,r,async()=>(0,Qle.findElements)(await this.getArtifactUnlocked(t,r),n))}async withDirtyFlags(t){let r=[];for(let n of t)r.push({...n,isDirty:await this.versions.isDirty(n.type,n.id)});return r}async listArtifacts(t,r){return this.withDirtyFlags(await this.workspace.listArtifacts(t,r))}async getEntityMetadata(t){let r=await this.readCachedEntityMetadata(t);if(!r)throw new Z.ArtifactNotFoundError("entityMetadata",t);return r}async getFieldMetadata(t,r){let i=(await this.getEntityMetadata(t)).attributes.find(o=>o.logicalName===r);if(!i)throw new Z.PathNotFoundError("entityMetadata",t,r);return i}async updateElement(t,r,n,i){let o=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let a=await this.readForMutation(t,r,n,o),s=Nn.JsonPointer.resolve(a,n);if(s===void 0)throw new Z.PathNotFoundError(t,r,n);let l=oo(s)&&oo(i)?{...s,...i}:i;return Nn.JsonPointer.set(a,n,(0,Ai.cloneJson)(l)),this.assertStructurallyValid(t,r,a,n),await this.workspace.writeArtifact(t,r,a),this.getArtifactUnlocked(t,r)})}async addElement(t,r,n,i,o){let a=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let s=await this.readForMutation(t,r,n,a),l=Nn.JsonPointer.resolve(s,n);if(l===void 0)throw new Z.PathNotFoundError(t,r,n);if(!Array.isArray(l)){if(!oo(l)||!oo(i))throw new Z.ValidationError(t,r,n,"parent must be an array, or an object with an object of properties to add");if(o?.position!==void 0)throw new Z.ValidationError(t,r,n,"position is not supported for an object parent");let d={};for(let f of Object.keys(i)){if(f==="id")throw new Z.ValidationError(t,r,n,"refusing to write 'id' \u2014 that re-keys the node rather than adding a property");let m=(0,Ai.cloneJson)(i[f]),p=(0,Mm.isValueMapKey)(f)||(0,Mm.pointerTouchesValueMap)(n);d[f]=p?m:Array.isArray(m)?m.map(h=>oo(h)?this.assignMissingIds(t,h):h):oo(m)?this.assignMissingIds(t,m):m}for(let f of Object.keys(d))Nn.JsonPointer.set(s,Nn.JsonPointer.append(n,f),d[f]);return this.assertStructurallyValid(t,r,s,n),await this.workspace.writeArtifact(t,r,s),this.getArtifactUnlocked(t,r)}let u=(0,Mm.pointerTouchesValueMap)(n)?(0,Ai.cloneJson)(i):this.assignMissingIds(t,(0,Ai.cloneJson)(i)),c=_ue(l,o?.position);return l.splice(c,0,u),this.assertStructurallyValid(t,r,s,n),await this.workspace.writeArtifact(t,r,s),this.getArtifactUnlocked(t,r)})}async moveElement(t,r,n,i,o){let a=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{var s;let l=await this.readForMutation(t,r,n,a),u=Nn.JsonPointer.resolve(l,n);if(u===void 0)throw new Z.PathNotFoundError(t,r,n);let c=Nn.JsonPointer.resolve(l,i);if(c===void 0)throw new Z.PathNotFoundError(t,r,i);if(!Array.isArray(c))throw new Z.ValidationError(t,r,i,"move target must be an array");if(i===n||i.startsWith(`${n}/`))throw new Z.ValidationError(t,r,i,"cannot move an element into its own subtree");Nn.JsonPointer.remove(l,n);let d=(s=o?.index)!==null&&s!==void 0?s:c.length;c.splice(Math.max(0,Math.min(d,c.length)),0,u),YU(c);let f=Nn.JsonPointer.resolve(l,JU(n));return Array.isArray(f)&&f!==c&&YU(f),this.assertStructurallyValid(t,r,l,i),await this.workspace.writeArtifact(t,r,l),this.getArtifactUnlocked(t,r)})}async removeElement(t,r,n){let i=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let o=await this.readForMutation(t,r,n,i);if(Nn.JsonPointer.resolve(o,n)===void 0)throw new Z.PathNotFoundError(t,r,n);return Nn.JsonPointer.remove(o,n),this.assertStructurallyValid(t,r,o,JU(n)),await this.workspace.writeArtifact(t,r,o),this.getArtifactUnlocked(t,r)})}assertStructurallyValid(t,r,n,i){var o,a,s;let l=this.registrations.get(t),u=(s=(a=l==null?void 0:(o=l.adapter).validate)===null||a===void 0?void 0:a.call(o,n,i))!==null&&s!==void 0?s:[];if(u.length>0)throw new Z.ValidationError(t,r,u)}retrieveSetting(t,r){return(0,kl.retrieveSetting)(this.dataverse,t,r)}saveSettingValue(t,r,n){return(0,kl.saveSettingValue)(this.dataverse,t,r,n)}getAiReadiness(t){return(0,kl.getAiReadiness)(this.dataverse,t)}setAppAiFeatures(t,r,n){return(0,kl.setAppAiFeatures)(this.dataverse,t,r,n)}configureRowSummary(t,r){return(0,kl.configureRowSummary)(this.dataverse,t,r)}removeRowSummary(t){return(0,kl.removeRowSummary)(this.dataverse,t)}async enrichDefaultViews(t,r,n={}){let i=await(0,due.findDefaultViews)(this.dataverse,t,{excludeViewIds:n.excludeViewIds}),o=n.publish===!1,a=[],s=[],l=()=>({updated:[...a],results:[...s],pendingPublish:a.length>0?[{scope:(0,BU.boundEntityPublishScope)({entityLogicalName:t}),artifacts:a.map(c=>({type:"view",id:c}))}]:[]}),u;try{for(let c of i){await this.fetchArtifact("view",c.id),await this.updateElement("view",c.id,"/columns",r),u=c.id;let d=await this.pushArtifact("view",c.id);u=void 0,s.push(d),d.saved&&a.push(c.id)}}catch(c){throw u&&pue(c)&&a.push(u),o?(0,Z.withPartialEnrichment)(c,l()):c}if(o)return l();if(a.length){let c=await this.publishArtifact("view",a[0]);if(c.publish.kind==="failed")throw new Z.SdkError("ENRICH_DEFAULT_VIEWS_PUBLISH_FAILED",`enrichDefaultViews: ${a.length} view(s) on '${t}' were saved but the publish FAILED, so none of them is live (${c.publish.error.message}). Re-publish the entity to make them visible; the saves themselves are unaffected.`)}return{updated:a}}async createArtifact(t,r){let n=this.requireRegistration(t,"createArtifact"),i=n.adapter.assignMissingIds(n.adapter.createDefault(r)),o=i.id;if(!o)throw new Z.ValidationError(t,"(new)","/id","created artifact must have an id");return this.withArtifactLock(t,o,async()=>(await this.workspace.writeArtifact(t,o,i),(0,Ai.cloneJson)(i)))}async deleteArtifact(t,r){return this.withArtifactLock(t,r,async()=>{await this.workspace.deleteArtifact(t,r)})}async deleteRemoteArtifact(t,r){return this.withArtifactLock(t,r,async()=>{let n=this.requireRegistration(t,"deleteRemoteArtifact");await this.workspace.ensureReady(),await n.api.delete(this.dataverse,r),await this.workspace.readArtifact(t,r)&&await this.workspace.deleteArtifact(t,r)})}async publishArtifact(t,r,n){let{result:i,siblings:o}=await this.withArtifactLock(t,r,()=>this.publishArtifactUnlocked(t,r,n));for(let a of o)await this.withArtifactLock(a.type,a.id,()=>this.adoptBracket(a));return i}async publishArtifacts(t,r){var n,i;let o=new Map;for(let p of t){let h=this.artifactKey(p.type,p.id);o.has(h)||o.set(h,{type:p.type,id:p.id})}let a=[];for(let[p,h]of o)a.push(await this.withArtifactLock(h.type,h.id,()=>this.preparePublish(p,h.type,h.id)));let s=new Set(o.keys()),l=[],u=new Set;for(let p of a){let h=((n=p.scope)===null||n===void 0?void 0:n.envelope)==="entity"?(i=p.scope.entityLogicalName)===null||i===void 0?void 0:i.toLowerCase():void 0;p.scope&&h&&!u.has(h)&&(u.add(h),l.push(p.scope))}let c=await this.captureSiblings(l,s),d=vue(a),f;if(d)try{await(0,BU.publishXml)(this.dataverse,d)}catch(p){f=zo(p)}let m=new Map;for(let p of a)m.set(p.key,await this.withArtifactLock(p.type,p.id,()=>this.settlePublish(p,f,r)));for(let p of c)await this.withArtifactLock(p.type,p.id,()=>this.adoptBracket(p));return t.map(p=>({...m.get(this.artifactKey(p.type,p.id))}))}async preparePublish(t,r,n){var i;let o=await this.readRaw(r,n),a=this.registrations.get(r);if(!a?.publish)return{key:t,type:r,id:n,artifact:o,notApplicable:!0};let s=(i=a.publishScope)===null||i===void 0?void 0:i.call(a,n,o);if(!s||!bue.has(s.envelope))throw new Z.InvalidArgumentError(`publishArtifacts: ${r} '${n}' publishes through ${s?`a '${s.envelope}'`:"no declared"} scope, which one PublishXml envelope cannot carry. Publish it with publishArtifact.`);let l=a.rebaselineAfterPublish==="bracket"?await this.captureBracket(a,r,n):void 0;return{key:t,type:r,id:n,artifact:o,reg:a,scope:s,...l?{own:l}:{}}}async settlePublish(t,r,n){let{type:i,id:o}=t;if(t.notApplicable||!t.reg)return{type:i,id:o,shipped:!1,publish:{kind:"notApplicable"}};let a=t.scope?{publishScope:t.scope}:{};if(t.reg.rebaselineAfterPublish==="snapshot"&&await this.rebaselineAfterPublish(t.reg,i,o),t.own&&await this.adoptBracket(t.own),r)return{type:i,id:o,shipped:!1,publish:{kind:"failed",error:r},...a};if(!n?.verify)return{type:i,id:o,shipped:!1,publish:{kind:"submitted"},...a};let s=await this.workspace.readArtifact(i,o).catch(()=>null);if(!s||!(0,_n.deepEqual)(s,t.artifact))return{type:i,id:o,shipped:!1,publish:{kind:"unverifiable",reason:`the local ${i} was ${s?"edited":"deleted"} while the publish was in flight, so what shipped cannot be told from what is local now; verify it with publishArtifact`},...a};let l=await this.verifyPublished(i,o,t.artifact);return{type:i,id:o,shipped:l.kind==="verified",publish:l,...a}}async publishArtifactUnlocked(t,r,n){var i;let o=await this.readRaw(t,r),a=this.registrations.get(t);if(!a?.publish)return{result:{type:t,id:r,shipped:!1,publish:{kind:"notApplicable"}},siblings:[]};let s=(i=a.publishScope)===null||i===void 0?void 0:i.call(a,r,o),l=a.rebaselineAfterPublish==="bracket"?await this.captureBracket(a,t,r):void 0,u=s?await this.captureSiblings([s],new Set([this.artifactKey(t,r)])):[];try{await a.publish(this.dataverse,r,o)}catch(d){return{result:{type:t,id:r,shipped:!1,publish:{kind:"failed",error:zo(d)},...s?{publishScope:s}:{}},siblings:[]}}if(a.rebaselineAfterPublish==="snapshot"&&await this.rebaselineAfterPublish(a,t,r),l&&await this.adoptBracket(l),!n?.verify)return{result:{type:t,id:r,shipped:!1,publish:{kind:"submitted"},...s?{publishScope:s}:{}},siblings:u};let c=await this.verifyPublished(t,r,o);return{result:{type:t,id:r,shipped:c.kind==="verified",publish:c,...s?{publishScope:s}:{}},siblings:u}}async captureBracket(t,r,n){try{let i=await this.versions.getMeta(r,n),o=i?.etag;if(!(0,Cr.isVersionToken)(o)||!t.api.readContentThenToken)return;let{raw:a,etag:s,siblingEtags:l}=await t.api.readContentThenToken(this.dataverse,n),u=i?.siblingEtags;return s!==o||!Sue(u,l)?void 0:{type:r,id:n,reg:t,heldEtag:o,...u?{heldSiblings:u}:{},content:this.bracketContent(t,a)}}catch{return}}async captureSiblings(t,r){var n,i,o;let a=new Map;for(let u of t){let c=u.envelope==="entity"?(n=u.entityLogicalName)===null||n===void 0?void 0:n.toLowerCase():void 0;c&&!a.has(c)&&a.set(c,[])}if(a.size===0)return[];let s;try{s=await this.workspace.listArtifacts()}catch{return[]}for(let u of s){let c=this.registrations.get(u.type);if(!(r.has(this.artifactKey(u.type,u.id))||c?.rebaselineAfterPublish!=="bracket"||!c.publishScope))try{let d=await this.workspace.readArtifact(u.type,u.id),f=d?c.publishScope(u.id,d):void 0,m=f?.envelope==="entity"?(i=f.entityLogicalName)===null||i===void 0?void 0:i.toLowerCase():void 0;m!==void 0&&((o=a.get(m))===null||o===void 0||o.push(u))}catch{continue}}let l=[];for(let u of a.values())for(let c of u){let d=this.registrations.get(c.type),f=d?await this.captureBracket(d,c.type,c.id):void 0;f&&l.push(f)}return l}async adoptBracket(t){var r;try{let n=await this.versions.getMeta(t.type,t.id);if(!n||n.etag!==t.heldEtag||!(0,_n.deepEqual)((r=n.siblingEtags)!==null&&r!==void 0?r:void 0,t.heldSiblings))return;let{raw:i,etag:o,siblingEtags:a}=await t.reg.api.get(this.dataverse,t.id);if(!(0,Cr.isVersionToken)(o)||!ZU(a,t.heldSiblings)||!eB(a)||!(o!==t.heldEtag||!(0,_n.deepEqual)(a??void 0,t.heldSiblings))||!(0,_n.deepEqual)(this.bracketContent(t.reg,i),t.content))return;await this.versions.storeMeta(t.type,t.id,{...n,etag:o,...t.heldSiblings?{siblingEtags:{...a}}:{},fetchedAt:(0,Cr.nowIso)()},n)}catch{}}bracketContent(t,r){var n,i,o;let a=t.adapter.fromApiResponse(r);return(o=(i=(n=t.adapter).baselineContent)===null||i===void 0?void 0:i.call(n,a))!==null&&o!==void 0?o:a}adoptReadBack(t,r){try{return{artifact:t.adapter.fromApiResponse(r)}}catch(n){return{warning:`The write was saved, but the record read back after it could not be read into the local copy (${zo(n).message}). The SDK holds no version for it now, so the next push is refused: re-fetch before editing again.`}}}adoptedAsSent(t,r,n,i){try{let o={...n,...i},a=t.adapter.fromApiResponse(t.adapter.completeAsStored?t.adapter.completeAsStored(o,n):o);return(0,_n.deepEqual)(r,a)}catch{return!1}}async rebaselineAfterPublish(t,r,n){try{let i=await this.versions.getMeta(r,n);if(!i)return;let{raw:o,etag:a,memberEtags:s,siblingEtags:l}=t.api.getForRebaseline?await t.api.getForRebaseline(this.dataverse,n):await t.api.get(this.dataverse,n),u=t.adapter.fromApiResponse(o),c=d=>{var f,m,p;return(p=(m=(f=t.adapter).baselineContent)===null||m===void 0?void 0:m.call(f,d))!==null&&p!==void 0?p:d};if(!a||!(0,_n.deepEqual)(c(i.snapshot),c(u)))return;await this.versions.storeMeta(r,n,{...i,etag:a,fetchedAt:(0,Cr.nowIso)(),...s?{memberEtags:s}:{},...l?{siblingEtags:l}:{}},i)}catch{}}async verifyPublished(t,r,n){var i,o,a,s,l;if(t!=="app"){let u=this.registrations.get(t);return u?.api.getPublished?this.verifyPublishedContent(u,t,r,n):{kind:"unverifiable",reason:`published-projection verification is not characterised for '${t}'; the publish was submitted`}}try{let u=`/appmodules(${(0,ja.normalizeGuid)(r,"id")})${(0,ja.odataQuery)([["$select","appmoduleid,name,description"]])}`,c=await this.dataverse.get(u);if(c.status>=200&&c.status<300){let d=(i=c.body)!==null&&i!==void 0?i:{},f=n;if(!f)return{kind:"unverifiable",reason:"there is no local copy of the app to compare the published projection with"};let m=[];return((o=f.name)!==null&&o!==void 0?o:"")!==((a=d.name)!==null&&a!==void 0?a:"")&&m.push("name"),((s=f.description)!==null&&s!==void 0?s:"")!==((l=d.description)!==null&&l!==void 0?l:"")&&m.push("description"),m.length>0?{kind:"unverifiable",reason:`the published projection does not yet match the saved app (${m.join(", ")} still differ). PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}:{kind:"verified"}}return{kind:"unverifiable",reason:`the published projection answered HTTP ${c.status}`}}catch(u){return{kind:"unverifiable",reason:zo(u).message}}}async verifyPublishedContent(t,r,n,i){var o,a,s;try{let l=f=>{var m,p,h;return(h=(p=(m=t.adapter).baselineContent)===null||p===void 0?void 0:p.call(m,f))!==null&&h!==void 0?h:f},u=l(i),c=(o=await this.versions.getMeta(r,n))===null||o===void 0?void 0:o.snapshot;if(c===void 0||!(0,_n.deepEqual)(u,l(c)))return{kind:"unverifiable",reason:`the local ${r} holds edits that were never pushed, so no publish could have shipped them \u2014 push, then publish again`};let d=await((s=(a=t.api).getPublished)===null||s===void 0?void 0:s.call(a,this.dataverse,n));return d?(0,_n.deepEqual)(u,l(t.adapter.fromApiResponse(d.raw)))?{kind:"verified"}:{kind:"unverifiable",reason:"the published projection does not show what was pushed. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists"}:{kind:"unverifiable",reason:`the ${r} is not in the published projection yet. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}}catch(l){return{kind:"unverifiable",reason:zo(l).message}}}async pushArtifact(t,r){return this.withArtifactLock(t,r,()=>this.pushArtifactUnlocked(t,r))}async prepareArtifactUnlocked(t,r,n){var i,o;let a=this.requireRegistration(t,"pushArtifact"),s=await this.workspace.readArtifactWithText(t,r);if(!s)throw new Z.ArtifactNotFoundError(t,r);let l=s.artifact,u=s.text,c=(o=(i=a.adapter).normalize)===null||o===void 0?void 0:o.call(i,l);c&&c!==l&&(await this.workspace.writeArtifact(t,r,c),l=c,u=void 0);let d=await this.versions.getMeta(t,r);this.assertLanguageMatches(t,r,d,a),this.assertProjectionMatches(t,r,d);let f=await this.buildMetadataContext(a.adapter,l,d?.snapshot),m=await a.adapter.toApiPayload(l,d?.snapshot,f);return await this.assertSemanticallyComplete(a,t,r,l,d===null,d?.everActivated,n),{type:t,id:r,reg:a,json:l,...u!==void 0?{storedText:u}:{},meta:d,payload:m}}async assertSemanticallyComplete(t,r,n,i,o,a,s){let l=t.adapter.issuesBlockingPush;if(!l)return;let u=i.entityLogicalName,d=(u?await this.columnsForCheck(t,u,i,s):[]).map(m=>({logicalName:m.logicalName,displayName:m.displayName,attributeType:m.attributeType,isCustomAttribute:m.isCustomAttribute,...m.maxLength!==void 0?{maxLength:m.maxLength}:{},...m.options?{options:m.options.map(p=>({value:p.value,label:p.label}))}:{},...m.targets?{targets:m.targets}:{}})),f=l.call(t.adapter,i,d,{isCreate:o,everActivated:a});if(f.length>0)throw new Z.ValidationError(r,n,f)}columnsForCheck(t,r,n,i){var o,a,s;let l=(s=(a=(o=t.adapter).columnsCheckedAtPush)===null||a===void 0?void 0:a.call(o,n))!==null&&s!==void 0?s:[],u=async()=>{let f=await this.readCachedEntityMetadata(r);if(f)return f.attributes;try{return await(0,Rl.readCheckColumns)(this.dataverse,r,l)}catch{return[]}};if(!i)return u();let c=[r,...[...new Set(l)].sort()].join("\0"),d=i.get(c);return d||(d=u(),i.set(c,d)),d}async pushArtifactUnlocked(t,r,n){return this.executePrepared(await this.prepareArtifactUnlocked(t,r,n))}async executePrepared(t){var r,n,i,o,a,s,l,u,c;let{type:d,id:f,reg:m,json:p,meta:h,payload:g}=t,b=!1;try{let w;if(h)w=await m.api.update(this.dataverse,f,g,h.etag,h.memberEtags,h.siblingEtags);else{let P=await this.createWithMintedId(m,d,f,g,p);if("adopted"in P)return await this.persistAdoption(d,f,p,P.adopted);w=P.written}b=!0;let C=f;h||(w.serverIdentity&&m.adapter.applyServerIdentity&&m.adapter.applyServerIdentity(p,w.serverIdentity),w.id&&w.id!==f&&(p.id=w.id,await this.workspace.deleteArtifact(d,f),C=w.id));let S=h&&w.readBack!==void 0?this.adoptReadBack(m,w.readBack):void 0,O=S?.artifact?{artifact:S.artifact,baseline:S.artifact}:m.adapter.committed?m.adapter.committed(p,g,{intentPending:w.intentPending===!0}):{artifact:p,baseline:p};await this.workspace.writeArtifact(d,C,O.artifact,h&&C===f?t.storedText:void 0);let L=S?.artifact!==void 0&&!(0,_n.deepEqual)(S.artifact,p),I=L?this.nextRefreshGeneration(d,C,h):(r=h?.refreshGeneration)!==null&&r!==void 0?r:0,D=[...(n=w.warnings)!==null&&n!==void 0?n:[],...S?.warning?[S.warning]:[],...S?.artifact!==void 0&&!this.adoptedAsSent(m,S.artifact,w.readBack,g)?[`Saved, but the server holds something other than what was pushed (another writer saved in between, or the platform rewrote something the SDK does not model \u2014 a label in a language the org does not provision, a hand-written fragment); the local ${d} now holds the server's version. Read it (getArtifact) before the next edit: a mutation whose pointer was derived from the earlier copy is refused (StaleArtifactError).`]:[]];return await this.versions.storeMeta(d,C,{etag:S&&!S.artifact?null:w.etag,...I>0?{refreshGeneration:I,observedGeneration:(i=h?.observedGeneration)!==null&&i!==void 0?i:0}:{},languageCode:this.languageCode,projectionVersion:Pl.PROJECTION_VERSION,fetchedAt:(0,Cr.nowIso)(),snapshot:(0,Ai.cloneJson)(O.baseline),...w.memberEtags?{memberEtags:w.memberEtags}:{},...w.siblingEtags?{siblingEtags:w.siblingEtags}:{}},C===f?h:void 0),{type:d,id:C,saved:!0,shipped:!1,publish:(o=w.publish)!==null&&o!==void 0?o:{kind:"notRequested"},...w.publish&&w.publish.kind!=="notRequested"?(()=>{var P;let x=(P=m.publishScope)===null||P===void 0?void 0:P.call(m,C,p);return x?{publishScope:x}:{}})():{},...L?{refreshed:!0}:{},...D.length>0?{warnings:D}:{}}}catch(w){let C=(0,Z.readPartialTokens)(w);if(C&&h){let S={...(a=h.memberEtags)!==null&&a!==void 0?a:{},...(s=C.memberEtags)!==null&&s!==void 0?s:{}},O={...(l=h.siblingEtags)!==null&&l!==void 0?l:{},...(u=C.siblingEtags)!==null&&u!==void 0?u:{}};await this.versions.storeMeta(d,f,{...h,...Object.keys(S).length>0?{memberEtags:S}:{},...Object.keys(O).length>0?{siblingEtags:O}:{}},h)}if(w instanceof Z.SdkError&&w.code===Er.ALREADY_EXISTS_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===UU.WFOM_API_UNAVAILABLE_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===UU.BUSINESS_RULE_LEFT_DEACTIVATED_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===Cr.VERSION_CONFLICT_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:(0,GU.isFailureAfterPrimaryWrite)(w)?w:new Z.VersionConflictError(d,f,(c=h?.etag)!==null&&c!==void 0?c:null,null,w.message)};throw b?fue(w):w}}assertLanguageMatches(t,r,n,i){if(i?.languageSensitive&&!(n?.languageCode===void 0||n.languageCode===this.languageCode))throw new Z.SdkError("ARTIFACT_LANGUAGE_MISMATCH",`Refusing to push ${t} '${r}': it was fetched with languageCode ${n.languageCode} but this SDK is configured with ${this.languageCode}. Pushing would rewrite labels read in one language as labels in another. Re-fetch with languageCode ${this.languageCode}, or create the SDK with languageCode ${n.languageCode}.`)}assertProjectionMatches(t,r,n){var i;if(n&&n.projectionVersion!==Pl.PROJECTION_VERSION)throw new Z.SdkError("ARTIFACT_PROJECTION_STALE",`Refusing to push ${t} '${r}': its workspace copy was produced by projection version ${(i=n.projectionVersion)!==null&&i!==void 0?i:"unknown (pre-versioning)"}, but this SDK produces version ${Pl.PROJECTION_VERSION}. The parsers changed in between, so an unedited part of this artifact can no longer be told apart from an edited one and pushing could overwrite server content the caller never touched. Re-fetch it with fetchArtifact('${t}', '${r}') and re-apply any local edits.`)}async createWithMintedId(t,r,n,i,o){try{return{written:await t.api.create(this.dataverse,i,n)}}catch(a){let s=r==="form"?(0,$w.readPrimaryCreateRefusal)(a):void 0;if(s?.status===404&&await(0,VU.formExistsAtId)(()=>t.api.get(this.dataverse,n),s.sent.formid)){let u=`the platform answered the create with ${a.message} \u2014 this build refuses a replayed create that way \u2014 but a read of that id finds the record`;throw(0,Z.attachCause)(new Z.SdkError(Er.ALREADY_EXISTS_CODE,Mw(r,n,u)+(this.createRecovery==="adoptExact"?` ${KU(Cue)}`:"")),a)}if(!(a instanceof Z.SdkError)||a.code!==Cr.VERSION_CONFLICT_CODE||(0,GU.isFailureAfterPrimaryWrite)(a))throw a;if(this.createRecovery==="adoptExact"&&s?.status===412){let l=await(0,VU.recoverFormCreate)({client:this.dataverse,read:()=>t.api.get(this.dataverse,n),sent:s.sent,authoredFormType:o.formType,project:u=>t.adapter.fromApiResponse(u)});if("adopted"in l)return{adopted:l.adopted};throw new Z.SdkError(Er.ALREADY_EXISTS_CODE,`${Mw(r,n)} ${KU(l.refused)}`)}throw new Z.SdkError(Er.ALREADY_EXISTS_CODE,Mw(r,n))}}async persistAdoption(t,r,n,i){let{artifact:o,etag:a}=i,s=!(0,_n.deepEqual)(o,n);return await this.versions.storeMeta(t,r,{etag:a,...s?{refreshGeneration:this.nextRefreshGeneration(t,r,null),observedGeneration:0}:{},languageCode:this.languageCode,projectionVersion:Pl.PROJECTION_VERSION,fetchedAt:(0,Cr.nowIso)(),snapshot:(0,Ai.cloneJson)(o)},null),s&&await this.workspace.writeArtifact(t,r,o),{type:t,id:r,saved:!1,adoptedExisting:!0,shipped:!1,publish:{kind:"notRequested"},...s?{refreshed:!0}:{}}}async buildMetadataContext(t,r,n){var i,o,a,s;let l=(o=(i=t.metadataNeeds)===null||i===void 0?void 0:i.call(t,r,n))!==null&&o!==void 0?o:[],u=new Set(l.map(L=>L.entityLogicalName).filter(L=>!!L)),c=new Set(l.filter(L=>L.needsColumnDetail).map(L=>L.entityLogicalName)),d=new Set(l.filter(L=>L.needsColumnDetail||!L.fieldName).map(L=>L.entityLogicalName)),f=L=>l.filter(I=>I.entityLogicalName===L).every(I=>I.fetchRequired===!1),m=new Map,p=new Map;for(let L of u){let I=await this.readCachedEntityMetadata(L);if(I&&c.has(L)&&(I.columnDetailComplete!==!0||!(typeof I.columnDetailVersion=="number"&&I.columnDetailVersion>=Rl.COLUMN_DETAIL_VERSION)||I.attributes.some(D=>typeof D.attributeTypeName!="string"))&&(I=null),!I&&!d.has(L)){if(!f(L)){let D=l.filter(P=>P.entityLogicalName===L).map(P=>P.fieldName);try{let P=await(0,Rl.readColumnHints)(this.dataverse,L,D);p.set(L,new Map(P.map(x=>[x.logicalName,x])))}catch{}}continue}if(!I&&!f(L))try{await this.loadMissedEntityMetadata(L),I=await this.readCachedEntityMetadata(L)}catch{}I&&m.set(L,I)}let h=(L,I)=>{var D,P,x;return(P=(D=m.get(L))===null||D===void 0?void 0:D.attributes.find(K=>K.logicalName===I))!==null&&P!==void 0?P:(x=p.get(L))===null||x===void 0?void 0:x.get(I)},g=this.languageCode,w=l.some(L=>{if(!L.needsLabel||!L.fieldName)return!1;let I=h(L.entityLogicalName,L.fieldName);return I?.localizedDisplayName!==void 0&&!I.localizedDisplayName[g]})?await this.readBaseLanguage():void 0,C=!((a=t.needsBaseLanguage)===null||a===void 0)&&a.call(t,r)?await this.readBaseLanguage():void 0,S=(s=t.customControlNeeds)===null||s===void 0?void 0:s.call(t,r,n),O=S&&(S.controls.length>0||S.columns.length>0)?await this.readPcfNeeds(S):void 0;return{resolveField:(L,I)=>{let D=h(L,I);return D?{displayName:Nue(D,g,w),attributeType:D.attributeType}:void 0},resolveEntity:L=>m.get(L),loadTypeScript:()=>this.compiler.load(),...C!==void 0?{baseLanguageCode:C}:{},...O?{pcf:O}:{}}}async readPcfNeeds(t){let r=new Map;for(let i of t.controls)r.set(i,await(0,qU.readControlManifest)(this.dataverse,i));let n=new Map;for(let i of t.columns)n.set(i,await(0,qU.readPcfColumn)(this.dataverse,t.entityLogicalName,i,t.requireCreateEligibility?{requireCreateEligibility:!0}:void 0));return{control:i=>r.get(i),column:(i,o)=>i===t.entityLogicalName?n.get(o):void 0}}readBaseLanguage(){if(!this.baseLanguage){let t=(async()=>{var r,n,i;try{let o=await this.dataverse.get("/organizations?$select=languagecode");if(o.status<200||o.status>=300)return;let a=Number((i=(n=(r=o.body)===null||r===void 0?void 0:r.value)===null||n===void 0?void 0:n[0])===null||i===void 0?void 0:i.languagecode);return Number.isInteger(a)&&a>0?a:void 0}catch{return}})();this.baseLanguage=t,t.then(r=>{r===void 0&&this.baseLanguage===t&&(this.baseLanguage=void 0)})}return this.baseLanguage}async pushAll(){let t=await this.getDirtyArtifacts();await this.warmBatchMetadata(t);let r=new Map,n=new Map;for(let o=0;o<t.length;o+=1){let a=t[o];try{await this.withArtifactLock(a.type,a.id,()=>this.prepareArtifactUnlocked(a.type,a.id,r))}catch(s){n.set(o,{type:a.type,id:a.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:zo(s)})}}if(n.size>0)return t.map((o,a)=>{var s;return(s=n.get(a))!==null&&s!==void 0?s:{type:o.type,id:o.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:new Z.SdkError(Er.PUSH_NOT_ATTEMPTED_CODE,`Not attempted: ${n.size} artifact(s) in this batch could not be prepared, so no writes were issued. Fix the reported failures and push again.`)}});let i=[];for(let o of t)try{i.push(await this.withArtifactLock(o.type,o.id,()=>this.pushArtifactUnlocked(o.type,o.id,r)))}catch(a){i.push({type:o.type,id:o.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:zo(a)})}return i}async warmBatchMetadata(t){var r,n,i;let o=new Set;for(let a of t){let s=this.registrations.get(a.type);if(!s)continue;let l;try{l=await this.readLocal(a.type,a.id)}catch{continue}let u=l.entityLogicalName;u&&o.add(u);for(let c of(i=(n=(r=s.adapter).metadataNeeds)===null||n===void 0?void 0:n.call(r,l))!==null&&i!==void 0?i:[])c.entityLogicalName&&o.add(c.entityLogicalName)}for(let a of o)if(!await this.readCachedEntityMetadata(a))try{await this.loadMissedEntityMetadata(a)}catch{}}async getDirtyArtifacts(){return(await this.withDirtyFlags(await this.workspace.listArtifacts())).filter(r=>r.isDirty)}async diffArtifact(t,r){return this.versions.diff(t,r)}assignMissingIds(t,r){let n=this.registrations.get(t);return n?n.adapter.assignMissingIds(r):(0,Mm.assignMissingIds)(r)}async resolveComponentType(t){if(t.genPage)return"genPage";switch(t.componentType){case ar.SolutionComponentType.SavedQuery:return"view";case ar.SolutionComponentType.SavedQueryVisualization:return"chart";case ar.SolutionComponentType.AppModule:return"app";case ar.SolutionComponentType.Workflow:return this.workflowArtifactType(t);case ar.SolutionComponentType.SystemForm:return this.systemFormArtifactType(t.objectId);default:return}}async systemFormArtifactType(t){let r=await(0,xm.readSystemFormType)(this.dataverse,t);if(Number.isNaN(r))throw new Z.SdkError(Fw,`System form '${t}' answered without a readable type, so whether it is a form or a dashboard cannot be told.`);return(0,xm.systemFormKindOf)(r)}async workflowArtifactType(t){let r=(0,ja.normalizeGuid)(t.objectId,"workflowId"),n=`/workflows(${r})${(0,ja.odataQuery)([["$select","category,businessprocesstype"]])}`,o=(0,Cr.ensureSuccess)(await this.dataverse.get(n),this.dataverse.apiUrl(n)).body,a=(0,xm.decodeCode)(o?.category);if(Number.isNaN(a))throw new Z.SdkError(Fw,`Workflow '${r}' answered without a readable category, so its kind cannot be told.`);if(t.workflowCategory=a,a===hue)return"businessRule";if(a===gue){let s=(0,xm.decodeCode)(o?.businessprocesstype);if(Number.isNaN(s))throw new Z.SdkError(Fw,`Workflow '${r}' (category 4) answered without a readable businessprocesstype, so whether it is a business process flow or a task flow cannot be told.`);return s===0?"bpf":void 0}}requireRegistration(t,r){let n=this.registrations.get(t);if(!n)throw new Z.NotImplementedError(r,`no adapter registered for artifact type '${t}'`);return n}};Er.MakerSdk=Um;function Aue(e){return new Um(e)}Er.createMakerSdk=Aue;function zo(e){return e instanceof Error?e:new Error(String(e))}function ZU(e,t){let r=Object.keys(e??{}),n=Object.keys(t??{});return r.length===n.length&&r.every(i=>Object.prototype.hasOwnProperty.call(t??{},i))}function eB(e){return Object.values(e??{}).every(Cr.isVersionToken)}function Sue(e,t){return ZU(e,t)&&eB(e)&&Object.keys(e??{}).every(r=>t?.[r]===e?.[r])}function KU(e){return`createRecovery 'adoptExact' did not adopt it: ${e}.`}function Mw(e,t,r){return`Cannot create ${e} '${t}': a record already exists at that id${r?` (${r})`:""}, so an earlier push of this artifact committed before its local version metadata was saved. No duplicate was created. Run fetchArtifact('${e}', '${t}', { overwrite: true }) to adopt the existing record's identity, etag and snapshot \u2014 the overwrite is required, because this local copy has never been pushed, so a plain fetch keeps it and adopts nothing; it REPLACES the local copy, so keep any outstanding local changes aside first \u2014 then re-apply them and push again: a conditional update, provided the adopted record is complete. If the earlier push committed only PART of a multi-row artifact (e.g. an app's appmodule without its sitemap), that update refuses, naming what is missing and how to remove the partial record. This is not done automatically because the only recovery available here would be an UNCONDITIONAL overwrite, which would destroy any edit made to the record in the meantime.`}function Nue(e,t,r){let n=e.localizedDisplayName;return n?.[t]||(r===void 0?void 0:n?.[r])||e.displayName}function oo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function JU(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function YU(e){e.length===0||!e.every(t=>oo(t)&&typeof t.order=="number")||e.forEach((t,r)=>{t.order=r})}function _ue(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=>oo(i)&&i.id===t.before);return n<0?e.length:n}let r=e.findIndex(n=>oo(n)&&n.id===t.after);return r<0?e.length:r+1}});var rB=v(Bm=>{"use strict";Object.defineProperty(Bm,"__esModule",{value:!0});Bm.ARTIFACT_TYPES=void 0;Bm.ARTIFACT_TYPES=["form","view","businessRule","app","command","chart","dashboard","genPage","bpf"]});var iB=v(nB=>{"use strict";Object.defineProperty(nB,"__esModule",{value:!0})});var aB=v(oB=>{"use strict";Object.defineProperty(oB,"__esModule",{value:!0})});var lB=v(sB=>{"use strict";Object.defineProperty(sB,"__esModule",{value:!0})});var cB=v(uB=>{"use strict";Object.defineProperty(uB,"__esModule",{value:!0})});var fB=v(dB=>{"use strict";Object.defineProperty(dB,"__esModule",{value:!0})});var mB=v(pB=>{"use strict";Object.defineProperty(pB,"__esModule",{value:!0})});var gB=v(hB=>{"use strict";Object.defineProperty(hB,"__esModule",{value:!0})});var bB=v(yB=>{"use strict";Object.defineProperty(yB,"__esModule",{value:!0})});var wB=v(vB=>{"use strict";Object.defineProperty(vB,"__esModule",{value:!0})});var EB=v(CB=>{"use strict";Object.defineProperty(CB,"__esModule",{value:!0})});var SB=v(AB=>{"use strict";Object.defineProperty(AB,"__esModule",{value:!0})});var _B=v(NB=>{"use strict";Object.defineProperty(NB,"__esModule",{value:!0})});var DB=v(TB=>{"use strict";Object.defineProperty(TB,"__esModule",{value:!0})});var OB=v(IB=>{"use strict";Object.defineProperty(IB,"__esModule",{value:!0})});var RB=v(PB=>{"use strict";Object.defineProperty(PB,"__esModule",{value:!0})});var kB=v(LB=>{"use strict";Object.defineProperty(LB,"__esModule",{value:!0})});var xB=v($B=>{"use strict";Object.defineProperty($B,"__esModule",{value:!0})});var MB=v(FB=>{"use strict";Object.defineProperty(FB,"__esModule",{value:!0})});var BB=v(UB=>{"use strict";Object.defineProperty(UB,"__esModule",{value:!0})});var VB=v(qB=>{"use strict";Object.defineProperty(qB,"__esModule",{value:!0})});var WB=v(GB=>{"use strict";Object.defineProperty(GB,"__esModule",{value:!0})});var jB=v(zB=>{"use strict";Object.defineProperty(zB,"__esModule",{value:!0})});var KB=v(ce=>{"use strict";var Tue=ce&&ce.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),Ue=ce&&ce.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&Tue(t,e,r)};Object.defineProperty(ce,"__esModule",{value:!0});ce.projectConnectorOperationSchema=ce.projectConnectorOperations=ce.createMakerSdk=void 0;var Due=tB();Object.defineProperty(ce,"createMakerSdk",{enumerable:!0,get:function(){return Due.createMakerSdk}});Ue(rB(),ce);Ue(iB(),ce);Ue(aB(),ce);Ue(lB(),ce);Ue(cB(),ce);Ue(fB(),ce);Ue(mB(),ce);Ue(gB(),ce);Ue(bB(),ce);Ue(wB(),ce);Ue(EB(),ce);Ue(SB(),ce);Ue(_B(),ce);Ue(DB(),ce);Ue(OB(),ce);Ue(nf(),ce);Ue(RB(),ce);Ue(kB(),ce);Ue(xB(),ce);Ue(MB(),ce);Ue(BB(),ce);Ue(VB(),ce);Ue(WB(),ce);Ue(jB(),ce);Ue(Q(),ce);var HB=Wl();Object.defineProperty(ce,"projectConnectorOperations",{enumerable:!0,get:function(){return HB.projectConnectorOperations}});Object.defineProperty(ce,"projectConnectorOperationSchema",{enumerable:!0,get:function(){return HB.projectConnectorOperationSchema}})});var Bw=v(Si=>{"use strict";var Iue=Si&&Si.__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]})),Oue=Si&&Si.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),QB=Si&&Si.__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)&&Iue(t,e,r);return Oue(t,e),t};Object.defineProperty(Si,"__esModule",{value:!0});Si.NodeFileSystemStorage=void 0;var Nt=QB(require("fs")),sr=QB(require("path")),JB=Q(),YB=mh();async function XB(e){let t;try{t=await Nt.promises.lstat(e)}catch{return}if(t.isSymbolicLink()){try{await Nt.promises.unlink(e)}catch{await Nt.promises.rmdir(e)}return}if(!t.isDirectory()){await Nt.promises.unlink(e);return}for(let r of await Nt.promises.readdir(e))await XB(sr.join(e,r));await Nt.promises.rmdir(e)}var Uw=class{constructor(t){this.root=t}getRoot(){return this.root}pathFor(t,r=!0){return this.assertWithinRoot(sr.join(this.root,...t),r)}realPathThroughNearestAncestor(t){let r=t,n=[];for(;!Nt.existsSync(r);){n.unshift(sr.basename(r));let i=sr.dirname(r);if(i===r)return sr.resolve(t);r=i}return sr.resolve(Nt.realpathSync(r),...n)}assertWithinRoot(t,r){let n=sr.resolve(this.root),i=sr.resolve(t);if(i!==n&&!i.startsWith(n+sr.sep))throw new JB.PathTraversalError(t,this.root);let o=this.realPathThroughNearestAncestor(n),a=r?this.realPathThroughNearestAncestor(i):sr.resolve(this.realPathThroughNearestAncestor(sr.dirname(i)),sr.basename(i));if(a!==o&&!a.startsWith(o+sr.sep))throw new JB.PathTraversalError(t,this.root);return i}async readText(t){let r=this.pathFor(t);if(!Nt.existsSync(r))return null;try{return await(0,YB.retryTransientIoAsync)(()=>Nt.promises.readFile(r,"utf8"))}catch(n){if(n.code==="ENOENT")return null;throw n}}async writeTextAtomic(t,r){let n=this.pathFor(t),i=sr.dirname(n);await Nt.promises.mkdir(i,{recursive:!0});let o=sr.join(i,`.${sr.basename(n)}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);try{await Nt.promises.writeFile(o,r,"utf8"),await(0,YB.retryTransientIoAsync)(()=>Nt.promises.rename(o,n))}catch(a){try{Nt.existsSync(o)&&await Nt.promises.unlink(o)}catch{}throw a}}async deleteFile(t){let r=this.pathFor(t);Nt.existsSync(r)&&await Nt.promises.unlink(r)}async deleteByPrefix(t){await XB(this.pathFor(t,!1))}async ensureContainer(t){await Nt.promises.mkdir(this.pathFor(t),{recursive:!0})}async exists(t){return Nt.existsSync(this.pathFor(t))}};Si.NodeFileSystemStorage=Uw});var ZB=v(Wr=>{"use strict";var Pue=Wr&&Wr.__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]})),Rue=Wr&&Wr.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Lue=Wr&&Wr.__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)&&Pue(t,e,r);return Rue(t,e),t};Object.defineProperty(Wr,"__esModule",{value:!0});Wr.loadNodeTypeScript=Wr.createNodeWorkspaceStorage=Wr.NodeFileSystemStorage=void 0;var kue=Bw(),$ue=Bw();Object.defineProperty(Wr,"NodeFileSystemStorage",{enumerable:!0,get:function(){return $ue.NodeFileSystemStorage}});function xue(e){return new kue.NodeFileSystemStorage(e)}Wr.createNodeWorkspaceStorage=xue;async function Fue(){return await Promise.resolve().then(()=>Lue(require("typescript")))}Wr.loadNodeTypeScript=Fue});var ao={};module.exports=zr(ao);so(ao,Ce(KB()),module.exports);so(ao,Ce(ZB()),module.exports);diff --git a/plugins/model-apps/scripts/verify-model-app.js b/plugins/model-apps/scripts/verify-model-app.jsindex bee518659..8b5d7b4e5 100644--- a/plugins/model-apps/scripts/verify-model-app.js+++ b/plugins/model-apps/scripts/verify-model-app.js@@ -622,7 +622,12 @@ async function main() {// error instead of a later throw when dereferencing spec.entities / schemaName.// 'warn' is verify-only. A spec built before the collision gate must still be verifiable; the// endpoint check below names the holder. Every other entry point keeps the error.- const v = validateAppSpec(spec, { profile: 'deploy', relationshipCollisions: 'warn' });+ // `columnValues: 'warn'` is the same arrangement for the two column rules (an AutoNumber column needs a format; `required` is true, false or+ // "recommended"). They keep a BUILD from misreading a column's declaration, and verification creates and updates nothing — it only reads whether+ // each column exists — so the spec of an app an earlier release built from a value they refuse (an AutoNumber column made as plain text, a+ // `required: "true"` made not required) must still reach its deployment. The warning names the column and the fix for the next build. Not the+ // structural profile: that would also skip the checks of pages and forms that verification relies on.+ const v = validateAppSpec(spec, { profile: 'deploy', relationshipCollisions: 'warn', columnValues: 'warn' });if (!v.ok) { emitResult(false, { ok: false, errors: v.errors }); return; }for (const w of v.warnings || []) process.stderr.write(`WARNING: ${w}\n`);const workspaceDir = workspaceArg || path.join(path.dirname(specPath), '.maker-workspace');diff --git a/plugins/model-apps/skills/app-builder/SKILL.md b/plugins/model-apps/skills/app-builder/SKILL.mdindex 22ded1f62..27ff42426 100644--- a/plugins/model-apps/skills/app-builder/SKILL.md+++ b/plugins/model-apps/skills/app-builder/SKILL.md@@ -553,9 +553,10 @@ a lookup column from a retained table or deletes a shared option set. Dashboardsteardown deletes only those the app's solution holds, never another app's namesake — and none when the spechas no real solution to ask (the `Default` a download may leave); it keeps the solution itself while any stepfailed, so a re-run can still tell, keeps the page manifest while the generative-pages step failed, so a-re-run still finds the pages the app authored, and keeps a table while a business rule on it could not be-deleted (the rule's activated copy can never be deleted once its table is gone), so a re-run deletes the rule-first, then the table. **Dry-run by default**; add `--apply+re-run still finds the pages the app authored, and keeps a table — with its icon web resource and a global choice its+columns bind, which the platform refuses to delete while the table exists, and its relationship to itself — while a+business rule on it could not be deleted (the rule's activated copy can never be deleted once its table is gone), so+a re-run deletes the rule first, then the table and what was kept with it. **Dry-run by default**; add `--apply--allow-destructive` to actually delete (`--clear-workspace` also prunes `.maker-workspace/`).**`--allow-destructive` is required for `teardown --apply`** — without it teardown refuses andtouches nothing.@@ -691,7 +692,12 @@ Then:earlier `app-spec.json` gives one key to two pages (or one page two keys) and **nothing was written**: showthe user the message, which names the pages and keys, and either correct the file and pull again or —only when the user says so, because fresh keys can make a copy deployed elsewhere update the wrong- pages — pull again with `--reset-page-keys`, which re-keys exactly those pages.+ pages — pull again with `--reset-page-keys`, which re-keys exactly those pages. If it answers+ `"code": "navigation-language-unknown"`, the environment's base language could not be read, so the+ language of the app's navigation titles is not known, and **nothing was written**: pull again, or pass+ `--language-code <lcid>` (the environment's base language — the flag the build takes; a spec already in+ the folder that pins `languageCode` needs neither). Do not guess it: a spec whose titles were read in the+ wrong language writes them over the right ones on the next build.2. Edit `app-spec.json` (and any page `.tsx`) for the requested change. A page you edit by hand ischecked like a generated one: run `node "${PLUGIN_ROOT}/scripts/check-griffel-styles.js" --file <page.tsx>`on it before you rebuild (the rule and the ten shorthands are in Phase 1.5, step 5) and fix what it@@ -820,7 +826,9 @@ child view id. Each step emits `[n/total]`.`workflows` row through the SDK's generic artifact surface, with no bound member involved.- Supported: the full data model — all column types, **AutoNumber primary**, global choices, statusreasons, alternate keys, **N:N + junction-with-payload**; **`required` reconciled on existing- columns** (an explicit `required` converges on rebuild; an omitted one never demotes);+ columns** (`true`, `false` or `"recommended"` — anything else is refused at validation; an explicit+ `required` converges on rebuild; an omitted one never demotes) and **asked+ of a new table's primary column in its create**, said applied only once the SDK confirms it;**Boolean `defaultValue`**, whole-number **`integerFormat`** (incl. `Duration`), and per-column**write permissions** (`isValidForCreate` / `isValidForUpdate` / `isValidForRead` — this is how youmake a column read-only), all applied on **create and on rebuild**; adaptivediff --git a/plugins/pcf/scripts/vendor/PROVENANCE.json b/plugins/pcf/scripts/vendor/PROVENANCE.jsonindex 3a7c83c48..707ba670b 100644--- a/plugins/pcf/scripts/vendor/PROVENANCE.json+++ b/plugins/pcf/scripts/vendor/PROVENANCE.json@@ -1,13 +1,13 @@{- "commit": "2d6f9c9f556cb20fce36d4764f3b618c6268b711",+ "commit": "ccf2c1a11a829fe261199936493aa12f3e2bd0ed","dirtySdkPackage": 0,- "libBuiltAt": "2026-10-13T23:12:08.257Z",- "newestSrcAt": "2026-10-13T23:06:00.253Z",+ "libBuiltAt": "2026-10-19T15:37:01.994Z",+ "newestSrcAt": "2026-10-18T02:54:15.290Z","libIsStale": false,"nostub": false,"esbuildVersion": "0.28.1","nodeVersion": "v20.20.2",- "builtAt": "2026-10-13T23:12:43.825Z",- "bundleSha256": "8e0316becce9e45f9641a067eba9e653869cde77dc82da080676da5c152cfebf",- "bundleBytes": 1005262+ "builtAt": "2026-10-19T15:38:54.180Z",+ "bundleSha256": "b8497fbc98f732df23b83d4002818612a9f41c1b94bff7bbeefc5cc60e910f36",+ "bundleBytes": 1057824}diff --git a/plugins/pcf/scripts/vendor/cds-maker-sdk.cjs b/plugins/pcf/scripts/vendor/cds-maker-sdk.cjsindex 3a2e676a1..f359733cc 100644--- a/plugins/pcf/scripts/vendor/cds-maker-sdk.cjs+++ b/plugins/pcf/scripts/vendor/cds-maker-sdk.cjs@@ -25,56 +25,56 @@}globalThis.document=globalThis.document||globalThis.window.document;})();-var tU=Object.create;var hc=Object.defineProperty;var rU=Object.getOwnPropertyDescriptor;var nU=Object.getOwnPropertyNames;var iU=Object.getPrototypeOf,oU=Object.prototype.hasOwnProperty;var k=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var v=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},jr=(e,t)=>{for(var r in t)hc(e,r,{get:t[r],enumerable:!0})},mc=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of nU(t))!oU.call(e,i)&&i!==r&&hc(e,i,{get:()=>t[i],enumerable:!(n=rU(t,i))||n.enumerable});return e},Ki=(e,t,r)=>(mc(e,t,"default"),r&&mc(r,t,"default")),we=(e,t,r)=>(r=e!=null?tU(iU(e)):{},mc(t||!e||!e.__esModule?hc(r,"default",{value:e,enumerable:!0}):r,e)),kr=e=>mc(hc({},"__esModule",{value:!0}),e);var Ji=v(T=>{"use strict";Object.defineProperty(T,"__esModule",{value:!0});T.DateTimeBehavior=T.PrecisionSource=T.StringFormatName=T.SourceType=T.ImeMode=T.SolutionEntityTypeCodeExtToComponentTypeCode=T.SolutionComponentTypeCodeToEntityTypeCodeExt=T.SolutionComponentVirtualAttributeSubtype=T.EntityTypeCode=T.SolutionComponentTypeCodeExt=T.RootComponentBehavior=T.SolutionComponentTypeCode=T.EntityKeyIndexStatus=T.ViewStateCode=T.ViewStatusCode=T.RelationshipSecurityTypes=T.CascadeType=T.RelationshipTypeExt=T.RelationshipType=T.AppSubType=T.BusinessProcessType=T.WorkflowCategory=T.WorkflowScope=T.WorkflowTypeCode=T.StatusCodeEnabledDisabled=T.StateCodeEnabledDisabled=T.StatusCode=T.StateCode=T.OptionSetType=T.AttributeTypeCodeNum=T.AttributeFormatName=T.AttributeFormatCode=T.AttributeTypeName=T.AttributeTypeCode=T.PluginSourceType=T.AuthType=T.PluginIsolationMode=T.ComponentState=T.ChartType=T.ChartsType=T.ViewType=T.AttributeType=T.ActivationState=T.FormPresentation=T.FormType=T.TableTypeCode=T.TableTypes=T.ActivityTypeMask=T.PrincipalType=T.OwnershipTypes=void 0;T.QueryType=T.KnownCustomSolutionComponentEntitySetName=T.TeamTypeEnum=T.EnvironmentVariableDefinitionTypeEnum=T.ConnectorTypeEnum=T.RoleInheritance=T.DefaultRoleTemplates=T.DeleteDependencyErrorCode=T.ServiceEndpointConnectionMode=T.ServiceEndpointContract=T.ServiceNamespaceFormat=T.ConnectionRoleCategory=T.ReportTypeCode=T.SdkMessageProcessingMode=T.SupportedDeployment=T.SdkMessageProcessingStage=T.WebResourceTypeCode=T.IntegerFormat=T.DateTimeFormat=void 0;var Gv;(function(e){e.None="None",e.UserOwned="UserOwned",e.TeamOwned="TeamOwned",e.BusinessOwned="BusinessOwned",e.OrganizationOwned="OrganizationOwned",e.BusinessParented="BusinessParented",e.Filtered="Filtered"})(Gv||(T.OwnershipTypes=Gv={}));var Wv;(function(e){e.User="Microsoft.Dynamics.CRM.systemuser",e.Team="Microsoft.Dynamics.CRM.team"})(Wv||(T.PrincipalType=Wv={}));var zv;(function(e){e[e.DoNotDisplayInActivityMenus=0]="DoNotDisplayInActivityMenus",e[e.DisplayInActivityMenus=1]="DisplayInActivityMenus"})(zv||(T.ActivityTypeMask=zv={}));var jv;(function(e){e.Activity="Activity",e.Virtual="Virtual",e.Standard="Standard",e.Elastic="Elastic"})(jv||(T.TableTypes=jv={}));var Hv;(function(e){e.Standard="Standard",e.Virtual="Virtual",e.Elastic="Elastic"})(Hv||(T.TableTypeCode=Hv={}));var Kv;(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"})(Kv||(T.FormType=Kv={}));var Jv;(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(Jv||(T.FormPresentation=Jv={}));var Yv;(function(e){e[e.Inactive=0]="Inactive",e[e.Active=1]="Active"})(Yv||(T.ActivationState=Yv={}));var Qv;(function(e){e[e.String=0]="String",e[e.Number=1]="Number",e[e.Picklist=2]="Picklist"})(Qv||(T.AttributeType=Qv={}));var Xv;(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"})(Xv||(T.ViewType=Xv={}));var Zv;(function(e){e[e.ASPChart=0]="ASPChart",e[e.PowerBI=1]="PowerBI"})(Zv||(T.ChartsType=Zv={}));var ew;(function(e){e[e.DataAndInteractionCentric=0]="DataAndInteractionCentric",e[e.InteractionCentric=1]="InteractionCentric"})(ew||(T.ChartType=ew={}));var tw;(function(e){e[e.Published=0]="Published",e[e.Unpublished=1]="Unpublished",e[e.Deleted=2]="Deleted",e[e.DeletedUnpublished=3]="DeletedUnpublished"})(tw||(T.ComponentState=tw={}));var rw;(function(e){e[e.None=1]="None",e[e.Sandbox=2]="Sandbox",e[e.External=3]="External"})(rw||(T.PluginIsolationMode=rw={}));var nw;(function(e){e[e.BasicAuth=0]="BasicAuth"})(nw||(T.AuthType=nw={}));var iw;(function(e){e[e.Database=0]="Database",e[e.Disk=1]="Disk",e[e.Normal=2]="Normal",e[e.AzureWebApp=3]="AzureWebApp"})(iw||(T.PluginSourceType=iw={}));var ow;(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"})(ow||(T.AttributeTypeCode=ow={}));var aw;(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"})(aw||(T.AttributeTypeName=aw={}));var sw;(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"})(sw||(T.AttributeFormatCode=sw={}));var lw;(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"})(lw||(T.AttributeFormatName=lw={}));var uw;(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"})(uw||(T.AttributeTypeCodeNum=uw={}));var cw;(function(e){e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean"})(cw||(T.OptionSetType=cw={}));var dw;(function(e){e[e.Draft=0]="Draft",e[e.Activated=1]="Activated"})(dw||(T.StateCode=dw={}));var fw;(function(e){e[e.Draft=1]="Draft",e[e.Activated=2]="Activated"})(fw||(T.StatusCode=fw={}));var pw;(function(e){e[e.Enabled=0]="Enabled",e[e.Disabled=1]="Disabled"})(pw||(T.StateCodeEnabledDisabled=pw={}));var mw;(function(e){e[e.Enabled=1]="Enabled",e[e.Disabled=2]="Disabled"})(mw||(T.StatusCodeEnabledDisabled=mw={}));var hw;(function(e){e[e.Definition=1]="Definition",e[e.Activation=2]="Activation",e[e.Template=3]="Template"})(hw||(T.WorkflowTypeCode=hw={}));var gw;(function(e){e[e.User=1]="User",e[e.BusinessUnit=2]="BusinessUnit",e[e.ParentChildBusinessUnit=3]="ParentChildBusinessUnit",e[e.Organization=4]="Organization"})(gw||(T.WorkflowScope=gw={}));var yw;(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"})(yw||(T.WorkflowCategory=yw={}));var bw;(function(e){e[e.None=-1]="None",e[e.BusinessFlow=0]="BusinessFlow",e[e.TaskFlow=1]="TaskFlow"})(bw||(T.BusinessProcessType=bw={}));var vw;(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"})(vw||(T.AppSubType=vw={}));var ww;(function(e){e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(ww||(T.RelationshipType=ww={}));var Cw;(function(e){e.ManyToOneRelationship="ManyToOneRelationship",e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(Cw||(T.RelationshipTypeExt=Cw={}));var Ew;(function(e){e.NoCascade="NoCascade",e.Cascade="Cascade",e.Active="Active",e.UserOwned="UserOwned",e.RemoveLink="RemoveLink",e.Restrict="Restrict"})(Ew||(T.CascadeType=Ew={}));var Aw;(function(e){e.None="None",e.Append="Append",e.ParentChild="ParentChild",e.Pointer="Pointer",e.Inheritance="Inheritance"})(Aw||(T.RelationshipSecurityTypes=Aw={}));var Sw;(function(e){e[e.Active=1]="Active",e[e.Inactive=2]="Inactive"})(Sw||(T.ViewStatusCode=Sw={}));var Nw;(function(e){e[e.Active=0]="Active",e[e.Inactive=1]="Inactive"})(Nw||(T.ViewStateCode=Nw={}));var _w;(function(e){e.Active="Active",e.Failed="Failed",e.InProgress="InProgress",e.Pending="Pending"})(_w||(T.EntityKeyIndexStatus=_w={}));var Tw;(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"})(Tw||(T.SolutionComponentTypeCode=Tw={}));var Dw;(function(e){e[e.IncludeSubcomponents=0]="IncludeSubcomponents",e[e.DoNotIncludeSubcomponents=1]="DoNotIncludeSubcomponents",e[e.IncludeAsShellOnly=2]="IncludeAsShellOnly"})(Dw||(T.RootComponentBehavior=Dw={}));var gc;(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"})(gc||(T.SolutionComponentTypeCodeExt=gc={}));var yc;(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"})(yc||(T.EntityTypeCode=yc={}));var Iw;(function(e){e.MultiSelectPicklist="MultiSelectPicklist",e.File="File",e.Image="Image"})(Iw||(T.SolutionComponentVirtualAttributeSubtype=Iw={}));function aU(e){let t=gc[e];return yc[t]}T.SolutionComponentTypeCodeToEntityTypeCodeExt=aU;function sU(e){let t=yc[e];return gc[t]}T.SolutionEntityTypeCodeExtToComponentTypeCode=sU;var Ow;(function(e){e.Active="Active",e.Auto="Auto",e.Disabled="Disabled",e.Inactive="Inactive"})(Ow||(T.ImeMode=Ow={}));var Pw;(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"})(Pw||(T.SourceType=Pw={}));var Rw;(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"})(Rw||(T.StringFormatName=Rw={}));var Lw;(function(e){e[e.PrecisionProperty=0]="PrecisionProperty",e[e.Organization=1]="Organization",e[e.TransactionCurrency=2]="TransactionCurrency"})(Lw||(T.PrecisionSource=Lw={}));var kw;(function(e){e.UserLocal="UserLocal",e.DateOnly="DateOnly",e.TimeZoneIndependent="TimeZoneIndependent"})(kw||(T.DateTimeBehavior=kw={}));var xw;(function(e){e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(xw||(T.DateTimeFormat=xw={}));var $w;(function(e){e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})($w||(T.IntegerFormat=$w={}));var Fw;(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"})(Fw||(T.WebResourceTypeCode=Fw={}));var Mw;(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"})(Mw||(T.SdkMessageProcessingStage=Mw={}));var Uw;(function(e){e[e.ServerOnly=0]="ServerOnly",e[e.OutlookClientOnly=1]="OutlookClientOnly",e[e.Both=2]="Both"})(Uw||(T.SupportedDeployment=Uw={}));var Bw;(function(e){e[e.Synchronous=0]="Synchronous",e[e.Asynchronous=1]="Asynchronous"})(Bw||(T.SdkMessageProcessingMode=Bw={}));var qw;(function(e){e[e.ReportingServicesReport=1]="ReportingServicesReport",e[e.OtherReport=2]="OtherReport",e[e.LinkedReport=3]="LinkedReport"})(qw||(T.ReportTypeCode=qw={}));var Vw;(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"})(Vw||(T.ConnectionRoleCategory=Vw={}));var Gw;(function(e){e[e.Name=1]="Name",e[e.Address=2]="Address"})(Gw||(T.ServiceNamespaceFormat=Gw={}));var Ww;(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"})(Ww||(T.ServiceEndpointContract=Ww={}));var zw;(function(e){e[e.Normal=1]="Normal",e[e.Federated=2]="Federated"})(zw||(T.ServiceEndpointConnectionMode=zw={}));var jw;(function(e){e.CannotDeleteInUseComponent="0x8004f01f",e.CannotDeleteInUseAttribute="0x80048418",e.CannotDeleteInUseOptionSet="0x80048417",e.CannotDeleteInUseEntity="0x80048420",e.CannotUninstallWithDependencies="0x8004F01D"})(jw||(T.DeleteDependencyErrorCode=jw={}));var Hw;(function(e){e.SystemAdministrator="627090FF-40A3-4053-8790-584EDC5BE201",e.SystemCustomizer="119F245C-3CC8-4B62-B31C-D1A046CED15D"})(Hw||(T.DefaultRoleTemplates=Hw={}));var Kw;(function(e){e[e.DefaultTeamPrivilege=0]="DefaultTeamPrivilege",e[e.DirectUserAndTeamPrivilege=1]="DirectUserAndTeamPrivilege"})(Kw||(T.RoleInheritance=Kw={}));var Jw;(function(e){e[e.NotSpecified=0]="NotSpecified",e[e.CustomConnector=1]="CustomConnector"})(Jw||(T.ConnectorTypeEnum=Jw={}));var Yw;(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"})(Yw||(T.EnvironmentVariableDefinitionTypeEnum=Yw={}));var Qw;(function(e){e[e.Owner=0]="Owner",e[e.Access=1]="Access",e[e.AADSecurityGroup=2]="AADSecurityGroup",e[e.AADOfficeGroup=3]="AADOfficeGroup"})(Qw||(T.TeamTypeEnum=Qw={}));var Xw;(function(e){e.Bots="bots"})(Xw||(T.KnownCustomSolutionComponentEntitySetName=Xw={}));var Zw;(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"})(Zw||(T.QueryType=Zw={}))});var Q=v(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.IncompatibleWorkspaceError=X.PathTraversalError=X.AmbiguousArtifactError=X.JsonPointerError=X.NotImplementedError=X.WorkspaceOrgMismatchError=X.WorkspaceNotInitializedError=X.attachCause=X.ConnectionError=X.VersionConflictError=X.LocalEditsWouldBeLostError=X.StaleArtifactError=X.InvalidArgumentError=X.ValidationError=X.PathNotFoundError=X.ArtifactNotFoundError=X.readCleanupWarnings=X.withCleanupWarnings=X.readPartialEnrichment=X.withPartialEnrichment=X.readPartialTokens=X.withPartialTokens=X.SdkError=void 0;var gt=class extends Error{constructor(t,r){super(r),this.code=t,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}};X.SdkError=gt;var eC=Symbol.for("cds-maker-sdk.partialWriteTokens");function lU(e,t){return typeof e=="object"&&e!==null&&(e[eC]=t),e}X.withPartialTokens=lU;function uU(e){return hm(e,eC)}X.readPartialTokens=uU;function hm(e,t){let r=e;for(let n=0;r&&typeof r=="object"&&n<8;n++){let i=r[t];if(i&&typeof i=="object")return i;r=r.cause}}var tC=Symbol.for("cds-maker-sdk.partialDefaultViewEnrichment");function cU(e,t){return typeof e=="object"&&e!==null&&(e[tC]=t),e}X.withPartialEnrichment=cU;function dU(e){return hm(e,tC)}X.readPartialEnrichment=dU;var Zp=Symbol.for("cds-maker-sdk.cleanupWarnings");function fU(e,t){if(typeof e=="object"&&e!==null&&t.length>0){let r=e,n=r[Zp];r[Zp]=[...Array.isArray(n)?n:[],...t]}return e}X.withCleanupWarnings=fU;function pU(e){let t=hm(e,Zp);return t?[...t]:void 0}X.readCleanupWarnings=pU;var em=class extends gt{constructor(t,r){super("ARTIFACT_NOT_FOUND",`Artifact ${t}/${r} not found in workspace`),this.type=t,this.id=r}};X.ArtifactNotFoundError=em;var tm=class extends gt{constructor(t,r,n){super("PATH_NOT_FOUND",`Path ${n} not found in ${t}/${r}`),this.type=t,this.id=r,this.pointer=n}};X.PathNotFoundError=tm;var rm=class extends gt{constructor(t,r,n,i){var o,a,s,l;let u=Array.isArray(n)?n:[{pointer:n,rule:i??"invalid",message:i??"invalid"}];super("VALIDATION_ERROR",`Validation failed for ${t}/${r}:+var eq=Object.create;var qc=Object.defineProperty;var tq=Object.getOwnPropertyDescriptor;var rq=Object.getOwnPropertyNames;var nq=Object.getPrototypeOf,iq=Object.prototype.hasOwnProperty;var k=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var v=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},nn=(e,t)=>{for(var r in t)qc(e,r,{get:t[r],enumerable:!0})},Bc=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of rq(t))!iq.call(e,i)&&i!==r&&qc(e,i,{get:()=>t[i],enumerable:!(n=tq(t,i))||n.enumerable});return e},so=(e,t,r)=>(Bc(e,t,"default"),r&&Bc(r,t,"default")),Ce=(e,t,r)=>(r=e!=null?eq(nq(e)):{},Bc(t||!e||!e.__esModule?qc(r,"default",{value:e,enumerable:!0}):r,e)),zr=e=>Bc(qc({},"__esModule",{value:!0}),e);var lo=v(T=>{"use strict";Object.defineProperty(T,"__esModule",{value:!0});T.DateTimeBehavior=T.PrecisionSource=T.StringFormatName=T.SourceType=T.ImeMode=T.SolutionEntityTypeCodeExtToComponentTypeCode=T.SolutionComponentTypeCodeToEntityTypeCodeExt=T.SolutionComponentVirtualAttributeSubtype=T.EntityTypeCode=T.SolutionComponentTypeCodeExt=T.RootComponentBehavior=T.SolutionComponentTypeCode=T.EntityKeyIndexStatus=T.ViewStateCode=T.ViewStatusCode=T.RelationshipSecurityTypes=T.CascadeType=T.RelationshipTypeExt=T.RelationshipType=T.AppSubType=T.BusinessProcessType=T.WorkflowCategory=T.WorkflowScope=T.WorkflowTypeCode=T.StatusCodeEnabledDisabled=T.StateCodeEnabledDisabled=T.StatusCode=T.StateCode=T.OptionSetType=T.AttributeTypeCodeNum=T.AttributeFormatName=T.AttributeFormatCode=T.AttributeTypeName=T.AttributeTypeCode=T.PluginSourceType=T.AuthType=T.PluginIsolationMode=T.ComponentState=T.ChartType=T.ChartsType=T.ViewType=T.AttributeType=T.ActivationState=T.FormPresentation=T.FormType=T.TableTypeCode=T.TableTypes=T.ActivityTypeMask=T.PrincipalType=T.OwnershipTypes=void 0;T.QueryType=T.KnownCustomSolutionComponentEntitySetName=T.TeamTypeEnum=T.EnvironmentVariableDefinitionTypeEnum=T.ConnectorTypeEnum=T.RoleInheritance=T.DefaultRoleTemplates=T.DeleteDependencyErrorCode=T.ServiceEndpointConnectionMode=T.ServiceEndpointContract=T.ServiceNamespaceFormat=T.ConnectionRoleCategory=T.ReportTypeCode=T.SdkMessageProcessingMode=T.SupportedDeployment=T.SdkMessageProcessingStage=T.WebResourceTypeCode=T.IntegerFormat=T.DateTimeFormat=void 0;var qw;(function(e){e.None="None",e.UserOwned="UserOwned",e.TeamOwned="TeamOwned",e.BusinessOwned="BusinessOwned",e.OrganizationOwned="OrganizationOwned",e.BusinessParented="BusinessParented",e.Filtered="Filtered"})(qw||(T.OwnershipTypes=qw={}));var Vw;(function(e){e.User="Microsoft.Dynamics.CRM.systemuser",e.Team="Microsoft.Dynamics.CRM.team"})(Vw||(T.PrincipalType=Vw={}));var Gw;(function(e){e[e.DoNotDisplayInActivityMenus=0]="DoNotDisplayInActivityMenus",e[e.DisplayInActivityMenus=1]="DisplayInActivityMenus"})(Gw||(T.ActivityTypeMask=Gw={}));var Ww;(function(e){e.Activity="Activity",e.Virtual="Virtual",e.Standard="Standard",e.Elastic="Elastic"})(Ww||(T.TableTypes=Ww={}));var zw;(function(e){e.Standard="Standard",e.Virtual="Virtual",e.Elastic="Elastic"})(zw||(T.TableTypeCode=zw={}));var jw;(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"})(jw||(T.FormType=jw={}));var Hw;(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(Hw||(T.FormPresentation=Hw={}));var Kw;(function(e){e[e.Inactive=0]="Inactive",e[e.Active=1]="Active"})(Kw||(T.ActivationState=Kw={}));var Jw;(function(e){e[e.String=0]="String",e[e.Number=1]="Number",e[e.Picklist=2]="Picklist"})(Jw||(T.AttributeType=Jw={}));var Yw;(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"})(Yw||(T.ViewType=Yw={}));var Qw;(function(e){e[e.ASPChart=0]="ASPChart",e[e.PowerBI=1]="PowerBI"})(Qw||(T.ChartsType=Qw={}));var Xw;(function(e){e[e.DataAndInteractionCentric=0]="DataAndInteractionCentric",e[e.InteractionCentric=1]="InteractionCentric"})(Xw||(T.ChartType=Xw={}));var Zw;(function(e){e[e.Published=0]="Published",e[e.Unpublished=1]="Unpublished",e[e.Deleted=2]="Deleted",e[e.DeletedUnpublished=3]="DeletedUnpublished"})(Zw||(T.ComponentState=Zw={}));var eC;(function(e){e[e.None=1]="None",e[e.Sandbox=2]="Sandbox",e[e.External=3]="External"})(eC||(T.PluginIsolationMode=eC={}));var tC;(function(e){e[e.BasicAuth=0]="BasicAuth"})(tC||(T.AuthType=tC={}));var rC;(function(e){e[e.Database=0]="Database",e[e.Disk=1]="Disk",e[e.Normal=2]="Normal",e[e.AzureWebApp=3]="AzureWebApp"})(rC||(T.PluginSourceType=rC={}));var nC;(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"})(nC||(T.AttributeTypeCode=nC={}));var iC;(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"})(iC||(T.AttributeTypeName=iC={}));var oC;(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"})(oC||(T.AttributeFormatCode=oC={}));var aC;(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"})(aC||(T.AttributeFormatName=aC={}));var sC;(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"})(sC||(T.AttributeTypeCodeNum=sC={}));var lC;(function(e){e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean"})(lC||(T.OptionSetType=lC={}));var uC;(function(e){e[e.Draft=0]="Draft",e[e.Activated=1]="Activated"})(uC||(T.StateCode=uC={}));var cC;(function(e){e[e.Draft=1]="Draft",e[e.Activated=2]="Activated"})(cC||(T.StatusCode=cC={}));var dC;(function(e){e[e.Enabled=0]="Enabled",e[e.Disabled=1]="Disabled"})(dC||(T.StateCodeEnabledDisabled=dC={}));var fC;(function(e){e[e.Enabled=1]="Enabled",e[e.Disabled=2]="Disabled"})(fC||(T.StatusCodeEnabledDisabled=fC={}));var pC;(function(e){e[e.Definition=1]="Definition",e[e.Activation=2]="Activation",e[e.Template=3]="Template"})(pC||(T.WorkflowTypeCode=pC={}));var mC;(function(e){e[e.User=1]="User",e[e.BusinessUnit=2]="BusinessUnit",e[e.ParentChildBusinessUnit=3]="ParentChildBusinessUnit",e[e.Organization=4]="Organization"})(mC||(T.WorkflowScope=mC={}));var hC;(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"})(hC||(T.WorkflowCategory=hC={}));var gC;(function(e){e[e.None=-1]="None",e[e.BusinessFlow=0]="BusinessFlow",e[e.TaskFlow=1]="TaskFlow"})(gC||(T.BusinessProcessType=gC={}));var yC;(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"})(yC||(T.AppSubType=yC={}));var bC;(function(e){e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(bC||(T.RelationshipType=bC={}));var vC;(function(e){e.ManyToOneRelationship="ManyToOneRelationship",e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(vC||(T.RelationshipTypeExt=vC={}));var wC;(function(e){e.NoCascade="NoCascade",e.Cascade="Cascade",e.Active="Active",e.UserOwned="UserOwned",e.RemoveLink="RemoveLink",e.Restrict="Restrict"})(wC||(T.CascadeType=wC={}));var CC;(function(e){e.None="None",e.Append="Append",e.ParentChild="ParentChild",e.Pointer="Pointer",e.Inheritance="Inheritance"})(CC||(T.RelationshipSecurityTypes=CC={}));var EC;(function(e){e[e.Active=1]="Active",e[e.Inactive=2]="Inactive"})(EC||(T.ViewStatusCode=EC={}));var AC;(function(e){e[e.Active=0]="Active",e[e.Inactive=1]="Inactive"})(AC||(T.ViewStateCode=AC={}));var SC;(function(e){e.Active="Active",e.Failed="Failed",e.InProgress="InProgress",e.Pending="Pending"})(SC||(T.EntityKeyIndexStatus=SC={}));var NC;(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"})(NC||(T.SolutionComponentTypeCode=NC={}));var _C;(function(e){e[e.IncludeSubcomponents=0]="IncludeSubcomponents",e[e.DoNotIncludeSubcomponents=1]="DoNotIncludeSubcomponents",e[e.IncludeAsShellOnly=2]="IncludeAsShellOnly"})(_C||(T.RootComponentBehavior=_C={}));var Vc;(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"})(Vc||(T.SolutionComponentTypeCodeExt=Vc={}));var Gc;(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"})(Gc||(T.EntityTypeCode=Gc={}));var TC;(function(e){e.MultiSelectPicklist="MultiSelectPicklist",e.File="File",e.Image="Image"})(TC||(T.SolutionComponentVirtualAttributeSubtype=TC={}));function oq(e){let t=Vc[e];return Gc[t]}T.SolutionComponentTypeCodeToEntityTypeCodeExt=oq;function aq(e){let t=Gc[e];return Vc[t]}T.SolutionEntityTypeCodeExtToComponentTypeCode=aq;var DC;(function(e){e.Active="Active",e.Auto="Auto",e.Disabled="Disabled",e.Inactive="Inactive"})(DC||(T.ImeMode=DC={}));var IC;(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"})(IC||(T.SourceType=IC={}));var OC;(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"})(OC||(T.StringFormatName=OC={}));var PC;(function(e){e[e.PrecisionProperty=0]="PrecisionProperty",e[e.Organization=1]="Organization",e[e.TransactionCurrency=2]="TransactionCurrency"})(PC||(T.PrecisionSource=PC={}));var RC;(function(e){e.UserLocal="UserLocal",e.DateOnly="DateOnly",e.TimeZoneIndependent="TimeZoneIndependent"})(RC||(T.DateTimeBehavior=RC={}));var LC;(function(e){e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(LC||(T.DateTimeFormat=LC={}));var kC;(function(e){e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(kC||(T.IntegerFormat=kC={}));var $C;(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"})($C||(T.WebResourceTypeCode=$C={}));var xC;(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"})(xC||(T.SdkMessageProcessingStage=xC={}));var FC;(function(e){e[e.ServerOnly=0]="ServerOnly",e[e.OutlookClientOnly=1]="OutlookClientOnly",e[e.Both=2]="Both"})(FC||(T.SupportedDeployment=FC={}));var MC;(function(e){e[e.Synchronous=0]="Synchronous",e[e.Asynchronous=1]="Asynchronous"})(MC||(T.SdkMessageProcessingMode=MC={}));var UC;(function(e){e[e.ReportingServicesReport=1]="ReportingServicesReport",e[e.OtherReport=2]="OtherReport",e[e.LinkedReport=3]="LinkedReport"})(UC||(T.ReportTypeCode=UC={}));var BC;(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"})(BC||(T.ConnectionRoleCategory=BC={}));var qC;(function(e){e[e.Name=1]="Name",e[e.Address=2]="Address"})(qC||(T.ServiceNamespaceFormat=qC={}));var VC;(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"})(VC||(T.ServiceEndpointContract=VC={}));var GC;(function(e){e[e.Normal=1]="Normal",e[e.Federated=2]="Federated"})(GC||(T.ServiceEndpointConnectionMode=GC={}));var WC;(function(e){e.CannotDeleteInUseComponent="0x8004f01f",e.CannotDeleteInUseAttribute="0x80048418",e.CannotDeleteInUseOptionSet="0x80048417",e.CannotDeleteInUseEntity="0x80048420",e.CannotUninstallWithDependencies="0x8004F01D"})(WC||(T.DeleteDependencyErrorCode=WC={}));var zC;(function(e){e.SystemAdministrator="627090FF-40A3-4053-8790-584EDC5BE201",e.SystemCustomizer="119F245C-3CC8-4B62-B31C-D1A046CED15D"})(zC||(T.DefaultRoleTemplates=zC={}));var jC;(function(e){e[e.DefaultTeamPrivilege=0]="DefaultTeamPrivilege",e[e.DirectUserAndTeamPrivilege=1]="DirectUserAndTeamPrivilege"})(jC||(T.RoleInheritance=jC={}));var HC;(function(e){e[e.NotSpecified=0]="NotSpecified",e[e.CustomConnector=1]="CustomConnector"})(HC||(T.ConnectorTypeEnum=HC={}));var KC;(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"})(KC||(T.EnvironmentVariableDefinitionTypeEnum=KC={}));var JC;(function(e){e[e.Owner=0]="Owner",e[e.Access=1]="Access",e[e.AADSecurityGroup=2]="AADSecurityGroup",e[e.AADOfficeGroup=3]="AADOfficeGroup"})(JC||(T.TeamTypeEnum=JC={}));var YC;(function(e){e.Bots="bots"})(YC||(T.KnownCustomSolutionComponentEntitySetName=YC={}));var QC;(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"})(QC||(T.QueryType=QC={}))});var Q=v(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.IncompatibleWorkspaceError=X.PathTraversalError=X.AmbiguousArtifactError=X.JsonPointerError=X.NotImplementedError=X.WorkspaceOrgMismatchError=X.WorkspaceNotInitializedError=X.attachCause=X.ConnectionError=X.VersionConflictError=X.LocalEditsWouldBeLostError=X.StaleArtifactError=X.InvalidArgumentError=X.ValidationError=X.PathNotFoundError=X.ArtifactNotFoundError=X.readPcfRegistrationProgress=X.withPcfRegistrationProgress=X.readCleanupWarnings=X.withCleanupWarnings=X.readPartialEnrichment=X.withPartialEnrichment=X.readPartialTokens=X.withPartialTokens=X.SdkError=void 0;var _t=class extends Error{constructor(t,r){super(r),this.code=t,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}};X.SdkError=_t;var XC=Symbol.for("cds-maker-sdk.partialWriteTokens");function sq(e,t){return typeof e=="object"&&e!==null&&(e[XC]=t),e}X.withPartialTokens=sq;function lq(e){return Wc(e,XC)}X.readPartialTokens=lq;function Wc(e,t){let r=e;for(let n=0;r&&typeof r=="object"&&n<8;n++){let i=r[t];if(i&&typeof i=="object")return i;r=r.cause}}var ZC=Symbol.for("cds-maker-sdk.partialDefaultViewEnrichment");function uq(e,t){return typeof e=="object"&&e!==null&&(e[ZC]=t),e}X.withPartialEnrichment=uq;function cq(e){return Wc(e,ZC)}X.readPartialEnrichment=cq;var qm=Symbol.for("cds-maker-sdk.cleanupWarnings");function dq(e,t){if(typeof e=="object"&&e!==null&&t.length>0){let r=e,n=r[qm];r[qm]=[...Array.isArray(n)?n:[],...t]}return e}X.withCleanupWarnings=dq;function fq(e){let t=Wc(e,qm);return t?[...t]:void 0}X.readCleanupWarnings=fq;var eE=Symbol.for("cds-maker-sdk.pcfRegistrationProgress");function tE(e){return{...e,written:[...e.written],unconfirmed:[...e.unconfirmed],published:[...e.published],publishedUnknown:[...e.publishedUnknown],temporaries:[...e.temporaries]}}function pq(e,t){return typeof e=="object"&&e!==null&&(e[eE]=tE(t)),e}X.withPcfRegistrationProgress=pq;function mq(e){let t=Wc(e,eE);return t?tE(t):void 0}X.readPcfRegistrationProgress=mq;var Vm=class extends _t{constructor(t,r){super("ARTIFACT_NOT_FOUND",`Artifact ${t}/${r} not found in workspace`),this.type=t,this.id=r}};X.ArtifactNotFoundError=Vm;var Gm=class extends _t{constructor(t,r,n){super("PATH_NOT_FOUND",`Path ${n} not found in ${t}/${r}`),this.type=t,this.id=r,this.pointer=n}};X.PathNotFoundError=Gm;var Wm=class extends _t{constructor(t,r,n,i){var o,a,s,l;let u=Array.isArray(n)?n:[{pointer:n,rule:i??"invalid",message:i??"invalid"}];super("VALIDATION_ERROR",`Validation failed for ${t}/${r}:`+u.map(c=>` \u2022 ${c.pointer}: ${c.message} [${c.rule}]`).join(`-`)),this.type=t,this.id=r,this.issues=u,this.pointer=(a=(o=u[0])===null||o===void 0?void 0:o.pointer)!==null&&a!==void 0?a:"",this.rule=(l=(s=u[0])===null||s===void 0?void 0:s.rule)!==null&&l!==void 0?l:"invalid"}};X.ValidationError=rm;var nm=class extends gt{constructor(t){super("INVALID_ARGUMENT",t)}};X.InvalidArgumentError=nm;var im=class extends gt{constructor(t,r,n,i="revalidated"){super("STALE_ARTIFACT",i==="pushed"?`Cannot apply the edit at ${n} to ${t}/${r}: a push made after this pointer's copy was read replaced the local copy with the record the server holds, which differs from that copy (ids and defaults the SDK filled in at save, a rewrite the platform made on save, or another writer's save), so the pointer may now identify a different node. Read the whole artifact (getArtifact), re-derive the pointer, and retry.`:`Cannot apply the edit at ${n} to ${t}/${r}: the cached copy was stale and the server copy has since changed, so any pointer derived from the old copy may now identify a different node. The local copy has been refreshed \u2014 re-read the artifact, re-derive the pointer, and retry.`),this.type=t,this.id=r,this.pointer=n,this.reason=i}};X.StaleArtifactError=im;var om=class extends gt{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}};X.LocalEditsWouldBeLostError=om;var am=class extends gt{constructor(t,r,n,i,o){super("VERSION_CONFLICT",`Version conflict for ${t}/${r}: local=${n??"(none)"}, server=${i??"(none)"}. Re-fetch and reapply changes.${o?` ${o}`:""}`),this.type=t,this.id=r,this.localEtag=n,this.serverEtag=i,this.detail=o}};X.VersionConflictError=am;var sm=class extends gt{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,Object.defineProperty(this,"cause",{value:i,enumerable:!1,writable:!1,configurable:!0})}};X.ConnectionError=sm;function mU(e,t){return typeof e=="object"&&e!==null&&Object.defineProperty(e,"cause",{value:t,enumerable:!1,writable:!0,configurable:!0}),e}X.attachCause=mU;var lm=class extends gt{constructor(t){super("WORKSPACE_NOT_INITIALIZED",`Workspace not initialized at ${t}. Call initWorkspace() first.`),this.workspacePath=t}};X.WorkspaceNotInitializedError=lm;var um=class extends gt{constructor(t,r){super("WORKSPACE_ORG_MISMATCH",`This workspace belongs to ${t?`'${t}'`:"no recorded org"}, but this SDK targets '${r}'. Its local copies, baselines and cached metadata are that org's, so nothing was read or written. Use one workspace per org, or call cleanWorkspace() to discard this workspace's contents and bind it to '${r}'.`),this.workspaceInstanceUrl=t,this.instanceUrl=r}};X.WorkspaceOrgMismatchError=um;var cm=class extends gt{constructor(t,r){super("NOT_IMPLEMENTED",`Operation '${t}' is not implemented yet${r?`: ${r}`:""}.`),this.operation=t}};X.NotImplementedError=cm;var dm=class extends gt{constructor(t,r){super("INVALID_JSON_POINTER",`Invalid JSON Pointer '${t}': ${r}`),this.pointer=t}};X.JsonPointerError=dm;var fm=class extends gt{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}};X.AmbiguousArtifactError=fm;var pm=class extends gt{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}};X.PathTraversalError=pm;var mm=class extends gt{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}};X.IncompatibleWorkspaceError=mm});var ue=v(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.odataQuery=Xe.normalizeGuid=Xe.createSafeXmlElement=Xe.assertNoControlChars=Xe.assertODataName=Xe.assertXmlName=Xe.xmlText=Xe.odataPathLiteral=Xe.odataLiteral=void 0;var bc=Q();function rC(e){return String(e??"").replace(/'/g,"''")}Xe.odataLiteral=rC;function hU(e){return encodeURIComponent(rC(e))}Xe.odataPathLiteral=hU;function gU(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}Xe.xmlText=gU;function nC(e,t){let r=String(e??""),n=/^[A-Za-z_][0-9A-Za-z_.-]*$/,i=r.split(":");if(!(i.length<=2&&i.every(a=>n.test(a))&&!/^xmlns/i.test(r)))throw new bc.InvalidArgumentError(`${t} must be a valid XML element name (got '${e}')`);return e}Xe.assertXmlName=nC;function yU(e,t){let r=String(e??"");if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new bc.InvalidArgumentError(`${t} must be a valid OData identifier (letters, digits, underscore): got '${e}'`);return e}Xe.assertODataName=yU;function bU(e,t){if(/[\u0000-\u001F\u007F]/.test(String(e??"")))throw new bc.InvalidArgumentError(`${t} must not contain control characters (including CR/LF): they would inject additional lines into the request`);return e}Xe.assertNoControlChars=bU;function vU(e,t,r){return e.createElement(nC(t,r))}Xe.createSafeXmlElement=vU;var wU=/^[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 CU(e,t){let r=String(e??""),n=r.length===38&&r.startsWith("{")&&r.endsWith("}")?r.slice(1,-1):r;if(!wU.test(n))throw new bc.InvalidArgumentError(`${t} must be a valid GUID (got '${e}')`);return n.toLowerCase()}Xe.normalizeGuid=CU;function EU(e){let t=[];for(let[r,n]of e)n!=null&&n!==""&&t.push(`${r}=${encodeURIComponent(String(n))}`);return t.length>0?`?${t.join("&")}`:""}Xe.odataQuery=EU});var ye=v(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.nowIso=j.isAlreadyDeleted=j.deleteRecord=j.resendAppSearchIndexRace=j.resendDeadlockVictim=j.resendWhile=j.isAppSearchIndexRace=j.namesAppSearchIndexRace=j.isTransactionNotStarted=j.TRANSACTION_NOT_STARTED_CODE=j.LOCK_BACKOFF_MS=j.isConcurrencyLockRefusal=j.CONCURRENCY_LOCK_CODE=j.AMBIGUOUS_WRITE_STATUSES=j.DEADLOCK_BACKOFF_MS=j.isSqlDeadlockVictim=j.ensureSuccess=j.resolveCreatedId=j.requireCreatedId=j.withClientMintedId=j.readCreatedId=j.readRowEtag=j.readEtag=j.requireEtag=j.isVersionToken=j.echoWrite=j.UPDATE_NO_ETAG_CODE=j.VERSION_CONFLICT_CODE=void 0;var La=Q(),ka=ue();j.VERSION_CONFLICT_CODE="VERSION_CONFLICT";j.UPDATE_NO_ETAG_CODE="ARTIFACT_UPDATE_NO_ETAG";function AU(e,t){return{query:`?$select=${encodeURIComponent(e)}`,options:{headers:{...t??{},Prefer:"return=representation"}}}}j.echoWrite=AU;function iC(e){return typeof e=="string"&&e.trim()!==""&&e.trim()!=="*"}j.isVersionToken=iC;function SU(e,t,r){if(!iC(e))throw new La.SdkError(j.UPDATE_NO_ETAG_CODE,`Refusing to push ${t} '${r}': ${e?`the concurrency token held for it ('${e}') is not a version`:"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}j.requireEtag=SU;function oC(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}j.readEtag=oC;async function NU(e,t,r,n){let i=`/${t}(${n})${(0,ka.odataQuery)([["$select",r]])}`;return oC(ym(await e.get(i),e.apiUrl(i)))}j.readRowEtag=NU;function gm(e,t){var r;let n=e.body;if(n&&typeof n[t]=="string")return(0,ka.normalizeGuid)(n[t],t);let i=(r=e.headers)!==null&&r!==void 0?r:{};for(let o of Object.keys(i))if(o.toLowerCase()==="odata-entityid"){let a=/\(([0-9a-fA-F-]{36})\)/.exec(i[o]);if(a)return(0,ka.normalizeGuid)(a[1],t)}return null}j.readCreatedId=gm;function _U(e,t,r){return r?{...e,[t]:(0,ka.normalizeGuid)(r,t)}:e}j.withClientMintedId=_U;function TU(e,t,r){let n=gm(e,t);if(!n)throw new La.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`);return n}j.requireCreatedId=TU;function DU(e,t,r,n){let i=gm(e,t);if(i)return i;if(n)return(0,ka.normalizeGuid)(n,t);throw new La.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`)}j.resolveCreatedId=DU;function ym(e,t){if(e.status===412)throw new La.SdkError(j.VERSION_CONFLICT_CODE,`Version conflict (412) from ${t}`);if(e.status<200||e.status>=300)throw new La.ConnectionError(t,e.status,kU(e.body),e.body);return e}j.ensureSuccess=ym;function aC(e){if(e.status!==500||e.body===void 0||e.body===null)return!1;let t=typeof e.body=="string"?e.body:JSON.stringify(e.body);return/\bSql Number:\s*1205\b/i.test(t)}j.isSqlDeadlockVictim=aC;j.DEADLOCK_BACKOFF_MS=[1e3,2e3,4e3];j.AMBIGUOUS_WRITE_STATUSES=new Set([408,502,503,504]);j.CONCURRENCY_LOCK_CODE="0x80071151";function IU(e){var t,r;if(e.status!==429)return!1;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return typeof n=="string"&&n.toLowerCase()===j.CONCURRENCY_LOCK_CODE}j.isConcurrencyLockRefusal=IU;j.LOCK_BACKOFF_MS=[2e3,3e3,...Array.from({length:35},()=>5e3)];j.TRANSACTION_NOT_STARTED_CODE="0x80040251";function OU(e){var t,r;if(e.status!==500)return!1;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return typeof n=="string"&&n.toLowerCase()===j.TRANSACTION_NOT_STARTED_CODE}j.isTransactionNotStarted=OU;var PU=/(?:^|[^a-z0-9_])AppModule_DVTableSearch_M365AppModuleId(?![a-z0-9_])/i;function sC(e){return PU.test(e)&&/\bSql Number:\s*547\b/i.test(e)}j.namesAppSearchIndexRace=sC;function lC(e){return e.status!==400||e.body===void 0||e.body===null?!1:sC(typeof e.body=="string"?e.body:JSON.stringify(e.body))}j.isAppSearchIndexRace=lC;async function bm(e,t,r=j.DEADLOCK_BACKOFF_MS){for(let n=0;;n+=1){let i=await t();if(n>=r.length||!e(i))return i;await new Promise(o=>setTimeout(o,r[n]))}}j.resendWhile=bm;function RU(e){return bm(aC,e,j.DEADLOCK_BACKOFF_MS)}j.resendDeadlockVictim=RU;function LU(e){return bm(lC,e,j.DEADLOCK_BACKOFF_MS)}j.resendAppSearchIndexRace=LU;function kU(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 xU(e,t,r,n){let i=(0,ka.normalizeGuid)(r,"id"),o=`/${t}(${i})`;ym(await e.delete(o,n?{headers:{"If-Match":n}}:void 0),e.apiUrl(o))}j.deleteRecord=xU;function $U(e){return e instanceof La.ConnectionError&&e.statusCode===404}j.isAlreadyDeleted=$U;function FU(){return new Date().toISOString()}j.nowIso=FU});var Xt=v(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.describeMalformedValue=xa.collectPages=void 0;var uC=ye(),vm=Q();async function MU(e,t,r,n,i){let o=[],a=new Set,s=e.apiUrl(t),l=(0,uC.ensureSuccess)(await e.get(t,i),s);for(n?.(l);;){let u=l.body,c=u?.value;if(!Array.isArray(c))throw new vm.ConnectionError(s,l.status,`${r}: paginated read returned a malformed page \u2014 expected an OData 'value' array but got ${wm(c)}; refusing to return partial results.`);for(let f of c)o.push(f);let d=u?.["@odata.nextLink"];if(d==null)break;if(typeof d!="string"||d.length===0)throw new vm.ConnectionError(s,l.status,`${r}: paginated read returned a malformed @odata.nextLink (${wm(d)}); cannot follow it, and refusing to return partial results.`);if(a.has(d))throw new vm.InvalidArgumentError(`${r}: aborting pagination \u2014 the server returned a repeated @odata.nextLink ('${d}'), which would loop indefinitely.`);a.add(d),s=d,l=(0,uC.ensureSuccess)(await e.getAbsolute(d,i),d)}return o}xa.collectPages=MU;function wm(e){return e===null?"null":e===void 0?"undefined (missing)":`a ${typeof e}`}xa.describeMalformedValue=wm});var Cm=v(ko=>{"use strict";Object.defineProperty(ko,"__esModule",{value:!0});ko.assertWorkflowKind=ko.WORKFLOW_KIND_MISMATCH_CODE=void 0;var Lo=Ji(),UU=Q(),cC=ye(),BU=ue();ko.WORKFLOW_KIND_MISMATCH_CODE="WORKFLOW_KIND_MISMATCH";var dC={[Lo.WorkflowCategory.Workflow]:"classic workflow",[Lo.WorkflowCategory.Dialog]:"dialog",[Lo.WorkflowCategory.BusinessRule]:"business rule",[Lo.WorkflowCategory.Action]:"custom action",[Lo.WorkflowCategory.BusinessProcessFlow]:"business process flow",[Lo.WorkflowCategory.Flow]:"cloud flow",[Lo.WorkflowCategory.UIFlow]:"desktop flow"};async function qU(e,t,r){var n,i;let o=`/workflows(${t})${(0,BU.odataQuery)([["$select","category"]])}`,a=await e.get(o);if(a.status===404)return null;(0,cC.ensureSuccess)(a,e.apiUrl(o));let s=(n=a.body)===null||n===void 0?void 0:n.category,l=typeof s=="number"?s:typeof s=="string"&&s!==""?Number(s):NaN;if(l!==r){let u=Number.isFinite(l)?`a ${(i=dC[l])!==null&&i!==void 0?i:"process"} (category ${l})`:"a process whose category could not be read";throw new UU.SdkError(ko.WORKFLOW_KIND_MISMATCH_CODE,`Refusing to delete workflow '${t}' as a ${dC[r]}: it is ${u}. Nothing was changed. Check the id.`)}return(0,cC.readEtag)(a)}ko.assertWorkflowKind=qU});var Am=v(Hr=>{"use strict";Object.defineProperty(Hr,"__esModule",{value:!0});Hr.deleteWorkflowResending=Hr.isWorkflowDeleteUnsettled=Hr.failedAfterResend=Hr.WORKFLOW_DELETE_UNSETTLED_CODE=void 0;var ml=Q(),fi=ye(),pC=ue();Hr.WORKFLOW_DELETE_UNSETTLED_CODE="WORKFLOW_DELETE_UNSETTLED";var mC=new WeakSet;function Em(e){return typeof e=="object"&&e!==null&&mC.add(e),e}function VU(e){return typeof e=="object"&&e!==null&&mC.has(e)}Hr.failedAfterResend=VU;function GU(e){return e instanceof ml.SdkError&&e.code===Hr.WORKFLOW_DELETE_UNSETTLED_CODE}Hr.isWorkflowDeleteUnsettled=GU;function WU(e,t){try{(0,fi.ensureSuccess)(e,t)}catch(r){return r}}function zU(e){return(0,fi.isSqlDeadlockVictim)(e)?"lost a SQL deadlock (HTTP 500, Sql Number 1205)":`lost its transaction (HTTP 500 ${fi.TRANSACTION_NOT_STARTED_CODE})`}async function fC(e,t){try{return(await e.get(`/workflows(${t})${(0,pC.odataQuery)([["$select","workflowid"]])}`)).status===404}catch{return!1}}async function jU(e,t,{bindingToken:r,kindName:n,deactivated:i=!1,resendDeadlockVictim:o=!1,ifMatchOnFirst:a=!1}){let s=(0,pC.normalizeGuid)(t,"id");if(a&&!r)throw new ml.InvalidArgumentError(`Refusing to delete ${n} '${s}': its delete must be conditional on a token this operation holds, and it holds none.`);let l=`/workflows(${s})`,u=e.apiUrl(l),c=m=>(0,fi.isTransactionNotStarted)(m)||o&&(0,fi.isSqlDeadlockVictim)(m),d=0,f,p;try{p=await(0,fi.resendWhile)(c,async()=>{d+=1;let m=d>1||a,h=await e.delete(l,m?{headers:{"If-Match":r}}:void 0);return f=f??h,h},r?fi.DEADLOCK_BACKOFF_MS:[])}catch(m){if(m instanceof ml.ConnectionError&&m.statusCode===0&&r&&await fC(e,s))return;throw d>1?Em(m):m}if(!(d>1&&p.status===404)){if(d>1&&p.status===412){let m=zU(f),h=new ml.SdkError(Hr.WORKFLOW_DELETE_UNSETTLED_CODE,`Deleting ${n} '${s}' ${m}, and its re-send was refused (HTTP 412): the row at that id is no longer the version this delete checked \u2014 it was edited, or deleted and re-created at the same id \u2014 so nothing more was deleted. `+(i?"This delete had deactivated the process first and has NOT re-activated it: it MAY be left DISABLED. ":"")+"Read the row before deleting it again.");throw Em((0,ml.attachCause)(h,WU(f,u)))}if(!(r&&fi.AMBIGUOUS_WRITE_STATUSES.has(p.status)&&await fC(e,s)))try{(0,fi.ensureSuccess)(p,u)}catch(m){throw d>1?Em(m):m}}}Hr.deleteWorkflowResending=jU});var Sm=v(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.businessRuleApi=xn.BUSINESS_RULE_LEFT_DEACTIVATED_CODE=xn.WFOM_API_UNAVAILABLE_CODE=void 0;var kn=Ji(),HU=Xt(),KU=Cm(),JU=Am(),Ft=ye(),pi=ue(),wc=Q();xn.WFOM_API_UNAVAILABLE_CODE="BUSINESS_RULE_API_UNAVAILABLE";xn.BUSINESS_RULE_LEFT_DEACTIVATED_CODE="BUSINESS_RULE_LEFT_DEACTIVATED";async function hC(e,t,r,n){let i=`/workflows(${XU})/Microsoft.Dynamics.CRM.${t}`;try{return(0,Ft.ensureSuccess)(await e.post(i,{Entity:r.Entity,WfomJson:r.WfomJson},{headers:n}),e.apiUrl(i))}catch(o){throw o?.statusCode!==404?o:new wc.SdkError(xn.WFOM_API_UNAVAILABLE_CODE,`Business-rule authoring (preview) is not enabled on this environment yet: it does not expose 'Microsoft.Dynamics.CRM.${t}'. The bound members are still rolling out, so re-check once the release flag reaches this environment. Nothing was written. The SDK does NOT fall back to generating workflow XAML: that covered only 4 of the 7 action types and would silently save a rule different from the one you wrote.`)}}async function YU(e,t){let r=`/workflows(${t})${(0,pi.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,Ft.readEtag)(n),statecode:typeof i?.statecode=="number"?i.statecode:null,statuscode:typeof i?.statuscode=="number"?i.statuscode:null}}catch{return null}}async function QU(e,t,r){let n=await YU(e,t);if(n===null||n.etag===null)throw new wc.SdkError(Ft.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 wc.SdkError(Ft.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 XU="00000000-0000-0000-0000-000000000000",vc={"Content-Type":"application/json",Accept:"application/json","OData-Version":"4.0","OData-MaxVersion":"4.0"},ZU="workflowid,name,description,primaryentity,statecode,category,type",eB="category eq 2 and type eq 1";async function gC(e,t,r){var n;if(r==="Draft")return null;let i=(0,pi.normalizeGuid)(t,"workflowid"),o=r==="Active",a={statecode:o?kn.StateCode.Activated:kn.StateCode.Draft,statuscode:o?kn.StatusCode.Activated:kn.StatusCode.Draft},s=`/workflows(${i})`,l=(0,Ft.ensureSuccess)(await e.patch(s,a,{headers:vc}),e.apiUrl(s));return(n=(0,Ft.readEtag)(l))!==null&&n!==void 0?n:await hl(e,i)}async function hl(e,t){let r=`/workflows(${t})${(0,pi.odataQuery)([["$select","workflowid"]])}`;try{let n=await e.get(r);return n.status>=200&&n.status<300?(0,Ft.readEtag)(n):null}catch{return null}}async function tB(e,t,r){let n=await hl(e,t),i=await r(),o=(0,Ft.readEtag)(i);if(o)return{response:i,etag:o};let a=await hl(e,t);return{response:i,etag:n!==null&&n===a?a:null}}xn.businessRuleApi={async get(e,t){let r=(0,pi.normalizeGuid)(t,"id"),n=`/workflows(${r})/Microsoft.Dynamics.CRM.RetrieveProcessWithWfomJson`,{response:i,etag:o}=await tB(e,r,async()=>(0,Ft.ensureSuccess)(await e.get(n),e.apiUrl(n)));return{raw:i.body,etag:o}},async list(e,t){let r=[eB];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,pi.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,pi.odataQuery)([["$select",ZU],["$filter",r.join(" and ")]])}`;return(await(0,HU.collectPages)(e,n,"listArtifacts('businessRule')")).map(o=>{var a,s;return{type:"businessRule",id:(a=o.workflowid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",entityLogicalName:o.primaryentity,isDirty:!1}})},async create(e,t){var r;let n=t,i=(0,pi.normalizeGuid)(n.Entity.workflowid,"workflowid"),o=await hC(e,"CreateProcessWithWfomJson",n,vc),a=(0,Ft.resolveCreatedId)(o,"workflowid","business rule",i),s=null;try{s=await gC(e,a,n.status)}catch(l){try{await(0,Ft.deleteRecord)(e,"workflows",a)}catch{}throw l}return{id:a,etag:(r=s??(0,Ft.readEtag)(o))!==null&&r!==void 0?r:await hl(e,a)}},async update(e,t,r,n){var i,o;let a=r,s=(0,pi.normalizeGuid)(t,"id"),l=`/workflows(${s})`,u={...vc,"If-Match":(0,Ft.requireEtag)(n,"business rule",s)},c=await QU(e,s,u["If-Match"]),d=c.statecode===kn.StateCode.Activated;d&&(0,Ft.ensureSuccess)(await e.patch(l,{statecode:kn.StateCode.Draft,statuscode:kn.StatusCode.Draft},{headers:u}),e.apiUrl(l));let f;try{f=await hC(e,"UpdateProcessWithWfomJson",a,u)}catch(m){if(d)try{(0,Ft.ensureSuccess)(await e.patch(l,{statecode:kn.StateCode.Activated,statuscode:(i=c.statuscode)!==null&&i!==void 0?i:kn.StatusCode.Activated},{headers:vc}),e.apiUrl(l))}catch(h){throw new wc.SdkError(xn.BUSINESS_RULE_LEFT_DEACTIVATED_CODE,`The business-rule write failed AND the rule could not be re-activated, so '${s}' is left DEACTIVATED (Draft) on the server. Re-activate it before relying on it. Original write failure: ${m instanceof Error?m.message:String(m)}. Restore failure: ${h instanceof Error?h.message:String(h)}`)}throw m}let p=await gC(e,s,a.status);return{id:s,etag:(o=p??(0,Ft.readEtag)(f))!==null&&o!==void 0?o:await hl(e,s)}},async delete(e,t){let r=(0,pi.normalizeGuid)(t,"id"),n=await(0,KU.assertWorkflowKind)(e,r,kn.WorkflowCategory.BusinessRule);return(0,JU.deleteWorkflowResending)(e,r,{bindingToken:n,kindName:"business rule"})}}});var Kr=v(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.publishBoundEntity=yt.boundEntityPublishScope=yt.publishGenPageById=yt.publishDashboardById=yt.publishWebResourceById=yt.publishEntity=yt.publishAppModule=yt.publishXml=void 0;var yC=ye(),gl=ue(),bC="/PublishXml";async function $a(e,t){(0,yC.ensureSuccess)(await(0,yC.resendDeadlockVictim)(()=>e.post(bC,{ParameterXml:t})),e.apiUrl(bC))}yt.publishXml=$a;function rB(e,t){return $a(e,`<importexportxml><appmodules><appmodule>${(0,gl.xmlText)(t)}</appmodule></appmodules></importexportxml>`)}yt.publishAppModule=rB;function vC(e,t){return $a(e,`<importexportxml><entities><entity>${(0,gl.xmlText)(t)}</entity></entities></importexportxml>`)}yt.publishEntity=vC;function nB(e,t){return $a(e,`<importexportxml><webresources><webresource>${(0,gl.xmlText)(t)}</webresource></webresources></importexportxml>`)}yt.publishWebResourceById=nB;function iB(e,t){return $a(e,`<importexportxml><dashboards><dashboard>${(0,gl.xmlText)(t)}</dashboard></dashboards></importexportxml>`)}yt.publishDashboardById=iB;function oB(e,t){return $a(e,`<importexportxml><uxagentprojects><uxagentproject>${(0,gl.xmlText)(t)}</uxagentproject></uxagentprojects></importexportxml>`)}yt.publishGenPageById=oB;function aB(e){let t=e?.entityLogicalName;return t?{envelope:"entity",entityLogicalName:t,blastRadiusWarning:"ENTITY_ENVELOPE_ALSO_SHIPS_UNRELATED_UNPUBLISHED_CHANGES"}:{envelope:"entity"}}yt.boundEntityPublishScope=aB;function sB(e,t){let r=t?.entityLogicalName;return r?vC(e,r):Promise.resolve()}yt.publishBoundEntity=sB});var Fa=v(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});Ec.JsonPointer=void 0;var xr=Q(),Cc=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 xr.JsonPointerError(t,'non-empty pointers must start with "/"');return t.substring(1).split("/").map(r=>{if(/~(?![01])/.test(r))throw new xr.JsonPointerError(t,`invalid '~' escape in token '${r}' (expected ~0 or ~1)`);return e.decodeToken(r)})}static compile(t){return t.length===0?"":"/"+t.map(r=>e.encodeToken(r)).join("/")}static resolve(t,r){let n=e.parse(r),i=t;for(let o of n)if(Array.isArray(i)){let a=e.toArrayIndex(o,i.length);if(a===void 0)return;i=i[a]}else if(i!==null&&typeof i=="object"){let a=i;if(e.isReservedToken(o)||!Object.prototype.hasOwnProperty.call(a,o))return;i=a[o]}else return;return i}static set(t,r,n){let i=e.parse(r);if(i.length===0)throw new xr.JsonPointerError(r,"cannot set the document root");let{parent:o,lastToken:a}=e.resolveParent(t,i,r);if(Array.isArray(o)){let s=e.toArrayIndex(a,o.length);if(s===void 0)throw new xr.JsonPointerError(r,`'${a}' is not a valid array index`);if(s>o.length)throw new xr.JsonPointerError(r,`array index '${a}' is out of range`);o[s]=n}else{if(e.isReservedToken(a))throw new xr.JsonPointerError(r,`refusing to write reserved property '${a}'`);o[a]=n}}static remove(t,r){let n=e.parse(r);if(n.length===0)throw new xr.JsonPointerError(r,"cannot remove the document root");let{parent:i,lastToken:o}=e.resolveParent(t,n,r);if(Array.isArray(i)){let a=e.toArrayIndex(o,i.length);if(a===void 0||a>=i.length)throw new xr.JsonPointerError(r,`array index '${o}' is out of range`);i.splice(a,1)}else{if(e.isReservedToken(o))throw new xr.JsonPointerError(r,`refusing to remove reserved property '${o}'`);delete i[o]}}static add(t,r,n,i){let o=e.parse(r);if(o.length>0&&o[o.length-1]==="-"){let l=e.compile(o.slice(0,-1)),u=e.resolve(t,l);if(!Array.isArray(u))throw new xr.JsonPointerError(r,"add target must be an array");u.push(n);return}let a=e.resolve(t,r);if(!Array.isArray(a))throw new xr.JsonPointerError(r,"add target must be an array");let s=i===void 0?a.length:i;if(s<0||s>a.length)throw new xr.JsonPointerError(r,`insert index ${s} is out of range`);a.splice(s,0,n)}static parent(t){let r=e.parse(t);return r.pop(),e.compile(r)}static lastToken(t){let r=e.parse(t);return r.length===0?"":r[r.length-1]}static append(t,r){return`${t}/${e.encodeToken(String(r))}`}static resolveParent(t,r,n){let i=r[r.length-1],o=e.compile(r.slice(0,-1)),a=e.resolve(t,o);if(a===null||typeof a!="object")throw new xr.JsonPointerError(n,"parent path does not resolve to an object or array");return{parent:a,lastToken:i}}static toArrayIndex(t,r){if(t==="-")return r;if(/^(0|[1-9][0-9]*)$/.test(t))return Number(t)}};Ec.JsonPointer=Cc;Cc.RESERVED_TOKENS=new Set(["__proto__","prototype","constructor"])});var CC=v(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});Ac.findElements=void 0;var wC=Fa();function lB(e,t){let r=[];return Nm(e,"",t,r),r}Ac.findElements=lB;function Nm(e,t,r,n){if(!(e===null||typeof e!="object"))if(r(e,t)&&n.push({pointer:t,value:e}),Array.isArray(e))e.forEach((i,o)=>{Nm(i,wC.JsonPointer.append(t,o),r,n)});else for(let i of Object.keys(e))Nm(e[i],wC.JsonPointer.append(t,i),r,n)}});var _m=v($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.assertMutationResult=$n.assertExistsResult=$n.assertReadResult=$n.assertStorageContract=void 0;var uB=["readText","writeTextAtomic","deleteFile","deleteByPrefix"],cB=["ensureContainer","exists"];function dB(e){if(typeof e!="object"||e===null)throw new Error("workspaceStorage must be an object implementing WorkspaceStorage.");for(let t of uB)if(typeof e[t]!="function")throw new Error(`workspaceStorage is missing the required method '${t}'.`);for(let t of cB){let r=e[t];if(r!==void 0&&typeof r!="function")throw new Error(`workspaceStorage.${t} must be a function when present.`)}return e}$n.assertStorageContract=dB;function fB(e,t){if(e===null||typeof e=="string")return e;throw new Error(`workspaceStorage.readText must resolve to a string or null for ${t}; got ${typeof e}. Absence is null \u2014 resolving undefined would make a present value look absent.`)}$n.assertReadResult=fB;function pB(e,t){if(typeof e=="boolean")return e;throw new Error(`workspaceStorage.exists must resolve to a boolean for ${t}; got ${typeof e}. A truthy non-boolean would make an absent value look present.`)}$n.assertExistsResult=pB;function mB(e,t){if(e!==void 0)throw new Error(`workspaceStorage.${t} must resolve to undefined; got ${typeof e}. A status-returning implementation would let a failed write be reported as a completed one.`)}$n.assertMutationResult=mB});var Tm=v(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});Ma.retryTransientIoAsync=Ma.retryTransientIo=void 0;var hB=new Set(["EPERM","EACCES","EBUSY","UNKNOWN"]),gB=5,EC=10;function yB(e){for(let t=1;;t+=1)try{return e()}catch(r){if(!AC(r,t))throw r;vB(EC*t)}}Ma.retryTransientIo=yB;async function bB(e){for(let t=1;;t+=1)try{return await e()}catch(r){if(!AC(r,t))throw r;await new Promise(n=>setTimeout(n,EC*t))}}Ma.retryTransientIoAsync=bB;function AC(e,t){let r=e.code;return t<gB&&!!r&&hB.has(r)}function vB(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{let t=Date.now()+e;for(;Date.now()<t;);}}});var DC=v($r=>{"use strict";Object.defineProperty($r,"__esModule",{value:!0});$r.canonicalArtifactId=$r.WorkspaceManager=$r.WORKSPACE_SCHEMA_VERSION=$r.retryTransientIo=void 0;var Mt=_m(),Fn=Q(),wB=Tm();Object.defineProperty($r,"retryTransientIo",{enumerable:!0,get:function(){return wB.retryTransientIo}});function SC(e){let t=e;return typeof t.pathFor=="function"&&typeof t.getRoot=="function"?e:null}$r.WORKSPACE_SCHEMA_VERSION=1;var Yi={form:"forms",view:"views",businessRule:"business-rules",app:"apps",command:"commands",chart:"charts",dashboard:"dashboards",genPage:"gen-pages",bpf:"business-process-flows"},CB="manifest.json",Ua=".metadata",Dm="entities";function NC(e){try{return Promise.resolve(e())}catch(t){return Promise.reject(t)}}function Im(e){if(e.schemaVersion!==void 0&&e.schemaVersion>$r.WORKSPACE_SCHEMA_VERSION)throw new Fn.IncompatibleWorkspaceError(e.schemaVersion,$r.WORKSPACE_SCHEMA_VERSION)}function _C(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Sc(e){return e.trim().toLowerCase().replace(/\/+$/,"")}var Om=class{withManifest(t){let r=this.manifestQueue.then(t,t);return this.manifestQueue=r.then(()=>{},()=>{}),r}constructor(t,r,n){if(this.workspaceLabel=t,this.instanceUrl=r,this.manifestQueue=Promise.resolve(),this.bound=!1,n==null)throw new Error("WorkspaceManager requires a WorkspaceStorage. Node callers can build one with `createNodeWorkspaceStorage(path)` from '@maker-studio/cds-maker-sdk/node'.");this.storage=n}artifactKey(t,r){return this.assertSafeId(r),[Yi[t],`${yl(r)}.json`]}metaKey(t,r){return this.assertSafeId(r),[Ua,Yi[t],`${yl(r)}.meta.json`]}entityKey(t){return this.assertSafeId(t),[Ua,Dm,`${t.toLowerCase()}.json`]}fsStore(){let t=SC(this.storage);if(!t)throw new Error("This workspace is not filesystem-backed, so it has no physical paths. Use the artifact/metadata/manifest accessors instead of the path helpers.");return t}getRoot(){let t=SC(this.storage);return t?t.getRoot():this.workspaceLabel}getArtifactDir(t){return this.fsStore().pathFor([Yi[t]])}getArtifactFilePath(t,r){return this.fsStore().pathFor(this.artifactKey(t,r))}getMetaFilePath(t,r){return this.fsStore().pathFor(this.metaKey(t,r))}getEntityMetaFilePath(t){return this.fsStore().pathFor(this.entityKey(t))}assertSafeId(t){if(typeof t!="string"||t.length===0||/[\u0000-\u001f]/.test(t)||t.includes("/")||t.includes("\\")||t.includes(":")||t==="."||t===".."||t.includes(".."))throw new Fn.PathTraversalError(String(t),this.workspaceLabel)}get manifestKey(){return[CB]}assertDataKey(t,r){if(!Array.isArray(t)||t.length<2)throw new Fn.InvalidArgumentError(`${r} writes only inside the workspace's folders; '${String(t)}' is at its root, where only the manifest lives \u2014 and the manifest is changed only by the workspace itself.`);t.forEach(n=>this.assertSafeId(n))}async init(){let t=await this.withManifest(async()=>{let r=await this.readStoredManifest();return r.present&&this.assertBoundHere(r.value),r.present});await this.ensureLayout(),t||await this.withManifest(async()=>{let r=await this.readStoredManifest();if(r.present){this.assertBoundHere(r.value);return}let n={instanceUrl:this.instanceUrl,createdAt:new Date().toISOString(),artifacts:[]};await this.writeManifest(n)}),this.bound=!0}async readStoredManifest(){let t=(0,Mt.assertReadResult)(await this.storage.readText(this.manifestKey),"manifest.json");return t===null?{present:!1}:{present:!0,value:JSON.parse(t)}}async ensureLayout(){if(!this.storage.ensureContainer)return;let t=this.storage.ensureContainer.bind(this.storage),r=[[Ua,Dm]];for(let i of Object.keys(Yi))r.push([Yi[i]],[Ua,Yi[i]]);let n=await Promise.allSettled(r.map(i=>NC(()=>t(i))));for(let i of n){if(i.status==="rejected")throw i.reason;(0,Mt.assertMutationResult)(i.value,"ensureContainer")}}async isInitialized(){return this.storage.exists?(0,Mt.assertExistsResult)(await this.storage.exists(this.manifestKey),"manifest.json"):(0,Mt.assertReadResult)(await this.storage.readText(this.manifestKey),"manifest.json")!==null}async ensureInitialized(){if(!this.bound){await this.verifyBinding();return}if(!await this.isInitialized())throw new Fn.WorkspaceNotInitializedError(this.workspaceLabel)}async ensureReady(){await this.ensureInitialized()}async ensureBound(){this.bound||await this.verifyBinding()}verifyBinding(){if(!this.verifying){let t=()=>{this.verifying=void 0};this.verifying=this.readAndCheckBinding().then(t,r=>{throw t(),r})}return this.verifying}async readAndCheckBinding(){let t=await this.readStoredManifest();if(!t.present)throw new Fn.WorkspaceNotInitializedError(this.workspaceLabel);this.assertBoundHere(t.value),this.bound=!0}assertBoundHere(t){if(!_C(t))throw new Fn.WorkspaceOrgMismatchError("",this.instanceUrl);Im(t);let r=typeof t.instanceUrl=="string"?t.instanceUrl.trim():"",n=Sc(r);if(!n||n!==Sc(this.instanceUrl))throw new Fn.WorkspaceOrgMismatchError(r,this.instanceUrl)}async clean(){let t=await this.readStoredManifest();if(!t.present||!_C(t.value))throw new Fn.WorkspaceNotInitializedError(this.workspaceLabel);let r=t.value;Im(r);let n=Object.keys(Yi).map(o=>[Yi[o]]);n.push([Ua]);let i=await Promise.allSettled(n.map(o=>NC(()=>this.storage.deleteByPrefix(o))));for(let o of i){if(o.status==="rejected")throw o.reason;(0,Mt.assertMutationResult)(o.value,"deleteByPrefix")}await this.ensureLayout(),await this.withManifest(()=>this.writeManifest({...r,instanceUrl:this.instanceUrl,artifacts:[],lastSyncAt:void 0})),this.bound=!0}async readArtifact(t,r){return await this.ensureInitialized(),this.readJsonUnchecked(this.artifactKey(t,r))}async readArtifactWithText(t,r){await this.ensureInitialized();let n=this.artifactKey(t,r),i=(0,Mt.assertReadResult)(await this.storage.readText(n),n.join("/"));return i===null?null:{artifact:JSON.parse(i),text:i}}async writeArtifact(t,r,n,i){await this.ensureInitialized();let o=TC(n);if(i!==void 0&&o===i){await this.upsertManifestEntry(t,r,n,{unlessCurrent:!0});return}(0,Mt.assertMutationResult)(await this.storage.writeTextAtomic(this.artifactKey(t,r),o),"writeTextAtomic"),await this.upsertManifestEntry(t,r,n)}async deleteArtifact(t,r){await this.ensureInitialized(),(0,Mt.assertMutationResult)(await this.storage.deleteFile(this.artifactKey(t,r)),"deleteFile"),(0,Mt.assertMutationResult)(await this.storage.deleteFile(this.metaKey(t,r)),"deleteFile");let n=yl(r);await this.withManifest(async()=>{let i=await this.getManifest();i.artifacts=i.artifacts.filter(o=>!(o.type===t&&o.id===n)),await this.writeManifest(i)})}async readMeta(t,r){return await this.ensureBound(),this.readJsonUnchecked(this.metaKey(t,r))}async writeMeta(t,r,n){await this.ensureBound(),await this.writeJsonUnchecked(this.metaKey(t,r),n)}async listArtifacts(t,r){return await this.ensureInitialized(),(await this.getManifest()).artifacts.filter(n=>!(t&&n.type!==t||r?.entityLogicalName&&n.entityLogicalName!==r.entityLogicalName))}async readEntityMetadata(t){await this.ensureInitialized();let r=await this.readJsonUnchecked(this.entityKey(t));return!r||typeof r.schemaName!="string"||typeof r.primaryNameAttribute!="string"||typeof r.primaryIdAttribute!="string"||typeof r.isCustomEntity!="boolean"?null:r}async writeEntityMetadata(t,r){await this.ensureInitialized(),await this.writeJsonUnchecked(this.entityKey(t),r)}async dropEntityMetadata(t){if(await this.ensureInitialized(),t===void 0){(0,Mt.assertMutationResult)(await this.storage.deleteByPrefix([Ua,Dm]),"deleteByPrefix");return}(0,Mt.assertMutationResult)(await this.storage.deleteFile(this.entityKey(t)),"deleteFile")}async getManifest(){await this.ensureInitialized();let t=await this.readJsonUnchecked(this.manifestKey);if(!t)throw new Fn.WorkspaceNotInitializedError(this.workspaceLabel);return Im(t),t}async writeManifest(t){await this.writeJsonUnchecked(this.manifestKey,{...t,schemaVersion:$r.WORKSPACE_SCHEMA_VERSION})}async updateManifest(t){await this.withManifest(async()=>{let r=await this.getManifest();if(t.instanceUrl!==void 0&&Sc(String(t.instanceUrl))!==Sc(r.instanceUrl))throw new Fn.InvalidArgumentError("updateManifest cannot change the workspace's org: it is bound to the org it was created for. cleanWorkspace() discards its contents and binds it to the org of the SDK that calls it.");await this.writeManifest({...r,...t,instanceUrl:r.instanceUrl})})}async upsertManifestEntry(t,r,n,i={}){await this.withManifest(async()=>{let o=await this.getManifest(),a=yl(r),s=n,l=typeof s.name=="string"?s.name:`${t}:${a}`,u=typeof s.entityLogicalName=="string"?s.entityLogicalName:void 0,c=o.artifacts.find(d=>d.type===t&&d.id===a);i.unlessCurrent&&c?.name===l&&c.entityLogicalName===u||(c?(c.name=l,c.entityLogicalName=u):o.artifacts.push({type:t,id:a,name:l,entityLogicalName:u,isDirty:!1}),await this.writeManifest(o))})}async readJson(t){return await this.ensureBound(),this.readJsonUnchecked(t)}async writeJson(t,r){this.assertDataKey(t,"writeJson"),await this.ensureBound(),await this.writeJsonUnchecked(t,r)}async removeFile(t){this.assertDataKey(t,"removeFile"),await this.ensureBound(),(0,Mt.assertMutationResult)(await this.storage.deleteFile(t),"deleteFile")}async exists(t){return await this.ensureBound(),this.storage.exists?(0,Mt.assertExistsResult)(await this.storage.exists(t),t.join("/")):(0,Mt.assertReadResult)(await this.storage.readText(t),t.join("/"))!==null}async readJsonUnchecked(t){let r=(0,Mt.assertReadResult)(await this.storage.readText(t),t.join("/"));return r===null?null:JSON.parse(r)}async writeJsonUnchecked(t,r){(0,Mt.assertMutationResult)(await this.storage.writeTextAtomic(t,TC(r)),"writeTextAtomic")}};$r.WorkspaceManager=Om;function TC(e){return`${JSON.stringify(e,null,2)}-`}function yl(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()}$r.canonicalArtifactId=yl});var Pm=v(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.deepEqual=Ba.deepDiff=void 0;var EB=Fa();function AB(e,t){let r=[];return OC(e,t,"",r,0),r}Ba.deepDiff=AB;var Nc=Symbol("missing"),_c=512;function OC(e,t,r,n,i){if(e===t)return;if(i>_c)throw new RangeError(`deepDiff exceeded the maximum supported depth of ${_c}`);let o=Tc(e),a=Tc(t);if(o&&a&&Array.isArray(e)===Array.isArray(t)){let s=SB(e,t);for(let l of s){let u=IC(e,l),c=IC(t,l),d=EB.JsonPointer.append(r,l);u===Nc?n.push({pointer:d,type:"added",newValue:c}):c===Nc?n.push({pointer:d,type:"removed",oldValue:u}):OC(u,c,d,n,i+1)}return}PC(e,t)||n.push({pointer:r,type:"modified",oldValue:e,newValue:t})}function Tc(e){return e!==null&&typeof e=="object"}function SB(e,t){if(Array.isArray(e)&&Array.isArray(t)){let n=Math.max(e.length,t.length),i=[];for(let o=0;o<n;o++)i.push(String(o));return i}let r=new Set([...Object.keys(e),...Object.keys(t)]);return Array.from(r)}function IC(e,t){if(Array.isArray(e)){let r=Number(t);return r<e.length?e[r]:Nc}return t in e?e[t]:Nc}function PC(e,t){return RC(e,t,0)}Ba.deepEqual=PC;function RC(e,t,r){if(e===t)return!0;if(r>_c)throw new RangeError(`deepEqual exceeded the maximum supported depth of ${_c}`);if(!Tc(e)||!Tc(t)||Array.isArray(e)!==Array.isArray(t))return!1;let n=Object.keys(e),i=Object.keys(t);return n.length!==i.length?!1:n.every(o=>o in t&&RC(e[o],t[o],r+1))}});var kC=v(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.VersionManager=qa.PROJECTION_VERSION=void 0;var LC=Pm();qa.PROJECTION_VERSION=7;var Rm=class{constructor(t){this.workspace=t}async storeMeta(t,r,n,i){var o;let a=i===void 0?await this.getMeta(t,r):i,s=((o=n.snapshot)===null||o===void 0?void 0:o.status)==="Active",l=a?.everActivated===!0||s;await this.workspace.writeMeta(t,r,l?{...n,everActivated:l}:n)}async getMeta(t,r){return this.workspace.readMeta(t,r)}async isDirty(t,r,n){let i=await this.workspace.readArtifact(t,r);if(i===null)return!1;let o=n===void 0?await this.getMeta(t,r):n;return o?!(0,LC.deepEqual)(o.snapshot,i):!0}async diff(t,r){let n=await this.workspace.readArtifact(t,r),i=await this.getMeta(t,r),o;return n===null?o=i?[{pointer:"",type:"removed",oldValue:i.snapshot}]:[]:i?o=(0,LC.deepDiff)(i.snapshot,n):o=[{pointer:"",type:"added",newValue:n}],{artifactType:t,artifactId:r,changes:o}}async checkConflict(t,r,n){let i=await this.getMeta(t,r);return!i||i.etag===null?!1:i.etag!==n}};qa.VersionManager=Rm});var $C=v((Lm,xC)=>{(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof Lm=="object"?xC.exports=t():e.compareVersions=t()})(Lm,function(){var e=/^v?(?:\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+))?(?:-[\da-z\-]+(?:\.[\da-z\-]+)*)?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;function t(o,a){return o.indexOf(a)===-1?o.length:o.indexOf(a)}function r(o){var a=o.replace(/^v/,"").replace(/\+.*$/,""),s=t(a,"-"),l=a.substring(0,s).split(".");return l.push(a.substring(s+1)),l}function n(o){return isNaN(Number(o))?o:Number(o)}function i(o){if(typeof o!="string")throw new TypeError("Invalid argument expected string");if(!e.test(o))throw new Error("Invalid argument not valid semver ('"+o+"' received)")}return function(a,s){[a,s].forEach(i);for(var l=r(a),u=r(s),c=0;c<Math.max(l.length-1,u.length-1);c++){var d=parseInt(l[c]||0,10),f=parseInt(u[c]||0,10);if(d>f)return 1;if(f>d)return-1}var p=l[l.length-1],m=u[u.length-1];if(p&&m){var h=p.split(".").map(n),g=m.split(".").map(n);for(c=0;c<Math.max(h.length,g.length);c++){if(h[c]===void 0||typeof g[c]=="string"&&typeof h[c]=="number")return-1;if(g[c]===void 0||typeof h[c]=="string"&&typeof g[c]=="number"||h[c]>g[c])return 1;if(g[c]>h[c])return-1}}else if(p||m)return p?-1:1;return 0}})});var qC=v(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.EnvironmentFlowHostingType=ze.EnvironmentDisableReasonCode=ze.EnvironmentMigrationConstants=ze.EnvironmentProvisioningStates=ze.EnvironmentLocations=ze.EnvironmentCreationTypeConstants=ze.EnvironmentType=ze.EnvironmentSkuConstants=ze.environmentPermissions=ze.DatabaseType=void 0;var FC;(function(e){e.CommonDataService="CommonDataService",e.None="None"})(FC||(ze.DatabaseType=FC={}));ze.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"};ze.EnvironmentSkuConstants={NotSpecified:"NotSpecified",Standard:"Standard",Premium:"Premium",Developer:"Developer",Basic:"Basic",Production:"Production",Sandbox:"Sandbox",Trial:"Trial",Default:"Default",Teams:"Teams",Platform:"Platform"};var MC;(function(e){e[e.CDS2=0]="CDS2",e[e.CDS1=1]="CDS1",e[e.Empty=2]="Empty"})(MC||(ze.EnvironmentType=MC={}));ze.EnvironmentCreationTypeConstants={NotSpecified:"NotSpecified",Legacy:"Legacy",DefaultTenant:"DefaultTenant",User:"User",CommonDataModelLegacy:"CommonDataModelLegacy"};ze.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"};ze.EnvironmentProvisioningStates={NotSpecified:"NotSpecified",Succeeded:"Succeeded",Deleting:"Deleting",Deleted:"Deleted",FailedDeleting:"FailedDeleting",LinkedDatabaseProvisioning:"LinkedDatabaseProvisioning",LinkedDatabaseFailedProvisioning:"LinkedDatabaseFailedProvisioning",LinkedDatabaseFailedConfiguring:"LinkedDatabaseFailedConfiguring",LinkedDatabaseUnavailable:"LinkedDatabaseUnavailable",Creating:"Creating"};ze.EnvironmentMigrationConstants={phases:{completed:"Completed"}};var UC;(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"})(UC||(ze.EnvironmentDisableReasonCode=UC={}));var BC;(function(e){e.LogicApps="LogicApps",e.SelfHostSingleTenant="SelfHostSingleTenant",e.SelfHostMultiTenant="SelfHostMultiTenant"})(BC||(ze.EnvironmentFlowHostingType=BC={}))});var JC=v(_=>{"use strict";var NB=_&&_.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(_,"__esModule",{value:!0});_.hasCommonDataServiceDatabase=_.getEnvironmentDiscoveryUrl=_.getEnvironmentWebApiUrl=_.getEnvironmentInstanceApiUrl=_.getEnvironmentLanguageCode=_.getEnvironmentUpdateCadence=_.checkVersions=_.isCds2EnvironmentVersionAtLeast=_.getSecurityOrConnectedGroupId=_.hasSecurityGroupId=_.doesCds2VersionSupportApiVersion9_1=_.doesCds2EnvironmentSupportApiVersion9_1=_.cdsVersionSupportingOSColorEdit=_.getEnvironmentDisplayName=_.getEnvironmentName=_.isEnvironmentInFirstReleaseCluster=_.isEnvironmentInPreprodCluster=_.isEnvironmentInTestCluster=_.isLiteEnvironmentUpgrading=_.isEnvironmentExpired=_.isEnvironmentInDeletedState=_.isEnvironmentInCreatingState=_.isDatabaseInProvisioningState=_.canUserCreateDatabase=_.isDisabledEnvironment=_.isDefaultEnvironment=_.isTrialEnvironment=_.isPlatformEnvironment=_.isTeamsEnvironment=_.isSandboxEnvironment=_.isProdEnvironment=_.isDevEnvironment=_.getEnvironmentType=_.getCrmInstanceName=_.getCrmInstanceUrl=_.getCrmAppDesignerUrl=_.getDevResourcesUrl=_.isEnvironmentInSuccessfulState=_.getAllThemesUrl=_.getAllPublishersUrl=_.getAllSolutionsUrl=_.getSecurityRolesUrl=_.getSecurityUsersUrl=_.environmentHasCds2Database=_.DEFAULT_SOLUTION_UNIQUE_NAME=_.DEFAULT_SOLUTION_ID=_.crmBapSolutionId=_.doesUserHavePermission=_.getLinkedEnvironmentMetadata=_.getCrmVersion=void 0;_.doesUserHaveFlowRunOnlyPermission=_.isUserPautoMakerWithoutDataAccess=_.isUserPautoMakerWithDataAccess=_.doesUserHaveCreateFlowPermission=_.equalsIgnoreCase=_.doesUserHaveCreateDatabasePermission=_.doesUserHaveDatabaseTablePermissions=_.isUserMakerWithoutDataAccess=_.isUserMakerWithDataAccess=_.doesUserHaveCreateAppPermission=_.doesUserHaveAdminPermission=void 0;var _B=NB($C()),Te=qC(),bl=xm();function TB(e){let t=hi(e);return t&&t.version}_.getCrmVersion=TB;function hi(e){return e&&e.properties&&e.properties.linkedEnvironmentMetadata}_.getLinkedEnvironmentMetadata=hi;function mi(e,t){return e?!!e[t]:!1}_.doesUserHavePermission=mi;_.crmBapSolutionId="00000001-0000-0000-0001-00000000009b";_.DEFAULT_SOLUTION_ID="fd140aaf-4df4-11dd-bd17-0019b9312238";_.DEFAULT_SOLUTION_UNIQUE_NAME="Default";function xo(e){return!!hi(e)&&VC(e)}_.environmentHasCds2Database=xo;function DB(e){if(e&&xo(e)){let t=Qi(e);return(0,bl.getCrmAdminSecurityRolesUrl)(t)}return""}_.getSecurityUsersUrl=DB;function IB(e){if(e&&xo(e)){let t=Qi(e);return(0,bl.getCrmAdminSecurityUsersUrl)(t)}return""}_.getSecurityRolesUrl=IB;function OB(e){if(e&&xo(e)){let t=Qi(e);(0,bl.getCrmAllSolutionsUrl)(t)}return""}_.getAllSolutionsUrl=OB;function PB(e){if(e&&xo(e)){let t=Qi(e);return(0,bl.getCrmAllPublishersUrl)(t)}return""}_.getAllPublishersUrl=PB;function RB(e){return e&&xo(e)?Qi(e):""}_.getAllThemesUrl=RB;function VC(e){return!!e&&e.properties&&!!e.properties.provisioningState&&e.properties.provisioningState.toUpperCase()===Te.EnvironmentProvisioningStates.Succeeded.toUpperCase()}_.isEnvironmentInSuccessfulState=VC;function LB(e){if(e&&xo(e)){let t=Qi(e);return(0,bl.getCrmDevResourcesUrl)(t)}return""}_.getDevResourcesUrl=LB;function kB(e){return`${e}designer/app/{${_.crmBapSolutionId}}/CreateNewApp}}`}_.getCrmAppDesignerUrl=kB;function Qi(e){let t=hi(e);if(t){let r=t.instanceUrl;return r?r.endsWith("/")?r:r+"/":""}return""}_.getCrmInstanceUrl=Qi;function xB(e){let t=hi(e);return t?t.uniqueName:""}_.getCrmInstanceName=xB;function $B(e){return hi(e)?Te.EnvironmentType.CDS2:e&&e.properties&&e.properties.namespace?Te.EnvironmentType.CDS1:Te.EnvironmentType.Empty}_.getEnvironmentType=$B;function FB(e){return e&&e.properties&&e.properties.environmentSku===Te.EnvironmentSkuConstants.Developer}_.isDevEnvironment=FB;function MB(e){return e&&e.properties&&e.properties.environmentSku===Te.EnvironmentSkuConstants.Production}_.isProdEnvironment=MB;function UB(e){return e&&e.properties&&e.properties.environmentSku===Te.EnvironmentSkuConstants.Sandbox}_.isSandboxEnvironment=UB;function vl(e){return e&&e.properties&&e.properties.environmentSku===Te.EnvironmentSkuConstants.Teams}_.isTeamsEnvironment=vl;function BB(e){return e&&e.properties&&e.properties.environmentSku===Te.EnvironmentSkuConstants.Platform}_.isPlatformEnvironment=BB;var qB=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.environmentSku)===Te.EnvironmentSkuConstants.Trial};_.isTrialEnvironment=qB;function VB(e){return e&&e.properties&&(e.properties.isDefault||e.properties.creationType===Te.EnvironmentCreationTypeConstants.DefaultTenant)}_.isDefaultEnvironment=VB;function GB(e){return e&&e.properties&&!!e.properties.states&&!!e.properties.states.runtime&&e.properties.states.runtime.id==="Disabled"}_.isDisabledEnvironment=GB;function WB(e){return e&&e.properties&&mi(e.properties.permissions,Te.environmentPermissions.CreateDatabase)}_.canUserCreateDatabase=WB;function zB(e){return!!(e&&e.properties&&e.properties.provisioningState&&KC(e.properties.provisioningState,Te.EnvironmentProvisioningStates.LinkedDatabaseProvisioning))}_.isDatabaseInProvisioningState=zB;function jB(e){return!!e&&!!e.properties&&e.properties.provisioningState===Te.EnvironmentProvisioningStates.Creating}_.isEnvironmentInCreatingState=jB;function HB(e){return e&&e.properties&&(e.properties.provisioningState===Te.EnvironmentProvisioningStates.Deleted||e.properties.provisioningState===Te.EnvironmentProvisioningStates.Deleting||e.properties.provisioningState===Te.EnvironmentProvisioningStates.FailedDeleting)}_.isEnvironmentInDeletedState=HB;function KB(e){return!!e&&!!e.properties&&!!e.properties.expirationTime&&Date.parse(e.properties.expirationTime)<Date.now()}_.isEnvironmentExpired=KB;function JB(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"}_.isLiteEnvironmentUpgrading=JB;function YB(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Test"}_.isEnvironmentInTestCluster=YB;function QB(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Preprod"}_.isEnvironmentInPreprodCluster=QB;function XB(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="FirstRelease"}_.isEnvironmentInFirstReleaseCluster=XB;function ZB(e){return e&&e.name||""}_.getEnvironmentName=ZB;function eq(e){return e&&e.properties&&e.properties.displayName||""}_.getEnvironmentDisplayName=eq;var GC="9.1.0.8202";_.cdsVersionSupportingOSColorEdit="9.1.0000.20708";function tq(e){return jC(e,GC)}_.doesCds2EnvironmentSupportApiVersion9_1=tq;function rq(e){return km(e,GC)}_.doesCds2VersionSupportApiVersion9_1=rq;function WC(e){let t=hi(e);if(t)return t.securityGroupId}function zC(e){return e&&e.properties&&e.properties.connectedGroups}function nq(e,t){let r=zC(e);return!!r&&!!r.find(n=>n.id===t)||WC(e)===t}_.hasSecurityGroupId=nq;function iq(e){let t=zC(e);return t&&t.length>0&&t[0].id?t[0].id:WC(e)}_.getSecurityOrConnectedGroupId=iq;function jC(e,t){let r=e.version;return r?km(r,t):!1}_.isCds2EnvironmentVersionAtLeast=jC;function km(e,t){return t?e?(0,_B.default)(e,t)>=0:!1:!0}_.checkVersions=km;function oq(e){return e&&e.properties&&e.properties.updateCadence&&e.properties.updateCadence.id||"NotSpecified"}_.getEnvironmentUpdateCadence=oq;function aq(e){let t=hi(e);return t?Number(t.baseLanguage):0}_.getEnvironmentLanguageCode=aq;function HC(e){let t=hi(e);return t?t.instanceApiUrl:void 0}_.getEnvironmentInstanceApiUrl=HC;function sq(e){let t=HC(e);return t?t+"/api/data/v9.2":""}_.getEnvironmentWebApiUrl=sq;function lq(e){let t=Qi(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"}_.getEnvironmentDiscoveryUrl=lq;var uq=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.databaseType)===Te.DatabaseType.CommonDataService};_.hasCommonDataServiceDatabase=uq;var cq=e=>{var t;return mi((t=e.properties)===null||t===void 0?void 0:t.permissions,Te.environmentPermissions.AdminReadEnvironment)};_.doesUserHaveAdminPermission=cq;var dq=e=>{var t;return mi((t=e.properties)===null||t===void 0?void 0:t.permissions,Te.environmentPermissions.CreatePowerApp)};_.doesUserHaveCreateAppPermission=dq;var fq=e=>(0,_.doesUserHaveAdminPermission)(e)&&(0,_.hasCommonDataServiceDatabase)(e)?!0:(0,_.doesUserHaveCreateAppPermission)(e)?vl(e)||(0,_.doesUserHaveDatabaseTablePermissions)(e):!1;_.isUserMakerWithDataAccess=fq;var pq=e=>(0,_.doesUserHaveCreateAppPermission)(e)&&!vl(e)&&!(0,_.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,_.doesUserHaveAdminPermission)(e)||!(0,_.hasCommonDataServiceDatabase)(e));_.isUserMakerWithoutDataAccess=pq;var mq=e=>[Te.environmentPermissions.CreateDatabaseEntities,Te.environmentPermissions.ListDatabaseEntities,Te.environmentPermissions.UpdateDatabaseEntities,Te.environmentPermissions.DeleteDatabaseEntities].every(t=>{var r;return mi((r=e.properties)===null||r===void 0?void 0:r.permissions,t)});_.doesUserHaveDatabaseTablePermissions=mq;var hq=e=>{var t;return mi((t=e.properties)===null||t===void 0?void 0:t.permissions,Te.environmentPermissions.CreateDatabase)};_.doesUserHaveCreateDatabasePermission=hq;function KC(e,t){return!e&&!t?!0:!e||!t?!1:e.toUpperCase()===t.toUpperCase()}_.equalsIgnoreCase=KC;var gq=e=>{var t;return mi((t=e.properties)===null||t===void 0?void 0:t.permissions,Te.environmentPermissions.CreateFlow)};_.doesUserHaveCreateFlowPermission=gq;var yq=e=>(0,_.doesUserHaveAdminPermission)(e)&&(0,_.hasCommonDataServiceDatabase)(e)?!0:(0,_.doesUserHaveCreateFlowPermission)(e)?vl(e)||(0,_.doesUserHaveDatabaseTablePermissions)(e):!1;_.isUserPautoMakerWithDataAccess=yq;var bq=e=>(0,_.doesUserHaveCreateFlowPermission)(e)&&!vl(e)&&!(0,_.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,_.doesUserHaveAdminPermission)(e)||!(0,_.hasCommonDataServiceDatabase)(e));_.isUserPautoMakerWithoutDataAccess=bq;var vq=e=>{var t,r;return!mi((t=e.properties)===null||t===void 0?void 0:t.permissions,Te.environmentPermissions.CreateFlow)&&mi((r=e.properties)===null||r===void 0?void 0:r.permissions,Te.environmentPermissions.ReadEnvironment)};_.doesUserHaveFlowRunOnlyPermission=vq});var xm=v(S=>{"use strict";Object.defineProperty(S,"__esModule",{value:!0});S.getRequiredComponentsQueryUrl=S.solutionComponentCountSummariesQueryUrl=S.solutionComponentSummariesQueryUrl=S.solutionComponentConfigurationsQueryUrl=S.chartsQueryUrl=S.workflowsQueryUrl=S.entityDefinitionsQueryUrl=S.solutionComponentDefinitionsQueryUrl=S.getCreateNewArticleTemplateUrl=S.getCreateNewPublisherUrl=S.getEnableSecurityRolesUrl=S.getArticleTemplateUrl=S.getFieldSecurityProfileDesignerUrl=S.getSecurityRoleDesignerUrl=S.getMailMergeTemplateDesignerUrl=S.getEmailTemplateDesignerUrl=S.getConnectionRoleDesignerUrl=S.getSiteMapDesignerUrl=S.getWebResourceFileUrl=S.getWebResourceDesignerUrl=S.getReportDesignerUrl=S.getBusinessProcessFlowDesignerUrl=S.getProcessShareUrl=S.getProcessDesignerUrl=S.getChartDesignerUrl=S.getOpenModernEntityDashboardUrl=S.getNewModernEntityDashboardUrl=S.getNewModernDashboardUrl=S.getOpenModernDashboardUrl=S.getDashboardDesignerUrl=S.getAppModuleDesignerUrl=S.privilegesQueryUrls=S.xrmApiUrl=S.getPlayAppModuleUrl=S.getCrmAdminSecurityUsersUrl=S.getCrmAdminSecurityRolesUrl=S.getCrmMyAppsUrl=S.getCrmAppDesignerUrl=S.getCrmDevResourcesUrl=S.getCrmAllPublishersUrl=S.getCrmAllSolutionsUrl=S.getSolutionPublisherUrl=S.getExportTranslationFileName=S.getExportSolutionTranslationUrl=S.getImportSolutionTranslationUrl=S.getShowSolutionDependenciesUrl=S.getShowComponentDependenciesUrl=S.cdsServiceUrl=S.ODATA_NEXT_LINK=S.ODATA_MAX_PAGE_SIZE=void 0;S.retrieveOrganizationResources=S.getUCIEntityRecordEditUrl=S.getUCIEntityRecordBaseUrl=S.getBusinessRuleDesignerUri=S.retrieveUnpublishedSuffix=S.getSavePowerSettingUri=S.getPowerSettingUri=S.getPowerSettingsUri=S.RetrievePlatform=S.getAppSettingOverrideUri=S.AppSettingOverrideName=S.getOrgSettingOverrideUri=S.OrgSettingOverrideName=S.getSettingDefinitionsUri=S.retrieveFeatureControlSettingsByNamespaceUrl=S.retrieveDeploymentPipelineConfigAppUrl=S.SPNPrincipalIdUrl=S.retrieveDeploymentEnvironmentInfoUrl=S.devSolutionInfoUrl=S.deployOperationStatusUrl=S.getAIGeneratedDeploymentNotesUrl=S.deploymentStageRunUrl=S.validatePackageAsyncUrl=S.deployPackageAsyncUrl=S.updateDeploymentStageRunUrl=S.createDeploymentStageRunUrl=S.retrieveDeploymentStagesUrl=S.retrievePipelinesUrl=S.retrieveDeploymentPipelineInfoUrl=S.getDeploymentStageRunsUrl=S.appDeploymentUrls=S.getProvisionLanguageUrl=S.getSolutionQueryUrl=S.getSolutionsByUniqueNameQueryUrl=S.solutionsQueryUrl=S.getDependentComponentsWithMetadataQueryUrl=void 0;var YC=JC();S.ODATA_MAX_PAGE_SIZE="odata.maxpagesize";S.ODATA_NEXT_LINK="@odata.nextLink";S.cdsServiceUrl="https://cds-org/";var Cl;(function(e){e.AllSolutions="11",e.AllPublishers="10",e.DevResources="05"})(Cl||(Cl={}));function wq(e,t,r,n){return`${e}tools/dependency/dependencyviewdialog.aspx?appSolutionId=%7b${t}%7d&dType=1&objectid=%7b${r}%7d&objecttype=${n}&operationtype=showdependency`}S.getShowComponentDependenciesUrl=wq;function Cq(e,t){let r=`dType=1&isproactivecheck=true&objecttype=7100&operationtype=dependenciesforuninstall&objectid=${t}`;return`${e}tools/dependency/dependencyviewdialog.aspx?${r}`}S.getShowSolutionDependenciesUrl=Cq;function Eq(e,t){return`${e}tools/muiProvisioning/Dialogs/LangTranslationsImport.aspx?dType=1&appSolutionId=${t}`}S.getImportSolutionTranslationUrl=Eq;function Aq(e,t){return`${e}_grid/cmds/dlg_exportsolution.aspx?command=exporttranslation&appSolutionId=${t}`}S.getExportSolutionTranslationUrl=Aq;function Sq(e,t){return e!==void 0&&t!==void 0&&`CrmTranslations_${e}_${t.replace(/[.]/g,"_")}.zip`||""}S.getExportTranslationFileName=Sq;function Nq(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`}S.getSolutionPublisherUrl=Nq;function $m(e,t){return`${e}tools/systemcustomization/systemCustomization.aspx?pid=${t}`}function _q(e){return $m(e,Cl.AllSolutions)}S.getCrmAllSolutionsUrl=_q;function Tq(e){return $m(e,Cl.AllPublishers)}S.getCrmAllPublishersUrl=Tq;function Dq(e){return $m(e,Cl.DevResources)}S.getCrmDevResourcesUrl=Dq;function Iq(e,t=YC.crmBapSolutionId){return`${e}designer/app/${t}#/CreateNewApp`}S.getCrmAppDesignerUrl=Iq;function Oq(e){return`${e}apps`}S.getCrmMyAppsUrl=Oq;function Pq(e){return QC(e,"role")+"&forceUCI=0"}S.getCrmAdminSecurityRolesUrl=Pq;function Rq(e){return`${QC(e,"systemuser")}&forceclassic=1`}S.getCrmAdminSecurityUsersUrl=Rq;function QC(e,t){return`${e}main.aspx?pagetype=entitylist&etn=${t}`}function Lq(e,t){return`${e}main.aspx?appid=${t}`}S.getPlayAppModuleUrl=Lq;S.xrmApiUrl="api/data/v9.0";S.privilegesQueryUrls={systemUserInfo:e=>`${e}${S.xrmApiUrl}/WhoAmI`,userPrivileges:(e,t)=>`${e}${S.xrmApiUrl}/systemusers(${t})/Microsoft.Dynamics.CRM.RetrieveUserPrivileges`,systemPrivileges:e=>`${e}${S.xrmApiUrl}/privileges/Microsoft.Dynamics.CRM.RetrievePrivilegeSet`};function kq(e,t,r=YC.crmBapSolutionId){return`${e}designer/app/${r}/${t}/AppDesignerCanvas/${t}`}S.getAppModuleDesignerUrl=kq;function xq(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${r}%7d&extraqs=%26formId%3d%7b${t}%7d%26dashboardType%3d1030&pagetype=${`${n?"ic":""}dashboardeditor`}`}S.getDashboardDesignerUrl=xq;function $q(e,t,r){return`/e/${e}/s/${t}/dashboard/${r}`}S.getOpenModernDashboardUrl=$q;function Fq(e,t,r){let n=r!==void 0?r.toString():void 0;return`/e/${e}/s/${t}/dashboard/new${n?`/${n}`:""}`}S.getNewModernDashboardUrl=Fq;function Mq(e,t,r,n){let i=n!==void 0?n.toString():void 0;return`/e/${e}/s/${t}/n/${r}/dashboard/new${i?`/${i}`:""}`}S.getNewModernEntityDashboardUrl=Mq;function Uq(e,t,r,n){return`/e/${e}/s/${t}/n/${r}/dashboard/${n}`}S.getOpenModernEntityDashboardUrl=Uq;function Bq(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${t}%7d&extraqs=etc=${r||""}`+(n?`%26id=${n}`:"")+"&pagetype=vizdesigner"}S.getChartDesignerUrl=Bq;function qq(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}S.getProcessDesignerUrl=qq;function Vq(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}S.getProcessShareUrl=Vq;function Gq(e,t){return`${e}Tools/ProcessControl/UnifiedProcessDesigner.aspx?id=${t}`}S.getBusinessProcessFlowDesignerUrl=Gq;function Wq(e,t,r){return`${e}CRMReports/reportproperty.aspx?appSolutionId=%7b${r}%7d&disablePersonal=true&id=%7b${t}%7d`}S.getReportDesignerUrl=Wq;function zq(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`}S.getWebResourceDesignerUrl=zq;function jq(e,t){return`${e}WebResources/${t}`}S.getWebResourceFileUrl=jq;function Hq(e,t,r){return`${e}designer/sitemap/${r}/${t}/SiteMapHome/${t}`}S.getSiteMapDesignerUrl=Hq;function Kq(e,t,r){return`${e}connections/connectionroles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}S.getConnectionRoleDesignerUrl=Kq;function Jq(e,t,r){return`${e}tools/emailtemplateeditor/emailtemplateeditor.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}S.getEmailTemplateDesignerUrl=Jq;function Yq(e,t,r){return`${e}tools/mailmerge/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}S.getMailMergeTemplateDesignerUrl=Yq;function Qq(e,t,r){return`${e}biz/roles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}S.getSecurityRoleDesignerUrl=Qq;function Xq(e,t,r){return`${e}biz/fieldsecurityprofiles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}S.getFieldSecurityProfileDesignerUrl=Xq;function Zq(e,t,r){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?_CreateFromId=%7b${t}%7d&_CreateFromType=7100&appSolutionId=%7b${t}%7d&id=%7b${r}%7d`}S.getArticleTemplateUrl=Zq;function e3(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}`}S.getEnableSecurityRolesUrl=e3;function t3(e){return`${e}tools/publisher/edit.aspx`}S.getCreateNewPublisherUrl=t3;function r3(e,t){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?appSolutionId=${t}`}S.getCreateNewArticleTemplateUrl=r3;S.solutionComponentDefinitionsQueryUrl="api/data/v9.0/solutioncomponentdefinitions";S.entityDefinitionsQueryUrl="api/data/v9.0/EntityDefinitions?$select=EntitySetName,DisplayName,LogicalName&$filter=";S.workflowsQueryUrl="api/data/v9.0/workflows";S.chartsQueryUrl="/api/data/v9.0/savedqueryvisualizations";S.solutionComponentConfigurationsQueryUrl="/api/data/v9.1/solutioncomponentconfigurations?$filter=isdisplayable eq true&$select=name";S.solutionComponentSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentsummaries";S.solutionComponentCountSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentcountsummaries";function n3(e,t){return`${S.xrmApiUrl}/RetrieveRequiredComponents(ObjectId=${e},ComponentType=${t})`}S.getRequiredComponentsQueryUrl=n3;function i3(e,t){return`${S.cdsServiceUrl}${S.xrmApiUrl}/RetrieveDependentComponentsWithMetadata(ObjectId=${e},ComponentType=${t})`}S.getDependentComponentsWithMetadataQueryUrl=i3;S.solutionsQueryUrl="/api/data/v9.0/solutions?$expand=publisherid&$filter=(isvisible eq true)";function o3(e){return`/api/data/v9.0/solutions?$expand=publisherid&$filter=(uniquename eq '${e}')`}S.getSolutionsByUniqueNameQueryUrl=o3;function a3(e){return`/api/data/v9.0/solutions(${e})?$expand=publisherid`}S.getSolutionQueryUrl=a3;function s3(e){return`${e}api/data/v9.1/ProvisionLanguageForUser`}S.getProvisionLanguageUrl=s3;S.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 l3(e,t,r,n=!1,i=!1,o=!1,a=!1,s=!1,l=!1,u=!1){return`/api/data/v9.1/deploymentstageruns+`)),this.type=t,this.id=r,this.issues=u,this.pointer=(a=(o=u[0])===null||o===void 0?void 0:o.pointer)!==null&&a!==void 0?a:"",this.rule=(l=(s=u[0])===null||s===void 0?void 0:s.rule)!==null&&l!==void 0?l:"invalid"}};X.ValidationError=Wm;var zm=class extends _t{constructor(t){super("INVALID_ARGUMENT",t)}};X.InvalidArgumentError=zm;var jm=class extends _t{constructor(t,r,n,i="revalidated"){super("STALE_ARTIFACT",i==="pushed"?`Cannot apply the edit at ${n} to ${t}/${r}: a push made after this pointer's copy was read replaced the local copy with the record the server holds, which differs from that copy (ids and defaults the SDK filled in at save, a rewrite the platform made on save, or another writer's save), so the pointer may now identify a different node. Read the whole artifact (getArtifact), re-derive the pointer, and retry.`:`Cannot apply the edit at ${n} to ${t}/${r}: the cached copy was stale and the server copy has since changed, so any pointer derived from the old copy may now identify a different node. The local copy has been refreshed \u2014 re-read the artifact, re-derive the pointer, and retry.`),this.type=t,this.id=r,this.pointer=n,this.reason=i}};X.StaleArtifactError=jm;var Hm=class extends _t{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}};X.LocalEditsWouldBeLostError=Hm;var Km=class extends _t{constructor(t,r,n,i,o){super("VERSION_CONFLICT",`Version conflict for ${t}/${r}: local=${n??"(none)"}, server=${i??"(none)"}. Re-fetch and reapply changes.${o?` ${o}`:""}`),this.type=t,this.id=r,this.localEtag=n,this.serverEtag=i,this.detail=o}};X.VersionConflictError=Km;var Jm=class extends _t{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,Object.defineProperty(this,"cause",{value:i,enumerable:!1,writable:!1,configurable:!0})}};X.ConnectionError=Jm;function hq(e,t){return typeof e=="object"&&e!==null&&Object.defineProperty(e,"cause",{value:t,enumerable:!1,writable:!0,configurable:!0}),e}X.attachCause=hq;var Ym=class extends _t{constructor(t){super("WORKSPACE_NOT_INITIALIZED",`Workspace not initialized at ${t}. Call initWorkspace() first.`),this.workspacePath=t}};X.WorkspaceNotInitializedError=Ym;var Qm=class extends _t{constructor(t,r){super("WORKSPACE_ORG_MISMATCH",`This workspace belongs to ${t?`'${t}'`:"no recorded org"}, but this SDK targets '${r}'. Its local copies, baselines and cached metadata are that org's, so nothing was read or written. Use one workspace per org, or call cleanWorkspace() to discard this workspace's contents and bind it to '${r}'.`),this.workspaceInstanceUrl=t,this.instanceUrl=r}};X.WorkspaceOrgMismatchError=Qm;var Xm=class extends _t{constructor(t,r){super("NOT_IMPLEMENTED",`Operation '${t}' is not implemented yet${r?`: ${r}`:""}.`),this.operation=t}};X.NotImplementedError=Xm;var Zm=class extends _t{constructor(t,r){super("INVALID_JSON_POINTER",`Invalid JSON Pointer '${t}': ${r}`),this.pointer=t}};X.JsonPointerError=Zm;var eh=class extends _t{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}};X.AmbiguousArtifactError=eh;var th=class extends _t{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}};X.PathTraversalError=th;var rh=class extends _t{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}};X.IncompatibleWorkspaceError=rh});var oe=v(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.odataQuery=at.normalizeGuid=at.createSafeXmlElement=at.assertNoControlChars=at.assertODataName=at.assertXmlName=at.xmlText=at.odataPathLiteral=at.odataLiteral=void 0;var zc=Q();function rE(e){return String(e??"").replace(/'/g,"''")}at.odataLiteral=rE;function gq(e){return encodeURIComponent(rE(e))}at.odataPathLiteral=gq;function yq(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}at.xmlText=yq;function nE(e,t){let r=String(e??""),n=/^[A-Za-z_][0-9A-Za-z_.-]*$/,i=r.split(":");if(!(i.length<=2&&i.every(a=>n.test(a))&&!/^xmlns/i.test(r)))throw new zc.InvalidArgumentError(`${t} must be a valid XML element name (got '${e}')`);return e}at.assertXmlName=nE;function bq(e,t){let r=String(e??"");if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new zc.InvalidArgumentError(`${t} must be a valid OData identifier (letters, digits, underscore): got '${e}'`);return e}at.assertODataName=bq;function vq(e,t){if(/[\u0000-\u001F\u007F]/.test(String(e??"")))throw new zc.InvalidArgumentError(`${t} must not contain control characters (including CR/LF): they would inject additional lines into the request`);return e}at.assertNoControlChars=vq;function wq(e,t,r){return e.createElement(nE(t,r))}at.createSafeXmlElement=wq;var Cq=/^[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 Eq(e,t){let r=String(e??""),n=r.length===38&&r.startsWith("{")&&r.endsWith("}")?r.slice(1,-1):r;if(!Cq.test(n))throw new zc.InvalidArgumentError(`${t} must be a valid GUID (got '${e}')`);return n.toLowerCase()}at.normalizeGuid=Eq;function Aq(e){let t=[];for(let[r,n]of e)n!=null&&n!==""&&t.push(`${r}=${encodeURIComponent(String(n))}`);return t.length>0?`?${t.join("&")}`:""}at.odataQuery=Aq});var fe=v(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.nowIso=j.isAlreadyDeleted=j.deleteRecord=j.resendAppSearchIndexRace=j.resendDeadlockVictim=j.resendWhile=j.isAppSearchIndexRace=j.namesAppSearchIndexRace=j.isTransactionNotStarted=j.TRANSACTION_NOT_STARTED_CODE=j.LOCK_BACKOFF_MS=j.isConcurrencyLockRefusal=j.CONCURRENCY_LOCK_CODE=j.AMBIGUOUS_WRITE_STATUSES=j.DEADLOCK_BACKOFF_MS=j.isSqlDeadlockVictim=j.ensureSuccess=j.resolveCreatedId=j.requireCreatedId=j.withClientMintedId=j.readCreatedId=j.readRowEtag=j.readEtag=j.requireEtag=j.isVersionToken=j.echoWrite=j.UPDATE_NO_ETAG_CODE=j.VERSION_CONFLICT_CODE=void 0;var Ka=Q(),Ja=oe();j.VERSION_CONFLICT_CODE="VERSION_CONFLICT";j.UPDATE_NO_ETAG_CODE="ARTIFACT_UPDATE_NO_ETAG";function Sq(e,t){return{query:`?$select=${encodeURIComponent(e)}`,options:{headers:{...t??{},Prefer:"return=representation"}}}}j.echoWrite=Sq;function iE(e){return typeof e=="string"&&e.trim()!==""&&e.trim()!=="*"}j.isVersionToken=iE;function Nq(e,t,r){if(!iE(e))throw new Ka.SdkError(j.UPDATE_NO_ETAG_CODE,`Refusing to push ${t} '${r}': ${e?`the concurrency token held for it ('${e}') is not a version`:"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}j.requireEtag=Nq;function oE(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}j.readEtag=oE;async function _q(e,t,r,n){let i=`/${t}(${n})${(0,Ja.odataQuery)([["$select",r]])}`;return oE(ih(await e.get(i),e.apiUrl(i)))}j.readRowEtag=_q;function nh(e,t){var r;let n=e.body;if(n&&typeof n[t]=="string")return(0,Ja.normalizeGuid)(n[t],t);let i=(r=e.headers)!==null&&r!==void 0?r:{};for(let o of Object.keys(i))if(o.toLowerCase()==="odata-entityid"){let a=/\(([0-9a-fA-F-]{36})\)/.exec(i[o]);if(a)return(0,Ja.normalizeGuid)(a[1],t)}return null}j.readCreatedId=nh;function Tq(e,t,r){return r?{...e,[t]:(0,Ja.normalizeGuid)(r,t)}:e}j.withClientMintedId=Tq;function Dq(e,t,r){let n=nh(e,t);if(!n)throw new Ka.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`);return n}j.requireCreatedId=Dq;function Iq(e,t,r,n){let i=nh(e,t);if(i)return i;if(n)return(0,Ja.normalizeGuid)(n,t);throw new Ka.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`)}j.resolveCreatedId=Iq;function ih(e,t){if(e.status===412)throw new Ka.SdkError(j.VERSION_CONFLICT_CODE,`Version conflict (412) from ${t}`);if(e.status<200||e.status>=300)throw new Ka.ConnectionError(t,e.status,$q(e.body),e.body);return e}j.ensureSuccess=ih;function aE(e){if(e.status!==500||e.body===void 0||e.body===null)return!1;let t=typeof e.body=="string"?e.body:JSON.stringify(e.body);return/\bSql Number:\s*1205\b/i.test(t)}j.isSqlDeadlockVictim=aE;j.DEADLOCK_BACKOFF_MS=[1e3,2e3,4e3];j.AMBIGUOUS_WRITE_STATUSES=new Set([408,502,503,504]);j.CONCURRENCY_LOCK_CODE="0x80071151";function Oq(e){var t,r;if(e.status!==429)return!1;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return typeof n=="string"&&n.toLowerCase()===j.CONCURRENCY_LOCK_CODE}j.isConcurrencyLockRefusal=Oq;j.LOCK_BACKOFF_MS=[2e3,3e3,...Array.from({length:35},()=>5e3)];j.TRANSACTION_NOT_STARTED_CODE="0x80040251";function Pq(e){var t,r;if(e.status!==500)return!1;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return typeof n=="string"&&n.toLowerCase()===j.TRANSACTION_NOT_STARTED_CODE}j.isTransactionNotStarted=Pq;var Rq=/(?:^|[^a-z0-9_])AppModule_DVTableSearch_M365AppModuleId(?![a-z0-9_])/i;function sE(e){return Rq.test(e)&&/\bSql Number:\s*547\b/i.test(e)}j.namesAppSearchIndexRace=sE;function lE(e){return e.status!==400||e.body===void 0||e.body===null?!1:sE(typeof e.body=="string"?e.body:JSON.stringify(e.body))}j.isAppSearchIndexRace=lE;async function oh(e,t,r=j.DEADLOCK_BACKOFF_MS){for(let n=0;;n+=1){let i=await t();if(n>=r.length||!e(i))return i;await new Promise(o=>setTimeout(o,r[n]))}}j.resendWhile=oh;function Lq(e){return oh(aE,e,j.DEADLOCK_BACKOFF_MS)}j.resendDeadlockVictim=Lq;function kq(e){return oh(lE,e,j.DEADLOCK_BACKOFF_MS)}j.resendAppSearchIndexRace=kq;function $q(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 xq(e,t,r,n){let i=(0,Ja.normalizeGuid)(r,"id"),o=`/${t}(${i})`;ih(await e.delete(o,n?{headers:{"If-Match":n}}:void 0),e.apiUrl(o))}j.deleteRecord=xq;function Fq(e){return e instanceof Ka.ConnectionError&&e.statusCode===404}j.isAlreadyDeleted=Fq;function Mq(){return new Date().toISOString()}j.nowIso=Mq});var Tt=v(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});Ya.describeMalformedValue=Ya.collectPages=void 0;var uE=fe(),ah=Q();async function Uq(e,t,r,n,i){let o=[],a=new Set,s=e.apiUrl(t),l=(0,uE.ensureSuccess)(await e.get(t,i),s);for(n?.(l);;){let u=l.body,c=u?.value;if(!Array.isArray(c))throw new ah.ConnectionError(s,l.status,`${r}: paginated read returned a malformed page \u2014 expected an OData 'value' array but got ${sh(c)}; refusing to return partial results.`);for(let f of c)o.push(f);let d=u?.["@odata.nextLink"];if(d==null)break;if(typeof d!="string"||d.length===0)throw new ah.ConnectionError(s,l.status,`${r}: paginated read returned a malformed @odata.nextLink (${sh(d)}); cannot follow it, and refusing to return partial results.`);if(a.has(d))throw new ah.InvalidArgumentError(`${r}: aborting pagination \u2014 the server returned a repeated @odata.nextLink ('${d}'), which would loop indefinitely.`);a.add(d),s=d,l=(0,uE.ensureSuccess)(await e.getAbsolute(d,i),d)}return o}Ya.collectPages=Uq;function sh(e){return e===null?"null":e===void 0?"undefined (missing)":`a ${typeof e}`}Ya.describeMalformedValue=sh});var lh=v(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});Ho.assertWorkflowKind=Ho.WORKFLOW_KIND_MISMATCH_CODE=void 0;var jo=lo(),Bq=Q(),cE=fe(),qq=oe();Ho.WORKFLOW_KIND_MISMATCH_CODE="WORKFLOW_KIND_MISMATCH";var dE={[jo.WorkflowCategory.Workflow]:"classic workflow",[jo.WorkflowCategory.Dialog]:"dialog",[jo.WorkflowCategory.BusinessRule]:"business rule",[jo.WorkflowCategory.Action]:"custom action",[jo.WorkflowCategory.BusinessProcessFlow]:"business process flow",[jo.WorkflowCategory.Flow]:"cloud flow",[jo.WorkflowCategory.UIFlow]:"desktop flow"};async function Vq(e,t,r){var n,i;let o=`/workflows(${t})${(0,qq.odataQuery)([["$select","category"]])}`,a=await e.get(o);if(a.status===404)return null;(0,cE.ensureSuccess)(a,e.apiUrl(o));let s=(n=a.body)===null||n===void 0?void 0:n.category,l=typeof s=="number"?s:typeof s=="string"&&s!==""?Number(s):NaN;if(l!==r){let u=Number.isFinite(l)?`a ${(i=dE[l])!==null&&i!==void 0?i:"process"} (category ${l})`:"a process whose category could not be read";throw new Bq.SdkError(Ho.WORKFLOW_KIND_MISMATCH_CODE,`Refusing to delete workflow '${t}' as a ${dE[r]}: it is ${u}. Nothing was changed. Check the id.`)}return(0,cE.readEtag)(a)}Ho.assertWorkflowKind=Vq});var ch=v(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.deleteWorkflowResending=on.isWorkflowDeleteUnsettled=on.failedAfterResend=on.WORKFLOW_DELETE_UNSETTLED_CODE=void 0;var $l=Q(),_i=fe(),pE=oe();on.WORKFLOW_DELETE_UNSETTLED_CODE="WORKFLOW_DELETE_UNSETTLED";var mE=new WeakSet;function uh(e){return typeof e=="object"&&e!==null&&mE.add(e),e}function Gq(e){return typeof e=="object"&&e!==null&&mE.has(e)}on.failedAfterResend=Gq;function Wq(e){return e instanceof $l.SdkError&&e.code===on.WORKFLOW_DELETE_UNSETTLED_CODE}on.isWorkflowDeleteUnsettled=Wq;function zq(e,t){try{(0,_i.ensureSuccess)(e,t)}catch(r){return r}}function jq(e){return(0,_i.isSqlDeadlockVictim)(e)?"lost a SQL deadlock (HTTP 500, Sql Number 1205)":`lost its transaction (HTTP 500 ${_i.TRANSACTION_NOT_STARTED_CODE})`}async function fE(e,t){try{return(await e.get(`/workflows(${t})${(0,pE.odataQuery)([["$select","workflowid"]])}`)).status===404}catch{return!1}}async function Hq(e,t,{bindingToken:r,kindName:n,deactivated:i=!1,resendDeadlockVictim:o=!1,ifMatchOnFirst:a=!1}){let s=(0,pE.normalizeGuid)(t,"id");if(a&&!r)throw new $l.InvalidArgumentError(`Refusing to delete ${n} '${s}': its delete must be conditional on a token this operation holds, and it holds none.`);let l=`/workflows(${s})`,u=e.apiUrl(l),c=p=>(0,_i.isTransactionNotStarted)(p)||o&&(0,_i.isSqlDeadlockVictim)(p),d=0,f,m;try{m=await(0,_i.resendWhile)(c,async()=>{d+=1;let p=d>1||a,h=await e.delete(l,p?{headers:{"If-Match":r}}:void 0);return f=f??h,h},r?_i.DEADLOCK_BACKOFF_MS:[])}catch(p){if(p instanceof $l.ConnectionError&&p.statusCode===0&&r&&await fE(e,s))return;throw d>1?uh(p):p}if(!(d>1&&m.status===404)){if(d>1&&m.status===412){let p=jq(f),h=new $l.SdkError(on.WORKFLOW_DELETE_UNSETTLED_CODE,`Deleting ${n} '${s}' ${p}, and its re-send was refused (HTTP 412): the row at that id is no longer the version this delete checked \u2014 it was edited, or deleted and re-created at the same id \u2014 so nothing more was deleted. `+(i?"This delete had deactivated the process first and has NOT re-activated it: it MAY be left DISABLED. ":"")+"Read the row before deleting it again.");throw uh((0,$l.attachCause)(h,zq(f,u)))}if(!(r&&_i.AMBIGUOUS_WRITE_STATUSES.has(m.status)&&await fE(e,s)))try{(0,_i.ensureSuccess)(m,u)}catch(p){throw d>1?uh(p):p}}}on.deleteWorkflowResending=Hq});var dh=v(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.businessRuleApi=Hn.BUSINESS_RULE_LEFT_DEACTIVATED_CODE=Hn.WFOM_API_UNAVAILABLE_CODE=void 0;var jn=lo(),Kq=Tt(),Jq=lh(),Yq=ch(),Kt=fe(),Ti=oe(),Hc=Q();Hn.WFOM_API_UNAVAILABLE_CODE="BUSINESS_RULE_API_UNAVAILABLE";Hn.BUSINESS_RULE_LEFT_DEACTIVATED_CODE="BUSINESS_RULE_LEFT_DEACTIVATED";async function hE(e,t,r,n){let i=`/workflows(${Zq})/Microsoft.Dynamics.CRM.${t}`;try{return(0,Kt.ensureSuccess)(await e.post(i,{Entity:r.Entity,WfomJson:r.WfomJson},{headers:n}),e.apiUrl(i))}catch(o){throw o?.statusCode!==404?o:new Hc.SdkError(Hn.WFOM_API_UNAVAILABLE_CODE,`Business-rule authoring (preview) is not enabled on this environment yet: it does not expose 'Microsoft.Dynamics.CRM.${t}'. The bound members are still rolling out, so re-check once the release flag reaches this environment. Nothing was written. The SDK does NOT fall back to generating workflow XAML: that covered only 4 of the 7 action types and would silently save a rule different from the one you wrote.`)}}async function Qq(e,t){let r=`/workflows(${t})${(0,Ti.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,Kt.readEtag)(n),statecode:typeof i?.statecode=="number"?i.statecode:null,statuscode:typeof i?.statuscode=="number"?i.statuscode:null}}catch{return null}}async function Xq(e,t,r){let n=await Qq(e,t);if(n===null||n.etag===null)throw new Hc.SdkError(Kt.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 Hc.SdkError(Kt.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 Zq="00000000-0000-0000-0000-000000000000",jc={"Content-Type":"application/json",Accept:"application/json","OData-Version":"4.0","OData-MaxVersion":"4.0"},e3="workflowid,name,description,primaryentity,statecode,category,type",t3="category eq 2 and type eq 1";async function gE(e,t,r){var n;if(r==="Draft")return null;let i=(0,Ti.normalizeGuid)(t,"workflowid"),o=r==="Active",a={statecode:o?jn.StateCode.Activated:jn.StateCode.Draft,statuscode:o?jn.StatusCode.Activated:jn.StatusCode.Draft},s=`/workflows(${i})`,l=(0,Kt.ensureSuccess)(await e.patch(s,a,{headers:jc}),e.apiUrl(s));return(n=(0,Kt.readEtag)(l))!==null&&n!==void 0?n:await xl(e,i)}async function xl(e,t){let r=`/workflows(${t})${(0,Ti.odataQuery)([["$select","workflowid"]])}`;try{let n=await e.get(r);return n.status>=200&&n.status<300?(0,Kt.readEtag)(n):null}catch{return null}}async function r3(e,t,r){let n=await xl(e,t),i=await r(),o=(0,Kt.readEtag)(i);if(o)return{response:i,etag:o};let a=await xl(e,t);return{response:i,etag:n!==null&&n===a?a:null}}Hn.businessRuleApi={async get(e,t){let r=(0,Ti.normalizeGuid)(t,"id"),n=`/workflows(${r})/Microsoft.Dynamics.CRM.RetrieveProcessWithWfomJson`,{response:i,etag:o}=await r3(e,r,async()=>(0,Kt.ensureSuccess)(await e.get(n),e.apiUrl(n)));return{raw:i.body,etag:o}},async list(e,t){let r=[t3];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,Ti.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,Ti.odataQuery)([["$select",e3],["$filter",r.join(" and ")]])}`;return(await(0,Kq.collectPages)(e,n,"listArtifacts('businessRule')")).map(o=>{var a,s;return{type:"businessRule",id:(a=o.workflowid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",entityLogicalName:o.primaryentity,isDirty:!1}})},async create(e,t){var r;let n=t,i=(0,Ti.normalizeGuid)(n.Entity.workflowid,"workflowid"),o=await hE(e,"CreateProcessWithWfomJson",n,jc),a=(0,Kt.resolveCreatedId)(o,"workflowid","business rule",i),s=null;try{s=await gE(e,a,n.status)}catch(l){try{await(0,Kt.deleteRecord)(e,"workflows",a)}catch{}throw l}return{id:a,etag:(r=s??(0,Kt.readEtag)(o))!==null&&r!==void 0?r:await xl(e,a)}},async update(e,t,r,n){var i,o;let a=r,s=(0,Ti.normalizeGuid)(t,"id"),l=`/workflows(${s})`,u={...jc,"If-Match":(0,Kt.requireEtag)(n,"business rule",s)},c=await Xq(e,s,u["If-Match"]),d=c.statecode===jn.StateCode.Activated;d&&(0,Kt.ensureSuccess)(await e.patch(l,{statecode:jn.StateCode.Draft,statuscode:jn.StatusCode.Draft},{headers:u}),e.apiUrl(l));let f;try{f=await hE(e,"UpdateProcessWithWfomJson",a,u)}catch(p){if(d)try{(0,Kt.ensureSuccess)(await e.patch(l,{statecode:jn.StateCode.Activated,statuscode:(i=c.statuscode)!==null&&i!==void 0?i:jn.StatusCode.Activated},{headers:jc}),e.apiUrl(l))}catch(h){throw new Hc.SdkError(Hn.BUSINESS_RULE_LEFT_DEACTIVATED_CODE,`The business-rule write failed AND the rule could not be re-activated, so '${s}' is left DEACTIVATED (Draft) on the server. Re-activate it before relying on it. Original write failure: ${p instanceof Error?p.message:String(p)}. Restore failure: ${h instanceof Error?h.message:String(h)}`)}throw p}let m=await gE(e,s,a.status);return{id:s,etag:(o=m??(0,Kt.readEtag)(f))!==null&&o!==void 0?o:await xl(e,s)}},async delete(e,t){let r=(0,Ti.normalizeGuid)(t,"id"),n=await(0,Jq.assertWorkflowKind)(e,r,jn.WorkflowCategory.BusinessRule);return(0,Yq.deleteWorkflowResending)(e,r,{bindingToken:n,kindName:"business rule"})}}});var jr=v(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.publishBoundEntity=st.boundEntityPublishScope=st.publishGenPageById=st.publishDashboardById=st.publishWebResourceById=st.publishEntity=st.publishAppModule=st.publishAllXml=st.publishXml=void 0;var Kc=fe(),Fl=oe(),yE="/PublishXml";async function Qa(e,t){(0,Kc.ensureSuccess)(await(0,Kc.resendDeadlockVictim)(()=>e.post(yE,{ParameterXml:t})),e.apiUrl(yE))}st.publishXml=Qa;var bE="/PublishAllXml";async function n3(e){(0,Kc.ensureSuccess)(await(0,Kc.resendDeadlockVictim)(()=>e.post(bE,{})),e.apiUrl(bE))}st.publishAllXml=n3;function i3(e,t){return Qa(e,`<importexportxml><appmodules><appmodule>${(0,Fl.xmlText)(t)}</appmodule></appmodules></importexportxml>`)}st.publishAppModule=i3;function vE(e,t){return Qa(e,`<importexportxml><entities><entity>${(0,Fl.xmlText)(t)}</entity></entities></importexportxml>`)}st.publishEntity=vE;function o3(e,t){return Qa(e,`<importexportxml><webresources><webresource>${(0,Fl.xmlText)(t)}</webresource></webresources></importexportxml>`)}st.publishWebResourceById=o3;function a3(e,t){return Qa(e,`<importexportxml><dashboards><dashboard>${(0,Fl.xmlText)(t)}</dashboard></dashboards></importexportxml>`)}st.publishDashboardById=a3;function s3(e,t){return Qa(e,`<importexportxml><uxagentprojects><uxagentproject>${(0,Fl.xmlText)(t)}</uxagentproject></uxagentprojects></importexportxml>`)}st.publishGenPageById=s3;function l3(e){let t=e?.entityLogicalName;return t?{envelope:"entity",entityLogicalName:t,blastRadiusWarning:"ENTITY_ENVELOPE_ALSO_SHIPS_UNRELATED_UNPUBLISHED_CHANGES"}:{envelope:"entity"}}st.boundEntityPublishScope=l3;function u3(e,t){let r=t?.entityLogicalName;return r?vE(e,r):Promise.resolve()}st.publishBoundEntity=u3});var Xa=v(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});Yc.JsonPointer=void 0;var Hr=Q(),Jc=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 Hr.JsonPointerError(t,'non-empty pointers must start with "/"');return t.substring(1).split("/").map(r=>{if(/~(?![01])/.test(r))throw new Hr.JsonPointerError(t,`invalid '~' escape in token '${r}' (expected ~0 or ~1)`);return e.decodeToken(r)})}static compile(t){return t.length===0?"":"/"+t.map(r=>e.encodeToken(r)).join("/")}static resolve(t,r){let n=e.parse(r),i=t;for(let o of n)if(Array.isArray(i)){let a=e.toArrayIndex(o,i.length);if(a===void 0)return;i=i[a]}else if(i!==null&&typeof i=="object"){let a=i;if(e.isReservedToken(o)||!Object.prototype.hasOwnProperty.call(a,o))return;i=a[o]}else return;return i}static set(t,r,n){let i=e.parse(r);if(i.length===0)throw new Hr.JsonPointerError(r,"cannot set the document root");let{parent:o,lastToken:a}=e.resolveParent(t,i,r);if(Array.isArray(o)){let s=e.toArrayIndex(a,o.length);if(s===void 0)throw new Hr.JsonPointerError(r,`'${a}' is not a valid array index`);if(s>o.length)throw new Hr.JsonPointerError(r,`array index '${a}' is out of range`);o[s]=n}else{if(e.isReservedToken(a))throw new Hr.JsonPointerError(r,`refusing to write reserved property '${a}'`);o[a]=n}}static remove(t,r){let n=e.parse(r);if(n.length===0)throw new Hr.JsonPointerError(r,"cannot remove the document root");let{parent:i,lastToken:o}=e.resolveParent(t,n,r);if(Array.isArray(i)){let a=e.toArrayIndex(o,i.length);if(a===void 0||a>=i.length)throw new Hr.JsonPointerError(r,`array index '${o}' is out of range`);i.splice(a,1)}else{if(e.isReservedToken(o))throw new Hr.JsonPointerError(r,`refusing to remove reserved property '${o}'`);delete i[o]}}static add(t,r,n,i){let o=e.parse(r);if(o.length>0&&o[o.length-1]==="-"){let l=e.compile(o.slice(0,-1)),u=e.resolve(t,l);if(!Array.isArray(u))throw new Hr.JsonPointerError(r,"add target must be an array");u.push(n);return}let a=e.resolve(t,r);if(!Array.isArray(a))throw new Hr.JsonPointerError(r,"add target must be an array");let s=i===void 0?a.length:i;if(s<0||s>a.length)throw new Hr.JsonPointerError(r,`insert index ${s} is out of range`);a.splice(s,0,n)}static parent(t){let r=e.parse(t);return r.pop(),e.compile(r)}static lastToken(t){let r=e.parse(t);return r.length===0?"":r[r.length-1]}static append(t,r){return`${t}/${e.encodeToken(String(r))}`}static resolveParent(t,r,n){let i=r[r.length-1],o=e.compile(r.slice(0,-1)),a=e.resolve(t,o);if(a===null||typeof a!="object")throw new Hr.JsonPointerError(n,"parent path does not resolve to an object or array");return{parent:a,lastToken:i}}static toArrayIndex(t,r){if(t==="-")return r;if(/^(0|[1-9][0-9]*)$/.test(t))return Number(t)}};Yc.JsonPointer=Jc;Jc.RESERVED_TOKENS=new Set(["__proto__","prototype","constructor"])});var CE=v(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});Qc.findElements=void 0;var wE=Xa();function c3(e,t){let r=[];return fh(e,"",t,r),r}Qc.findElements=c3;function fh(e,t,r,n){if(!(e===null||typeof e!="object"))if(r(e,t)&&n.push({pointer:t,value:e}),Array.isArray(e))e.forEach((i,o)=>{fh(i,wE.JsonPointer.append(t,o),r,n)});else for(let i of Object.keys(e))fh(e[i],wE.JsonPointer.append(t,i),r,n)}});var ph=v(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.assertMutationResult=Kn.assertExistsResult=Kn.assertReadResult=Kn.assertStorageContract=void 0;var d3=["readText","writeTextAtomic","deleteFile","deleteByPrefix"],f3=["ensureContainer","exists"];function p3(e){if(typeof e!="object"||e===null)throw new Error("workspaceStorage must be an object implementing WorkspaceStorage.");for(let t of d3)if(typeof e[t]!="function")throw new Error(`workspaceStorage is missing the required method '${t}'.`);for(let t of f3){let r=e[t];if(r!==void 0&&typeof r!="function")throw new Error(`workspaceStorage.${t} must be a function when present.`)}return e}Kn.assertStorageContract=p3;function m3(e,t){if(e===null||typeof e=="string")return e;throw new Error(`workspaceStorage.readText must resolve to a string or null for ${t}; got ${typeof e}. Absence is null \u2014 resolving undefined would make a present value look absent.`)}Kn.assertReadResult=m3;function h3(e,t){if(typeof e=="boolean")return e;throw new Error(`workspaceStorage.exists must resolve to a boolean for ${t}; got ${typeof e}. A truthy non-boolean would make an absent value look present.`)}Kn.assertExistsResult=h3;function g3(e,t){if(e!==void 0)throw new Error(`workspaceStorage.${t} must resolve to undefined; got ${typeof e}. A status-returning implementation would let a failed write be reported as a completed one.`)}Kn.assertMutationResult=g3});var mh=v(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});Za.retryTransientIoAsync=Za.retryTransientIo=void 0;var y3=new Set(["EPERM","EACCES","EBUSY","UNKNOWN"]),b3=5,EE=10;function v3(e){for(let t=1;;t+=1)try{return e()}catch(r){if(!AE(r,t))throw r;C3(EE*t)}}Za.retryTransientIo=v3;async function w3(e){for(let t=1;;t+=1)try{return await e()}catch(r){if(!AE(r,t))throw r;await new Promise(n=>setTimeout(n,EE*t))}}Za.retryTransientIoAsync=w3;function AE(e,t){let r=e.code;return t<b3&&!!r&&y3.has(r)}function C3(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{let t=Date.now()+e;for(;Date.now()<t;);}}});var DE=v(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});Kr.canonicalArtifactId=Kr.WorkspaceManager=Kr.WORKSPACE_SCHEMA_VERSION=Kr.retryTransientIo=void 0;var Jt=ph(),Jn=Q(),E3=mh();Object.defineProperty(Kr,"retryTransientIo",{enumerable:!0,get:function(){return E3.retryTransientIo}});function SE(e){let t=e;return typeof t.pathFor=="function"&&typeof t.getRoot=="function"?e:null}Kr.WORKSPACE_SCHEMA_VERSION=1;var uo={form:"forms",view:"views",businessRule:"business-rules",app:"apps",command:"commands",chart:"charts",dashboard:"dashboards",genPage:"gen-pages",bpf:"business-process-flows"},A3="manifest.json",es=".metadata",hh="entities";function NE(e){try{return Promise.resolve(e())}catch(t){return Promise.reject(t)}}function gh(e){if(e.schemaVersion!==void 0&&e.schemaVersion>Kr.WORKSPACE_SCHEMA_VERSION)throw new Jn.IncompatibleWorkspaceError(e.schemaVersion,Kr.WORKSPACE_SCHEMA_VERSION)}function _E(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xc(e){return e.trim().toLowerCase().replace(/\/+$/,"")}var yh=class{withManifest(t){let r=this.manifestQueue.then(t,t);return this.manifestQueue=r.then(()=>{},()=>{}),r}constructor(t,r,n){if(this.workspaceLabel=t,this.instanceUrl=r,this.manifestQueue=Promise.resolve(),this.bound=!1,n==null)throw new Error("WorkspaceManager requires a WorkspaceStorage. Node callers can build one with `createNodeWorkspaceStorage(path)` from '@maker-studio/cds-maker-sdk/node'.");this.storage=n}artifactKey(t,r){return this.assertSafeId(r),[uo[t],`${Ml(r)}.json`]}metaKey(t,r){return this.assertSafeId(r),[es,uo[t],`${Ml(r)}.meta.json`]}entityKey(t){return this.assertSafeId(t),[es,hh,`${t.toLowerCase()}.json`]}fsStore(){let t=SE(this.storage);if(!t)throw new Error("This workspace is not filesystem-backed, so it has no physical paths. Use the artifact/metadata/manifest accessors instead of the path helpers.");return t}getRoot(){let t=SE(this.storage);return t?t.getRoot():this.workspaceLabel}getArtifactDir(t){return this.fsStore().pathFor([uo[t]])}getArtifactFilePath(t,r){return this.fsStore().pathFor(this.artifactKey(t,r))}getMetaFilePath(t,r){return this.fsStore().pathFor(this.metaKey(t,r))}getEntityMetaFilePath(t){return this.fsStore().pathFor(this.entityKey(t))}assertSafeId(t){if(typeof t!="string"||t.length===0||/[\u0000-\u001f]/.test(t)||t.includes("/")||t.includes("\\")||t.includes(":")||t==="."||t===".."||t.includes(".."))throw new Jn.PathTraversalError(String(t),this.workspaceLabel)}get manifestKey(){return[A3]}assertDataKey(t,r){if(!Array.isArray(t)||t.length<2)throw new Jn.InvalidArgumentError(`${r} writes only inside the workspace's folders; '${String(t)}' is at its root, where only the manifest lives \u2014 and the manifest is changed only by the workspace itself.`);t.forEach(n=>this.assertSafeId(n))}async init(){let t=await this.withManifest(async()=>{let r=await this.readStoredManifest();return r.present&&this.assertBoundHere(r.value),r.present});await this.ensureLayout(),t||await this.withManifest(async()=>{let r=await this.readStoredManifest();if(r.present){this.assertBoundHere(r.value);return}let n={instanceUrl:this.instanceUrl,createdAt:new Date().toISOString(),artifacts:[]};await this.writeManifest(n)}),this.bound=!0}async readStoredManifest(){let t=(0,Jt.assertReadResult)(await this.storage.readText(this.manifestKey),"manifest.json");return t===null?{present:!1}:{present:!0,value:JSON.parse(t)}}async ensureLayout(){if(!this.storage.ensureContainer)return;let t=this.storage.ensureContainer.bind(this.storage),r=[[es,hh]];for(let i of Object.keys(uo))r.push([uo[i]],[es,uo[i]]);let n=await Promise.allSettled(r.map(i=>NE(()=>t(i))));for(let i of n){if(i.status==="rejected")throw i.reason;(0,Jt.assertMutationResult)(i.value,"ensureContainer")}}async isInitialized(){return this.storage.exists?(0,Jt.assertExistsResult)(await this.storage.exists(this.manifestKey),"manifest.json"):(0,Jt.assertReadResult)(await this.storage.readText(this.manifestKey),"manifest.json")!==null}async ensureInitialized(){if(!this.bound){await this.verifyBinding();return}if(!await this.isInitialized())throw new Jn.WorkspaceNotInitializedError(this.workspaceLabel)}async ensureReady(){await this.ensureInitialized()}async ensureBound(){this.bound||await this.verifyBinding()}verifyBinding(){if(!this.verifying){let t=()=>{this.verifying=void 0};this.verifying=this.readAndCheckBinding().then(t,r=>{throw t(),r})}return this.verifying}async readAndCheckBinding(){let t=await this.readStoredManifest();if(!t.present)throw new Jn.WorkspaceNotInitializedError(this.workspaceLabel);this.assertBoundHere(t.value),this.bound=!0}assertBoundHere(t){if(!_E(t))throw new Jn.WorkspaceOrgMismatchError("",this.instanceUrl);gh(t);let r=typeof t.instanceUrl=="string"?t.instanceUrl.trim():"",n=Xc(r);if(!n||n!==Xc(this.instanceUrl))throw new Jn.WorkspaceOrgMismatchError(r,this.instanceUrl)}async clean(){let t=await this.readStoredManifest();if(!t.present||!_E(t.value))throw new Jn.WorkspaceNotInitializedError(this.workspaceLabel);let r=t.value;gh(r);let n=Object.keys(uo).map(o=>[uo[o]]);n.push([es]);let i=await Promise.allSettled(n.map(o=>NE(()=>this.storage.deleteByPrefix(o))));for(let o of i){if(o.status==="rejected")throw o.reason;(0,Jt.assertMutationResult)(o.value,"deleteByPrefix")}await this.ensureLayout(),await this.withManifest(()=>this.writeManifest({...r,instanceUrl:this.instanceUrl,artifacts:[],lastSyncAt:void 0})),this.bound=!0}async readArtifact(t,r){return await this.ensureInitialized(),this.readJsonUnchecked(this.artifactKey(t,r))}async readArtifactWithText(t,r){await this.ensureInitialized();let n=this.artifactKey(t,r),i=(0,Jt.assertReadResult)(await this.storage.readText(n),n.join("/"));return i===null?null:{artifact:JSON.parse(i),text:i}}async writeArtifact(t,r,n,i){await this.ensureInitialized();let o=TE(n);if(i!==void 0&&o===i){await this.upsertManifestEntry(t,r,n,{unlessCurrent:!0});return}(0,Jt.assertMutationResult)(await this.storage.writeTextAtomic(this.artifactKey(t,r),o),"writeTextAtomic"),await this.upsertManifestEntry(t,r,n)}async deleteArtifact(t,r){await this.ensureInitialized(),(0,Jt.assertMutationResult)(await this.storage.deleteFile(this.artifactKey(t,r)),"deleteFile"),(0,Jt.assertMutationResult)(await this.storage.deleteFile(this.metaKey(t,r)),"deleteFile");let n=Ml(r);await this.withManifest(async()=>{let i=await this.getManifest();i.artifacts=i.artifacts.filter(o=>!(o.type===t&&o.id===n)),await this.writeManifest(i)})}async readMeta(t,r){return await this.ensureBound(),this.readJsonUnchecked(this.metaKey(t,r))}async writeMeta(t,r,n){await this.ensureBound(),await this.writeJsonUnchecked(this.metaKey(t,r),n)}async listArtifacts(t,r){return await this.ensureInitialized(),(await this.getManifest()).artifacts.filter(n=>!(t&&n.type!==t||r?.entityLogicalName&&n.entityLogicalName!==r.entityLogicalName))}async readEntityMetadata(t){await this.ensureInitialized();let r=await this.readJsonUnchecked(this.entityKey(t));return!r||typeof r.schemaName!="string"||typeof r.primaryNameAttribute!="string"||typeof r.primaryIdAttribute!="string"||typeof r.isCustomEntity!="boolean"?null:r}async writeEntityMetadata(t,r){await this.ensureInitialized(),await this.writeJsonUnchecked(this.entityKey(t),r)}async dropEntityMetadata(t){if(await this.ensureInitialized(),t===void 0){(0,Jt.assertMutationResult)(await this.storage.deleteByPrefix([es,hh]),"deleteByPrefix");return}(0,Jt.assertMutationResult)(await this.storage.deleteFile(this.entityKey(t)),"deleteFile")}async getManifest(){await this.ensureInitialized();let t=await this.readJsonUnchecked(this.manifestKey);if(!t)throw new Jn.WorkspaceNotInitializedError(this.workspaceLabel);return gh(t),t}async writeManifest(t){await this.writeJsonUnchecked(this.manifestKey,{...t,schemaVersion:Kr.WORKSPACE_SCHEMA_VERSION})}async updateManifest(t){await this.withManifest(async()=>{let r=await this.getManifest();if(t.instanceUrl!==void 0&&Xc(String(t.instanceUrl))!==Xc(r.instanceUrl))throw new Jn.InvalidArgumentError("updateManifest cannot change the workspace's org: it is bound to the org it was created for. cleanWorkspace() discards its contents and binds it to the org of the SDK that calls it.");await this.writeManifest({...r,...t,instanceUrl:r.instanceUrl})})}async upsertManifestEntry(t,r,n,i={}){await this.withManifest(async()=>{let o=await this.getManifest(),a=Ml(r),s=n,l=typeof s.name=="string"?s.name:`${t}:${a}`,u=typeof s.entityLogicalName=="string"?s.entityLogicalName:void 0,c=o.artifacts.find(d=>d.type===t&&d.id===a);i.unlessCurrent&&c?.name===l&&c.entityLogicalName===u||(c?(c.name=l,c.entityLogicalName=u):o.artifacts.push({type:t,id:a,name:l,entityLogicalName:u,isDirty:!1}),await this.writeManifest(o))})}async readJson(t){return await this.ensureBound(),this.readJsonUnchecked(t)}async writeJson(t,r){this.assertDataKey(t,"writeJson"),await this.ensureBound(),await this.writeJsonUnchecked(t,r)}async removeFile(t){this.assertDataKey(t,"removeFile"),await this.ensureBound(),(0,Jt.assertMutationResult)(await this.storage.deleteFile(t),"deleteFile")}async exists(t){return await this.ensureBound(),this.storage.exists?(0,Jt.assertExistsResult)(await this.storage.exists(t),t.join("/")):(0,Jt.assertReadResult)(await this.storage.readText(t),t.join("/"))!==null}async readJsonUnchecked(t){let r=(0,Jt.assertReadResult)(await this.storage.readText(t),t.join("/"));return r===null?null:JSON.parse(r)}async writeJsonUnchecked(t,r){(0,Jt.assertMutationResult)(await this.storage.writeTextAtomic(t,TE(r)),"writeTextAtomic")}};Kr.WorkspaceManager=yh;function TE(e){return`${JSON.stringify(e,null,2)}+`}function Ml(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()}Kr.canonicalArtifactId=Ml});var bh=v(ts=>{"use strict";Object.defineProperty(ts,"__esModule",{value:!0});ts.deepEqual=ts.deepDiff=void 0;var S3=Xa();function N3(e,t){let r=[];return OE(e,t,"",r,0),r}ts.deepDiff=N3;var Zc=Symbol("missing"),ed=512;function OE(e,t,r,n,i){if(e===t)return;if(i>ed)throw new RangeError(`deepDiff exceeded the maximum supported depth of ${ed}`);let o=td(e),a=td(t);if(o&&a&&Array.isArray(e)===Array.isArray(t)){let s=_3(e,t);for(let l of s){let u=IE(e,l),c=IE(t,l),d=S3.JsonPointer.append(r,l);u===Zc?n.push({pointer:d,type:"added",newValue:c}):c===Zc?n.push({pointer:d,type:"removed",oldValue:u}):OE(u,c,d,n,i+1)}return}PE(e,t)||n.push({pointer:r,type:"modified",oldValue:e,newValue:t})}function td(e){return e!==null&&typeof e=="object"}function _3(e,t){if(Array.isArray(e)&&Array.isArray(t)){let n=Math.max(e.length,t.length),i=[];for(let o=0;o<n;o++)i.push(String(o));return i}let r=new Set([...Object.keys(e),...Object.keys(t)]);return Array.from(r)}function IE(e,t){if(Array.isArray(e)){let r=Number(t);return r<e.length?e[r]:Zc}return t in e?e[t]:Zc}function PE(e,t){return RE(e,t,0)}ts.deepEqual=PE;function RE(e,t,r){if(e===t)return!0;if(r>ed)throw new RangeError(`deepEqual exceeded the maximum supported depth of ${ed}`);if(!td(e)||!td(t)||Array.isArray(e)!==Array.isArray(t))return!1;let n=Object.keys(e),i=Object.keys(t);return n.length!==i.length?!1:n.every(o=>o in t&&RE(e[o],t[o],r+1))}});var kE=v(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});rs.VersionManager=rs.PROJECTION_VERSION=void 0;var LE=bh(),T3=fe();rs.PROJECTION_VERSION=8;var vh=class{constructor(t){this.workspace=t}async storeMeta(t,r,n,i){var o;let a=i===void 0?await this.getMeta(t,r):i,s=((o=n.snapshot)===null||o===void 0?void 0:o.status)==="Active",l=a?.everActivated===!0||s;await this.workspace.writeMeta(t,r,l?{...n,everActivated:l}:n)}async getMeta(t,r){return this.workspace.readMeta(t,r)}async isDirty(t,r,n){let i=await this.workspace.readArtifact(t,r);if(i===null)return!1;let o=n===void 0?await this.getMeta(t,r):n;return o?!(0,LE.deepEqual)(o.snapshot,i):!0}async diff(t,r){let n=await this.workspace.readArtifact(t,r),i=await this.getMeta(t,r),o;return n===null?o=i?[{pointer:"",type:"removed",oldValue:i.snapshot}]:[]:i?o=(0,LE.deepDiff)(i.snapshot,n):o=[{pointer:"",type:"added",newValue:n}],{artifactType:t,artifactId:r,changes:o}}async checkConflict(t,r,n){let i=await this.getMeta(t,r);return!i||!(0,T3.isVersionToken)(i.etag)?!0:i.etag!==n}};rs.VersionManager=vh});var xE=v((wh,$E)=>{(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof wh=="object"?$E.exports=t():e.compareVersions=t()})(wh,function(){var e=/^v?(?:\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+))?(?:-[\da-z\-]+(?:\.[\da-z\-]+)*)?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;function t(o,a){return o.indexOf(a)===-1?o.length:o.indexOf(a)}function r(o){var a=o.replace(/^v/,"").replace(/\+.*$/,""),s=t(a,"-"),l=a.substring(0,s).split(".");return l.push(a.substring(s+1)),l}function n(o){return isNaN(Number(o))?o:Number(o)}function i(o){if(typeof o!="string")throw new TypeError("Invalid argument expected string");if(!e.test(o))throw new Error("Invalid argument not valid semver ('"+o+"' received)")}return function(a,s){[a,s].forEach(i);for(var l=r(a),u=r(s),c=0;c<Math.max(l.length-1,u.length-1);c++){var d=parseInt(l[c]||0,10),f=parseInt(u[c]||0,10);if(d>f)return 1;if(f>d)return-1}var m=l[l.length-1],p=u[u.length-1];if(m&&p){var h=m.split(".").map(n),g=p.split(".").map(n);for(c=0;c<Math.max(h.length,g.length);c++){if(h[c]===void 0||typeof g[c]=="string"&&typeof h[c]=="number")return-1;if(g[c]===void 0||typeof h[c]=="string"&&typeof g[c]=="number"||h[c]>g[c])return 1;if(g[c]>h[c])return-1}}else if(m||p)return m?-1:1;return 0}})});var qE=v(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.EnvironmentFlowHostingType=Je.EnvironmentDisableReasonCode=Je.EnvironmentMigrationConstants=Je.EnvironmentProvisioningStates=Je.EnvironmentLocations=Je.EnvironmentCreationTypeConstants=Je.EnvironmentType=Je.EnvironmentSkuConstants=Je.environmentPermissions=Je.DatabaseType=void 0;var FE;(function(e){e.CommonDataService="CommonDataService",e.None="None"})(FE||(Je.DatabaseType=FE={}));Je.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"};Je.EnvironmentSkuConstants={NotSpecified:"NotSpecified",Standard:"Standard",Premium:"Premium",Developer:"Developer",Basic:"Basic",Production:"Production",Sandbox:"Sandbox",Trial:"Trial",Default:"Default",Teams:"Teams",Platform:"Platform"};var ME;(function(e){e[e.CDS2=0]="CDS2",e[e.CDS1=1]="CDS1",e[e.Empty=2]="Empty"})(ME||(Je.EnvironmentType=ME={}));Je.EnvironmentCreationTypeConstants={NotSpecified:"NotSpecified",Legacy:"Legacy",DefaultTenant:"DefaultTenant",User:"User",CommonDataModelLegacy:"CommonDataModelLegacy"};Je.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"};Je.EnvironmentProvisioningStates={NotSpecified:"NotSpecified",Succeeded:"Succeeded",Deleting:"Deleting",Deleted:"Deleted",FailedDeleting:"FailedDeleting",LinkedDatabaseProvisioning:"LinkedDatabaseProvisioning",LinkedDatabaseFailedProvisioning:"LinkedDatabaseFailedProvisioning",LinkedDatabaseFailedConfiguring:"LinkedDatabaseFailedConfiguring",LinkedDatabaseUnavailable:"LinkedDatabaseUnavailable",Creating:"Creating"};Je.EnvironmentMigrationConstants={phases:{completed:"Completed"}};var UE;(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"})(UE||(Je.EnvironmentDisableReasonCode=UE={}));var BE;(function(e){e.LogicApps="LogicApps",e.SelfHostSingleTenant="SelfHostSingleTenant",e.SelfHostMultiTenant="SelfHostMultiTenant"})(BE||(Je.EnvironmentFlowHostingType=BE={}))});var JE=v(_=>{"use strict";var D3=_&&_.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(_,"__esModule",{value:!0});_.hasCommonDataServiceDatabase=_.getEnvironmentDiscoveryUrl=_.getEnvironmentWebApiUrl=_.getEnvironmentInstanceApiUrl=_.getEnvironmentLanguageCode=_.getEnvironmentUpdateCadence=_.checkVersions=_.isCds2EnvironmentVersionAtLeast=_.getSecurityOrConnectedGroupId=_.hasSecurityGroupId=_.doesCds2VersionSupportApiVersion9_1=_.doesCds2EnvironmentSupportApiVersion9_1=_.cdsVersionSupportingOSColorEdit=_.getEnvironmentDisplayName=_.getEnvironmentName=_.isEnvironmentInFirstReleaseCluster=_.isEnvironmentInPreprodCluster=_.isEnvironmentInTestCluster=_.isLiteEnvironmentUpgrading=_.isEnvironmentExpired=_.isEnvironmentInDeletedState=_.isEnvironmentInCreatingState=_.isDatabaseInProvisioningState=_.canUserCreateDatabase=_.isDisabledEnvironment=_.isDefaultEnvironment=_.isTrialEnvironment=_.isPlatformEnvironment=_.isTeamsEnvironment=_.isSandboxEnvironment=_.isProdEnvironment=_.isDevEnvironment=_.getEnvironmentType=_.getCrmInstanceName=_.getCrmInstanceUrl=_.getCrmAppDesignerUrl=_.getDevResourcesUrl=_.isEnvironmentInSuccessfulState=_.getAllThemesUrl=_.getAllPublishersUrl=_.getAllSolutionsUrl=_.getSecurityRolesUrl=_.getSecurityUsersUrl=_.environmentHasCds2Database=_.DEFAULT_SOLUTION_UNIQUE_NAME=_.DEFAULT_SOLUTION_ID=_.crmBapSolutionId=_.doesUserHavePermission=_.getLinkedEnvironmentMetadata=_.getCrmVersion=void 0;_.doesUserHaveFlowRunOnlyPermission=_.isUserPautoMakerWithoutDataAccess=_.isUserPautoMakerWithDataAccess=_.doesUserHaveCreateFlowPermission=_.equalsIgnoreCase=_.doesUserHaveCreateDatabasePermission=_.doesUserHaveDatabaseTablePermissions=_.isUserMakerWithoutDataAccess=_.isUserMakerWithDataAccess=_.doesUserHaveCreateAppPermission=_.doesUserHaveAdminPermission=void 0;var I3=D3(xE()),Oe=qE(),Ul=Eh();function O3(e){let t=Ii(e);return t&&t.version}_.getCrmVersion=O3;function Ii(e){return e&&e.properties&&e.properties.linkedEnvironmentMetadata}_.getLinkedEnvironmentMetadata=Ii;function Di(e,t){return e?!!e[t]:!1}_.doesUserHavePermission=Di;_.crmBapSolutionId="00000001-0000-0000-0001-00000000009b";_.DEFAULT_SOLUTION_ID="fd140aaf-4df4-11dd-bd17-0019b9312238";_.DEFAULT_SOLUTION_UNIQUE_NAME="Default";function Ko(e){return!!Ii(e)&&VE(e)}_.environmentHasCds2Database=Ko;function P3(e){if(e&&Ko(e)){let t=co(e);return(0,Ul.getCrmAdminSecurityRolesUrl)(t)}return""}_.getSecurityUsersUrl=P3;function R3(e){if(e&&Ko(e)){let t=co(e);return(0,Ul.getCrmAdminSecurityUsersUrl)(t)}return""}_.getSecurityRolesUrl=R3;function L3(e){if(e&&Ko(e)){let t=co(e);(0,Ul.getCrmAllSolutionsUrl)(t)}return""}_.getAllSolutionsUrl=L3;function k3(e){if(e&&Ko(e)){let t=co(e);return(0,Ul.getCrmAllPublishersUrl)(t)}return""}_.getAllPublishersUrl=k3;function $3(e){return e&&Ko(e)?co(e):""}_.getAllThemesUrl=$3;function VE(e){return!!e&&e.properties&&!!e.properties.provisioningState&&e.properties.provisioningState.toUpperCase()===Oe.EnvironmentProvisioningStates.Succeeded.toUpperCase()}_.isEnvironmentInSuccessfulState=VE;function x3(e){if(e&&Ko(e)){let t=co(e);return(0,Ul.getCrmDevResourcesUrl)(t)}return""}_.getDevResourcesUrl=x3;function F3(e){return`${e}designer/app/{${_.crmBapSolutionId}}/CreateNewApp}}`}_.getCrmAppDesignerUrl=F3;function co(e){let t=Ii(e);if(t){let r=t.instanceUrl;return r?r.endsWith("/")?r:r+"/":""}return""}_.getCrmInstanceUrl=co;function M3(e){let t=Ii(e);return t?t.uniqueName:""}_.getCrmInstanceName=M3;function U3(e){return Ii(e)?Oe.EnvironmentType.CDS2:e&&e.properties&&e.properties.namespace?Oe.EnvironmentType.CDS1:Oe.EnvironmentType.Empty}_.getEnvironmentType=U3;function B3(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Developer}_.isDevEnvironment=B3;function q3(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Production}_.isProdEnvironment=q3;function V3(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Sandbox}_.isSandboxEnvironment=V3;function Bl(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Teams}_.isTeamsEnvironment=Bl;function G3(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Platform}_.isPlatformEnvironment=G3;var W3=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.environmentSku)===Oe.EnvironmentSkuConstants.Trial};_.isTrialEnvironment=W3;function z3(e){return e&&e.properties&&(e.properties.isDefault||e.properties.creationType===Oe.EnvironmentCreationTypeConstants.DefaultTenant)}_.isDefaultEnvironment=z3;function j3(e){return e&&e.properties&&!!e.properties.states&&!!e.properties.states.runtime&&e.properties.states.runtime.id==="Disabled"}_.isDisabledEnvironment=j3;function H3(e){return e&&e.properties&&Di(e.properties.permissions,Oe.environmentPermissions.CreateDatabase)}_.canUserCreateDatabase=H3;function K3(e){return!!(e&&e.properties&&e.properties.provisioningState&&KE(e.properties.provisioningState,Oe.EnvironmentProvisioningStates.LinkedDatabaseProvisioning))}_.isDatabaseInProvisioningState=K3;function J3(e){return!!e&&!!e.properties&&e.properties.provisioningState===Oe.EnvironmentProvisioningStates.Creating}_.isEnvironmentInCreatingState=J3;function Y3(e){return e&&e.properties&&(e.properties.provisioningState===Oe.EnvironmentProvisioningStates.Deleted||e.properties.provisioningState===Oe.EnvironmentProvisioningStates.Deleting||e.properties.provisioningState===Oe.EnvironmentProvisioningStates.FailedDeleting)}_.isEnvironmentInDeletedState=Y3;function Q3(e){return!!e&&!!e.properties&&!!e.properties.expirationTime&&Date.parse(e.properties.expirationTime)<Date.now()}_.isEnvironmentExpired=Q3;function X3(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"}_.isLiteEnvironmentUpgrading=X3;function Z3(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Test"}_.isEnvironmentInTestCluster=Z3;function e4(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Preprod"}_.isEnvironmentInPreprodCluster=e4;function t4(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="FirstRelease"}_.isEnvironmentInFirstReleaseCluster=t4;function r4(e){return e&&e.name||""}_.getEnvironmentName=r4;function n4(e){return e&&e.properties&&e.properties.displayName||""}_.getEnvironmentDisplayName=n4;var GE="9.1.0.8202";_.cdsVersionSupportingOSColorEdit="9.1.0000.20708";function i4(e){return jE(e,GE)}_.doesCds2EnvironmentSupportApiVersion9_1=i4;function o4(e){return Ch(e,GE)}_.doesCds2VersionSupportApiVersion9_1=o4;function WE(e){let t=Ii(e);if(t)return t.securityGroupId}function zE(e){return e&&e.properties&&e.properties.connectedGroups}function a4(e,t){let r=zE(e);return!!r&&!!r.find(n=>n.id===t)||WE(e)===t}_.hasSecurityGroupId=a4;function s4(e){let t=zE(e);return t&&t.length>0&&t[0].id?t[0].id:WE(e)}_.getSecurityOrConnectedGroupId=s4;function jE(e,t){let r=e.version;return r?Ch(r,t):!1}_.isCds2EnvironmentVersionAtLeast=jE;function Ch(e,t){return t?e?(0,I3.default)(e,t)>=0:!1:!0}_.checkVersions=Ch;function l4(e){return e&&e.properties&&e.properties.updateCadence&&e.properties.updateCadence.id||"NotSpecified"}_.getEnvironmentUpdateCadence=l4;function u4(e){let t=Ii(e);return t?Number(t.baseLanguage):0}_.getEnvironmentLanguageCode=u4;function HE(e){let t=Ii(e);return t?t.instanceApiUrl:void 0}_.getEnvironmentInstanceApiUrl=HE;function c4(e){let t=HE(e);return t?t+"/api/data/v9.2":""}_.getEnvironmentWebApiUrl=c4;function d4(e){let t=co(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"}_.getEnvironmentDiscoveryUrl=d4;var f4=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.databaseType)===Oe.DatabaseType.CommonDataService};_.hasCommonDataServiceDatabase=f4;var p4=e=>{var t;return Di((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.AdminReadEnvironment)};_.doesUserHaveAdminPermission=p4;var m4=e=>{var t;return Di((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreatePowerApp)};_.doesUserHaveCreateAppPermission=m4;var h4=e=>(0,_.doesUserHaveAdminPermission)(e)&&(0,_.hasCommonDataServiceDatabase)(e)?!0:(0,_.doesUserHaveCreateAppPermission)(e)?Bl(e)||(0,_.doesUserHaveDatabaseTablePermissions)(e):!1;_.isUserMakerWithDataAccess=h4;var g4=e=>(0,_.doesUserHaveCreateAppPermission)(e)&&!Bl(e)&&!(0,_.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,_.doesUserHaveAdminPermission)(e)||!(0,_.hasCommonDataServiceDatabase)(e));_.isUserMakerWithoutDataAccess=g4;var y4=e=>[Oe.environmentPermissions.CreateDatabaseEntities,Oe.environmentPermissions.ListDatabaseEntities,Oe.environmentPermissions.UpdateDatabaseEntities,Oe.environmentPermissions.DeleteDatabaseEntities].every(t=>{var r;return Di((r=e.properties)===null||r===void 0?void 0:r.permissions,t)});_.doesUserHaveDatabaseTablePermissions=y4;var b4=e=>{var t;return Di((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreateDatabase)};_.doesUserHaveCreateDatabasePermission=b4;function KE(e,t){return!e&&!t?!0:!e||!t?!1:e.toUpperCase()===t.toUpperCase()}_.equalsIgnoreCase=KE;var v4=e=>{var t;return Di((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreateFlow)};_.doesUserHaveCreateFlowPermission=v4;var w4=e=>(0,_.doesUserHaveAdminPermission)(e)&&(0,_.hasCommonDataServiceDatabase)(e)?!0:(0,_.doesUserHaveCreateFlowPermission)(e)?Bl(e)||(0,_.doesUserHaveDatabaseTablePermissions)(e):!1;_.isUserPautoMakerWithDataAccess=w4;var C4=e=>(0,_.doesUserHaveCreateFlowPermission)(e)&&!Bl(e)&&!(0,_.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,_.doesUserHaveAdminPermission)(e)||!(0,_.hasCommonDataServiceDatabase)(e));_.isUserPautoMakerWithoutDataAccess=C4;var E4=e=>{var t,r;return!Di((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreateFlow)&&Di((r=e.properties)===null||r===void 0?void 0:r.permissions,Oe.environmentPermissions.ReadEnvironment)};_.doesUserHaveFlowRunOnlyPermission=E4});var Eh=v(A=>{"use strict";Object.defineProperty(A,"__esModule",{value:!0});A.getRequiredComponentsQueryUrl=A.solutionComponentCountSummariesQueryUrl=A.solutionComponentSummariesQueryUrl=A.solutionComponentConfigurationsQueryUrl=A.chartsQueryUrl=A.workflowsQueryUrl=A.entityDefinitionsQueryUrl=A.solutionComponentDefinitionsQueryUrl=A.getCreateNewArticleTemplateUrl=A.getCreateNewPublisherUrl=A.getEnableSecurityRolesUrl=A.getArticleTemplateUrl=A.getFieldSecurityProfileDesignerUrl=A.getSecurityRoleDesignerUrl=A.getMailMergeTemplateDesignerUrl=A.getEmailTemplateDesignerUrl=A.getConnectionRoleDesignerUrl=A.getSiteMapDesignerUrl=A.getWebResourceFileUrl=A.getWebResourceDesignerUrl=A.getReportDesignerUrl=A.getBusinessProcessFlowDesignerUrl=A.getProcessShareUrl=A.getProcessDesignerUrl=A.getChartDesignerUrl=A.getOpenModernEntityDashboardUrl=A.getNewModernEntityDashboardUrl=A.getNewModernDashboardUrl=A.getOpenModernDashboardUrl=A.getDashboardDesignerUrl=A.getAppModuleDesignerUrl=A.privilegesQueryUrls=A.xrmApiUrl=A.getPlayAppModuleUrl=A.getCrmAdminSecurityUsersUrl=A.getCrmAdminSecurityRolesUrl=A.getCrmMyAppsUrl=A.getCrmAppDesignerUrl=A.getCrmDevResourcesUrl=A.getCrmAllPublishersUrl=A.getCrmAllSolutionsUrl=A.getSolutionPublisherUrl=A.getExportTranslationFileName=A.getExportSolutionTranslationUrl=A.getImportSolutionTranslationUrl=A.getShowSolutionDependenciesUrl=A.getShowComponentDependenciesUrl=A.cdsServiceUrl=A.ODATA_NEXT_LINK=A.ODATA_MAX_PAGE_SIZE=void 0;A.retrieveOrganizationResources=A.getUCIEntityRecordEditUrl=A.getUCIEntityRecordBaseUrl=A.getBusinessRuleDesignerUri=A.retrieveUnpublishedSuffix=A.getSavePowerSettingUri=A.getPowerSettingUri=A.getPowerSettingsUri=A.RetrievePlatform=A.getAppSettingOverrideUri=A.AppSettingOverrideName=A.getOrgSettingOverrideUri=A.OrgSettingOverrideName=A.getSettingDefinitionsUri=A.retrieveFeatureControlSettingsByNamespaceUrl=A.retrieveDeploymentPipelineConfigAppUrl=A.SPNPrincipalIdUrl=A.retrieveDeploymentEnvironmentInfoUrl=A.devSolutionInfoUrl=A.deployOperationStatusUrl=A.getAIGeneratedDeploymentNotesUrl=A.deploymentStageRunUrl=A.validatePackageAsyncUrl=A.deployPackageAsyncUrl=A.updateDeploymentStageRunUrl=A.createDeploymentStageRunUrl=A.retrieveDeploymentStagesUrl=A.retrievePipelinesUrl=A.retrieveDeploymentPipelineInfoUrl=A.getDeploymentStageRunsUrl=A.appDeploymentUrls=A.getProvisionLanguageUrl=A.getSolutionQueryUrl=A.getSolutionsByUniqueNameQueryUrl=A.solutionsQueryUrl=A.getDependentComponentsWithMetadataQueryUrl=void 0;var YE=JE();A.ODATA_MAX_PAGE_SIZE="odata.maxpagesize";A.ODATA_NEXT_LINK="@odata.nextLink";A.cdsServiceUrl="https://cds-org/";var Vl;(function(e){e.AllSolutions="11",e.AllPublishers="10",e.DevResources="05"})(Vl||(Vl={}));function A4(e,t,r,n){return`${e}tools/dependency/dependencyviewdialog.aspx?appSolutionId=%7b${t}%7d&dType=1&objectid=%7b${r}%7d&objecttype=${n}&operationtype=showdependency`}A.getShowComponentDependenciesUrl=A4;function S4(e,t){let r=`dType=1&isproactivecheck=true&objecttype=7100&operationtype=dependenciesforuninstall&objectid=${t}`;return`${e}tools/dependency/dependencyviewdialog.aspx?${r}`}A.getShowSolutionDependenciesUrl=S4;function N4(e,t){return`${e}tools/muiProvisioning/Dialogs/LangTranslationsImport.aspx?dType=1&appSolutionId=${t}`}A.getImportSolutionTranslationUrl=N4;function _4(e,t){return`${e}_grid/cmds/dlg_exportsolution.aspx?command=exporttranslation&appSolutionId=${t}`}A.getExportSolutionTranslationUrl=_4;function T4(e,t){return e!==void 0&&t!==void 0&&`CrmTranslations_${e}_${t.replace(/[.]/g,"_")}.zip`||""}A.getExportTranslationFileName=T4;function D4(e,t,r){return r?`${e}tools/publisher/edit.aspx?appSolutionId=%7b${r}%7d&id=%7b${t}%7d`:`${e}tools/publisher/edit.aspx?id=%7b${t}%7d`}A.getSolutionPublisherUrl=D4;function Ah(e,t){return`${e}tools/systemcustomization/systemCustomization.aspx?pid=${t}`}function I4(e){return Ah(e,Vl.AllSolutions)}A.getCrmAllSolutionsUrl=I4;function O4(e){return Ah(e,Vl.AllPublishers)}A.getCrmAllPublishersUrl=O4;function P4(e){return Ah(e,Vl.DevResources)}A.getCrmDevResourcesUrl=P4;function R4(e,t=YE.crmBapSolutionId){return`${e}designer/app/${t}#/CreateNewApp`}A.getCrmAppDesignerUrl=R4;function L4(e){return`${e}apps`}A.getCrmMyAppsUrl=L4;function k4(e){return QE(e,"role")+"&forceUCI=0"}A.getCrmAdminSecurityRolesUrl=k4;function $4(e){return`${QE(e,"systemuser")}&forceclassic=1`}A.getCrmAdminSecurityUsersUrl=$4;function QE(e,t){return`${e}main.aspx?pagetype=entitylist&etn=${t}`}function x4(e,t){return`${e}main.aspx?appid=${t}`}A.getPlayAppModuleUrl=x4;A.xrmApiUrl="api/data/v9.0";A.privilegesQueryUrls={systemUserInfo:e=>`${e}${A.xrmApiUrl}/WhoAmI`,userPrivileges:(e,t)=>`${e}${A.xrmApiUrl}/systemusers(${t})/Microsoft.Dynamics.CRM.RetrieveUserPrivileges`,systemPrivileges:e=>`${e}${A.xrmApiUrl}/privileges/Microsoft.Dynamics.CRM.RetrievePrivilegeSet`};function F4(e,t,r=YE.crmBapSolutionId){return`${e}designer/app/${r}/${t}/AppDesignerCanvas/${t}`}A.getAppModuleDesignerUrl=F4;function M4(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${r}%7d&extraqs=%26formId%3d%7b${t}%7d%26dashboardType%3d1030&pagetype=${`${n?"ic":""}dashboardeditor`}`}A.getDashboardDesignerUrl=M4;function U4(e,t,r){return`/e/${e}/s/${t}/dashboard/${r}`}A.getOpenModernDashboardUrl=U4;function B4(e,t,r){let n=r!==void 0?r.toString():void 0;return`/e/${e}/s/${t}/dashboard/new${n?`/${n}`:""}`}A.getNewModernDashboardUrl=B4;function q4(e,t,r,n){let i=n!==void 0?n.toString():void 0;return`/e/${e}/s/${t}/n/${r}/dashboard/new${i?`/${i}`:""}`}A.getNewModernEntityDashboardUrl=q4;function V4(e,t,r,n){return`/e/${e}/s/${t}/n/${r}/dashboard/${n}`}A.getOpenModernEntityDashboardUrl=V4;function G4(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${t}%7d&extraqs=etc=${r||""}`+(n?`%26id=${n}`:"")+"&pagetype=vizdesigner"}A.getChartDesignerUrl=G4;function W4(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getProcessDesignerUrl=W4;function z4(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getProcessShareUrl=z4;function j4(e,t){return`${e}Tools/ProcessControl/UnifiedProcessDesigner.aspx?id=${t}`}A.getBusinessProcessFlowDesignerUrl=j4;function H4(e,t,r){return`${e}CRMReports/reportproperty.aspx?appSolutionId=%7b${r}%7d&disablePersonal=true&id=%7b${t}%7d`}A.getReportDesignerUrl=H4;function K4(e,t,r){return`${e}main.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&etc=9333&id=%7b${t}%7d&pagetype=webresourceedit`}A.getWebResourceDesignerUrl=K4;function J4(e,t){return`${e}WebResources/${t}`}A.getWebResourceFileUrl=J4;function Y4(e,t,r){return`${e}designer/sitemap/${r}/${t}/SiteMapHome/${t}`}A.getSiteMapDesignerUrl=Y4;function Q4(e,t,r){return`${e}connections/connectionroles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getConnectionRoleDesignerUrl=Q4;function X4(e,t,r){return`${e}tools/emailtemplateeditor/emailtemplateeditor.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getEmailTemplateDesignerUrl=X4;function Z4(e,t,r){return`${e}tools/mailmerge/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getMailMergeTemplateDesignerUrl=Z4;function eV(e,t,r){return`${e}biz/roles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getSecurityRoleDesignerUrl=eV;function tV(e,t,r){return`${e}biz/fieldsecurityprofiles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getFieldSecurityProfileDesignerUrl=tV;function rV(e,t,r){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?_CreateFromId=%7b${t}%7d&_CreateFromType=7100&appSolutionId=%7b${t}%7d&id=%7b${r}%7d`}A.getArticleTemplateUrl=rV;function nV(e,t,r,n){return`${e}tools/FormEditor/Dialogs/FormRoleAssignment.aspx?appSolutionId=%7b${t}%7d&dType=1&formId=%7b${r}%7d&objectTypeCode=0&type=${n}`}A.getEnableSecurityRolesUrl=nV;function iV(e){return`${e}tools/publisher/edit.aspx`}A.getCreateNewPublisherUrl=iV;function oV(e,t){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?appSolutionId=${t}`}A.getCreateNewArticleTemplateUrl=oV;A.solutionComponentDefinitionsQueryUrl="api/data/v9.0/solutioncomponentdefinitions";A.entityDefinitionsQueryUrl="api/data/v9.0/EntityDefinitions?$select=EntitySetName,DisplayName,LogicalName&$filter=";A.workflowsQueryUrl="api/data/v9.0/workflows";A.chartsQueryUrl="/api/data/v9.0/savedqueryvisualizations";A.solutionComponentConfigurationsQueryUrl="/api/data/v9.1/solutioncomponentconfigurations?$filter=isdisplayable eq true&$select=name";A.solutionComponentSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentsummaries";A.solutionComponentCountSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentcountsummaries";function aV(e,t){return`${A.xrmApiUrl}/RetrieveRequiredComponents(ObjectId=${e},ComponentType=${t})`}A.getRequiredComponentsQueryUrl=aV;function sV(e,t){return`${A.cdsServiceUrl}${A.xrmApiUrl}/RetrieveDependentComponentsWithMetadata(ObjectId=${e},ComponentType=${t})`}A.getDependentComponentsWithMetadataQueryUrl=sV;A.solutionsQueryUrl="/api/data/v9.0/solutions?$expand=publisherid&$filter=(isvisible eq true)";function lV(e){return`/api/data/v9.0/solutions?$expand=publisherid&$filter=(uniquename eq '${e}')`}A.getSolutionsByUniqueNameQueryUrl=lV;function uV(e){return`/api/data/v9.0/solutions(${e})?$expand=publisherid`}A.getSolutionQueryUrl=uV;function cV(e){return`${e}api/data/v9.1/ProvisionLanguageForUser`}A.getProvisionLanguageUrl=cV;A.appDeploymentUrls={associateEnvironmentToPipelineUrl:e=>`/api/data/v9.0/deploymentpipelines(${e})/deploymentpipeline_deploymentenvironment/$ref`,deploymentArtifactsUrl:"/api/data/v9.0/deploymentartifacts",deploymentEnvironmentUrl:"/api/data/v9.0/deploymentenvironments",deploymentPipelinesUrl:"/api/data/v9.0/deploymentpipelines",deploymentStagesUrl:"/api/data/v9.0/deploymentstages",retrieveDeploymentPipelinesUrl:e=>`/api/data/v9.0/RetrieveDeploymentPipelines(SourceEnvironmentId='${e}')`,deletePipelinesUrl:e=>`/api/data/v9.0/deploymentpipelines(${e})`};function dV(e,t,r,n=!1,i=!1,o=!1,a=!1,s=!1,l=!1,u=!1){return`/api/data/v9.1/deploymentstageruns?$select=artifactname,artifactversion,deploymentstagerunid,devenvironmentid,endtime,errormessage,${s?"_artifactid_value,isredeployment,":""}${n?"deploymentnotes,":""}operation,operationdetails,operationstatus,${l?"retrycount,":""}${i?"scheduledtime,":""}${u?"solutionid,":""}stagerunstatus,starttime,suboperation,targetenvironmentid,${o?"predeploymentstepnotes,":""}validationresults,${a?"approvalcomments,":""}_devdeploymentenvironment_value,_targetdeploymentenvironment_value&$expand=deploymentstageid($select=deploymentstageid,name,_deploymentpipelineid_value),targetdeploymentenvironment($select=deploymentenvironmentid,environmentid,name),createdby($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)${l?",RetryUser($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)":""}&$filter=deploymentstageid/_deploymentpipelineid_value eq ${e} and devenvironmentid eq '${t}' and artifactname eq '${r}' and ((operation ne 200000201) or (operation eq 200000201 and operationstatus eq 200000003))- &$orderby=starttime desc`}S.getDeploymentStageRunsUrl=l3;function u3(e,t,r){return`/api/data/v9.1/RetrieveDeploymentPipelineInfo(DeploymentPipelineId=${e},SourceEnvironmentId='${t}',ArtifactName='${r}')`}S.retrieveDeploymentPipelineInfoUrl=u3;function c3(e){return`/api/data/v9.0/deploymentenvironments+ &$orderby=starttime desc`}A.getDeploymentStageRunsUrl=dV;function fV(e,t,r){return`/api/data/v9.1/RetrieveDeploymentPipelineInfo(DeploymentPipelineId=${e},SourceEnvironmentId='${t}',ArtifactName='${r}')`}A.retrieveDeploymentPipelineInfoUrl=fV;function pV(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}')`}S.retrievePipelinesUrl=c3;function d3(e){return`/api/data/v9.0/deploymentstages+ &$filter=(environmentid eq '${e}')`}A.retrievePipelinesUrl=pV;function mV(e){return`/api/data/v9.0/deploymentstages?$filter=(_deploymentpipelineid_value eq ${e})&$select=name,description,deploymentstageid,_previousdeploymentstageid_value- &$expand=targetdeploymentenvironmentid($select=deploymentenvironmentid,environmentid,name)`}S.retrieveDeploymentStagesUrl=d3;function f3(){return"/api/data/v9.0/deploymentstageruns?$select=deploymentstagerunid"}S.createDeploymentStageRunUrl=f3;function p3(e){return`/api/data/v9.0/deploymentstageruns(${e})`}S.updateDeploymentStageRunUrl=p3;function m3(){return"/api/data/v9.0/DeployPackageAsync"}S.deployPackageAsyncUrl=m3;function h3(){return"/api/data/v9.0/ValidatePackageAsync"}S.validatePackageAsyncUrl=h3;function g3(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)":""}`}S.deploymentStageRunUrl=g3;function y3(e){return`/api/data/v9.0/deploymentstageruns(${e})- ?$select=aigenerateddeploymentnotes,deploymentstagerunid`}S.getAIGeneratedDeploymentNotesUrl=y3;function b3(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)`}A.retrieveDeploymentStagesUrl=mV;function hV(){return"/api/data/v9.0/deploymentstageruns?$select=deploymentstagerunid"}A.createDeploymentStageRunUrl=hV;function gV(e){return`/api/data/v9.0/deploymentstageruns(${e})`}A.updateDeploymentStageRunUrl=gV;function yV(){return"/api/data/v9.0/DeployPackageAsync"}A.deployPackageAsyncUrl=yV;function bV(){return"/api/data/v9.0/ValidatePackageAsync"}A.validatePackageAsyncUrl=bV;function vV(e,t=!1,r=!1){return`/api/data/v9.0/deploymentstageruns(${e})+ ?$select=deploymentstagerunid,stagerunstatus,errormessage,operation,operationdetails,operationstatus,${t?"scheduledtime,":""}targetenvironmentid,validationresults,artifactname,deploymentsettingsjson${r?"&$expand=createdby($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)":""}`}A.deploymentStageRunUrl=vV;function wV(e){return`/api/data/v9.0/deploymentstageruns(${e})+ ?$select=aigenerateddeploymentnotes,deploymentstagerunid`}A.getAIGeneratedDeploymentNotesUrl=wV;function CV(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`}S.deployOperationStatusUrl=b3;function v3(e){return`/api/data/v9.0/solutions(${e})- ?$select=solutionid,uniquename,version`}S.devSolutionInfoUrl=v3;function w3(e){return`/api/data/v9.0/deploymentenvironments+ &$select=_deploymentstageid_value,deploymentstagerunid,stagerunstatus,operation,operationstatus,suboperation,artifactname`}A.deployOperationStatusUrl=CV;function EV(e){return`/api/data/v9.0/solutions(${e})+ ?$select=solutionid,uniquename,version`}A.devSolutionInfoUrl=EV;function AV(e){return`/api/data/v9.0/deploymentenvironments?$select=deploymentenvironmentid,environmentid,environmenttype,name- &$filter=(environmentid eq '${e}')`}S.retrieveDeploymentEnvironmentInfoUrl=w3;var C3=e=>`/api/data/v9.0/systemusers+ &$filter=(environmentid eq '${e}')`}A.retrieveDeploymentEnvironmentInfoUrl=AV;var SV=e=>`/api/data/v9.0/systemusers?$select=azureactivedirectoryobjectid- &$filter=(applicationid eq '${e}')`;S.SPNPrincipalIdUrl=C3;function E3(){return"/api/data/v9.0/appmodules?$filter=(uniquename eq 'AppDeploymentConfiguration')"}S.retrieveDeploymentPipelineConfigAppUrl=E3;S.retrieveFeatureControlSettingsByNamespaceUrl="/api/data/v9.1/RetrieveFeatureControlSettingsByNamespace";function A3(e){return`/api/data/v9.0/settingdefinitions${e}`}S.getSettingDefinitionsUri=A3;S.OrgSettingOverrideName="organizationsettings";function S3(e,t=!1){let r=`/api/data/v9.0/${S.OrgSettingOverrideName}${e}`;return t?`${S.cdsServiceUrl}${r}`:r}S.getOrgSettingOverrideUri=S3;S.AppSettingOverrideName="appsettings";function N3(e,t=!1){let r=`/api/data/v9.0/${S.AppSettingOverrideName}${e}`;return t?`${S.cdsServiceUrl.replace("/$","")}${r}`:r}S.getAppSettingOverrideUri=N3;var wl;(function(e){e[e.All=0]="All",e[e.IsPlatformOnly=1]="IsPlatformOnly",e[e.NotPlatformOnly=2]="NotPlatformOnly"})(wl||(S.RetrievePlatform=wl={}));function _3(e,t,r,n=wl.All,i=!1){let o=[];e&&o.push(`AppUniqueName='${e}'`),t!=null&&o.push(`ReleaseLevel=${t}`),r&&o.push(`RetrieveHiddenSettings=${r}`),n!==wl.All&&o.push(`RetrievePlatformSettings=${n===wl.IsPlatformOnly?1:0}`);let a="/api/data/v9.0/RetrieveUnpublishedOverridableSettingsInfo";return o.length&&(a=`${a}(${o.join(",")})`),i?`${S.cdsServiceUrl}${a}`:a}S.getPowerSettingsUri=_3;function T3(e,t,r,n=!1){let i=[`SettingName='${e}'`];t!==void 0&&i.push(`SolutionName='${t}'`),r!==void 0&&i.push(`AppUniqueName='${r}'`);let o="/api/data/v9.0/RetrieveUnpublishedSettingInfo";return i.length&&(o=`${o}(${i.join(",")})`),n?`${S.cdsServiceUrl}${o}`:o}S.getPowerSettingUri=T3;function D3(e=!1){let t="/api/data/v9.0/SaveSettingValue()";return e?`${S.cdsServiceUrl}${t}`:t}S.getSavePowerSettingUri=D3;S.retrieveUnpublishedSuffix="Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()";function I3(e){return`tools/systemcustomization/businessrules/businessRulesDesigner.aspx?BRlaunchpoint=BRGrid&appSolutionId={${e}}`}S.getBusinessRuleDesignerUri=I3;function XC({environmentInstanceUrl:e,entityLogicalName:t}){return e&&t?`${e}main.aspx?cmdbar=true&forceUCI=1&navbar=off&newWindow=true&pageType=entityRecord&etn=${t}`:void 0}S.getUCIEntityRecordBaseUrl=XC;function O3({baseUrl:e,environmentInstanceUrl:t,entityLogicalName:r,recordId:n}){let i=e||XC({environmentInstanceUrl:t,entityLogicalName:r});return i&&n?`${i}&id=${n}`:void 0}S.getUCIEntityRecordEditUrl=O3;S.retrieveOrganizationResources=`${S.cdsServiceUrl}api/data/v9.0/RetrieveOrganizationResources`});var tE=v(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});Dc.DataverseClient=void 0;var P3=xm(),$o=Q(),ZC=ye(),R3=new Set(["entitydefinitions","relationshipdefinitions","globaloptionsetdefinitions"]);function L3(e){var t,r,n,i;let o=e.split("?")[0].split("/").filter(l=>l!==""),a=((t=o[0])===null||t===void 0?void 0:t.toLowerCase())==="api"&&((r=o[1])===null||r===void 0?void 0:r.toLowerCase())==="data"&&/^v\d/i.test((n=o[2])!==null&&n!==void 0?n:""),s=((i=o[a?3:0])!==null&&i!==void 0?i:"").split("(")[0].toLowerCase();return R3.has(s)}function k3(e){let t=e.indexOf("://"),r=t===-1?"":e.slice(t+3),n=r.search(/[/?#]/),i=n===-1?"":r.slice(n),o=i.search(/[?#]/);return o===-1?i:i.slice(0,o)}function eE(e,t){var r;if(!L3(e))return t;let n=(r=t?.headers)!==null&&r!==void 0?r:{};return Object.keys(n).some(i=>i.toLowerCase()==="consistency")?t:{...t,headers:{...n,Consistency:"Strong"}}}var Fm=class{constructor(t,r,n,i=1){this.instanceUrl=t,this.httpClient=r,this.solutionUniqueName=n,this.readConcurrency=i}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}/${P3.xrmApiUrl}${n}`}async send(t,r){try{return await r()}catch(n){throw n instanceof $o.SdkError?n:new $o.ConnectionError(t,0,n instanceof Error?n.message:String(n),n)}}get(t,r){let n=this.apiUrl(t),i=eE(t,r);return(0,ZC.resendDeadlockVictim)(()=>this.send(n,()=>this.httpClient.get(n,i)))}getAbsolute(t,r){this.assertSameOrigin(t);let n=eE(k3(t),r);return(0,ZC.resendDeadlockVictim)(()=>this.send(t,()=>this.httpClient.get(t,n)))}assertSameOrigin(t){let r,n;try{r=new URL(t),n=new URL(this.instanceUrl)}catch{throw new $o.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${t}'`)}if(r.protocol!==n.protocol||r.host!==n.host)throw new $o.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 $o.InvalidArgumentError("The injected HttpClient does not implement postRaw(), required for atomic $batch change sets");let i=this.apiUrl("/$batch"),o={...n,headers:{...n?.headers,"Content-Type":`multipart/mixed;boundary=${r}`}};return this.send(i,()=>this.httpClient.postRaw(i,t,o))}patch(t,r,n){let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.patch(i,r,this.withSolution(n)))}get supportsBinaryPatch(){return typeof this.httpClient.patchRaw=="function"}patchRaw(t,r,n){if(!this.httpClient.patchRaw)throw new $o.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 $o.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)))}};Dc.DataverseClient=Fm});var iE=v(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.findColumns=Zt.findTables=Zt.readCheckColumns=Zt.readColumnHints=Zt.fetchEntityMetadataFromApi=Zt.COLUMN_DETAIL_VERSION=void 0;var Pc=ye(),fr=ue();function Jr(e){var t,r;return(r=(t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)!==null&&r!==void 0?r:""}Zt.COLUMN_DETAIL_VERSION=2;function Mm(e){var t,r;return typeof((t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)=="string"||((r=e?.LocalizedLabels)!==null&&r!==void 0?r:[]).some(n=>typeof n?.Label=="string")}function Fo(e){let t=e?.LocalizedLabels;if(!Array.isArray(t)||t.length<2)return;let r={};for(let n of t)typeof n?.LanguageCode=="number"&&typeof n.Label=="string"&&(r[n.LanguageCode]=n.Label);return Object.keys(r).length?r:void 0}async function Ic(e,t){return(await Rc(e,t)).rows}async function Rc(e,t){var r,n;let i=await e.get(t);return i.status<200||i.status>=300?{rows:[],ok:!1}:{rows:(n=(r=i.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[],ok:!0}}function Fr(e){return`/EntityDefinitions(LogicalName='${(0,fr.odataPathLiteral)(e)}')`}async function x3(e,t,r){let n=await Ic(e,`${Fr(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata${(0,fr.odataQuery)([["$select","LogicalName,MaxLength"]])}`);for(let i of n){let o=r.get(i.LogicalName);o&&typeof i.MaxLength=="number"&&(o.maxLength=i.MaxLength)}}function $3(e){return`${Fr(e)}/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata${(0,fr.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`}async function F3(e,t){var r;let{rows:n}=await e;for(let i of n){let o=t.get(i.LogicalName);o&&(!((r=i.OptionSet)===null||r===void 0)&&r.Options)&&(o.options=i.OptionSet.Options.map(a=>{var s;return{value:(s=a.Value)!==null&&s!==void 0?s:0,label:Jr(a.Label),...Fo(a.Label)?{localizedLabel:Fo(a.Label)}:{}}}))}}function Um(e){var t;return{value:(t=e.Value)!==null&&t!==void 0?t:0,label:Jr(e.Label),...e.InvariantName?{invariantName:e.InvariantName}:{},...e.Color?{color:e.Color}:{}}}async function M3(e,t,r){var n;let i=c=>Rc(e,c).catch(()=>({rows:[],ok:!1})),o=["MultiSelectPicklistAttributeMetadata","StateAttributeMetadata","StatusAttributeMetadata"],a=await Promise.all([r.catch(()=>({rows:[],ok:!1})),...o.map(c=>i(`${Fr(t)}/Attributes/Microsoft.Dynamics.CRM.${c}${(0,fr.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`))]),s=new Map,l=!0;for(let{rows:c}of a)for(let d of c)!((n=d.OptionSet)===null||n===void 0)&&n.Options&&(l=l&&d.OptionSet.Options.every(f=>Mm(f.Label)),s.set(d.LogicalName,d.OptionSet.Options.map(Um)));let u=await i(`${Fr(t)}/Attributes/Microsoft.Dynamics.CRM.BooleanAttributeMetadata${(0,fr.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=TrueOption,FalseOption)"]])}`);for(let c of u.rows){let d=c.OptionSet;d?.TrueOption&&d.FalseOption&&(l=l&&Mm(d.TrueOption.Label)&&Mm(d.FalseOption.Label),s.set(c.LogicalName,[Um(d.FalseOption),Um(d.TrueOption)]))}return{byColumn:s,complete:l&&u.ok&&a.every(c=>c.ok)}}async function U3(e,t,r){let{rows:n,ok:i}=await Rc(e,`${Fr(t)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata${(0,fr.odataQuery)([["$select","LogicalName,Targets"]])}`);for(let o of n){let a=r.get(o.LogicalName);a&&o.Targets&&(a.targets=o.Targets)}return i}function Oc(e,t){return e<t?-1:e>t?1:0}var rE={OneToMany:0,ManyToOne:1,ManyToMany:2};function B3(e,t){return rE[e.type]-rE[t.type]||Oc(e.schemaName,t.schemaName)||Oc(e.relatedEntity,t.relatedEntity)||Oc(e.relatedAttribute,t.relatedAttribute)}async function q3(e,t){var r,n,i,o;let a=[],s=await Ic(e,`${Fr(t)}/OneToManyRelationships${(0,fr.odataQuery)([["$select","SchemaName,ReferencingEntity,ReferencingAttribute"]])}`);for(let c of s)a.push({schemaName:c.SchemaName,type:"OneToMany",relatedEntity:(r=c.ReferencingEntity)!==null&&r!==void 0?r:"",relatedAttribute:(n=c.ReferencingAttribute)!==null&&n!==void 0?n:""});let l=await Ic(e,`${Fr(t)}/ManyToOneRelationships${(0,fr.odataQuery)([["$select","SchemaName,ReferencedEntity,ReferencedAttribute"]])}`);for(let c of l)a.push({schemaName:c.SchemaName,type:"ManyToOne",relatedEntity:(i=c.ReferencedEntity)!==null&&i!==void 0?i:"",relatedAttribute:(o=c.ReferencedAttribute)!==null&&o!==void 0?o:""});let u=await Ic(e,`${Fr(t)}/ManyToManyRelationships${(0,fr.odataQuery)([["$select","SchemaName,Entity1LogicalName,Entity2LogicalName"]])}`);for(let c of u){let d=c.Entity1LogicalName===t?c.Entity2LogicalName:c.Entity1LogicalName;a.push({schemaName:c.SchemaName,type:"ManyToMany",relatedEntity:d??"",relatedAttribute:""})}return a.sort(B3)}async function V3(e,t){var r,n,i,o,a;let s=`${Fr(t)}`+(0,fr.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,Description,EntitySetName,IsCustomEntity,PrimaryNameAttribute,PrimaryIdAttribute,PrimaryImageAttribute"],["$expand","Attributes($select=LogicalName,DisplayName,Description,AttributeType,AttributeTypeName,IsCustomAttribute,IsValidForUpdate,IsValidForRead,AttributeOf)"]]),u=(0,Pc.ensureSuccess)(await e.get(s),e.apiUrl(s)).body,c=((r=u.Attributes)!==null&&r!==void 0?r:[]).map(g=>{var b,w,E;return{logicalName:g.LogicalName,displayName:Jr(g.DisplayName),...Fo(g.DisplayName)?{localizedDisplayName:Fo(g.DisplayName)}:{},attributeType:(b=g.AttributeType)!==null&&b!==void 0?b:"Unknown",isCustomAttribute:!!g.IsCustomAttribute,attributeTypeName:(E=(w=g.AttributeTypeName)===null||w===void 0?void 0:w.Value)!==null&&E!==void 0?E:"",...typeof g.IsValidForUpdate=="boolean"?{isValidForUpdate:g.IsValidForUpdate}:{},...typeof g.IsValidForRead=="boolean"?{isValidForRead:g.IsValidForRead}:{},...g.AttributeOf?{attributeOf:g.AttributeOf}:{},...Jr(g.Description)?{description:Jr(g.Description)}:{}}}).sort((g,b)=>Oc(g.logicalName,b.logicalName)),d=new Map(c.map(g=>[g.logicalName,g])),f=Rc(e,$3(t)),[,,p,m,h]=await Promise.all([x3(e,t,d),F3(f,d),M3(e,t,f),U3(e,t,d),q3(e,t)]);for(let g of c){let b=p.byColumn.get(g.logicalName);b&&(g.choices=b)}return{logicalName:u.LogicalName,schemaName:(n=u.SchemaName)!==null&&n!==void 0?n:u.LogicalName,displayName:Jr(u.DisplayName),...Fo(u.DisplayName)?{localizedDisplayName:Fo(u.DisplayName)}:{},entitySetName:(i=u.EntitySetName)!==null&&i!==void 0?i:"",primaryNameAttribute:(o=u.PrimaryNameAttribute)!==null&&o!==void 0?o:"",primaryIdAttribute:(a=u.PrimaryIdAttribute)!==null&&a!==void 0?a:"",...u.PrimaryImageAttribute?{primaryImageAttribute:u.PrimaryImageAttribute}:{},isCustomEntity:!!u.IsCustomEntity,...Jr(u.Description)?{description:Jr(u.Description)}:{},columnDetailComplete:p.complete&&m,columnDetailVersion:Zt.COLUMN_DETAIL_VERSION,attributes:c,relationships:h}}Zt.fetchEntityMetadataFromApi=V3;var nE=40;async function Bm(e,t,r,n){var i,o;let a=[...new Set(n.filter(l=>l!==""))],s=[];for(let l=0;l<a.length;l+=nE){let u=a.slice(l,l+nE).map(f=>`LogicalName eq '${(0,fr.odataLiteral)(f)}'`).join(" or "),c=t+(0,fr.odataQuery)([["$select",r],["$filter",u]]),d=(0,Pc.ensureSuccess)(await e.get(c),e.apiUrl(c));s.push(...(o=(i=d.body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[])}return s}async function G3(e,t,r){return(await Bm(e,`${Fr(t)}/Attributes`,"LogicalName,AttributeType,DisplayName",r)).map(i=>{var o;let a=Fo(i.DisplayName);return{logicalName:i.LogicalName,displayName:Jr(i.DisplayName),...a?{localizedDisplayName:a}:{},attributeType:(o=i.AttributeType)!==null&&o!==void 0?o:"Unknown"}})}Zt.readColumnHints=G3;async function W3(e,t,r){let i=(await Bm(e,`${Fr(t)}/Attributes`,"LogicalName,AttributeType,DisplayName,IsCustomAttribute",r)).map(s=>{var l;return{logicalName:s.LogicalName,displayName:Jr(s.DisplayName),attributeType:(l=s.AttributeType)!==null&&l!==void 0?l:"Unknown",isCustomAttribute:!!s.IsCustomAttribute}}),o=new Map(i.filter(s=>s.attributeType==="String").map(s=>[s.logicalName,s])),a=await Bm(e,`${Fr(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata`,"LogicalName,MaxLength",[...o.keys()]);for(let s of a){let l=o.get(s.LogicalName);l&&typeof s.MaxLength=="number"&&(l.maxLength=s.MaxLength)}return i}Zt.readCheckColumns=W3;async function z3(e,t,r){var n,i;let o=`/EntityDefinitions${(0,fr.odataQuery)([["$select","LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity"]])}`,s=(i=(n=(0,Pc.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[],l=(t??"").toLowerCase(),u=s.filter(c=>!r?.customOnly||c.IsCustomEntity).map(c=>{var d,f;return{logicalName:c.LogicalName,schemaName:(d=c.SchemaName)!==null&&d!==void 0?d:c.LogicalName,displayName:Jr(c.DisplayName),entitySetName:(f=c.EntitySetName)!==null&&f!==void 0?f:"",isCustom:!!c.IsCustomEntity}}).filter(c=>c.logicalName.toLowerCase().includes(l)||c.schemaName.toLowerCase().includes(l)||c.displayName.toLowerCase().includes(l));return typeof r?.top=="number"?u.slice(0,r.top):u}Zt.findTables=z3;async function j3(e,t,r,n){var i,o;let a=`${Fr(t)}/Attributes`+(0,fr.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute"]]),l=(o=(i=(0,Pc.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[],u=(r??"").toLowerCase(),c=l.map(d=>{var f,p;return{logicalName:d.LogicalName,schemaName:(f=d.SchemaName)!==null&&f!==void 0?f:d.LogicalName,displayName:Jr(d.DisplayName),attributeType:(p=d.AttributeType)!==null&&p!==void 0?p:"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}Zt.findColumns=j3});var Gm=v(pr=>{"use strict";Object.defineProperty(pr,"__esModule",{value:!0});pr.renderTypeRegistrations=pr.buildGenPageLegacyEnums=pr.renderGenPageAuthoringTypes=pr.buildGenPageRuntimeTypes=pr.toDesignerEntity=pr.TABLE_LOGICAL_NAME=void 0;pr.TABLE_LOGICAL_NAME=/^[a-z_][a-z0-9_]*$/;function qm(e){return e.replace(/[\r\n\u2028\u2029]+/g," ")}var H3=new Set(["createdby","createdon","createdonbehalfby","importsequencenumber","modifiedby","modifiedon","modifiedonbehalfby","overriddencreatedon","ownerid","owningbusinessunit","owningteam","owninguser","timezoneruleversionnumber","utcconversiontimezonecode","versionnumber"]);function Lc(e){var t;return((t=e.attributeTypeName)!==null&&t!==void 0?t:"").replace(/Type$/,"").toLowerCase()}function sE(e){var t,r;let n=e.choices;if(!n||n.length===0)return;let i=Lc(e)==="boolean",o={};for(let a of n)o[a.value]={text:(r=(t=a.invariantName)!==null&&t!==void 0?t:a.label)!==null&&r!==void 0?r:"",value:a.value,...!i&&a.color?{color:a.color}:{}};return o}function oE(e,t){return e.logicalName<t.logicalName?-1:e.logicalName>t.logicalName?1:0}function lE(e){return!H3.has(e.logicalName)&&(!e.attributeOf||Lc(e)==="image")&&e.isValidForRead!==!1}var aE=new Set(["boolean","picklist","multiselectpicklist","state","status"]);function uE(e){let t=e.primaryImageAttribute,r=new Set([e.primaryIdAttribute,e.primaryNameAttribute,t,t?`${t}_url`:void 0,"processid","statecode","statuscode"].filter(o=>!!o)),n=e.attributes.filter(o=>r.has(o.logicalName)).sort(oE),i=e.attributes.filter(o=>!r.has(o.logicalName)).sort(oE);return[...n,...i]}function Vm(e){var t;let r=[],n=new Set,i=uE(e);for(let o of i){let a=Lc(o),s=a==="image";lE(o)&&(s&&o.attributeOf&&n.add(o.attributeOf),r.push({AttributeTypeName:a,IsReadOnly:!o.isValidForUpdate,LogicalName:o.logicalName,OptionSet:sE(o),Targets:o.targets,Description:o.description,MaxLength:o.maxLength}))}return{Description:(t=e.description)!==null&&t!==void 0?t:"",LogicalName:e.logicalName,PrimaryIdAttribute:e.primaryIdAttribute,Attributes:r.filter(o=>!n.has(o.LogicalName))}}pr.toDesignerEntity=Vm;function cE(e,t="None"){let r={};for(let n of e)r[n.logicalName]=Vm(n);return pE(r,t)}pr.buildGenPageRuntimeTypes=cE;var dE=`export interface TableRegistrations extends BaseTableRegistrations {-`,fE=`export interface EnumRegistrations extends BaseEnumRegistrations {-`;function K3(e,t){return e.length>0?cE(e,t).text:hE(`${dE}}-`,`${fE}}-`,"","")}pr.renderGenPageAuthoringTypes=K3;function J3(e){let t=new Set;for(let n of e)for(let i of Vm(n).Attributes)aE.has(i.AttributeTypeName)&&t.add(`${n.logicalName}_${i.LogicalName}`);let r=new Map;for(let n of e)for(let i of uE(n)){let o=`${n.logicalName}_${i.logicalName}`,a=sE(i);if(lE(i)||!aE.has(Lc(i))||!a||t.has(o)||r.has(o))continue;let s={name:o,runtime:{},labels:new Map};r.set(o,{declaration:mE(o,a,!1,s),model:s})}return r}pr.buildGenPageLegacyEnums=J3;function pE(e,t="None"){var r,n;let i=new Map,o=Object.values(e);if(o.length===0)return{text:"",enums:i};let a=t==="ColorsDefaultsConstraints"||t==="ColorsDefaultsConstraintsDescriptions",s=t==="ColorsDefaultsConstraintsDescriptions",l=dE,u=fE,c="",d="";for(let f of o){s&&f.Description&&(c+=`// ${qm(f.Description)}+ &$filter=(applicationid eq '${e}')`;A.SPNPrincipalIdUrl=SV;function NV(){return"/api/data/v9.0/appmodules?$filter=(uniquename eq 'AppDeploymentConfiguration')"}A.retrieveDeploymentPipelineConfigAppUrl=NV;A.retrieveFeatureControlSettingsByNamespaceUrl="/api/data/v9.1/RetrieveFeatureControlSettingsByNamespace";function _V(e){return`/api/data/v9.0/settingdefinitions${e}`}A.getSettingDefinitionsUri=_V;A.OrgSettingOverrideName="organizationsettings";function TV(e,t=!1){let r=`/api/data/v9.0/${A.OrgSettingOverrideName}${e}`;return t?`${A.cdsServiceUrl}${r}`:r}A.getOrgSettingOverrideUri=TV;A.AppSettingOverrideName="appsettings";function DV(e,t=!1){let r=`/api/data/v9.0/${A.AppSettingOverrideName}${e}`;return t?`${A.cdsServiceUrl.replace("/$","")}${r}`:r}A.getAppSettingOverrideUri=DV;var ql;(function(e){e[e.All=0]="All",e[e.IsPlatformOnly=1]="IsPlatformOnly",e[e.NotPlatformOnly=2]="NotPlatformOnly"})(ql||(A.RetrievePlatform=ql={}));function IV(e,t,r,n=ql.All,i=!1){let o=[];e&&o.push(`AppUniqueName='${e}'`),t!=null&&o.push(`ReleaseLevel=${t}`),r&&o.push(`RetrieveHiddenSettings=${r}`),n!==ql.All&&o.push(`RetrievePlatformSettings=${n===ql.IsPlatformOnly?1:0}`);let a="/api/data/v9.0/RetrieveUnpublishedOverridableSettingsInfo";return o.length&&(a=`${a}(${o.join(",")})`),i?`${A.cdsServiceUrl}${a}`:a}A.getPowerSettingsUri=IV;function OV(e,t,r,n=!1){let i=[`SettingName='${e}'`];t!==void 0&&i.push(`SolutionName='${t}'`),r!==void 0&&i.push(`AppUniqueName='${r}'`);let o="/api/data/v9.0/RetrieveUnpublishedSettingInfo";return i.length&&(o=`${o}(${i.join(",")})`),n?`${A.cdsServiceUrl}${o}`:o}A.getPowerSettingUri=OV;function PV(e=!1){let t="/api/data/v9.0/SaveSettingValue()";return e?`${A.cdsServiceUrl}${t}`:t}A.getSavePowerSettingUri=PV;A.retrieveUnpublishedSuffix="Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()";function RV(e){return`tools/systemcustomization/businessrules/businessRulesDesigner.aspx?BRlaunchpoint=BRGrid&appSolutionId={${e}}`}A.getBusinessRuleDesignerUri=RV;function XE({environmentInstanceUrl:e,entityLogicalName:t}){return e&&t?`${e}main.aspx?cmdbar=true&forceUCI=1&navbar=off&newWindow=true&pageType=entityRecord&etn=${t}`:void 0}A.getUCIEntityRecordBaseUrl=XE;function LV({baseUrl:e,environmentInstanceUrl:t,entityLogicalName:r,recordId:n}){let i=e||XE({environmentInstanceUrl:t,entityLogicalName:r});return i&&n?`${i}&id=${n}`:void 0}A.getUCIEntityRecordEditUrl=LV;A.retrieveOrganizationResources=`${A.cdsServiceUrl}api/data/v9.0/RetrieveOrganizationResources`});var tA=v(rd=>{"use strict";Object.defineProperty(rd,"__esModule",{value:!0});rd.DataverseClient=void 0;var kV=Eh(),Jo=Q(),ZE=fe(),$V=new Set(["entitydefinitions","relationshipdefinitions","globaloptionsetdefinitions"]);function xV(e){var t,r,n,i;let o=e.split("?")[0].split("/").filter(l=>l!==""),a=((t=o[0])===null||t===void 0?void 0:t.toLowerCase())==="api"&&((r=o[1])===null||r===void 0?void 0:r.toLowerCase())==="data"&&/^v\d/i.test((n=o[2])!==null&&n!==void 0?n:""),s=((i=o[a?3:0])!==null&&i!==void 0?i:"").split("(")[0].toLowerCase();return $V.has(s)}function FV(e){let t=e.indexOf("://"),r=t===-1?"":e.slice(t+3),n=r.search(/[/?#]/),i=n===-1?"":r.slice(n),o=i.search(/[?#]/);return o===-1?i:i.slice(0,o)}function eA(e,t){var r;if(!xV(e))return t;let n=(r=t?.headers)!==null&&r!==void 0?r:{};return Object.keys(n).some(i=>i.toLowerCase()==="consistency")?t:{...t,headers:{...n,Consistency:"Strong"}}}var Sh=class e{constructor(t,r,n,i=1){this.instanceUrl=t,this.httpClient=r,this.solutionUniqueName=n,this.readConcurrency=i}withSolutionScope(t){return new e(this.instanceUrl,this.httpClient,t,this.readConcurrency)}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}/${kV.xrmApiUrl}${n}`}async send(t,r){try{return await r()}catch(n){throw n instanceof Jo.SdkError?n:new Jo.ConnectionError(t,0,n instanceof Error?n.message:String(n),n)}}get(t,r){let n=this.apiUrl(t),i=eA(t,r);return(0,ZE.resendDeadlockVictim)(()=>this.send(n,()=>this.httpClient.get(n,i)))}getAbsolute(t,r){this.assertSameOrigin(t);let n=eA(FV(t),r);return(0,ZE.resendDeadlockVictim)(()=>this.send(t,()=>this.httpClient.get(t,n)))}assertSameOrigin(t){let r,n;try{r=new URL(t),n=new URL(this.instanceUrl)}catch{throw new Jo.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${t}'`)}if(r.protocol!==n.protocol||r.host!==n.host)throw new Jo.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 supportsPut(){return typeof this.httpClient.put=="function"}get solutionName(){return this.solutionUniqueName}postBatch(t,r,n){if(!this.httpClient.postRaw)throw new Jo.InvalidArgumentError("The injected HttpClient does not implement postRaw(), required for atomic $batch change sets");let i=this.apiUrl("/$batch"),o={...n,headers:{...n?.headers,"Content-Type":`multipart/mixed;boundary=${r}`}};return this.send(i,()=>this.httpClient.postRaw(i,t,o))}patch(t,r,n){let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.patch(i,r,this.withSolution(n)))}get supportsBinaryPatch(){return typeof this.httpClient.patchRaw=="function"}patchRaw(t,r,n){if(!this.httpClient.patchRaw)throw new Jo.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 Jo.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)))}};rd.DataverseClient=Sh});var iA=v(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.findColumns=cr.findTables=cr.readCheckColumns=cr.readColumnHints=cr.fetchEntityMetadataFromApi=cr.COLUMN_DETAIL_VERSION=void 0;var od=fe(),Ar=oe();function an(e){var t,r;return(r=(t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)!==null&&r!==void 0?r:""}cr.COLUMN_DETAIL_VERSION=2;function Nh(e){var t,r;return typeof((t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)=="string"||((r=e?.LocalizedLabels)!==null&&r!==void 0?r:[]).some(n=>typeof n?.Label=="string")}function Yo(e){let t=e?.LocalizedLabels;if(!Array.isArray(t)||t.length<2)return;let r={};for(let n of t)typeof n?.LanguageCode=="number"&&typeof n.Label=="string"&&(r[n.LanguageCode]=n.Label);return Object.keys(r).length?r:void 0}async function nd(e,t){return(await ad(e,t)).rows}async function ad(e,t){var r,n;let i=await e.get(t);return i.status<200||i.status>=300?{rows:[],ok:!1}:{rows:(n=(r=i.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[],ok:!0}}function Jr(e){return`/EntityDefinitions(LogicalName='${(0,Ar.odataPathLiteral)(e)}')`}async function MV(e,t,r){let n=await nd(e,`${Jr(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata${(0,Ar.odataQuery)([["$select","LogicalName,MaxLength"]])}`);for(let i of n){let o=r.get(i.LogicalName);o&&typeof i.MaxLength=="number"&&(o.maxLength=i.MaxLength)}}function UV(e){return`${Jr(e)}/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata${(0,Ar.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`}async function BV(e,t){var r;let{rows:n}=await e;for(let i of n){let o=t.get(i.LogicalName);o&&(!((r=i.OptionSet)===null||r===void 0)&&r.Options)&&(o.options=i.OptionSet.Options.map(a=>{var s;return{value:(s=a.Value)!==null&&s!==void 0?s:0,label:an(a.Label),...Yo(a.Label)?{localizedLabel:Yo(a.Label)}:{}}}))}}function _h(e){var t;return{value:(t=e.Value)!==null&&t!==void 0?t:0,label:an(e.Label),...e.InvariantName?{invariantName:e.InvariantName}:{},...e.Color?{color:e.Color}:{}}}async function qV(e,t,r){var n;let i=c=>ad(e,c).catch(()=>({rows:[],ok:!1})),o=["MultiSelectPicklistAttributeMetadata","StateAttributeMetadata","StatusAttributeMetadata"],a=await Promise.all([r.catch(()=>({rows:[],ok:!1})),...o.map(c=>i(`${Jr(t)}/Attributes/Microsoft.Dynamics.CRM.${c}${(0,Ar.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`))]),s=new Map,l=!0;for(let{rows:c}of a)for(let d of c)!((n=d.OptionSet)===null||n===void 0)&&n.Options&&(l=l&&d.OptionSet.Options.every(f=>Nh(f.Label)),s.set(d.LogicalName,d.OptionSet.Options.map(_h)));let u=await i(`${Jr(t)}/Attributes/Microsoft.Dynamics.CRM.BooleanAttributeMetadata${(0,Ar.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=TrueOption,FalseOption)"]])}`);for(let c of u.rows){let d=c.OptionSet;d?.TrueOption&&d.FalseOption&&(l=l&&Nh(d.TrueOption.Label)&&Nh(d.FalseOption.Label),s.set(c.LogicalName,[_h(d.FalseOption),_h(d.TrueOption)]))}return{byColumn:s,complete:l&&u.ok&&a.every(c=>c.ok)}}async function VV(e,t,r){let{rows:n,ok:i}=await ad(e,`${Jr(t)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata${(0,Ar.odataQuery)([["$select","LogicalName,Targets"]])}`);for(let o of n){let a=r.get(o.LogicalName);a&&o.Targets&&(a.targets=o.Targets)}return i}function id(e,t){return e<t?-1:e>t?1:0}var rA={OneToMany:0,ManyToOne:1,ManyToMany:2};function GV(e,t){return rA[e.type]-rA[t.type]||id(e.schemaName,t.schemaName)||id(e.relatedEntity,t.relatedEntity)||id(e.relatedAttribute,t.relatedAttribute)}async function WV(e,t){var r,n,i,o;let a=[],s=await nd(e,`${Jr(t)}/OneToManyRelationships${(0,Ar.odataQuery)([["$select","SchemaName,ReferencingEntity,ReferencingAttribute"]])}`);for(let c of s)a.push({schemaName:c.SchemaName,type:"OneToMany",relatedEntity:(r=c.ReferencingEntity)!==null&&r!==void 0?r:"",relatedAttribute:(n=c.ReferencingAttribute)!==null&&n!==void 0?n:""});let l=await nd(e,`${Jr(t)}/ManyToOneRelationships${(0,Ar.odataQuery)([["$select","SchemaName,ReferencedEntity,ReferencedAttribute"]])}`);for(let c of l)a.push({schemaName:c.SchemaName,type:"ManyToOne",relatedEntity:(i=c.ReferencedEntity)!==null&&i!==void 0?i:"",relatedAttribute:(o=c.ReferencedAttribute)!==null&&o!==void 0?o:""});let u=await nd(e,`${Jr(t)}/ManyToManyRelationships${(0,Ar.odataQuery)([["$select","SchemaName,Entity1LogicalName,Entity2LogicalName"]])}`);for(let c of u){let d=c.Entity1LogicalName===t?c.Entity2LogicalName:c.Entity1LogicalName;a.push({schemaName:c.SchemaName,type:"ManyToMany",relatedEntity:d??"",relatedAttribute:""})}return a.sort(GV)}async function zV(e,t){var r,n,i,o,a;let s=`${Jr(t)}`+(0,Ar.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,Description,EntitySetName,IsCustomEntity,PrimaryNameAttribute,PrimaryIdAttribute,PrimaryImageAttribute"],["$expand","Attributes($select=LogicalName,DisplayName,Description,AttributeType,AttributeTypeName,IsCustomAttribute,IsValidForUpdate,IsValidForRead,AttributeOf)"]]),u=(0,od.ensureSuccess)(await e.get(s),e.apiUrl(s)).body,c=((r=u.Attributes)!==null&&r!==void 0?r:[]).map(g=>{var b,w,C;return{logicalName:g.LogicalName,displayName:an(g.DisplayName),...Yo(g.DisplayName)?{localizedDisplayName:Yo(g.DisplayName)}:{},attributeType:(b=g.AttributeType)!==null&&b!==void 0?b:"Unknown",isCustomAttribute:!!g.IsCustomAttribute,attributeTypeName:(C=(w=g.AttributeTypeName)===null||w===void 0?void 0:w.Value)!==null&&C!==void 0?C:"",...typeof g.IsValidForUpdate=="boolean"?{isValidForUpdate:g.IsValidForUpdate}:{},...typeof g.IsValidForRead=="boolean"?{isValidForRead:g.IsValidForRead}:{},...g.AttributeOf?{attributeOf:g.AttributeOf}:{},...an(g.Description)?{description:an(g.Description)}:{}}}).sort((g,b)=>id(g.logicalName,b.logicalName)),d=new Map(c.map(g=>[g.logicalName,g])),f=ad(e,UV(t)),[,,m,p,h]=await Promise.all([MV(e,t,d),BV(f,d),qV(e,t,f),VV(e,t,d),WV(e,t)]);for(let g of c){let b=m.byColumn.get(g.logicalName);b&&(g.choices=b)}return{logicalName:u.LogicalName,schemaName:(n=u.SchemaName)!==null&&n!==void 0?n:u.LogicalName,displayName:an(u.DisplayName),...Yo(u.DisplayName)?{localizedDisplayName:Yo(u.DisplayName)}:{},entitySetName:(i=u.EntitySetName)!==null&&i!==void 0?i:"",primaryNameAttribute:(o=u.PrimaryNameAttribute)!==null&&o!==void 0?o:"",primaryIdAttribute:(a=u.PrimaryIdAttribute)!==null&&a!==void 0?a:"",...u.PrimaryImageAttribute?{primaryImageAttribute:u.PrimaryImageAttribute}:{},isCustomEntity:!!u.IsCustomEntity,...an(u.Description)?{description:an(u.Description)}:{},columnDetailComplete:m.complete&&p,columnDetailVersion:cr.COLUMN_DETAIL_VERSION,attributes:c,relationships:h}}cr.fetchEntityMetadataFromApi=zV;var nA=40;async function Th(e,t,r,n){var i,o;let a=[...new Set(n.filter(l=>l!==""))],s=[];for(let l=0;l<a.length;l+=nA){let u=a.slice(l,l+nA).map(f=>`LogicalName eq '${(0,Ar.odataLiteral)(f)}'`).join(" or "),c=t+(0,Ar.odataQuery)([["$select",r],["$filter",u]]),d=(0,od.ensureSuccess)(await e.get(c),e.apiUrl(c));s.push(...(o=(i=d.body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[])}return s}async function jV(e,t,r){return(await Th(e,`${Jr(t)}/Attributes`,"LogicalName,AttributeType,DisplayName",r)).map(i=>{var o;let a=Yo(i.DisplayName);return{logicalName:i.LogicalName,displayName:an(i.DisplayName),...a?{localizedDisplayName:a}:{},attributeType:(o=i.AttributeType)!==null&&o!==void 0?o:"Unknown"}})}cr.readColumnHints=jV;async function HV(e,t,r){let i=(await Th(e,`${Jr(t)}/Attributes`,"LogicalName,AttributeType,DisplayName,IsCustomAttribute",r)).map(s=>{var l;return{logicalName:s.LogicalName,displayName:an(s.DisplayName),attributeType:(l=s.AttributeType)!==null&&l!==void 0?l:"Unknown",isCustomAttribute:!!s.IsCustomAttribute}}),o=new Map(i.filter(s=>s.attributeType==="String").map(s=>[s.logicalName,s])),a=await Th(e,`${Jr(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata`,"LogicalName,MaxLength",[...o.keys()]);for(let s of a){let l=o.get(s.LogicalName);l&&typeof s.MaxLength=="number"&&(l.maxLength=s.MaxLength)}return i}cr.readCheckColumns=HV;async function KV(e,t,r){var n,i;let o=`/EntityDefinitions${(0,Ar.odataQuery)([["$select","LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity"]])}`,s=(i=(n=(0,od.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[],l=(t??"").toLowerCase(),u=s.filter(c=>!r?.customOnly||c.IsCustomEntity).map(c=>{var d,f;return{logicalName:c.LogicalName,schemaName:(d=c.SchemaName)!==null&&d!==void 0?d:c.LogicalName,displayName:an(c.DisplayName),entitySetName:(f=c.EntitySetName)!==null&&f!==void 0?f:"",isCustom:!!c.IsCustomEntity}}).filter(c=>c.logicalName.toLowerCase().includes(l)||c.schemaName.toLowerCase().includes(l)||c.displayName.toLowerCase().includes(l));return typeof r?.top=="number"?u.slice(0,r.top):u}cr.findTables=KV;async function JV(e,t,r,n){var i,o;let a=`${Jr(t)}/Attributes`+(0,Ar.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute"]]),l=(o=(i=(0,od.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[],u=(r??"").toLowerCase(),c=l.map(d=>{var f,m;return{logicalName:d.LogicalName,schemaName:(f=d.SchemaName)!==null&&f!==void 0?f:d.LogicalName,displayName:an(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}cr.findColumns=JV});var Oh=v(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.renderTypeRegistrations=Sr.buildGenPageLegacyEnums=Sr.renderGenPageAuthoringTypes=Sr.buildGenPageRuntimeTypes=Sr.toDesignerEntity=Sr.TABLE_LOGICAL_NAME=void 0;Sr.TABLE_LOGICAL_NAME=/^[a-z_][a-z0-9_]*$/;function Dh(e){return e.replace(/[\r\n\u2028\u2029]+/g," ")}var YV=new Set(["createdby","createdon","createdonbehalfby","importsequencenumber","modifiedby","modifiedon","modifiedonbehalfby","overriddencreatedon","ownerid","owningbusinessunit","owningteam","owninguser","timezoneruleversionnumber","utcconversiontimezonecode","versionnumber"]);function sd(e){var t;return((t=e.attributeTypeName)!==null&&t!==void 0?t:"").replace(/Type$/,"").toLowerCase()}function sA(e){var t,r;let n=e.choices;if(!n||n.length===0)return;let i=sd(e)==="boolean",o={};for(let a of n)o[a.value]={text:(r=(t=a.invariantName)!==null&&t!==void 0?t:a.label)!==null&&r!==void 0?r:"",value:a.value,...!i&&a.color?{color:a.color}:{}};return o}function oA(e,t){return e.logicalName<t.logicalName?-1:e.logicalName>t.logicalName?1:0}function lA(e){return!YV.has(e.logicalName)&&(!e.attributeOf||sd(e)==="image")&&e.isValidForRead!==!1}var aA=new Set(["boolean","picklist","multiselectpicklist","state","status"]);function uA(e){let t=e.primaryImageAttribute,r=new Set([e.primaryIdAttribute,e.primaryNameAttribute,t,t?`${t}_url`:void 0,"processid","statecode","statuscode"].filter(o=>!!o)),n=e.attributes.filter(o=>r.has(o.logicalName)).sort(oA),i=e.attributes.filter(o=>!r.has(o.logicalName)).sort(oA);return[...n,...i]}function Ih(e){var t;let r=[],n=new Set,i=uA(e);for(let o of i){let a=sd(o),s=a==="image";lA(o)&&(s&&o.attributeOf&&n.add(o.attributeOf),r.push({AttributeTypeName:a,IsReadOnly:!o.isValidForUpdate,LogicalName:o.logicalName,OptionSet:sA(o),Targets:o.targets,Description:o.description,MaxLength:o.maxLength}))}return{Description:(t=e.description)!==null&&t!==void 0?t:"",LogicalName:e.logicalName,PrimaryIdAttribute:e.primaryIdAttribute,Attributes:r.filter(o=>!n.has(o.LogicalName))}}Sr.toDesignerEntity=Ih;function cA(e,t="None"){let r={};for(let n of e)r[n.logicalName]=Ih(n);return pA(r,t)}Sr.buildGenPageRuntimeTypes=cA;var dA=`export interface TableRegistrations extends BaseTableRegistrations {+`,fA=`export interface EnumRegistrations extends BaseEnumRegistrations {+`;function QV(e,t){return e.length>0?cA(e,t).text:hA(`${dA}}+`,`${fA}}+`,"","")}Sr.renderGenPageAuthoringTypes=QV;function XV(e){let t=new Set;for(let n of e)for(let i of Ih(n).Attributes)aA.has(i.AttributeTypeName)&&t.add(`${n.logicalName}_${i.LogicalName}`);let r=new Map;for(let n of e)for(let i of uA(n)){let o=`${n.logicalName}_${i.logicalName}`,a=sA(i);if(lA(i)||!aA.has(sd(i))||!a||t.has(o)||r.has(o))continue;let s={name:o,runtime:{},labels:new Map};r.set(o,{declaration:mA(o,a,!1,s),model:s})}return r}Sr.buildGenPageLegacyEnums=XV;function pA(e,t="None"){var r,n;let i=new Map,o=Object.values(e);if(o.length===0)return{text:"",enums:i};let a=t==="ColorsDefaultsConstraints"||t==="ColorsDefaultsConstraintsDescriptions",s=t==="ColorsDefaultsConstraintsDescriptions",l=dA,u=fA,c="",d="";for(let f of o){s&&f.Description&&(c+=`// ${Dh(f.Description)}`),c+=`export type ${f.LogicalName} = TableRow<{// Primary Key Columnreadonly ${f.PrimaryIdAttribute}: string,`,l+=` "${f.LogicalName}": ${f.LogicalName},-`;for(let p of f.Attributes){if(p.LogicalName===f.PrimaryIdAttribute)continue;let m=`${p.IsReadOnly?" readonly ":""}${p.LogicalName}`,h=!0;switch(p.AttributeTypeName){case"string":case"memo":case"uniqueidentifier":case"entityname":m+=`: string,-`;break;case"integer":case"double":case"decimal":case"money":case"bigint":m+=`: number,-`;break;case"datetime":m+=`: Date,-`;break;case"customer":case"lookup":{let g=(r=p.Targets)!==null&&r!==void 0?r:p.AttributeTypeName==="customer"?["account","contact"]:void 0;if(!g||g.length===0){h=!1;break}m=` // Foreign Key Column- ${p.IsReadOnly||g.every(w=>!e[w])?" readonly ":""}_${p.LogicalName}_value: `;let b="";for(let w of g)b+=`${b.length===0?"":" | "}\`/${w}(\${string})\``;m+=`${b},-`;break}case"boolean":case"picklist":case"multiselectpicklist":case"state":case"status":{let g=`${f.LogicalName}_${p.LogicalName}`;m+=`: ${g},-`;let b=(n=i.get(g))!==null&&n!==void 0?n:{name:g,runtime:{},labels:new Map};i.set(g,b),d+=mE(g,p.OptionSet,a,b),u+=` "${f.LogicalName}-${p.LogicalName}": ${g},+`;for(let m of f.Attributes){if(m.LogicalName===f.PrimaryIdAttribute)continue;let p=`${m.IsReadOnly?" readonly ":""}${m.LogicalName}`,h=!0;switch(m.AttributeTypeName){case"string":case"memo":case"uniqueidentifier":case"entityname":p+=`: string,+`;break;case"integer":case"double":case"decimal":case"money":case"bigint":p+=`: number,+`;break;case"datetime":p+=`: Date,+`;break;case"customer":case"lookup":{let g=(r=m.Targets)!==null&&r!==void 0?r:m.AttributeTypeName==="customer"?["account","contact"]:void 0;if(!g||g.length===0){h=!1;break}p=` // Foreign Key Column+ ${m.IsReadOnly||g.every(w=>!e[w])?" readonly ":""}_${m.LogicalName}_value: `;let b="";for(let w of g)b+=`${b.length===0?"":" | "}\`/${w}(\${string})\``;p+=`${b},+`;break}case"boolean":case"picklist":case"multiselectpicklist":case"state":case"status":{let g=`${f.LogicalName}_${m.LogicalName}`;p+=`: ${g},+`;let b=(n=i.get(g))!==null&&n!==void 0?n:{name:g,runtime:{},labels:new Map};i.set(g,b),d+=mA(g,m.OptionSet,a,b),u+=` "${f.LogicalName}-${m.LogicalName}": ${g},`;break}case"image":c+=` // This is an image encoded as a base64 string-`,m+=`: string,-`;break;default:h=!1}h&&(s&&p.Description&&(c+=` // ${qm(p.Description)}-`),a&&p.MaxLength&&(c+=" // Maximum length: "+p.MaxLength+`-`),c+=` ${m}`)}c+=`}>+`,p+=`: string,+`;break;default:h=!1}h&&(s&&m.Description&&(c+=` // ${Dh(m.Description)}+`),a&&m.MaxLength&&(c+=" // Maximum length: "+m.MaxLength+`+`),c+=` ${p}`)}c+=`}>`}return l+=`}`,u+=`}-`,{text:hE(l,u,c,d),enums:i}}pr.renderTypeRegistrations=pE;function mE(e,t,r,n){var i;let o=`const enum ${e} {-`;for(let a of Object.values(t??{}))if(a){r&&(o+=`${a.color?`// Option Color: ${qm(a.color)}+`,{text:hA(l,u,c,d),enums:i}}Sr.renderTypeRegistrations=pA;function mA(e,t,r,n){var i;let o=`const enum ${e} {+`;for(let a of Object.values(t??{}))if(a){r&&(o+=`${a.color?`// Option Color: ${Dh(a.color)}`:""}`),o+=`${JSON.stringify(a.text)} = ${a.value},`,n.runtime[a.text]=a.value,n.runtime[String(a.value)]=a.text;let s=(i=n.labels.get(a.text))!==null&&i!==void 0?i:[];s.includes(a.value)||s.push(a.value),n.labels.set(a.text,s)}return`${o}}-`}function hE(e,t,r,n){return`+`}function hA(e,t,r,n){return`// ---------------- Type Definitions which can be imported from ./RuntimeTypes -------------------------${e}${t}@@ -345,23 +345,23 @@ export interface GeneratedComponentProps {dataApi: UxAgentDataApi;pageInput?: PageInput;}-`}});var bE=v(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});kc.generateGenPageRuntimeTypes=void 0;var yE=Gm(),Mo=Q(),gE=new Set(["None","ColorsDefaultsConstraints","ColorsDefaultsConstraintsDescriptions"]),Uo="generateGenPageRuntimeTypes";async function Y3(e,t,r){let n=Q3(t),i=X3(r),o=[];for(let a of n){let s=await e(a);if(s.columnDetailComplete!==!0)throw new Mo.SdkError("GENPAGE_DATA_SOURCE_INCOMPLETE",`${Uo}: the column metadata of data source '${a}' could not be read completely (a choice or lookup read failed, or returned options with no label), so its RuntimeTypes would lack enums a page can use. Retry.`);o.push(s)}return(0,yE.renderGenPageAuthoringTypes)(o,i)}kc.generateGenPageRuntimeTypes=Y3;function Q3(e){if(!Array.isArray(e))throw new Mo.InvalidArgumentError(`${Uo}: dataSources must be an array of table logical names`);let t=new Set;for(let r of e){if(typeof r!="string"||!yE.TABLE_LOGICAL_NAME.test(r))throw new Mo.InvalidArgumentError(`${Uo}: a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(r)}'`);if(t.has(r))throw new Mo.InvalidArgumentError(`${Uo}: data source '${r}' is listed twice; a page's dataSources hold each table once`);t.add(r)}return[...t]}function X3(e){if(e===void 0)return"None";if(e===null||typeof e!="object"||Array.isArray(e))throw new Mo.InvalidArgumentError(`${Uo}: options must be an object`);let t=Object.keys(e).filter(n=>n!=="detail");if(t.length>0)throw new Mo.InvalidArgumentError(`${Uo}: unknown option '${t[0]}' (the only option is 'detail')`);let r=e.detail===void 0?"None":e.detail;if(typeof r!="string"||!gE.has(r))throw new Mo.InvalidArgumentError(`${Uo}: detail must be one of ${[...gE].map(n=>`'${n}'`).join(", ")}, got '${String(r)}'`);return r}});var SE=v(Bo=>{"use strict";Object.defineProperty(Bo,"__esModule",{value:!0});Bo.getEnvironmentLanguages=Bo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE=void 0;var Z3=Q(),CE=ye();Bo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE="ENVIRONMENT_LANGUAGES_UNREADABLE";var vE="/organizations?$select=languagecode",e4="/RetrieveProvisionedLanguages()",t4="/RetrieveAvailableLanguages()";function EE(e,t){return new Z3.SdkError(Bo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE,`The org's languages could not be read: ${e} ${t}. Nothing is assumed in its place \u2014 retry, or check the caller's access to the org.`)}function AE(e){return typeof e=="number"&&Number.isInteger(e)&&e>0}async function wE(e,t,r,n){let i=(0,CE.ensureSuccess)(await e.get(t),e.apiUrl(t)).body,o=i?.[r];if(!Array.isArray(o)||o.length===0||!o.every(AE))throw EE(n,`answered no list of language codes in '${r}'`);return[...new Set(o)]}async function r4(e){var t;let r=(0,CE.ensureSuccess)(await e.get(vE),e.apiUrl(vE)).body,n=r?.value,i=Array.isArray(n)&&n.length===1?(t=n[0])===null||t===void 0?void 0:t.languagecode:void 0;if(!AE(i))throw EE("the organization read","did not answer one row with a language code");let o=await wE(e,e4,"RetrieveProvisionedLanguages","RetrieveProvisionedLanguages"),a=await wE(e,t4,"LocaleIds","RetrieveAvailableLanguages");return{baseLanguage:i,available:a,provisioned:o}}Bo.getEnvironmentLanguages=r4});var Al=v(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.projectConnectorOperationSchema=Ze.projectConnectorOperations=Ze.validateConnectorSwagger=Ze.CONNECTOR_SCHEMA_TOO_LARGE_CODE=Ze.CONNECTOR_OPERATION_NOT_FOUND_CODE=Ze.CONNECTOR_SWAGGER_UNSUPPORTED_CODE=Ze.CONNECTIVITY_RESPONSE_UNREADABLE_CODE=void 0;var El=Q();Ze.CONNECTIVITY_RESPONSE_UNREADABLE_CODE="CONNECTIVITY_RESPONSE_UNREADABLE";Ze.CONNECTOR_SWAGGER_UNSUPPORTED_CODE="CONNECTOR_SWAGGER_UNSUPPORTED";Ze.CONNECTOR_OPERATION_NOT_FOUND_CODE="CONNECTOR_OPERATION_NOT_FOUND";Ze.CONNECTOR_SCHEMA_TOO_LARGE_CODE="CONNECTOR_SCHEMA_TOO_LARGE";var NE=64,_E=128,TE=2e5,DE=4e6,n4=new Set(["get","put","post","delete","patch","head","options"]),i4=new Set(["query","header","path","formData","body"]);function Yr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function yn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function bt(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function Ke(e){return e.length>80?`'${e.slice(0,80)}\u2026'`:`'${e}'`}function ke(e,t){return new El.SdkError(Ze.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`The connector's swagger could not be read: ${e} ${t}. Nothing was skipped or assumed in its place.`)}function Xi(e,t){return new El.SdkError(Ze.CONNECTOR_SWAGGER_UNSUPPORTED_CODE,`The connector's swagger is outside the supported contract (Swagger 2.0 as the Power Apps API serves it): ${e} ${t}.`)}function o4(e,t){let r=e;for(let n of t.slice(2).split("/")){let i=n.replace(/~1/g,"/").replace(/~0/g,"~");if(typeof r!="object"||r===null||!yn(r,i))return{found:!1};r=r[i]}return{found:!0,value:r}}function jm(e,t,r){if(!t.startsWith("#/"))throw Xi(r,`has a $ref that is not a local '#/\u2026' pointer (${Ke(t)})`);if(t.includes("%"))throw Xi(r,`has a $ref with a percent-encoded character (${Ke(t)}), which is not decoded`);if(/~(?![01])/.test(t))throw ke(r,`has a $ref with a malformed escape (${Ke(t)}): a '~' not followed by 0 or 1`);let n=o4(e,t);if(!n.found)throw ke(r,`has a $ref that does not resolve (${Ke(t)})`);return n.value}function xc(e,t){if(yn(e,"$ref")){if(typeof e.$ref!="string")throw ke(t,`has a $ref that is ${bt(e.$ref)}, not a string`);return e.$ref}}function a4(e,t,r){if(!Yr(t))throw ke(r,`is ${bt(t)}, not a parameter object`);let n=t,i=xc(t,r);if(i!==void 0){let s=jm(e,i,r);if(!Yr(s))throw ke(r,`has a $ref (${Ke(i)}) that resolves to ${bt(s)}, not a parameter object`);if(xc(s,`${r} \u2192 ${Ke(i)}`)!==void 0)throw Xi(r,`has a $ref (${Ke(i)}) to a parameter that is itself a $ref`);n=s}if(typeof n.name!="string")throw ke(r,"has no string name");let o=n.in;if(typeof o!="string"||!i4.has(o))throw ke(r,`has an in that is ${typeof o=="string"?Ke(o):bt(o)}, not one of query, header, path, formData or body`);if(yn(n,"required")&&typeof n.required!="boolean")throw ke(r,`has a required that is ${bt(n.required)}, not a boolean`);let a=n["x-ms-visibility"];if(yn(n,"x-ms-visibility")&&typeof a!="string")throw ke(r,`has an x-ms-visibility that is ${bt(a)}, not a string`);return{name:n.name,in:o,required:n.required===!0,internal:a==="internal"}}function Wm(e){return`${e.in}:${e.name}`}function OE(e,t,r){if(!yn(t,"parameters"))return[];let n=t.parameters;if(!Array.isArray(n))throw ke(r,`has parameters that are ${bt(n)}, not an array`);let i=new Set;return n.map((o,a)=>{let s=`${r} parameters[${a}]`,l=a4(e,o,s),u=Wm(l);if(i.has(u))throw ke(s,`repeats the parameter ${Ke(l.name)} in ${Ke(l.in)}, which must be unique in its list`);return i.add(u),l})}function PE(e,t,r){let n=t.responses;if(!yn(n,"200"))return;let i=`${r} response 200`,o=n[200];if(!Yr(o))throw ke(i,`is ${bt(o)}, not a response object`);let a=o,s=xc(o,i);if(s!==void 0){if(s.startsWith("#/")&&!/^#\/responses\/[^/]+$/.test(s))throw ke(i,`has a $ref (${Ke(s)}) that does not name a response ('#/responses/<name>')`);let l=jm(e,s,i);if(!Yr(l))throw ke(i,`has a $ref (${Ke(s)}) that resolves to ${bt(l)}, not a response object`);if(xc(l,`${i} \u2192 ${Ke(s)}`)!==void 0)throw Xi(i,`has a $ref (${Ke(s)}) to a response that is itself a $ref`);a=l}if(yn(a,"content"))throw Xi(i,"is an OpenAPI 3 response (it has content), not a Swagger 2.0 one");if(yn(a,"schema")){if(!Yr(a.schema))throw ke(i,`has a schema that is ${bt(a.schema)}, not an object`);return a.schema}}function IE(e,t,r){if(!yn(e,t))return;let n=e[t];if(typeof n!="string")throw ke(r,`has a ${t} that is ${bt(n)}, not a string`);return n}function s4(e,t,r,n,i){if(!Yr(t))throw ke(r,`is ${bt(t)}, not an operation object`);let o=t.operationId;if(typeof o!="string")throw ke(r,`has no string operationId (${bt(o)})`);if(n.has(o))throw ke(r,`repeats the operationId ${Ke(o)}, which must be unique in the document`);n.add(o);let a=IE(t,"summary",r),s=IE(t,"description",r),l=OE(e,t,r);if(!Yr(t.responses))throw ke(r,`has no responses object (${bt(t.responses)})`);return PE(e,t,r),{id:o,summary:a,description:s,node:t,where:r,parameters:l,pathParameters:i}}function Hm(e){if(!Yr(e))throw ke("the document",`is ${bt(e)}, not an object`);if(yn(e,"openapi"))throw Xi("the document","is OpenAPI 3 (it has an openapi member), not Swagger 2.0");if(!yn(e,"swagger"))throw ke("the document","names no Swagger version");if(e.swagger!=="2.0")throw Xi("the document",`declares swagger ${Ke(String(e.swagger))}, not 2.0`);let t=e.paths;if(!Yr(t))throw ke("the document",`has paths that are ${bt(t)}, not an object`);let r=[],n=new Set;for(let i of Object.keys(t)){let o=t[i],a=`paths[${Ke(i)}]`;if(!Yr(o))throw ke(a,`is ${bt(o)}, not a path item object`);let s=[];for(let l of Object.keys(o))if(n4.has(l.toLowerCase()))r.push(s4(e,o[l],`${a}.${l}`,n,s));else if(l==="parameters")for(let u of OE(e,o,a))s.push(u);else if(!l.startsWith("x-"))throw Xi(a,`has a ${Ke(l)} member; a path item may hold only HTTP methods, parameters and x- extensions`)}return{document:e,operations:r}}function l4(e){Hm(e)}Ze.validateConnectorSwagger=l4;var zm=class{constructor(t,r){this.root=t,this.where=r,this.nodes=0,this.characters=0,this.path=[]}run(t){return this.visit(t,0)}tooLarge(t){return new El.SdkError(Ze.CONNECTOR_SCHEMA_TOO_LARGE_CODE,`The response schema of ${this.where} is too large to return: it has ${t}. That is far above any connector measured, so this one is not read.`)}node(){if(this.nodes+=1,this.nodes>TE)throw this.tooLarge(`more than ${TE} nodes`)}text(t){if(this.characters+=t,this.characters>DE)throw this.tooLarge(`more than ${DE} characters of strings and keys`)}checkDepth(t){if(t>_E)throw this.tooLarge(`nesting deeper than ${_E} levels`)}visit(t,r){if(this.checkDepth(r),Array.isArray(t)){this.node();let n=[];for(let i of t)n.push(this.visit(i,r+1));return n}if(Yr(t)){if(typeof t.$ref=="string")return this.reference(t.$ref,r);this.node();let n={};for(let i of Object.keys(t))this.text(i.length),Object.defineProperty(n,i,{value:this.visit(t[i],r+1),enumerable:!0,writable:!0,configurable:!0});return n}return this.node(),typeof t=="string"&&this.text(t.length),t}reference(t,r){if(this.path.includes(t)){this.checkDepth(r+1);let o=t.slice(t.lastIndexOf("/")+1);return this.node(),this.text(4),this.node(),this.text(o.length),{$ref:o}}if(this.path.length>=NE)throw this.tooLarge(`a $ref chain of more than ${NE} references`);let n=jm(this.root,t,this.where);if(!Yr(n))throw ke(this.where,`has a schema $ref (${Ke(t)}) that resolves to ${bt(n)}, not a schema object`);this.path.push(t);let i=this.visit(n,r);return this.path.pop(),i}};function u4(e){let{operations:t}=Hm(e);return{operations:t.map(r=>{var n,i;return{name:r.id,summary:(i=(n=r.summary)!==null&&n!==void 0?n:r.description)!==null&&i!==void 0?i:null}})}}Ze.projectConnectorOperations=u4;function c4(e,t){if(typeof t!="string"||t==="")throw new El.InvalidArgumentError("operationId must be a non-empty string.");let{document:r,operations:n}=Hm(e),i=n.find(u=>u.id===t);if(!i)throw new El.SdkError(Ze.CONNECTOR_OPERATION_NOT_FOUND_CODE,`The connector has no operation with the id ${Ke(t)} (ids are matched exactly, case included). List the connector\u2019s operations to see its ids.`);let o=new Set(i.parameters.map(Wm)),a=[...i.parameters,...i.pathParameters.filter(u=>!o.has(Wm(u)))].filter(u=>!u.internal).map(({name:u,required:c})=>({name:u,required:c})),s=PE(r,i.node,i.where),l=s===void 0?{}:new zm(r,`${i.where} (${Ke(i.id)})`).run(s);return{operation:i.id,parameters:a,response:l}}Ze.projectConnectorOperationSchema=c4});var qo=v(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.readEnvironmentName=J.readConnection=J.connectorShortName=J.CONNECTOR_PREFIX=J.connectivityUnauthorized=J.errorCodeOf=J.messageOf=J.environmentFilter=J.unreadable=J.connectivityCloudOf=J.sameOrigin=J.parseUrl=J.bounded=J.kindOf=J.isObject=J.CONNECTOR_RUNTIME_UNSUPPORTED_CODE=J.CONNECTOR_NOT_TABULAR_CODE=J.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE=J.CONNECTIVITY_UNAUTHORIZED_CODE=J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE=J.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE=J.CONNECTIVITY_NOT_CONFIGURED_CODE=void 0;var Sl=Q(),d4=ye(),f4=Al();J.CONNECTIVITY_NOT_CONFIGURED_CODE="CONNECTIVITY_NOT_CONFIGURED";J.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE="CONNECTIVITY_CLOUD_UNSUPPORTED";J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE="CONNECTIVITY_ENVIRONMENT_UNVERIFIED";J.CONNECTIVITY_UNAUTHORIZED_CODE="CONNECTIVITY_UNAUTHORIZED";J.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE="CONNECTIVITY_ROUTE_DECOMMISSIONED";J.CONNECTOR_NOT_TABULAR_CODE="CONNECTOR_NOT_TABULAR";J.CONNECTOR_RUNTIME_UNSUPPORTED_CODE="CONNECTOR_RUNTIME_UNSUPPORTED";function mr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}J.isObject=mr;function Va(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}J.kindOf=Va;function Ga(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}J.bounded=Ga;function LE(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}J.parseUrl=LE;function p4(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}J.sameOrigin=p4;var m4=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,h4=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/;function g4(e){let t=LE(e),r=t?t.host.toLowerCase():"";if(h4.test(r))return"Test";let n=m4.exec(r);return n&&n[1]!=="9"?"Public":"Unsupported"}J.connectivityCloudOf=g4;function Mn(e,t){return new Sl.SdkError(f4.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}J.unreadable=Mn;function y4(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}J.environmentFilter=y4;function b4(e){if(typeof e=="string"&&e.length>0)return Ga(e,500);if(mr(e)){let t=mr(e.error)?e.error.message:void 0;for(let r of[t,e.Message,e.message])if(typeof r=="string")return Ga(r,500)}return"request failed"}J.messageOf=b4;function kE(e){return mr(e)&&mr(e.error)?e.error.code:void 0}J.errorCodeOf=kE;function v4(e){if(mr(e)&&mr(e.error)&&mr(e.error.innererror))return e.error.innererror.code}function w4(e,t,r){let n=[],i=kE(t);typeof i=="string"&&i.length>0&&n.push(Ga(i,80));let o=v4(t);typeof o=="string"&&o.length>0&&n.push(Ga(o,80));let a=n.length>0?` (${n.join("; ")})`:"";return(0,Sl.attachCause)(new Sl.SdkError(J.CONNECTIVITY_UNAUTHORIZED_CODE,`A connectivity request was refused with HTTP ${e}${a}: the token's audience, scopes, expiry, or access was rejected. Supply a valid token for this route, or fall back to pac.`),r)}J.connectivityUnauthorized=w4;J.CONNECTOR_PREFIX="/providers/Microsoft.PowerApps/apis/";var C4=/^[A-Za-z0-9_.-]{1,128}$/,E4=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]);function A4(e){if(typeof e=="string"){let r=e.slice(0,J.CONNECTOR_PREFIX.length).toLowerCase()===J.CONNECTOR_PREFIX.toLowerCase()?e.slice(J.CONNECTOR_PREFIX.length):e;if(C4.test(r)&&!/^\.{1,2}$/.test(r))return r}throw new Sl.InvalidArgumentError(`connector must be a connector's short name ('shared_office365users') or its full API id ('${J.CONNECTOR_PREFIX}shared_office365users'); got ${typeof e=="string"?`'${Ga(e,80)}'`:Va(e)}.`)}J.connectorShortName=A4;function S4(e,t,r){let n=`Connection row ${t}`;if(!mr(e))throw Mn(n,`it is ${Va(e)}, not an object`);let i=e.properties;if(!mr(i))throw Mn(n,`its properties are ${Va(i)}, not an object`);let o=i.apiId;if(typeof o!="string"||o.slice(0,J.CONNECTOR_PREFIX.length).toLowerCase()!==J.CONNECTOR_PREFIX.toLowerCase())throw Mn(n,`its apiId is not '${J.CONNECTOR_PREFIX}<connector>'`);let a=o.slice(J.CONNECTOR_PREFIX.length);if(a===""||a.includes("/"))throw Mn(n,"its apiId names no single connector");if(E4.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw Mn(n,"it has no name");let l=i.environment,u=mr(l)?l.name:void 0;if(typeof u!="string"||u.toLowerCase()!==r.toLowerCase())throw Mn(n,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw Mn(n,`its displayName is ${Va(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw Mn(n,`its statuses are ${Va(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let p=mr(f)?f.status:void 0;if(typeof p!="string")throw Mn(n,"one of its statuses has no string status");return p})}}J.readConnection=S4;var RE="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'";async function N4(e){let t=(0,d4.ensureSuccess)(await e.get(RE),e.apiUrl(RE)).body,r=mr(t)?t.Detail:void 0,n=mr(r)?r.EnvironmentId:void 0;if(typeof n!="string"||n==="")throw new Sl.SdkError(J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,"The environment of this org could not be verified: the org answered no environment id (RetrieveCurrentOrganization, Detail.EnvironmentId).");return n}J.readEnvironmentName=N4});var qE=v(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.ConnectivityApi=hr.CONNECTIVITY_UNAUTHORIZED_CODE=hr.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE=hr.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE=hr.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE=hr.CONNECTIVITY_NOT_CONFIGURED_CODE=void 0;var Ut=Q(),_4=ye(),Fc=Al(),_l=qo(),Tl=qo();Object.defineProperty(hr,"CONNECTIVITY_NOT_CONFIGURED_CODE",{enumerable:!0,get:function(){return Tl.CONNECTIVITY_NOT_CONFIGURED_CODE}});Object.defineProperty(hr,"CONNECTIVITY_CLOUD_UNSUPPORTED_CODE",{enumerable:!0,get:function(){return Tl.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE}});Object.defineProperty(hr,"CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE",{enumerable:!0,get:function(){return Tl.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE}});Object.defineProperty(hr,"CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE",{enumerable:!0,get:function(){return Tl.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE}});Object.defineProperty(hr,"CONNECTIVITY_UNAUTHORIZED_CODE",{enumerable:!0,get:function(){return Tl.CONNECTIVITY_UNAUTHORIZED_CODE}});var xE="2016-11-01",T4="2021-04-01",D4="https://api.bap.microsoft.com",I4="https://test.api.bap.microsoft.com",O4=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,P4=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,$E="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'",gi="/providers/Microsoft.PowerApps/apis/",R4=/^[A-Za-z0-9_.-]{1,128}$/,L4=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]),k4="ServiceDecommissioned";function st(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Zi(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function Un(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}function Nl(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}function FE(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}function x4(e){return/^[a-z0-9][a-z0-9.-]*$/.test(e)&&(e==="api.powerapps.com"||e.endsWith(".api.powerapps.com"))}function Qr(e,t){return new Ut.SdkError(Fc.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}function $c(e){return new Ut.SdkError(_l.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: ${e}. The Power Apps service was not asked about it.`)}function ME(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}function UE(e){if(typeof e=="string"&&e.length>0)return Un(e,500);if(st(e)){let t=st(e.error)?e.error.message:void 0;for(let r of[t,e.Message,e.message])if(typeof r=="string")return Un(r,500)}return"request failed"}function $4(e){return st(e)&&st(e.error)?e.error.code:void 0}function BE(e){if(typeof e=="string"){let r=e.slice(0,gi.length).toLowerCase()===gi.toLowerCase()?e.slice(gi.length):e;if(R4.test(r)&&!/^\.{1,2}$/.test(r))return r}throw new Ut.InvalidArgumentError(`connector must be a connector's short name ('shared_office365users') or its full API id ('${gi}shared_office365users'); got ${typeof e=="string"?`'${Un(e,80)}'`:Zi(e)}.`)}function F4(e,t,r){let n=`Connection row ${t}`;if(!st(e))throw Qr(n,`it is ${Zi(e)}, not an object`);let i=e.properties;if(!st(i))throw Qr(n,`its properties are ${Zi(i)}, not an object`);let o=i.apiId;if(typeof o!="string"||o.slice(0,gi.length).toLowerCase()!==gi.toLowerCase())throw Qr(n,`its apiId is not '${gi}<connector>'`);let a=o.slice(gi.length);if(a===""||a.includes("/"))throw Qr(n,"its apiId names no single connector");if(L4.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw Qr(n,"it has no name");let l=i.environment,u=st(l)?l.name:void 0;if(typeof u!="string"||u.toLowerCase()!==r.toLowerCase())throw Qr(n,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw Qr(n,`its displayName is ${Zi(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw Qr(n,`its statuses are ${Zi(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let p=st(f)?f.status:void 0;if(typeof p!="string")throw Qr(n,"one of its statuses has no string status");return p})}}var Km=class{constructor(t,r,n){this.org=t,this.instanceUrl=r,this.service=n,this.swaggers=new Map}async listConnections(){let t=this.requireService(),r=await this.resolveEnvironment(t),n=[],i=new Set,o=`${r.origin}/providers/Microsoft.PowerApps/connections?api-version=${xE}&$filter=${ME(r.id)}`,a=await this.send(t,o,!0),s=1,l=0;for(;;){let u=`Page ${s} of the connections`,c=a.body,d=c?.value;if(!Array.isArray(d))throw Qr(u,`its value is ${Zi(d)}, not an array`);for(let p of d){let m=F4(p,l,r.id);l+=1,m&&n.push(m)}let f=c?.nextLink;if(f==null)return n;if(typeof f!="string"||f.length===0)throw Qr(u,`its nextLink is ${f===""?"an empty string":Zi(f)}, not a non-empty string`);if(i.has(f))throw new Ut.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${Un(f)}'), which would loop indefinitely.`);i.add(f),this.assertSameOrigin(f,r.parsed),a=await this.send(t,f,!0),s+=1}}async listConnectorOperations(t){let r=this.requireService(),n=BE(t);return(0,Fc.projectConnectorOperations)(await this.swagger(r,n))}async getConnectorOperationSchema(t,r){let n=this.requireService(),i=BE(t);if(typeof r!="string"||r==="")throw new Ut.InvalidArgumentError("operationId must be a non-empty string.");return(0,Fc.projectConnectorOperationSchema)(await this.swagger(n,i),r)}requireService(){if(!this.service)throw new Ut.SdkError(_l.CONNECTIVITY_NOT_CONFIGURED_CODE,"This SDK was created without a powerAppsServiceClient (MakerSdkOptions), so it cannot read connections or connectors: it needs an HttpClient that authenticates for https://service.powerapps.com/ and does not follow redirects. Nothing was requested.");return this.service}resolveEnvironment(t){if(!this.environment){let r=this.verifyEnvironment(t);this.environment=r,r.catch(()=>{this.environment===r&&(this.environment=void 0)})}return this.environment}async verifyEnvironment(t){let r=this.candidateBapOrigin(),n=await this.readEnvironmentId(),i=`${r}/providers/Microsoft.BusinessAppPlatform/environments/${encodeURIComponent(n)}?api-version=${T4}`,o=(await this.send(t,i,!1)).body,a=st(o)?o.properties:void 0,s=st(o)?o.name:void 0;if(typeof s!="string"||s.toLowerCase()!==n.toLowerCase())throw $c(`BAP's environment row is not the one named '${Un(n,80)}' (its name)`);let l=st(a)&&st(a.linkedEnvironmentMetadata)?a.linkedEnvironmentMetadata.instanceUrl:void 0,u=typeof l=="string"?Nl(l):void 0,c=Nl(this.instanceUrl);if(!u||!c||!FE(u,c))throw $c("BAP's row is not linked to this org (its linkedEnvironmentMetadata.instanceUrl is another origin)");let d=st(a)?a.runtimeEndpoints:void 0,f=st(d)?d["microsoft.PowerApps"]:void 0,p=typeof f=="string"?Nl(f):void 0;if(!p||p.protocol!=="https:"||!x4(p.host.toLowerCase()))throw $c("BAP's Power Apps runtime endpoint is not an https host of api.powerapps.com (runtimeEndpoints['microsoft.PowerApps'])");return{id:n,origin:p.origin.toLowerCase(),parsed:p}}candidateBapOrigin(){let t=Nl(this.instanceUrl),r=t?t.host.toLowerCase():"",n=O4.exec(r);if(n&&n[1]!=="9")return D4;if(P4.test(r))return I4;throw new Ut.SdkError(_l.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The org's host is not one of the clouds this reads in (${t?`'${Un(t.host,80)}'`:`'${Un(this.instanceUrl,80)}', which is not a URL`}): a Public org is <name>.crm[N].dynamics.com (N other than 9) and a Test org <name>.crmtest.dynamics.com. GCC (crm9), GCC High, DoD, China, ports and custom domains are not supported. Nothing was requested.`)}async readEnvironmentId(){let t=(0,_4.ensureSuccess)(await this.org.get($E),this.org.apiUrl($E)).body,r=st(t)?t.Detail:void 0,n=st(r)?r.EnvironmentId:void 0;if(typeof n!="string"||n==="")throw $c("the org answered no environment id (RetrieveCurrentOrganization, Detail.EnvironmentId)");return n}swagger(t,r){let n=r.toLowerCase(),i=this.swaggers.get(n);if(!i){let o=this.readSwagger(t,r);i=o,this.swaggers.set(n,o),o.catch(()=>{this.swaggers.get(n)===o&&this.swaggers.delete(n)})}return i}async readSwagger(t,r){let n=await this.resolveEnvironment(t),i=encodeURIComponent(r),o=`${n.origin}${gi}${i}?api-version=${xE}&$filter=${ME(n.id)}`,a=(await this.send(t,o,!0)).body,s=st(a)?a.properties:void 0,l=st(s)?s.swagger:void 0;if(!st(l))throw Qr(`The connector '${Un(r,80)}'`,`its properties.swagger is ${Zi(l)}, not an object`);return(0,Fc.validateConnectorSwagger)(l),l}assertSameOrigin(t,r){let n=Nl(t);if(!n)throw new Ut.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${Un(t)}'`);if(!FE(n,r))throw new Ut.InvalidArgumentError(`Refusing to follow a cross-origin link ('${Un(n.origin,120)}' is not the environment's Power Apps endpoint '${r.origin}'); server-driven pagination must stay on that origin.`)}async send(t,r,n){let i;try{i=await t.get(r)}catch(o){throw o instanceof Ut.ConnectionError&&typeof o.statusCode=="number"&&o.statusCode>0?this.mapNon2xx(r,o.statusCode,void 0,n,o):o instanceof Ut.SdkError?o:new Ut.ConnectionError(r,0,o instanceof Error?o.message:String(o),o)}if(!i||typeof i.status!="number")throw new Ut.ConnectionError(r,0,"the transport returned no HTTP response");if(i.status>=200&&i.status<300)return i;throw this.mapNon2xx(r,i.status,i.body,n)}mapNon2xx(t,r,n,i,o){let a=o??new Ut.ConnectionError(t,r,UE(n),n);return i&&r===410&&$4(n)===k4?(0,Ut.attachCause)(new Ut.SdkError(_l.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE,`The Power Apps API this reads through is decommissioned for this environment: ${UE(n)} Fall back to pac, or to the Power Platform API when the host has a client for it; the SDK does not fall back.`),a):r===401||r===403?(0,_l.connectivityUnauthorized)(r,n,a):a}};hr.ConnectivityApi=Km});var Zm=v(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.projectConnectorTableSchema=Me.projectConnectorTables=Me.tableSchemaSuffix=Me.tablesSuffix=Me.encodeTable=Me.encodeDataset=Me.checkTabularConnection=Me.runtimeAuthority=Me.tabularRevision=Me.checkTableSchemaArguments=Me.checkListTablesArguments=void 0;var Vo=Q(),M=qo(),M4=/^[A-Za-z0-9_.-]{1,128}$/,Go=/^\.{1,2}$/,U4="shared_sharepointonline",B4=/^[0-9]{1,9}$/,q4=/^[A-Za-z0-9._~-]+$/,V4=/^\/apim\/([A-Za-z0-9._-]+)\/?$/,G4=/^\/connectors\/runtime\/invoke\/scalegroups\/([A-Za-z0-9._-]+)\/(scaleunits|shards)\/([A-Za-z0-9._-]+)\/apis\/([A-Za-z0-9._-]+)\/connections\/?$/,W4=/^[A-Za-z0-9._~!'()*-]$/,z4=/^[0-9A-Fa-f]{2}$/;function yi(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Dl(e){return typeof e=="string"?`'${(0,M.bounded)(e,80)}'`:(0,M.kindOf)(e)}function Jm(e,t){return new Vo.SdkError(M.CONNECTOR_NOT_TABULAR_CODE,`The connector '${(0,M.bounded)(e,80)}' has no tables: ${t}.`)}function Mc(e,t){return new Vo.SdkError(M.CONNECTOR_RUNTIME_UNSUPPORTED_CODE,`The connector '${(0,M.bounded)(e,80)}' runs where this SDK does not send a token: ${t}. Nothing was sent to it.`)}function j4(e){if(typeof e=="string"&&M4.test(e)&&!Go.test(e))return e;throw new Vo.InvalidArgumentError(`connectionId must be a connection's name (letters, digits, '_', '.', '-'; at most 128; not '.' or '..'); got ${Dl(e)}.`)}function H4(e){if(e!=null){if(typeof e=="string"&&e!==""&&e.split(",").find(r=>r===""||Go.test(r))===void 0)return e;throw new Vo.InvalidArgumentError(`dataset must be a non-empty string (a SharePoint site URL, a SQL 'server,database', \u2026) none of whose ','-separated parts is empty, '.' or '..', or absent for a connector without datasets; got ${Dl(e)}.`)}}function K4(e){if(typeof e=="string"&&e!==""&&!Go.test(e))return e;throw new Vo.InvalidArgumentError(`table must be a non-empty string other than '.' and '..'; got ${Dl(e)}.`)}function GE(e,t,r){return{short:(0,M.connectorShortName)(e),connectionId:j4(t),dataset:H4(r)}}Me.checkListTablesArguments=GE;function J4(e,t,r,n){return{...GE(e,t,r),table:K4(n)}}Me.checkTableSchemaArguments=J4;function Y4(e,t){let r=`The connector '${(0,M.bounded)(t,80)}'`,n=e.properties;if(!(0,M.isObject)(n))throw(0,M.unreadable)(r,`its properties are ${(0,M.kindOf)(n)}, not an object`);if(!yi(n,"interfaces"))throw Jm(t,"it declares no interfaces");let i=n.interfaces;if(!(0,M.isObject)(i))throw(0,M.unreadable)(r,`its properties.interfaces are ${(0,M.kindOf)(i)}, not an object`);if(!yi(i,"CDPTabular1"))throw Jm(t,"it declares no CDPTabular1 interface");let o=i.CDPTabular1;if(!(0,M.isObject)(o))throw(0,M.unreadable)(r,`its CDPTabular1 interface is ${(0,M.kindOf)(o)}, not an object`);let a=o.revisions;if(!(0,M.isObject)(a))throw(0,M.unreadable)(r,`its CDPTabular1 revisions are ${(0,M.kindOf)(a)}, not an object`);let s,l=new Map;for(let u of Object.keys(a)){let c=a[u],d=`its CDPTabular1 revision '${(0,M.bounded)(u,40)}'`;if(!(0,M.isObject)(c)||typeof c.status!="string")throw(0,M.unreadable)(r,`${d} is not an object with a string status`);if(c.status!=="Production")continue;if(!B4.test(u))throw(0,M.unreadable)(r,`${d} is a Production revision whose key is not a decimal integer of 1\u20139 digits`);let f=Q4(c.baseUrl);if(f===void 0)throw(0,M.unreadable)(r,`${d} has a baseUrl that is not '/' or '/'-separated [A-Za-z0-9._~-] segments`);let p=Number(u),m=l.get(p);if(m!==void 0)throw(0,M.unreadable)(r,`its Production revisions '${m}' and '${(0,M.bounded)(u,40)}' have the same number`);l.set(p,u),(!s||p>s.revisionNumber)&&(s={revisionNumber:p,revision:f})}if(!s)throw Jm(t,"its CDPTabular1 interface has no Production revision");return s.revision}Me.tabularRevision=Y4;function Q4(e){if(typeof e!="string")return;let t=e.replace(/^\/+/,"").replace(/\/+$/,"");return t===""?"":t.split("/").every(i=>q4.test(i)&&!Go.test(i))?t:void 0}function X4(e,t,r){let n=(0,M.isObject)(e.properties)?e.properties:void 0,i=n?n.primaryRuntimeUrl:void 0;if(typeof i!="string")throw Mc(r,`its primaryRuntimeUrl is ${(0,M.kindOf)(i)}, not a string`);let o=t.cloud==="Test",a=(o?`https://${t.name}.tip2-001.tip2.azure-apihub.net`:t.origin).toLowerCase(),s=(0,M.parseUrl)(i);if(!s||s.protocol!=="https:"||s.origin.toLowerCase()!==a)throw Mc(r,`its runtime ('${(0,M.bounded)(i,120)}') is not ${o?"this environment's measured API Hub host (<environment name>.tip2-001.tip2.azure-apihub.net)":"under this environment's own Power Platform API origin"} over https`);let l=i.slice(0,a.length).toLowerCase()===a?i.slice(a.length):void 0;if(o){let c=l===void 0?null:V4.exec(l);if(!c||Go.test(c[1]))throw Mc(r,`its runtime ('${(0,M.bounded)(i,120)}') is not <host>/apim/<connector>`);return{transport:"invoke",origin:a,path:`/apim/${c[1]}`}}let u=l===void 0?null:G4.exec(l);if(!u||[u[1],u[3],u[4]].some(c=>Go.test(c)))throw Mc(r,`its runtime ('${(0,M.bounded)(i,120)}') is not <origin>/connectors/runtime/invoke/scalegroups/<group>/(scaleunits|shards)/<unit>/apis/<api>/connections`);return{transport:"direct",origin:a,path:`/connectors/runtime/invoke/scalegroups/${u[1]}/${u[2]}/${u[3]}/apis/${u[4]}/connections`}}Me.runtimeAuthority=X4;function Z4(e,t,r,n){let i=`The connection '${(0,M.bounded)(t,128)}'`;if(!(0,M.isObject)(e))throw(0,M.unreadable)(i,`it is ${(0,M.kindOf)(e)}, not an object`);if(e.name!==t)throw(0,M.unreadable)(i,`its name is ${Dl(e.name)}, not the requested connection`);let o=e.properties;if(!(0,M.isObject)(o))throw(0,M.unreadable)(i,`its properties are ${(0,M.kindOf)(o)}, not an object`);let a=o.apiId;if(typeof a!="string"||a.toLowerCase()!==`${M.CONNECTOR_PREFIX}${r}`.toLowerCase())throw(0,M.unreadable)(i,`its apiId is ${Dl(a)}, not the connector '${(0,M.bounded)(r,80)}'`);let s=o.environment,l=(0,M.isObject)(s)?s.name:void 0;if(typeof l!="string"||l.toLowerCase()!==n.toLowerCase())throw(0,M.unreadable)(i,"it is not a connection of this environment (properties.environment.name)");return t}Me.checkTabularConnection=Z4;function VE(e){return encodeURIComponent(e).replace(/[!'()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`)}function eV(e){if(e==="")return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="%"){if(!z4.test(e.slice(t+1,t+3)))return!1;t+=2}else if(!W4.test(e[t]))return!1;return!0}function WE(e,t){let r,n,i;try{r=VE(e),n=VE(r),i=decodeURIComponent(n)}catch{throw new Vo.InvalidArgumentError(`${t} is not well-formed Unicode (it has a lone surrogate), so it cannot be sent.`)}if(!eV(n)||Go.test(n)||i!==r)throw new Vo.InvalidArgumentError(`${t} cannot be sent as one path segment.`);return n}function Xm(e){return e.split(",").map((t,r)=>WE(t,`dataset part ${r}`)).join(",")}Me.encodeDataset=Xm;function zE(e){return WE(e,"table")}Me.encodeTable=zE;function tV(e,t){if(t===void 0)return"/tables";let r=e.toLowerCase()===U4?"allTables":"tables";return`/datasets/${Xm(t)}/${r}`}Me.tablesSuffix=tV;function rV(e,t){return`/$metadata.json${e===void 0?"":`/datasets/${Xm(e)}`}/tables/${zE(t)}`}Me.tableSchemaSuffix=rV;function Wa(e,t){let r=t.toLowerCase();for(let n of Object.keys(e))if(n.toLowerCase()===r)return{found:!0,value:e[n]};return{found:!1}}function nV(e){let t="The table list",r;if(Array.isArray(e))r=e;else if((0,M.isObject)(e)){for(let o of["nextLink","@odata.nextLink"])if(Wa(e,o).found)throw(0,M.unreadable)(t,`it carries a ${o} \u2014 a paged answer is refused, never read as a partial list`);let n=Wa(e,"value"),i=n.found?n:Wa(e,"tables");if(!i.found)throw(0,M.unreadable)(t,"it is an object with neither a value nor a tables member");if(!Array.isArray(i.value))throw(0,M.unreadable)(t,`its ${n.found?"value":"tables"} is ${(0,M.kindOf)(i.value)}, not an array`);r=i.value}else throw(0,M.unreadable)(t,`it is ${(0,M.kindOf)(e)}, not an array or an object`);return{tables:r.map((n,i)=>iV(n,i))}}Me.projectConnectorTables=nV;function iV(e,t){let r=`Table row ${t}`;if(!(0,M.isObject)(e))throw(0,M.unreadable)(r,`it is ${(0,M.kindOf)(e)}, not an object`);let n=Wa(e,"name");if(!n.found||typeof n.value!="string"||n.value==="")throw(0,M.unreadable)(r,"it has no non-empty string name");let i=Wa(e,"displayName");if(i.found&&typeof i.value!="string")throw(0,M.unreadable)(r,`its displayName is ${(0,M.kindOf)(i.value)}, not a string`);let o=Wa(e,"id");if(o.found&&(typeof o.value!="string"||o.value===""))throw(0,M.unreadable)(r,`its id is ${o.value===""?"an empty string":(0,M.kindOf)(o.value)}, not a non-empty string`);return{name:n.value,displayName:i.found?i.value:null,id:o.found?o.value:n.value}}function Ym(e,t,r){if(!yi(e,t))return;let n=e[t];if(!(0,M.isObject)(n))throw(0,M.unreadable)("The table schema",`its ${r} is ${(0,M.kindOf)(n)}, not an object`);return n}function Qm(e,t,r){if(!yi(e,t))return;let n=e[t];if(typeof n!="string")throw(0,M.unreadable)(r,`its ${t} is ${(0,M.kindOf)(n)}, not a string`);return n}function oV(e,t){var r,n;if(yi(e,"$ref"))throw(0,M.unreadable)(t,"it is a $ref, whose type is not guessed");let i=Qm(e,"type",t),o=Qm(e,"format",t),a=(r=i??o)!==null&&r!==void 0?r:"object";if(!yi(e,"items"))return a;let s=e.items;if(!(0,M.isObject)(s))throw(0,M.unreadable)(t,`its items are ${(0,M.kindOf)(s)}, not an object`);if(yi(s,"$ref"))throw(0,M.unreadable)(t,"its items are a $ref, whose type is not guessed");return`${a}<${(n=Qm(s,"type",`${t} items`))!==null&&n!==void 0?n:"object"}>`}function aV(e,t){let r="The table schema";if(!(0,M.isObject)(e))throw(0,M.unreadable)(r,`it is ${(0,M.kindOf)(e)}, not an object`);let n=Ym(e,"items","items"),i=Ym(e,"schema","schema"),o=i?Ym(i,"items","schema.items"):void 0,a=[[e,"the answer"],[n,"items"],[i,"schema"],[o,"schema.items"]],s=new Set;for(let[c,d]of a)if(c&&yi(c,"required")){let f=c.required;if(!Array.isArray(f))throw(0,M.unreadable)(r,`the required of ${d} is ${(0,M.kindOf)(f)}, not an array`);f.forEach(p=>{if(typeof p!="string")throw(0,M.unreadable)(r,`the required of ${d} has an entry that is ${(0,M.kindOf)(p)}, not a string`);s.add(p.toLowerCase())})}let l;for(let[c,d]of a)if(c&&yi(c,"properties")){if(!(0,M.isObject)(c.properties))throw(0,M.unreadable)(r,`the properties of ${d} are ${(0,M.kindOf)(c.properties)}, not an object`);l=c.properties;break}if(!l)throw(0,M.unreadable)(r,"it has no properties, items.properties, schema.properties or schema.items.properties");let u=Object.keys(l).map(c=>{let d=`Column '${(0,M.bounded)(c,80)}'`,f=l[c];if(!(0,M.isObject)(f))throw(0,M.unreadable)(d,`it is ${(0,M.kindOf)(f)}, not an object`);return{name:c,type:oV(f,d),required:s.has(c.toLowerCase())}});return{table:t,columns:u}}Me.projectConnectorTableSchema=aV});var jE=v(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});Uc.PowerPlatformApiDiscovery=void 0;var eh=class{constructor(t){this.clusterCategory=t}getTokenAudience(){return`https://${this._getEnvironmentApiHostNameSuffix()}`}getTokenEndpointHost(){return this._getEnvironmentApiHostNameSuffix()}getTenantEndpoint(t){return this._generatePowerPlatformApiDomain(t,"tenant")}getTenantIslandClusterEndpoint(t){return this._generatePowerPlatformApiDomain(t,"tenant","il-")}getEnvironmentEndpoint(t){return this._generatePowerPlatformApiDomain(t,"environment")}_generatePowerPlatformApiDomain(t,r,n=""){if(!/^[a-zA-Z0-9\-]+$/g.test(t))throw new Error(`Cannot generate Power Platform API endpoint because the ${r} identifier contains invalid host name characters, only alphanumeric and dash characters are expected: ${t}`);let i=this._getHexApiSuffixLength(),o=t.toLowerCase().replace(/-/g,"");if(i>=o.length)throw new Error(`Cannot generate Power Platform API endpoint because the normalized ${r} identifier must be at least ${i+1} characters in length: ${o}`);let a=o.substring(o.length-i),s=o.substring(0,o.length-i),l=this._getEnvironmentApiHostNameSuffix();return`${n}${s}.${a}.${r}.${l}`}_getHexApiSuffixLength(){switch(this.clusterCategory){case"firstrelease":case"prod":return 2;default:return 1}}_getEnvironmentApiHostNameSuffix(){switch(this.clusterCategory){case"local":return"api.powerplatform.localhost";case"dev":return"api.dev.powerplatform.com";case"test":return"api.test.powerplatform.com";case"preprod":return"api.preprod.powerplatform.com";case"firstrelease":case"prod":return"api.powerplatform.com";case"gov":return"api.gov.powerplatform.microsoft.us";case"high":return"api.high.powerplatform.microsoft.us";case"dod":return"api.appsplatform.us";case"mooncake":return"api.powerplatform.partner.microsoftonline.cn";case"ex":return"api.powerplatform.eaglex.ic.gov";case"rx":return"api.powerplatform.microsoft.scloud";default:throw new Error(`Invalid ClusterCategory value: ${this.clusterCategory}`)}}};Uc.PowerPlatformApiDiscovery=eh});var HE=v(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});Bc.PowerPlatformApiDiscovery=void 0;var sV=jE();Object.defineProperty(Bc,"PowerPlatformApiDiscovery",{enumerable:!0,get:function(){return sV.PowerPlatformApiDiscovery}})});var QE=v(eo=>{"use strict";Object.defineProperty(eo,"__esModule",{value:!0});eo.platformTokenAudience=eo.platformEnvironment=eo.platformClusterOf=void 0;var KE=HE(),JE=Q(),YE=qo(),lV=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,uV=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,cV=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,dV=/^default-/i;function th(e,t=80){return e.length>t?`${e.slice(0,t)}\u2026`:e}function fV(e){try{return new URL(e).host.toLowerCase()}catch{return}}function pV(e){let t=fV(e);if(t){if(uV.test(t))return{cloud:"Test",category:"test"};let r=lV.exec(t);if(r&&r[1]!=="9")return{cloud:"Public",category:"prod"}}throw new JE.SdkError(YE.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The Power Platform API route is built for the Test and Public clouds; this org (${t?`'${th(t)}'`:`'${th(e)}', which is not a URL`}) is another cloud. A Public org is <name>.crm[N].dynamics.com (N other than 9) and a Test org <name>.crmtest.dynamics.com. GCC (crm9), GCC High, DoD, China, ports and custom domains are pending or out of scope. Nothing was requested.`)}eo.platformClusterOf=pV;function mV(e,t){let r=dV.test(e)?e.slice(8):e;if(!cV.test(r))throw new JE.SdkError(YE.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: its name ('${th(e)}') is neither a GUID nor 'Default-<GUID>', the forms this route is measured for. The Power Platform API was not asked about it.`);return{origin:`https://${new KE.PowerPlatformApiDiscovery(t).getEnvironmentEndpoint(e)}`,guid:r.toLowerCase()}}eo.platformEnvironment=mV;function hV(e){return new KE.PowerPlatformApiDiscovery(e).getTokenAudience()}eo.platformTokenAudience=hV});var ZE=v(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.PlatformConnectivityApi=za.assertTabularCloud=void 0;var bn=Q(),rh=Al(),de=qo(),XE=QE(),bi=Zm(),nh="1";function ih(e){let t=(0,de.connectivityCloudOf)(e);if(t!=="Test"&&t!=="Public")throw new bn.SdkError(de.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,"Connector tables are read in the Test and Public clouds; this org's cloud is neither (GCC, GCC High and DoD are pending). Nothing was requested.")}za.assertTabularCloud=ih;var oh=class{constructor(t,r,n,i){this.org=t,this.instanceUrl=r,this.client=n,this.runtime=i,this.records=new Map,this.swaggers=new Map}async listConnections(){let t=await this.resolveEnvironment(),r=[],n=new Set,i=await this.send(this.client,"GET",`${t.origin}/connectivity/connections?api-version=${nh}`,[401,403]),o=1,a=0;for(;;){let s=`Page ${o} of the connections`,l=i.body,u=l?.value;if(!Array.isArray(u))throw(0,de.unreadable)(s,`its value is ${(0,de.kindOf)(u)}, not an array`);for(let d of u){let f=(0,de.readConnection)(d,a,t.name);a+=1,f&&r.push(f)}let c=l?.nextLink;if(c==null)return r;if(typeof c!="string"||c.length===0)throw(0,de.unreadable)(s,`its nextLink is ${c===""?"an empty string":(0,de.kindOf)(c)}, not a non-empty string`);if(n.has(c))throw new bn.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${(0,de.bounded)(c)}'), which would loop indefinitely.`);n.add(c),this.assertSameOrigin(c,t.parsed),i=await this.send(this.client,"GET",c,[401,403]),o+=1}}async listConnectorOperations(t){let r=(0,de.connectorShortName)(t);return(0,rh.projectConnectorOperations)(await this.swagger(r))}async getConnectorOperationSchema(t,r){let n=(0,de.connectorShortName)(t);if(typeof r!="string"||r==="")throw new bn.InvalidArgumentError("operationId must be a non-empty string.");return(0,rh.projectConnectorOperationSchema)(await this.swagger(n),r)}async listConnectorTables(t,r,n){ih(this.instanceUrl);let i=(0,bi.checkListTablesArguments)(t,r,n),o=(0,bi.tablesSuffix)(i.short,i.dataset);return(0,bi.projectConnectorTables)(await this.invokeTabular(i,o))}async getConnectorTableSchema(t,r,n,i){ih(this.instanceUrl);let o=(0,bi.checkTableSchemaArguments)(t,r,n,i),a=(0,bi.tableSchemaSuffix)(o.dataset,o.table);return(0,bi.projectConnectorTableSchema)(await this.invokeTabular(o,a),o.table)}async invokeTabular(t,r){let n=this.requireRuntime(),i=await this.resolveEnvironment(),o=await this.record(t.short),a=(0,bi.tabularRevision)(o,t.short),s=(0,bi.runtimeAuthority)(o,{cloud:i.cloud,name:i.name,origin:i.origin},t.short),l=`${i.origin}/connectivity/connectors/${encodeURIComponent(t.short)}/connections/${encodeURIComponent(t.connectionId)}?$filter=${(0,de.environmentFilter)(i.name)}&api-version=${nh}`,u=(await this.send(this.client,"GET",l,[401,403])).body,c=(0,bi.checkTabularConnection)(u,t.connectionId,t.short,i.name),d=`${s.path}/${c}${a===""?"":`/${a}`}${r}`;return(s.transport==="invoke"?await this.send(n,"POST",`${s.origin}/invoke`,[401],{"X-Ms-Request-Url":d,"X-Ms-Request-Method":"GET"}):await this.send(n,"GET",`${s.origin}${d}`,[401])).body}requireRuntime(){if(!this.runtime)throw new bn.SdkError(de.CONNECTIVITY_NOT_CONFIGURED_CODE,"This SDK was created without a connectorRuntimeClient (MakerSdkOptions), so it cannot read connector tables: it needs an HttpClient that authenticates for API Hub (https://apihub.azure.com) and does not follow redirects. Nothing was requested.");return this.runtime}resolveEnvironment(){if(!this.environment){let t=this.readEnvironment();this.environment=t,t.catch(()=>{this.environment===t&&(this.environment=void 0)})}return this.environment}async readEnvironment(){let{cloud:t,category:r}=(0,XE.platformClusterOf)(this.instanceUrl),n=await(0,de.readEnvironmentName)(this.org),{origin:i,guid:o}=(0,XE.platformEnvironment)(n,r),a=(0,de.parseUrl)(i);if(!a)throw(0,de.unreadable)("The Power Platform API origin",`'${(0,de.bounded)(i)}' is not a URL`);return{cloud:t,origin:i,parsed:a,name:n,guid:o}}cached(t,r,n){let i=t.get(r);if(!i){let o=n();i=o,t.set(r,o),o.catch(()=>{t.get(r)===o&&t.delete(r)})}return i}record(t){return this.cached(this.records,t.toLowerCase(),()=>this.readRecord(t))}async readRecord(t){let r=await this.resolveEnvironment(),n=`${r.origin}/connectivity/connectors/${encodeURIComponent(t)}?$filter=${(0,de.environmentFilter)(r.name)}&api-version=${nh}`,i=(await this.send(this.client,"GET",n,[401,403])).body,o=(0,de.isObject)(i)?i.name:void 0;if(!(0,de.isObject)(i)||typeof o!="string"||o.toLowerCase()!==t.toLowerCase())throw(0,de.unreadable)(`The connector '${(0,de.bounded)(t,80)}'`,`the record's name is ${typeof o=="string"?`'${(0,de.bounded)(o,80)}'`:(0,de.kindOf)(o)}, not the requested connector`);return i}swagger(t){return this.cached(this.swaggers,t.toLowerCase(),async()=>{let n=(await this.record(t)).properties,i=(0,de.isObject)(n)?n.swagger:void 0;if(!(0,de.isObject)(i))throw(0,de.unreadable)(`The connector '${(0,de.bounded)(t,80)}'`,`its properties.swagger is ${(0,de.kindOf)(i)}, not an object`);return(0,rh.validateConnectorSwagger)(i),i})}assertSameOrigin(t,r){let n=(0,de.parseUrl)(t);if(!n)throw new bn.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${(0,de.bounded)(t)}'`);if(!(0,de.sameOrigin)(n,r))throw new bn.InvalidArgumentError(`Refusing to follow a cross-origin link ('${(0,de.bounded)(n.origin,120)}' is not the environment's Power Platform API origin '${r.origin}'); server-driven pagination must stay on that origin.`)}async send(t,r,n,i,o){let a;try{a=r==="GET"?await t.get(n):await t.post(n,void 0,{headers:o})}catch(s){throw s instanceof bn.ConnectionError&&typeof s.statusCode=="number"&&s.statusCode>0?this.non2xx(n,s.statusCode,void 0,i,s):s instanceof bn.SdkError?s:new bn.ConnectionError(n,0,s instanceof Error?s.message:String(s),s)}if(!a||typeof a.status!="number")throw new bn.ConnectionError(n,0,"the transport returned no HTTP response");if(a.status>=200&&a.status<300)return a;throw this.non2xx(n,a.status,a.body,i)}non2xx(t,r,n,i,o){let a=o??new bn.ConnectionError(t,r,(0,de.messageOf)(n),n);return i.includes(r)?(0,de.connectivityUnauthorized)(r,n,a):a}};za.PlatformConnectivityApi=oh});var tA=v(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});Vc.ConnectivityRouter=void 0;var ah=Q(),gV=qE(),qc=qo(),eA=Zm(),sh=ZE(),lh=class{constructor(t,r,n){this.org=t,this.instanceUrl=r,this.clients=n}async listConnections(){return this.route().listConnections()}async listConnectorOperations(t){return this.route().listConnectorOperations(t)}async getConnectorOperationSchema(t,r){return this.route().getConnectorOperationSchema(t,r)}async listConnectorTables(t,r,n){return(0,sh.assertTabularCloud)(this.instanceUrl),(0,eA.checkListTablesArguments)(t,r,n),this.tabularRoute().listConnectorTables(t,r,n)}async getConnectorTableSchema(t,r,n,i){return(0,sh.assertTabularCloud)(this.instanceUrl),(0,eA.checkTableSchemaArguments)(t,r,n,i),this.tabularRoute().getConnectorTableSchema(t,r,n,i)}route(){return this.delegate||(this.delegate=this.select()),this.delegate}platformRoute(t){return this.platform||(this.platform=new sh.PlatformConnectivityApi(this.org,this.instanceUrl,t,this.clients.connectorRuntimeClient)),this.platform}tabularRoute(){let{powerPlatformApiClient:t,connectorRuntimeClient:r}=this.clients,n=[t?void 0:"powerPlatformApiClient (the Power Platform API)",r?void 0:"connectorRuntimeClient (API Hub, https://apihub.azure.com)"].filter(i=>i!==void 0);if(n.length>0||!t)throw new ah.SdkError(qc.CONNECTIVITY_NOT_CONFIGURED_CODE,`Connector tables are read through the Power Platform API and the connector runtime: this SDK was created without MakerSdkOptions.${n.join(" or MakerSdkOptions.")}, an HttpClient that does not follow redirects. Nothing was requested.`);return this.platformRoute(t)}select(){let t=(0,qc.connectivityCloudOf)(this.instanceUrl),{powerAppsServiceClient:r,powerPlatformApiClient:n}=this.clients;if(t==="Unsupported")throw new ah.SdkError(qc.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,"This org's cloud has no connection/connector route: the Test and Public clouds are served (through the Power Platform API, or the classic route for Public); GCC, GCC High and DoD are pending. Nothing was requested.");if(n)return this.platformRoute(n);if(t==="Public"&&r)return new gV.ConnectivityApi(this.org,this.instanceUrl,r);throw new ah.SdkError(qc.CONNECTIVITY_NOT_CONFIGURED_CODE,t==="Test"?"This org is in the Test cloud, whose connection and connector reads go through the Power Platform API: supply MakerSdkOptions.powerPlatformApiClient (an HttpClient that authenticates for the Power Platform API and does not follow redirects). Nothing was requested.":"This org is in the Public cloud: supply MakerSdkOptions.powerPlatformApiClient (the Power Platform API route) or powerAppsServiceClient (the classic route). Neither was given, so nothing was requested.")}};Vc.ConnectivityRouter=lh});var ja=v(vi=>{"use strict";function yV(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 ch(e,t){return t===void 0&&(t=Object),t&&typeof t.freeze=="function"?t.freeze(e):e}function bV(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 rA=ch({HTML:"text/html",isHTML:function(e){return e===rA.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),nA=ch({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(e){return e===nA.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"}),Gc=/[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]/,uh=new RegExp("[\\-\\.0-9"+Gc.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),vV=new RegExp("^"+Gc.source+uh.source+"*(?::"+Gc.source+uh.source+"*)?$");vi.assign=bV;vi.find=yV;vi.freeze=ch;vi.MIME_TYPE=rA;vi.NAMESPACE=nA;vi.nameStartChar=Gc;vi.nameChar=uh;vi.tagNamePattern=vV});var Eh=v(Ai=>{var dh=ja(),Bn=dh.find,Ol=dh.NAMESPACE,Ha=dh.tagNamePattern;function wV(e){return e!==""}function CV(e){return e?e.split(/[\t\n\f\r ]+/).filter(wV):[]}function EV(e,t){return e.hasOwnProperty(t)||(e[t]=!0),e}function iA(e){if(!e)return[];var t=CV(e);return Object.keys(t.reduce(EV,{}))}function AV(e){return function(t){return e&&e.indexOf(t)!==-1}}function Rl(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function yr(e,t){var r=e.prototype;if(!(r instanceof t)){let i=function(){};var n=i;i.prototype=t.prototype,i=new i,Rl(r,i),e.prototype=r=i}r.constructor!=e&&(typeof e!="function"&&console.error("unknown Class:"+e),r.constructor=e)}var br={},Xr=br.ELEMENT_NODE=1,Ka=br.ATTRIBUTE_NODE=2,Il=br.TEXT_NODE=3,fA=br.CDATA_SECTION_NODE=4,pA=br.ENTITY_REFERENCE_NODE=5,SV=br.ENTITY_NODE=6,fh=br.PROCESSING_INSTRUCTION_NODE=7,ph=br.COMMENT_NODE=8,mA=br.DOCUMENT_NODE=9,hA=br.DOCUMENT_TYPE_NODE=10,wi=br.DOCUMENT_FRAGMENT_NODE=11,NV=br.NOTATION_NODE=12,Bt={},wt={},rse=Bt.INDEX_SIZE_ERR=(wt[1]="Index size error",1),nse=Bt.DOMSTRING_SIZE_ERR=(wt[2]="DOMString size error",2),gr=Bt.HIERARCHY_REQUEST_ERR=(wt[3]="Hierarchy request error",3),ise=Bt.WRONG_DOCUMENT_ERR=(wt[4]="Wrong document",4),oA=Bt.INVALID_CHARACTER_ERR=(wt[5]="Invalid character",5),ose=Bt.NO_DATA_ALLOWED_ERR=(wt[6]="No data allowed",6),ase=Bt.NO_MODIFICATION_ALLOWED_ERR=(wt[7]="No modification allowed",7),gA=Bt.NOT_FOUND_ERR=(wt[8]="Not found",8),sse=Bt.NOT_SUPPORTED_ERR=(wt[9]="Not supported",9),aA=Bt.INUSE_ATTRIBUTE_ERR=(wt[10]="Attribute in use",10),vn=Bt.INVALID_STATE_ERR=(wt[11]="Invalid state",11),lse=Bt.SYNTAX_ERR=(wt[12]="Syntax error",12),use=Bt.INVALID_MODIFICATION_ERR=(wt[13]="Invalid modification",13),cse=Bt.NAMESPACE_ERR=(wt[14]="Invalid namespace",14),dse=Bt.INVALID_ACCESS_ERR=(wt[15]="Invalid access",15);function fe(e,t){if(t instanceof Error)var r=t;else r=this,Error.call(this,wt[e]),this.message=wt[e],Error.captureStackTrace&&Error.captureStackTrace(this,fe);return r.code=e,t&&(this.message=this.message+": "+t),r}fe.prototype=Error.prototype;Rl(Bt,fe);function Ci(){}Ci.prototype={length:0,item:function(e){return e>=0&&e<this.length?this[e]:null},toString:function(e,t,r){for(var n=!!r&&!!r.requireWellFormed,i=[],o=0;o<this.length;o++)Ch(this[o],i,e,t,null,n);return i.join("")},filter:function(e){return Array.prototype.filter.call(this,e)},indexOf:function(e){return Array.prototype.indexOf.call(this,e)}};function Ja(e,t){this._node=e,this._refresh=t,mh(this)}function mh(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!==t){var r=e._refresh(e._node);if(IA(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];Rl(r,e),e._inc=t}}Ja.prototype.item=function(e){return mh(this),this[e]||null};yr(Ja,Ci);function zc(){this._nameIndex=Object.create(null)}function yA(e,t){for(var r=e.length;r--;)if(e[r]===t)return r}function _V(e,t){e._nameIndex[t.nodeName]=t}function bA(e,t){e._nameIndex[t.nodeName]===t&&delete e._nameIndex[t.nodeName]}function sA(e,t,r,n){if(n?(t[yA(t,n)]=r,bA(t,n)):t[t.length++]=r,_V(t,r),e){r.ownerElement=e;var i=e.ownerDocument;i&&(n&&CA(i,e,n),TV(i,e,r))}}function lA(e,t,r){var n=yA(t,r);if(n>=0){for(var i=t.length-1;n<i;)t[n]=t[++n];if(t.length=i,bA(t,r),e){var o=e.ownerDocument;o&&(CA(o,e,r),r.ownerElement=null)}}else throw new fe(gA,new Error(e.tagName+"@"+r))}zc.prototype={length:0,item:Ci.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 fe(aA);var r=this._nameIndex[e.nodeName];return sA(this._ownerElement,this,e,r),r},setNamedItemNS:function(e){var t=e.ownerElement,r;if(t&&t!=this._ownerElement)throw new fe(aA);return r=this.getNamedItemNS(e.namespaceURI,e.localName),sA(this._ownerElement,this,e,r),r},removeNamedItem:function(e){var t=this.getNamedItem(e);return lA(this._ownerElement,this,t),t},removeNamedItemNS:function(e,t){var r=this.getNamedItemNS(e,t);return lA(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 vA(){}vA.prototype={hasFeature:function(e,t){return!0},createDocument:function(e,t,r){var n=new Ll;if(n.implementation=this,n.childNodes=new Ci,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 Yc;return n.name=e,n.nodeName=e,n.publicId=t||"",n.systemId=r||"",n}};function Ne(){}Ne.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 Hc(this,e,t)},replaceChild:function(e,t){Hc(this,e,t,AA),t&&this.removeChild(t)},removeChild:function(e){return EA(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return DA(this.ownerDocument||this,this,e)},normalize:function(){vt(this,null,{enter:function(e){for(var t=e.firstChild;t;){var r=t.nextSibling;if(r!==null&&r.nodeType===Il&&t.nodeType===Il){for(var n=[],i=r;i!==null&&i.nodeType===Il;)n.push(i.data),i=i.nextSibling;for(var o=t.nextSibling;o!==i;){var a=o.nextSibling;o.parentNode=null,o.previousSibling=null,o.nextSibling=null,o=a}t.nextSibling=i,i!==null?i.previousSibling=t:e.lastChild=t,t.appendData(n.join("")),Jc(e.ownerDocument,e),t=i}else t=r}return!0}})},isSupported:function(e,t){return this.ownerDocument.implementation.hasFeature(e,t)},hasAttributes:function(){return this.attributes.length>0},lookupPrefix:function(e){for(var t=this;t;){var r=t._nsMap;if(r){for(var n in r)if(Object.prototype.hasOwnProperty.call(r,n)&&r[n]===e)return n}t=t.nodeType==Ka?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==Ka?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){var t=this.lookupPrefix(e);return t==null}};function wA(e){return e=="<"&&"<"||e==">"&&">"||e=="&"&&"&"||e=='"'&&"""||"&#"+e.charCodeAt()+";"}Rl(br,Ne);Rl(br,Ne.prototype);function jc(e,t){return vt(e,null,{enter:function(r){return t(r)?vt.STOP:!0}})===vt.STOP}function vt(e,t,r){for(var n=[{node:e,context:t,phase:vt.ENTER}];n.length>0;){var i=n.pop();if(i.phase===vt.ENTER){var o=r.enter(i.node,i.context);if(o===vt.STOP)return vt.STOP;if(n.push({node:i.node,context:o,phase:vt.EXIT}),o==null)continue;for(var a=i.node.lastChild;a;)n.push({node:a,context:o,phase:vt.ENTER}),a=a.previousSibling}else r.exit&&r.exit(i.node,i.context)}}vt.STOP=Symbol("walkDOM.STOP");vt.ENTER=0;vt.EXIT=1;function Ll(){this.ownerDocument=this}function TV(e,t,r){e&&e._inc++;var n=r.namespaceURI;n===Ol.XMLNS&&(t._nsMap[r.prefix?r.localName:""]=r.value)}function CA(e,t,r,n){e&&e._inc++;var i=r.namespaceURI;i===Ol.XMLNS&&delete t._nsMap[r.prefix?r.localName:""]}function Jc(e,t,r){if(e&&e._inc){e._inc++;var n=t.childNodes;if(r)n[n.length++]=r;else{for(var i=t.firstChild,o=0;i;)n[o++]=i,i=i.nextSibling;n.length=o,delete n[n.length]}}}function EA(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,Jc(e.ownerDocument,e),t}function DV(e){return e&&(e.nodeType===Ne.DOCUMENT_NODE||e.nodeType===Ne.DOCUMENT_FRAGMENT_NODE||e.nodeType===Ne.ELEMENT_NODE)}function IV(e){return e&&(qn(e)||hh(e)||Ei(e)||e.nodeType===Ne.DOCUMENT_FRAGMENT_NODE||e.nodeType===Ne.COMMENT_NODE||e.nodeType===Ne.PROCESSING_INSTRUCTION_NODE)}function Ei(e){return e&&e.nodeType===Ne.DOCUMENT_TYPE_NODE}function qn(e){return e&&e.nodeType===Ne.ELEMENT_NODE}function hh(e){return e&&e.nodeType===Ne.TEXT_NODE}function uA(e,t){var r=e.childNodes||[];if(Bn(r,qn)||Ei(t))return!1;var n=Bn(r,Ei);return!(t&&n&&r.indexOf(n)>r.indexOf(t))}function cA(e,t){var r=e.childNodes||[];function n(o){return qn(o)&&o!==t}if(Bn(r,n))return!1;var i=Bn(r,Ei);return!(t&&i&&r.indexOf(i)>r.indexOf(t))}function OV(e,t,r){if(!DV(e))throw new fe(gr,"Unexpected parent node type "+e.nodeType);if(r&&r.parentNode!==e)throw new fe(gA,"child not in parent");if(!IV(t)||Ei(t)&&e.nodeType!==Ne.DOCUMENT_NODE)throw new fe(gr,"Unexpected node type "+t.nodeType+" for parent node type "+e.nodeType)}function PV(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===Ne.DOCUMENT_FRAGMENT_NODE){var o=i.filter(qn);if(o.length>1||Bn(i,hh))throw new fe(gr,"More than one element or text in fragment");if(o.length===1&&!uA(e,r))throw new fe(gr,"Element in fragment can not be inserted before doctype")}if(qn(t)&&!uA(e,r))throw new fe(gr,"Only one element can be added and only after doctype");if(Ei(t)){if(Bn(n,Ei))throw new fe(gr,"Only one doctype is allowed");var a=Bn(n,qn);if(r&&n.indexOf(a)<n.indexOf(r))throw new fe(gr,"Doctype can only be inserted before an element");if(!r&&a)throw new fe(gr,"Doctype can not be appended since element is present")}}function AA(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===Ne.DOCUMENT_FRAGMENT_NODE){var o=i.filter(qn);if(o.length>1||Bn(i,hh))throw new fe(gr,"More than one element or text in fragment");if(o.length===1&&!cA(e,r))throw new fe(gr,"Element in fragment can not be inserted before doctype")}if(qn(t)&&!cA(e,r))throw new fe(gr,"Only one element can be added and only after doctype");if(Ei(t)){let l=function(u){return Ei(u)&&u!==r};var s=l;if(Bn(n,l))throw new fe(gr,"Only one doctype is allowed");var a=Bn(n,qn);if(r&&n.indexOf(a)<n.indexOf(r))throw new fe(gr,"Doctype can only be inserted before an element")}}function Hc(e,t,r,n){OV(e,t,r),e.nodeType===Ne.DOCUMENT_NODE&&(n||PV)(e,t,r);var i=t.parentNode;if(i&&i.removeChild(t),t.nodeType===wi){var o=t.firstChild;if(o==null)return t;var a=t.lastChild}else o=a=t;var s=r?r.previousSibling:e.lastChild;o.previousSibling=s,a.nextSibling=r,s?s.nextSibling=o:e.firstChild=o,r==null?e.lastChild=a:r.previousSibling=a;do{o.parentNode=e;var l=e.ownerDocument||e;Pl(o,l)}while(o!==a&&(o=o.nextSibling));return Jc(e.ownerDocument||e,e),t.nodeType==wi&&(t.firstChild=t.lastChild=null),t}function Pl(e,t){if(e.ownerDocument!==t){if(e.ownerDocument=t,e.nodeType===Xr&&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;)Pl(i,t),i=i.nextSibling}}function RV(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,Jc(e.ownerDocument,e,t);var r=e.ownerDocument||e;return Pl(t,r),t}Ll.prototype={nodeName:"#document",nodeType:mA,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==wi){for(var r=e.firstChild;r;){var n=r.nextSibling;this.insertBefore(r,t),r=n}return e}return Hc(this,e,t),Pl(e,this),this.documentElement===null&&e.nodeType===Xr&&(this.documentElement=e),e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),EA(this,e)},replaceChild:function(e,t){Hc(this,e,t,AA),Pl(e,this),t&&this.removeChild(t),qn(e)&&(this.documentElement=e)},importNode:function(e,t){return LV(this,e,t)},getElementById:function(e){var t=null;return jc(this.documentElement,function(r){if(r.nodeType==Xr&&r.getAttribute("id")==e)return t=r,!0}),t},getElementsByClassName:function(e){var t=iA(e);return new Ja(this,function(r){var n=[];return t.length>0&&jc(r.documentElement,function(i){if(i!==r&&i.nodeType===Xr){var o=i.getAttribute("class");if(o){var a=e===o;if(!a){var s=iA(o);a=t.every(AV(s))}a&&n.push(i)}}}),n})},createElement:function(e){var t=new Wo;t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.localName=e,t.childNodes=new Ci;var r=t.attributes=new zc;return r._ownerElement=t,t},createDocumentFragment:function(){var e=new Qc;return e.ownerDocument=this,e.childNodes=new Ci,e},createTextNode:function(e){var t=new gh;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new yh;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){if(e.indexOf("]]>")!==-1)throw new fe(oA,'data contains "]]>"');var t=new bh;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var r=new wh;return r.ownerDocument=this,r.tagName=r.nodeName=r.target=e,r.nodeValue=r.data=t,r},createAttribute:function(e){var t=new Kc;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){if(!Ha.test(e))throw new fe(oA,'not a valid xml name "'+e+'"');var t=new vh;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var r=new Wo,n=t.split(":"),i=r.attributes=new zc;return r.childNodes=new Ci,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 Kc,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}};yr(Ll,Ne);function Wo(){this._nsMap={}}Wo.prototype={nodeType:Xr,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===wi?this.insertBefore(e,null):RV(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 Ja(this,function(t){var r=[];return jc(t,function(n){n!==t&&n.nodeType==Xr&&(e==="*"||n.tagName==e)&&r.push(n)}),r})},getElementsByTagNameNS:function(e,t){return new Ja(this,function(r){var n=[];return jc(r,function(i){i!==r&&i.nodeType===Xr&&(e==="*"||i.namespaceURI===e)&&(t==="*"||i.localName==t)&&n.push(i)}),n})}};Ll.prototype.getElementsByTagName=Wo.prototype.getElementsByTagName;Ll.prototype.getElementsByTagNameNS=Wo.prototype.getElementsByTagNameNS;yr(Wo,Ne);function Kc(){}Kc.prototype.nodeType=Ka;yr(Kc,Ne);function kl(){}kl.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(wt[gr])},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}};yr(kl,Ne);function gh(){}gh.prototype={nodeName:"#text",nodeType:Il,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}};yr(gh,kl);function yh(){}yh.prototype={nodeName:"#comment",nodeType:ph};yr(yh,kl);function bh(){}bh.prototype={nodeName:"#cdata-section",nodeType:fA};yr(bh,kl);function Yc(){}Yc.prototype.nodeType=hA;yr(Yc,Ne);function SA(){}SA.prototype.nodeType=NV;yr(SA,Ne);function NA(){}NA.prototype.nodeType=SV;yr(NA,Ne);function vh(){}vh.prototype.nodeType=pA;yr(vh,Ne);function Qc(){}Qc.prototype.nodeName="#document-fragment";Qc.prototype.nodeType=wi;yr(Qc,Ne);function wh(){}wh.prototype.nodeType=fh;yr(wh,Ne);function _A(){}_A.prototype.serializeToString=function(e,t,r,n){return TA.call(e,t,r,n)};Ne.prototype.toString=TA;function TA(e,t,r){var n=!!r&&!!r.requireWellFormed,i=[],o=this.nodeType==9&&this.documentElement||this,a=o.prefix,s=o.namespaceURI;if(s&&a==null){var a=o.lookupPrefix(s);if(a==null)var l=[{namespace:s,prefix:null}]}return Ch(this,i,e,t,l,n),i.join("")}function dA(e,t,r){var n=e.prefix||"",i=e.namespaceURI;if(!i||n==="xml"&&i===Ol.XML||i===Ol.XMLNS)return!1;for(var o=r.length;o--;){var a=r[o];if(a.prefix===n)return a.namespace!==i}return!0}function Wc(e,t,r,n){if(n&&!Ha.test(t))throw new fe(vn,'The attribute name "'+t+'" is not a valid XML QName');e.push(" ",t,'="',r.replace(/[<>&"\t\n\r]/g,wA),'"')}function Ch(e,t,r,n,i,o){i||(i=[]),vt(e,{ns:i,isHTML:r},{enter:function(a,s){var l=s.ns,u=s.isHTML;if(n)if(a=n(a),a){if(typeof a=="string")return t.push(a),null}else return null;switch(a.nodeType){case Xr:var c=a.attributes,d=c.length,f=a.tagName;u=Ol.isHTML(a.namespaceURI)||u;var p=f;if(!u&&!a.prefix&&a.namespaceURI){for(var m,h=0;h<c.length;h++)if(c.item(h).name==="xmlns"){m=c.item(h).value;break}if(!m)for(var g=l.length-1;g>=0;g--){var b=l[g];if(b.prefix===""&&b.namespace===a.namespaceURI){m=b.namespace;break}}if(m!==a.namespaceURI)for(var g=l.length-1;g>=0;g--){var b=l[g];if(b.namespace===a.namespaceURI){b.prefix&&(p=b.prefix+":"+f);break}}}if(o&&!Ha.test(p))throw new fe(vn,'The element name "'+p+'" is not a valid XML QName');t.push("<",p);for(var w=l.slice(),E=0;E<d;E++){var A=c.item(E);A.prefix=="xmlns"?w.push({prefix:A.localName,namespace:A.value}):A.nodeName=="xmlns"&&w.push({prefix:"",namespace:A.value})}for(var E=0;E<d;E++){var A=c.item(E);if(dA(A,u,w)){var L=A.prefix||"",R=A.namespaceURI;Wc(t,L?"xmlns:"+L:"xmlns",R,o),w.push({prefix:L,namespace:R})}var I=n?n(A):A;I&&(typeof I=="string"?t.push(I):Wc(t,I.name,I.value,o))}if(f===p&&dA(a,u,w)){var D=a.prefix||"",R=a.namespaceURI;Wc(t,D?"xmlns:"+D:"xmlns",R,o),w.push({prefix:D,namespace:R})}var O=a.firstChild;if(O||u&&!/^(?:meta|link|img|br|hr|input)$/i.test(f)){if(t.push(">"),u&&/^script$/i.test(f)){for(;O;)O.data?t.push(O.data):Ch(O,t,u,n,w.slice(),o),O=O.nextSibling;return t.push("</",f,">"),null}return{ns:w,isHTML:u,tag:p}}else return t.push("/>"),null;case mA:case wi:return{ns:l.slice(),isHTML:u,tag:null};case Ka:return Wc(t,a.name,a.value,o),null;case Il:return t.push(a.data.replace(/[<&>]/g,wA)),null;case fA:if(o&&a.data.indexOf("]]>")!==-1)throw new fe(vn,'The CDATASection data contains "]]>"');return t.push("<![CDATA[",a.data.replace(/]]>/g,"]]]]><![CDATA[>"),"]]>"),null;case ph:if(o&&a.data.indexOf("-->")!==-1)throw new fe(vn,'The comment node data contains "-->"');return t.push("<!--",a.data,"-->"),null;case hA:if(o){if(!Ha.test(a.name))throw new fe(vn,'The doctype name "'+a.name+'" is not a valid XML Name');if(a.publicId&&!/^("[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%']*"|'[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%'"]*')$/.test(a.publicId))throw new fe(vn,"DocumentType publicId is not a valid PubidLiteral");if(a.systemId&&!/^("[^"]*"|'[^']*')$/.test(a.systemId))throw new fe(vn,"DocumentType systemId is not a valid SystemLiteral");if(a.internalSubset&&a.internalSubset.indexOf("]>")!==-1)throw new fe(vn,'DocumentType internalSubset contains "]>"')}var $=a.publicId,K=a.systemId;if(t.push("<!DOCTYPE ",a.name),$)t.push(" PUBLIC ",$),K&&K!="."&&t.push(" ",K),t.push(">");else if(K&&K!=".")t.push(" SYSTEM ",K,">");else{var Re=a.internalSubset;Re&&t.push(" [",Re,"]"),t.push(">")}return null;case fh:if(o){if(!Ha.test(a.target)||a.target.indexOf(":")!==-1||a.target.toLowerCase()==="xml")throw new fe(vn,'The processing instruction target "'+a.target+'" is not a valid XML NCName or is reserved');if(a.data.indexOf("?>")!==-1)throw new fe(vn,'The ProcessingInstruction data contains "?>"')}return t.push("<?",a.target," ",a.data,"?>"),null;case pA:if(o&&!Ha.test(a.nodeName))throw new fe(vn,'The entity reference name "'+a.nodeName+'" is not a valid XML Name');return t.push("&",a.nodeName,";"),null;default:return t.push("??",a.nodeName),null}},exit:function(a,s){s&&s.tag&&t.push("</",s.tag,">")}})}function LV(e,t,r){var n;return vt(t,null,{enter:function(i,o){var a=i.cloneNode(!1);a.ownerDocument=e,a.parentNode=null,o===null?n=a:o.appendChild(a);var s=i.nodeType===Ka||r;return s?a:null}}),n}function DA(e,t,r){var n;return vt(t,null,{enter:function(i,o){var a=new i.constructor;for(var s in i)if(Object.prototype.hasOwnProperty.call(i,s)){var l=i[s];typeof l!="object"&&l!=a[s]&&(a[s]=l)}i.childNodes&&(a.childNodes=new Ci),a.ownerDocument=e;var u=r;switch(a.nodeType){case Xr:var c=i.attributes,d=a.attributes=new zc,f=c.length;d._ownerElement=a;for(var p=0;p<f;p++)a.setAttributeNode(DA(e,c.item(p),!0));break;case Ka:u=!0}return o!==null?o.appendChild(a):n=a,u?a:null}}),n}function IA(e,t,r){e[t]=r}try{Object.defineProperty&&(Object.defineProperty(Ja.prototype,"length",{get:function(){return mh(this),this.$$length}}),Object.defineProperty(Ne.prototype,"textContent",{get:function(){if(this.nodeType===Xr||this.nodeType===wi){var e=[];return vt(this,null,{enter:function(t){if(t.nodeType===Xr||t.nodeType===wi)return!0;if(t.nodeType===fh||t.nodeType===ph)return null;e.push(t.nodeValue)}}),e.join("")}return this.nodeValue},set:function(e){switch(this.nodeType){case Xr:case wi: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}}}),IA=function(e,t,r){e["$$"+t]=r})}catch{}Ai.DocumentType=Yc;Ai.DOMException=fe;Ai.DOMImplementation=vA;Ai.Element=Wo;Ai.Node=Ne;Ai.NodeList=Ci;Ai.walkDOM=vt;Ai.XMLSerializer=_A});var PA=v(xl=>{"use strict";var OA=ja().freeze;xl.XML_ENTITIES=OA({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});xl.HTML_ENTITIES=OA({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"});xl.entityMap=xl.HTML_ENTITIES});var $A=v(Sh=>{var Ml=ja().NAMESPACE,Ah=ja().tagNamePattern,Ya=0,to=1,Qa=2,$l=3,Xa=4,Za=5,Fl=6,Xc=7;function es(e,t){this.message=e,this.locator=t,Error.captureStackTrace&&Error.captureStackTrace(this,es)}es.prototype=new Error;es.prototype.name=es.name;function kA(){}kA.prototype={parse:function(e,t,r){var n=this.domBuilder;n.startDocument(),MV(t,t={}),kV(e,t,r,n,this.errorHandler),n.endDocument()}};function kV(e,t,r,n,i){function o(ge){if(ge>65535){ge-=65536;var ht=55296+(ge>>10),Ro=56320+(ge&1023);return String.fromCharCode(ht,Ro)}else return String.fromCharCode(ge)}function a(ge){var ht=ge.slice(1,-1);return Object.hasOwnProperty.call(r,ht)?r[ht]:ht.charAt(0)==="#"?o(parseInt(ht.substr(1).replace("x","0x"))):(i.error("entity not found:"+ge),ge)}function s(ge){if(ge>h){var ht=e.substring(h,ge).replace(/&#?\w+;/g,a);f&&l(h),n.characters(ht,0,ge-h),h=ge}}function l(ge,ht){for(;ge>=c&&(ht=d.exec(e));)u=ht.index,c=u+ht[0].length,f.lineNumber++;f.columnNumber=ge-u+1}for(var u=0,c=0,d=/.*(?:\r\n?|\n)|.*$/g,f=n.locator,p=[{currentNSMap:t}],m={},h=0;;){try{var g=e.indexOf("<",h);if(g<0){if(!e.substr(h).match(/^\s*$/)){var b=n.doc,w=b.createTextNode(e.substr(h));b.appendChild(w),n.currentElement=w}return}switch(g>h&&s(g),e.charAt(g+1)){case"/":var K=e.indexOf(">",g+3),E=e.substring(g+2,K).replace(/^([\s\S]*?[^ \t\n\r])?[ \t\n\r]*$/,"$1"),A=p.pop();K<0?(E=e.substring(g+2).replace(/[\s<].*/,""),i.error("end tag name: "+E+" is not complete:"+A.tagName),K=g+1+E.length):E.match(/\s</)?(E=E.replace(/[\s<].*/,""),i.error("end tag name: "+E+" maybe not complete"),K=g+1+E.length):/[ \t\n\r]/.test(E)&&Ah.test(E.split(/[ \t\n\r]/)[0])&&i.error('end tag name is followed by whitespace and trailing content: "'+E+'"');var L=A.localNSMap,R=A.tagName==E,I=R||A.tagName&&A.tagName.toLowerCase()==E.toLowerCase();if(I){if(n.endElement(A.uri,A.localName,E),L)for(var D in L)Object.prototype.hasOwnProperty.call(L,D)&&n.endPrefixMapping(D);R||i.fatalError("end tag name: "+E+" is not match the current start tagName:"+A.tagName)}else p.push(A);K++;break;case"?":f&&l(g),K=BV(e,g,n);break;case"!":f&&l(g),K=UV(e,g,n,i);break;default:f&&l(g);var O=new xA,$=p[p.length-1].currentNSMap,K=xV(e,g,O,$,a,i),Re=O.length;if(!O.closed&&FV(e,K,O.tagName,m)&&(O.closed=!0,r.nbsp||i.warning("unclosed xml attribute")),f&&Re){for(var It=RA(f,{}),Le=0;Le<Re;Le++){var at=O[Le];l(at.offset),at.locator=RA(f,{})}n.locator=It,LA(O,n,$)&&p.push(O),n.locator=f}else LA(O,n,$)&&p.push(O);Ml.isHTML(O.uri)&&!O.closed?K=$V(e,K,O.tagName,a,n):K++}}catch(ge){if(ge instanceof es)throw ge;i.error("element parse error: "+ge),K=-1}K>h?h=K:s(Math.max(g,h)+1)}}function RA(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function xV(e,t,r,n,i,o){function a(p,m,h){r.attributeNames.hasOwnProperty(p)&&o.fatalError("Attribute "+p+" redefined"),r.addValue(p,m.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,i),h)}for(var s,l,u=++t,c=Ya;;){var d=e.charAt(u);if(c===Ya&&d==="<")throw new Error("unexpected < in tag name: "+e.slice(t,u));switch(d){case"=":if(c===to)s=e.slice(t,u),c=$l;else if(c===Qa)c=$l;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(c===$l||c===to)if(c===to&&(o.warning('attribute value must after "="'),s=e.slice(t,u)),t=u+1,u=e.indexOf(d,t),u>0)l=e.slice(t,u),a(s,l,t-1),c=Za;else throw new Error("attribute value no end '"+d+"' match");else if(c==Xa)l=e.slice(t,u),a(s,l,t),o.warning('attribute "'+s+'" missed start quot('+d+")!!"),t=u+1,c=Za;else throw new Error('attribute value must after "="');break;case"/":switch(c){case Ya:r.setTagName(e.slice(t,u));case Za:case Fl:case Xc:c=Xc,r.closed=!0;case Xa:case to:break;case Qa:r.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return o.error("unexpected end of input"),c==Ya&&r.setTagName(e.slice(t,u)),u;case">":switch(c){case Ya:r.setTagName(e.slice(t,u));case Za:case Fl:case Xc:break;case Xa:case to:l=e.slice(t,u),l.slice(-1)==="/"&&(r.closed=!0,l=l.slice(0,-1));case Qa:c===Qa&&(l=s),c==Xa?(o.warning('attribute "'+l+'" missed quot(")!'),a(s,l,t)):((!Ml.isHTML(n[""])||!l.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+l+'" missed value!! "'+l+'" instead!!'),a(l,l,t));break;case $l:throw new Error("attribute value missed!!")}return u;case"\x80":d=" ";default:if(d<=" ")switch(c){case Ya:r.setTagName(e.slice(t,u)),c=Fl;break;case to:s=e.slice(t,u),c=Qa;break;case Xa:var l=e.slice(t,u);o.warning('attribute "'+l+'" missed quot(")!!'),a(s,l,t);case Za:c=Fl;break}else switch(c){case Qa:var f=r.tagName;(!Ml.isHTML(n[""])||!s.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+s+'" missed value!! "'+s+'" instead2!!'),a(s,s,t),t=u,c=to;break;case Za:o.warning('attribute space is required"'+s+'"!!');case Fl:c=to,t=u;break;case $l:c=Xa,t=u;break;case Xc:throw new Error("elements closed character '/' and '>' must be connected to")}}u++}}function LA(e,t,r){for(var n=e.tagName,i=null,d=e.length;d--;){var o=e[d],a=o.qName,s=o.value,f=a.indexOf(":");if(f>0)var l=o.prefix=a.slice(0,f),u=a.slice(f+1),c=l==="xmlns"&&u;else u=a,l=null,c=a==="xmlns"&&"";o.localName=u,c!==!1&&(i==null&&(i={},r=Object.create(r)),r[c]=i[c]=s,o.uri=Ml.XMLNS,t.startPrefixMapping(c,s))}for(var d=e.length;d--;){o=e[d];var l=o.prefix;l&&(l==="xml"&&(o.uri=Ml.XML),l!=="xmlns"&&(o.uri=r[l||""]))}var f=n.indexOf(":");f>0?(l=e.prefix=n.slice(0,f),u=e.localName=n.slice(f+1)):(l=null,u=e.localName=n);var p=e.uri=r[l||""];if(t.startElement(p,u,n,e),e.closed){if(t.endElement(p,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 $V(e,t,r,n,i){if(/^(?:script|textarea)$/i.test(r)){var o=e.indexOf("</"+r+">",t),a=e.substring(t+1,o);if(/[&<]/.test(a))return/^script$/i.test(r)?(i.characters(a,0,a.length),o):(a=a.replace(/&#?\w+;/g,n),i.characters(a,0,a.length),o)}return t+1}function FV(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 MV(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function UV(e,t,r,n){var i=e.charAt(t+2);switch(i){case"-":if(e.charAt(t+3)==="-"){var o=e.indexOf("-->",t+4);return o>t?(r.comment(e,t+4,o-t-4),o+3):(n.error("Unclosed comment"),-1)}else return-1;default:if(e.substr(t+3,6)=="CDATA["){var o=e.indexOf("]]>",t+9);return r.startCDATA(),r.characters(e,t+9,o-t-9),r.endCDATA(),o+3}var a=qV(e,t),s=a.length;if(s>1&&/!doctype/i.test(a[0][0])){var l=a[1][0],u=!1,c=!1;s>3&&(/^public$/i.test(a[2][0])?(u=a[3][0],c=s>4&&a[4][0]):/^system$/i.test(a[2][0])&&(c=a[3][0]));var d=a[s-1];return r.startDTD(l,u,c),r.endDTD(),d.index+d[0].length}}return-1}function BV(e,t,r){var n=e.indexOf("?>",t);if(n){var i=e.substring(t,n).match(/^<\?(\S*)\s*([\s\S]*?)$/);if(i){var o=i[0].length;return r.processingInstruction(i[1],i[2]),n+2}else return-1}return-1}function xA(){this.attributeNames={}}xA.prototype={setTagName:function(e){if(!Ah.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},addValue:function(e,t,r){if(!Ah.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 qV(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}Sh.XMLReader=kA;Sh.ParseError=es});var GA=v(ed=>{var VV=ja(),GV=Eh(),FA=PA(),BA=$A(),WV=GV.DOMImplementation,MA=VV.NAMESPACE,zV=BA.ParseError,jV=BA.XMLReader;function qA(e){return e.replace(/\r[\n\u0085]/g,`+`}});var bA=v(ld=>{"use strict";Object.defineProperty(ld,"__esModule",{value:!0});ld.generateGenPageRuntimeTypes=void 0;var yA=Oh(),Qo=Q(),gA=new Set(["None","ColorsDefaultsConstraints","ColorsDefaultsConstraintsDescriptions"]),Xo="generateGenPageRuntimeTypes";async function ZV(e,t,r){let n=eG(t),i=tG(r),o=[];for(let a of n){let s=await e(a);if(s.columnDetailComplete!==!0)throw new Qo.SdkError("GENPAGE_DATA_SOURCE_INCOMPLETE",`${Xo}: the column metadata of data source '${a}' could not be read completely (a choice or lookup read failed, or returned options with no label), so its RuntimeTypes would lack enums a page can use. Retry.`);o.push(s)}return(0,yA.renderGenPageAuthoringTypes)(o,i)}ld.generateGenPageRuntimeTypes=ZV;function eG(e){if(!Array.isArray(e))throw new Qo.InvalidArgumentError(`${Xo}: dataSources must be an array of table logical names`);let t=new Set;for(let r of e){if(typeof r!="string"||!yA.TABLE_LOGICAL_NAME.test(r))throw new Qo.InvalidArgumentError(`${Xo}: a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(r)}'`);if(t.has(r))throw new Qo.InvalidArgumentError(`${Xo}: data source '${r}' is listed twice; a page's dataSources hold each table once`);t.add(r)}return[...t]}function tG(e){if(e===void 0)return"None";if(e===null||typeof e!="object"||Array.isArray(e))throw new Qo.InvalidArgumentError(`${Xo}: options must be an object`);let t=Object.keys(e).filter(n=>n!=="detail");if(t.length>0)throw new Qo.InvalidArgumentError(`${Xo}: unknown option '${t[0]}' (the only option is 'detail')`);let r=e.detail===void 0?"None":e.detail;if(typeof r!="string"||!gA.has(r))throw new Qo.InvalidArgumentError(`${Xo}: detail must be one of ${[...gA].map(n=>`'${n}'`).join(", ")}, got '${String(r)}'`);return r}});var SA=v(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});Zo.getEnvironmentLanguages=Zo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE=void 0;var rG=Q(),CA=fe();Zo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE="ENVIRONMENT_LANGUAGES_UNREADABLE";var vA="/organizations?$select=languagecode",nG="/RetrieveProvisionedLanguages()",iG="/RetrieveAvailableLanguages()";function EA(e,t){return new rG.SdkError(Zo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE,`The org's languages could not be read: ${e} ${t}. Nothing is assumed in its place \u2014 retry, or check the caller's access to the org.`)}function AA(e){return typeof e=="number"&&Number.isInteger(e)&&e>0}async function wA(e,t,r,n){let i=(0,CA.ensureSuccess)(await e.get(t),e.apiUrl(t)).body,o=i?.[r];if(!Array.isArray(o)||o.length===0||!o.every(AA))throw EA(n,`answered no list of language codes in '${r}'`);return[...new Set(o)]}async function oG(e){var t;let r=(0,CA.ensureSuccess)(await e.get(vA),e.apiUrl(vA)).body,n=r?.value,i=Array.isArray(n)&&n.length===1?(t=n[0])===null||t===void 0?void 0:t.languagecode:void 0;if(!AA(i))throw EA("the organization read","did not answer one row with a language code");let o=await wA(e,nG,"RetrieveProvisionedLanguages","RetrieveProvisionedLanguages"),a=await wA(e,iG,"LocaleIds","RetrieveAvailableLanguages");return{baseLanguage:i,available:a,provisioned:o}}Zo.getEnvironmentLanguages=oG});var Wl=v(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.projectConnectorOperationSchema=lt.projectConnectorOperations=lt.validateConnectorSwagger=lt.CONNECTOR_SCHEMA_TOO_LARGE_CODE=lt.CONNECTOR_OPERATION_NOT_FOUND_CODE=lt.CONNECTOR_SWAGGER_UNSUPPORTED_CODE=lt.CONNECTIVITY_RESPONSE_UNREADABLE_CODE=void 0;var Gl=Q();lt.CONNECTIVITY_RESPONSE_UNREADABLE_CODE="CONNECTIVITY_RESPONSE_UNREADABLE";lt.CONNECTOR_SWAGGER_UNSUPPORTED_CODE="CONNECTOR_SWAGGER_UNSUPPORTED";lt.CONNECTOR_OPERATION_NOT_FOUND_CODE="CONNECTOR_OPERATION_NOT_FOUND";lt.CONNECTOR_SCHEMA_TOO_LARGE_CODE="CONNECTOR_SCHEMA_TOO_LARGE";var NA=64,_A=128,TA=2e5,DA=4e6,aG=new Set(["get","put","post","delete","patch","head","options"]),sG=new Set(["query","header","path","formData","body"]);function sn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Tn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Dt(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function et(e){return e.length>80?`'${e.slice(0,80)}\u2026'`:`'${e}'`}function ke(e,t){return new Gl.SdkError(lt.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`The connector's swagger could not be read: ${e} ${t}. Nothing was skipped or assumed in its place.`)}function fo(e,t){return new Gl.SdkError(lt.CONNECTOR_SWAGGER_UNSUPPORTED_CODE,`The connector's swagger is outside the supported contract (Swagger 2.0 as the Power Apps API serves it): ${e} ${t}.`)}function lG(e,t){let r=e;for(let n of t.slice(2).split("/")){let i=n.replace(/~1/g,"/").replace(/~0/g,"~");if(typeof r!="object"||r===null||!Tn(r,i))return{found:!1};r=r[i]}return{found:!0,value:r}}function Lh(e,t,r){if(!t.startsWith("#/"))throw fo(r,`has a $ref that is not a local '#/\u2026' pointer (${et(t)})`);if(t.includes("%"))throw fo(r,`has a $ref with a percent-encoded character (${et(t)}), which is not decoded`);if(/~(?![01])/.test(t))throw ke(r,`has a $ref with a malformed escape (${et(t)}): a '~' not followed by 0 or 1`);let n=lG(e,t);if(!n.found)throw ke(r,`has a $ref that does not resolve (${et(t)})`);return n.value}function ud(e,t){if(Tn(e,"$ref")){if(typeof e.$ref!="string")throw ke(t,`has a $ref that is ${Dt(e.$ref)}, not a string`);return e.$ref}}function uG(e,t,r){if(!sn(t))throw ke(r,`is ${Dt(t)}, not a parameter object`);let n=t,i=ud(t,r);if(i!==void 0){let s=Lh(e,i,r);if(!sn(s))throw ke(r,`has a $ref (${et(i)}) that resolves to ${Dt(s)}, not a parameter object`);if(ud(s,`${r} \u2192 ${et(i)}`)!==void 0)throw fo(r,`has a $ref (${et(i)}) to a parameter that is itself a $ref`);n=s}if(typeof n.name!="string")throw ke(r,"has no string name");let o=n.in;if(typeof o!="string"||!sG.has(o))throw ke(r,`has an in that is ${typeof o=="string"?et(o):Dt(o)}, not one of query, header, path, formData or body`);if(Tn(n,"required")&&typeof n.required!="boolean")throw ke(r,`has a required that is ${Dt(n.required)}, not a boolean`);let a=n["x-ms-visibility"];if(Tn(n,"x-ms-visibility")&&typeof a!="string")throw ke(r,`has an x-ms-visibility that is ${Dt(a)}, not a string`);return{name:n.name,in:o,required:n.required===!0,internal:a==="internal"}}function Ph(e){return`${e.in}:${e.name}`}function OA(e,t,r){if(!Tn(t,"parameters"))return[];let n=t.parameters;if(!Array.isArray(n))throw ke(r,`has parameters that are ${Dt(n)}, not an array`);let i=new Set;return n.map((o,a)=>{let s=`${r} parameters[${a}]`,l=uG(e,o,s),u=Ph(l);if(i.has(u))throw ke(s,`repeats the parameter ${et(l.name)} in ${et(l.in)}, which must be unique in its list`);return i.add(u),l})}function PA(e,t,r){let n=t.responses;if(!Tn(n,"200"))return;let i=`${r} response 200`,o=n[200];if(!sn(o))throw ke(i,`is ${Dt(o)}, not a response object`);let a=o,s=ud(o,i);if(s!==void 0){if(s.startsWith("#/")&&!/^#\/responses\/[^/]+$/.test(s))throw ke(i,`has a $ref (${et(s)}) that does not name a response ('#/responses/<name>')`);let l=Lh(e,s,i);if(!sn(l))throw ke(i,`has a $ref (${et(s)}) that resolves to ${Dt(l)}, not a response object`);if(ud(l,`${i} \u2192 ${et(s)}`)!==void 0)throw fo(i,`has a $ref (${et(s)}) to a response that is itself a $ref`);a=l}if(Tn(a,"content"))throw fo(i,"is an OpenAPI 3 response (it has content), not a Swagger 2.0 one");if(Tn(a,"schema")){if(!sn(a.schema))throw ke(i,`has a schema that is ${Dt(a.schema)}, not an object`);return a.schema}}function IA(e,t,r){if(!Tn(e,t))return;let n=e[t];if(typeof n!="string")throw ke(r,`has a ${t} that is ${Dt(n)}, not a string`);return n}function cG(e,t,r,n,i){if(!sn(t))throw ke(r,`is ${Dt(t)}, not an operation object`);let o=t.operationId;if(typeof o!="string")throw ke(r,`has no string operationId (${Dt(o)})`);if(n.has(o))throw ke(r,`repeats the operationId ${et(o)}, which must be unique in the document`);n.add(o);let a=IA(t,"summary",r),s=IA(t,"description",r),l=OA(e,t,r);if(!sn(t.responses))throw ke(r,`has no responses object (${Dt(t.responses)})`);return PA(e,t,r),{id:o,summary:a,description:s,node:t,where:r,parameters:l,pathParameters:i}}function kh(e){if(!sn(e))throw ke("the document",`is ${Dt(e)}, not an object`);if(Tn(e,"openapi"))throw fo("the document","is OpenAPI 3 (it has an openapi member), not Swagger 2.0");if(!Tn(e,"swagger"))throw ke("the document","names no Swagger version");if(e.swagger!=="2.0")throw fo("the document",`declares swagger ${et(String(e.swagger))}, not 2.0`);let t=e.paths;if(!sn(t))throw ke("the document",`has paths that are ${Dt(t)}, not an object`);let r=[],n=new Set;for(let i of Object.keys(t)){let o=t[i],a=`paths[${et(i)}]`;if(!sn(o))throw ke(a,`is ${Dt(o)}, not a path item object`);let s=[];for(let l of Object.keys(o))if(aG.has(l.toLowerCase()))r.push(cG(e,o[l],`${a}.${l}`,n,s));else if(l==="parameters")for(let u of OA(e,o,a))s.push(u);else if(!l.startsWith("x-"))throw fo(a,`has a ${et(l)} member; a path item may hold only HTTP methods, parameters and x- extensions`)}return{document:e,operations:r}}function dG(e){kh(e)}lt.validateConnectorSwagger=dG;var Rh=class{constructor(t,r){this.root=t,this.where=r,this.nodes=0,this.characters=0,this.path=[]}run(t){return this.visit(t,0)}tooLarge(t){return new Gl.SdkError(lt.CONNECTOR_SCHEMA_TOO_LARGE_CODE,`The response schema of ${this.where} is too large to return: it has ${t}. That is far above any connector measured, so this one is not read.`)}node(){if(this.nodes+=1,this.nodes>TA)throw this.tooLarge(`more than ${TA} nodes`)}text(t){if(this.characters+=t,this.characters>DA)throw this.tooLarge(`more than ${DA} characters of strings and keys`)}checkDepth(t){if(t>_A)throw this.tooLarge(`nesting deeper than ${_A} levels`)}visit(t,r){if(this.checkDepth(r),Array.isArray(t)){this.node();let n=[];for(let i of t)n.push(this.visit(i,r+1));return n}if(sn(t)){if(typeof t.$ref=="string")return this.reference(t.$ref,r);this.node();let n={};for(let i of Object.keys(t))this.text(i.length),Object.defineProperty(n,i,{value:this.visit(t[i],r+1),enumerable:!0,writable:!0,configurable:!0});return n}return this.node(),typeof t=="string"&&this.text(t.length),t}reference(t,r){if(this.path.includes(t)){this.checkDepth(r+1);let o=t.slice(t.lastIndexOf("/")+1);return this.node(),this.text(4),this.node(),this.text(o.length),{$ref:o}}if(this.path.length>=NA)throw this.tooLarge(`a $ref chain of more than ${NA} references`);let n=Lh(this.root,t,this.where);if(!sn(n))throw ke(this.where,`has a schema $ref (${et(t)}) that resolves to ${Dt(n)}, not a schema object`);this.path.push(t);let i=this.visit(n,r);return this.path.pop(),i}};function fG(e){let{operations:t}=kh(e);return{operations:t.map(r=>{var n,i;return{name:r.id,summary:(i=(n=r.summary)!==null&&n!==void 0?n:r.description)!==null&&i!==void 0?i:null}})}}lt.projectConnectorOperations=fG;function pG(e,t){if(typeof t!="string"||t==="")throw new Gl.InvalidArgumentError("operationId must be a non-empty string.");let{document:r,operations:n}=kh(e),i=n.find(u=>u.id===t);if(!i)throw new Gl.SdkError(lt.CONNECTOR_OPERATION_NOT_FOUND_CODE,`The connector has no operation with the id ${et(t)} (ids are matched exactly, case included). List the connector\u2019s operations to see its ids.`);let o=new Set(i.parameters.map(Ph)),a=[...i.parameters,...i.pathParameters.filter(u=>!o.has(Ph(u)))].filter(u=>!u.internal).map(({name:u,required:c})=>({name:u,required:c})),s=PA(r,i.node,i.where),l=s===void 0?{}:new Rh(r,`${i.where} (${et(i.id)})`).run(s);return{operation:i.id,parameters:a,response:l}}lt.projectConnectorOperationSchema=pG});var ea=v(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.readEnvironmentName=J.readConnection=J.connectorShortName=J.CONNECTOR_PREFIX=J.connectivityUnauthorized=J.errorCodeOf=J.messageOf=J.environmentFilter=J.unreadable=J.connectivityCloudOf=J.sameOrigin=J.parseUrl=J.bounded=J.kindOf=J.isObject=J.CONNECTOR_RUNTIME_UNSUPPORTED_CODE=J.CONNECTOR_NOT_TABULAR_CODE=J.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE=J.CONNECTIVITY_UNAUTHORIZED_CODE=J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE=J.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE=J.CONNECTIVITY_NOT_CONFIGURED_CODE=void 0;var zl=Q(),mG=fe(),hG=Wl();J.CONNECTIVITY_NOT_CONFIGURED_CODE="CONNECTIVITY_NOT_CONFIGURED";J.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE="CONNECTIVITY_CLOUD_UNSUPPORTED";J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE="CONNECTIVITY_ENVIRONMENT_UNVERIFIED";J.CONNECTIVITY_UNAUTHORIZED_CODE="CONNECTIVITY_UNAUTHORIZED";J.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE="CONNECTIVITY_ROUTE_DECOMMISSIONED";J.CONNECTOR_NOT_TABULAR_CODE="CONNECTOR_NOT_TABULAR";J.CONNECTOR_RUNTIME_UNSUPPORTED_CODE="CONNECTOR_RUNTIME_UNSUPPORTED";function Nr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}J.isObject=Nr;function ns(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}J.kindOf=ns;function is(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}J.bounded=is;function LA(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}J.parseUrl=LA;function gG(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}J.sameOrigin=gG;var yG=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,bG=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/;function vG(e){let t=LA(e),r=t?t.host.toLowerCase():"";if(bG.test(r))return"Test";let n=yG.exec(r);return n&&n[1]!=="9"?"Public":"Unsupported"}J.connectivityCloudOf=vG;function Yn(e,t){return new zl.SdkError(hG.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}J.unreadable=Yn;function wG(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}J.environmentFilter=wG;function CG(e){if(typeof e=="string"&&e.length>0)return is(e,500);if(Nr(e)){let t=Nr(e.error)?e.error.message:void 0;for(let r of[t,e.Message,e.message])if(typeof r=="string")return is(r,500)}return"request failed"}J.messageOf=CG;function kA(e){return Nr(e)&&Nr(e.error)?e.error.code:void 0}J.errorCodeOf=kA;function EG(e){if(Nr(e)&&Nr(e.error)&&Nr(e.error.innererror))return e.error.innererror.code}function AG(e,t,r){let n=[],i=kA(t);typeof i=="string"&&i.length>0&&n.push(is(i,80));let o=EG(t);typeof o=="string"&&o.length>0&&n.push(is(o,80));let a=n.length>0?` (${n.join("; ")})`:"";return(0,zl.attachCause)(new zl.SdkError(J.CONNECTIVITY_UNAUTHORIZED_CODE,`A connectivity request was refused with HTTP ${e}${a}: the token's audience, scopes, expiry, or access was rejected. Supply a valid token for this route, or fall back to pac.`),r)}J.connectivityUnauthorized=AG;J.CONNECTOR_PREFIX="/providers/Microsoft.PowerApps/apis/";var SG=/^[A-Za-z0-9_.-]{1,128}$/,NG=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]);function _G(e){if(typeof e=="string"){let r=e.slice(0,J.CONNECTOR_PREFIX.length).toLowerCase()===J.CONNECTOR_PREFIX.toLowerCase()?e.slice(J.CONNECTOR_PREFIX.length):e;if(SG.test(r)&&!/^\.{1,2}$/.test(r))return r}throw new zl.InvalidArgumentError(`connector must be a connector's short name ('shared_office365users') or its full API id ('${J.CONNECTOR_PREFIX}shared_office365users'); got ${typeof e=="string"?`'${is(e,80)}'`:ns(e)}.`)}J.connectorShortName=_G;function TG(e,t,r){let n=`Connection row ${t}`;if(!Nr(e))throw Yn(n,`it is ${ns(e)}, not an object`);let i=e.properties;if(!Nr(i))throw Yn(n,`its properties are ${ns(i)}, not an object`);let o=i.apiId;if(typeof o!="string"||o.slice(0,J.CONNECTOR_PREFIX.length).toLowerCase()!==J.CONNECTOR_PREFIX.toLowerCase())throw Yn(n,`its apiId is not '${J.CONNECTOR_PREFIX}<connector>'`);let a=o.slice(J.CONNECTOR_PREFIX.length);if(a===""||a.includes("/"))throw Yn(n,"its apiId names no single connector");if(NG.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw Yn(n,"it has no name");let l=i.environment,u=Nr(l)?l.name:void 0;if(typeof u!="string"||u.toLowerCase()!==r.toLowerCase())throw Yn(n,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw Yn(n,`its displayName is ${ns(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw Yn(n,`its statuses are ${ns(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let m=Nr(f)?f.status:void 0;if(typeof m!="string")throw Yn(n,"one of its statuses has no string status");return m})}}J.readConnection=TG;var RA="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'";async function DG(e){let t=(0,mG.ensureSuccess)(await e.get(RA),e.apiUrl(RA)).body,r=Nr(t)?t.Detail:void 0,n=Nr(r)?r.EnvironmentId:void 0;if(typeof n!="string"||n==="")throw new zl.SdkError(J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,"The environment of this org could not be verified: the org answered no environment id (RetrieveCurrentOrganization, Detail.EnvironmentId).");return n}J.readEnvironmentName=DG});var qA=v(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.ConnectivityApi=_r.CONNECTIVITY_UNAUTHORIZED_CODE=_r.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE=_r.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE=_r.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE=_r.CONNECTIVITY_NOT_CONFIGURED_CODE=void 0;var Yt=Q(),IG=fe(),dd=Wl(),Hl=ea(),Kl=ea();Object.defineProperty(_r,"CONNECTIVITY_NOT_CONFIGURED_CODE",{enumerable:!0,get:function(){return Kl.CONNECTIVITY_NOT_CONFIGURED_CODE}});Object.defineProperty(_r,"CONNECTIVITY_CLOUD_UNSUPPORTED_CODE",{enumerable:!0,get:function(){return Kl.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE}});Object.defineProperty(_r,"CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE",{enumerable:!0,get:function(){return Kl.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE}});Object.defineProperty(_r,"CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE",{enumerable:!0,get:function(){return Kl.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE}});Object.defineProperty(_r,"CONNECTIVITY_UNAUTHORIZED_CODE",{enumerable:!0,get:function(){return Kl.CONNECTIVITY_UNAUTHORIZED_CODE}});var $A="2016-11-01",OG="2021-04-01",PG="https://api.bap.microsoft.com",RG="https://test.api.bap.microsoft.com",LG=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,kG=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,xA="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'",Oi="/providers/Microsoft.PowerApps/apis/",$G=/^[A-Za-z0-9_.-]{1,128}$/,xG=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]),FG="ServiceDecommissioned";function gt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function po(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function Qn(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}function jl(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}function FA(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}function MG(e){return/^[a-z0-9][a-z0-9.-]*$/.test(e)&&(e==="api.powerapps.com"||e.endsWith(".api.powerapps.com"))}function ln(e,t){return new Yt.SdkError(dd.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}function cd(e){return new Yt.SdkError(Hl.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: ${e}. The Power Apps service was not asked about it.`)}function MA(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}function UA(e){if(typeof e=="string"&&e.length>0)return Qn(e,500);if(gt(e)){let t=gt(e.error)?e.error.message:void 0;for(let r of[t,e.Message,e.message])if(typeof r=="string")return Qn(r,500)}return"request failed"}function UG(e){return gt(e)&>(e.error)?e.error.code:void 0}function BA(e){if(typeof e=="string"){let r=e.slice(0,Oi.length).toLowerCase()===Oi.toLowerCase()?e.slice(Oi.length):e;if($G.test(r)&&!/^\.{1,2}$/.test(r))return r}throw new Yt.InvalidArgumentError(`connector must be a connector's short name ('shared_office365users') or its full API id ('${Oi}shared_office365users'); got ${typeof e=="string"?`'${Qn(e,80)}'`:po(e)}.`)}function BG(e,t,r){let n=`Connection row ${t}`;if(!gt(e))throw ln(n,`it is ${po(e)}, not an object`);let i=e.properties;if(!gt(i))throw ln(n,`its properties are ${po(i)}, not an object`);let o=i.apiId;if(typeof o!="string"||o.slice(0,Oi.length).toLowerCase()!==Oi.toLowerCase())throw ln(n,`its apiId is not '${Oi}<connector>'`);let a=o.slice(Oi.length);if(a===""||a.includes("/"))throw ln(n,"its apiId names no single connector");if(xG.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw ln(n,"it has no name");let l=i.environment,u=gt(l)?l.name:void 0;if(typeof u!="string"||u.toLowerCase()!==r.toLowerCase())throw ln(n,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw ln(n,`its displayName is ${po(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw ln(n,`its statuses are ${po(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let m=gt(f)?f.status:void 0;if(typeof m!="string")throw ln(n,"one of its statuses has no string status");return m})}}var $h=class{constructor(t,r,n){this.org=t,this.instanceUrl=r,this.service=n,this.swaggers=new Map}async listConnections(){let t=this.requireService(),r=await this.resolveEnvironment(t),n=[],i=new Set,o=`${r.origin}/providers/Microsoft.PowerApps/connections?api-version=${$A}&$filter=${MA(r.id)}`,a=await this.send(t,o,!0),s=1,l=0;for(;;){let u=`Page ${s} of the connections`,c=a.body,d=c?.value;if(!Array.isArray(d))throw ln(u,`its value is ${po(d)}, not an array`);for(let m of d){let p=BG(m,l,r.id);l+=1,p&&n.push(p)}let f=c?.nextLink;if(f==null)return n;if(typeof f!="string"||f.length===0)throw ln(u,`its nextLink is ${f===""?"an empty string":po(f)}, not a non-empty string`);if(i.has(f))throw new Yt.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${Qn(f)}'), which would loop indefinitely.`);i.add(f),this.assertSameOrigin(f,r.parsed),a=await this.send(t,f,!0),s+=1}}async listConnectorOperations(t){let r=this.requireService(),n=BA(t);return(0,dd.projectConnectorOperations)(await this.swagger(r,n))}async getConnectorOperationSchema(t,r){let n=this.requireService(),i=BA(t);if(typeof r!="string"||r==="")throw new Yt.InvalidArgumentError("operationId must be a non-empty string.");return(0,dd.projectConnectorOperationSchema)(await this.swagger(n,i),r)}requireService(){if(!this.service)throw new Yt.SdkError(Hl.CONNECTIVITY_NOT_CONFIGURED_CODE,"This SDK was created without a powerAppsServiceClient (MakerSdkOptions), so it cannot read connections or connectors: it needs an HttpClient that authenticates for https://service.powerapps.com/ and does not follow redirects. Nothing was requested.");return this.service}resolveEnvironment(t){if(!this.environment){let r=this.verifyEnvironment(t);this.environment=r,r.catch(()=>{this.environment===r&&(this.environment=void 0)})}return this.environment}async verifyEnvironment(t){let r=this.candidateBapOrigin(),n=await this.readEnvironmentId(),i=`${r}/providers/Microsoft.BusinessAppPlatform/environments/${encodeURIComponent(n)}?api-version=${OG}`,o=(await this.send(t,i,!1)).body,a=gt(o)?o.properties:void 0,s=gt(o)?o.name:void 0;if(typeof s!="string"||s.toLowerCase()!==n.toLowerCase())throw cd(`BAP's environment row is not the one named '${Qn(n,80)}' (its name)`);let l=gt(a)&>(a.linkedEnvironmentMetadata)?a.linkedEnvironmentMetadata.instanceUrl:void 0,u=typeof l=="string"?jl(l):void 0,c=jl(this.instanceUrl);if(!u||!c||!FA(u,c))throw cd("BAP's row is not linked to this org (its linkedEnvironmentMetadata.instanceUrl is another origin)");let d=gt(a)?a.runtimeEndpoints:void 0,f=gt(d)?d["microsoft.PowerApps"]:void 0,m=typeof f=="string"?jl(f):void 0;if(!m||m.protocol!=="https:"||!MG(m.host.toLowerCase()))throw cd("BAP's Power Apps runtime endpoint is not an https host of api.powerapps.com (runtimeEndpoints['microsoft.PowerApps'])");return{id:n,origin:m.origin.toLowerCase(),parsed:m}}candidateBapOrigin(){let t=jl(this.instanceUrl),r=t?t.host.toLowerCase():"",n=LG.exec(r);if(n&&n[1]!=="9")return PG;if(kG.test(r))return RG;throw new Yt.SdkError(Hl.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The org's host is not one of the clouds this reads in (${t?`'${Qn(t.host,80)}'`:`'${Qn(this.instanceUrl,80)}', which is not a URL`}): a Public org is <name>.crm[N].dynamics.com (N other than 9) and a Test org <name>.crmtest.dynamics.com. GCC (crm9), GCC High, DoD, China, ports and custom domains are not supported. Nothing was requested.`)}async readEnvironmentId(){let t=(0,IG.ensureSuccess)(await this.org.get(xA),this.org.apiUrl(xA)).body,r=gt(t)?t.Detail:void 0,n=gt(r)?r.EnvironmentId:void 0;if(typeof n!="string"||n==="")throw cd("the org answered no environment id (RetrieveCurrentOrganization, Detail.EnvironmentId)");return n}swagger(t,r){let n=r.toLowerCase(),i=this.swaggers.get(n);if(!i){let o=this.readSwagger(t,r);i=o,this.swaggers.set(n,o),o.catch(()=>{this.swaggers.get(n)===o&&this.swaggers.delete(n)})}return i}async readSwagger(t,r){let n=await this.resolveEnvironment(t),i=encodeURIComponent(r),o=`${n.origin}${Oi}${i}?api-version=${$A}&$filter=${MA(n.id)}`,a=(await this.send(t,o,!0)).body,s=gt(a)?a.properties:void 0,l=gt(s)?s.swagger:void 0;if(!gt(l))throw ln(`The connector '${Qn(r,80)}'`,`its properties.swagger is ${po(l)}, not an object`);return(0,dd.validateConnectorSwagger)(l),l}assertSameOrigin(t,r){let n=jl(t);if(!n)throw new Yt.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${Qn(t)}'`);if(!FA(n,r))throw new Yt.InvalidArgumentError(`Refusing to follow a cross-origin link ('${Qn(n.origin,120)}' is not the environment's Power Apps endpoint '${r.origin}'); server-driven pagination must stay on that origin.`)}async send(t,r,n){let i;try{i=await t.get(r)}catch(o){throw o instanceof Yt.ConnectionError&&typeof o.statusCode=="number"&&o.statusCode>0?this.mapNon2xx(r,o.statusCode,void 0,n,o):o instanceof Yt.SdkError?o:new Yt.ConnectionError(r,0,o instanceof Error?o.message:String(o),o)}if(!i||typeof i.status!="number")throw new Yt.ConnectionError(r,0,"the transport returned no HTTP response");if(i.status>=200&&i.status<300)return i;throw this.mapNon2xx(r,i.status,i.body,n)}mapNon2xx(t,r,n,i,o){let a=o??new Yt.ConnectionError(t,r,UA(n),n);return i&&r===410&&UG(n)===FG?(0,Yt.attachCause)(new Yt.SdkError(Hl.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE,`The Power Apps API this reads through is decommissioned for this environment: ${UA(n)} Fall back to pac, or to the Power Platform API when the host has a client for it; the SDK does not fall back.`),a):r===401||r===403?(0,Hl.connectivityUnauthorized)(r,n,a):a}};_r.ConnectivityApi=$h});var Bh=v(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.projectConnectorTableSchema=Be.projectConnectorTables=Be.tableSchemaSuffix=Be.tablesSuffix=Be.encodeTable=Be.encodeDataset=Be.checkTabularConnection=Be.runtimeAuthority=Be.tabularRevision=Be.checkTableSchemaArguments=Be.checkListTablesArguments=void 0;var ta=Q(),M=ea(),qG=/^[A-Za-z0-9_.-]{1,128}$/,ra=/^\.{1,2}$/,VG="shared_sharepointonline",GG=/^[0-9]{1,9}$/,WG=/^[A-Za-z0-9._~-]+$/,zG=/^\/apim\/([A-Za-z0-9._-]+)\/?$/,jG=/^\/connectors\/runtime\/invoke\/scalegroups\/([A-Za-z0-9._-]+)\/(scaleunits|shards)\/([A-Za-z0-9._-]+)\/apis\/([A-Za-z0-9._-]+)\/connections\/?$/,HG=/^[A-Za-z0-9._~!'()*-]$/,KG=/^[0-9A-Fa-f]{2}$/;function Pi(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Jl(e){return typeof e=="string"?`'${(0,M.bounded)(e,80)}'`:(0,M.kindOf)(e)}function xh(e,t){return new ta.SdkError(M.CONNECTOR_NOT_TABULAR_CODE,`The connector '${(0,M.bounded)(e,80)}' has no tables: ${t}.`)}function fd(e,t){return new ta.SdkError(M.CONNECTOR_RUNTIME_UNSUPPORTED_CODE,`The connector '${(0,M.bounded)(e,80)}' runs where this SDK does not send a token: ${t}. Nothing was sent to it.`)}function JG(e){if(typeof e=="string"&&qG.test(e)&&!ra.test(e))return e;throw new ta.InvalidArgumentError(`connectionId must be a connection's name (letters, digits, '_', '.', '-'; at most 128; not '.' or '..'); got ${Jl(e)}.`)}function YG(e){if(e!=null){if(typeof e=="string"&&e!==""&&e.split(",").find(r=>r===""||ra.test(r))===void 0)return e;throw new ta.InvalidArgumentError(`dataset must be a non-empty string (a SharePoint site URL, a SQL 'server,database', \u2026) none of whose ','-separated parts is empty, '.' or '..', or absent for a connector without datasets; got ${Jl(e)}.`)}}function QG(e){if(typeof e=="string"&&e!==""&&!ra.test(e))return e;throw new ta.InvalidArgumentError(`table must be a non-empty string other than '.' and '..'; got ${Jl(e)}.`)}function GA(e,t,r){return{short:(0,M.connectorShortName)(e),connectionId:JG(t),dataset:YG(r)}}Be.checkListTablesArguments=GA;function XG(e,t,r,n){return{...GA(e,t,r),table:QG(n)}}Be.checkTableSchemaArguments=XG;function ZG(e,t){let r=`The connector '${(0,M.bounded)(t,80)}'`,n=e.properties;if(!(0,M.isObject)(n))throw(0,M.unreadable)(r,`its properties are ${(0,M.kindOf)(n)}, not an object`);if(!Pi(n,"interfaces"))throw xh(t,"it declares no interfaces");let i=n.interfaces;if(!(0,M.isObject)(i))throw(0,M.unreadable)(r,`its properties.interfaces are ${(0,M.kindOf)(i)}, not an object`);if(!Pi(i,"CDPTabular1"))throw xh(t,"it declares no CDPTabular1 interface");let o=i.CDPTabular1;if(!(0,M.isObject)(o))throw(0,M.unreadable)(r,`its CDPTabular1 interface is ${(0,M.kindOf)(o)}, not an object`);let a=o.revisions;if(!(0,M.isObject)(a))throw(0,M.unreadable)(r,`its CDPTabular1 revisions are ${(0,M.kindOf)(a)}, not an object`);let s,l=new Map;for(let u of Object.keys(a)){let c=a[u],d=`its CDPTabular1 revision '${(0,M.bounded)(u,40)}'`;if(!(0,M.isObject)(c)||typeof c.status!="string")throw(0,M.unreadable)(r,`${d} is not an object with a string status`);if(c.status!=="Production")continue;if(!GG.test(u))throw(0,M.unreadable)(r,`${d} is a Production revision whose key is not a decimal integer of 1\u20139 digits`);let f=e8(c.baseUrl);if(f===void 0)throw(0,M.unreadable)(r,`${d} has a baseUrl that is not '/' or '/'-separated [A-Za-z0-9._~-] segments`);let m=Number(u),p=l.get(m);if(p!==void 0)throw(0,M.unreadable)(r,`its Production revisions '${p}' and '${(0,M.bounded)(u,40)}' have the same number`);l.set(m,u),(!s||m>s.revisionNumber)&&(s={revisionNumber:m,revision:f})}if(!s)throw xh(t,"its CDPTabular1 interface has no Production revision");return s.revision}Be.tabularRevision=ZG;function e8(e){if(typeof e!="string")return;let t=e.replace(/^\/+/,"").replace(/\/+$/,"");return t===""?"":t.split("/").every(i=>WG.test(i)&&!ra.test(i))?t:void 0}function t8(e,t,r){let n=(0,M.isObject)(e.properties)?e.properties:void 0,i=n?n.primaryRuntimeUrl:void 0;if(typeof i!="string")throw fd(r,`its primaryRuntimeUrl is ${(0,M.kindOf)(i)}, not a string`);let o=t.cloud==="Test",a=(o?`https://${t.name}.tip2-001.tip2.azure-apihub.net`:t.origin).toLowerCase(),s=(0,M.parseUrl)(i);if(!s||s.protocol!=="https:"||s.origin.toLowerCase()!==a)throw fd(r,`its runtime ('${(0,M.bounded)(i,120)}') is not ${o?"this environment's measured API Hub host (<environment name>.tip2-001.tip2.azure-apihub.net)":"under this environment's own Power Platform API origin"} over https`);let l=i.slice(0,a.length).toLowerCase()===a?i.slice(a.length):void 0;if(o){let c=l===void 0?null:zG.exec(l);if(!c||ra.test(c[1]))throw fd(r,`its runtime ('${(0,M.bounded)(i,120)}') is not <host>/apim/<connector>`);return{transport:"invoke",origin:a,path:`/apim/${c[1]}`}}let u=l===void 0?null:jG.exec(l);if(!u||[u[1],u[3],u[4]].some(c=>ra.test(c)))throw fd(r,`its runtime ('${(0,M.bounded)(i,120)}') is not <origin>/connectors/runtime/invoke/scalegroups/<group>/(scaleunits|shards)/<unit>/apis/<api>/connections`);return{transport:"direct",origin:a,path:`/connectors/runtime/invoke/scalegroups/${u[1]}/${u[2]}/${u[3]}/apis/${u[4]}/connections`}}Be.runtimeAuthority=t8;function r8(e,t,r,n){let i=`The connection '${(0,M.bounded)(t,128)}'`;if(!(0,M.isObject)(e))throw(0,M.unreadable)(i,`it is ${(0,M.kindOf)(e)}, not an object`);if(e.name!==t)throw(0,M.unreadable)(i,`its name is ${Jl(e.name)}, not the requested connection`);let o=e.properties;if(!(0,M.isObject)(o))throw(0,M.unreadable)(i,`its properties are ${(0,M.kindOf)(o)}, not an object`);let a=o.apiId;if(typeof a!="string"||a.toLowerCase()!==`${M.CONNECTOR_PREFIX}${r}`.toLowerCase())throw(0,M.unreadable)(i,`its apiId is ${Jl(a)}, not the connector '${(0,M.bounded)(r,80)}'`);let s=o.environment,l=(0,M.isObject)(s)?s.name:void 0;if(typeof l!="string"||l.toLowerCase()!==n.toLowerCase())throw(0,M.unreadable)(i,"it is not a connection of this environment (properties.environment.name)");return t}Be.checkTabularConnection=r8;function VA(e){return encodeURIComponent(e).replace(/[!'()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`)}function n8(e){if(e==="")return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="%"){if(!KG.test(e.slice(t+1,t+3)))return!1;t+=2}else if(!HG.test(e[t]))return!1;return!0}function WA(e,t){let r,n,i;try{r=VA(e),n=VA(r),i=decodeURIComponent(n)}catch{throw new ta.InvalidArgumentError(`${t} is not well-formed Unicode (it has a lone surrogate), so it cannot be sent.`)}if(!n8(n)||ra.test(n)||i!==r)throw new ta.InvalidArgumentError(`${t} cannot be sent as one path segment.`);return n}function Uh(e){return e.split(",").map((t,r)=>WA(t,`dataset part ${r}`)).join(",")}Be.encodeDataset=Uh;function zA(e){return WA(e,"table")}Be.encodeTable=zA;function i8(e,t){if(t===void 0)return"/tables";let r=e.toLowerCase()===VG?"allTables":"tables";return`/datasets/${Uh(t)}/${r}`}Be.tablesSuffix=i8;function o8(e,t){return`/$metadata.json${e===void 0?"":`/datasets/${Uh(e)}`}/tables/${zA(t)}`}Be.tableSchemaSuffix=o8;function os(e,t){let r=t.toLowerCase();for(let n of Object.keys(e))if(n.toLowerCase()===r)return{found:!0,value:e[n]};return{found:!1}}function a8(e){let t="The table list",r;if(Array.isArray(e))r=e;else if((0,M.isObject)(e)){for(let o of["nextLink","@odata.nextLink"])if(os(e,o).found)throw(0,M.unreadable)(t,`it carries a ${o} \u2014 a paged answer is refused, never read as a partial list`);let n=os(e,"value"),i=n.found?n:os(e,"tables");if(!i.found)throw(0,M.unreadable)(t,"it is an object with neither a value nor a tables member");if(!Array.isArray(i.value))throw(0,M.unreadable)(t,`its ${n.found?"value":"tables"} is ${(0,M.kindOf)(i.value)}, not an array`);r=i.value}else throw(0,M.unreadable)(t,`it is ${(0,M.kindOf)(e)}, not an array or an object`);return{tables:r.map((n,i)=>s8(n,i))}}Be.projectConnectorTables=a8;function s8(e,t){let r=`Table row ${t}`;if(!(0,M.isObject)(e))throw(0,M.unreadable)(r,`it is ${(0,M.kindOf)(e)}, not an object`);let n=os(e,"name");if(!n.found||typeof n.value!="string"||n.value==="")throw(0,M.unreadable)(r,"it has no non-empty string name");let i=os(e,"displayName");if(i.found&&typeof i.value!="string")throw(0,M.unreadable)(r,`its displayName is ${(0,M.kindOf)(i.value)}, not a string`);let o=os(e,"id");if(o.found&&(typeof o.value!="string"||o.value===""))throw(0,M.unreadable)(r,`its id is ${o.value===""?"an empty string":(0,M.kindOf)(o.value)}, not a non-empty string`);return{name:n.value,displayName:i.found?i.value:null,id:o.found?o.value:n.value}}function Fh(e,t,r){if(!Pi(e,t))return;let n=e[t];if(!(0,M.isObject)(n))throw(0,M.unreadable)("The table schema",`its ${r} is ${(0,M.kindOf)(n)}, not an object`);return n}function Mh(e,t,r){if(!Pi(e,t))return;let n=e[t];if(typeof n!="string")throw(0,M.unreadable)(r,`its ${t} is ${(0,M.kindOf)(n)}, not a string`);return n}function l8(e,t){var r,n;if(Pi(e,"$ref"))throw(0,M.unreadable)(t,"it is a $ref, whose type is not guessed");let i=Mh(e,"type",t),o=Mh(e,"format",t),a=(r=i??o)!==null&&r!==void 0?r:"object";if(!Pi(e,"items"))return a;let s=e.items;if(!(0,M.isObject)(s))throw(0,M.unreadable)(t,`its items are ${(0,M.kindOf)(s)}, not an object`);if(Pi(s,"$ref"))throw(0,M.unreadable)(t,"its items are a $ref, whose type is not guessed");return`${a}<${(n=Mh(s,"type",`${t} items`))!==null&&n!==void 0?n:"object"}>`}function u8(e,t){let r="The table schema";if(!(0,M.isObject)(e))throw(0,M.unreadable)(r,`it is ${(0,M.kindOf)(e)}, not an object`);let n=Fh(e,"items","items"),i=Fh(e,"schema","schema"),o=i?Fh(i,"items","schema.items"):void 0,a=[[e,"the answer"],[n,"items"],[i,"schema"],[o,"schema.items"]],s=new Set;for(let[c,d]of a)if(c&&Pi(c,"required")){let f=c.required;if(!Array.isArray(f))throw(0,M.unreadable)(r,`the required of ${d} is ${(0,M.kindOf)(f)}, not an array`);f.forEach(m=>{if(typeof m!="string")throw(0,M.unreadable)(r,`the required of ${d} has an entry that is ${(0,M.kindOf)(m)}, not a string`);s.add(m.toLowerCase())})}let l;for(let[c,d]of a)if(c&&Pi(c,"properties")){if(!(0,M.isObject)(c.properties))throw(0,M.unreadable)(r,`the properties of ${d} are ${(0,M.kindOf)(c.properties)}, not an object`);l=c.properties;break}if(!l)throw(0,M.unreadable)(r,"it has no properties, items.properties, schema.properties or schema.items.properties");let u=Object.keys(l).map(c=>{let d=`Column '${(0,M.bounded)(c,80)}'`,f=l[c];if(!(0,M.isObject)(f))throw(0,M.unreadable)(d,`it is ${(0,M.kindOf)(f)}, not an object`);return{name:c,type:l8(f,d),required:s.has(c.toLowerCase())}});return{table:t,columns:u}}Be.projectConnectorTableSchema=u8});var jA=v(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});pd.PowerPlatformApiDiscovery=void 0;var qh=class{constructor(t){this.clusterCategory=t}getTokenAudience(){return`https://${this._getEnvironmentApiHostNameSuffix()}`}getTokenEndpointHost(){return this._getEnvironmentApiHostNameSuffix()}getTenantEndpoint(t){return this._generatePowerPlatformApiDomain(t,"tenant")}getTenantIslandClusterEndpoint(t){return this._generatePowerPlatformApiDomain(t,"tenant","il-")}getEnvironmentEndpoint(t){return this._generatePowerPlatformApiDomain(t,"environment")}_generatePowerPlatformApiDomain(t,r,n=""){if(!/^[a-zA-Z0-9\-]+$/g.test(t))throw new Error(`Cannot generate Power Platform API endpoint because the ${r} identifier contains invalid host name characters, only alphanumeric and dash characters are expected: ${t}`);let i=this._getHexApiSuffixLength(),o=t.toLowerCase().replace(/-/g,"");if(i>=o.length)throw new Error(`Cannot generate Power Platform API endpoint because the normalized ${r} identifier must be at least ${i+1} characters in length: ${o}`);let a=o.substring(o.length-i),s=o.substring(0,o.length-i),l=this._getEnvironmentApiHostNameSuffix();return`${n}${s}.${a}.${r}.${l}`}_getHexApiSuffixLength(){switch(this.clusterCategory){case"firstrelease":case"prod":return 2;default:return 1}}_getEnvironmentApiHostNameSuffix(){switch(this.clusterCategory){case"local":return"api.powerplatform.localhost";case"dev":return"api.dev.powerplatform.com";case"test":return"api.test.powerplatform.com";case"preprod":return"api.preprod.powerplatform.com";case"firstrelease":case"prod":return"api.powerplatform.com";case"gov":return"api.gov.powerplatform.microsoft.us";case"high":return"api.high.powerplatform.microsoft.us";case"dod":return"api.appsplatform.us";case"mooncake":return"api.powerplatform.partner.microsoftonline.cn";case"ex":return"api.powerplatform.eaglex.ic.gov";case"rx":return"api.powerplatform.microsoft.scloud";default:throw new Error(`Invalid ClusterCategory value: ${this.clusterCategory}`)}}};pd.PowerPlatformApiDiscovery=qh});var HA=v(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});md.PowerPlatformApiDiscovery=void 0;var c8=jA();Object.defineProperty(md,"PowerPlatformApiDiscovery",{enumerable:!0,get:function(){return c8.PowerPlatformApiDiscovery}})});var QA=v(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.platformTokenAudience=mo.platformEnvironment=mo.platformClusterOf=void 0;var KA=HA(),JA=Q(),YA=ea(),d8=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,f8=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,p8=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,m8=/^default-/i;function Vh(e,t=80){return e.length>t?`${e.slice(0,t)}\u2026`:e}function h8(e){try{return new URL(e).host.toLowerCase()}catch{return}}function g8(e){let t=h8(e);if(t){if(f8.test(t))return{cloud:"Test",category:"test"};let r=d8.exec(t);if(r&&r[1]!=="9")return{cloud:"Public",category:"prod"}}throw new JA.SdkError(YA.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The Power Platform API route is built for the Test and Public clouds; this org (${t?`'${Vh(t)}'`:`'${Vh(e)}', which is not a URL`}) is another cloud. A Public org is <name>.crm[N].dynamics.com (N other than 9) and a Test org <name>.crmtest.dynamics.com. GCC (crm9), GCC High, DoD, China, ports and custom domains are pending or out of scope. Nothing was requested.`)}mo.platformClusterOf=g8;function y8(e,t){let r=m8.test(e)?e.slice(8):e;if(!p8.test(r))throw new JA.SdkError(YA.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: its name ('${Vh(e)}') is neither a GUID nor 'Default-<GUID>', the forms this route is measured for. The Power Platform API was not asked about it.`);return{origin:`https://${new KA.PowerPlatformApiDiscovery(t).getEnvironmentEndpoint(e)}`,guid:r.toLowerCase()}}mo.platformEnvironment=y8;function b8(e){return new KA.PowerPlatformApiDiscovery(e).getTokenAudience()}mo.platformTokenAudience=b8});var ZA=v(as=>{"use strict";Object.defineProperty(as,"__esModule",{value:!0});as.PlatformConnectivityApi=as.assertTabularCloud=void 0;var Dn=Q(),Gh=Wl(),pe=ea(),XA=QA(),Ri=Bh(),Wh="1";function zh(e){let t=(0,pe.connectivityCloudOf)(e);if(t!=="Test"&&t!=="Public")throw new Dn.SdkError(pe.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,"Connector tables are read in the Test and Public clouds; this org's cloud is neither (GCC, GCC High and DoD are pending). Nothing was requested.")}as.assertTabularCloud=zh;var jh=class{constructor(t,r,n,i){this.org=t,this.instanceUrl=r,this.client=n,this.runtime=i,this.records=new Map,this.swaggers=new Map}async listConnections(){let t=await this.resolveEnvironment(),r=[],n=new Set,i=await this.send(this.client,"GET",`${t.origin}/connectivity/connections?api-version=${Wh}`,[401,403]),o=1,a=0;for(;;){let s=`Page ${o} of the connections`,l=i.body,u=l?.value;if(!Array.isArray(u))throw(0,pe.unreadable)(s,`its value is ${(0,pe.kindOf)(u)}, not an array`);for(let d of u){let f=(0,pe.readConnection)(d,a,t.name);a+=1,f&&r.push(f)}let c=l?.nextLink;if(c==null)return r;if(typeof c!="string"||c.length===0)throw(0,pe.unreadable)(s,`its nextLink is ${c===""?"an empty string":(0,pe.kindOf)(c)}, not a non-empty string`);if(n.has(c))throw new Dn.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${(0,pe.bounded)(c)}'), which would loop indefinitely.`);n.add(c),this.assertSameOrigin(c,t.parsed),i=await this.send(this.client,"GET",c,[401,403]),o+=1}}async listConnectorOperations(t){let r=(0,pe.connectorShortName)(t);return(0,Gh.projectConnectorOperations)(await this.swagger(r))}async getConnectorOperationSchema(t,r){let n=(0,pe.connectorShortName)(t);if(typeof r!="string"||r==="")throw new Dn.InvalidArgumentError("operationId must be a non-empty string.");return(0,Gh.projectConnectorOperationSchema)(await this.swagger(n),r)}async listConnectorTables(t,r,n){zh(this.instanceUrl);let i=(0,Ri.checkListTablesArguments)(t,r,n),o=(0,Ri.tablesSuffix)(i.short,i.dataset);return(0,Ri.projectConnectorTables)(await this.invokeTabular(i,o))}async getConnectorTableSchema(t,r,n,i){zh(this.instanceUrl);let o=(0,Ri.checkTableSchemaArguments)(t,r,n,i),a=(0,Ri.tableSchemaSuffix)(o.dataset,o.table);return(0,Ri.projectConnectorTableSchema)(await this.invokeTabular(o,a),o.table)}async invokeTabular(t,r){let n=this.requireRuntime(),i=await this.resolveEnvironment(),o=await this.record(t.short),a=(0,Ri.tabularRevision)(o,t.short),s=(0,Ri.runtimeAuthority)(o,{cloud:i.cloud,name:i.name,origin:i.origin},t.short),l=`${i.origin}/connectivity/connectors/${encodeURIComponent(t.short)}/connections/${encodeURIComponent(t.connectionId)}?$filter=${(0,pe.environmentFilter)(i.name)}&api-version=${Wh}`,u=(await this.send(this.client,"GET",l,[401,403])).body,c=(0,Ri.checkTabularConnection)(u,t.connectionId,t.short,i.name),d=`${s.path}/${c}${a===""?"":`/${a}`}${r}`;return(s.transport==="invoke"?await this.send(n,"POST",`${s.origin}/invoke`,[401],{"X-Ms-Request-Url":d,"X-Ms-Request-Method":"GET"}):await this.send(n,"GET",`${s.origin}${d}`,[401])).body}requireRuntime(){if(!this.runtime)throw new Dn.SdkError(pe.CONNECTIVITY_NOT_CONFIGURED_CODE,"This SDK was created without a connectorRuntimeClient (MakerSdkOptions), so it cannot read connector tables: it needs an HttpClient that authenticates for API Hub (https://apihub.azure.com) and does not follow redirects. Nothing was requested.");return this.runtime}resolveEnvironment(){if(!this.environment){let t=this.readEnvironment();this.environment=t,t.catch(()=>{this.environment===t&&(this.environment=void 0)})}return this.environment}async readEnvironment(){let{cloud:t,category:r}=(0,XA.platformClusterOf)(this.instanceUrl),n=await(0,pe.readEnvironmentName)(this.org),{origin:i,guid:o}=(0,XA.platformEnvironment)(n,r),a=(0,pe.parseUrl)(i);if(!a)throw(0,pe.unreadable)("The Power Platform API origin",`'${(0,pe.bounded)(i)}' is not a URL`);return{cloud:t,origin:i,parsed:a,name:n,guid:o}}cached(t,r,n){let i=t.get(r);if(!i){let o=n();i=o,t.set(r,o),o.catch(()=>{t.get(r)===o&&t.delete(r)})}return i}record(t){return this.cached(this.records,t.toLowerCase(),()=>this.readRecord(t))}async readRecord(t){let r=await this.resolveEnvironment(),n=`${r.origin}/connectivity/connectors/${encodeURIComponent(t)}?$filter=${(0,pe.environmentFilter)(r.name)}&api-version=${Wh}`,i=(await this.send(this.client,"GET",n,[401,403])).body,o=(0,pe.isObject)(i)?i.name:void 0;if(!(0,pe.isObject)(i)||typeof o!="string"||o.toLowerCase()!==t.toLowerCase())throw(0,pe.unreadable)(`The connector '${(0,pe.bounded)(t,80)}'`,`the record's name is ${typeof o=="string"?`'${(0,pe.bounded)(o,80)}'`:(0,pe.kindOf)(o)}, not the requested connector`);return i}swagger(t){return this.cached(this.swaggers,t.toLowerCase(),async()=>{let n=(await this.record(t)).properties,i=(0,pe.isObject)(n)?n.swagger:void 0;if(!(0,pe.isObject)(i))throw(0,pe.unreadable)(`The connector '${(0,pe.bounded)(t,80)}'`,`its properties.swagger is ${(0,pe.kindOf)(i)}, not an object`);return(0,Gh.validateConnectorSwagger)(i),i})}assertSameOrigin(t,r){let n=(0,pe.parseUrl)(t);if(!n)throw new Dn.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${(0,pe.bounded)(t)}'`);if(!(0,pe.sameOrigin)(n,r))throw new Dn.InvalidArgumentError(`Refusing to follow a cross-origin link ('${(0,pe.bounded)(n.origin,120)}' is not the environment's Power Platform API origin '${r.origin}'); server-driven pagination must stay on that origin.`)}async send(t,r,n,i,o){let a;try{a=r==="GET"?await t.get(n):await t.post(n,void 0,{headers:o})}catch(s){throw s instanceof Dn.ConnectionError&&typeof s.statusCode=="number"&&s.statusCode>0?this.non2xx(n,s.statusCode,void 0,i,s):s instanceof Dn.SdkError?s:new Dn.ConnectionError(n,0,s instanceof Error?s.message:String(s),s)}if(!a||typeof a.status!="number")throw new Dn.ConnectionError(n,0,"the transport returned no HTTP response");if(a.status>=200&&a.status<300)return a;throw this.non2xx(n,a.status,a.body,i)}non2xx(t,r,n,i,o){let a=o??new Dn.ConnectionError(t,r,(0,pe.messageOf)(n),n);return i.includes(r)?(0,pe.connectivityUnauthorized)(r,n,a):a}};as.PlatformConnectivityApi=jh});var tS=v(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});gd.ConnectivityRouter=void 0;var Hh=Q(),v8=qA(),hd=ea(),eS=Bh(),Kh=ZA(),Jh=class{constructor(t,r,n){this.org=t,this.instanceUrl=r,this.clients=n}async listConnections(){return this.route().listConnections()}async listConnectorOperations(t){return this.route().listConnectorOperations(t)}async getConnectorOperationSchema(t,r){return this.route().getConnectorOperationSchema(t,r)}async listConnectorTables(t,r,n){return(0,Kh.assertTabularCloud)(this.instanceUrl),(0,eS.checkListTablesArguments)(t,r,n),this.tabularRoute().listConnectorTables(t,r,n)}async getConnectorTableSchema(t,r,n,i){return(0,Kh.assertTabularCloud)(this.instanceUrl),(0,eS.checkTableSchemaArguments)(t,r,n,i),this.tabularRoute().getConnectorTableSchema(t,r,n,i)}route(){return this.delegate||(this.delegate=this.select()),this.delegate}platformRoute(t){return this.platform||(this.platform=new Kh.PlatformConnectivityApi(this.org,this.instanceUrl,t,this.clients.connectorRuntimeClient)),this.platform}tabularRoute(){let{powerPlatformApiClient:t,connectorRuntimeClient:r}=this.clients,n=[t?void 0:"powerPlatformApiClient (the Power Platform API)",r?void 0:"connectorRuntimeClient (API Hub, https://apihub.azure.com)"].filter(i=>i!==void 0);if(n.length>0||!t)throw new Hh.SdkError(hd.CONNECTIVITY_NOT_CONFIGURED_CODE,`Connector tables are read through the Power Platform API and the connector runtime: this SDK was created without MakerSdkOptions.${n.join(" or MakerSdkOptions.")}, an HttpClient that does not follow redirects. Nothing was requested.`);return this.platformRoute(t)}select(){let t=(0,hd.connectivityCloudOf)(this.instanceUrl),{powerAppsServiceClient:r,powerPlatformApiClient:n}=this.clients;if(t==="Unsupported")throw new Hh.SdkError(hd.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,"This org's cloud has no connection/connector route: the Test and Public clouds are served (through the Power Platform API, or the classic route for Public); GCC, GCC High and DoD are pending. Nothing was requested.");if(n)return this.platformRoute(n);if(t==="Public"&&r)return new v8.ConnectivityApi(this.org,this.instanceUrl,r);throw new Hh.SdkError(hd.CONNECTIVITY_NOT_CONFIGURED_CODE,t==="Test"?"This org is in the Test cloud, whose connection and connector reads go through the Power Platform API: supply MakerSdkOptions.powerPlatformApiClient (an HttpClient that authenticates for the Power Platform API and does not follow redirects). Nothing was requested.":"This org is in the Public cloud: supply MakerSdkOptions.powerPlatformApiClient (the Power Platform API route) or powerAppsServiceClient (the classic route). Neither was given, so nothing was requested.")}};gd.ConnectivityRouter=Jh});var ss=v(Li=>{"use strict";function w8(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 Qh(e,t){return t===void 0&&(t=Object),t&&typeof t.freeze=="function"?t.freeze(e):e}function C8(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 rS=Qh({HTML:"text/html",isHTML:function(e){return e===rS.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),nS=Qh({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(e){return e===nS.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"}),yd=/[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]/,Yh=new RegExp("[\\-\\.0-9"+yd.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),E8=new RegExp("^"+yd.source+Yh.source+"*(?::"+yd.source+Yh.source+"*)?$");Li.assign=C8;Li.find=w8;Li.freeze=Qh;Li.MIME_TYPE=rS;Li.NAMESPACE=nS;Li.nameStartChar=yd;Li.nameChar=Yh;Li.tagNamePattern=E8});var ug=v(Fi=>{var Xh=ss(),Xn=Xh.find,Ql=Xh.NAMESPACE,ls=Xh.tagNamePattern;function A8(e){return e!==""}function S8(e){return e?e.split(/[\t\n\f\r ]+/).filter(A8):[]}function N8(e,t){return e.hasOwnProperty(t)||(e[t]=!0),e}function iS(e){if(!e)return[];var t=S8(e);return Object.keys(t.reduce(N8,{}))}function _8(e){return function(t){return e&&e.indexOf(t)!==-1}}function Zl(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function Dr(e,t){var r=e.prototype;if(!(r instanceof t)){let i=function(){};var n=i;i.prototype=t.prototype,i=new i,Zl(r,i),e.prototype=r=i}r.constructor!=e&&(typeof e!="function"&&console.error("unknown Class:"+e),r.constructor=e)}var Ir={},un=Ir.ELEMENT_NODE=1,us=Ir.ATTRIBUTE_NODE=2,Yl=Ir.TEXT_NODE=3,fS=Ir.CDATA_SECTION_NODE=4,pS=Ir.ENTITY_REFERENCE_NODE=5,T8=Ir.ENTITY_NODE=6,Zh=Ir.PROCESSING_INSTRUCTION_NODE=7,eg=Ir.COMMENT_NODE=8,mS=Ir.DOCUMENT_NODE=9,hS=Ir.DOCUMENT_TYPE_NODE=10,ki=Ir.DOCUMENT_FRAGMENT_NODE=11,D8=Ir.NOTATION_NODE=12,Qt={},Ot={},vce=Qt.INDEX_SIZE_ERR=(Ot[1]="Index size error",1),wce=Qt.DOMSTRING_SIZE_ERR=(Ot[2]="DOMString size error",2),Tr=Qt.HIERARCHY_REQUEST_ERR=(Ot[3]="Hierarchy request error",3),Cce=Qt.WRONG_DOCUMENT_ERR=(Ot[4]="Wrong document",4),oS=Qt.INVALID_CHARACTER_ERR=(Ot[5]="Invalid character",5),Ece=Qt.NO_DATA_ALLOWED_ERR=(Ot[6]="No data allowed",6),Ace=Qt.NO_MODIFICATION_ALLOWED_ERR=(Ot[7]="No modification allowed",7),gS=Qt.NOT_FOUND_ERR=(Ot[8]="Not found",8),Sce=Qt.NOT_SUPPORTED_ERR=(Ot[9]="Not supported",9),aS=Qt.INUSE_ATTRIBUTE_ERR=(Ot[10]="Attribute in use",10),In=Qt.INVALID_STATE_ERR=(Ot[11]="Invalid state",11),Nce=Qt.SYNTAX_ERR=(Ot[12]="Syntax error",12),_ce=Qt.INVALID_MODIFICATION_ERR=(Ot[13]="Invalid modification",13),Tce=Qt.NAMESPACE_ERR=(Ot[14]="Invalid namespace",14),Dce=Qt.INVALID_ACCESS_ERR=(Ot[15]="Invalid access",15);function me(e,t){if(t instanceof Error)var r=t;else r=this,Error.call(this,Ot[e]),this.message=Ot[e],Error.captureStackTrace&&Error.captureStackTrace(this,me);return r.code=e,t&&(this.message=this.message+": "+t),r}me.prototype=Error.prototype;Zl(Qt,me);function $i(){}$i.prototype={length:0,item:function(e){return e>=0&&e<this.length?this[e]:null},toString:function(e,t,r){for(var n=!!r&&!!r.requireWellFormed,i=[],o=0;o<this.length;o++)lg(this[o],i,e,t,null,n);return i.join("")},filter:function(e){return Array.prototype.filter.call(this,e)},indexOf:function(e){return Array.prototype.indexOf.call(this,e)}};function cs(e,t){this._node=e,this._refresh=t,tg(this)}function tg(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!==t){var r=e._refresh(e._node);if(IS(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];Zl(r,e),e._inc=t}}cs.prototype.item=function(e){return tg(this),this[e]||null};Dr(cs,$i);function vd(){this._nameIndex=Object.create(null)}function yS(e,t){for(var r=e.length;r--;)if(e[r]===t)return r}function I8(e,t){e._nameIndex[t.nodeName]=t}function bS(e,t){e._nameIndex[t.nodeName]===t&&delete e._nameIndex[t.nodeName]}function sS(e,t,r,n){if(n?(t[yS(t,n)]=r,bS(t,n)):t[t.length++]=r,I8(t,r),e){r.ownerElement=e;var i=e.ownerDocument;i&&(n&&CS(i,e,n),O8(i,e,r))}}function lS(e,t,r){var n=yS(t,r);if(n>=0){for(var i=t.length-1;n<i;)t[n]=t[++n];if(t.length=i,bS(t,r),e){var o=e.ownerDocument;o&&(CS(o,e,r),r.ownerElement=null)}}else throw new me(gS,new Error(e.tagName+"@"+r))}vd.prototype={length:0,item:$i.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 me(aS);var r=this._nameIndex[e.nodeName];return sS(this._ownerElement,this,e,r),r},setNamedItemNS:function(e){var t=e.ownerElement,r;if(t&&t!=this._ownerElement)throw new me(aS);return r=this.getNamedItemNS(e.namespaceURI,e.localName),sS(this._ownerElement,this,e,r),r},removeNamedItem:function(e){var t=this.getNamedItem(e);return lS(this._ownerElement,this,t),t},removeNamedItemNS:function(e,t){var r=this.getNamedItemNS(e,t);return lS(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 vS(){}vS.prototype={hasFeature:function(e,t){return!0},createDocument:function(e,t,r){var n=new eu;if(n.implementation=this,n.childNodes=new $i,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 Sd;return n.name=e,n.nodeName=e,n.publicId=t||"",n.systemId=r||"",n}};function De(){}De.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 Cd(this,e,t)},replaceChild:function(e,t){Cd(this,e,t,AS),t&&this.removeChild(t)},removeChild:function(e){return ES(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return DS(this.ownerDocument||this,this,e)},normalize:function(){It(this,null,{enter:function(e){for(var t=e.firstChild;t;){var r=t.nextSibling;if(r!==null&&r.nodeType===Yl&&t.nodeType===Yl){for(var n=[],i=r;i!==null&&i.nodeType===Yl;)n.push(i.data),i=i.nextSibling;for(var o=t.nextSibling;o!==i;){var a=o.nextSibling;o.parentNode=null,o.previousSibling=null,o.nextSibling=null,o=a}t.nextSibling=i,i!==null?i.previousSibling=t:e.lastChild=t,t.appendData(n.join("")),Ad(e.ownerDocument,e),t=i}else t=r}return!0}})},isSupported:function(e,t){return this.ownerDocument.implementation.hasFeature(e,t)},hasAttributes:function(){return this.attributes.length>0},lookupPrefix:function(e){for(var t=this;t;){var r=t._nsMap;if(r){for(var n in r)if(Object.prototype.hasOwnProperty.call(r,n)&&r[n]===e)return n}t=t.nodeType==us?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==us?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){var t=this.lookupPrefix(e);return t==null}};function wS(e){return e=="<"&&"<"||e==">"&&">"||e=="&"&&"&"||e=='"'&&"""||"&#"+e.charCodeAt()+";"}Zl(Ir,De);Zl(Ir,De.prototype);function wd(e,t){return It(e,null,{enter:function(r){return t(r)?It.STOP:!0}})===It.STOP}function It(e,t,r){for(var n=[{node:e,context:t,phase:It.ENTER}];n.length>0;){var i=n.pop();if(i.phase===It.ENTER){var o=r.enter(i.node,i.context);if(o===It.STOP)return It.STOP;if(n.push({node:i.node,context:o,phase:It.EXIT}),o==null)continue;for(var a=i.node.lastChild;a;)n.push({node:a,context:o,phase:It.ENTER}),a=a.previousSibling}else r.exit&&r.exit(i.node,i.context)}}It.STOP=Symbol("walkDOM.STOP");It.ENTER=0;It.EXIT=1;function eu(){this.ownerDocument=this}function O8(e,t,r){e&&e._inc++;var n=r.namespaceURI;n===Ql.XMLNS&&(t._nsMap[r.prefix?r.localName:""]=r.value)}function CS(e,t,r,n){e&&e._inc++;var i=r.namespaceURI;i===Ql.XMLNS&&delete t._nsMap[r.prefix?r.localName:""]}function Ad(e,t,r){if(e&&e._inc){e._inc++;var n=t.childNodes;if(r)n[n.length++]=r;else{for(var i=t.firstChild,o=0;i;)n[o++]=i,i=i.nextSibling;n.length=o,delete n[n.length]}}}function ES(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,Ad(e.ownerDocument,e),t}function P8(e){return e&&(e.nodeType===De.DOCUMENT_NODE||e.nodeType===De.DOCUMENT_FRAGMENT_NODE||e.nodeType===De.ELEMENT_NODE)}function R8(e){return e&&(Zn(e)||rg(e)||xi(e)||e.nodeType===De.DOCUMENT_FRAGMENT_NODE||e.nodeType===De.COMMENT_NODE||e.nodeType===De.PROCESSING_INSTRUCTION_NODE)}function xi(e){return e&&e.nodeType===De.DOCUMENT_TYPE_NODE}function Zn(e){return e&&e.nodeType===De.ELEMENT_NODE}function rg(e){return e&&e.nodeType===De.TEXT_NODE}function uS(e,t){var r=e.childNodes||[];if(Xn(r,Zn)||xi(t))return!1;var n=Xn(r,xi);return!(t&&n&&r.indexOf(n)>r.indexOf(t))}function cS(e,t){var r=e.childNodes||[];function n(o){return Zn(o)&&o!==t}if(Xn(r,n))return!1;var i=Xn(r,xi);return!(t&&i&&r.indexOf(i)>r.indexOf(t))}function L8(e,t,r){if(!P8(e))throw new me(Tr,"Unexpected parent node type "+e.nodeType);if(r&&r.parentNode!==e)throw new me(gS,"child not in parent");if(!R8(t)||xi(t)&&e.nodeType!==De.DOCUMENT_NODE)throw new me(Tr,"Unexpected node type "+t.nodeType+" for parent node type "+e.nodeType)}function k8(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===De.DOCUMENT_FRAGMENT_NODE){var o=i.filter(Zn);if(o.length>1||Xn(i,rg))throw new me(Tr,"More than one element or text in fragment");if(o.length===1&&!uS(e,r))throw new me(Tr,"Element in fragment can not be inserted before doctype")}if(Zn(t)&&!uS(e,r))throw new me(Tr,"Only one element can be added and only after doctype");if(xi(t)){if(Xn(n,xi))throw new me(Tr,"Only one doctype is allowed");var a=Xn(n,Zn);if(r&&n.indexOf(a)<n.indexOf(r))throw new me(Tr,"Doctype can only be inserted before an element");if(!r&&a)throw new me(Tr,"Doctype can not be appended since element is present")}}function AS(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===De.DOCUMENT_FRAGMENT_NODE){var o=i.filter(Zn);if(o.length>1||Xn(i,rg))throw new me(Tr,"More than one element or text in fragment");if(o.length===1&&!cS(e,r))throw new me(Tr,"Element in fragment can not be inserted before doctype")}if(Zn(t)&&!cS(e,r))throw new me(Tr,"Only one element can be added and only after doctype");if(xi(t)){let l=function(u){return xi(u)&&u!==r};var s=l;if(Xn(n,l))throw new me(Tr,"Only one doctype is allowed");var a=Xn(n,Zn);if(r&&n.indexOf(a)<n.indexOf(r))throw new me(Tr,"Doctype can only be inserted before an element")}}function Cd(e,t,r,n){L8(e,t,r),e.nodeType===De.DOCUMENT_NODE&&(n||k8)(e,t,r);var i=t.parentNode;if(i&&i.removeChild(t),t.nodeType===ki){var o=t.firstChild;if(o==null)return t;var a=t.lastChild}else o=a=t;var s=r?r.previousSibling:e.lastChild;o.previousSibling=s,a.nextSibling=r,s?s.nextSibling=o:e.firstChild=o,r==null?e.lastChild=a:r.previousSibling=a;do{o.parentNode=e;var l=e.ownerDocument||e;Xl(o,l)}while(o!==a&&(o=o.nextSibling));return Ad(e.ownerDocument||e,e),t.nodeType==ki&&(t.firstChild=t.lastChild=null),t}function Xl(e,t){if(e.ownerDocument!==t){if(e.ownerDocument=t,e.nodeType===un&&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;)Xl(i,t),i=i.nextSibling}}function $8(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,Ad(e.ownerDocument,e,t);var r=e.ownerDocument||e;return Xl(t,r),t}eu.prototype={nodeName:"#document",nodeType:mS,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==ki){for(var r=e.firstChild;r;){var n=r.nextSibling;this.insertBefore(r,t),r=n}return e}return Cd(this,e,t),Xl(e,this),this.documentElement===null&&e.nodeType===un&&(this.documentElement=e),e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),ES(this,e)},replaceChild:function(e,t){Cd(this,e,t,AS),Xl(e,this),t&&this.removeChild(t),Zn(e)&&(this.documentElement=e)},importNode:function(e,t){return x8(this,e,t)},getElementById:function(e){var t=null;return wd(this.documentElement,function(r){if(r.nodeType==un&&r.getAttribute("id")==e)return t=r,!0}),t},getElementsByClassName:function(e){var t=iS(e);return new cs(this,function(r){var n=[];return t.length>0&&wd(r.documentElement,function(i){if(i!==r&&i.nodeType===un){var o=i.getAttribute("class");if(o){var a=e===o;if(!a){var s=iS(o);a=t.every(_8(s))}a&&n.push(i)}}}),n})},createElement:function(e){var t=new na;t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.localName=e,t.childNodes=new $i;var r=t.attributes=new vd;return r._ownerElement=t,t},createDocumentFragment:function(){var e=new Nd;return e.ownerDocument=this,e.childNodes=new $i,e},createTextNode:function(e){var t=new ng;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new ig;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){if(e.indexOf("]]>")!==-1)throw new me(oS,'data contains "]]>"');var t=new og;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var r=new sg;return r.ownerDocument=this,r.tagName=r.nodeName=r.target=e,r.nodeValue=r.data=t,r},createAttribute:function(e){var t=new Ed;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){if(!ls.test(e))throw new me(oS,'not a valid xml name "'+e+'"');var t=new ag;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var r=new na,n=t.split(":"),i=r.attributes=new vd;return r.childNodes=new $i,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 Ed,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}};Dr(eu,De);function na(){this._nsMap={}}na.prototype={nodeType:un,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===ki?this.insertBefore(e,null):$8(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 cs(this,function(t){var r=[];return wd(t,function(n){n!==t&&n.nodeType==un&&(e==="*"||n.tagName==e)&&r.push(n)}),r})},getElementsByTagNameNS:function(e,t){return new cs(this,function(r){var n=[];return wd(r,function(i){i!==r&&i.nodeType===un&&(e==="*"||i.namespaceURI===e)&&(t==="*"||i.localName==t)&&n.push(i)}),n})}};eu.prototype.getElementsByTagName=na.prototype.getElementsByTagName;eu.prototype.getElementsByTagNameNS=na.prototype.getElementsByTagNameNS;Dr(na,De);function Ed(){}Ed.prototype.nodeType=us;Dr(Ed,De);function tu(){}tu.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(Ot[Tr])},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}};Dr(tu,De);function ng(){}ng.prototype={nodeName:"#text",nodeType:Yl,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}};Dr(ng,tu);function ig(){}ig.prototype={nodeName:"#comment",nodeType:eg};Dr(ig,tu);function og(){}og.prototype={nodeName:"#cdata-section",nodeType:fS};Dr(og,tu);function Sd(){}Sd.prototype.nodeType=hS;Dr(Sd,De);function SS(){}SS.prototype.nodeType=D8;Dr(SS,De);function NS(){}NS.prototype.nodeType=T8;Dr(NS,De);function ag(){}ag.prototype.nodeType=pS;Dr(ag,De);function Nd(){}Nd.prototype.nodeName="#document-fragment";Nd.prototype.nodeType=ki;Dr(Nd,De);function sg(){}sg.prototype.nodeType=Zh;Dr(sg,De);function _S(){}_S.prototype.serializeToString=function(e,t,r,n){return TS.call(e,t,r,n)};De.prototype.toString=TS;function TS(e,t,r){var n=!!r&&!!r.requireWellFormed,i=[],o=this.nodeType==9&&this.documentElement||this,a=o.prefix,s=o.namespaceURI;if(s&&a==null){var a=o.lookupPrefix(s);if(a==null)var l=[{namespace:s,prefix:null}]}return lg(this,i,e,t,l,n),i.join("")}function dS(e,t,r){var n=e.prefix||"",i=e.namespaceURI;if(!i||n==="xml"&&i===Ql.XML||i===Ql.XMLNS)return!1;for(var o=r.length;o--;){var a=r[o];if(a.prefix===n)return a.namespace!==i}return!0}function bd(e,t,r,n){if(n&&!ls.test(t))throw new me(In,'The attribute name "'+t+'" is not a valid XML QName');e.push(" ",t,'="',r.replace(/[<>&"\t\n\r]/g,wS),'"')}function lg(e,t,r,n,i,o){i||(i=[]),It(e,{ns:i,isHTML:r},{enter:function(a,s){var l=s.ns,u=s.isHTML;if(n)if(a=n(a),a){if(typeof a=="string")return t.push(a),null}else return null;switch(a.nodeType){case un:var c=a.attributes,d=c.length,f=a.tagName;u=Ql.isHTML(a.namespaceURI)||u;var m=f;if(!u&&!a.prefix&&a.namespaceURI){for(var p,h=0;h<c.length;h++)if(c.item(h).name==="xmlns"){p=c.item(h).value;break}if(!p)for(var g=l.length-1;g>=0;g--){var b=l[g];if(b.prefix===""&&b.namespace===a.namespaceURI){p=b.namespace;break}}if(p!==a.namespaceURI)for(var g=l.length-1;g>=0;g--){var b=l[g];if(b.namespace===a.namespaceURI){b.prefix&&(m=b.prefix+":"+f);break}}}if(o&&!ls.test(m))throw new me(In,'The element name "'+m+'" is not a valid XML QName');t.push("<",m);for(var w=l.slice(),C=0;C<d;C++){var S=c.item(C);S.prefix=="xmlns"?w.push({prefix:S.localName,namespace:S.value}):S.nodeName=="xmlns"&&w.push({prefix:"",namespace:S.value})}for(var C=0;C<d;C++){var S=c.item(C);if(dS(S,u,w)){var O=S.prefix||"",L=S.namespaceURI;bd(t,O?"xmlns:"+O:"xmlns",L,o),w.push({prefix:O,namespace:L})}var I=n?n(S):S;I&&(typeof I=="string"?t.push(I):bd(t,I.name,I.value,o))}if(f===m&&dS(a,u,w)){var D=a.prefix||"",L=a.namespaceURI;bd(t,D?"xmlns:"+D:"xmlns",L,o),w.push({prefix:D,namespace:L})}var P=a.firstChild;if(P||u&&!/^(?:meta|link|img|br|hr|input)$/i.test(f)){if(t.push(">"),u&&/^script$/i.test(f)){for(;P;)P.data?t.push(P.data):lg(P,t,u,n,w.slice(),o),P=P.nextSibling;return t.push("</",f,">"),null}return{ns:w,isHTML:u,tag:m}}else return t.push("/>"),null;case mS:case ki:return{ns:l.slice(),isHTML:u,tag:null};case us:return bd(t,a.name,a.value,o),null;case Yl:return t.push(a.data.replace(/[<&>]/g,wS)),null;case fS:if(o&&a.data.indexOf("]]>")!==-1)throw new me(In,'The CDATASection data contains "]]>"');return t.push("<![CDATA[",a.data.replace(/]]>/g,"]]]]><![CDATA[>"),"]]>"),null;case eg:if(o&&a.data.indexOf("-->")!==-1)throw new me(In,'The comment node data contains "-->"');return t.push("<!--",a.data,"-->"),null;case hS:if(o){if(!ls.test(a.name))throw new me(In,'The doctype name "'+a.name+'" is not a valid XML Name');if(a.publicId&&!/^("[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%']*"|'[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%'"]*')$/.test(a.publicId))throw new me(In,"DocumentType publicId is not a valid PubidLiteral");if(a.systemId&&!/^("[^"]*"|'[^']*')$/.test(a.systemId))throw new me(In,"DocumentType systemId is not a valid SystemLiteral");if(a.internalSubset&&a.internalSubset.indexOf("]>")!==-1)throw new me(In,'DocumentType internalSubset contains "]>"')}var x=a.publicId,K=a.systemId;if(t.push("<!DOCTYPE ",a.name),x)t.push(" PUBLIC ",x),K&&K!="."&&t.push(" ",K),t.push(">");else if(K&&K!=".")t.push(" SYSTEM ",K,">");else{var Le=a.internalSubset;Le&&t.push(" [",Le,"]"),t.push(">")}return null;case Zh:if(o){if(!ls.test(a.target)||a.target.indexOf(":")!==-1||a.target.toLowerCase()==="xml")throw new me(In,'The processing instruction target "'+a.target+'" is not a valid XML NCName or is reserved');if(a.data.indexOf("?>")!==-1)throw new me(In,'The ProcessingInstruction data contains "?>"')}return t.push("<?",a.target," ",a.data,"?>"),null;case pS:if(o&&!ls.test(a.nodeName))throw new me(In,'The entity reference name "'+a.nodeName+'" is not a valid XML Name');return t.push("&",a.nodeName,";"),null;default:return t.push("??",a.nodeName),null}},exit:function(a,s){s&&s.tag&&t.push("</",s.tag,">")}})}function x8(e,t,r){var n;return It(t,null,{enter:function(i,o){var a=i.cloneNode(!1);a.ownerDocument=e,a.parentNode=null,o===null?n=a:o.appendChild(a);var s=i.nodeType===us||r;return s?a:null}}),n}function DS(e,t,r){var n;return It(t,null,{enter:function(i,o){var a=new i.constructor;for(var s in i)if(Object.prototype.hasOwnProperty.call(i,s)){var l=i[s];typeof l!="object"&&l!=a[s]&&(a[s]=l)}i.childNodes&&(a.childNodes=new $i),a.ownerDocument=e;var u=r;switch(a.nodeType){case un:var c=i.attributes,d=a.attributes=new vd,f=c.length;d._ownerElement=a;for(var m=0;m<f;m++)a.setAttributeNode(DS(e,c.item(m),!0));break;case us:u=!0}return o!==null?o.appendChild(a):n=a,u?a:null}}),n}function IS(e,t,r){e[t]=r}try{Object.defineProperty&&(Object.defineProperty(cs.prototype,"length",{get:function(){return tg(this),this.$$length}}),Object.defineProperty(De.prototype,"textContent",{get:function(){if(this.nodeType===un||this.nodeType===ki){var e=[];return It(this,null,{enter:function(t){if(t.nodeType===un||t.nodeType===ki)return!0;if(t.nodeType===Zh||t.nodeType===eg)return null;e.push(t.nodeValue)}}),e.join("")}return this.nodeValue},set:function(e){switch(this.nodeType){case un:case ki: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}}}),IS=function(e,t,r){e["$$"+t]=r})}catch{}Fi.DocumentType=Sd;Fi.DOMException=me;Fi.DOMImplementation=vS;Fi.Element=na;Fi.Node=De;Fi.NodeList=$i;Fi.walkDOM=It;Fi.XMLSerializer=_S});var PS=v(ru=>{"use strict";var OS=ss().freeze;ru.XML_ENTITIES=OS({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});ru.HTML_ENTITIES=OS({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"});ru.entityMap=ru.HTML_ENTITIES});var xS=v(dg=>{var ou=ss().NAMESPACE,cg=ss().tagNamePattern,ds=0,ho=1,fs=2,nu=3,ps=4,ms=5,iu=6,_d=7;function hs(e,t){this.message=e,this.locator=t,Error.captureStackTrace&&Error.captureStackTrace(this,hs)}hs.prototype=new Error;hs.prototype.name=hs.name;function kS(){}kS.prototype={parse:function(e,t,r){var n=this.domBuilder;n.startDocument(),q8(t,t={}),F8(e,t,r,n,this.errorHandler),n.endDocument()}};function F8(e,t,r,n,i){function o(de){if(de>65535){de-=65536;var Ke=55296+(de>>10),ur=56320+(de&1023);return String.fromCharCode(Ke,ur)}else return String.fromCharCode(de)}function a(de){var Ke=de.slice(1,-1);return Object.hasOwnProperty.call(r,Ke)?r[Ke]:Ke.charAt(0)==="#"?o(parseInt(Ke.substr(1).replace("x","0x"))):(i.error("entity not found:"+de),de)}function s(de){if(de>h){var Ke=e.substring(h,de).replace(/&#?\w+;/g,a);f&&l(h),n.characters(Ke,0,de-h),h=de}}function l(de,Ke){for(;de>=c&&(Ke=d.exec(e));)u=Ke.index,c=u+Ke[0].length,f.lineNumber++;f.columnNumber=de-u+1}for(var u=0,c=0,d=/.*(?:\r\n?|\n)|.*$/g,f=n.locator,m=[{currentNSMap:t}],p={},h=0;;){try{var g=e.indexOf("<",h);if(g<0){if(!e.substr(h).match(/^\s*$/)){var b=n.doc,w=b.createTextNode(e.substr(h));b.appendChild(w),n.currentElement=w}return}switch(g>h&&s(g),e.charAt(g+1)){case"/":var K=e.indexOf(">",g+3),C=e.substring(g+2,K).replace(/^([\s\S]*?[^ \t\n\r])?[ \t\n\r]*$/,"$1"),S=m.pop();K<0?(C=e.substring(g+2).replace(/[\s<].*/,""),i.error("end tag name: "+C+" is not complete:"+S.tagName),K=g+1+C.length):C.match(/\s</)?(C=C.replace(/[\s<].*/,""),i.error("end tag name: "+C+" maybe not complete"),K=g+1+C.length):/[ \t\n\r]/.test(C)&&cg.test(C.split(/[ \t\n\r]/)[0])&&i.error('end tag name is followed by whitespace and trailing content: "'+C+'"');var O=S.localNSMap,L=S.tagName==C,I=L||S.tagName&&S.tagName.toLowerCase()==C.toLowerCase();if(I){if(n.endElement(S.uri,S.localName,C),O)for(var D in O)Object.prototype.hasOwnProperty.call(O,D)&&n.endPrefixMapping(D);L||i.fatalError("end tag name: "+C+" is not match the current start tagName:"+S.tagName)}else m.push(S);K++;break;case"?":f&&l(g),K=G8(e,g,n);break;case"!":f&&l(g),K=V8(e,g,n,i);break;default:f&&l(g);var P=new $S,x=m[m.length-1].currentNSMap,K=M8(e,g,P,x,a,i),Le=P.length;if(!P.closed&&B8(e,K,P.tagName,p)&&(P.closed=!0,r.nbsp||i.warning("unclosed xml attribute")),f&&Le){for(var lr=RS(f,{}),Ge=0;Ge<Le;Ge++){var Ut=P[Ge];l(Ut.offset),Ut.locator=RS(f,{})}n.locator=lr,LS(P,n,x)&&m.push(P),n.locator=f}else LS(P,n,x)&&m.push(P);ou.isHTML(P.uri)&&!P.closed?K=U8(e,K,P.tagName,a,n):K++}}catch(de){if(de instanceof hs)throw de;i.error("element parse error: "+de),K=-1}K>h?h=K:s(Math.max(g,h)+1)}}function RS(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function M8(e,t,r,n,i,o){function a(m,p,h){r.attributeNames.hasOwnProperty(m)&&o.fatalError("Attribute "+m+" redefined"),r.addValue(m,p.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,i),h)}for(var s,l,u=++t,c=ds;;){var d=e.charAt(u);if(c===ds&&d==="<")throw new Error("unexpected < in tag name: "+e.slice(t,u));switch(d){case"=":if(c===ho)s=e.slice(t,u),c=nu;else if(c===fs)c=nu;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(c===nu||c===ho)if(c===ho&&(o.warning('attribute value must after "="'),s=e.slice(t,u)),t=u+1,u=e.indexOf(d,t),u>0)l=e.slice(t,u),a(s,l,t-1),c=ms;else throw new Error("attribute value no end '"+d+"' match");else if(c==ps)l=e.slice(t,u),a(s,l,t),o.warning('attribute "'+s+'" missed start quot('+d+")!!"),t=u+1,c=ms;else throw new Error('attribute value must after "="');break;case"/":switch(c){case ds:r.setTagName(e.slice(t,u));case ms:case iu:case _d:c=_d,r.closed=!0;case ps:case ho:break;case fs:r.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return o.error("unexpected end of input"),c==ds&&r.setTagName(e.slice(t,u)),u;case">":switch(c){case ds:r.setTagName(e.slice(t,u));case ms:case iu:case _d:break;case ps:case ho:l=e.slice(t,u),l.slice(-1)==="/"&&(r.closed=!0,l=l.slice(0,-1));case fs:c===fs&&(l=s),c==ps?(o.warning('attribute "'+l+'" missed quot(")!'),a(s,l,t)):((!ou.isHTML(n[""])||!l.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+l+'" missed value!! "'+l+'" instead!!'),a(l,l,t));break;case nu:throw new Error("attribute value missed!!")}return u;case"\x80":d=" ";default:if(d<=" ")switch(c){case ds:r.setTagName(e.slice(t,u)),c=iu;break;case ho:s=e.slice(t,u),c=fs;break;case ps:var l=e.slice(t,u);o.warning('attribute "'+l+'" missed quot(")!!'),a(s,l,t);case ms:c=iu;break}else switch(c){case fs:var f=r.tagName;(!ou.isHTML(n[""])||!s.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+s+'" missed value!! "'+s+'" instead2!!'),a(s,s,t),t=u,c=ho;break;case ms:o.warning('attribute space is required"'+s+'"!!');case iu:c=ho,t=u;break;case nu:c=ps,t=u;break;case _d:throw new Error("elements closed character '/' and '>' must be connected to")}}u++}}function LS(e,t,r){for(var n=e.tagName,i=null,d=e.length;d--;){var o=e[d],a=o.qName,s=o.value,f=a.indexOf(":");if(f>0)var l=o.prefix=a.slice(0,f),u=a.slice(f+1),c=l==="xmlns"&&u;else u=a,l=null,c=a==="xmlns"&&"";o.localName=u,c!==!1&&(i==null&&(i={},r=Object.create(r)),r[c]=i[c]=s,o.uri=ou.XMLNS,t.startPrefixMapping(c,s))}for(var d=e.length;d--;){o=e[d];var l=o.prefix;l&&(l==="xml"&&(o.uri=ou.XML),l!=="xmlns"&&(o.uri=r[l||""]))}var f=n.indexOf(":");f>0?(l=e.prefix=n.slice(0,f),u=e.localName=n.slice(f+1)):(l=null,u=e.localName=n);var 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 U8(e,t,r,n,i){if(/^(?:script|textarea)$/i.test(r)){var o=e.indexOf("</"+r+">",t),a=e.substring(t+1,o);if(/[&<]/.test(a))return/^script$/i.test(r)?(i.characters(a,0,a.length),o):(a=a.replace(/&#?\w+;/g,n),i.characters(a,0,a.length),o)}return t+1}function B8(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 q8(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function V8(e,t,r,n){var i=e.charAt(t+2);switch(i){case"-":if(e.charAt(t+3)==="-"){var o=e.indexOf("-->",t+4);return o>t?(r.comment(e,t+4,o-t-4),o+3):(n.error("Unclosed comment"),-1)}else return-1;default:if(e.substr(t+3,6)=="CDATA["){var o=e.indexOf("]]>",t+9);return r.startCDATA(),r.characters(e,t+9,o-t-9),r.endCDATA(),o+3}var a=W8(e,t),s=a.length;if(s>1&&/!doctype/i.test(a[0][0])){var l=a[1][0],u=!1,c=!1;s>3&&(/^public$/i.test(a[2][0])?(u=a[3][0],c=s>4&&a[4][0]):/^system$/i.test(a[2][0])&&(c=a[3][0]));var d=a[s-1];return r.startDTD(l,u,c),r.endDTD(),d.index+d[0].length}}return-1}function G8(e,t,r){var n=e.indexOf("?>",t);if(n){var i=e.substring(t,n).match(/^<\?(\S*)\s*([\s\S]*?)$/);if(i){var o=i[0].length;return r.processingInstruction(i[1],i[2]),n+2}else return-1}return-1}function $S(){this.attributeNames={}}$S.prototype={setTagName:function(e){if(!cg.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},addValue:function(e,t,r){if(!cg.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 W8(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}dg.XMLReader=kS;dg.ParseError=hs});var GS=v(Dd=>{var z8=ss(),j8=ug(),FS=PS(),BS=xS(),H8=j8.DOMImplementation,MS=z8.NAMESPACE,K8=BS.ParseError,J8=BS.XMLReader;function qS(e){return e.replace(/\r[\n\u0085]/g,``).replace(/[\r\u0085\u2028]/g,`-`)}function VA(e){this.options=e||{locator:{}}}VA.prototype.parseFromString=function(e,t){var r=this.options,n=new jV,i=r.domBuilder||new Ul,o=r.errorHandler,a=r.locator,s=r.xmlns||{},l=/\/x?html?$/.test(t),u=l?FA.HTML_ENTITIES:FA.XML_ENTITIES;a&&i.setDocumentLocator(a),n.errorHandler=HV(o,i,a),n.domBuilder=r.domBuilder||i,l&&(s[""]=MA.HTML),s.xml=s.xml||MA.XML;var c=r.normalizeLineEndings||qA;return e&&typeof e=="string"?n.parse(c(e),s,u):n.errorHandler.error("invalid doc source"),i.doc};function HV(e,t,r){if(!e){if(t instanceof Ul)return t;e=t}var n={},i=e instanceof Function;r=r||{};function o(a){var s=e[a];!s&&i&&(s=e.length==2?function(l){e(a,l)}:e),n[a]=s&&function(l){s("[xmldom "+a+"] "+l+Nh(r))}||function(){}}return o("warning"),o("error"),o("fatalError"),n}function Ul(){this.cdata=!1}function ts(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}Ul.prototype={startDocument:function(){this.doc=new WV().createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(e,t,r,n){var i=this.doc,o=i.createElementNS(e,r||t),a=n.length;Zc(this,o),this.currentElement=o,this.locator&&ts(this.locator,o);for(var s=0;s<a;s++){var e=n.getURI(s),l=n.getValue(s),r=n.getQName(s),u=i.createAttributeNS(e,r);this.locator&&ts(n.getLocator(s),u),u.value=u.nodeValue=l,o.setAttributeNode(u)}},endElement:function(e,t,r){var n=this.currentElement,i=n.tagName;this.currentElement=n.parentNode},startPrefixMapping:function(e,t){},endPrefixMapping:function(e){},processingInstruction:function(e,t){var r=this.doc.createProcessingInstruction(e,t);this.locator&&ts(this.locator,r),Zc(this,r)},ignorableWhitespace:function(e,t,r){},characters:function(e,t,r){if(e=UA.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&&ts(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=UA.apply(this,arguments);var n=this.doc.createComment(e);this.locator&&ts(this.locator,n),Zc(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&&ts(this.locator,i),Zc(this,i),this.doc.doctype=i}},warning:function(e){console.warn("[xmldom warning] "+e,Nh(this.locator))},error:function(e){console.error("[xmldom error] "+e,Nh(this.locator))},fatalError:function(e){throw new zV(e,this.locator)}};function Nh(e){if(e)return`-@`+(e.systemId||"")+"#[line:"+e.lineNumber+",col:"+e.columnNumber+"]"}function UA(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){Ul.prototype[e]=function(){return null}});function Zc(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}ed.__DOMHandler=Ul;ed.normalizeLineEndings=qA;ed.DOMParser=VA});var rs=v(td=>{var WA=Eh();td.DOMImplementation=WA.DOMImplementation;td.XMLSerializer=WA.XMLSerializer;td.DOMParser=GA().DOMParser});var jA={};jr(jA,{CCFControlConstants:()=>zA,CCFPropertyConstants:()=>Th,CustomControlDataType:()=>F,CustomControlNames:()=>Si,DefaultControlNameKeys:()=>_h,ICCModeEnum:()=>ro,JSONParametersConstants:()=>Dh,LookUpType:()=>rd,ManifestXMLConstants:()=>qt,NumberType:()=>nd,Usage:()=>zo});var zA,Th,Dh,qt,F,_h,Si,ro,zo,rd,nd,jo=k(()=>{"use strict";zA={CCID:"CustomControlId",CCName:"DisplayName",Properties:"Properties",Mode:"ControlMode",AvailableOn:"AvailableOn",CCDescription:"description-key",ImageURL:"preview-image",TypeGroup:"type-group",DataSets:"DataSets",EntityNameKey:"EntityNameKey",NameSpace:"Name",OfTypeKey:"OfType"},Th={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"},Dh={GroupDefinition:"GroupDefinition"},qt={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"})(F||(F={}));(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"})(_h||(_h={}));(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"})(Si||(Si={}));(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"})(ro||(ro={}));(function(e){e[e.Bound=0]="Bound",e[e.Input=1]="Input",e[e.Output=2]="Output"})(zo||(zo={}));rd=[F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.LookupSimple],nd=[F.WholeNone,F.WholeDuration,F.WholeLanguage,F.WholeTimeZone,F.FP,F.Decimal]});var ns,er,Bl=k(()=>{"use strict";ns=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}},er=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 HA={};jr(HA,{AttributeDataSourceType:()=>ql,AttributeDataSourceTypeMask:()=>id,AttributePrecisionSource:()=>Vl,EntityAttributeDataSourceType:()=>Ho,EntityAttributeDateTimeBehavior:()=>Ph,EntityAttributeImeMode:()=>Oh,EntityAttributePrecisionSource:()=>Rh,EntityAttributeRequiredLevel:()=>no,EntityAttributeType:()=>x,EntityAttributeTypeFormat:()=>W,EntityMetadataLookUpBase:()=>Ni,EntityResxKeyLookUp:()=>od,SourceTypeMask:()=>Ih});var Ni,x,W,no,Ho,Ih,ql,id,Oh,Ph,Rh,Vl,od,is=k(()=>{"use strict";Bl();Ni=class{name;constructor(t){this.name=t}toString(){return this.name}getName(){return this.name}getDisplayNameResourceKey(){return od.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"})(x||(x={}));(function(e){e.Email="Email",e.Text="Text",e.TextArea="TextArea",e.Url="Url",e.TickerSymbol="TickerSymbol",e.PhoneticGuide="PhoneticGuide",e.VersionNumber="VersionNumber",e.Phone="Phone",e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale",e.DateOnly="DateOnly",e.DateAndTime="DateAndTime",e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean",e.Regarding="Regarding"})(W||(W={}));no=class extends Ni{constructor(t){super(t)}static get None(){return"None"}static get SystemRequired(){return"SystemRequired"}static get ApplicationRequired(){return"ApplicationRequired"}static get Recommended(){return"Recommended"}},Ho=class e extends Ni{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?ql.Persistent:parseInt(ql[this.name])}},Ih=class e extends Ni{constructor(t){super(t),t||(this.name=e.Undefined)}static get Undefined(){return"Undefined"}static get Simple(){return"Simple"}static get Related(){return"Related"}static get Logical(){return"Logical"}static get Calculated(){return"Calculated"}static get Rollup(){return"Rollup"}static get Invalid(){return"Invalid"}GetValue(){return parseInt(id[this.name])}};(function(e){e[e.Persistent=0]="Persistent",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup"})(ql||(ql={}));(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"})(id||(id={}));Oh=class e extends Ni{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Auto(){return"Auto"}static get Inactive(){return"Inactive"}static get Active(){return"Active"}static get Disabled(){return"Disabled"}},Ph=class e extends Ni{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get UserLocal(){return"UserLocal"}static get DateOnly(){return"DateOnly"}static get TimeZoneIndependent(){return"TimeZoneIndependent"}},Rh=class e extends Ni{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Attribute(){return"Attribute"}static get Organization(){return"Organization"}static get Currency(){return"Currency"}GetValue(){return this.name===e.None?Vl.Currency:parseInt(Vl[this.name])}};(function(e){e[e.Attribute=0]="Attribute",e[e.Organization=1]="Organization",e[e.Currency=2]="Currency"})(Vl||(Vl={}));od=class e{static resourceKeyMap=e.initResourceKeyMap();static initResourceKeyMap(){let t=new ns;return t.add(x.TwoOptions,"SystemCustomization.type.bit.label"),t.add(x.Customer,"SystemCustomization.type.customer.label"),t.add(x.CustomerType,"SystemCustomization.type.customer.label"),t.add(x.DateTime,"SystemCustomization.type.datetime.label"),t.add(x.DecimalNumber,"SystemCustomization.type.decimal.label"),t.add(x.FloatingPointNumber,"SystemCustomization.type.float.label"),t.add(x.WholeNumber,"SystemCustomization.type.int.label"),t.add(x.LookupType,"SystemCustomization.type.lookup.label"),t.add(x.Lookup,"SystemCustomization.type.lookup.label"),t.add(x.MultipleLineofText,"SystemCustomization.type.ntext.label"),t.add(x.Currency,"SystemCustomization.type.money.label"),t.add(x.Owner,"SystemCustomization.type.owner.label"),t.add(x.OwnerType,"SystemCustomization.type.owner.label"),t.add(x.PartyList,"SystemCustomization.type.partylist.label"),t.add(x.PartyListType,"SystemCustomization.type.partylist.label"),t.add(x.OptionSet,"SystemCustomization.type.picklist.label"),t.add(x.State,"SystemCustomization.type.state.label"),t.add(x.Status,"SystemCustomization.type.status.label"),t.add(x.SingleLineofText,"SystemCustomization.type.nvarchar.label"),t.add(x.UniqueIdentifier,"SystemCustomization.type.uniqueidentifier.label"),t.add(x.UniqueIdentifierType,"SystemCustomization.type.uniqueidentifiertype.label"),t.add(x.CalendarRulesType,"SystemCustomization.type.calendarrules.label"),t.add(x.VirtualType,"SystemCustomization.type.virtual.label"),t.add(x.BigInt,"SystemCustomization.type.bigint.label"),t.add(x.ManagedPropertyType,"SystemCustomization.type.managedproperty.label"),t.add(x.EntityNameType,"SystemCustomization.type.entityname.label"),t.add(x.Image,"SystemCustomization.type.image.label"),t.add(x.MultiSelectOptionSet,"SystemCustomization.type.multiselectpicklist.label"),t.add(x.PrimaryNameAttributeType,"SystemCustomization.type.primaryname.label"),t.add(x.LookupType,"SystemCustomization.type.lookuptype.label"),t.add(x.Subject,"SystemCustomization.type.subject.label"),t.add(W.Email,"SystemCustomization.String.Format.email"),t.add(W.Text,"SystemCustomization.String.Format.text"),t.add(W.TextArea,"SystemCustomization.String.Format.textarea"),t.add(W.Url,"SystemCustomization.String.Format.url"),t.add(W.TickerSymbol,"SystemCustomization.String.Format.tickersymbol"),t.add(W.PhoneticGuide,"SystemCustomization.String.Format.phoneticguide"),t.add(W.VersionNumber,"SystemCustomization.String.Format.versionnumber"),t.add(W.Phone,"SystemCustomization.String.Format.phone"),t.add(W.None,"SystemCustomization.Integer.Format."),t.add(W.Duration,"SystemCustomization.Integer.Format.duration"),t.add(W.TimeZone,"SystemCustomization.Integer.Format.timezone"),t.add(W.Language,"SystemCustomization.Integer.Format.language"),t.add(W.Locale,"SystemCustomization.Integer.Format.language"),t.add(W.DateOnly,"SystemCustomization.DateTime.Format.date"),t.add(W.DateAndTime,"SystemCustomization.DateTime.Format.datetime"),t.add(W.Regarding,"SystemCustomization.Lookup.Format.regarding"),t.add(Ho.Persistent,"SystemCustomization.String.Source.persistent"),t.add(Ho.Calculated,"SystemCustomization.String.Source.calculated"),t.add(Ho.Rollup,"SystemCustomization.String.Source.rollup"),t.add(Ho.None,"SystemCustomization.String.Source.none"),t}static getDisplayNameResourceKey(t){return e.resourceKeyMap.getValue(t)}}});var Lh=v(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.parsePcfManifest=Gn.manifestTypesForColumn=Gn.DEFAULT_TYPE_GROUPS=void 0;var KV=rs(),H=(jo(),kr(jA)),be=(is(),kr(HA));Gn.DEFAULT_TYPE_GROUPS={numbers:[H.CustomControlDataType.WholeNone,H.CustomControlDataType.FP,H.CustomControlDataType.Decimal,H.CustomControlDataType.Currency],text:[H.CustomControlDataType.SingleLineText,H.CustomControlDataType.SingleLineTextArea,H.CustomControlDataType.Multiple],lookup:[H.CustomControlDataType.LookupSimple,H.CustomControlDataType.LookupCustomer,H.CustomControlDataType.LookupOwner,H.CustomControlDataType.LookupPartyList,H.CustomControlDataType.LookupRegarding],dates:[H.CustomControlDataType.DateAndTimeDateOnly,H.CustomControlDataType.DateAndTimeDateAndTime],allFields:[H.CustomControlDataType.TwoOptions,H.CustomControlDataType.DateAndTimeDateOnly,H.CustomControlDataType.DateAndTimeDateAndTime,H.CustomControlDataType.FP,H.CustomControlDataType.Decimal,H.CustomControlDataType.WholeNone,H.CustomControlDataType.WholeDuration,H.CustomControlDataType.WholeTimeZone,H.CustomControlDataType.WholeLanguage,H.CustomControlDataType.LookupSimple,H.CustomControlDataType.LookupCustomer,H.CustomControlDataType.LookupOwner,H.CustomControlDataType.LookupPartyList,H.CustomControlDataType.LookupRegarding,H.CustomControlDataType.Multiple,H.CustomControlDataType.OptionSet,H.CustomControlDataType.SingleLineText,H.CustomControlDataType.SingleLineTextArea,H.CustomControlDataType.SingleLineEmail,H.CustomControlDataType.SingleLineURL,H.CustomControlDataType.SingleLineTickerSymbol,H.CustomControlDataType.SingleLinePhone]};var JV="Phone";function YV(e,t,r){switch(e){case be.EntityAttributeType.TwoOptions:return[H.CustomControlDataType.TwoOptions,H.CustomControlDataType.Boolean];case be.EntityAttributeType.Customer:case be.EntityAttributeType.CustomerType:return[H.CustomControlDataType.LookupCustomer];case be.EntityAttributeType.DateTime:return t===be.EntityAttributeTypeFormat.DateAndTime?[H.CustomControlDataType.DateAndTimeDateAndTime]:[H.CustomControlDataType.DateAndTimeDateOnly];case be.EntityAttributeType.DecimalNumber:return[H.CustomControlDataType.Decimal];case be.EntityAttributeType.FloatingPointNumber:return[H.CustomControlDataType.FP];case be.EntityAttributeType.File:return[H.CustomControlDataType.File];case be.EntityAttributeType.Image:return[H.CustomControlDataType.Image];case be.EntityAttributeType.WholeNumber:return t===be.EntityAttributeTypeFormat.Duration?[H.CustomControlDataType.WholeDuration]:t===be.EntityAttributeTypeFormat.Language?[H.CustomControlDataType.WholeLanguage]:t===be.EntityAttributeTypeFormat.TimeZone?[H.CustomControlDataType.WholeTimeZone]:[H.CustomControlDataType.WholeNone];case be.EntityAttributeType.LookupType:case be.EntityAttributeType.Lookup:return t===be.EntityAttributeTypeFormat.Regarding?[H.CustomControlDataType.LookupRegarding]:[H.CustomControlDataType.LookupSimple];case be.EntityAttributeType.MultipleLineofText:return[H.CustomControlDataType.Multiple];case be.EntityAttributeType.Currency:return[H.CustomControlDataType.Currency];case be.EntityAttributeType.Owner:case be.EntityAttributeType.OwnerType:return[H.CustomControlDataType.LookupOwner];case be.EntityAttributeType.PartyList:case be.EntityAttributeType.PartyListType:return[H.CustomControlDataType.LookupPartyList];case be.EntityAttributeType.Status:case be.EntityAttributeType.OptionSet:return[H.CustomControlDataType.OptionSet];case be.EntityAttributeType.SingleLineofText:switch(t){case be.EntityAttributeTypeFormat.Email:return[H.CustomControlDataType.SingleLineEmail];case be.EntityAttributeTypeFormat.Phone:return[H.CustomControlDataType.SingleLinePhone];case be.EntityAttributeTypeFormat.Text:return r===JV?[H.CustomControlDataType.SingleLinePhone]:[H.CustomControlDataType.SingleLineText];case be.EntityAttributeTypeFormat.TextArea:return[H.CustomControlDataType.SingleLineTextArea];case be.EntityAttributeTypeFormat.TickerSymbol:return[H.CustomControlDataType.SingleLineTickerSymbol];case be.EntityAttributeTypeFormat.Url:return[H.CustomControlDataType.SingleLineURL];default:return[H.CustomControlDataType.SingleLineText]}case be.EntityAttributeType.MultiSelectOptionSet:return[H.CustomControlDataType.MultiSelectOptionSet];default:return null}}Gn.manifestTypesForColumn=YV;function KA(e){let t=[],r=e.childNodes;for(let n=0;n<r.length;n+=1)r[n].nodeType===1&&t.push(r[n]);return t}function Vn(e,t){return e.hasAttribute(t)?e.getAttribute(t):null}function _i(e,...t){return KA(e).filter(r=>t.includes(r.tagName))}function QV(e){let t=new Map;for(let r of _i(e,"type-group"))t.set(String(Vn(r,"name")),_i(r,"type").map(n=>String(n.textContent)));for(let[r,n]of t)t.set(r,n.sort());return t}function XV(e){let t=e.getElementsByTagName("AvailableOn")[0];if(!t)return{web:!0,phone:!0,tablet:!0};let r=new Set(KA(t).map(n=>n.tagName));return{web:r.has("web"),phone:r.has("phone"),tablet:r.has("tablet")}}var ZV={input:"input",bound:"bound",output:"output"};function eG(e,t,r){let n=Vn(e,"usage"),i=n!==null&&ZV[n]||"input",o=Vn(e,"default-value"),a=_i(e,"value").map(p=>{let m={name:Vn(p,"name"),value:String(p.textContent),isDefault:Vn(p,"default")==="true"};return m.isDefault&&(o=m.value),m}),s=Vn(e,"of-type-group"),l=s!==null?t.get(s):void 0,u=s!==null&&Object.prototype.hasOwnProperty.call(Gn.DEFAULT_TYPE_GROUPS,s)?Gn.DEFAULT_TYPE_GROUPS[s]:void 0,c=l?[...l]:u?[...u]:[],d=Vn(e,"of-type"),f=d!==null?d:c.length>0?c[0]:null;return{name:Vn(e,"name"),usage:i,ofType:d,typeGroupName:s,ofTypeGroup:c,defaultType:f||void 0,required:Vn(e,"required")==="true",hidden:Vn(e,"hidden")==="true",defaultValue:o,enumValues:a,isPrimary:r&&i==="bound"}}function tG(e){var t;let r=[],n=m=>h=>r.push(`${m}: ${h}`),i=new KV.DOMParser({errorHandler:{warning:n("warning"),error:n("error"),fatalError:n("fatalError")}}).parseFromString(e,"text/xml"),o=(t=i?.documentElement)!==null&&t!==void 0?t:null;if(!o||r.length>0)throw new Error(`the control manifest does not parse cleanly${r.length>0?` (${r[0]})`:""}`);let a=_i(o,"control")[0];if(!a)throw new Error("the control manifest has no <control> element");let s=QV(a),l=_i(a,"data-set"),u=_i(a,"property"),c=_i(a,"groups"),d=[],f=!1;for(let m of u){let h=eG(m,s,l.length===0&&!f);f=f||h.isPrimary,d.push(h)}let p=l.length>0||(d.length>0?d[0].usage==="bound":c.some(m=>_i(m,"group").some(h=>_i(h,"data-set","property").length>0)));return{properties:d,hasDataset:l.length>0,hasGroups:c.length>0,isBound:p,availableOn:XV(a)}}Gn.parsePcfManifest=tG});var YA=v(as=>{"use strict";Object.defineProperty(as,"__esModule",{value:!0});as.readPcfColumn=as.readControlManifest=void 0;var os=ue(),rG=Lh();function kh(e,t,r){var n;let i=(n=r?.error)===null||n===void 0?void 0:n.message;return new Error(`${e}: HTTP ${t}${typeof i=="string"?` ${i}`:""}`)}async function nG(e,t){var r,n;let i="/customcontrols"+(0,os.odataQuery)([["$select","name,manifest"],["$filter",`name eq '${(0,os.odataLiteral)(t)}'`]]);try{let o=await e.get(i);if(o.status<200||o.status>=300)return{kind:"unavailable",error:kh(`reading control "${t}"`,o.status,o.body)};let a=((n=(r=o.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]).filter(l=>l!==null&&typeof l=="object");if(a.length===0)return{kind:"missing"};if(a.length>1)return{kind:"ambiguous"};let s=a[0].manifest;return typeof s!="string"?{kind:"unavailable",error:new Error(`control "${t}" has no manifest`)}:{kind:"found",value:(0,rG.parsePcfManifest)(s)}}catch(o){return{kind:"unavailable",error:o instanceof Error?o:new Error(String(o))}}}as.readControlManifest=nG;var iG=new Map([["StringType",{cast:"StringAttributeMetadata",select:"Format,FormatName"}],["MemoType",{cast:"MemoAttributeMetadata",select:"Format"}],["IntegerType",{cast:"IntegerAttributeMetadata",select:"Format"}],["DateTimeType",{cast:"DateTimeAttributeMetadata",select:"Format"}],["LookupType",{cast:"LookupAttributeMetadata",select:"Format"}]]);function JA(e){let t=e?.Value;return typeof t=="string"?t:void 0}async function oG(e,t,r,n){var i,o;let a=`/EntityDefinitions(LogicalName='${(0,os.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,os.odataPathLiteral)(r)}')`,s=n?.requireCreateEligibility===!0;try{let l=await e.get(a+(0,os.odataQuery)([["$select",`LogicalName,AttributeType,AttributeTypeName,IsValidForForm,IsPrimaryId${s?",IsValidForCreate":""}`]]));if(l.status===404)return{kind:"missing"};if(l.status<200||l.status>=300)return{kind:"unavailable",error:kh(`reading column "${r}"`,l.status,l.body)};let u=(i=l.body)!==null&&i!==void 0?i:{},c=JA(u.AttributeTypeName);if(!c)return{kind:"unavailable",error:new Error(`column "${r}" has no AttributeTypeName`)};if(s&&typeof u.IsValidForCreate!="boolean")return{kind:"unavailable",error:new Error(`column "${r}" has no IsValidForCreate`)};let d={logicalName:typeof u.LogicalName=="string"?u.LogicalName:r,attributeTypeName:c,isValidForForm:u.IsValidForForm===!0,isPrimaryId:u.IsPrimaryId===!0,...s?{isValidForCreate:u.IsValidForCreate}:{}},f=iG.get(c);if(f){let p=await e.get(`${a}/Microsoft.Dynamics.CRM.${f.cast}`+(0,os.odataQuery)([["$select",f.select]]));if(p.status<200||p.status>=300)return{kind:"unavailable",error:kh(`reading the format of column "${r}"`,p.status,p.body)};let m=(o=p.body)!==null&&o!==void 0?o:{};typeof m.Format=="string"&&(d.format=m.Format);let h=JA(m.FormatName);h&&(d.formatName=h)}return{kind:"found",value:d}}catch(l){return{kind:"unavailable",error:l instanceof Error?l:new Error(String(l))}}}as.readPcfColumn=oG});var Ko=v(ad=>{"use strict";Object.defineProperty(ad,"__esModule",{value:!0});ad.DEFAULT_LCID=void 0;ad.DEFAULT_LCID=1033});var lt=v(Wn=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.assignMissingIds=Wn.pointerTouchesValueMap=Wn.isValueMapKey=Wn.newId=void 0;var aG=Fa();function QA(){return globalThis.crypto.randomUUID().toLowerCase()}Wn.newId=QA;function sG(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var $h=new Set(["parameters","bag","expression","rawExpression","lookupValue","stepLabels","genPage","inputData","customControl"]);function lG(e){return $h.has(e)}Wn.isValueMapKey=lG;function uG(e){return aG.JsonPointer.parse(e).some(t=>$h.has(t))}Wn.pointerTouchesValueMap=uG;function cG(e){return xh(e),e}Wn.assignMissingIds=cG;function xh(e){if(Array.isArray(e)){e.forEach(t=>xh(t));return}if(sG(e)){(typeof e.id!="string"||e.id.length===0)&&(e.id=QA());for(let t of Object.keys(e))t==="id"||$h.has(t)||xh(e[t])}}});var Wl=v(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});vr.sendChangeSet=vr.partResponse=vr.postChangeSet=vr.parseChangeSetParts=vr.parseChangeSetStatuses=vr.renderChangeSet=void 0;var io=Q(),Fh=ye(),XA=lt(),Gl=ue();function Mh(e,t){let r=`batch_${(0,XA.newId)()}`,n=`changeset_${(0,XA.newId)()}`,i=t.map((s,l)=>String(l+1)),o=t.map((s,l)=>{var u,c;if(s.rawBody!==void 0&&s.contentType===void 0)throw new io.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a raw body but no Content-Type`);let d=(u=s.rawBody)!==null&&u!==void 0?u:s.body===void 0?void 0:JSON.stringify(s.body);if(d!==void 0&&(d.includes(`--${n}`)||d.includes(`--${r}`)))throw new io.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a body containing the batch boundary`);(0,Gl.assertNoControlChars)(s.path,"batch operation path"),s.etag&&(0,Gl.assertNoControlChars)(s.etag,"batch operation etag");let f=Object.entries((c=s.headers)!==null&&c!==void 0?c:{});for(let[p,m]of f)if((0,Gl.assertNoControlChars)(p,"batch operation header name"),(0,Gl.assertNoControlChars)(m,"batch operation header value"),!/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(p))throw new io.InvalidArgumentError(`batch operation header name '${p}' is not a valid HTTP token`);return s.contentType!==void 0&&(0,Gl.assertNoControlChars)(s.contentType,"batch operation content type"),[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${i[l]}`,"",`${s.method} ${e.apiUrl(s.path)} HTTP/1.1`,...d===void 0?[]:[`Content-Type: ${s.rawBody!==void 0?s.contentType:"application/json;type=entry"}`],...e.solutionName?[`MSCRM.SolutionUniqueName: ${e.solutionName}`]:[],...s.etag?[`If-Match: ${s.etag}`]:[],...f.map(([p,m])=>`${p}: ${m}`),"",...d===void 0?[]:[d]].join(`\r+`)}function VS(e){this.options=e||{locator:{}}}VS.prototype.parseFromString=function(e,t){var r=this.options,n=new J8,i=r.domBuilder||new au,o=r.errorHandler,a=r.locator,s=r.xmlns||{},l=/\/x?html?$/.test(t),u=l?FS.HTML_ENTITIES:FS.XML_ENTITIES;a&&i.setDocumentLocator(a),n.errorHandler=Y8(o,i,a),n.domBuilder=r.domBuilder||i,l&&(s[""]=MS.HTML),s.xml=s.xml||MS.XML;var c=r.normalizeLineEndings||qS;return e&&typeof e=="string"?n.parse(c(e),s,u):n.errorHandler.error("invalid doc source"),i.doc};function Y8(e,t,r){if(!e){if(t instanceof au)return t;e=t}var n={},i=e instanceof Function;r=r||{};function o(a){var s=e[a];!s&&i&&(s=e.length==2?function(l){e(a,l)}:e),n[a]=s&&function(l){s("[xmldom "+a+"] "+l+fg(r))}||function(){}}return o("warning"),o("error"),o("fatalError"),n}function au(){this.cdata=!1}function gs(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}au.prototype={startDocument:function(){this.doc=new H8().createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(e,t,r,n){var i=this.doc,o=i.createElementNS(e,r||t),a=n.length;Td(this,o),this.currentElement=o,this.locator&&gs(this.locator,o);for(var s=0;s<a;s++){var e=n.getURI(s),l=n.getValue(s),r=n.getQName(s),u=i.createAttributeNS(e,r);this.locator&&gs(n.getLocator(s),u),u.value=u.nodeValue=l,o.setAttributeNode(u)}},endElement:function(e,t,r){var n=this.currentElement,i=n.tagName;this.currentElement=n.parentNode},startPrefixMapping:function(e,t){},endPrefixMapping:function(e){},processingInstruction:function(e,t){var r=this.doc.createProcessingInstruction(e,t);this.locator&&gs(this.locator,r),Td(this,r)},ignorableWhitespace:function(e,t,r){},characters:function(e,t,r){if(e=US.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&&gs(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=US.apply(this,arguments);var n=this.doc.createComment(e);this.locator&&gs(this.locator,n),Td(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&&gs(this.locator,i),Td(this,i),this.doc.doctype=i}},warning:function(e){console.warn("[xmldom warning] "+e,fg(this.locator))},error:function(e){console.error("[xmldom error] "+e,fg(this.locator))},fatalError:function(e){throw new K8(e,this.locator)}};function fg(e){if(e)return`+@`+(e.systemId||"")+"#[line:"+e.lineNumber+",col:"+e.columnNumber+"]"}function US(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){au.prototype[e]=function(){return null}});function Td(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}Dd.__DOMHandler=au;Dd.normalizeLineEndings=qS;Dd.DOMParser=VS});var ys=v(Id=>{var WS=ug();Id.DOMImplementation=WS.DOMImplementation;Id.XMLSerializer=WS.XMLSerializer;Id.DOMParser=GS().DOMParser});var jS={};nn(jS,{CCFControlConstants:()=>zS,CCFPropertyConstants:()=>mg,CustomControlDataType:()=>F,CustomControlNames:()=>Mi,DefaultControlNameKeys:()=>pg,ICCModeEnum:()=>go,JSONParametersConstants:()=>hg,LookUpType:()=>Od,ManifestXMLConstants:()=>Xt,NumberType:()=>Pd,Usage:()=>ia});var zS,mg,hg,Xt,F,pg,Mi,go,ia,Od,Pd,oa=k(()=>{"use strict";zS={CCID:"CustomControlId",CCName:"DisplayName",Properties:"Properties",Mode:"ControlMode",AvailableOn:"AvailableOn",CCDescription:"description-key",ImageURL:"preview-image",TypeGroup:"type-group",DataSets:"DataSets",EntityNameKey:"EntityNameKey",NameSpace:"Name",OfTypeKey:"OfType"},mg={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"},hg={GroupDefinition:"GroupDefinition"},Xt={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"})(F||(F={}));(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"})(pg||(pg={}));(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"})(Mi||(Mi={}));(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"})(go||(go={}));(function(e){e[e.Bound=0]="Bound",e[e.Input=1]="Input",e[e.Output=2]="Output"})(ia||(ia={}));Od=[F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.LookupSimple],Pd=[F.WholeNone,F.WholeDuration,F.WholeLanguage,F.WholeTimeZone,F.FP,F.Decimal]});var bs,dr,su=k(()=>{"use strict";bs=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}},dr=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 HS={};nn(HS,{AttributeDataSourceType:()=>lu,AttributeDataSourceTypeMask:()=>Rd,AttributePrecisionSource:()=>uu,EntityAttributeDataSourceType:()=>aa,EntityAttributeDateTimeBehavior:()=>bg,EntityAttributeImeMode:()=>yg,EntityAttributePrecisionSource:()=>vg,EntityAttributeRequiredLevel:()=>yo,EntityAttributeType:()=>$,EntityAttributeTypeFormat:()=>W,EntityMetadataLookUpBase:()=>Ui,EntityResxKeyLookUp:()=>Ld,SourceTypeMask:()=>gg});var Ui,$,W,yo,aa,gg,lu,Rd,yg,bg,vg,uu,Ld,vs=k(()=>{"use strict";su();Ui=class{name;constructor(t){this.name=t}toString(){return this.name}getName(){return this.name}getDisplayNameResourceKey(){return Ld.getDisplayNameResourceKey(this.name)}};(function(e){e.BigInt="BigIntType",e.CalendarRulesType="CalendarRulesType",e.Currency="MoneyType",e.Customer="Customer",e.CustomerType="CustomerType",e.DateTime="DateTimeType",e.DecimalNumber="DecimalType",e.EntityNameType="EntityNameType",e.FloatingPointNumber="DoubleType",e.Image="ImageType",e.File="FileType",e.Lookup="Lookup",e.LookupType="LookupType",e.ManagedPropertyType="ManagedPropertyType",e.MultipleLineofText="MemoType",e.MultiSelectOptionSet="MultiSelectPicklistType",e.OptionSet="PicklistType",e.Owner="Owner",e.OwnerType="OwnerType",e.PartyList="PartyList",e.PartyListType="PartyListType",e.PrimaryNameAttributeType="String",e.SingleLineofText="StringType",e.State="StateType",e.Status="StatusType",e.Subject="Subject",e.TimeStamp="TimeStampType",e.TwoOptions="BooleanType",e.UniqueIdentifier="Uniqueidentifier",e.UniqueIdentifierType="UniqueidentifierType",e.VirtualType="VirtualType",e.WholeNumber="IntegerType"})($||($={}));(function(e){e.Email="Email",e.Text="Text",e.TextArea="TextArea",e.Url="Url",e.TickerSymbol="TickerSymbol",e.PhoneticGuide="PhoneticGuide",e.VersionNumber="VersionNumber",e.Phone="Phone",e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale",e.DateOnly="DateOnly",e.DateAndTime="DateAndTime",e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean",e.Regarding="Regarding"})(W||(W={}));yo=class extends Ui{constructor(t){super(t)}static get None(){return"None"}static get SystemRequired(){return"SystemRequired"}static get ApplicationRequired(){return"ApplicationRequired"}static get Recommended(){return"Recommended"}},aa=class e extends Ui{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Persistent(){return"Persistent"}static get Calculated(){return"Calculated"}static get Rollup(){return"Rollup"}GetValue(){return this.name===e.None?lu.Persistent:parseInt(lu[this.name])}},gg=class e extends Ui{constructor(t){super(t),t||(this.name=e.Undefined)}static get Undefined(){return"Undefined"}static get Simple(){return"Simple"}static get Related(){return"Related"}static get Logical(){return"Logical"}static get Calculated(){return"Calculated"}static get Rollup(){return"Rollup"}static get Invalid(){return"Invalid"}GetValue(){return parseInt(Rd[this.name])}};(function(e){e[e.Persistent=0]="Persistent",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup"})(lu||(lu={}));(function(e){e[e.Undefined=0]="Undefined",e[e.Simple=1]="Simple",e[e.Related=2]="Related",e[e.Logical=4]="Logical",e[e.Calculated=8]="Calculated",e[e.Rollup=16]="Rollup",e[e.Invalid=32]="Invalid"})(Rd||(Rd={}));yg=class e extends Ui{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Auto(){return"Auto"}static get Inactive(){return"Inactive"}static get Active(){return"Active"}static get Disabled(){return"Disabled"}},bg=class e extends Ui{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get UserLocal(){return"UserLocal"}static get DateOnly(){return"DateOnly"}static get TimeZoneIndependent(){return"TimeZoneIndependent"}},vg=class e extends Ui{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Attribute(){return"Attribute"}static get Organization(){return"Organization"}static get Currency(){return"Currency"}GetValue(){return this.name===e.None?uu.Currency:parseInt(uu[this.name])}};(function(e){e[e.Attribute=0]="Attribute",e[e.Organization=1]="Organization",e[e.Currency=2]="Currency"})(uu||(uu={}));Ld=class e{static resourceKeyMap=e.initResourceKeyMap();static initResourceKeyMap(){let t=new bs;return t.add($.TwoOptions,"SystemCustomization.type.bit.label"),t.add($.Customer,"SystemCustomization.type.customer.label"),t.add($.CustomerType,"SystemCustomization.type.customer.label"),t.add($.DateTime,"SystemCustomization.type.datetime.label"),t.add($.DecimalNumber,"SystemCustomization.type.decimal.label"),t.add($.FloatingPointNumber,"SystemCustomization.type.float.label"),t.add($.WholeNumber,"SystemCustomization.type.int.label"),t.add($.LookupType,"SystemCustomization.type.lookup.label"),t.add($.Lookup,"SystemCustomization.type.lookup.label"),t.add($.MultipleLineofText,"SystemCustomization.type.ntext.label"),t.add($.Currency,"SystemCustomization.type.money.label"),t.add($.Owner,"SystemCustomization.type.owner.label"),t.add($.OwnerType,"SystemCustomization.type.owner.label"),t.add($.PartyList,"SystemCustomization.type.partylist.label"),t.add($.PartyListType,"SystemCustomization.type.partylist.label"),t.add($.OptionSet,"SystemCustomization.type.picklist.label"),t.add($.State,"SystemCustomization.type.state.label"),t.add($.Status,"SystemCustomization.type.status.label"),t.add($.SingleLineofText,"SystemCustomization.type.nvarchar.label"),t.add($.UniqueIdentifier,"SystemCustomization.type.uniqueidentifier.label"),t.add($.UniqueIdentifierType,"SystemCustomization.type.uniqueidentifiertype.label"),t.add($.CalendarRulesType,"SystemCustomization.type.calendarrules.label"),t.add($.VirtualType,"SystemCustomization.type.virtual.label"),t.add($.BigInt,"SystemCustomization.type.bigint.label"),t.add($.ManagedPropertyType,"SystemCustomization.type.managedproperty.label"),t.add($.EntityNameType,"SystemCustomization.type.entityname.label"),t.add($.Image,"SystemCustomization.type.image.label"),t.add($.MultiSelectOptionSet,"SystemCustomization.type.multiselectpicklist.label"),t.add($.PrimaryNameAttributeType,"SystemCustomization.type.primaryname.label"),t.add($.LookupType,"SystemCustomization.type.lookuptype.label"),t.add($.Subject,"SystemCustomization.type.subject.label"),t.add(W.Email,"SystemCustomization.String.Format.email"),t.add(W.Text,"SystemCustomization.String.Format.text"),t.add(W.TextArea,"SystemCustomization.String.Format.textarea"),t.add(W.Url,"SystemCustomization.String.Format.url"),t.add(W.TickerSymbol,"SystemCustomization.String.Format.tickersymbol"),t.add(W.PhoneticGuide,"SystemCustomization.String.Format.phoneticguide"),t.add(W.VersionNumber,"SystemCustomization.String.Format.versionnumber"),t.add(W.Phone,"SystemCustomization.String.Format.phone"),t.add(W.None,"SystemCustomization.Integer.Format."),t.add(W.Duration,"SystemCustomization.Integer.Format.duration"),t.add(W.TimeZone,"SystemCustomization.Integer.Format.timezone"),t.add(W.Language,"SystemCustomization.Integer.Format.language"),t.add(W.Locale,"SystemCustomization.Integer.Format.language"),t.add(W.DateOnly,"SystemCustomization.DateTime.Format.date"),t.add(W.DateAndTime,"SystemCustomization.DateTime.Format.datetime"),t.add(W.Regarding,"SystemCustomization.Lookup.Format.regarding"),t.add(aa.Persistent,"SystemCustomization.String.Source.persistent"),t.add(aa.Calculated,"SystemCustomization.String.Source.calculated"),t.add(aa.Rollup,"SystemCustomization.String.Source.rollup"),t.add(aa.None,"SystemCustomization.String.Source.none"),t}static getDisplayNameResourceKey(t){return e.resourceKeyMap.getValue(t)}}});var cu=v(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.parsePcfManifest=ut.parseControlElement=ut.parseManifestRoot=ut.firstLevel=ut.attr=ut.elementChildren=ut.manifestTypesForColumn=ut.DEFAULT_TYPE_GROUPS=void 0;var Q8=ys(),H=(oa(),zr(jS)),ve=(vs(),zr(HS));ut.DEFAULT_TYPE_GROUPS={numbers:[H.CustomControlDataType.WholeNone,H.CustomControlDataType.FP,H.CustomControlDataType.Decimal,H.CustomControlDataType.Currency],text:[H.CustomControlDataType.SingleLineText,H.CustomControlDataType.SingleLineTextArea,H.CustomControlDataType.Multiple],lookup:[H.CustomControlDataType.LookupSimple,H.CustomControlDataType.LookupCustomer,H.CustomControlDataType.LookupOwner,H.CustomControlDataType.LookupPartyList,H.CustomControlDataType.LookupRegarding],dates:[H.CustomControlDataType.DateAndTimeDateOnly,H.CustomControlDataType.DateAndTimeDateAndTime],allFields:[H.CustomControlDataType.TwoOptions,H.CustomControlDataType.DateAndTimeDateOnly,H.CustomControlDataType.DateAndTimeDateAndTime,H.CustomControlDataType.FP,H.CustomControlDataType.Decimal,H.CustomControlDataType.WholeNone,H.CustomControlDataType.WholeDuration,H.CustomControlDataType.WholeTimeZone,H.CustomControlDataType.WholeLanguage,H.CustomControlDataType.LookupSimple,H.CustomControlDataType.LookupCustomer,H.CustomControlDataType.LookupOwner,H.CustomControlDataType.LookupPartyList,H.CustomControlDataType.LookupRegarding,H.CustomControlDataType.Multiple,H.CustomControlDataType.OptionSet,H.CustomControlDataType.SingleLineText,H.CustomControlDataType.SingleLineTextArea,H.CustomControlDataType.SingleLineEmail,H.CustomControlDataType.SingleLineURL,H.CustomControlDataType.SingleLineTickerSymbol,H.CustomControlDataType.SingleLinePhone]};var X8="Phone";function Z8(e,t,r){switch(e){case ve.EntityAttributeType.TwoOptions:return[H.CustomControlDataType.TwoOptions,H.CustomControlDataType.Boolean];case ve.EntityAttributeType.Customer:case ve.EntityAttributeType.CustomerType:return[H.CustomControlDataType.LookupCustomer];case ve.EntityAttributeType.DateTime:return t===ve.EntityAttributeTypeFormat.DateAndTime?[H.CustomControlDataType.DateAndTimeDateAndTime]:[H.CustomControlDataType.DateAndTimeDateOnly];case ve.EntityAttributeType.DecimalNumber:return[H.CustomControlDataType.Decimal];case ve.EntityAttributeType.FloatingPointNumber:return[H.CustomControlDataType.FP];case ve.EntityAttributeType.File:return[H.CustomControlDataType.File];case ve.EntityAttributeType.Image:return[H.CustomControlDataType.Image];case ve.EntityAttributeType.WholeNumber:return t===ve.EntityAttributeTypeFormat.Duration?[H.CustomControlDataType.WholeDuration]:t===ve.EntityAttributeTypeFormat.Language?[H.CustomControlDataType.WholeLanguage]:t===ve.EntityAttributeTypeFormat.TimeZone?[H.CustomControlDataType.WholeTimeZone]:[H.CustomControlDataType.WholeNone];case ve.EntityAttributeType.LookupType:case ve.EntityAttributeType.Lookup:return t===ve.EntityAttributeTypeFormat.Regarding?[H.CustomControlDataType.LookupRegarding]:[H.CustomControlDataType.LookupSimple];case ve.EntityAttributeType.MultipleLineofText:return[H.CustomControlDataType.Multiple];case ve.EntityAttributeType.Currency:return[H.CustomControlDataType.Currency];case ve.EntityAttributeType.Owner:case ve.EntityAttributeType.OwnerType:return[H.CustomControlDataType.LookupOwner];case ve.EntityAttributeType.PartyList:case ve.EntityAttributeType.PartyListType:return[H.CustomControlDataType.LookupPartyList];case ve.EntityAttributeType.Status:case ve.EntityAttributeType.OptionSet:return[H.CustomControlDataType.OptionSet];case ve.EntityAttributeType.SingleLineofText:switch(t){case ve.EntityAttributeTypeFormat.Email:return[H.CustomControlDataType.SingleLineEmail];case ve.EntityAttributeTypeFormat.Phone:return[H.CustomControlDataType.SingleLinePhone];case ve.EntityAttributeTypeFormat.Text:return r===X8?[H.CustomControlDataType.SingleLinePhone]:[H.CustomControlDataType.SingleLineText];case ve.EntityAttributeTypeFormat.TextArea:return[H.CustomControlDataType.SingleLineTextArea];case ve.EntityAttributeTypeFormat.TickerSymbol:return[H.CustomControlDataType.SingleLineTickerSymbol];case ve.EntityAttributeTypeFormat.Url:return[H.CustomControlDataType.SingleLineURL];default:return[H.CustomControlDataType.SingleLineText]}case ve.EntityAttributeType.MultiSelectOptionSet:return[H.CustomControlDataType.MultiSelectOptionSet];default:return null}}ut.manifestTypesForColumn=Z8;function wg(e){let t=[],r=e.childNodes;for(let n=0;n<r.length;n+=1)r[n].nodeType===1&&t.push(r[n]);return t}ut.elementChildren=wg;function On(e,t){return e.hasAttribute(t)?e.getAttribute(t):null}ut.attr=On;function ei(e,...t){return wg(e).filter(r=>t.includes(r.tagName))}ut.firstLevel=ei;function e9(e){let t=new Map;for(let r of ei(e,"type-group"))t.set(String(On(r,"name")),ei(r,"type").map(n=>String(n.textContent)));for(let[r,n]of t)t.set(r,n.sort());return t}function t9(e){let t=e.getElementsByTagName("AvailableOn")[0];if(!t)return{web:!0,phone:!0,tablet:!0};let r=new Set(wg(t).map(n=>n.tagName));return{web:r.has("web"),phone:r.has("phone"),tablet:r.has("tablet")}}var r9={input:"input",bound:"bound",output:"output"};function n9(e,t,r){let n=On(e,"usage"),i=n!==null&&r9[n]||"input",o=On(e,"default-value"),a=ei(e,"value").map(m=>{let p={name:On(m,"name"),value:String(m.textContent),isDefault:On(m,"default")==="true"};return p.isDefault&&(o=p.value),p}),s=On(e,"of-type-group"),l=s!==null?t.get(s):void 0,u=s!==null&&Object.prototype.hasOwnProperty.call(ut.DEFAULT_TYPE_GROUPS,s)?ut.DEFAULT_TYPE_GROUPS[s]:void 0,c=l?[...l]:u?[...u]:[],d=On(e,"of-type"),f=d!==null?d:c.length>0?c[0]:null;return{name:On(e,"name"),usage:i,ofType:d,typeGroupName:s,ofTypeGroup:c,defaultType:f||void 0,required:On(e,"required")==="true",hidden:On(e,"hidden")==="true",defaultValue:o,enumValues:a,isPrimary:r&&i==="bound"}}function KS(e){var t;let r=[],n=a=>s=>r.push(`${a}: ${s}`),i=new Q8.DOMParser({errorHandler:{warning:n("warning"),error:n("error"),fatalError:n("fatalError")}}).parseFromString(e,"text/xml"),o=(t=i?.documentElement)!==null&&t!==void 0?t:null;if(!o||r.length>0)throw new Error(`the control manifest does not parse cleanly${r.length>0?` (${r[0]})`:""}`);return o}ut.parseManifestRoot=KS;function JS(e){let t=ei(KS(e),"control")[0];if(!t)throw new Error("the control manifest has no <control> element");return t}ut.parseControlElement=JS;function i9(e){let t=JS(e),r=e9(t),n=ei(t,"data-set"),i=ei(t,"property"),o=ei(t,"groups"),a=[],s=!1;for(let u of i){let c=n9(u,r,n.length===0&&!s);s=s||c.isPrimary,a.push(c)}let l=n.length>0||(a.length>0?a[0].usage==="bound":o.some(u=>ei(u,"group").some(c=>ei(c,"data-set","property").length>0)));return{properties:a,hasDataset:n.length>0,hasGroups:o.length>0,isBound:l,availableOn:t9(t)}}ut.parsePcfManifest=i9});var QS=v(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});Cs.readPcfColumn=Cs.readControlManifest=void 0;var ws=oe(),o9=cu();function Cg(e,t,r){var n;let i=(n=r?.error)===null||n===void 0?void 0:n.message;return new Error(`${e}: HTTP ${t}${typeof i=="string"?` ${i}`:""}`)}async function a9(e,t){var r;let n="/customcontrols"+(0,ws.odataQuery)([["$select","name,manifest"],["$filter",`name eq '${(0,ws.odataLiteral)(t)}'`]]);try{let i=await e.get(n);if(i.status<200||i.status>=300)return{kind:"unavailable",error:Cg(`reading control "${t}"`,i.status,i.body)};let o=(r=i.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(o)||o.some(l=>l===null||typeof l!="object"))return{kind:"unavailable",error:new Error(`reading control "${t}": the answer is unreadable \u2014 expected an OData 'value' array of rows`)};let a=o;if(a.length===0)return{kind:"missing"};if(a.length>1)return{kind:"ambiguous"};let s=a[0].manifest;return typeof s!="string"?{kind:"unavailable",error:new Error(`control "${t}" has no manifest`)}:{kind:"found",value:(0,o9.parsePcfManifest)(s)}}catch(i){return{kind:"unavailable",error:i instanceof Error?i:new Error(String(i))}}}Cs.readControlManifest=a9;var s9=new Map([["StringType",{cast:"StringAttributeMetadata",select:"Format,FormatName"}],["MemoType",{cast:"MemoAttributeMetadata",select:"Format"}],["IntegerType",{cast:"IntegerAttributeMetadata",select:"Format"}],["DateTimeType",{cast:"DateTimeAttributeMetadata",select:"Format"}],["LookupType",{cast:"LookupAttributeMetadata",select:"Format"}]]);function YS(e){let t=e?.Value;return typeof t=="string"?t:void 0}async function l9(e,t,r,n){var i;let o=`/EntityDefinitions(LogicalName='${(0,ws.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,ws.odataPathLiteral)(r)}')`,a=n?.requireCreateEligibility===!0;try{let s=await e.get(o+(0,ws.odataQuery)([["$select",`LogicalName,AttributeType,AttributeTypeName,IsValidForForm,IsPrimaryId${a?",IsValidForCreate":""}`]]));if(s.status===404)return{kind:"missing"};if(s.status<200||s.status>=300)return{kind:"unavailable",error:Cg(`reading column "${r}"`,s.status,s.body)};let l=(i=s.body)!==null&&i!==void 0?i:{},u=YS(l.AttributeTypeName);if(!u)return{kind:"unavailable",error:new Error(`column "${r}" has no AttributeTypeName`)};if(a&&typeof l.IsValidForCreate!="boolean")return{kind:"unavailable",error:new Error(`column "${r}" has no IsValidForCreate`)};let c={logicalName:typeof l.LogicalName=="string"?l.LogicalName:r,attributeTypeName:u,isValidForForm:l.IsValidForForm===!0,isPrimaryId:l.IsPrimaryId===!0,...a?{isValidForCreate:l.IsValidForCreate}:{}},d=s9.get(u);if(d){let f=await e.get(`${o}/Microsoft.Dynamics.CRM.${d.cast}`+(0,ws.odataQuery)([["$select",d.select]]));if(f.status<200||f.status>=300)return{kind:"unavailable",error:Cg(`reading the format of column "${r}"`,f.status,f.body)};let m=f.body;if(m===null||typeof m!="object"||m.Format!==null&&typeof m.Format!="string")return{kind:"unavailable",error:new Error(`reading the format of column "${r}": the answer is unreadable \u2014 expected its Format (a string or null)`)};typeof m.Format=="string"&&(c.format=m.Format);let p=YS(m.FormatName);p&&(c.formatName=p)}return{kind:"found",value:c}}catch(s){return{kind:"unavailable",error:s instanceof Error?s:new Error(String(s))}}}Cs.readPcfColumn=l9});var sa=v(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});kd.DEFAULT_LCID=void 0;kd.DEFAULT_LCID=1033});var ct=v(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});ti.assignMissingIds=ti.pointerTouchesValueMap=ti.isValueMapKey=ti.newId=void 0;var u9=Xa();function XS(){return globalThis.crypto.randomUUID().toLowerCase()}ti.newId=XS;function c9(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Ag=new Set(["parameters","bag","expression","rawExpression","lookupValue","stepLabels","genPage","inputData","customControl"]);function d9(e){return Ag.has(e)}ti.isValueMapKey=d9;function f9(e){return u9.JsonPointer.parse(e).some(t=>Ag.has(t))}ti.pointerTouchesValueMap=f9;function p9(e){return Eg(e),e}ti.assignMissingIds=p9;function Eg(e){if(Array.isArray(e)){e.forEach(t=>Eg(t));return}if(c9(e)){(typeof e.id!="string"||e.id.length===0)&&(e.id=XS());for(let t of Object.keys(e))t==="id"||Ag.has(t)||Eg(e[t])}}});var Es=v(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.sendChangeSet=Or.partResponse=Or.postChangeSet=Or.parseChangeSetParts=Or.parseChangeSetStatuses=Or.renderChangeSet=void 0;var bo=Q(),Sg=fe(),ZS=ct(),du=oe();function Ng(e,t){let r=`batch_${(0,ZS.newId)()}`,n=`changeset_${(0,ZS.newId)()}`,i=t.map((s,l)=>String(l+1)),o=t.map((s,l)=>{var u,c;if(s.rawBody!==void 0&&s.contentType===void 0)throw new bo.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a raw body but no Content-Type`);let d=(u=s.rawBody)!==null&&u!==void 0?u:s.body===void 0?void 0:JSON.stringify(s.body);if(d!==void 0&&(d.includes(`--${n}`)||d.includes(`--${r}`)))throw new bo.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a body containing the batch boundary`);(0,du.assertNoControlChars)(s.path,"batch operation path"),s.etag&&(0,du.assertNoControlChars)(s.etag,"batch operation etag");let f=Object.entries((c=s.headers)!==null&&c!==void 0?c:{});for(let[m,p]of f)if((0,du.assertNoControlChars)(m,"batch operation header name"),(0,du.assertNoControlChars)(p,"batch operation header value"),!/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(m))throw new bo.InvalidArgumentError(`batch operation header name '${m}' is not a valid HTTP token`);return s.contentType!==void 0&&(0,du.assertNoControlChars)(s.contentType,"batch operation content type"),[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${i[l]}`,"",`${s.method} ${e.apiUrl(s.path)} HTTP/1.1`,...d===void 0?[]:[`Content-Type: ${s.rawBody!==void 0?s.contentType:"application/json;type=entry"}`],...e.solutionName?[`MSCRM.SolutionUniqueName: ${e.solutionName}`]:[],...s.etag?[`If-Match: ${s.etag}`]:[],...f.map(([m,p])=>`${m}: ${p}`),"",...d===void 0?[]:[d]].join(`\r`)});return{body:[`--${r}`,`Content-Type: multipart/mixed;boundary=${n}`,"",...o,`--${n}--`,`--${r}--`,""].join(`\r-`),batchId:r,contentIds:i}}vr.renderChangeSet=Mh;function ZA(e,t){var r;return(r=Uh(e,t))===null||r===void 0?void 0:r.map(n=>n.status)}vr.parseChangeSetStatuses=ZA;function Uh(e,t){var r,n,i,o;if(typeof e!="string"||e.length===0)return;let a=(r=/^--(\S+)\r?\n/.exec(e))===null||r===void 0?void 0:r[1];if(a===void 0||!e.trimEnd().endsWith(`--${a}--`))return;let s=(n=/Content-Type:\s*multipart\/mixed;\s*boundary=(\S+)/i.exec(e))===null||n===void 0?void 0:n[1];if(s===void 0||s===a)return;let l=e.split(`--${s}`);if(l.length<2||!/^--(\r?\n|$)/.test(l[l.length-1]))return;let u=new Set(t),c=[],d=new Set;for(let f of l.slice(1)){if(f.startsWith("--"))break;let p=f.indexOf(`\r+`),batchId:r,contentIds:i}}Or.renderChangeSet=Ng;function eN(e,t){var r;return(r=_g(e,t))===null||r===void 0?void 0:r.map(n=>n.status)}Or.parseChangeSetStatuses=eN;function _g(e,t){var r,n,i,o;if(typeof e!="string"||e.length===0)return;let a=(r=/^--(\S+)\r?\n/.exec(e))===null||r===void 0?void 0:r[1];if(a===void 0||!e.trimEnd().endsWith(`--${a}--`))return;let s=(n=/Content-Type:\s*multipart\/mixed;\s*boundary=(\S+)/i.exec(e))===null||n===void 0?void 0:n[1];if(s===void 0||s===a)return;let l=e.split(`--${s}`);if(l.length<2||!/^--(\r?\n|$)/.test(l[l.length-1]))return;let u=new Set(t),c=[],d=new Set;for(let f of l.slice(1)){if(f.startsWith("--"))break;let m=f.indexOf(`\r\r-`);if(p===-1)return;let m=f.slice(0,p),h=f.slice(p+4);if(!/^Content-Type:\s*application\/http\b/im.test(m))return;let g=/^HTTP\/1\.[01] (\d{3})\b/.exec(h);if(!g||((i=h.match(/^HTTP\/1\.[01] \d{3}\b/gm))!==null&&i!==void 0?i:[]).length!==1)return;let b=(o=/^Content-ID:\s*(\S+)/im.exec(m))===null||o===void 0?void 0:o[1];if(b===void 0||d.has(b)||!u.has(b))return;d.add(b),c.push({status:Number(g[1]),text:h,contentId:b})}return c.length===0?void 0:c}vr.parseChangeSetParts=Uh;async function dG(e,t,r){if(t.length===0)return;let{body:n,batchId:i,contentIds:o}=Mh(e,t),a=await e.postBatch(n,i),s=e.apiUrl("/$batch");if((0,Fh.ensureSuccess)(a,s),typeof a.body!="string"||a.body.length===0)throw new io.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`);let l=ZA(a.body,o);if(l===void 0)throw new io.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`);if(l.length!==t.length)throw new io.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the change set reported ${l.length} result(s) for ${t.length} operation(s)`);let u=l.find(c=>c<200||c>=300);if(u!==void 0)throw new io.ConnectionError(s,u,`atomic write of ${r} was rolled back: the change set reported HTTP ${u}`)}vr.postChangeSet=dG;function eS(e){let t=e.text.replace(/\r\n/g,`+`);if(m===-1)return;let p=f.slice(0,m),h=f.slice(m+4);if(!/^Content-Type:\s*application\/http\b/im.test(p))return;let g=/^HTTP\/1\.[01] (\d{3})\b/.exec(h);if(!g||((i=h.match(/^HTTP\/1\.[01] \d{3}\b/gm))!==null&&i!==void 0?i:[]).length!==1)return;let b=(o=/^Content-ID:\s*(\S+)/im.exec(p))===null||o===void 0?void 0:o[1];if(b===void 0||d.has(b)||!u.has(b))return;d.add(b),c.push({status:Number(g[1]),text:h,contentId:b})}return c.length===0?void 0:c}Or.parseChangeSetParts=_g;async function m9(e,t,r){if(t.length===0)return;let{body:n,batchId:i,contentIds:o}=Ng(e,t),a=await e.postBatch(n,i),s=e.apiUrl("/$batch");if((0,Sg.ensureSuccess)(a,s),typeof a.body!="string"||a.body.length===0)throw new bo.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`);let l=eN(a.body,o);if(l===void 0)throw new bo.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`);if(l.length!==t.length)throw new bo.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the change set reported ${l.length} result(s) for ${t.length} operation(s)`);let u=l.find(c=>c<200||c>=300);if(u!==void 0)throw new bo.ConnectionError(s,u,`atomic write of ${r} was rolled back: the change set reported HTTP ${u}`)}Or.postChangeSet=m9;function tN(e){let t=e.text.replace(/\r\n/g,``),r=t.indexOf(``),n=r===-1?t:t.slice(0,r),i=(r===-1?"":t.slice(r+2)).trim(),o={};for(let s of n.split(`-`).slice(1)){let l=s.indexOf(":");l>0&&(o[s.slice(0,l).trim()]=s.slice(l+1).trim())}let a=i===""?void 0:i;if(i!=="")try{a=JSON.parse(i)}catch{}return{status:e.status,headers:o,body:a}}vr.partResponse=eS;async function fG(e,t,r){let{body:n,batchId:i,contentIds:o}=Mh(e,t),a=await e.postBatch(n,i),s=e.apiUrl("/$batch"),l=Uh(a.body,o),u=l?.find(c=>c.status<200||c.status>=300);if(u&&(0,Fh.ensureSuccess)(eS(u),e.apiUrl(t[o.indexOf(u.contentId)].path)),(0,Fh.ensureSuccess)(a,s),!l||l.length!==t.length)throw new io.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the $batch response ${l?`reported ${l.length} result(s) for ${t.length} operation(s)`:"could not be parsed"}, so the outcome is unknown`);return o.map(c=>l.find(d=>d.contentId===c))}vr.sendChangeSet=fG});var sd=v(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.updateTable=ie.deleteAlternateKey=ie.createAlternateKey=ie.deleteGlobalOptionSet=ie.createGlobalOptionSet=ie.deleteRelationship=ie.deleteColumn=ie.updateColumn=ie.deleteTable=ie.createRelationship=ie.insertStatusValue=ie.createCustomerColumn=ie.createColumns=ie.setColumnVisualization=ie.getColumnVisualization=ie.createColumn=ie.createTable=ie.resolveEntitySetName=ie.pluralFallback=void 0;var Ae=ye(),ne=ue(),zn=Ko(),Ie=Q(),pG=Wl(),mG={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 Je(e,t){return{"@odata.type":"Microsoft.Dynamics.CRM.Label",LocalizedLabels:hG(e,t)}}var tS=65535;function hG(e,t){let r=(o,a)=>({"@odata.type":"Microsoft.Dynamics.CRM.LocalizedLabel",Label:o,LanguageCode:a});if(typeof e=="string")return[r(e,t)];let n=Object.entries(e);if(!n.length)throw new Ie.InvalidArgumentError("a localized label must contain at least one language");let i=new Set;return n.map(([o,a])=>{if(!/^[1-9]\d*$/.test(o))throw new Ie.InvalidArgumentError(`localized label key '${o}' is not an LCID (expected a canonical positive integer, e.g. 1033)`);let s=Number(o);if(s>tS)throw new Ie.InvalidArgumentError(`localized label LCID ${s} is out of range (1-${tS})`);if(i.has(s))throw new Ie.InvalidArgumentError(`localized label LCID ${s} is specified more than once`);if(i.add(s),typeof a!="string")throw new Ie.InvalidArgumentError(`localized label for LCID ${s} must be a string`);return r(a,s)})}function oS(e){return typeof e=="string"?`${e}s`:Object.fromEntries(Object.entries(e).map(([t,r])=>{if(typeof r!="string")throw new Ie.InvalidArgumentError(`localized label for LCID ${t} must be a string`);return[t,`${r}s`]}))}ie.pluralFallback=oS;function zl(e){return{Value:e,CanBeChanged:!0,ManagedPropertyLogicalName:"canmodifyrequirementlevelsettings"}}function Vh(e){let t=e.indexOf("_");return t>0?e.slice(0,t):e}function rS(e,t,r){let n=e[t];n&&typeof n=="object"?n.Value=r:e[t]={Value:r}}function jl(e){let t=(0,Ae.readCreatedId)(e,"MetadataId");if(!t)throw new Ie.InvalidArgumentError("Dataverse did not return a MetadataId for the created metadata component");return t}function gG(e,t,r){var n,i,o,a,s,l,u,c,d,f,p,m,h,g,b,w,E,A,L,R,I,D,O,$;if(t.defaultValue!==void 0&&e!=="boolean")throw new Ie.InvalidArgumentError(`createColumn: 'defaultValue' applies to boolean columns, but '${t.schemaName}' is of type '${e}'.`);if(t.integerFormat!==void 0&&e!=="integer")throw new Ie.InvalidArgumentError(`createColumn: 'integerFormat' applies to integer columns, but '${t.schemaName}' is of type '${e}'.`);switch(e){case"string":return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},MaxLength:(n=t.maxLength)!==null&&n!==void 0?n:100,FormatName:{Value:(i=t.stringFormat)!==null&&i!==void 0?i:"Text"}};case"memo":return{"@odata.type":"Microsoft.Dynamics.CRM.MemoAttributeMetadata",AttributeType:"Memo",AttributeTypeName:{Value:"MemoType"},MaxLength:(o=t.maxLength)!==null&&o!==void 0?o:2e3,Format:"TextArea"};case"integer":return{"@odata.type":"Microsoft.Dynamics.CRM.IntegerAttributeMetadata",AttributeType:"Integer",AttributeTypeName:{Value:"IntegerType"},Format:(a=t.integerFormat)!==null&&a!==void 0?a:"None",MinValue:(s=t.minValue)!==null&&s!==void 0?s:-2147483648,MaxValue:(l=t.maxValue)!==null&&l!==void 0?l:2147483647};case"bigint":return{"@odata.type":"Microsoft.Dynamics.CRM.BigIntAttributeMetadata",AttributeType:"BigInt",AttributeTypeName:{Value:"BigIntType"}};case"double":return{"@odata.type":"Microsoft.Dynamics.CRM.DoubleAttributeMetadata",AttributeType:"Double",AttributeTypeName:{Value:"DoubleType"},Precision:(u=t.precision)!==null&&u!==void 0?u:2,MinValue:(c=t.minValue)!==null&&c!==void 0?c:-1e11,MaxValue:(d=t.maxValue)!==null&&d!==void 0?d:1e11};case"decimal":return{"@odata.type":"Microsoft.Dynamics.CRM.DecimalAttributeMetadata",AttributeType:"Decimal",AttributeTypeName:{Value:"DecimalType"},Precision:(f=t.precision)!==null&&f!==void 0?f:2,MinValue:(p=t.minValue)!==null&&p!==void 0?p:-1e11,MaxValue:(m=t.maxValue)!==null&&m!==void 0?m:1e11};case"money":return{"@odata.type":"Microsoft.Dynamics.CRM.MoneyAttributeMetadata",AttributeType:"Money",AttributeTypeName:{Value:"MoneyType"},Precision:(h=t.precision)!==null&&h!==void 0?h:2,PrecisionSource:2,MinValue:(g=t.minValue)!==null&&g!==void 0?g:0,MaxValue:(b=t.maxValue)!==null&&b!==void 0?b:1e9};case"boolean":return{"@odata.type":"Microsoft.Dynamics.CRM.BooleanAttributeMetadata",AttributeType:"Boolean",AttributeTypeName:{Value:"BooleanType"},DefaultValue:(w=t.defaultValue)!==null&&w!==void 0?w:!1,OptionSet:{"@odata.type":"Microsoft.Dynamics.CRM.BooleanOptionSetMetadata",TrueOption:{Value:1,Label:Je((E=t.trueLabel)!==null&&E!==void 0?E:"Yes",r)},FalseOption:{Value:0,Label:Je((A=t.falseLabel)!==null&&A!==void 0?A:"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 nS(t,r,!1);case"multiChoice":return nS(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:(I=t.isPrimaryImage)!==null&&I!==void 0?I:!1,MaxSizeInKB:(D=t.maxSizeKb)!==null&&D!==void 0?D:10240};case"autonumber":return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},FormatName:{Value:"Text"},MaxLength:(O=t.maxLength)!==null&&O!==void 0?O:100,AutoNumberFormat:($=t.autoNumberFormat)!==null&&$!==void 0?$:""};default:throw new Ie.InvalidArgumentError(`unsupported column type '${String(e)}'`)}}function nS(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,ne.normalizeGuid)(e.globalChoiceMetadataId,"globalChoiceMetadataId")})`,i;if(!e.options||e.options.length===0)throw new Ie.InvalidArgumentError(`choice column '${e.schemaName}' requires at least one option (or a globalChoiceMetadataId)`);return i.OptionSet={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",IsGlobal:!1,OptionSetType:"Picklist",Options:e.options.map(o=>({Value:o.value,Label:Je(o.label,t)}))},i}var Bh=new WeakMap;async function yG(e,t){var r,n;let i=(r=Bh.get(e))===null||r===void 0?void 0:r.get(t);if(i)return i;let o=`/EntityDefinitions(LogicalName='${(0,ne.odataPathLiteral)(t)}')${(0,ne.odataQuery)([["$select","EntitySetName"]])}`,s=(n=(0,Ae.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.EntitySetName;if(!s)throw new Ie.InvalidArgumentError(`could not resolve EntitySetName for '${t}'`);(0,ne.assertODataName)(s,`server-derived EntitySetName for '${t}'`);let l=Bh.get(e);return l||(l=new Map,Bh.set(e,l)),l.set(t,s),s}ie.resolveEntitySetName=yG;async function bG(e,t){var r,n,i,o,a,s,l,u,c,d,f,p,m,h,g;let b=(r=t.languageCode)!==null&&r!==void 0?r:zn.DEFAULT_LCID,w=Vh(t.schemaName),E=(n=t.primaryColumnSchemaName)!==null&&n!==void 0?n:`${w}_Name`,A={"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},SchemaName:E,RequiredLevel:zl("None"),MaxLength:(i=t.primaryColumnMaxLength)!==null&&i!==void 0?i:100,FormatName:{Value:"Text"},DisplayName:Je((o=t.primaryColumnDisplayName)!==null&&o!==void 0?o:"Name",b),IsPrimaryName:!0};t.primaryColumnAutoNumberFormat&&(A.AutoNumberFormat=t.primaryColumnAutoNumberFormat),t.columns&&lS(t.columns,"createTable");let L={"@odata.type":"Microsoft.Dynamics.CRM.EntityMetadata",SchemaName:t.schemaName,DisplayName:Je(t.displayName,b),DisplayCollectionName:Je((a=t.pluralName)!==null&&a!==void 0?a:oS(t.displayName),b),OwnershipType:(s=t.ownership)!==null&&s!==void 0?s:"UserOwned",IsActivity:!1,HasActivities:(l=t.hasActivities)!==null&&l!==void 0?l:!1,HasNotes:(u=t.hasNotes)!==null&&u!==void 0?u:!1,Attributes:[A,...((c=t.columns)!==null&&c!==void 0?c:[]).map(Le=>Gh(Le,b))]};t.description&&(L.Description=Je(t.description,b));let R="/EntityDefinitions",I=(0,Ae.ensureSuccess)(await e.post(R,L),e.apiUrl(R)),D=jl(I),O=`/EntityDefinitions(${D})`+(0,ne.odataQuery)([["$select","LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute"]]),$=Math.max(1,Math.trunc((d=t.readBackAttempts)!==null&&d!==void 0?d:6)),K=Math.max(0,(f=t.readBackDelayMs)!==null&&f!==void 0?f:1e3),Re;for(let Le=1;Le<=$;Le+=1){let at=await e.get(O);if(at.status>=200&&at.status<300){Re=at;break}at.status!==404&&(0,Ae.ensureSuccess)(at,e.apiUrl(O)),Le<$&&K>0&&await new Promise(ge=>setTimeout(ge,K))}if(!Re)throw new Ie.SdkError("TABLE_METADATA_NOT_VISIBLE",`Table '${t.schemaName}' WAS CREATED (MetadataId ${D}) but its metadata was still not readable after ${$} attempt(s). Do NOT re-run the create \u2014 it will collide on the schema name. Re-read /EntityDefinitions(${D}) once the environment catches up, or raise 'readBackAttempts'.`);let It=Re.body;return{logicalName:(p=It.LogicalName)!==null&&p!==void 0?p:t.schemaName.toLowerCase(),metadataId:D,entitySetName:(m=It.EntitySetName)!==null&&m!==void 0?m:"",primaryIdAttribute:(h=It.PrimaryIdAttribute)!==null&&h!==void 0?h:`${t.schemaName.toLowerCase()}id`,primaryNameAttribute:(g=It.PrimaryNameAttribute)!==null&&g!==void 0?g:E.toLowerCase()}}ie.createTable=bG;function Gh(e,t){var r,n;let i=(r=e.languageCode)!==null&&r!==void 0?r:t,o={...gG(e.type,e,i),SchemaName:e.schemaName,RequiredLevel:zl((n=e.required)!==null&&n!==void 0?n:"None"),DisplayName:Je(e.displayName,i)};return e.description&&(o.Description=Je(e.description,i)),e.sourceType&&e.sourceType!=="Simple"&&(o.SourceType=e.sourceType==="Rollup"?2:1,e.formulaDefinition&&(o.FormulaDefinition=e.formulaDefinition)),aS(o,e),o}function aS(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 vG(e,t,r){var n;let i=Gh(r,(n=r.languageCode)!==null&&n!==void 0?n:zn.DEFAULT_LCID),o=`/EntityDefinitions(LogicalName='${(0,ne.odataPathLiteral)(t)}')/Attributes`,a=(0,Ae.ensureSuccess)(await e.post(o,i),e.apiUrl(o)),s={logicalName:r.schemaName.toLowerCase(),metadataId:jl(a)};if(r.visualization&&r.visualization!=="None")try{await dS(e,t,s.logicalName,s.metadataId,r.visualization)}catch(l){let u=new Ie.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(0,Ie.attachCause)(u,l),u}return s}ie.createColumn=vG;var ss="/controlconfigurations",sS="CustomRenderersConfiguration",qh={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 lS(e,t){let r=e.find(n=>n.visualization&&n.visualization!=="None");if(r)throw new Ie.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 uS(e){return JSON.stringify({type:qh[e]})}function wG(e){if(!e)return"None";let t;try{t=JSON.parse(e)}catch{return"None"}let r=t?.type,n=Object.keys(qh).find(i=>qh[i]===r);return n??"None"}async function cS(e,t,r){var n,i;let o=`entitylogicalname eq '${(0,ne.odataLiteral)(t)}' and Attribute/logicalname eq '${(0,ne.odataLiteral)(r)}'`,a=`${ss}${(0,ne.odataQuery)([["$select","name,uniquename,metadatajson"],["$expand","Attribute($select=name,logicalname)"],["$filter",o]])}`,l=(i=(n=(0,Ae.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[],u=r.toLowerCase();return l.filter(c=>{var d,f;return((f=(d=c.Attribute)===null||d===void 0?void 0:d.logicalname)===null||f===void 0?void 0:f.toLowerCase())===u})}async function CG(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,ne.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,ne.odataPathLiteral)(r)}')${(0,ne.odataQuery)([["$select","MetadataId"]])}`,a=(n=(0,Ae.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||n===void 0?void 0:n.MetadataId;if(!a)throw new Ie.InvalidArgumentError(`cannot resolve column '${r}' on '${t}' to set its visualization`);return(0,ne.normalizeGuid)(a,"MetadataId")}async function dS(e,t,r,n,i){let o={name:sS,uniquename:`msdyn_${t}_${r}_customrenderers`,metadatajson:uS(i),"[email protected]":`/attributes(${(0,ne.normalizeGuid)(n,"MetadataId")})`,entitylogicalname:t};(0,Ae.ensureSuccess)(await e.post(ss,o),e.apiUrl(ss))}async function EG(e,t,r){var n;let i=await cS(e,t,r);return wG((n=i[0])===null||n===void 0?void 0:n.metadatajson)}ie.getColumnVisualization=EG;async function AG(e,t,r,n){let o=(await cS(e,t,r)).map(u=>u.controlconfigurationid).filter(u=>!!u);if(n==="None"){for(let u of o){let c=`${ss}(${(0,ne.normalizeGuid)(u,"controlconfigurationid")})`;(0,Ae.ensureSuccess)(await e.delete(c),e.apiUrl(c))}return}let[a,...s]=o,l=await CG(e,t,r);if(a){let u=`${ss}(${(0,ne.normalizeGuid)(a,"controlconfigurationid")})`,c={name:sS,metadatajson:uS(n),"[email protected]":`/attributes(${l})`,entitylogicalname:t};(0,Ae.ensureSuccess)(await e.patch(u,c),e.apiUrl(u))}else await dS(e,t,r,l,n);for(let u of s){let c=`${ss}(${(0,ne.normalizeGuid)(u,"controlconfigurationid")})`;(0,Ae.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}ie.setColumnVisualization=AG;async function SG(e,t,r){if(r.length===0)return;if(lS(r,"createColumns"),!e.supportsAtomicBatch)throw new Ie.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,ne.odataPathLiteral)(t)}')/Attributes`;await(0,pG.postChangeSet)(e,r.map(i=>{var o;return{method:"POST",path:n,body:Gh(i,(o=i.languageCode)!==null&&o!==void 0?o:zn.DEFAULT_LCID)}}),`${r.length} column(s) on '${t}'`)}ie.createColumns=SG;async function NG(e,t,r){var n,i,o,a;let s=(n=r.languageCode)!==null&&n!==void 0?n:zn.DEFAULT_LCID,l=Vh(r.schemaName),u=(i=r.accountRelationshipName)!==null&&i!==void 0?i:`${l}_${t}_account`,c=(o=r.contactRelationshipName)!==null&&o!==void 0?o:`${l}_${t}_contact`,d={Lookup:{"@odata.type":"Microsoft.Dynamics.CRM.ComplexLookupAttributeMetadata",SchemaName:r.schemaName,DisplayName:Je(r.displayName,s),RequiredLevel:zl((a=r.required)!==null&&a!==void 0?a:"None"),Targets:["account","contact"]},OneToManyRelationships:[{"@odata.type":"Microsoft.Dynamics.CRM.ComplexOneToManyRelationshipMetadata",SchemaName:u,ReferencedEntity:"account",ReferencingEntity:t},{"@odata.type":"Microsoft.Dynamics.CRM.ComplexOneToManyRelationshipMetadata",SchemaName:c,ReferencedEntity:"contact",ReferencingEntity:t}]};return(0,Ae.ensureSuccess)(await e.post("/CreateCustomerRelationships",d),e.apiUrl("/CreateCustomerRelationships")),{logicalName:r.schemaName.toLowerCase(),metadataId:""}}ie.createCustomerColumn=NG;async function _G(e,t,r){var n,i,o,a,s;let l=(n=r.languageCode)!==null&&n!==void 0?n:zn.DEFAULT_LCID,u={EntityLogicalName:t,AttributeLogicalName:"statuscode",Label:Je(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,Ae.ensureSuccess)(await e.post("/InsertStatusValue",u),e.apiUrl("/InsertStatusValue"));return Number((s=(a=(o=c.body)===null||o===void 0?void 0:o.NewOptionValue)!==null&&a!==void 0?a:r.value)!==null&&s!==void 0?s:0)}ie.insertStatusValue=_G;async function TG(e,t){var r,n,i,o,a;let s=(r=t.languageCode)!==null&&r!==void 0?r:zn.DEFAULT_LCID,l,u;if(t.type==="OneToMany"){if(!t.referencedEntity||!t.referencingEntity)throw new Ie.InvalidArgumentError("OneToMany relationship requires referencedEntity and referencingEntity");let f=(n=t.lookupSchemaName)!==null&&n!==void 0?n:`${Vh(t.schemaName)}_${t.referencedEntity}Id`;u=f.toLowerCase(),l={"@odata.type":"Microsoft.Dynamics.CRM.OneToManyRelationshipMetadata",SchemaName:t.schemaName,ReferencedEntity:t.referencedEntity,ReferencingEntity:t.referencingEntity,Lookup:{"@odata.type":"Microsoft.Dynamics.CRM.LookupAttributeMetadata",AttributeType:"Lookup",AttributeTypeName:{Value:"LookupType"},SchemaName:f,RequiredLevel:zl((i=t.lookupRequired)!==null&&i!==void 0?i:"None"),DisplayName:Je((o=t.lookupDisplayName)!==null&&o!==void 0?o:t.referencedEntity,s)}}}else{if(!t.entity1||!t.entity2)throw new Ie.InvalidArgumentError("ManyToMany relationship requires entity1 and entity2");l={"@odata.type":"Microsoft.Dynamics.CRM.ManyToManyRelationshipMetadata",SchemaName:t.schemaName,IntersectEntityName:(a=t.intersectEntityName)!==null&&a!==void 0?a:t.schemaName.toLowerCase(),Entity1LogicalName:t.entity1,Entity2LogicalName:t.entity2}}let c="/RelationshipDefinitions",d=(0,Ae.ensureSuccess)(await e.post(c,l),e.apiUrl(c));return{schemaName:t.schemaName,metadataId:jl(d),lookupLogicalName:u}}ie.createRelationship=TG;async function DG(e,t){let r=`/EntityDefinitions(LogicalName='${(0,ne.odataPathLiteral)(t)}')`;(0,Ae.ensureSuccess)(await e.delete(r),e.apiUrl(r))}ie.deleteTable=DG;async function IG(e,t,r,n){var i,o;let a=(i=n.languageCode)!==null&&i!==void 0?i:zn.DEFAULT_LCID,s=`/EntityDefinitions(LogicalName='${(0,ne.odataPathLiteral)(t)}')/Attributes`,l=`${s}(LogicalName='${(0,ne.odataPathLiteral)(r)}')${(0,ne.odataQuery)([["$select","MetadataId,AttributeType"]])}`,c=(0,Ae.ensureSuccess)(await e.get(l),e.apiUrl(l)).body,d=mG[(o=c.AttributeType)!==null&&o!==void 0?o:""];if(!c.MetadataId||!d)throw new Ie.InvalidArgumentError(`cannot update column '${r}' on '${t}' (type '${c.AttributeType}' not supported)`);let f=(0,ne.normalizeGuid)(c.MetadataId,"MetadataId"),p=`${s}(${f})/${d}`,m=(0,Ae.ensureSuccess)(await e.get(p),e.apiUrl(p)).body;for(let g of Object.keys(m))g.startsWith("@odata.")&&delete m[g];if(m["@odata.type"]=d,n.displayName!==void 0&&(m.DisplayName=Je(n.displayName,a)),n.description!==void 0&&(m.Description=Je(n.description,a)),n.required!==void 0&&(m.RequiredLevel=zl(n.required)),n.maxLength!==void 0&&(m.MaxLength=n.maxLength),n.autoNumberFormat!==void 0&&(m.AutoNumberFormat=n.autoNumberFormat),n.defaultValue!==void 0&&c.AttributeType!=="Boolean")throw new Ie.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 Ie.InvalidArgumentError(`updateColumn: 'integerFormat' applies to Integer columns, but '${r}' on '${t}' is of type '${c.AttributeType}'.`);n.defaultValue!==void 0&&(m.DefaultValue=n.defaultValue),n.integerFormat!==void 0&&(m.Format=n.integerFormat),aS(m,n);let h=`${s}(${f})`;(0,Ae.ensureSuccess)(await e.put(h,m,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(h))}ie.updateColumn=IG;async function OG(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,ne.odataPathLiteral)(t)}')/Attributes`,o=`${i}(LogicalName='${(0,ne.odataPathLiteral)(r)}')${(0,ne.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,Ae.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new Ie.InvalidArgumentError(`column '${r}' not found on '${t}'`);let l=`${i}(${(0,ne.normalizeGuid)(s,"MetadataId")})`;(0,Ae.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteColumn=OG;async function PG(e,t){var r,n,i;let o=`/RelationshipDefinitions${(0,ne.odataQuery)([["$filter",`SchemaName eq '${(0,ne.odataLiteral)(t)}'`],["$select","MetadataId"]])}`,s=(i=(n=(r=(0,Ae.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||r===void 0?void 0:r.value)===null||n===void 0?void 0:n[0])===null||i===void 0?void 0:i.MetadataId;if(!s)throw new Ie.InvalidArgumentError(`relationship '${t}' not found`);let l=`/RelationshipDefinitions(${(0,ne.normalizeGuid)(s,"MetadataId")})`;(0,Ae.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteRelationship=PG;async function iS(e,t){var r;let n=`/GlobalOptionSetDefinitions(Name='${(0,ne.odataPathLiteral)(t)}')${(0,ne.odataQuery)([["$select","MetadataId"]])}`,i=await e.get(n);if(i.status===404)return;let a=(r=(0,Ae.ensureSuccess)(i,e.apiUrl(n)).body)===null||r===void 0?void 0:r.MetadataId;return a?(0,ne.normalizeGuid)(a,"MetadataId"):void 0}async function RG(e,t){var r;let n=t.name.toLowerCase(),i=await iS(e,n);if(i)return{name:n,metadataId:i};let o=(r=t.languageCode)!==null&&r!==void 0?r:zn.DEFAULT_LCID,a={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",Name:n,DisplayName:Je(t.displayName,o),IsGlobal:!0,OptionSetType:"Picklist",Options:t.options.map(l=>({Value:l.value,Label:Je(l.label,o)}))};t.description&&(a.Description=Je(t.description,o));let s="/GlobalOptionSetDefinitions";try{let l=(0,Ae.ensureSuccess)(await e.post(s,a),e.apiUrl(s));return{name:n,metadataId:jl(l)}}catch(l){let u;try{u=await iS(e,n)}catch{u=void 0}if(u)return{name:n,metadataId:u};throw l}}ie.createGlobalOptionSet=RG;async function LG(e,t){let r=`/GlobalOptionSetDefinitions(Name='${(0,ne.odataPathLiteral)(t.toLowerCase())}')`;(0,Ae.ensureSuccess)(await e.delete(r),e.apiUrl(r))}ie.deleteGlobalOptionSet=LG;async function kG(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:zn.DEFAULT_LCID,o={"@odata.type":"Microsoft.Dynamics.CRM.EntityKeyMetadata",SchemaName:r.schemaName,DisplayName:Je(r.displayName,i),KeyAttributes:r.keyAttributes},a=`/EntityDefinitions(LogicalName='${(0,ne.odataPathLiteral)(t)}')/Keys`,s=(0,Ae.ensureSuccess)(await e.post(a,o),e.apiUrl(a));return{logicalName:r.schemaName.toLowerCase(),metadataId:jl(s)}}ie.createAlternateKey=kG;async function xG(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,ne.odataPathLiteral)(t)}')/Keys`,o=`${i}(LogicalName='${(0,ne.odataPathLiteral)(r.toLowerCase())}')${(0,ne.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,Ae.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new Ie.InvalidArgumentError(`alternate key '${r}' not found on '${t}'`);let l=`${i}(${(0,ne.normalizeGuid)(s,"MetadataId")})`;(0,Ae.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteAlternateKey=xG;async function $G(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:zn.DEFAULT_LCID,o=`/EntityDefinitions(LogicalName='${(0,ne.odataPathLiteral)(t)}')`,s=(0,Ae.ensureSuccess)(await e.get(o),e.apiUrl(o)).body,l=s.MetadataId;if(!l)throw new Ie.InvalidArgumentError(`table '${t}' not found`);let u=(0,ne.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=Je(r.displayName,i)),r.pluralName!==void 0&&(s.DisplayCollectionName=Je(r.pluralName,i)),r.description!==void 0&&(s.Description=Je(r.description,i)),r.auditEnabled!==void 0&&rS(s,"IsAuditEnabled",r.auditEnabled),r.duplicateDetectionEnabled!==void 0&&rS(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,Ae.ensureSuccess)(await e.put(c,s,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(c))}ie.updateTable=$G});var ao=v(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.rebuildRaw=wr.assembleChildren=wr.spliceChildren=wr.mergeAttrs=wr.rawFromNode=wr.emptyBag=void 0;var oo=Q(),fS=1e6,ud=512;function FG(){return{a:[],c:[]}}wr.emptyBag=FG;function pS(e,t=0){if(t>ud)throw new oo.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${ud}`);return{n:e.getNodeName(),a:e.getAllProperties().map(r=>[r.key,r.value]),c:e.getAllChildren().map(r=>pS(r,t+1))}}wr.rawFromNode=pS;function MG(e,t,r=[]){let n=new Map;for(let[s,l]of t)n.set(s,l);let i=new Set(r.filter(s=>!n.has(s))),o=new Set,a=[];for(let[s,l]of e)i.has(s)||(n.has(s)?a.push([s,n.get(s)]):a.push([s,l]),o.add(s));for(let[s,l]of t)o.has(s)||(a.push([s,l]),o.add(s));return a}wr.mergeAttrs=MG;function ld(e,t){let r=new Set;for(let s of e){let l=s.i;if(!Number.isInteger(l)||l<0||l>fS)throw new oo.InvalidArgumentError(`Bag child index must be an integer in [0, ${fS}] (got ${String(l)})`);if(r.has(l))throw new oo.InvalidArgumentError(`Duplicate bag child index ${l}`);r.add(l)}let n=[...e].sort((s,l)=>s.i-l.i),i=[],o=0,a=0;for(let s of n){for(;a<s.i&&o<t.length;)i.push(t[o]),o+=1,a+=1;a<s.i&&(a=s.i),i.push(s.node),a+=1}for(;o<t.length;)i.push(t[o]),o+=1;return i}wr.spliceChildren=ld;function UG(e,t){if(e.w){let r={n:e.w.n,a:e.w.a.map(n=>[n[0],n[1]]),c:ld(e.w.c,t)};return ld(e.c,[r])}return ld(e.c,t)}wr.assembleChildren=UG;function mS(e,t,r,n=0){if(n>ud)throw new oo.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${ud}`);BG(e,n);let i=t.make(e.n,r);for(let[o,a]of e.a)t.setProp(i,o,a);for(let o of e.c)t.addChild(i,mS(o,t,i,n+1));return i}wr.rebuildRaw=mS;function BG(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new oo.InvalidArgumentError(`Malformed hybrid node at depth ${t}: expected a JSON object`);let r=e;if(typeof r.n!="string")throw new oo.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 oo.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 oo.InvalidArgumentError(`Malformed hybrid node '${r.n}': each attribute must be a [string, string] pair`)}});var so=v(cd=>{"use strict";Object.defineProperty(cd,"__esModule",{value:!0});cd.installDomShim=void 0;var hS=rs(),gS=!1,qG={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 VG(){if(gS)return;let e=globalThis;typeof e.DOMParser>"u"&&(e.DOMParser=hS.DOMParser),typeof e.XMLSerializer>"u"&&(e.XMLSerializer=hS.XMLSerializer),typeof e.Node>"u"&&(e.Node=qG),gS=!0}cd.installDomShim=VG});var lo=v(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.projectElementBag=Ye.serializeNode=Ye.domEngine=Ye.nodeLikeFromDom=Ye.parseXmlRoot=Ye.EMPTY_FORM_SENTINEL=Ye.TEXT_SENTINEL=void 0;var GG=ao(),Hl=Q(),WG=so();Ye.TEXT_SENTINEL="#text";Ye.EMPTY_FORM_SENTINEL="#empty";var fd=new WeakSet;function zG(e,t){(0,WG.installDomShim)();let r=e&&e.trim()!==""?e:t,i=new DOMParser().parseFromString(r,"text/xml").documentElement;if(!i)throw new Hl.InvalidArgumentError("XML source has no root element (empty or malformed input)");return HG(i),KG(i),QG(i,r),i}Ye.parseXmlRoot=zG;var jG=new Set([1,3]);function HG(e){let t=[e];for(;t.length>0;){let n=t.pop().childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];if(!jG.has(o.nodeType))throw new Hl.InvalidArgumentError(`Unsupported XML node type ${o.nodeType} (CDATA / comment / processing-instruction) is outside the hybrid projection's lossless grammar and cannot be round-tripped`);o.nodeType===1&&t.push(o)}}}function KG(e){var t,r;let n=(t=e.ownerDocument)!==null&&t!==void 0?t:e.parentNode;if(!n)return;let i=n.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];if(a!==e&&!(a.nodeType===3&&((r=a.nodeValue)!==null&&r!==void 0?r:"").trim()===""))throw new Hl.InvalidArgumentError(`Unsupported document-level XML node (type ${a.nodeType}: declaration / comment / processing-instruction outside the root element) cannot be round-tripped`)}}function JG(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 YG(e){let t=[],r=[e];for(;r.length>0;){let n=r.pop();t.push(n);let i=n.childNodes;for(let o=i.length-1;o>=0;o-=1){let a=i[o];a.nodeType===1&&r.push(a)}}return t}function bS(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 QG(e,t){let r=JG(t),n=YG(e),i=Math.min(r.length,n.length);for(let o=0;o<i;o+=1){if(r[o])continue;let a=n[o];bS(a)||fd.add(a)}}function Wh(e){let t=e.nodeType===3;return{getNodeName:()=>t?Ye.TEXT_SENTINEL:e.tagName,getAllProperties:()=>{var r;if(t)return[{key:Ye.TEXT_SENTINEL,value:(r=e.nodeValue)!==null&&r!==void 0?r:""}];let n=e.attributes,i=[];for(let o=0;o<n.length;o+=1)i.push({key:n[o].name,value:n[o].value});return fd.has(e)&&!bS(e)&&i.push({key:Ye.EMPTY_FORM_SENTINEL,value:"1"}),i},getAllChildren:()=>{if(t)return[];let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];(o.nodeType===1||o.nodeType===3)&&r.push(Wh(o))}return r}}}Ye.nodeLikeFromDom=Wh;function XG(e){return{make:t=>t===Ye.TEXT_SENTINEL?e.createTextNode(""):e.createElement(t),setProp:(t,r,n)=>{t.nodeType===3?t.nodeValue=n:r===Ye.EMPTY_FORM_SENTINEL?fd.add(t):t.setAttribute(r,n)},addChild:(t,r)=>{t.appendChild(r)}}}Ye.domEngine=XG;function vS(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 dd(r);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))throw dd(r);t+=1;continue}if(r>=56320&&r<=57343)throw dd(r)}}function dd(e){let t=e.toString(16).toUpperCase().padStart(4,"0");return new Hl.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 ZG(e){return vS(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/\r/g,"
").replace(/\n/g,"
").replace(/\t/g,"	")}function e9(e){return vS(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function t9(e){return wS(e,0)}Ye.serializeNode=t9;var yS=512;function wS(e,t){var r;if(t>yS)throw new Hl.InvalidArgumentError(`XML nesting exceeds the maximum supported depth of ${yS}`);if(e.nodeType===3)return e9((r=e.nodeValue)!==null&&r!==void 0?r:"");let n=e,i="<"+n.tagName,o=n.attributes;for(let l=0;l<o.length;l+=1)i+=" "+o[l].name+'="'+ZG(o[l].value)+'"';let a=[],s=n.childNodes;for(let l=0;l<s.length;l+=1){let u=s[l];(u.nodeType===1||u.nodeType===3)&&a.push(u)}if(a.length===0)return fd.has(n)?i+"></"+n.tagName+">":i+" />";i+=">";for(let l of a)i+=wS(l,t+1);return i+"</"+n.tagName+">"}function r9(e){let t=Wh(e);return{a:t.getAllProperties().map(r=>[r.key,r.value]),c:t.getAllChildren().map((r,n)=>({i:n,node:(0,GG.rawFromNode)(r)}))}}Ye.projectElementBag=r9});var Zr=v(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.rejectUnknownKeys=Vt.childObjects=Vt.optionalGuidId=Vt.optionalEnum=Vt.eachObject=Vt.issue=Vt.isJsonObject=void 0;function CS(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}Vt.isJsonObject=CS;function ls(e,t,r,n){return n?{pointer:e,rule:t,message:r,fatal:n}:{pointer:e,rule:t,message:r}}Vt.issue=ls;function ES(e,t,r,n){if(!Array.isArray(e))return[];let i=[];return e.forEach((o,a)=>{CS(o)?i.push({node:o,index:a}):n.push(ls(`${t}/${a}`,`${r}-must-be-object`,`a ${r} must be a JSON object, got ${o===null?"null":typeof o}`))}),i}Vt.eachObject=ES;function n9(e,t,r,n,i,o){let a=e[t];a!==void 0&&(typeof a!="string"||!r.includes(a))&&o.push(ls(`${n}/${t}`,i,`${t} must be one of ${r.map(s=>`'${s}'`).join(", ")}, got ${JSON.stringify(a)}`))}Vt.optionalEnum=n9;var i9=/^(?:\{[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 o9(e,t,r,n,i){let o=e[t];typeof o=="string"&&o!==""&&!i9.test(o)&&i.push(ls(`${r}/${t}`,n,`${t} must be a GUID or empty, got '${o}'`))}Vt.optionalGuidId=o9;function a9(e,t,r,n,i){let o=e[t],a=`${r}/${t}`;return o===void 0?[]:Array.isArray(o)?ES(o,a,n,i):(i.push(ls(a,`${n}-list-must-be-array`,`${t} must be an array when present, got ${typeof o}`)),[])}Vt.childObjects=a9;function s9(e,t,r,n,i,o={}){var a,s;for(let l of Object.keys(e)){if(t.has(l))continue;let u=(a=o.elsewhere)===null||a===void 0?void 0:a[l],c=(s=o.unsupported)===null||s===void 0?void 0:s[l],d=u?` '${l}' is a ${u} key \u2014 set it on the ${u} instead.`:c?` ${c}`:` Put values the typed layer does not model in '${n}.bag', which round-trips them verbatim.`;i.push(ls(`${r}/${l}`,`${n}-unknown-key`,`'${l}' is not a ${n} property, and would be SILENTLY DROPPED at serialization.${d}`))}}Vt.rejectUnknownKeys=s9});var yd=v(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.genPageEmbedIssues=B.setUniqueId=B.mintEmbedIdentity=B.authoredUniqueId=B.hasGenPage=B.applyEmbedCellDefaults=B.applyEmbedControlDefaults=B.mayCommitEmbedState=B.commitEmbedState=B.reconcileEmbedDescriptions=B.embedAppendIndex=B.activeEmbedBindings=B.projectGenPageEmbeds=B.isRecognizedEmbed=B.isUnbound=B.effectiveClassId=B.effectiveFormType=B.inputDataFrom=B.classifyBinding=B.isStaticParameter=B.entryParameter=B.pageEntries=B.descriptionFor=B.descriptionsRegion=B.controlUniqueIds=B.controlUniqueId=B.typedCellSites=B.typedCells=B.rawText=B.rawAttr=B.normGuid=B.GENPAGE_FORM_FACTORS=B.GENPAGE_EMBED_ROWSPAN=B.GENPAGE_CONTROL_NAME=B.CUSTOM_CONTROL_CLASS_ID=void 0;var l9=rs(),u9=Fa(),zh=lt(),en=Zr();B.CUSTOM_CONTROL_CLASS_ID="F9A8A302-114E-466A-B582-6771B2AE0D92";B.GENPAGE_CONTROL_NAME="MscrmControls.UxAgentControl";B.GENPAGE_EMBED_ROWSPAN=6;B.GENPAGE_FORM_FACTORS=["2","0","1"];var c9=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Cr(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase();return t.startsWith("{")&&t.endsWith("}")&&(t=t.slice(1,-1)),c9.test(t)?t:""}B.normGuid=Cr;function uo(e,t){let r=Ce(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}B.rawAttr=uo;function Jl(e){return Ce(e?.c).filter(t=>typeof t?.n=="string"&&t.n.startsWith("<")).map(t=>t.n.slice(1)).join("")}B.rawText=Jl;function Ce(e){return Array.isArray(e)?e:[]}function Qh(e,t){let r=Ce(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}function NS(e){return typeof e=="string"?e.trim().replace(/^\{|\}$/g,"").toUpperCase():""}function _S(e){return wn(e).map(t=>t.cell)}B.typedCells=_S;function wn(e){let t=[];return Ce(e?.tabs).forEach((r,n)=>{Ce(De(r)?r.columns:void 0).forEach((i,o)=>{Ce(De(i)?i.sections:void 0).forEach((a,s)=>{Ce(De(a)?a.rows:void 0).forEach((l,u)=>{Ce(De(l)?l.cells:void 0).forEach((c,d)=>{De(c)&&t.push({cell:c,pointer:`/tabs/${n}/columns/${o}/sections/${s}/rows/${u}/cells/${d}`})})})})})}),t}B.typedCellSites=wn;function Ti(e){return De(e)?Cr(Qh(e.bag,"uniqueid")):""}B.controlUniqueId=Ti;function d9(e){let t=new Set;for(let{cell:r}of wn(e)){let n=Qo(r.control)?Ti(r.control):"";n&&t.add(n)}return t}function f9(e){let t=new Map;for(let{cell:r}of wn(e)){let n=De(r.control)?Ti(r.control):"";n&&!t.has(n)&&t.set(n,r.control)}return t}function p9(e){return e!==void 0&&e.genPage===void 0&&(eg(e)!==B.CUSTOM_CONTROL_CLASS_ID||!gd(e))}function jh(e,t){if(De(e)){t(e);for(let r of Ce(e.c))jh(r,t)}}function Jo(e,t){var r;if(De(e)){for(let n of Ce(e.c))jh(n?.node,t);for(let n of Ce((r=e.w)===null||r===void 0?void 0:r.c))jh(n?.node,t)}}function md(e){let t=new Map,r=i=>{var o;i&&t.set(i,((o=t.get(i))!==null&&o!==void 0?o:0)+1)},n=i=>{i.n==="control"&&r(Cr(uo(i,"uniqueid")))};return Jo(e?.bag,n),Ce(e?.tabs).forEach(i=>{De(i)&&(Jo(i.bag,n),Ce(i.columns).forEach(o=>{De(o)&&(Jo(o.bag,n),Ce(o.sections).forEach(a=>{De(a)&&(Jo(a.bag,n),Ce(a.rows).forEach(s=>{De(s)&&(Jo(s.bag,n),Ce(s.cells).forEach(l=>{De(l)&&(Jo(l.bag,n),De(l.control)&&(r(Ti(l.control)),Jo(l.control.bag,n)))}))}))}))}))}),t}B.controlUniqueIds=md;function us(e){return Ce(e?.c).find(t=>{var r;return((r=t?.node)===null||r===void 0?void 0:r.n)==="controlDescriptions"})}B.descriptionsRegion=us;function Yo(e,t){var r;let n=Cr(t);if(n)return Ce((r=us(e))===null||r===void 0?void 0:r.node.c).find(i=>i?.n==="controlDescription"&&Cr(uo(i,"forControl"))===n)}B.descriptionFor=Yo;function Yl(e){return Ce(e.c).filter(TS)}B.pageEntries=Yl;function TS(e){return e?.n==="customControl"&&uo(e,"name")===B.GENPAGE_CONTROL_NAME}function Hh(e,t){let r=Ce(e.c).find(n=>n?.n==="parameters");return Ce(r?.c).find(n=>n?.n===t)}B.entryParameter=Hh;function Kh(e){return uo(e,"static")==="true"}B.isStaticParameter=Kh;function Ql(e){let t=Yl(e);if(t.length===0)return{kind:"none"};let r,n;for(let i=0;i<t.length;i+=1){let o=Hh(t[i],"RefId");if(!o||!Kh(o))return{kind:"unsupported"};let a=Cr(Jl(o));if(!a)return{kind:"unsupported"};let s=Hh(t[i],"PageInput");if(s&&!Kh(s))return{kind:"unsupported"};let l=s?Jl(s):void 0;if(i===0)r=a,n=l;else if(a!==r||l!==n)return{kind:"unsupported"}}return n===void 0?{kind:"projectable",pageId:r}:{kind:"projectable",pageId:r,pageInputRaw:n}}B.classifyBinding=Ql;function De(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Xh(e){if(e===void 0)return;let t;try{t=JSON.parse(e)}catch{return}return De(t)&&De(t.data)?t.data:void 0}B.inputDataFrom=Xh;function Zh(e){var t;return(t=e.formType)!==null&&t!==void 0?t:"Main"}B.effectiveFormType=Zh;function eg(e){return NS(e.classId!==void 0?e.classId:Qh(e.bag,"classid"))}B.effectiveClassId=eg;function gd(e){return!e.fieldName}B.isUnbound=gd;function tg(e,t){if(Zh(e)!=="Main"||!gd(t)||eg(t)!==B.CUSTOM_CONTROL_CLASS_ID)return!1;let r=Ti(t),n=r?Yo(e.bag,r):void 0;return n!==void 0&&Ql(n).kind==="projectable"}B.isRecognizedEmbed=tg;function m9(e){for(let t of _S(e)){let r=t.control;if(!r||!tg(e,r))continue;let n=Ql(Yo(e.bag,Ti(r)));if(n.kind!=="projectable")continue;let i=Xh(n.pageInputRaw);r.genPage=i===void 0?{pageId:n.pageId}:{pageId:n.pageId,inputData:i}}}B.projectGenPageEmbeds=m9;var h9=new Set(["pageId","inputData"]);function Kl(e){let t=[];for(let r=0;r<e.childNodes.length;r+=1){let n=e.childNodes[r];n.nodeType===1&&t.push(n)}return t}function g9(e){let t=[],r=u=>c=>t.push(`${u}: ${c}`),i=new l9.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml").documentElement;if(!i||t.length>0)throw new Error(`the formxml does not parse cleanly${t.length>0?` (${t[0]})`:""}`);let o=new Set,a=i.getElementsByTagName("control");for(let u=0;u<a.length;u+=1){let c=Cr(a[u].getAttribute("uniqueid"));c&&o.add(c)}let s=Kl(i).find(u=>u.nodeName==="controlDescriptions"),l=new Map;for(let u of s?Kl(s):[]){let c=Cr(u.getAttribute("forControl"));if(!(u.nodeName!=="controlDescription"||!c||!o.has(c)))for(let d of Kl(u)){if(d.nodeName!=="customControl"||d.getAttribute("name")!==B.GENPAGE_CONTROL_NAME)continue;let f=Kl(d).find(h=>h.nodeName==="parameters"),p=f?Kl(f).find(h=>h.nodeName==="RefId"):void 0,m=p&&p.getAttribute("static")==="true"?Cr(p.textContent):"";m&&l.set(`${c}|${m}`,[c,m])}}return[...l.values()]}B.activeEmbedBindings=g9;function pd(e){return{n:`<${e}`,a:[],c:[]}}function Jh(e,t){return{n:e,a:[["type","SingleLine.Text"],["static","true"]],c:[pd(t)]}}function Yh(e,t){let r={};if(t!==void 0)try{let n=JSON.parse(t);De(n)&&(r=n)}catch{}return JSON.stringify({...r,data:e})}function y9(e,t,r){return{n:"controlDescription",a:[["forControl",e]],c:B.GENPAGE_FORM_FACTORS.map(n=>({n:"customControl",a:[["name",B.GENPAGE_CONTROL_NAME],["formFactor",n]],c:[{n:"parameters",a:[],c:[Jh("RefId",t),...r===void 0?[]:[Jh("PageInput",Yh(r))]]}]}))}}function hd(e,t){if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>hd(r,t[n]));if(De(e)&&De(t)){let r=Object.keys(e);return r.length===Object.keys(t).length&&r.every(n=>n in t&&hd(e[n],t[n]))}return e===t}function b9(e,t,r){let n=Ce(e.c).find(u=>u?.n==="parameters");if(!n||!Array.isArray(n.c))return;let i=n.c.find(u=>u?.n==="RefId");i&&Cr(Jl(i))!==t&&(i.c=[pd(t)]);let o=n.c.findIndex(u=>u?.n==="PageInput"),a=o>=0?n.c[o]:void 0,s=a?Jl(a):void 0;if(hd(Xh(s),r))return;if(r!==void 0){a?a.c=[pd(Yh(r,s))]:n.c.push(Jh("PageInput",Yh(r)));return}let l=JSON.parse(s);delete l.data,Object.keys(l).length===0?n.c.splice(o,1):a.c=[pd(JSON.stringify(l))]}function rg(e){let t=Ce(e?.c),r=t.reduce((n,i)=>i.i>n?i.i:n,-1);return Math.max(r,t.length)+1}B.embedAppendIndex=rg;function v9(e,t){var r;let n=e.bag,i=us(n);if(i&&t){let o=md(t),a=md(e),s=d9(t),l=f9(e),u=Ce(i.node.c),c=[];for(let d of u){let f=d?.n==="controlDescription"&&Yl(d).length>0?Cr(uo(d,"forControl")):"";if(!f||!o.has(f))c.push(d);else if(a.has(f))if(s.has(f)&&p9(l.get(f))&&hd(d,Yo(t.bag,f))){let p=Ce(d.c).filter(m=>!TS(m));p.length>0&&c.push({...d,c:p})}else c.push(d)}(c.length!==u.length||c.some((d,f)=>d!==u[f]))&&(i.node.c=c)}for(let{cell:o}of wn(e)){let a=o.control;if(!Qo(a)||!De(a.genPage))continue;let s=Cr(a.genPage.pageId),l=a.genPage.inputData,u=Ti(a);if(!u){if(Xl(a)!==void 0)continue;u=ng(a)}let c=Yo(n,u);if(c){for(let p of Yl(c))b9(p,s,l);continue}i||(i={i:rg(n),node:{n:"controlDescriptions",a:[],c:[]}},n.c.push(i));let d=((r=Qh(a.bag,"uniqueid"))!==null&&r!==void 0?r:"").trim(),f=d.startsWith("{")?d:`{${u}}`;i.node.c.push(y9(f,s,l))}}B.reconcileEmbedDescriptions=v9;function w9(e,t){let r=us(e.bag),n=t!==void 0&&(r===void 0||JSON.stringify(r.node)!==JSON.stringify(t)),i=wn(e).some(({cell:a})=>Qo(a.control)&&(a.rowspan===void 0||a.control.classId===void 0||a.control.showLabel===void 0||a.control.label===void 0||a.control.fieldName===void 0));if(!n&&!i)return e;let o=JSON.parse(JSON.stringify(e));if(n){let a=JSON.parse(JSON.stringify(t)),s=us(o.bag);s?s.node=a:(o.bag=De(o.bag)?o.bag:{a:[],c:[]},o.bag.c=Ce(o.bag.c),o.bag.c.push({i:rg(e.bag),node:a}))}for(let{cell:a}of wn(o))Qo(a.control)&&(DS(a.control),IS(a));return o}B.commitEmbedState=w9;function C9(e){if(wn(e).some(({cell:r})=>Qo(r.control)))return!0;let t=us(e.bag);return Ce(t?.node.c).some(r=>r?.n==="controlDescription"&&Yl(r).length>0)}B.mayCommitEmbedState=C9;function DS(e){e.classId===void 0&&(e.classId=B.CUSTOM_CONTROL_CLASS_ID),e.showLabel===void 0&&(e.showLabel=!1),e.label===void 0&&(e.label=""),e.fieldName===void 0&&(e.fieldName=null)}B.applyEmbedControlDefaults=DS;function IS(e){e.rowspan===void 0&&(e.rowspan=B.GENPAGE_EMBED_ROWSPAN)}B.applyEmbedCellDefaults=IS;function Qo(e){return De(e)&&e.genPage!==void 0}B.hasGenPage=Qo;function AS(e){return Qo(e.control)&&(!e.control.id||!e.id||Xl(e.control)===void 0)}function Xl(e){let t=Ce(De(e.bag)?e.bag.a:void 0).find(n=>Array.isArray(n)&&n[0]==="uniqueid");if(!t)return;let r=t[1];return typeof r=="string"&&r.trim()===""?void 0:r}B.authoredUniqueId=Xl;function E9(e){if(!wn(e).some(({cell:r})=>AS(r)))return e;let t=JSON.parse(JSON.stringify(e));for(let{cell:r}of wn(t)){if(!AS(r))continue;let n=r.control;n.id||(n.id=(0,zh.newId)()),r.id||(r.id=(0,zh.newId)()),Xl(n)===void 0&&ng(n)}return t}B.mintEmbedIdentity=E9;function ng(e){let t=(0,zh.newId)(),r=`{${t}}`;if(!De(e.bag))return e.bag={a:[["uniqueid",r]],c:[]},t;let n=Ce(e.bag.a),i=n.find(o=>Array.isArray(o)&&o[0]==="uniqueid");return i?i[1]=r:n.push(["uniqueid",r]),e.bag.a=n,e.bag.c=Ce(e.bag.c),t}B.setUniqueId=ng;function SS(e){return e===null?"null":Array.isArray(e)?"an array":typeof e}function A9(e){let t=Ce(e.c).filter(r=>r?.n==="customControl").map(r=>{var n,i;return(i=(n=uo(r,"name"))!==null&&n!==void 0?n:uo(r,"id"))!==null&&i!==void 0?i:"(unnamed)"});return[...new Set(t)].join(", ")||"(no custom control)"}function S9(e){let t=[],r;for(let{cell:n,pointer:i}of wn(e)){let o=n.control;if(!De(o))continue;let a=`${i}/control`;if(o.genPage===void 0){N9(e,o,a,t);continue}r=r??md(e),_9(e,o,a,r,t)}return t}B.genPageEmbedIssues=S9;function N9(e,t,r,n){if(!tg(e,t))return;let i=Ql(Yo(e.bag,Ti(t)));n.push((0,en.issue)(r,"genpage-embed-removed",`this control still embeds generative page ${i.pageId}: removing genPage alone would leave that binding on the form. To remove the embed, remove the cell (or set the cell's control to null); to change the page, edit genPage/pageId. A copy fetched by an older SDK (projection 3) shows no genPage at all \u2014 re-fetch the form.`))}function _9(e,t,r,n,i){var o;let a=`${r}/genPage`,s=t.genPage;if(!De(s))i.push((0,en.issue)(a,"genpage-embed-shape",`genPage must be an object { pageId, inputData? }, got ${SS(s)}.`+(s===null?" To remove an embed, remove the cell (or set the cell's control to null).":"")));else{(typeof s.pageId!="string"||!Cr(s.pageId))&&i.push((0,en.issue)(`${a}/pageId`,"genpage-embed-shape",`genPage.pageId must be the id (a GUID) of a generative page, got ${s.pageId===void 0?"nothing":JSON.stringify(s.pageId)}`)),s.inputData!==void 0&&!De(s.inputData)&&i.push((0,en.issue)(`${a}/inputData`,"genpage-embed-shape",`genPage.inputData must be a JSON object \u2014 the page reads it as pageInput.data \u2014 got ${SS(s.inputData)}`));for(let p of Object.keys(s))h9.has(p)||i.push((0,en.issue)(u9.JsonPointer.append(a,p),"genpage-embed-unknown-key",`'${p}' is not a genPage property (pageId, inputData), and would be SILENTLY DROPPED at serialization.`))}gd(t)||i.push((0,en.issue)(`${r}/fieldName`,"genpage-embed-bound",`a generative-page embed is an unbound control, but this one is bound to column '${t.fieldName}'. Set fieldName to null, or embed the page in a new cell.`)),t.classId!==void 0&&NS(t.classId)!==B.CUSTOM_CONTROL_CLASS_ID&&i.push((0,en.issue)(`${r}/classId`,"genpage-embed-class-id",`a generative-page embed is the custom control {${B.CUSTOM_CONTROL_CLASS_ID}}, but classId is ${JSON.stringify(t.classId)}. Omit classId (the SDK defaults it) or set it to that class.`));let l=Zh(e);l!=="Main"&&i.push((0,en.issue)(a,"genpage-embed-main-form-only",`a generative page can be embedded only in a Main form, as in the maker portal; this is a ${l} form.`));let u=Xl(t);u!==void 0&&!Cr(u)&&i.push((0,en.issue)(`${r}/bag`,"genpage-embed-unique-id",`this embed's uniqueid ${JSON.stringify(u)} is not a GUID, and its page binding is keyed by it. Remove it from the bag (the SDK mints one) or set a GUID.`));let c=Ti(t);if(!c)return;let d=Yo(e.bag,c),f=d?Ql(d):void 0;d&&f?.kind==="none"?i.push((0,en.issue)(a,"genpage-embed-other-control",`this control is already bound to another custom control (${A9(d)}). genPage would have to delete that binding to take its place, so embed the page in a new cell instead.`)):f?.kind==="unsupported"&&i.push((0,en.issue)(a,"genpage-embed-unsupported-binding","this control already embeds a page through a binding genPage cannot represent exactly \u2014 a RefId or PageInput bound to a column, a RefId that is not a page id, or form factors that disagree. Taking it over would silently turn it into a static binding, so embed the page in a new cell instead.")),((o=n.get(c))!==null&&o!==void 0?o:0)>1&&i.push((0,en.issue)(`${r}/bag`,"genpage-embed-duplicate-unique-id",`this embed's uniqueid {${c}} is also carried by another control on the form, so both would share one binding. Author the copy without its bag and the SDK mints a new identity for it.`))}});var og=v(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});co.findMissingGenPages=co.GENPAGE_LOOKUP_CHUNK=void 0;var T9=Xt(),ig=ue();co.GENPAGE_LOOKUP_CHUNK=50;async function D9(e,t,r){let n=[...new Set(t.map(o=>(0,ig.normalizeGuid)(o,"uxagentprojectid")))],i=new Set;for(let o=0;o<n.length;o+=co.GENPAGE_LOOKUP_CHUNK){let a=n.slice(o,o+co.GENPAGE_LOOKUP_CHUNK),s="/uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,ig.odataQuery)([["$select","uxagentprojectid"],["$filter",a.map(u=>`uxagentprojectid eq ${u}`).join(" or ")]]),l=await(0,T9.collectPages)(e,s,r);for(let u of l){let c=u.uxagentprojectid;typeof c=="string"&&c.trim()!==""&&i.add((0,ig.normalizeGuid)(c,"uxagentprojectid"))}}return n.filter(o=>!i.has(o))}co.findMissingGenPages=D9});var Zl=v(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.assertSystemFormKind=Ct.readSystemFormType=Ct.decodeCode=Ct.assertSystemFormRecordKind=Ct.describeSystemFormType=Ct.systemFormKindOf=Ct.SYSTEMFORM_KIND_MISMATCH_CODE=void 0;var PS=Q(),I9=ye(),OS=ue();Ct.SYSTEMFORM_KIND_MISMATCH_CODE="SYSTEMFORM_KIND_MISMATCH";var O9={0:"dashboard",10:"dashboard",2:"form",6:"form",7:"form",11:"form"},P9={0:"dashboard",1:"appointment book",2:"Main form",3:"mini campaign form",4:"preview form",5:"mobile express form",6:"Quick View form",7:"Quick Create form",8:"dialog",9:"task flow form",10:"interactive dashboard",11:"card form",12:"interactive Main form",13:"contextual dashboard",100:"other form",101:"Main form backup",102:"appointment book backup",103:"Power BI dashboard"};function bd(e){return Number.isInteger(e)?O9[e]:void 0}Ct.systemFormKindOf=bd;function RS(e){var t;return Number.isFinite(e)?`a ${(t=P9[e])!==null&&t!==void 0?t:"systemform"} (type ${e})`:"a systemform whose type could not be read"}Ct.describeSystemFormType=RS;function LS(e,t,r,n){let i=RS(r),o=bd(r);switch(n){case"fetch":return`Refusing to fetch systemform '${e}' as a ${t}: it is ${i}. Nothing was read into the workspace. `+(o?`Fetch it as a ${o}.`:Number.isFinite(r)?"The SDK does not model that kind: check the id.":"Check the id.");case"write":return`Refusing to write systemform '${e}' as a ${t}: it is ${i}. Nothing was written. Check the id: a local copy fetched by an SDK that did not check the kind can name a row of another kind \u2014 discard it with deleteArtifact('${t}', '${e}').`;case"delete":return`Refusing to delete systemform '${e}' as a ${t}: it is ${i}. Nothing was changed. Check the id.`;default:return`Refusing to ${n} systemform '${e}': it is ${i}, not a ${t}.`+(n==="set the security roles of"?" Nothing was written.":"")+" Check the id."}}function R9(e,t,r,n){let i=ag(e?.type);if(bd(i)!==r)throw new PS.SdkError(Ct.SYSTEMFORM_KIND_MISMATCH_CODE,LS(t,r,i,n));return i}Ct.assertSystemFormRecordKind=R9;function ag(e){if(typeof e=="number")return Number.isInteger(e)?e:NaN;if(typeof e!="string"||!/^\s*-?\d+\s*$/.test(e))return NaN;let t=Number(e);return Number.isInteger(t)?t:NaN}Ct.decodeCode=ag;async function L9(e,t){return await kS(e,t,!1)}Ct.readSystemFormType=L9;async function k9(e,t){return kS(e,t,!0)}async function kS(e,t,r){var n;let o=`/systemforms(${(0,OS.normalizeGuid)(t,"formId")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,OS.odataQuery)([["$select","type"]]),a=await e.get(o);if(!(r&&a.status===404))return(0,I9.ensureSuccess)(a,e.apiUrl(o)),ag((n=a.body)===null||n===void 0?void 0:n.type)}async function x9(e,t,r){let n=await k9(e,t);if(!(n===void 0||bd(n)===r))throw new PS.SdkError(Ct.SYSTEMFORM_KIND_MISMATCH_CODE,LS(t,r,n,"delete"))}Ct.assertSystemFormKind=x9});var lg=v(Mr=>{"use strict";Object.defineProperty(Mr,"__esModule",{value:!0});Mr.patchSystemForm=Mr.assertSystemFormContentUnchanged=Mr.readSystemFormRowEtag=Mr.unpublishedSystemFormPath=Mr.FORM_TYPE_IMMUTABLE_CODE=void 0;var tn=ye(),$9=ue(),vd=Q(),fo=Zl();Mr.FORM_TYPE_IMMUTABLE_CODE="FORM_TYPE_IMMUTABLE";function sg(e,t="formid"){return`/systemforms(${e})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,$9.odataQuery)([["$select",t]])}Mr.unpublishedSystemFormPath=sg;function xS(e,t){return(0,tn.readRowEtag)(e,"systemforms","formid",t)}Mr.readSystemFormRowEtag=xS;async function $S(e,t,r,n,i){(0,tn.requireEtag)(i,r,t);let o=(0,tn.ensureSuccess)(await e.get(n),e.apiUrl(n)),a=(0,fo.assertSystemFormRecordKind)(o.body,t,r,"write"),s=(0,tn.readEtag)(o);if(s===null)throw new vd.SdkError(tn.VERSION_CONFLICT_CODE,`Refusing to write ${r} '${t}': its current version could not be read, so the write could not be verified as conditional and would risk silently overwriting a concurrent edit.`);if(s!==i)throw new vd.SdkError(tn.VERSION_CONFLICT_CODE,`Version conflict writing ${r} '${t}': its formxml changed on the server since it was read (held ${i}, server ${s}). Re-fetch the ${r} and re-apply the change.`);return a}Mr.assertSystemFormContentUnchanged=$S;async function F9(e,t,r,n,i,o){(0,tn.requireEtag)(i,r,t);let a=await xS(e,t);if(a===null)throw new vd.SdkError(tn.VERSION_CONFLICT_CODE,`Refusing to write ${r} '${t}': its row version could not be read, so the write could not be made conditional and would risk silently overwriting a concurrent edit.`);let s=await $S(e,t,r,sg(t,"formid,type"),i);if(n.type!==void 0&&(0,fo.decodeCode)(n.type)!==s)throw new vd.SdkError(Mr.FORM_TYPE_IMMUTABLE_CODE,`Refusing to push ${r} '${t}': it would change it from ${(0,fo.describeSystemFormType)(s)} to ${(0,fo.describeSystemFormType)((0,fo.decodeCode)(n.type))}. The platform ignores a type change on an existing ${r}, so the push would report a change that did not happen. Nothing was written. Create a new ${r} of that type instead.`);let l=(0,tn.echoWrite)("formid",{"If-Match":a}),u=`/systemforms(${t})${l.query}`;return(0,tn.ensureSuccess)(await e.patch(u,n,l.options),e.apiUrl(u)),M9(e,t,r,o)}Mr.patchSystemForm=F9;async function M9(e,t,r,n){let i;try{let o=sg(t,n.select),a=(0,tn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=a.body,l=(0,tn.readEtag)(a),u=typeof s?.formid=="string"&&s.formid.replace(/[{}]/g,"").toLowerCase()===t,c=typeof s?.formxml=="string"&&s.formxml.trim()!=="",d=n.required.filter(m=>s?.[m]===void 0||s?.[m]===null),f=(0,fo.decodeCode)(s?.type),p=(0,fo.systemFormKindOf)(f)===r;if(l&&u&&c&&d.length===0&&p)return{id:t,etag:l,readBack:s};i=l?!u||!c?`the read did not return this ${r}'s document`:d.length>0?`the read did not return its ${d.join(", ")}`:`the read returned ${(0,fo.describeSystemFormType)(f)}, not a ${r}`:"the read returned no version"}catch(o){i=o instanceof Error?o.message:String(o)}return{id:t,etag:null,warnings:[`The ${r} was saved, but its new version could not be read (${i}). The SDK holds no version for it now, so the next push is refused: re-fetch the ${r} before editing it again.`]}}});var pg=v(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.getFormSecurityRoles=Pt.setFormSecurityRoles=Pt.formApi=Pt.readPrimaryCreateRefusal=Pt.FORM_GENPAGE_TARGET_UNVERIFIABLE=Pt.FORM_GENPAGE_TARGET_NOT_FOUND=void 0;var U9=Xt(),Et=ye(),rn=ue(),Xo=Q(),ug=lo(),MS=yd(),B9=og(),cg=lg(),eu=Zl();Pt.FORM_GENPAGE_TARGET_NOT_FOUND="FORM_GENPAGE_TARGET_NOT_FOUND";Pt.FORM_GENPAGE_TARGET_UNVERIFIABLE="FORM_GENPAGE_TARGET_UNVERIFIABLE";var US="formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber",q9={select:US,required:["name","type","objecttypecode"]},V9="formid,name,type,objecttypecode",G9=2,W9={Main:G9,QuickView:6,QuickCreate:7,Card:11},BS=new WeakMap;function z9(e){return typeof e=="object"&&e!==null?BS.get(e):void 0}Pt.readPrimaryCreateRefusal=z9;Pt.formApi={async get(e,t){let r=(0,rn.normalizeGuid)(t,"id"),n=`/systemforms(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,rn.odataQuery)([["$select",US]]),i=(0,Et.ensureSuccess)(await e.get(n),e.apiUrl(n));return(0,eu.assertSystemFormRecordKind)(i.body,r,"form","fetch"),{raw:i.body,etag:(0,Et.readEtag)(i)}},async list(e,t){var r;let n=!((r=t?.formTypes)===null||r===void 0)&&r.length?t.formTypes:["Main"],i=[...new Set(n.map(u=>W9[u]))],a=[i.length===1?`type eq ${i[0]}`:`(${i.map(u=>`type eq ${u}`).join(" or ")})`];t?.entityLogicalName&&a.push(`objecttypecode eq '${(0,rn.odataLiteral)(t.entityLogicalName)}'`);let s=`/systemforms${(0,rn.odataQuery)([["$select",V9],["$filter",a.join(" and ")]])}`;return(await(0,U9.collectPages)(e,s,"listArtifacts('form')")).map(u=>{var c,d;return{type:"form",id:(c=u.formid)!==null&&c!==void 0?c:"",name:(d=u.name)!==null&&d!==void 0?d:"",entityLogicalName:u.objecttypecode,isDirty:!1}})},async create(e,t,r){let n=FS(t);n!==void 0&&await qS(e,fg(n,"payload"),[]);let i=(0,Et.echoWrite)("formid"),o=`/systemforms${i.query}`,a=(0,Et.withClientMintedId)(t,"formid",r),s=Object.freeze({...a}),l=await(0,Et.resendDeadlockVictim)(()=>e.post(o,{...s},i.options));try{(0,Et.ensureSuccess)(l,e.apiUrl(o))}catch(u){throw typeof u=="object"&&u!==null&&BS.set(u,{status:l.status,sent:s,desiredId:r}),u}return{id:(0,Et.resolveCreatedId)(l,"formid","form",r),etag:(0,Et.readEtag)(l)}},async update(e,t,r,n){let i=(0,rn.normalizeGuid)(t,"id"),o=FS(r);return o!==void 0&&await H9(e,i,o,n),(0,cg.patchSystemForm)(e,i,"form",r,n,q9)},readContentThenToken(e,t){return Pt.formApi.get(e,t)},async delete(e,t){let r=(0,rn.normalizeGuid)(t,"id");return await(0,eu.assertSystemFormKind)(e,r,"form"),(0,Et.deleteRecord)(e,"systemforms",r)}};var dg="DisplayConditions";async function j9(e,t,r){var n,i,o,a;if(r.everyone&&r.roleIds&&r.roleIds.length>0)throw new Xo.InvalidArgumentError("setFormSecurityRoles: `everyone` and `roleIds` are mutually exclusive \u2014 the platform models <Everyone /> as a replacement for the <Role> list, not an addition to it.");let s=(0,rn.normalizeGuid)(t,"formId"),l=`/systemforms(${s})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,rn.odataQuery)([["$select","formid,formxml,type"]]),u=(0,Et.ensureSuccess)(await e.get(l),e.apiUrl(l));(0,eu.assertSystemFormRecordKind)(u.body,s,"form","set the security roles of");let c=(0,Et.readEtag)(u),d=u.body,f=d?.formxml;if(!f)throw new Xo.InvalidArgumentError(`form '${s}' returned no formxml, so its roles cannot be set`);let p=(0,ug.parseXmlRoot)(f,"<form/>"),m=p.ownerDocument;if(!m)throw new Xo.InvalidArgumentError(`form '${s}' produced no owner document`);let h=VS(p,dg),g=h?.hasAttribute("Order")&&(n=h.getAttribute("Order"))!==null&&n!==void 0?n:void 0,b=h?.getAttribute("FallbackForm")||void 0;h&&p.removeChild(h);let w=!!r.everyone||((o=(i=r.roleIds)===null||i===void 0?void 0:i.length)!==null&&o!==void 0?o:0)>0;if(!w&&(r.order!==void 0||r.fallbackForm!==void 0)){if(!h)throw new Xo.InvalidArgumentError("setFormSecurityRoles: `order`/`fallbackForm` were supplied without `roleIds` or `everyone`, but this form has no <DisplayConditions> to attach them to. Pass the roles as well.");r.order!==void 0&&h.setAttribute("Order",String(r.order)),r.fallbackForm!==void 0&&h.setAttribute("FallbackForm",String(r.fallbackForm)),p.appendChild(h)}else if(w){let I=m.createElement(dg),D=r.order!==void 0?String(r.order):g;D!==void 0&&I.setAttribute("Order",D);let O=r.fallbackForm!==void 0?String(r.fallbackForm):b??"false";if(I.setAttribute("FallbackForm",O),r.everyone)I.appendChild(m.createElement("Everyone"));else for(let $ of(a=r.roleIds)!==null&&a!==void 0?a:[]){let K=m.createElement("Role");K.setAttribute("Id",`{${(0,rn.normalizeGuid)($,"roleId")}}`),I.appendChild(K)}p.appendChild(I)}let A=(0,ug.serializeNode)(p);await(0,cg.assertSystemFormContentUnchanged)(e,s,"form",l,c);let L=await(0,cg.readSystemFormRowEtag)(e,s),R=`/systemforms(${s})`;(0,Et.ensureSuccess)(await e.patch(R,{formxml:A},{headers:{"Content-Type":"application/json","If-Match":(0,Et.requireEtag)(L,"form",s)}}),e.apiUrl(R))}Pt.setFormSecurityRoles=j9;function FS(e){let t=e?.formxml;return typeof t=="string"&&t.includes(MS.GENPAGE_CONTROL_NAME)?t:void 0}function fg(e,t){try{return(0,MS.activeEmbedBindings)(e)}catch(r){throw new Xo.SdkError(Pt.FORM_GENPAGE_TARGET_UNVERIFIABLE,`Refusing to push the form: the ${t} formxml could not be parsed, so the generative pages it embeds cannot be verified (${r instanceof Error?r.message:String(r)}).`)}}async function qS(e,t,r){let n=new Set(r.map(([a,s])=>`${a}|${s}`)),i=t.filter(([a,s])=>!n.has(`${a}|${s}`)).map(([,a])=>a);if(i.length===0)return;let o=await(0,B9.findMissingGenPages)(e,i,"form generative-page preflight");if(o.length>0)throw new Xo.SdkError(Pt.FORM_GENPAGE_TARGET_NOT_FOUND,`Refusing to push the form: it embeds generative page(s) ${o.map(a=>`'${a}'`).join(", ")} that do not exist in this environment. Push the page before the form that embeds it.`)}async function H9(e,t,r,n){var i;(0,Et.requireEtag)(n,"form",t);let o=`/systemforms(${t})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,rn.odataQuery)([["$select","formid,formxml,type"]]),a=(0,Et.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,eu.assertSystemFormRecordKind)(a.body,t,"form","write");let s=(0,Et.readEtag)(a);if(s===null||s!==n)throw new Xo.SdkError(Et.VERSION_CONFLICT_CODE,`Version conflict writing form '${t}': its formxml changed on the server since it was read (held ${n}, server ${s??"(unreadable)"}). Re-fetch the form and re-apply the change.`);let l=(i=a.body)===null||i===void 0?void 0:i.formxml,u=typeof l=="string"&&l!==""?fg(l,"server"):[];await qS(e,fg(r,"payload"),u)}function VS(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 K9(e,t){var r,n;let i=(0,rn.normalizeGuid)(t,"formId"),o=`/systemforms(${i})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,rn.odataQuery)([["$select","formid,formxml,type"]]),a=(0,Et.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,eu.assertSystemFormRecordKind)(a.body,i,"form","read the security roles of");let s=(r=a.body)===null||r===void 0?void 0:r.formxml;if(!s)return;let l=(0,ug.parseXmlRoot)(s,"<form/>"),u=VS(l,dg);if(!u)return;let c=[],d=!1,f=u.childNodes;for(let m=0;m<f.length;m+=1){let h=f[m];if(h.nodeType!==1)continue;let g=h;if(g.tagName==="Everyone")d=!0;else if(g.tagName==="Role"){let b=(n=g.getAttribute("Id"))!==null&&n!==void 0?n:"";b&&c.push(b.replace(/[{}]/g,"").toLowerCase())}}let p=u.getAttribute("Order");return{...d?{everyone:!0}:{},...c.length>0?{roleIds:c}:{},fallbackForm:u.getAttribute("FallbackForm")==="true",...p!==null&&p!==""?{order:Number(p)}:{}}}Pt.getFormSecurityRoles=K9});var mg=v(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.deleteSolution=me.getDeploymentSettingsTemplate=me.importSolution=me.exportSolution=me.removeSolutionComponent=me.addSolutionComponent=me.setSolutionVersion=me.createSolution=me.createPublisher=me.getSolution=me.fetchSolutionComponents=me.resolveGenPageComponentType=me.SolutionComponentType=void 0;var J9=Xt(),Lt=ye(),nr=ue(),Y9=lt(),Gt=Q();me.SolutionComponentType={SavedQuery:26,Workflow:29,SavedQueryVisualization:59,SystemForm:60,AppModule:80};var Q9=[me.SolutionComponentType.SavedQuery,me.SolutionComponentType.Workflow,me.SolutionComponentType.SavedQueryVisualization,me.SolutionComponentType.SystemForm,me.SolutionComponentType.AppModule],GS="uxagentproject",WS=new WeakMap;async function YS(e){var t;let r=WS.get(e);if(r!==void 0)return r;let n=`/EntityDefinitions(LogicalName='${GS}')${(0,nr.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status===404)return;(0,Lt.ensureSuccess)(i,e.apiUrl(n));let o=(t=i.body)===null||t===void 0?void 0:t.ObjectTypeCode;if(typeof o!="number"||!Number.isInteger(o)||o<=0)throw new Gt.SdkError("GENPAGE_COMPONENT_TYPE_UNRESOLVED",`A generative page's solution component type \u2014 the ObjectTypeCode of '${GS}' \u2014 could not be read: its metadata answered without a usable value (${JSON.stringify(o)}). Without it a solution's generative pages cannot be told apart from other components. Retry.`);return WS.set(e,o),o}me.resolveGenPageComponentType=YS;var zS=1,jS=0;async function X9(e,t){let r=(0,nr.normalizeGuid)(t,"solutionId"),n=await YS(e),o=[zS,...Q9,...n===void 0?[]:[n]].map(c=>`componenttype eq ${c}`).join(" or "),a=`/solutioncomponents${(0,nr.odataQuery)([["$select","objectid,componenttype,rootcomponentbehavior"],["$filter",`_solutionid_value eq ${r} and (${o})`]])}`,s=await(0,J9.collectPages)(e,a,"fetchSolutionComponents"),l=[];for(let c of s){if(typeof c.objectid!="string")continue;let d=Number(c.componenttype);if(d===zS){let f=c.rootcomponentbehavior;(f===jS||f===String(jS))&&l.push({objectId:c.objectid,componentType:d,includesAllSubcomponents:!0});continue}l.push({objectId:c.objectid,componentType:d,...n!==void 0&&d===n?{genPage:!0}:{}})}let u=c=>c.objectId.toLowerCase().replace(/^\{|\}$/g,"");return l.sort((c,d)=>c.componentType-d.componentType||(u(c)<u(d)?-1:u(c)>u(d)?1:0))}me.fetchSolutionComponents=X9;function Z9(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 e5(e,t){var r,n,i,o,a,s,l,u,c,d;let f=String(t??"").trim();if(!f)throw new Gt.InvalidArgumentError("getSolution: a solution unique name or id is required.");let p=Z9(f)?`solutionid eq ${(0,nr.normalizeGuid)(f,"solutionId")}`:`uniquename eq '${(0,nr.odataLiteral)(f)}'`,m=`/solutions${(0,nr.odataQuery)([["$select","solutionid,uniquename,friendlyname,version,ismanaged"],["$expand","publisherid($select=publisherid,uniquename,customizationprefix,customizationoptionvalueprefix)"],["$filter",p]])}`,b=((n=(r=(0,Lt.ensureSuccess)(await e.get(m),e.apiUrl(m)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0];if(!b?.solutionid)throw new Gt.InvalidArgumentError(`No solution found for '${t}'.`);let w=b.publisherid;if(!w?.publisherid)throw new Gt.InvalidArgumentError(`Solution '${(i=b.uniquename)!==null&&i!==void 0?i:t}' returned no owning publisher, so its customization prefix cannot be determined; refusing to report an empty prefix that could be mistaken for "no prefix".`);if(!("customizationprefix"in w))throw new Gt.InvalidArgumentError(`Solution '${(o=b.uniquename)!==null&&o!==void 0?o:t}' returned a publisher without a customizationprefix property (partial expansion), so its prefix cannot be determined.`);return{solutionId:(0,nr.normalizeGuid)(b.solutionid,"solutionId"),uniqueName:(a=b.uniquename)!==null&&a!==void 0?a:"",friendlyName:(s=b.friendlyname)!==null&&s!==void 0?s:"",version:(l=b.version)!==null&&l!==void 0?l:"",isManaged:!!b.ismanaged,publisherId:(0,nr.normalizeGuid)(w.publisherid,"publisherId"),publisherUniqueName:(u=w.uniquename)!==null&&u!==void 0?u:"",publisherPrefix:(c=w.customizationprefix)!==null&&c!==void 0?c:"",publisherOptionValuePrefix:(d=w.customizationoptionvalueprefix)!==null&&d!==void 0?d:0}}me.getSolution=e5;async function t5(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,Lt.ensureSuccess)(await(0,Lt.resendDeadlockVictim)(()=>e.post("/publishers",{...n})),e.apiUrl("/publishers")),o=(0,Lt.readCreatedId)(i,"publisherid");if(!o)throw new Gt.InvalidArgumentError(`Dataverse did not return an id for publisher '${t.uniqueName}'`);return{id:o,uniqueName:t.uniqueName}}me.createPublisher=t5;async function r5(e,t){var r;let n=(0,nr.normalizeGuid)(t.publisherId,"publisherId"),i={uniquename:t.uniqueName,friendlyname:t.friendlyName,version:(r=t.version)!==null&&r!==void 0?r:"1.0.0.0","[email protected]":`/publishers(${n})`};t.description&&(i.description=t.description);let o=(0,Lt.ensureSuccess)(await e.post("/solutions",i),e.apiUrl("/solutions")),a=(0,Lt.readCreatedId)(o,"solutionid");if(!a)throw new Gt.InvalidArgumentError(`Dataverse did not return an id for solution '${t.uniqueName}'`);return{id:a,uniqueName:t.uniqueName}}me.createSolution=r5;async function n5(e,t,r){let i=`/solutions(${(0,nr.normalizeGuid)(t,"solutionId")})`;(0,Lt.ensureSuccess)(await e.patch(i,{version:r}),e.apiUrl(i))}me.setSolutionVersion=n5;async function i5(e,t){var r;let i={ComponentId:(0,nr.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,Lt.ensureSuccess)(await e.post("/AddSolutionComponent",i),e.apiUrl("/AddSolutionComponent"))}me.addSolutionComponent=i5;async function o5(e,t,r,n){let o={SolutionComponent:{"@odata.type":"Microsoft.Dynamics.CRM.solutioncomponent",solutioncomponentid:(0,nr.normalizeGuid)(t,"componentId")},ComponentType:r,SolutionUniqueName:n};(0,Lt.ensureSuccess)(await e.post("/RemoveSolutionComponent",o),e.apiUrl("/RemoveSolutionComponent"))}me.removeSolutionComponent=o5;async function a5(e,t){var r,n;let i={SolutionName:t.solutionName,Managed:(r=t.managed)!==null&&r!==void 0?r:!1},a=(n=(0,Lt.ensureSuccess)(await e.post("/ExportSolution",i),e.apiUrl("/ExportSolution")).body)===null||n===void 0?void 0:n.ExportSolutionFile;if(!a)throw new Gt.InvalidArgumentError(`ExportSolution returned no file for '${t.solutionName}'`);return{base64:a}}me.exportSolution=a5;async function s5(e,t){let r=[["overwriteUnmanagedCustomizations","overwrote unmanaged customizations made over the solution's components"],["publishWorkflows","activated the solution's workflows"]];for(let[a,s]of r)if(typeof t?.[a]!="boolean")throw new Gt.InvalidArgumentError(`importSolution: '${a}' is required and must be true or false (it was ${String(t?.[a])}). It used to default to true, which ${s} unless the caller said otherwise. Nothing was imported.`);let n=t.deploymentSettings===void 0?void 0:b5(t.deploymentSettings),i={OverwriteUnmanagedCustomizations:t.overwriteUnmanagedCustomizations,PublishWorkflows:t.publishWorkflows,CustomizationFile:t.base64,ImportJobId:t.importJobId?(0,nr.normalizeGuid)(t.importJobId,"importJobId"):(0,Y9.newId)()};if(!n)return(0,Lt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{};if(n.variables.length===0&&n.references.length===0)return(0,Lt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:{environmentVariables:[],connectionReferences:[]}};let o=[];try{let a=await QS(e,t.base64,tu,o),{parameters:s,applied:l}=v5(a,n);return i.ComponentParameters=s,(0,Lt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:l,...o.length>0?{warnings:o}:{}}}catch(a){throw(0,Gt.withCleanupWarnings)(a,o)}}me.importSolution=s5;var tu="importSolution",HS="getDeploymentSettingsTemplate";async function l5(e,t){var r;let n=t?.base64;if(typeof n!="string"||n.length===0)throw new Gt.InvalidArgumentError(`${HS}: 'base64' must be the solution package \u2014 a non-empty base64 string, e.g. exportSolution's result (it was ${(r=JSON.stringify(n))!==null&&r!==void 0?r:String(n)})`);let i=[];try{let o=await QS(e,n,HS,i),a=wd(o.variables,l=>l.SchemaName).map(({SchemaName:l,DefaultValue:u,TypeId:c,IsRequired:d})=>({SchemaName:l,Value:"",...u!==void 0?{DefaultValue:u}:{},...c!==void 0?{TypeId:c}:{},...d!==void 0?{IsRequired:d}:{}})),s=wd(o.references,l=>l.LogicalName).map(({LogicalName:l,ConnectorId:u})=>({LogicalName:l,ConnectionId:"",...u!==void 0?{ConnectorId:u}:{}}));return{settings:{EnvironmentVariables:a,ConnectionReferences:s},...i.length>0?{warnings:i}:{}}}catch(o){throw(0,Gt.withCleanupWarnings)(o,i)}}me.getDeploymentSettingsTemplate=l5;function wd(e,t){return[...e].sort((r,n)=>{let i=t(r).toLowerCase(),o=t(n).toLowerCase();return i<o?-1:i>o?1:0})}function Zo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Rt(e,t=120){var r;let n=(r=JSON.stringify(e))!==null&&r!==void 0?r:String(e);return n.length>t?`${n.slice(0,t)}\u2026`:n}async function QS(e,t,r,n){var i;let a=(i=(0,Lt.ensureSuccess)(await e.post("/StageSolution",{CustomizationFile:t}),e.apiUrl("/StageSolution")).body)===null||i===void 0?void 0:i.StageSolutionResults;try{return c5(a,r)}finally{await u5(e,Zo(a)?a.StageSolutionUploadId:void 0,n)}}async function u5(e,t,r){let n;try{n=(0,nr.normalizeGuid)(t,"StageSolutionUploadId")}catch{r.push(`StageSolution's reply named no usable staging upload id (${Rt(t,60)}), so the staged copy of the package it may have stored (a stagesolutionupload row of yours) could not be deleted.`);return}let i=`/stagesolutionuploads(${n})`;try{let o=await e.delete(i);o.status!==404&&(0,Lt.ensureSuccess)(o,e.apiUrl(i))}catch(o){r.push(`The staged copy of the package (stagesolutionupload ${n}) could not be deleted: ${o instanceof Error?o.message:String(o)}. It stays until it is deleted (DELETE ${i}).`)}}function rr(e,t){return new Gt.SdkError("SOLUTION_STAGING_UNREADABLE",`${e}: StageSolution's reply could not be read \u2014 ${t}.${e===tu?" Nothing was imported.":""}`)}function KS(e){return!Array.isArray(e)||e.length===0?"none":`${e.slice(0,5).map(r=>Zo(r)&&typeof r.Message=="string"?r.Message:Rt(r,200)).join("; ")}${e.length>5?` (+${e.length-5} more)`:""}`}function c5(e,t){if(!Zo(e))throw rr(t,`it holds no StageSolutionResults (${Rt(e,60)})`);let r=e.StageSolutionStatus;if(r==="Failed"||r===0)throw new Gt.SdkError("SOLUTION_STAGING_FAILED",`${t}: the package did not pass StageSolution in this environment (status ${Rt(r)}). Missing dependencies: ${KS(e.MissingDependencies)}. Validation: ${KS(e.SolutionValidationResults)}.${t===tu?" Its components cannot be checked against deploymentSettings. Nothing was imported.":" Stage it in the environment it was exported from."}`);if(r!=="Passed"&&r!==1)throw rr(t,`StageSolutionStatus is ${Rt(r)}, neither "Passed" nor "Failed"`);let n=e.SolutionComponentsDetails;if(!Array.isArray(n))throw rr(t,`SolutionComponentsDetails is not a list (${Rt(n,60)})`);let i=[],o=[],a=new Set,s=new Set;return n.forEach((l,u)=>{let c=`SolutionComponentsDetails[${u}]`;if(!Zo(l))throw rr(t,`${c} is not an object`);if(typeof l.ComponentTypeName!="string")throw rr(t,`${c}.ComponentTypeName is not a string`);let d=l.ComponentTypeName.toLowerCase();if(d!=="environmentvariabledefinition"&&d!=="connectionreference")return;let f=d5(l.Attributes,`${c}.Attributes`,t),p=(m,h)=>{let g=f.get(m);if(g==null){if(h)throw rr(t,`${c}.${m} is missing`);return}if(typeof g!="string"||h&&g.length===0)throw rr(t,`${c}.${m} is not ${h?"a non-empty string":"a string"}`);return g};if(d==="environmentvariabledefinition"){let m=p("schemaname",!0);if(a.has(m.toLowerCase()))throw rr(t,`${c}.schemaname '${m}' is listed twice`);a.add(m.toLowerCase());let h=p("defaultvalue",!1),g=f5(f.get("type"),`${c}.type`,t),b=p5(f.get("isrequired"),`${c}.isrequired`,t);i.push({SchemaName:m,...h!==void 0?{DefaultValue:h}:{},...g!==void 0?{TypeId:g}:{},...b!==void 0?{IsRequired:b}:{}})}else{let m=p("connectionreferencelogicalname",!0);if(s.has(m.toLowerCase()))throw rr(t,`${c}.connectionreferencelogicalname '${m}' is listed twice`);s.add(m.toLowerCase());let h=p("connectorid",!1);o.push({LogicalName:m,...h!==void 0?{ConnectorId:h}:{}})}}),{variables:i,references:o}}function d5(e,t,r){if(!Zo(e)||!Array.isArray(e.Keys)||!Array.isArray(e.Values))throw rr(r,`${t} is not { Keys: [...], Values: [...] }`);let{Keys:n,Values:i}=e;if(n.length!==i.length)throw rr(r,`${t} has ${n.length} keys but ${i.length} values`);let o=new Map;return n.forEach((a,s)=>{if(typeof a!="string")throw rr(r,`${t}.Keys[${s}] is not a string`);if(o.has(a))throw rr(r,`${t}.Keys lists '${a}' twice`);o.set(a,i[s])}),o}function f5(e,t,r){if(e!=null){if(typeof e=="number"&&Number.isSafeInteger(e))return e;if(typeof e=="string"&&/^\d{1,15}$/.test(e))return Number(e);throw rr(r,`${t} is not a whole number (${Rt(e,40)})`)}}function p5(e,t,r){if(e!=null){if(typeof e=="boolean")return e;if(typeof e=="string"&&/^(true|false)$/i.test(e))return e.toLowerCase()==="true";throw rr(r,`${t} is not true or false (${Rt(e,40)})`)}}var m5=new Set(["EnvironmentVariables","ConnectionReferences","Workflows","CanvasApps","CopilotAgents","$schema"]),h5=["Workflows","CanvasApps","CopilotAgents"],g5=new Set(["SchemaName","Value","DefaultValue","TypeId","IsRequired","Name"]),y5=new Set(["LogicalName","ConnectionId","ConnectorId"]);function tr(e,t){return new Gt.InvalidArgumentError(`${tu}: deploymentSettings is not a deployment-settings file this SDK applies \u2014 ${e} ${t}. Nothing was imported.`)}function b5(e){let t="deploymentSettings";if(!Zo(e))throw tr(t,`must be an object \u2014 the settings file, parsed (it was ${Rt(e,40)})`);for(let l of Object.keys(e))if(!m5.has(l))throw tr(`${t}.${l}`,"is not part of the format (EnvironmentVariables, ConnectionReferences; Workflows, CanvasApps and CopilotAgents only empty; $schema)");for(let l of h5){let u=e[l];if(u!==void 0&&!(Array.isArray(u)&&u.length===0))throw tr(`${t}.${l}`,"is a pac feature this SDK does not apply: only an empty list is accepted")}if(e.$schema!==void 0&&typeof e.$schema!="string")throw tr(`${t}.$schema`,"must be a string");let r=l=>{let u=e[l];if(u===void 0)return[];if(!Array.isArray(u))throw tr(`${t}.${l}`,`must be a list (it was ${Rt(u,40)})`);return u.map((c,d)=>{if(!Zo(c))throw tr(`${t}.${l}[${d}]`,`must be an object (it was ${Rt(c,40)})`);return c})},n=(l,u,c)=>{let d=l[u];if(typeof d!="string"||d.length===0)throw tr(c,`must be a non-empty string (it was ${Rt(d,40)})`);if(d.trim()!==d)throw tr(c,`must not begin or end with whitespace (it was ${Rt(d,60)})`);return d},i=(l,u,c)=>{if(l.has(u.toLowerCase()))throw tr(c,`names '${u}' a second time (names are case-insensitive)`);l.add(u.toLowerCase())},o={variables:[],references:[]},a=new Set;r("EnvironmentVariables").forEach((l,u)=>{let c=`${t}.EnvironmentVariables[${u}]`;for(let f of Object.keys(l))if(!g5.has(f))throw tr(`${c}.${f}`,"is not part of a variable (SchemaName, Value; DefaultValue, TypeId, IsRequired, Name)");let d=n(l,"SchemaName",`${c}.SchemaName`);if(i(a,d,`${c}.SchemaName`),typeof l.Value!="string")throw tr(`${c}.Value`,`must be a string \u2014 empty to override nothing (it was ${Rt(l.Value,40)})`);l.Value.length>0&&o.variables.push({name:d,value:l.Value})});let s=new Set;return r("ConnectionReferences").forEach((l,u)=>{let c=`${t}.ConnectionReferences[${u}]`;for(let p of Object.keys(l))if(!y5.has(p))throw tr(`${c}.${p}`,p==="ConnectionInstance"?"is pac's connection-instance feature, which this SDK does not apply":"is not part of a connection reference (LogicalName, ConnectionId, ConnectorId)");let d=n(l,"LogicalName",`${c}.LogicalName`);i(s,d,`${c}.LogicalName`);let f=l.ConnectionId;if(typeof f!="string")throw tr(`${c}.ConnectionId`,`must be a string \u2014 empty to bind nothing (it was ${Rt(f,40)})`);if(f.trim()!==f)throw tr(`${c}.ConnectionId`,`must not begin or end with whitespace (it was ${Rt(f,60)})`);if(l.ConnectorId!==void 0&&typeof l.ConnectorId!="string")throw tr(`${c}.ConnectorId`,`must be a string (it was ${Rt(l.ConnectorId,40)})`);f.length>0&&o.references.push({name:d,connectionId:f,...l.ConnectorId?{connectorId:l.ConnectorId}:{}})}),o}function JS(e,t=20){return e.length===0?"none":`${e.slice(0,t).join(", ")}${e.length>t?` (+${e.length-t} more)`:""}`}function v5(e,t){var r;let n=new Map(e.variables.map(l=>[l.SchemaName.toLowerCase(),l])),i=new Map(e.references.map(l=>[l.LogicalName.toLowerCase(),l])),o=[],a=[],s={environmentVariables:[],connectionReferences:[]};for(let l of t.variables){let u=n.get(l.name.toLowerCase());if(!u){o.push(`EnvironmentVariables: '${l.name}' is not a variable of the package`);continue}a.push({"@odata.type":"Microsoft.Dynamics.CRM.environmentvariablevalue",schemaname:u.SchemaName,value:l.value}),s.environmentVariables.push(u.SchemaName)}for(let l of t.references){let u=i.get(l.name.toLowerCase());if(!u){o.push(`ConnectionReferences: '${l.name}' is not a connection reference of the package`);continue}if(l.connectorId!==void 0&&l.connectorId.toLowerCase()!==((r=u.ConnectorId)===null||r===void 0?void 0:r.toLowerCase())){o.push(`ConnectionReferences: '${l.name}' names connector '${l.connectorId}', but the package's reference is for ${u.ConnectorId?`'${u.ConnectorId}'`:"no connector"}`);continue}a.push({"@odata.type":"Microsoft.Dynamics.CRM.connectionreference",connectionreferencelogicalname:u.LogicalName,connectionid:l.connectionId,...u.ConnectorId!==void 0?{connectorid:u.ConnectorId}:{}}),s.connectionReferences.push(u.LogicalName)}if(o.length>0){let l=o.join("; "),u=JS(wd(e.variables,d=>d.SchemaName).map(d=>d.SchemaName)),c=JS(wd(e.references,d=>d.LogicalName).map(d=>d.LogicalName));throw new Gt.InvalidArgumentError(`${tu}: deploymentSettings does not match the package \u2014 ${l}. The package's variables: ${u}; its connection references: ${c}. Nothing was imported.`)}return{parameters:a,applied:s}}async function w5(e,t){let n=`/solutions(${(0,nr.normalizeGuid)(t,"solutionId")})`;(0,Lt.ensureSuccess)(await e.delete(n),e.apiUrl(n))}me.deleteSolution=w5});var nN=v(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.recoverFormCreate=ut.solutionMembershipProblem=ut.formWriteMismatches=ut.validateExistingForm=ut.formExistsAtId=ut.isFormRecordAt=ut.MAIN_FORM_TYPE=void 0;var cs=ue(),XS=Xt(),ZS=mg();ut.MAIN_FORM_TYPE=2;function Cd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ed(e){return e instanceof Error?e.message:String(e)}function hg(e,t){if(typeof e!="string"||typeof t!="string")return!1;try{return(0,cs.normalizeGuid)(e,"a GUID")===(0,cs.normalizeGuid)(t,"a GUID")}catch{return!1}}function gg(e,t){return Cd(e)&&hg(e.formid,t)}ut.isFormRecordAt=gg;async function C5(e,t){try{return gg((await e()).raw,t)}catch{return!1}}ut.formExistsAtId=C5;function eN(e,t){let r=e.raw;if(!Cd(r))return{problem:"it is not a record"};if(!gg(r,t))return{problem:"its formid is not the id this create sent"};if(r.type!==ut.MAIN_FORM_TYPE)return{problem:`its type is not ${ut.MAIN_FORM_TYPE} (a Main form)`};if(typeof r.objecttypecode!="string")return{problem:"its objecttypecode is not a string"};if(typeof r.name!="string")return{problem:"its name is not a string"};if(typeof r.formxml!="string"||r.formxml.length===0)return{problem:"its formxml is not a non-empty string"};if(typeof r.formpresentation!="number")return{problem:"its formpresentation is not a number"};if(typeof r.formactivationstate!="number")return{problem:"its formactivationstate is not a number"};for(let o of["uniquename","description"]){let a=r[o];if(a!=null&&typeof a!="string")return{problem:`its ${o} is neither a string nor null`}}let n=r["@odata.etag"];if(n!==void 0&&typeof n!="string")return{problem:"its @odata.etag is not a string"};if(n!==void 0&&e.etag!==null&&e.etag!==n)return{problem:"the ETag header and the @odata.etag of the body disagree"};let i=e.etag;return i===null?{problem:"the read carries no concurrency token"}:i.trim()===""||i.trim()==="*"?{problem:"its concurrency token is blank or a wildcard"}:{record:r,etag:i}}ut.validateExistingForm=eN;function tN(e,t){let r=[];for(let i of["formxml","name","objecttypecode","type"])e[i]!==t[i]&&r.push(i);let n=t.description;if(n!==void 0){let i=e.description;typeof n=="string"&&(n===""?i==null||i==="":i===n)||r.push("description")}return r}ut.formWriteMismatches=tN;async function rN(e,t){let r=e.solutionName;if(r)try{let n=await(0,XS.collectPages)(e,`/solutions${(0,cs.odataQuery)([["$select","solutionid,uniquename"],["$filter",`uniquename eq '${(0,cs.odataLiteral)(r)}'`]])}`,"createRecovery solution lookup");if(n.length!==1)return`the configured solution '${r}' resolves to ${n.length} solutions, not exactly one`;let[i]=n,o;return Cd(i)&&typeof i.uniquename=="string"&&typeof i.solutionid=="string"&&i.uniquename.toLowerCase()===r.toLowerCase()&&(o=(0,cs.normalizeGuid)(i.solutionid,"solutionid")),o===void 0?`the configured solution '${r}' did not resolve to a valid solution of that name`:(await(0,XS.collectPages)(e,`/solutioncomponents${(0,cs.odataQuery)([["$select","objectid,componenttype,_solutionid_value"],["$filter",`_solutionid_value eq ${o} and componenttype eq ${ZS.SolutionComponentType.SystemForm} and objectid eq ${t}`]])}`,"createRecovery solution membership")).some(l=>Cd(l)&&l.componenttype===ZS.SolutionComponentType.SystemForm&&hg(l.objectid,t)&&hg(l._solutionid_value,o))?void 0:`the form is not a component of the configured solution '${r}'`}catch(n){return`membership in the configured solution '${r}' could not be established (${Ed(n)})`}}ut.solutionMembershipProblem=rN;async function E5(e){try{return await A5(e)}catch(t){return{refused:`the recovery could not be completed (${Ed(t)})`}}}ut.recoverFormCreate=E5;async function A5(e){let{client:t,read:r,sent:n,authoredFormType:i,project:o}=e;if(i!=="Main"||n.type!==ut.MAIN_FORM_TYPE)return{refused:`only a Main form is adopted (this one is authored as ${String(i)})`};let a=n.formid;if(typeof a!="string")return{refused:"the create sent no formid to look for"};let s;try{s=await r()}catch(f){return{refused:`the existing row could not be read (${Ed(f)})`}}let l=eN(s,a);if("problem"in l)return{refused:`the existing row cannot be trusted: ${l.problem}`};let u=tN(l.record,n);if(u.length>0)return{refused:`the existing row is not what this create wrote (it differs in ${u.join(", ")})`};let c;try{c=o(l.record)}catch(f){return{refused:`the existing row could not be read into a form (${Ed(f)})`}}let d=await rN(t,a);return d!==void 0?{refused:d}:{adopted:{artifact:c,etag:l.etag}}}});var Nd=v(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.disassociateRecords=je.associateRecords=je.createRecordsBulk=je.upsertRecord=je.queryAllRecords=je.queryRecords=je.getRecord=je.deleteRecord=je.updateRecord=je.createRecord=void 0;var S5=Xt(),Cn=ye(),Wt=ue(),Ad=Q(),jn=sd();function Sd(e){let t=e,r=!1,n={};for(let i of Object.keys(t)){let o=t[i];Array.isArray(o)&&o.every(a=>typeof a=="number")?(n[i]=o.join(","),r=!0):n[i]=o}return r?n:e}async function N5(e,t,r){let i=`/${await(0,jn.resolveEntitySetName)(e,t)}`,o=(0,Cn.ensureSuccess)(await e.post(i,Sd(r)),e.apiUrl(i)),a=(0,Cn.readCreatedId)(o,`${t}id`);if(!a)throw new Ad.InvalidArgumentError(`Dataverse did not return an id for the created '${t}' row`);return{id:a,entityType:t}}je.createRecord=N5;async function _5(e,t,r,n){let i=(0,Wt.normalizeGuid)(r,"id"),a=`/${await(0,jn.resolveEntitySetName)(e,t)}(${i})`;(0,Cn.ensureSuccess)(await e.patch(a,Sd(n)),e.apiUrl(a))}je.updateRecord=_5;async function T5(e,t,r){let n=(0,Wt.normalizeGuid)(r,"id"),o=`/${await(0,jn.resolveEntitySetName)(e,t)}(${n})`;(0,Cn.ensureSuccess)(await e.delete(o),e.apiUrl(o))}je.deleteRecord=T5;async function D5(e,t,r,n){var i;let o=(0,Wt.normalizeGuid)(r,"id"),a=await(0,jn.resolveEntitySetName)(e,t),s=(0,Wt.odataQuery)([["$select",n&&n.length>0?n.join(","):void 0]]),l=`/${a}(${o})${s}`;return(i=(0,Cn.ensureSuccess)(await e.get(l),e.apiUrl(l)).body)!==null&&i!==void 0?i:{}}je.getRecord=D5;function I5(e){return e?.fetchXml?(0,Wt.odataQuery)([["fetchXml",e.fetchXml]]):(0,Wt.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 iN(e,t,r){var n,i;if(r?.paginate){if(r.top!==void 0)throw new Ad.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 Ad.InvalidArgumentError("queryRecords: `paginate` is not supported with `fetchXml` \u2014 FetchXML paging uses a paging cookie (page / fetchxmlpagingcookie), not @odata.nextLink. Page the FetchXML manually, or use an OData query.")}let a=`/${await(0,jn.resolveEntitySetName)(e,t)}${I5(r)}`;return r?.paginate?(0,S5.collectPages)(e,a,"queryRecords"):(i=(n=(0,Cn.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]}je.queryRecords=iN;async function O5(e,t,r){return iN(e,t,{...r,paginate:!0})}je.queryAllRecords=O5;function P5(e){if("id"in e)return`(${(0,Wt.normalizeGuid)(e.id,"id")})`;let t=typeof e.value=="string"?`'${(0,Wt.odataPathLiteral)(e.value)}'`:e.value;return`(${(0,Wt.assertODataName)(e.key,"alternate key name")}=${t})`}async function R5(e,t,r,n){let i=P5(r),a=`/${await(0,jn.resolveEntitySetName)(e,t)}${i}`,s=(0,Cn.ensureSuccess)(await e.patch(a,Sd(n)),e.apiUrl(a)),l=s.status===201,u=(0,Cn.readCreatedId)(s,`${t}id`);return{id:u??("id"in r?(0,Wt.normalizeGuid)(r.id,"id"):""),created:l}}je.upsertRecord=R5;async function L5(e,t,r){var n,i;if(r.length===0)return[];let o=await(0,jn.resolveEntitySetName)(e,t),a=r.map(c=>({"@odata.type":`Microsoft.Dynamics.CRM.${t}`,...Sd(c)})),s=`/${o}/Microsoft.Dynamics.CRM.CreateMultiple`,u=(i=(n=(0,Cn.ensureSuccess)(await e.post(s,{Targets:a}),e.apiUrl(s)).body)===null||n===void 0?void 0:n.Ids)!==null&&i!==void 0?i:[];if(u.length!==r.length)throw new Ad.InvalidArgumentError(`CreateMultiple on '${t}' returned ${u.length} id(s) for ${r.length} row(s)`);return u}je.createRecordsBulk=L5;async function k5(e,t,r,n){let i=(0,Wt.normalizeGuid)(r,"id"),o=(0,Wt.normalizeGuid)(n.targetId,"targetId"),a=await(0,jn.resolveEntitySetName)(e,t),s=await(0,jn.resolveEntitySetName)(e,n.targetEntity),l=(0,Wt.assertODataName)(n.relationshipName,"relationshipName"),u=`/${a}(${i})/${l}/$ref`,c={"@odata.id":e.apiUrl(`/${s}(${o})`)};(0,Cn.ensureSuccess)(await e.post(u,c),e.apiUrl(u))}je.associateRecords=k5;async function x5(e,t,r,n,i){let o=(0,Wt.normalizeGuid)(r,"id"),a=(0,Wt.normalizeGuid)(i,"targetId"),s=await(0,jn.resolveEntitySetName)(e,t),l=(0,Wt.assertODataName)(n,"relationshipName"),u=`/${s}(${o})/${l}(${a})/$ref`;(0,Cn.ensureSuccess)(await e.delete(u),e.apiUrl(u))}je.disassociateRecords=x5});var Td=v(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.base64ToUtf8=Hn.base64ToBytes=Hn.bytesToBase64=Hn.utf8ToBase64=void 0;var yg=32768,Er="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function _d(){return globalThis}function $5(e){let t=[];for(let r=0;r<e.length;r+=1){let n=e.charCodeAt(r);if(n>=55296&&n<=56319){let i=r+1<e.length?e.charCodeAt(r+1):0;i>=56320&&i<=57343?(n=(n-55296<<10)+(i-56320)+65536,r+=1):n=65533}else n>=56320&&n<=57343&&(n=65533);n<128?t.push(n):n<2048?t.push(192|n>>6,128|n&63):n<65536?t.push(224|n>>12,128|n>>6&63,128|n&63):t.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|n&63)}return Uint8Array.from(t)}function F5(e){let t="";for(let r=0;r<e.length;r+=yg)t+=String.fromCharCode(...e.subarray(r,r+yg));return t}function M5(e){let t="";for(let r=0;r<e.length;r+=1){let n=String.fromCharCode(e.charCodeAt(r)&255);if(n==="=")break;n==="-"?t+="+":n==="_"?t+="/":Er.indexOf(n)>=0&&(t+=n)}for(t.length%4===1&&(t=t.slice(0,-1));t.length%4!==0;)t+="=";return t}function U5(e){let t="",r=0;for(;r+2<e.length;r+=3){let i=e[r]<<16|e[r+1]<<8|e[r+2];t+=Er[i>>18&63]+Er[i>>12&63]+Er[i>>6&63]+Er[i&63]}let n=e.length-r;if(n===1){let i=e[r]<<16;t+=`${Er[i>>18&63]}${Er[i>>12&63]}==`}else if(n===2){let i=e[r]<<16|e[r+1]<<8,o=Er[i>>18&63],a=Er[i>>12&63],s=Er[i>>6&63];t+=`${o}${a}${s}=`}return t}function B5(e){let t=e.endsWith("==")?2:e.endsWith("=")?1:0,r=e.length/4*3-t,n=new Uint8Array(r>0?r:0),i=0;for(let o=0;o<e.length;o+=4){let a=Er.indexOf(e[o])<<18|Er.indexOf(e[o+1])<<12|(e[o+2]==="="?0:Er.indexOf(e[o+2]))<<6|(e[o+3]==="="?0:Er.indexOf(e[o+3]));i<r&&(n[i++]=a>>16&255),i<r&&(n[i++]=a>>8&255),i<r&&(n[i++]=a&255)}return n}function q5(e){let t=_d();if(t.Buffer)return t.Buffer.from(e,"utf8").toString("base64");let r=t.TextEncoder;return oN(r?new r().encode(e):$5(e))}Hn.utf8ToBase64=q5;function oN(e){let t=_d();return t.Buffer?t.Buffer.from(e).toString("base64"):t.btoa?t.btoa(F5(e)):U5(e)}Hn.bytesToBase64=oN;function aN(e){let t=_d();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"base64"));let r=M5(e);if(t.atob){let n=t.atob(r);return Uint8Array.from(n,i=>i.charCodeAt(0))}return B5(r)}Hn.base64ToBytes=aN;function V5(e){let t=[],r="",n=()=>{r+=String.fromCharCode(...t),t.length=0},i=a=>{if(a>65535){let s=a-65536;t.push(55296+(s>>10),56320+(s&1023))}else t.push(a);t.length>=yg&&n()},o=0;for(;o<e.length;){let a=e[o],s=0,l=0,u=128,c=191;if(a<128){i(a),o+=1;continue}else if(a>=194&&a<=223)s=1,l=a&31;else if(a>=224&&a<=239)s=2,l=a&15,u=a===224?160:128,c=a===237?159:191;else if(a>=240&&a<=244)s=3,l=a&7,u=a===240?144:128,c=a===244?143:191;else{i(65533),o+=1;continue}let d=o+1,f=!0;for(let p=0;p<s;p+=1,d+=1){let m=d<e.length?e[d]:-1;if(m<u||m>c){f=!1;break}u=128,c=191,l=l<<6|m&63}f?(i(l),o=d):(i(65533),o=d)}return n(),r}function G5(e){let t=_d();return t.Buffer?t.Buffer.from(e,"base64").toString("utf8"):V5(aN(e))}Hn.base64ToUtf8=G5});var cN=v(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.deleteWebResource=Kn.getWebResource=Kn.updateWebResource=Kn.createWebResource=void 0;var W5=Kr(),ru=ye(),Dd=ue(),z5=Td(),sN=Q(),j5={html:1,css:2,js:3,xml:4,png:5,jpg:6,gif:7,xsl:9,ico:10,svg:11,resx:12};function lN(e){if(e.contentBase64!==void 0)return e.contentBase64;if(e.content!==void 0)return(0,z5.utf8ToBase64)(e.content)}async function uN(e,t){return(0,W5.publishWebResourceById)(e,t)}async function H5(e,t){var r;let n=lN(t);if(n===void 0)throw new sN.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:j5[t.type],content:n};t.description&&(i.description=t.description);let o=(0,ru.ensureSuccess)(await e.post("/webresourceset",i),e.apiUrl("/webresourceset")),a=(0,ru.readCreatedId)(o,"webresourceid");if(!a)throw new sN.InvalidArgumentError(`Dataverse did not return an id for web resource '${t.name}'`);return t.publish!==!1&&await uN(e,a),{id:a,name:t.name}}Kn.createWebResource=H5;async function K5(e,t,r){let n=(0,Dd.normalizeGuid)(t,"id"),i={},o=lN(r);o!==void 0&&(i.content=o),r.displayName!==void 0&&(i.displayname=r.displayName),r.description!==void 0&&(i.description=r.description);let a=`/webresourceset(${n})`;(0,ru.ensureSuccess)(await e.patch(a,i),e.apiUrl(a)),r.publish!==!1&&await uN(e,n)}Kn.updateWebResource=K5;async function J5(e,t){var r;let i=`/webresourceset(${(0,Dd.normalizeGuid)(t,"id")})${(0,Dd.odataQuery)([["$select","name,displayname,webresourcetype,content,description"]])}`;return(r=(0,ru.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)!==null&&r!==void 0?r:{}}Kn.getWebResource=J5;async function Y5(e,t){let n=`/webresourceset(${(0,Dd.normalizeGuid)(t,"id")})`;(0,ru.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Kn.deleteWebResource=Y5});var Id=v(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.applyAppSettings=At.setAppSetting=At.readAppSettings=At.resolveSettingDefinitions=At.APP_SETTING_UNSET=At.APP_SETTING_OFF=At.APP_SETTING_ON=At.HEADER_AND_NAVIGATION_REFRESH=void 0;var ds=ye(),Di=ue();At.HEADER_AND_NAVIGATION_REFRESH="HeaderAndNavigationRefresh";At.APP_SETTING_ON="2";At.APP_SETTING_OFF="1";At.APP_SETTING_UNSET="0";function pN(e,t){return"/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Di.odataQuery)([["$select",e],["$filter",t]])}async function mN(e,t){var r,n;let i=[...new Set(t.filter(Boolean))],o=new Map;if(i.length===0)return o;let a=i.map(c=>`uniquename eq '${(0,Di.odataLiteral)(c)}'`).join(" or "),s=`/settingdefinitions${(0,Di.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",a]])}`,u=((n=(r=(0,ds.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]).filter(Boolean);for(let c of u)c.uniquename&&o.set(c.uniquename,c);return o}At.resolveSettingDefinitions=mN;async function Q5(e,t){var r,n,i,o;let a=(0,Di.normalizeGuid)(t,"App id"),s=pN("appsettingid,value,_settingdefinitionid_value",`_parentappmoduleid_value eq ${a}`),u=((n=(r=(0,ds.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(f=>f._settingdefinitionid_value).filter(Boolean))],d=new Map;if(c.length>0){let f=c.map(h=>`settingdefinitionid eq ${(0,Di.normalizeGuid)(h,"Setting definition id")}`).join(" or "),p=`/settingdefinitions${(0,Di.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",f]])}`,m=(0,ds.ensureSuccess)(await e.get(p),e.apiUrl(p));for(let h of((o=(i=m.body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[]).filter(Boolean))h.settingdefinitionid&&d.set(h.settingdefinitionid.toLowerCase(),h)}return u.map(f=>{var p,m,h,g,b;let w=d.get(((p=f._settingdefinitionid_value)!==null&&p!==void 0?p:"").toLowerCase());return{id:(m=f.appsettingid)!==null&&m!==void 0?m:"",name:(g=(h=w?.uniquename)!==null&&h!==void 0?h:f._settingdefinitionid_value)!==null&&g!==void 0?g:"",value:(b=f.value)!==null&&b!==void 0?b:"",...w?.displayname?{displayName:w.displayname}:{}}})}At.readAppSettings=Q5;async function dN(e,t,r){var n,i,o;let a=pN("appsettingid,value",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${r}`),l=((i=(n=(0,ds.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]).filter(Boolean)[0];return l?.appsettingid?{id:l.appsettingid,value:(o=l.value)!==null&&o!==void 0?o:""}:void 0}async function hN(e,t,r,n){let i=(0,Di.normalizeGuid)(t,"App id"),a=(await mN(e,[r])).get(r),s=a?.settingdefinitionid;if(!s)throw new Error(`App setting '${r}' is not available in this environment: no settingdefinition row has that uniquename. The feature may be version-gated or its solution may not be installed.`);let l=(0,Di.normalizeGuid)(s,"Setting definition id"),u=await dN(e,i,l);if(u)return fN(e,u,n);let c="/appsettings",d={"[email protected]":`/appmodules(${i})`,"[email protected]":`/settingdefinitions(${l})`,value:n},f,p;try{if(f=await e.post(c,d),f.status>=200&&f.status<300)return"created"}catch(h){p=h}let m;try{m=await dN(e,i,l)}catch{m=void 0}if(m)return fN(e,m,n);throw f&&(0,ds.ensureSuccess)(f,e.apiUrl(c)),p}At.setAppSetting=hN;async function fN(e,t,r){if(t.value===r)return"unchanged";let n=`/appsettings(${(0,Di.normalizeGuid)(t.id,"App setting id")})`;return(0,ds.ensureSuccess)(await e.patch(n,{value:r}),e.apiUrl(n)),"updated"}async function X5(e,t,r){var n;let i=[];for(let[o,a]of Object.entries(r??{}))try{await hN(e,t,o,a)}catch(s){i.push(`App setting '${o}' was not applied: ${(n=s?.message)!==null&&n!==void 0?n:String(s)} The app was created; set it later with setAppSetting().`)}return i}At.applyAppSettings=X5});var Pd=v(Od=>{"use strict";Object.defineProperty(Od,"__esModule",{value:!0});Od.HEADER_NAV_BOOLEAN_RULE=void 0;Od.HEADER_NAV_BOOLEAN_RULE="headerAndNavigationRefresh-must-be-boolean"});var Cg=v(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.compileGenPage=Oe.legacyEnumsNeeded=Oe.createGenPageTypeScriptLoader=Oe.acceptGenPageTypeScript=Oe.isLoadableGenPageOutput=Oe.runtimeTypesImportSpans=Oe.GENPAGE_RUNTIME_TYPES_END=Oe.GENPAGE_RUNTIME_TYPES_BEGIN=Oe.GENPAGE_TYPESCRIPT_VERSION=void 0;var fs=Q();Oe.GENPAGE_TYPESCRIPT_VERSION="5.8.3";Oe.GENPAGE_RUNTIME_TYPES_BEGIN="// --- BEGIN GENERATED RUNTIME TYPES ---";Oe.GENPAGE_RUNTIME_TYPES_END="// --- END GENERATED RUNTIME TYPES ---";var En="./RuntimeTypes",Z5="'\"`",gN=/\s/;function e8(e){return e===10||e===13||e===8232||e===8233}function t8(e,t){let r=[];e.lastIndex=0;for(let n=e.exec(t);n!==null;n=e.exec(t))r.push(n.index);return r}function wN(e){let t=[],r=En.length;for(let l=e.indexOf(En);l!==-1;l=e.indexOf(En,l+1)){let u=l-1;u>=0&&Z5.includes(e[u])&&e[u+1+r]===e[u]&&t.push(u)}let n=[];if(t.length===0)return n;let i=-1,o=l=>{if(i<l)for(i=l;i<e.length&&e[i]!=="'"&&e[i]!=='"';)i+=1;return i},a=-1,s=l=>{for(;a+1<t.length&&t[a+1]<=l;)a+=1;return a>=0?t[a]:-1/0};for(let l=e.indexOf("import");l!==-1;){let u=l+1;if(l+6<e.length&&gN.test(e[l+6])){let c=s(o(l+6));if(c>=l+8){let d=c+2+r;for(e[d]===";"&&(d+=1);d<e.length&&gN.test(e[d]);)d+=1;n.push({start:l,end:d}),u=d}}l=e.indexOf("import",u)}return n}Oe.runtimeTypesImportSpans=wN;var r8=/\b(?:import\s*['"]|export\s)/;function n8(e){let t=t8(/from\s+['"]/g,e);if(t.length===0)return!1;let r=/\bimport\s/g,n=-1,i=0;for(let o=r.exec(e);o!==null;o=r.exec(e)){let a=o.index+7;if(a>n)for(n=a;n<e.length&&!e8(e.charCodeAt(n));)n+=1;for(;i<t.length&&t[i]<a+1;)i+=1;if(i<t.length&&t[i]<n)return!0}return!1}function i8(e){return e!==void 0&&e!==""&&(r8.test(e)||n8(e))}Oe.isLoadableGenPageOutput=i8;var yN=["transpileModule","createSourceFile","createProgram","getParseTreeNode","flattenDiagnosticMessageText","forEachChild","getModifiers","canHaveModifiers","isImportDeclaration","isExportDeclaration","isExportAssignment","isStringLiteral"];function CN(e){var t;let r=s=>s!==null&&(typeof s=="object"||typeof s=="function")?s:void 0,n=r(e);n&&typeof n.transpileModule!="function"&&(n=(t=r(n.default))!==null&&t!==void 0?t:n);let i=n?yN.filter(s=>typeof n?.[s]!="function"):[...yN];if(!n||i.length>0)throw new fs.SdkError("GENPAGE_COMPILER_INVALID",`The TypeScript compiler supplied as MakerSdkOptions.typescript is not the typescript module (missing ${i.join(", ")}). Pass the 'typescript' package's module object, loadNodeTypeScript from '@maker-studio/cds-maker-sdk/node', or \u2014 in a bare engine \u2014 globalThis.ts after evaluating typescript@${Oe.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js.`);let o=typeof n.version=="string"?n.version:"",a=Oe.GENPAGE_TYPESCRIPT_VERSION.split(".").slice(0,2).join(".");if(o.split(".").slice(0,2).join(".")!==a)throw new fs.SdkError("GENPAGE_COMPILER_VERSION",`The TypeScript compiler supplied as MakerSdkOptions.typescript is version '${o||"unknown"}', but generative pages are compiled with ${a}.x \u2014 the version the maker portal itself uses (${Oe.GENPAGE_TYPESCRIPT_VERSION}). Another version can emit different JavaScript for the same page. Supply typescript@${Oe.GENPAGE_TYPESCRIPT_VERSION}.`);return n}Oe.acceptGenPageTypeScript=CN;function o8(e){let t;return()=>{if(!t){if(e===void 0)return Promise.reject(new fs.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`This push must compile a generative page, but no TypeScript compiler was supplied. Pass MakerSdkOptions.typescript \u2014 in Node, loadNodeTypeScript from '@maker-studio/cds-maker-sdk/node'; in a bare engine, globalThis.ts after evaluating typescript@${Oe.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js. Nothing was written.`));t=Promise.resolve().then(()=>typeof e=="function"?e():e).then(CN).catch(r=>{throw t=void 0,r instanceof fs.SdkError?r:new fs.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`The TypeScript compiler could not be loaded, so a generative page cannot be compiled (${r instanceof Error?r.message:String(r)}). Nothing was written.`)})}return t}}Oe.createGenPageTypeScriptLoader=o8;var EN=e=>`${e.kind}:${e.pos}:${e.end}`;function a8(e,t){return()=>r=>{let n=i=>{let o=e.getParseTreeNode(i);o&&t.add(EN(o)),e.forEachChild(i,n)};return n(r),r}}function wg(e){return{target:e.ScriptTarget.ES5,module:e.ModuleKind.ES2020,jsx:e.JsxEmit.React}}var s8=2301;function bN(e,t,r){var n;let i=e.transpileModule(t,{compilerOptions:wg(e),reportDiagnostics:!0,...r?{transformers:{after:[a8(e,r)]}}:{}}),o=((n=i.diagnostics)!==null&&n!==void 0?n:[]).filter(a=>a.category===e.DiagnosticCategory.Error).map(a=>{let s=a.file&&typeof a.start=="number"?a.file.getLineAndCharacterOfPosition(a.start):{line:0,character:0};return{line:s.line+1,column:s.character+1,rule:"genpage-source-syntax",code:a.code,message:e.flattenDiagnosticMessageText(a.messageText,`-`)}});return{code:i.outputText,diagnostics:o}}var vN=e=>e.startsWith(".")||e.startsWith("/"),bg={line:1,column:1};function vg(e,t){let r=o=>{let a=t.getLineAndCharacterOfPosition(o.getStart(t));return{line:a.line+1,column:a.character+1}},n=o=>(e.isImportDeclaration(o)||e.isExportDeclaration(o))&&o.moduleSpecifier&&e.isStringLiteral(o.moduleSpecifier)?o.moduleSpecifier.text:void 0,i=o=>t.statements.filter(a=>e.isImportDeclaration(a)&&n(a)===o);return{statement(o,a){let s=t.statements.find(l=>n(l)===o&&(a==="import"?e.isImportDeclaration(l):e.isExportDeclaration(l)));return s?r(s):bg},element(o,a){var s;for(let l of i(o)){let u=(s=l.importClause)===null||s===void 0?void 0:s.namedBindings,c=u&&e.isNamedImports(u)?u.elements.find(d=>d.name.text===a):void 0;if(c)return r(c)}return this.statement(o,"import")},binding(o){var a,s;for(let l of t.statements)if(e.isImportDeclaration(l)&&l.importClause){let u=l.importClause,c=u.namedBindings,d=((a=u.name)===null||a===void 0?void 0:a.text)===o?u.name:c&&e.isNamespaceImport(c)&&c.name.text===o?c.name:c&&e.isNamedImports(c)?c.elements.find(f=>f.name.text===o):void 0;if(d)return r(d)}else{if((e.isFunctionDeclaration(l)||e.isClassDeclaration(l))&&((s=l.name)===null||s===void 0?void 0:s.text)===o)return r(l.name);if(e.isVariableStatement(l)){let u=l.declarationList.declarations.find(c=>e.isIdentifier(c.name)&&c.name.text===o);if(u)return r(u.name)}}return bg}}}function l8(e,t,r,n){var i,o;let a=[],s=vg(e,r),l=(m,h,g)=>{a.push({...m,rule:h,code:0,message:g})},u=(m,h)=>{var g;return(e.canHaveModifiers(m)?(g=e.getModifiers(m))!==null&&g!==void 0?g:[]:[]).some(b=>b.kind===h)},c=(m,h)=>l(m,"genpage-relative-import",`'${h}' cannot resolve at runtime: the page is loaded as a single module from a blob URL, so the only relative import it may have is './RuntimeTypes'`),d="genpage-runtime-types-import-form",f=!1,p=new Set;for(let m of t.statements){if(e.isExportAssignment(m)){f=f||!m.isExportEquals;continue}if(e.isFunctionDeclaration(m)||e.isClassDeclaration(m)){u(m,e.SyntaxKind.ExportKeyword)&&u(m,e.SyntaxKind.DefaultKeyword)&&(f=!0),m.name&&p.add(m.name.text);continue}if(e.isExportDeclaration(m)){let w=m.exportClause;w&&e.isNamedExports(w)&&w.elements.some(A=>A.name.text==="default")&&(f=!0);let E=m.moduleSpecifier&&e.isStringLiteral(m.moduleSpecifier)?m.moduleSpecifier.text:void 0;E===En?l(s.statement(E,"export"),d,"a page cannot re-export from './RuntimeTypes': that module does not exist at runtime"):E!==void 0&&vN(E)&&c(s.statement(E,"export"),E);continue}if(!e.isImportDeclaration(m)||!e.isStringLiteral(m.moduleSpecifier))continue;let h=m.moduleSpecifier.text,g=m.importClause;if(h!==En){vN(h)&&c(s.statement(h,"import"),h),g?.name&&p.add(g.name.text);let w=g?.namedBindings;w&&e.isNamespaceImport(w)?p.add(w.name.text):w&&e.isNamedImports(w)&&w.elements.forEach(E=>p.add(E.name.text));continue}if(!g){l(s.statement(h,"import"),d,"a side-effect import of './RuntimeTypes' cannot resolve at runtime; import the names it declares");continue}g.name&&l(s.binding(g.name.text),d,"'./RuntimeTypes' has no default export at runtime; import its names");let b=g.namedBindings;if(b&&e.isNamespaceImport(b))l(s.binding(b.name.text),d,"a namespace import of './RuntimeTypes' is undefined at runtime \u2014 its enums are inlined under their own names; import the names instead");else if(b&&e.isNamedImports(b))for(let w of b.elements){let E=w.name.text,A=(o=(i=w.propertyName)===null||i===void 0?void 0:i.text)!==null&&o!==void 0?o:E,L=s.element(h,E);A!==E?l(L,d,`'${A} as ${E}' would be undefined at runtime: the enum is inlined as '${A}', so import it under its own name`):n?.text?n.enums.has(E)||l(L,"genpage-runtime-types-unresolved",`'${E}' is imported from './RuntimeTypes' as a VALUE, but the runtime types define no value of that name \u2014 only the choice enums of the page's data sources are values. Import a type with 'import type'.`):l(L,"genpage-runtime-types-unresolved",`'${E}' is imported from './RuntimeTypes' as a VALUE, but the page has no data sources, so no runtime types are inlined and the import reaches the runtime, which cannot load it. Import it with 'import type', or add the table it belongs to to dataSources.`)}}if(f||l(bg,"genpage-no-default-export","the page has no default export \u2014 the runtime renders the module's default export as the page component"),n?.text)for(let m of p)n.enums.has(m)&&l(s.binding(m),"genpage-runtime-types-collision",`'${m}' is declared at the page's module scope and is also one of its inlined choice enums, so the compiled page would declare it twice and fail to load. Rename the page's binding, or import the enum from './RuntimeTypes'.`);return a}function AN(e,t,r){let n,i=()=>{if(!n){let m={getSourceFile:g=>g===t.fileName?t:void 0,getDefaultLibFileName:()=>"lib.d.ts",writeFile:()=>{},getCurrentDirectory:()=>"",getCanonicalFileName:g=>g,useCaseSensitiveFileNames:()=>!0,getNewLine:()=>`-`,fileExists:g=>g===t.fileName,readFile:()=>{},directoryExists:()=>!0,getDirectories:()=>[]},h={...r,noLib:!0,noResolve:!0,allowJs:!0,types:[],alwaysStrict:!0,moduleDetection:e.ModuleDetectionKind.Force};n=e.createProgram({rootNames:[t.fileName],options:h,host:m})}return n},o,a=()=>(o||(o=i().getTypeChecker()),o),s,l=()=>{if(!s){s=new Map;try{for(let m of i().getSemanticDiagnostics(t))m.code===s8&&typeof m.start=="number"&&s.set(m.start,e.flattenDiagnosticMessageText(m.messageText," "))}catch{}}return s},u=m=>e.isImportSpecifier(m)?m.parent.parent.parent:e.isImportClause(m)?m.parent:e.isNamespaceImport(m)?m.parent.parent:void 0,c=m=>{let h=u(m);return h!==void 0&&e.isImportDeclaration(h)&&e.isStringLiteral(h.moduleSpecifier)&&h.moduleSpecifier.text===En},d=m=>{var h;for(let g=m;g;g=g.parent)if(e.canHaveModifiers(g)&&((h=e.getModifiers(g))!==null&&h!==void 0?h:[]).some(b=>b.kind===e.SyntaxKind.DeclareKeyword))return!0;return!1},f=m=>d(m)||e.isImportEqualsDeclaration(m)&&(m.isTypeOnly||e.isExternalModuleReference(m.moduleReference))||e.isImportClause(m)&&m.isTypeOnly||e.isNamespaceImport(m)&&m.parent.isTypeOnly||e.isImportSpecifier(m)&&(m.isTypeOnly||m.parent.parent.isTypeOnly),p=m=>{var h;return((h=m?.declarations)!==null&&h!==void 0?h:[]).some(g=>!c(g)&&!f(g))};return{pageOwns:m=>{let h=m.parent;return p(e.isShorthandPropertyAssignment(h)&&h.name===m?a().getShorthandAssignmentValueSymbol(h):a().getSymbolAtLocation(m))},pageOwnsLocalExport:m=>p(a().getExportSpecifierLocalTargetSymbol(m)),initializerShadow:m=>l().get(m.getStart(t))}}function u8(e,t,r,n){let i=[],o=r?.enums;if(!o||o.size===0)return i;let a=(u,c,d)=>{let f=t.getLineAndCharacterOfPosition(u.getStart(t));i.push({line:f.line+1,column:f.character+1,rule:c,code:0,message:d})},s=AN(e,t,wg(e)),l=u=>{let c,d;if(e.isPropertyAccessExpression(u)&&e.isIdentifier(u.expression))c=u.expression,d=u.name.text;else if(e.isElementAccessExpression(u)&&e.isIdentifier(u.expression)){let p=u.argumentExpression;e.isStringLiteral(p)||e.isNoSubstitutionTemplateLiteral(p)?(c=u.expression,d=p.text):e.isNumericLiteral(p)&&(c=u.expression,d=String(Number(p.text)))}let f=c&&o.has(c.text)&&n.has(EN(u))&&!s.pageOwns(c)?o.get(c.text):void 0;if(c&&f&&d!==void 0){let p=e.isPropertyAccessExpression(u)?`${f.name}.${d}`:`${f.name}[${JSON.stringify(d)}]`,m=Object.prototype.hasOwnProperty.call(f.runtime,d)?f.runtime[d]:void 0,h=f.labels.get(d),g;m===void 0?g={rule:"genpage-enum-member-unknown",message:`${p} is undefined at runtime: '${f.name}' has no member '${d}' in this environment's metadata \u2014 members are the column's choice labels, so a renamed or differently localized label no longer matches. Known: ${[...f.labels.keys()].map(w=>`'${w}'`).join(", ")}`}:h&&typeof m!="number"?g={rule:"genpage-enum-member-clobbered",message:`${p} is the string '${String(m)}' at runtime, not a choice value: the label '${d}' looks like a number, and another option's reverse mapping overwrites it. Use the choice's numeric value instead.`}:h&&h.length>1&&(g={rule:"genpage-enum-member-ambiguous",message:`${p} labels more than one choice (${h.join(", ")}); the compiled value is whichever option comes last. Use the choice's numeric value instead.`});let b=g?s.initializerShadow(c):void 0;g&&b!==void 0?a(u,"genpage-enum-initializer-shadowed",`${p} does not read the choice enum at runtime. ${b} (TS2301): the ES5 emit moves an instance field's initializer into the constructor, where that parameter or local shadows '${c.text}'. If you meant the constructor's '${c.text}', move the assignment into the constructor body, or make it a parameter property and read \`this.${c.text}\`. If you meant the choice enum, rename the constructor's parameter or local.`):g&&a(u,g.rule,g.message)}e.forEachChild(u,l)};return l(t),i}function c8(e,t){return e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!1,e.ScriptKind.JS).statements.some(n=>(e.isImportDeclaration(n)||e.isExportDeclaration(n))&&n.moduleSpecifier!==void 0&&e.isStringLiteral(n.moduleSpecifier)&&n.moduleSpecifier.text===En)}function d8(e,t){let r=e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),n=new Set(r.statements.filter(s=>e.isImportDeclaration(s)&&e.isStringLiteral(s.moduleSpecifier)&&s.moduleSpecifier.text===En).map(s=>s.getStart(r))),i=!0,o="",a=0;for(let s of wN(t))n.has(s.start)||(i=!1),o+=t.slice(a,s.start),a=s.end;return o+=t.slice(a),{code:o,exact:i}}function SN(e,t,r){if(!r||r.size===0)return[];let n=AN(e,t,{...wg(e),target:e.ScriptTarget.ESNext}),i=new Set,o=s=>{var l,u;let c=s.parent;if(e.isImportSpecifier(c)){let d=c.parent.parent.parent;e.isImportDeclaration(d)&&e.isStringLiteral(d.moduleSpecifier)&&d.moduleSpecifier.text===En&&((l=c.propertyName)!==null&&l!==void 0?l:c.name)===s&&i.add(s.text);return}if(e.isExportSpecifier(c)){!(c.parent.parent.moduleSpecifier!==void 0)&&((u=c.propertyName)!==null&&u!==void 0?u:c.name)===s&&!n.pageOwnsLocalExport(c)&&i.add(s.text);return}e.isPropertyAccessExpression(c)&&c.name===s||e.isBindingElement(c)&&c.propertyName===s||e.isLabeledStatement(c)||e.isBreakOrContinueStatement(c)||n.pageOwns(s)||i.add(s.text)},a=s=>{e.isIdentifier(s)&&r.has(s.text)&&o(s),e.forEachChild(s,a)};return a(t),[...r.keys()].filter(s=>i.has(s))}Oe.legacyEnumsNeeded=SN;function f8(e,t,r){if(!e?.text||!t||r.length===0)return e;let n=new Map(e.enums),i=e.text;for(let o of r){let a=t.get(o);a&&(i+=a.declaration,n.set(o,a.model))}return{text:i,enums:n}}function p8(e,t,r,n){let i=new Set,o=bN(e,t,i);if(o.diagnostics.length>0)return o;let a=e.createSourceFile("page.tsx",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.TSX),s=e.createSourceFile("page.js",o.code,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),l=f8(r,n,SN(e,s,n)),u=[...l8(e,s,a,l),...u8(e,a,l,i)];if(!l?.text)return{code:o.code,diagnostics:u};let c=bN(e,l.text);if(c.diagnostics.length>0)throw new fs.SdkError("GENPAGE_RUNTIME_TYPES_INVALID",`The generated runtime types do not compile (${c.diagnostics.map(m=>`${m.line}:${m.column} ${m.message}`).join("; ")}). This is an SDK defect: the page was not written.`);let d=d8(e,o.code),f=d.code;return u.length===0&&!d.exact?u.push({...vg(e,a).statement(En,"import"),rule:"genpage-runtime-types-import-form",code:0,message:"the maker portal's patch would remove more than this './RuntimeTypes' import: a comment or other text before it contains the word 'import', and the pattern would delete from there \u2014 taking the code in between with it. Reword or move that text."}):u.length===0&&c8(e,f)&&u.push({...vg(e,a).statement(En,"import"),rule:"genpage-runtime-types-import-form",code:0,message:"this './RuntimeTypes' import is not one the maker portal's patch can remove (a comment holding a quote inside it stops the pattern), so it would reach the runtime, which cannot load it. Write it on one line, as 'import { name } from './RuntimeTypes';'."}),{code:[Oe.GENPAGE_RUNTIME_TYPES_BEGIN,c.code,Oe.GENPAGE_RUNTIME_TYPES_END,f].join(`+`).slice(1)){let l=s.indexOf(":");l>0&&(o[s.slice(0,l).trim()]=s.slice(l+1).trim())}let a=i===""?void 0:i;if(i!=="")try{a=JSON.parse(i)}catch{}return{status:e.status,headers:o,body:a}}Or.partResponse=tN;async function h9(e,t,r){let{body:n,batchId:i,contentIds:o}=Ng(e,t),a=await e.postBatch(n,i),s=e.apiUrl("/$batch"),l=_g(a.body,o),u=l?.find(c=>c.status<200||c.status>=300);if(u&&(0,Sg.ensureSuccess)(tN(u),e.apiUrl(t[o.indexOf(u.contentId)].path)),(0,Sg.ensureSuccess)(a,s),!l||l.length!==t.length)throw new bo.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the $batch response ${l?`reported ${l.length} result(s) for ${t.length} operation(s)`:"could not be parsed"}, so the outcome is unknown`);return o.map(c=>l.find(d=>d.contentId===c))}Or.sendChangeSet=h9});var $d=v(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.updateTable=ie.deleteAlternateKey=ie.createAlternateKey=ie.deleteGlobalOptionSet=ie.createGlobalOptionSet=ie.deleteRelationship=ie.deleteColumn=ie.updateColumn=ie.deleteTable=ie.createRelationship=ie.insertStatusValue=ie.createCustomerColumn=ie.createColumns=ie.setColumnVisualization=ie.getColumnVisualization=ie.createColumn=ie.createTable=ie.resolveEntitySetName=ie.pluralFallback=void 0;var Se=fe(),te=oe(),ri=sa(),he=Q(),g9=Es(),y9={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 tt(e,t){return{"@odata.type":"Microsoft.Dynamics.CRM.Label",LocalizedLabels:b9(e,t)}}var rN=65535;function b9(e,t){let r=(o,a)=>({"@odata.type":"Microsoft.Dynamics.CRM.LocalizedLabel",Label:o,LanguageCode:a});if(typeof e=="string")return[r(e,t)];let n=Object.entries(e);if(!n.length)throw new he.InvalidArgumentError("a localized label must contain at least one language");let i=new Set;return n.map(([o,a])=>{if(!/^[1-9]\d*$/.test(o))throw new he.InvalidArgumentError(`localized label key '${o}' is not an LCID (expected a canonical positive integer, e.g. 1033)`);let s=Number(o);if(s>rN)throw new he.InvalidArgumentError(`localized label LCID ${s} is out of range (1-${rN})`);if(i.has(s))throw new he.InvalidArgumentError(`localized label LCID ${s} is specified more than once`);if(i.add(s),typeof a!="string")throw new he.InvalidArgumentError(`localized label for LCID ${s} must be a string`);return r(a,s)})}function sN(e){return typeof e=="string"?`${e}s`:Object.fromEntries(Object.entries(e).map(([t,r])=>{if(typeof r!="string")throw new he.InvalidArgumentError(`localized label for LCID ${t} must be a string`);return[t,`${r}s`]}))}ie.pluralFallback=sN;function fu(e){return{Value:e,CanBeChanged:!0,ManagedPropertyLogicalName:"canmodifyrequirementlevelsettings"}}var nN=["None","ApplicationRequired","Recommended"];function Ig(e){let t=e.indexOf("_");return t>0?e.slice(0,t):e}function iN(e,t,r){let n=e[t];n&&typeof n=="object"?n.Value=r:e[t]={Value:r}}function pu(e){let t=(0,Se.readCreatedId)(e,"MetadataId");if(!t)throw new he.InvalidArgumentError("Dataverse did not return a MetadataId for the created metadata component");return t}function v9(e,t,r){var n,i,o,a,s,l,u,c,d,f,m,p,h,g,b,w,C,S,O,L,I,D,P,x;if(t.defaultValue!==void 0&&e!=="boolean")throw new he.InvalidArgumentError(`createColumn: 'defaultValue' applies to boolean columns, but '${t.schemaName}' is of type '${e}'.`);if(t.integerFormat!==void 0&&e!=="integer")throw new he.InvalidArgumentError(`createColumn: 'integerFormat' applies to integer columns, but '${t.schemaName}' is of type '${e}'.`);switch(e){case"string":return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},MaxLength:(n=t.maxLength)!==null&&n!==void 0?n:100,FormatName:{Value:(i=t.stringFormat)!==null&&i!==void 0?i:"Text"}};case"memo":return{"@odata.type":"Microsoft.Dynamics.CRM.MemoAttributeMetadata",AttributeType:"Memo",AttributeTypeName:{Value:"MemoType"},MaxLength:(o=t.maxLength)!==null&&o!==void 0?o:2e3,Format:"TextArea"};case"integer":return{"@odata.type":"Microsoft.Dynamics.CRM.IntegerAttributeMetadata",AttributeType:"Integer",AttributeTypeName:{Value:"IntegerType"},Format:(a=t.integerFormat)!==null&&a!==void 0?a:"None",MinValue:(s=t.minValue)!==null&&s!==void 0?s:-2147483648,MaxValue:(l=t.maxValue)!==null&&l!==void 0?l:2147483647};case"bigint":return{"@odata.type":"Microsoft.Dynamics.CRM.BigIntAttributeMetadata",AttributeType:"BigInt",AttributeTypeName:{Value:"BigIntType"}};case"double":return{"@odata.type":"Microsoft.Dynamics.CRM.DoubleAttributeMetadata",AttributeType:"Double",AttributeTypeName:{Value:"DoubleType"},Precision:(u=t.precision)!==null&&u!==void 0?u:2,MinValue:(c=t.minValue)!==null&&c!==void 0?c:-1e11,MaxValue:(d=t.maxValue)!==null&&d!==void 0?d:1e11};case"decimal":return{"@odata.type":"Microsoft.Dynamics.CRM.DecimalAttributeMetadata",AttributeType:"Decimal",AttributeTypeName:{Value:"DecimalType"},Precision:(f=t.precision)!==null&&f!==void 0?f:2,MinValue:(m=t.minValue)!==null&&m!==void 0?m:-1e11,MaxValue:(p=t.maxValue)!==null&&p!==void 0?p:1e11};case"money":return{"@odata.type":"Microsoft.Dynamics.CRM.MoneyAttributeMetadata",AttributeType:"Money",AttributeTypeName:{Value:"MoneyType"},Precision:(h=t.precision)!==null&&h!==void 0?h:2,PrecisionSource:2,MinValue:(g=t.minValue)!==null&&g!==void 0?g:0,MaxValue:(b=t.maxValue)!==null&&b!==void 0?b:1e9};case"boolean":return{"@odata.type":"Microsoft.Dynamics.CRM.BooleanAttributeMetadata",AttributeType:"Boolean",AttributeTypeName:{Value:"BooleanType"},DefaultValue:(w=t.defaultValue)!==null&&w!==void 0?w:!1,OptionSet:{"@odata.type":"Microsoft.Dynamics.CRM.BooleanOptionSetMetadata",TrueOption:{Value:1,Label:tt((C=t.trueLabel)!==null&&C!==void 0?C:"Yes",r)},FalseOption:{Value:0,Label:tt((S=t.falseLabel)!==null&&S!==void 0?S:"No",r)}}};case"dateTime":return{"@odata.type":"Microsoft.Dynamics.CRM.DateTimeAttributeMetadata",AttributeType:"DateTime",AttributeTypeName:{Value:"DateTimeType"},Format:(O=t.dateFormat)!==null&&O!==void 0?O:"DateAndTime"};case"choice":return oN(t,r,!1);case"multiChoice":return oN(t,r,!0);case"file":return{"@odata.type":"Microsoft.Dynamics.CRM.FileAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"FileType"},MaxSizeInKB:(L=t.maxSizeKb)!==null&&L!==void 0?L:10240};case"image":return{"@odata.type":"Microsoft.Dynamics.CRM.ImageAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"ImageType"},IsPrimaryImage:(I=t.isPrimaryImage)!==null&&I!==void 0?I:!1,MaxSizeInKB:(D=t.maxSizeKb)!==null&&D!==void 0?D:10240};case"autonumber":if(!(!((P=t.autoNumberFormat)===null||P===void 0)&&P.trim()))throw new he.InvalidArgumentError(`createColumn: an 'autonumber' column needs an 'autoNumberFormat' (e.g. 'CDS-{SEQNUM:5}'), but '${t.schemaName}' has none \u2014 without one Dataverse would create a plain text column.`);return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},FormatName:{Value:"Text"},MaxLength:(x=t.maxLength)!==null&&x!==void 0?x:100,AutoNumberFormat:t.autoNumberFormat};default:throw new he.InvalidArgumentError(`unsupported column type '${String(e)}'`)}}function oN(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,te.normalizeGuid)(e.globalChoiceMetadataId,"globalChoiceMetadataId")})`,i;if(!e.options||e.options.length===0)throw new he.InvalidArgumentError(`choice column '${e.schemaName}' requires at least one option (or a globalChoiceMetadataId)`);return i.OptionSet={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",IsGlobal:!1,OptionSetType:"Picklist",Options:e.options.map(o=>({Value:o.value,Label:tt(o.label,t)}))},i}var Tg=new WeakMap;async function w9(e,t){var r,n;let i=(r=Tg.get(e))===null||r===void 0?void 0:r.get(t);if(i)return i;let o=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')${(0,te.odataQuery)([["$select","EntitySetName"]])}`,s=(n=(0,Se.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.EntitySetName;if(!s)throw new he.InvalidArgumentError(`could not resolve EntitySetName for '${t}'`);(0,te.assertODataName)(s,`server-derived EntitySetName for '${t}'`);let l=Tg.get(e);return l||(l=new Map,Tg.set(e,l)),l.set(t,s),s}ie.resolveEntitySetName=w9;async function C9(e,t){var r,n,i,o,a,s,l,u,c,d,f,m,p,h,g;let b=t.primaryColumnRequired;if(b!==void 0&&!nN.includes(b))throw new he.InvalidArgumentError(`createTable: 'primaryColumnRequired' must be one of ${nN.join(", ")}; got '${String(b)}'.`);let w=b!==void 0&&b!=="None";if(w&&!t.primaryColumnAutoNumberFormat&&!e.supportsPut)throw new he.InvalidArgumentError(`createTable: 'primaryColumnRequired: ${b}' on a plain text primary column needs an HttpClient that implements put(): the platform ignores the level in the create, so the SDK sets it with an update.`);let C=(r=t.languageCode)!==null&&r!==void 0?r:ri.DEFAULT_LCID,S=Ig(t.schemaName),O=(n=t.primaryColumnSchemaName)!==null&&n!==void 0?n:`${S}_Name`,L={"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},SchemaName:O,RequiredLevel:fu(b??"None"),MaxLength:(i=t.primaryColumnMaxLength)!==null&&i!==void 0?i:100,FormatName:{Value:"Text"},DisplayName:tt((o=t.primaryColumnDisplayName)!==null&&o!==void 0?o:"Name",C),IsPrimaryName:!0};t.primaryColumnAutoNumberFormat&&(L.AutoNumberFormat=t.primaryColumnAutoNumberFormat),t.columns&&dN(t.columns,"createTable");let I={"@odata.type":"Microsoft.Dynamics.CRM.EntityMetadata",SchemaName:t.schemaName,DisplayName:tt(t.displayName,C),DisplayCollectionName:tt((a=t.pluralName)!==null&&a!==void 0?a:sN(t.displayName),C),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:[L,...((c=t.columns)!==null&&c!==void 0?c:[]).map(ur=>Og(ur,C))]};t.description&&(I.Description=tt(t.description,C));let D="/EntityDefinitions",P=(0,Se.ensureSuccess)(await e.post(D,I),e.apiUrl(D)),x=pu(P),K=`/EntityDefinitions(${x})`+(0,te.odataQuery)([["$select","LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute"]]),Le=Math.max(1,Math.trunc((d=t.readBackAttempts)!==null&&d!==void 0?d:6)),lr=Math.max(0,(f=t.readBackDelayMs)!==null&&f!==void 0?f:1e3),Ge=w?` Its primary column's requirement level '${b}' was NOT applied or checked: once the table is readable, set it with updateColumn('${t.schemaName.toLowerCase()}', '${O.toLowerCase()}', { required: '${b}' }).`:"",Ut;try{Ut=await lN(e,K,Le,lr)}catch(ur){throw w?(0,he.attachCause)(new he.SdkError("PRIMARY_COLUMN_REQUIRED_NOT_APPLIED",`Table '${t.schemaName}' WAS CREATED (MetadataId ${x}), but reading it back failed (${ur instanceof Error?ur.message:String(ur)}).${Ge} Do NOT re-run the create \u2014 it will collide on the schema name.`),ur):ur}if(!Ut)throw new he.SdkError("TABLE_METADATA_NOT_VISIBLE",`Table '${t.schemaName}' WAS CREATED (MetadataId ${x}) but its metadata was still not readable after ${Le} attempt(s). Do NOT re-run the create \u2014 it will collide on the schema name. Re-read /EntityDefinitions(${x}) once the environment catches up, or raise 'readBackAttempts'.${Ge}`);let de=Ut.body,Ke={logicalName:(m=de.LogicalName)!==null&&m!==void 0?m:t.schemaName.toLowerCase(),metadataId:x,entitySetName:(p=de.EntitySetName)!==null&&p!==void 0?p:"",primaryIdAttribute:(h=de.PrimaryIdAttribute)!==null&&h!==void 0?h:`${t.schemaName.toLowerCase()}id`,primaryNameAttribute:(g=de.PrimaryNameAttribute)!==null&&g!==void 0?g:O.toLowerCase()};return w&&(Ke.primaryColumnRequired=await E9(e,t.schemaName,Ke,b,Le,lr)),Ke}ie.createTable=C9;async function lN(e,t,r,n){for(let i=1;i<=r;i+=1){let o=await e.get(t);if(o.status>=200&&o.status<300)return o;o.status!==404&&(0,Se.ensureSuccess)(o,e.apiUrl(t)),i<r&&n>0&&await new Promise(a=>setTimeout(a,n))}}async function E9(e,t,r,n,i,o){let a=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(r.logicalName)}')/Attributes(LogicalName='${(0,te.odataPathLiteral)(r.primaryNameAttribute)}')`+(0,te.odataQuery)([["$select","RequiredLevel"]]),s=async()=>{var d,f;let m=await lN(e,a,i,o),p=(f=(d=m?.body)===null||d===void 0?void 0:d.RequiredLevel)===null||f===void 0?void 0:f.Value;return typeof p=="string"?p:void 0},l="read",u,c=d=>{let f=`its primary column '${r.primaryNameAttribute}'`,m=l==="read"?`${f} could not be read back`:l==="update"?`${f} read '${u??"(unreadable)"}' and the update to '${n}' failed, so it may or may not carry it`:u===void 0?`${f} was updated to '${n}' but could not be read back`:`${f} is still '${u}' after the update to '${n}'`;return new he.SdkError("PRIMARY_COLUMN_REQUIRED_NOT_APPLIED",`Table '${t}' WAS CREATED (MetadataId ${r.metadataId}), but ${m}${d?` (${d})`:""}. Do NOT re-run the create \u2014 it will collide on the schema name. Check the level, and set it with updateColumn('${r.logicalName}', '${r.primaryNameAttribute}', { required: '${n}' }).`)};try{u=await s(),u!==n&&(l="update",await hN(e,r.logicalName,r.primaryNameAttribute,{required:n}),l="verify",u=await s())}catch(d){throw l==="verify"&&(u=void 0),(0,he.attachCause)(c(d instanceof Error?d.message:String(d)),d)}if(u!==n)throw c(u===void 0?"the answer had no RequiredLevel":void 0);return n}function Og(e,t){var r,n;let i=(r=e.languageCode)!==null&&r!==void 0?r:t,o={...v9(e.type,e,i),SchemaName:e.schemaName,RequiredLevel:fu((n=e.required)!==null&&n!==void 0?n:"None"),DisplayName:tt(e.displayName,i)};return e.description&&(o.Description=tt(e.description,i)),e.sourceType&&e.sourceType!=="Simple"&&(o.SourceType=e.sourceType==="Rollup"?2:1,e.formulaDefinition&&(o.FormulaDefinition=e.formulaDefinition)),uN(o,e),o}function uN(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 A9(e,t,r){var n;let i=Og(r,(n=r.languageCode)!==null&&n!==void 0?n:ri.DEFAULT_LCID),o=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes`,a=(0,Se.ensureSuccess)(await e.post(o,i),e.apiUrl(o)),s={logicalName:r.schemaName.toLowerCase(),metadataId:pu(a)};if(r.visualization&&r.visualization!=="None")try{await mN(e,t,s.logicalName,s.metadataId,r.visualization)}catch(l){let u=new he.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(0,he.attachCause)(u,l),u}return s}ie.createColumn=A9;var As="/controlconfigurations",cN="CustomRenderersConfiguration",Dg={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 dN(e,t){let r=e.find(n=>n.visualization&&n.visualization!=="None");if(r)throw new he.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 fN(e){return JSON.stringify({type:Dg[e]})}function S9(e){if(!e)return"None";let t;try{t=JSON.parse(e)}catch{return"None"}let r=t?.type,n=Object.keys(Dg).find(i=>Dg[i]===r);return n??"None"}async function pN(e,t,r){var n,i;let o=`entitylogicalname eq '${(0,te.odataLiteral)(t)}' and Attribute/logicalname eq '${(0,te.odataLiteral)(r)}'`,a=`${As}${(0,te.odataQuery)([["$select","name,uniquename,metadatajson"],["$expand","Attribute($select=name,logicalname)"],["$filter",o]])}`,l=(i=(n=(0,Se.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[],u=r.toLowerCase();return l.filter(c=>{var d,f;return((f=(d=c.Attribute)===null||d===void 0?void 0:d.logicalname)===null||f===void 0?void 0:f.toLowerCase())===u})}async function N9(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,te.odataPathLiteral)(r)}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,a=(n=(0,Se.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||n===void 0?void 0:n.MetadataId;if(!a)throw new he.InvalidArgumentError(`cannot resolve column '${r}' on '${t}' to set its visualization`);return(0,te.normalizeGuid)(a,"MetadataId")}async function mN(e,t,r,n,i){let o={name:cN,uniquename:`msdyn_${t}_${r}_customrenderers`,metadatajson:fN(i),"[email protected]":`/attributes(${(0,te.normalizeGuid)(n,"MetadataId")})`,entitylogicalname:t};(0,Se.ensureSuccess)(await e.post(As,o),e.apiUrl(As))}async function _9(e,t,r){var n;let i=await pN(e,t,r);return S9((n=i[0])===null||n===void 0?void 0:n.metadatajson)}ie.getColumnVisualization=_9;async function T9(e,t,r,n){let o=(await pN(e,t,r)).map(u=>u.controlconfigurationid).filter(u=>!!u);if(n==="None"){for(let u of o){let c=`${As}(${(0,te.normalizeGuid)(u,"controlconfigurationid")})`;(0,Se.ensureSuccess)(await e.delete(c),e.apiUrl(c))}return}let[a,...s]=o,l=await N9(e,t,r);if(a){let u=`${As}(${(0,te.normalizeGuid)(a,"controlconfigurationid")})`,c={name:cN,metadatajson:fN(n),"[email protected]":`/attributes(${l})`,entitylogicalname:t};(0,Se.ensureSuccess)(await e.patch(u,c),e.apiUrl(u))}else await mN(e,t,r,l,n);for(let u of s){let c=`${As}(${(0,te.normalizeGuid)(u,"controlconfigurationid")})`;(0,Se.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}ie.setColumnVisualization=T9;async function D9(e,t,r){if(r.length===0)return;if(dN(r,"createColumns"),!e.supportsAtomicBatch)throw new he.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,te.odataPathLiteral)(t)}')/Attributes`;await(0,g9.postChangeSet)(e,r.map(i=>{var o;return{method:"POST",path:n,body:Og(i,(o=i.languageCode)!==null&&o!==void 0?o:ri.DEFAULT_LCID)}}),`${r.length} column(s) on '${t}'`)}ie.createColumns=D9;async function I9(e,t,r){var n,i,o,a;let s=(n=r.languageCode)!==null&&n!==void 0?n:ri.DEFAULT_LCID,l=Ig(r.schemaName),u=(i=r.accountRelationshipName)!==null&&i!==void 0?i:`${l}_${t}_account`,c=(o=r.contactRelationshipName)!==null&&o!==void 0?o:`${l}_${t}_contact`,d={Lookup:{"@odata.type":"Microsoft.Dynamics.CRM.ComplexLookupAttributeMetadata",SchemaName:r.schemaName,DisplayName:tt(r.displayName,s),RequiredLevel:fu((a=r.required)!==null&&a!==void 0?a:"None"),Targets:["account","contact"]},OneToManyRelationships:[{"@odata.type":"Microsoft.Dynamics.CRM.ComplexOneToManyRelationshipMetadata",SchemaName:u,ReferencedEntity:"account",ReferencingEntity:t},{"@odata.type":"Microsoft.Dynamics.CRM.ComplexOneToManyRelationshipMetadata",SchemaName:c,ReferencedEntity:"contact",ReferencingEntity:t}]};return(0,Se.ensureSuccess)(await e.post("/CreateCustomerRelationships",d),e.apiUrl("/CreateCustomerRelationships")),{logicalName:r.schemaName.toLowerCase(),metadataId:""}}ie.createCustomerColumn=I9;async function O9(e,t,r){var n,i,o,a,s;let l=(n=r.languageCode)!==null&&n!==void 0?n:ri.DEFAULT_LCID,u={EntityLogicalName:t,AttributeLogicalName:"statuscode",Label:tt(r.label,l),StateCode:(i=r.stateCode)!==null&&i!==void 0?i:0};typeof r.value=="number"&&(u.Value=r.value),r.color&&(u.Color=r.color);let c=(0,Se.ensureSuccess)(await e.post("/InsertStatusValue",u),e.apiUrl("/InsertStatusValue"));return Number((s=(a=(o=c.body)===null||o===void 0?void 0:o.NewOptionValue)!==null&&a!==void 0?a:r.value)!==null&&s!==void 0?s:0)}ie.insertStatusValue=O9;async function P9(e,t){var r,n,i,o,a;let s=(r=t.languageCode)!==null&&r!==void 0?r:ri.DEFAULT_LCID,l,u;if(t.type==="OneToMany"){if(!t.referencedEntity||!t.referencingEntity)throw new he.InvalidArgumentError("OneToMany relationship requires referencedEntity and referencingEntity");let f=(n=t.lookupSchemaName)!==null&&n!==void 0?n:`${Ig(t.schemaName)}_${t.referencedEntity}Id`;u=f.toLowerCase(),l={"@odata.type":"Microsoft.Dynamics.CRM.OneToManyRelationshipMetadata",SchemaName:t.schemaName,ReferencedEntity:t.referencedEntity,ReferencingEntity:t.referencingEntity,Lookup:{"@odata.type":"Microsoft.Dynamics.CRM.LookupAttributeMetadata",AttributeType:"Lookup",AttributeTypeName:{Value:"LookupType"},SchemaName:f,RequiredLevel:fu((i=t.lookupRequired)!==null&&i!==void 0?i:"None"),DisplayName:tt((o=t.lookupDisplayName)!==null&&o!==void 0?o:t.referencedEntity,s)}}}else{if(!t.entity1||!t.entity2)throw new he.InvalidArgumentError("ManyToMany relationship requires entity1 and entity2");l={"@odata.type":"Microsoft.Dynamics.CRM.ManyToManyRelationshipMetadata",SchemaName:t.schemaName,IntersectEntityName:(a=t.intersectEntityName)!==null&&a!==void 0?a:t.schemaName.toLowerCase(),Entity1LogicalName:t.entity1,Entity2LogicalName:t.entity2}}let c="/RelationshipDefinitions",d=(0,Se.ensureSuccess)(await e.post(c,l),e.apiUrl(c));return{schemaName:t.schemaName,metadataId:pu(d),lookupLogicalName:u}}ie.createRelationship=P9;async function R9(e,t){let r=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')`;(0,Se.ensureSuccess)(await e.delete(r),e.apiUrl(r))}ie.deleteTable=R9;async function hN(e,t,r,n){var i,o;let a=(i=n.languageCode)!==null&&i!==void 0?i:ri.DEFAULT_LCID,s=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes`,l=`${s}(LogicalName='${(0,te.odataPathLiteral)(r)}')${(0,te.odataQuery)([["$select","MetadataId,AttributeType"]])}`,c=(0,Se.ensureSuccess)(await e.get(l),e.apiUrl(l)).body,d=y9[(o=c.AttributeType)!==null&&o!==void 0?o:""];if(!c.MetadataId||!d){let g=c.MetadataId?c.AttributeType?`type '${c.AttributeType}' not supported`:"the attribute read returned no AttributeType":"the attribute read returned no MetadataId";throw new he.InvalidArgumentError(`cannot update column '${r}' on '${t}' (${g})`)}let f=(0,te.normalizeGuid)(c.MetadataId,"MetadataId"),m=`${s}(${f})/${d}`,p=(0,Se.ensureSuccess)(await e.get(m),e.apiUrl(m)).body;for(let g of Object.keys(p))g.startsWith("@odata.")&&delete p[g];if(p["@odata.type"]=d,n.displayName!==void 0&&(p.DisplayName=tt(n.displayName,a)),n.description!==void 0&&(p.Description=tt(n.description,a)),n.required!==void 0&&(p.RequiredLevel=fu(n.required)),n.maxLength!==void 0&&(p.MaxLength=n.maxLength),n.autoNumberFormat!==void 0&&(p.AutoNumberFormat=n.autoNumberFormat),n.defaultValue!==void 0&&c.AttributeType!=="Boolean")throw new he.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 he.InvalidArgumentError(`updateColumn: 'integerFormat' applies to Integer columns, but '${r}' on '${t}' is of type '${c.AttributeType}'.`);n.defaultValue!==void 0&&(p.DefaultValue=n.defaultValue),n.integerFormat!==void 0&&(p.Format=n.integerFormat),uN(p,n);let h=`${s}(${f})`;(0,Se.ensureSuccess)(await e.put(h,p,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(h))}ie.updateColumn=hN;async function L9(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes`,o=`${i}(LogicalName='${(0,te.odataPathLiteral)(r)}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,Se.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new he.InvalidArgumentError(`column '${r}' not found on '${t}'`);let l=`${i}(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,Se.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteColumn=L9;async function k9(e,t){var r,n,i;let o=`/RelationshipDefinitions${(0,te.odataQuery)([["$filter",`SchemaName eq '${(0,te.odataLiteral)(t)}'`],["$select","MetadataId"]])}`,s=(i=(n=(r=(0,Se.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||r===void 0?void 0:r.value)===null||n===void 0?void 0:n[0])===null||i===void 0?void 0:i.MetadataId;if(!s)throw new he.InvalidArgumentError(`relationship '${t}' not found`);let l=`/RelationshipDefinitions(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,Se.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteRelationship=k9;async function aN(e,t){var r;let n=`/GlobalOptionSetDefinitions(Name='${(0,te.odataPathLiteral)(t)}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,i=await e.get(n);if(i.status===404)return;let a=(r=(0,Se.ensureSuccess)(i,e.apiUrl(n)).body)===null||r===void 0?void 0:r.MetadataId;return a?(0,te.normalizeGuid)(a,"MetadataId"):void 0}async function $9(e,t){var r;let n=t.name.toLowerCase(),i=await aN(e,n);if(i)return{name:n,metadataId:i};let o=(r=t.languageCode)!==null&&r!==void 0?r:ri.DEFAULT_LCID,a={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",Name:n,DisplayName:tt(t.displayName,o),IsGlobal:!0,OptionSetType:"Picklist",Options:t.options.map(l=>({Value:l.value,Label:tt(l.label,o)}))};t.description&&(a.Description=tt(t.description,o));let s="/GlobalOptionSetDefinitions";try{let l=(0,Se.ensureSuccess)(await e.post(s,a),e.apiUrl(s));return{name:n,metadataId:pu(l)}}catch(l){let u;try{u=await aN(e,n)}catch{u=void 0}if(u)return{name:n,metadataId:u};throw l}}ie.createGlobalOptionSet=$9;async function x9(e,t){let r=`/GlobalOptionSetDefinitions(Name='${(0,te.odataPathLiteral)(t.toLowerCase())}')`;(0,Se.ensureSuccess)(await e.delete(r),e.apiUrl(r))}ie.deleteGlobalOptionSet=x9;async function F9(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:ri.DEFAULT_LCID,o={"@odata.type":"Microsoft.Dynamics.CRM.EntityKeyMetadata",SchemaName:r.schemaName,DisplayName:tt(r.displayName,i),KeyAttributes:r.keyAttributes},a=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Keys`,s=(0,Se.ensureSuccess)(await e.post(a,o),e.apiUrl(a));return{logicalName:r.schemaName.toLowerCase(),metadataId:pu(s)}}ie.createAlternateKey=F9;async function M9(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Keys`,o=`${i}(LogicalName='${(0,te.odataPathLiteral)(r.toLowerCase())}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,Se.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new he.InvalidArgumentError(`alternate key '${r}' not found on '${t}'`);let l=`${i}(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,Se.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteAlternateKey=M9;async function U9(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:ri.DEFAULT_LCID,o=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')`,s=(0,Se.ensureSuccess)(await e.get(o),e.apiUrl(o)).body,l=s.MetadataId;if(!l)throw new he.InvalidArgumentError(`table '${t}' not found`);let u=(0,te.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=tt(r.displayName,i)),r.pluralName!==void 0&&(s.DisplayCollectionName=tt(r.pluralName,i)),r.description!==void 0&&(s.Description=tt(r.description,i)),r.auditEnabled!==void 0&&iN(s,"IsAuditEnabled",r.auditEnabled),r.duplicateDetectionEnabled!==void 0&&iN(s,"IsDuplicateDetectionEnabled",r.duplicateDetectionEnabled),r.changeTrackingEnabled!==void 0&&(s.ChangeTrackingEnabled=r.changeTrackingEnabled),r.quickCreateEnabled!==void 0&&(s.IsQuickCreateEnabled=r.quickCreateEnabled),r.iconVectorName!==void 0&&(s.IconVectorName=r.iconVectorName),r.iconSmallName!==void 0&&(s.IconSmallName=r.iconSmallName),r.iconMediumName!==void 0&&(s.IconMediumName=r.iconMediumName),r.iconLargeName!==void 0&&(s.IconLargeName=r.iconLargeName);let c=`/EntityDefinitions(${u})`;(0,Se.ensureSuccess)(await e.put(c,s,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(c))}ie.updateTable=U9});var wo=v(Pr=>{"use strict";Object.defineProperty(Pr,"__esModule",{value:!0});Pr.rebuildRaw=Pr.assembleChildren=Pr.spliceChildren=Pr.mergeAttrs=Pr.rawFromNode=Pr.emptyBag=void 0;var vo=Q(),gN=1e6,Fd=512;function B9(){return{a:[],c:[]}}Pr.emptyBag=B9;function yN(e,t=0){if(t>Fd)throw new vo.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${Fd}`);return{n:e.getNodeName(),a:e.getAllProperties().map(r=>[r.key,r.value]),c:e.getAllChildren().map(r=>yN(r,t+1))}}Pr.rawFromNode=yN;function q9(e,t,r=[]){let n=new Map;for(let[s,l]of t)n.set(s,l);let i=new Set(r.filter(s=>!n.has(s))),o=new Set,a=[];for(let[s,l]of e)i.has(s)||(n.has(s)?a.push([s,n.get(s)]):a.push([s,l]),o.add(s));for(let[s,l]of t)o.has(s)||(a.push([s,l]),o.add(s));return a}Pr.mergeAttrs=q9;function xd(e,t){let r=new Set;for(let s of e){let l=s.i;if(!Number.isInteger(l)||l<0||l>gN)throw new vo.InvalidArgumentError(`Bag child index must be an integer in [0, ${gN}] (got ${String(l)})`);if(r.has(l))throw new vo.InvalidArgumentError(`Duplicate bag child index ${l}`);r.add(l)}let n=[...e].sort((s,l)=>s.i-l.i),i=[],o=0,a=0;for(let s of n){for(;a<s.i&&o<t.length;)i.push(t[o]),o+=1,a+=1;a<s.i&&(a=s.i),i.push(s.node),a+=1}for(;o<t.length;)i.push(t[o]),o+=1;return i}Pr.spliceChildren=xd;function V9(e,t){if(e.w){let r={n:e.w.n,a:e.w.a.map(n=>[n[0],n[1]]),c:xd(e.w.c,t)};return xd(e.c,[r])}return xd(e.c,t)}Pr.assembleChildren=V9;function bN(e,t,r,n=0){if(n>Fd)throw new vo.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${Fd}`);G9(e,n);let i=t.make(e.n,r);for(let[o,a]of e.a)t.setProp(i,o,a);for(let o of e.c)t.addChild(i,bN(o,t,i,n+1));return i}Pr.rebuildRaw=bN;function G9(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new vo.InvalidArgumentError(`Malformed hybrid node at depth ${t}: expected a JSON object`);let r=e;if(typeof r.n!="string")throw new vo.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 vo.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 vo.InvalidArgumentError(`Malformed hybrid node '${r.n}': each attribute must be a [string, string] pair`)}});var Co=v(Md=>{"use strict";Object.defineProperty(Md,"__esModule",{value:!0});Md.installDomShim=void 0;var vN=ys(),wN=!1,W9={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 z9(){if(wN)return;let e=globalThis;typeof e.DOMParser>"u"&&(e.DOMParser=vN.DOMParser),typeof e.XMLSerializer>"u"&&(e.XMLSerializer=vN.XMLSerializer),typeof e.Node>"u"&&(e.Node=W9),wN=!0}Md.installDomShim=z9});var Eo=v(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.projectElementBag=rt.serializeNode=rt.domEngine=rt.nodeLikeFromDom=rt.parseXmlRoot=rt.EMPTY_FORM_SENTINEL=rt.TEXT_SENTINEL=void 0;var j9=wo(),Ss=Q(),H9=Co();rt.TEXT_SENTINEL="#text";rt.EMPTY_FORM_SENTINEL="#empty";var Bd=new WeakSet;function K9(e,t){(0,H9.installDomShim)();let r=e&&e.trim()!==""?e:t,n=new DOMParser().parseFromString(r,"text/xml"),i=n.documentElement;if(!i)throw new Ss.InvalidArgumentError("XML source has no root element (empty or malformed input)");return J9(r),Q9(n),Z9(i),e5(i),n5(i,r),i}rt.parseXmlRoot=K9;function J9(e){let t=e.search(/\S/);if(t!==-1&&e[t]!=="<")throw EN(3)}var Y9=["http://www.mozilla.org/newlayout/xml/parsererror.xml","http://www.w3.org/1999/xhtml"];function Q9(e){var t;for(let r of Y9){let n=e.getElementsByTagNameNS(r,"parsererror")[0];if(n){let i=((t=n.textContent)!==null&&t!==void 0?t:"").replace(/\s+/g," ").trim().slice(0,200);throw new Ss.InvalidArgumentError(`XML source is not well-formed (${i||"the XML parser reported an error"}), so it cannot be round-tripped`)}}}var X9=new Set([1,3]);function Z9(e){let t=[e];for(;t.length>0;){let n=t.pop().childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];if(!X9.has(o.nodeType))throw new Ss.InvalidArgumentError(`Unsupported XML node type ${o.nodeType} (CDATA / comment / processing-instruction) is outside the hybrid projection's lossless grammar and cannot be round-tripped`);o.nodeType===1&&t.push(o)}}}function e5(e){var t,r;let n=(t=e.ownerDocument)!==null&&t!==void 0?t:e.parentNode;if(!n)return;let i=n.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];if(a!==e&&!(a.nodeType===3&&((r=a.nodeValue)!==null&&r!==void 0?r:"").trim()===""))throw EN(a.nodeType)}}function EN(e){return new Ss.InvalidArgumentError(`Unsupported document-level XML node (type ${e}: declaration / comment / processing-instruction outside the root element) cannot be round-tripped`)}function t5(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 r5(e){let t=[],r=[e];for(;r.length>0;){let n=r.pop();t.push(n);let i=n.childNodes;for(let o=i.length-1;o>=0;o-=1){let a=i[o];a.nodeType===1&&r.push(a)}}return t}function AN(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 n5(e,t){let r=t5(t),n=r5(e),i=Math.min(r.length,n.length);for(let o=0;o<i;o+=1){if(r[o])continue;let a=n[o];AN(a)||Bd.add(a)}}function Pg(e){let t=e.nodeType===3;return{getNodeName:()=>t?rt.TEXT_SENTINEL:e.tagName,getAllProperties:()=>{var r;if(t)return[{key:rt.TEXT_SENTINEL,value:(r=e.nodeValue)!==null&&r!==void 0?r:""}];let n=e.attributes,i=[];for(let o=0;o<n.length;o+=1)i.push({key:n[o].name,value:n[o].value});return Bd.has(e)&&!AN(e)&&i.push({key:rt.EMPTY_FORM_SENTINEL,value:"1"}),i},getAllChildren:()=>{if(t)return[];let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];(o.nodeType===1||o.nodeType===3)&&r.push(Pg(o))}return r}}}rt.nodeLikeFromDom=Pg;function i5(e){return{make:t=>t===rt.TEXT_SENTINEL?e.createTextNode(""):e.createElement(t),setProp:(t,r,n)=>{t.nodeType===3?t.nodeValue=n:r===rt.EMPTY_FORM_SENTINEL?Bd.add(t):t.setAttribute(r,n)},addChild:(t,r)=>{t.appendChild(r)}}}rt.domEngine=i5;function SN(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 Ud(r);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))throw Ud(r);t+=1;continue}if(r>=56320&&r<=57343)throw Ud(r)}}function Ud(e){let t=e.toString(16).toUpperCase().padStart(4,"0");return new Ss.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 o5(e){return SN(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/\r/g,"
").replace(/\n/g,"
").replace(/\t/g,"	")}function a5(e){return SN(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function s5(e){return NN(e,0)}rt.serializeNode=s5;var CN=512;function NN(e,t){var r;if(t>CN)throw new Ss.InvalidArgumentError(`XML nesting exceeds the maximum supported depth of ${CN}`);if(e.nodeType===3)return a5((r=e.nodeValue)!==null&&r!==void 0?r:"");let n=e,i="<"+n.tagName,o=n.attributes;for(let l=0;l<o.length;l+=1)i+=" "+o[l].name+'="'+o5(o[l].value)+'"';let a=[],s=n.childNodes;for(let l=0;l<s.length;l+=1){let u=s[l];(u.nodeType===1||u.nodeType===3)&&a.push(u)}if(a.length===0)return Bd.has(n)?i+"></"+n.tagName+">":i+" />";i+=">";for(let l of a)i+=NN(l,t+1);return i+"</"+n.tagName+">"}function l5(e){let t=Pg(e);return{a:t.getAllProperties().map(r=>[r.key,r.value]),c:t.getAllChildren().map((r,n)=>({i:n,node:(0,j9.rawFromNode)(r)}))}}rt.projectElementBag=l5});var cn=v(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.rejectUnknownKeys=Zt.childObjects=Zt.optionalGuidId=Zt.optionalEnum=Zt.eachObject=Zt.issue=Zt.isJsonObject=void 0;function _N(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}Zt.isJsonObject=_N;function Ns(e,t,r,n){return n?{pointer:e,rule:t,message:r,fatal:n}:{pointer:e,rule:t,message:r}}Zt.issue=Ns;function TN(e,t,r,n){if(!Array.isArray(e))return[];let i=[];return e.forEach((o,a)=>{_N(o)?i.push({node:o,index:a}):n.push(Ns(`${t}/${a}`,`${r}-must-be-object`,`a ${r} must be a JSON object, got ${o===null?"null":typeof o}`))}),i}Zt.eachObject=TN;function u5(e,t,r,n,i,o){let a=e[t];a!==void 0&&(typeof a!="string"||!r.includes(a))&&o.push(Ns(`${n}/${t}`,i,`${t} must be one of ${r.map(s=>`'${s}'`).join(", ")}, got ${JSON.stringify(a)}`))}Zt.optionalEnum=u5;var c5=/^(?:\{[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 o=e[t];typeof o=="string"&&o!==""&&!c5.test(o)&&i.push(Ns(`${r}/${t}`,n,`${t} must be a GUID or empty, got '${o}'`))}Zt.optionalGuidId=d5;function f5(e,t,r,n,i){let o=e[t],a=`${r}/${t}`;return o===void 0?[]:Array.isArray(o)?TN(o,a,n,i):(i.push(Ns(a,`${n}-list-must-be-array`,`${t} must be an array when present, got ${typeof o}`)),[])}Zt.childObjects=f5;function p5(e,t,r,n,i,o={}){var a,s;for(let l of Object.keys(e)){if(t.has(l))continue;let u=(a=o.elsewhere)===null||a===void 0?void 0:a[l],c=(s=o.unsupported)===null||s===void 0?void 0:s[l],d=u?` '${l}' is a ${u} key \u2014 set it on the ${u} instead.`:c?` ${c}`:` Put values the typed layer does not model in '${n}.bag', which round-trips them verbatim.`;i.push(Ns(`${r}/${l}`,`${n}-unknown-key`,`'${l}' is not a ${n} property, and would be SILENTLY DROPPED at serialization.${d}`))}}Zt.rejectUnknownKeys=p5});var zd=v(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.genPageEmbedIssues=B.setUniqueId=B.mintEmbedIdentity=B.authoredUniqueId=B.hasGenPage=B.applyEmbedCellDefaults=B.applyEmbedControlDefaults=B.mayCommitEmbedState=B.commitEmbedState=B.reconcileEmbedDescriptions=B.embedAppendIndex=B.activeEmbedBindings=B.projectGenPageEmbeds=B.isRecognizedEmbed=B.isUnbound=B.effectiveClassId=B.effectiveFormType=B.inputDataFrom=B.classifyBinding=B.isStaticParameter=B.entryParameter=B.pageEntries=B.descriptionFor=B.descriptionsRegion=B.controlUniqueIds=B.controlUniqueId=B.typedCellSites=B.typedCells=B.rawText=B.rawAttr=B.normGuid=B.GENPAGE_FORM_FACTORS=B.GENPAGE_EMBED_ROWSPAN=B.GENPAGE_CONTROL_NAME=B.CUSTOM_CONTROL_CLASS_ID=void 0;var m5=ys(),h5=Xa(),Rg=ct(),dn=cn();B.CUSTOM_CONTROL_CLASS_ID="F9A8A302-114E-466A-B582-6771B2AE0D92";B.GENPAGE_CONTROL_NAME="MscrmControls.UxAgentControl";B.GENPAGE_EMBED_ROWSPAN=6;B.GENPAGE_FORM_FACTORS=["2","0","1"];var g5=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Rr(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase();return t.startsWith("{")&&t.endsWith("}")&&(t=t.slice(1,-1)),g5.test(t)?t:""}B.normGuid=Rr;function Ao(e,t){let r=Ee(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}B.rawAttr=Ao;function hu(e){return Ee(e?.c).filter(t=>typeof t?.n=="string"&&t.n.startsWith("<")).map(t=>t.n.slice(1)).join("")}B.rawText=hu;function Ee(e){return Array.isArray(e)?e:[]}function Mg(e,t){let r=Ee(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}function ON(e){return typeof e=="string"?e.trim().replace(/^\{|\}$/g,"").toUpperCase():""}function PN(e){return Pn(e).map(t=>t.cell)}B.typedCells=PN;function Pn(e){let t=[];return Ee(e?.tabs).forEach((r,n)=>{Ee(Pe(r)?r.columns:void 0).forEach((i,o)=>{Ee(Pe(i)?i.sections:void 0).forEach((a,s)=>{Ee(Pe(a)?a.rows:void 0).forEach((l,u)=>{Ee(Pe(l)?l.cells:void 0).forEach((c,d)=>{Pe(c)&&t.push({cell:c,pointer:`/tabs/${n}/columns/${o}/sections/${s}/rows/${u}/cells/${d}`})})})})})}),t}B.typedCellSites=Pn;function Bi(e){return Pe(e)?Rr(Mg(e.bag,"uniqueid")):""}B.controlUniqueId=Bi;function y5(e){let t=new Set;for(let{cell:r}of Pn(e)){let n=ca(r.control)?Bi(r.control):"";n&&t.add(n)}return t}function b5(e){let t=new Map;for(let{cell:r}of Pn(e)){let n=Pe(r.control)?Bi(r.control):"";n&&!t.has(n)&&t.set(n,r.control)}return t}function v5(e){return e!==void 0&&e.genPage===void 0&&(qg(e)!==B.CUSTOM_CONTROL_CLASS_ID||!Wd(e))}function Lg(e,t){if(Pe(e)){t(e);for(let r of Ee(e.c))Lg(r,t)}}function la(e,t){var r;if(Pe(e)){for(let n of Ee(e.c))Lg(n?.node,t);for(let n of Ee((r=e.w)===null||r===void 0?void 0:r.c))Lg(n?.node,t)}}function Vd(e){let t=new Map,r=i=>{var o;i&&t.set(i,((o=t.get(i))!==null&&o!==void 0?o:0)+1)},n=i=>{i.n==="control"&&r(Rr(Ao(i,"uniqueid")))};return la(e?.bag,n),Ee(e?.tabs).forEach(i=>{Pe(i)&&(la(i.bag,n),Ee(i.columns).forEach(o=>{Pe(o)&&(la(o.bag,n),Ee(o.sections).forEach(a=>{Pe(a)&&(la(a.bag,n),Ee(a.rows).forEach(s=>{Pe(s)&&(la(s.bag,n),Ee(s.cells).forEach(l=>{Pe(l)&&(la(l.bag,n),Pe(l.control)&&(r(Bi(l.control)),la(l.control.bag,n)))}))}))}))}))}),t}B.controlUniqueIds=Vd;function _s(e){return Ee(e?.c).find(t=>{var r;return((r=t?.node)===null||r===void 0?void 0:r.n)==="controlDescriptions"})}B.descriptionsRegion=_s;function ua(e,t){var r;let n=Rr(t);if(n)return Ee((r=_s(e))===null||r===void 0?void 0:r.node.c).find(i=>i?.n==="controlDescription"&&Rr(Ao(i,"forControl"))===n)}B.descriptionFor=ua;function gu(e){return Ee(e.c).filter(RN)}B.pageEntries=gu;function RN(e){return e?.n==="customControl"&&Ao(e,"name")===B.GENPAGE_CONTROL_NAME}function kg(e,t){let r=Ee(e.c).find(n=>n?.n==="parameters");return Ee(r?.c).find(n=>n?.n===t)}B.entryParameter=kg;function $g(e){return Ao(e,"static")==="true"}B.isStaticParameter=$g;function yu(e){let t=gu(e);if(t.length===0)return{kind:"none"};let r,n;for(let i=0;i<t.length;i+=1){let o=kg(t[i],"RefId");if(!o||!$g(o))return{kind:"unsupported"};let a=Rr(hu(o));if(!a)return{kind:"unsupported"};let s=kg(t[i],"PageInput");if(s&&!$g(s))return{kind:"unsupported"};let l=s?hu(s):void 0;if(i===0)r=a,n=l;else if(a!==r||l!==n)return{kind:"unsupported"}}return n===void 0?{kind:"projectable",pageId:r}:{kind:"projectable",pageId:r,pageInputRaw:n}}B.classifyBinding=yu;function Pe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ug(e){if(e===void 0)return;let t;try{t=JSON.parse(e)}catch{return}return Pe(t)&&Pe(t.data)?t.data:void 0}B.inputDataFrom=Ug;function Bg(e){var t;return(t=e.formType)!==null&&t!==void 0?t:"Main"}B.effectiveFormType=Bg;function qg(e){return ON(e.classId!==void 0?e.classId:Mg(e.bag,"classid"))}B.effectiveClassId=qg;function Wd(e){return!e.fieldName}B.isUnbound=Wd;function Vg(e,t){if(Bg(e)!=="Main"||!Wd(t)||qg(t)!==B.CUSTOM_CONTROL_CLASS_ID)return!1;let r=Bi(t),n=r?ua(e.bag,r):void 0;return n!==void 0&&yu(n).kind==="projectable"}B.isRecognizedEmbed=Vg;function w5(e){for(let t of PN(e)){let r=t.control;if(!r||!Vg(e,r))continue;let n=yu(ua(e.bag,Bi(r)));if(n.kind!=="projectable")continue;let i=Ug(n.pageInputRaw);r.genPage=i===void 0?{pageId:n.pageId}:{pageId:n.pageId,inputData:i}}}B.projectGenPageEmbeds=w5;var C5=new Set(["pageId","inputData"]);function mu(e){let t=[];for(let r=0;r<e.childNodes.length;r+=1){let n=e.childNodes[r];n.nodeType===1&&t.push(n)}return t}function E5(e){var t;let r=[],n=c=>d=>r.push(`${c}: ${d}`),i=new m5.DOMParser({errorHandler:{warning:n("warning"),error:n("error"),fatalError:n("fatalError")}}).parseFromString(e,"text/xml"),o=(t=i?.documentElement)!==null&&t!==void 0?t:null;if(!o||r.length>0)throw new Error(`the formxml does not parse cleanly${r.length>0?` (${r[0]})`:""}`);let a=new Set,s=o.getElementsByTagName("control");for(let c=0;c<s.length;c+=1){let d=Rr(s[c].getAttribute("uniqueid"));d&&a.add(d)}let l=mu(o).find(c=>c.nodeName==="controlDescriptions"),u=new Map;for(let c of l?mu(l):[]){let d=Rr(c.getAttribute("forControl"));if(!(c.nodeName!=="controlDescription"||!d||!a.has(d)))for(let f of mu(c)){if(f.nodeName!=="customControl"||f.getAttribute("name")!==B.GENPAGE_CONTROL_NAME)continue;let m=mu(f).find(g=>g.nodeName==="parameters"),p=m?mu(m).find(g=>g.nodeName==="RefId"):void 0,h=p&&p.getAttribute("static")==="true"?Rr(p.textContent):"";h&&u.set(`${d}|${h}`,[d,h])}}return[...u.values()]}B.activeEmbedBindings=E5;function qd(e){return{n:`<${e}`,a:[],c:[]}}function xg(e,t){return{n:e,a:[["type","SingleLine.Text"],["static","true"]],c:[qd(t)]}}function Fg(e,t){let r={};if(t!==void 0)try{let n=JSON.parse(t);Pe(n)&&(r=n)}catch{}return JSON.stringify({...r,data:e})}function A5(e,t,r){return{n:"controlDescription",a:[["forControl",e]],c:B.GENPAGE_FORM_FACTORS.map(n=>({n:"customControl",a:[["name",B.GENPAGE_CONTROL_NAME],["formFactor",n]],c:[{n:"parameters",a:[],c:[xg("RefId",t),...r===void 0?[]:[xg("PageInput",Fg(r))]]}]}))}}function Gd(e,t){if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>Gd(r,t[n]));if(Pe(e)&&Pe(t)){let r=Object.keys(e);return r.length===Object.keys(t).length&&r.every(n=>n in t&&Gd(e[n],t[n]))}return e===t}function S5(e,t,r){let n=Ee(e.c).find(u=>u?.n==="parameters");if(!n||!Array.isArray(n.c))return;let i=n.c.find(u=>u?.n==="RefId");i&&Rr(hu(i))!==t&&(i.c=[qd(t)]);let o=n.c.findIndex(u=>u?.n==="PageInput"),a=o>=0?n.c[o]:void 0,s=a?hu(a):void 0;if(Gd(Ug(s),r))return;if(r!==void 0){a?a.c=[qd(Fg(r,s))]:n.c.push(xg("PageInput",Fg(r)));return}let l=JSON.parse(s);delete l.data,Object.keys(l).length===0?n.c.splice(o,1):a.c=[qd(JSON.stringify(l))]}function Gg(e){let t=Ee(e?.c),r=t.reduce((n,i)=>i.i>n?i.i:n,-1);return Math.max(r,t.length)+1}B.embedAppendIndex=Gg;function N5(e,t){var r;let n=e.bag,i=_s(n);if(i&&t){let o=Vd(t),a=Vd(e),s=y5(t),l=b5(e),u=Ee(i.node.c),c=[];for(let d of u){let f=d?.n==="controlDescription"&&gu(d).length>0?Rr(Ao(d,"forControl")):"";if(!f||!o.has(f))c.push(d);else if(a.has(f))if(s.has(f)&&v5(l.get(f))&&Gd(d,ua(t.bag,f))){let m=Ee(d.c).filter(p=>!RN(p));m.length>0&&c.push({...d,c:m})}else c.push(d)}(c.length!==u.length||c.some((d,f)=>d!==u[f]))&&(i.node.c=c)}for(let{cell:o}of Pn(e)){let a=o.control;if(!ca(a)||!Pe(a.genPage))continue;let s=Rr(a.genPage.pageId),l=a.genPage.inputData,u=Bi(a);if(!u){if(bu(a)!==void 0)continue;u=Wg(a)}let c=ua(n,u);if(c){for(let m of gu(c))S5(m,s,l);continue}i||(i={i:Gg(n),node:{n:"controlDescriptions",a:[],c:[]}},n.c.push(i));let d=((r=Mg(a.bag,"uniqueid"))!==null&&r!==void 0?r:"").trim(),f=d.startsWith("{")?d:`{${u}}`;i.node.c.push(A5(f,s,l))}}B.reconcileEmbedDescriptions=N5;function _5(e,t){let r=_s(e.bag),n=t!==void 0&&(r===void 0||JSON.stringify(r.node)!==JSON.stringify(t)),i=Pn(e).some(({cell:a})=>ca(a.control)&&(a.rowspan===void 0||a.control.classId===void 0||a.control.showLabel===void 0||a.control.label===void 0||a.control.fieldName===void 0));if(!n&&!i)return e;let o=JSON.parse(JSON.stringify(e));if(n){let a=JSON.parse(JSON.stringify(t)),s=_s(o.bag);s?s.node=a:(o.bag=Pe(o.bag)?o.bag:{a:[],c:[]},o.bag.c=Ee(o.bag.c),o.bag.c.push({i:Gg(e.bag),node:a}))}for(let{cell:a}of Pn(o))ca(a.control)&&(LN(a.control),kN(a));return o}B.commitEmbedState=_5;function T5(e){if(Pn(e).some(({cell:r})=>ca(r.control)))return!0;let t=_s(e.bag);return Ee(t?.node.c).some(r=>r?.n==="controlDescription"&&gu(r).length>0)}B.mayCommitEmbedState=T5;function LN(e){e.classId===void 0&&(e.classId=B.CUSTOM_CONTROL_CLASS_ID),e.showLabel===void 0&&(e.showLabel=!1),e.label===void 0&&(e.label=""),e.fieldName===void 0&&(e.fieldName=null)}B.applyEmbedControlDefaults=LN;function kN(e){e.rowspan===void 0&&(e.rowspan=B.GENPAGE_EMBED_ROWSPAN)}B.applyEmbedCellDefaults=kN;function ca(e){return Pe(e)&&e.genPage!==void 0}B.hasGenPage=ca;function DN(e){return ca(e.control)&&(!e.control.id||!e.id||bu(e.control)===void 0)}function bu(e){let t=Ee(Pe(e.bag)?e.bag.a:void 0).find(n=>Array.isArray(n)&&n[0]==="uniqueid");if(!t)return;let r=t[1];return typeof r=="string"&&r.trim()===""?void 0:r}B.authoredUniqueId=bu;function D5(e){if(!Pn(e).some(({cell:r})=>DN(r)))return e;let t=JSON.parse(JSON.stringify(e));for(let{cell:r}of Pn(t)){if(!DN(r))continue;let n=r.control;n.id||(n.id=(0,Rg.newId)()),r.id||(r.id=(0,Rg.newId)()),bu(n)===void 0&&Wg(n)}return t}B.mintEmbedIdentity=D5;function Wg(e){let t=(0,Rg.newId)(),r=`{${t}}`;if(!Pe(e.bag))return e.bag={a:[["uniqueid",r]],c:[]},t;let n=Ee(e.bag.a),i=n.find(o=>Array.isArray(o)&&o[0]==="uniqueid");return i?i[1]=r:n.push(["uniqueid",r]),e.bag.a=n,e.bag.c=Ee(e.bag.c),t}B.setUniqueId=Wg;function IN(e){return e===null?"null":Array.isArray(e)?"an array":typeof e}function I5(e){let t=Ee(e.c).filter(r=>r?.n==="customControl").map(r=>{var n,i;return(i=(n=Ao(r,"name"))!==null&&n!==void 0?n:Ao(r,"id"))!==null&&i!==void 0?i:"unnamed"});return[...new Set(t)].join(", ")||"no custom control"}function O5(e){let t=[],r;for(let{cell:n,pointer:i}of Pn(e)){let o=n.control;if(!Pe(o))continue;let a=`${i}/control`;if(o.genPage===void 0){P5(e,o,a,t);continue}r=r??Vd(e),R5(e,o,a,r,t)}return t}B.genPageEmbedIssues=O5;function P5(e,t,r,n){if(!Vg(e,t))return;let i=yu(ua(e.bag,Bi(t)));n.push((0,dn.issue)(r,"genpage-embed-removed",`this control still embeds generative page ${i.pageId}: removing genPage alone would leave that binding on the form. To remove the embed, remove the cell (or set the cell's control to null); to change the page, edit genPage/pageId. A copy fetched by an older SDK (projection 3) shows no genPage at all \u2014 re-fetch the form.`))}function R5(e,t,r,n,i){var o;let a=`${r}/genPage`,s=t.genPage;if(!Pe(s))i.push((0,dn.issue)(a,"genpage-embed-shape",`genPage must be an object { pageId, inputData? }, got ${IN(s)}.`+(s===null?" To remove an embed, remove the cell (or set the cell's control to null).":"")));else{(typeof s.pageId!="string"||!Rr(s.pageId))&&i.push((0,dn.issue)(`${a}/pageId`,"genpage-embed-shape",`genPage.pageId must be the id (a GUID) of a generative page, got ${s.pageId===void 0?"nothing":JSON.stringify(s.pageId)}`)),s.inputData!==void 0&&!Pe(s.inputData)&&i.push((0,dn.issue)(`${a}/inputData`,"genpage-embed-shape",`genPage.inputData must be a JSON object \u2014 the page reads it as pageInput.data \u2014 got ${IN(s.inputData)}`));for(let m of Object.keys(s))C5.has(m)||i.push((0,dn.issue)(h5.JsonPointer.append(a,m),"genpage-embed-unknown-key",`'${m}' is not a genPage property (pageId, inputData), and would be SILENTLY DROPPED at serialization.`))}Wd(t)||i.push((0,dn.issue)(`${r}/fieldName`,"genpage-embed-bound",`a generative-page embed is an unbound control, but this one is bound to column '${t.fieldName}'. Set fieldName to null, or embed the page in a new cell.`)),t.classId!==void 0&&ON(t.classId)!==B.CUSTOM_CONTROL_CLASS_ID&&i.push((0,dn.issue)(`${r}/classId`,"genpage-embed-class-id",`a generative-page embed is the custom control {${B.CUSTOM_CONTROL_CLASS_ID}}, but classId is ${JSON.stringify(t.classId)}. Omit classId (the SDK defaults it) or set it to that class.`));let l=Bg(e);l!=="Main"&&i.push((0,dn.issue)(a,"genpage-embed-main-form-only",`a generative page can be embedded only in a Main form, as in the maker portal; this is a ${l} form.`));let u=bu(t);u!==void 0&&!Rr(u)&&i.push((0,dn.issue)(`${r}/bag`,"genpage-embed-unique-id",`this embed's uniqueid ${JSON.stringify(u)} is not a GUID, and its page binding is keyed by it. Remove it from the bag (the SDK mints one) or set a GUID.`));let c=Bi(t);if(!c)return;let d=ua(e.bag,c),f=d?yu(d):void 0;d&&f?.kind==="none"?i.push((0,dn.issue)(a,"genpage-embed-other-control",`this control is already bound to another custom control (${I5(d)}). genPage would have to delete that binding to take its place, so embed the page in a new cell instead.`)):f?.kind==="unsupported"&&i.push((0,dn.issue)(a,"genpage-embed-unsupported-binding","this control already embeds a page through a binding genPage cannot represent exactly \u2014 a RefId or PageInput bound to a column, a RefId that is not a page id, or form factors that disagree. Taking it over would silently turn it into a static binding, so embed the page in a new cell instead.")),((o=n.get(c))!==null&&o!==void 0?o:0)>1&&i.push((0,dn.issue)(`${r}/bag`,"genpage-embed-duplicate-unique-id",`this embed's uniqueid {${c}} is also carried by another control on the form, so both would share one binding. Author the copy without its bag and the SDK mints a new identity for it.`))}});var jg=v(So=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});So.findMissingGenPages=So.GENPAGE_LOOKUP_CHUNK=void 0;var L5=Tt(),zg=oe();So.GENPAGE_LOOKUP_CHUNK=50;async function k5(e,t,r){let n=[...new Set(t.map(o=>(0,zg.normalizeGuid)(o,"uxagentprojectid")))],i=new Set;for(let o=0;o<n.length;o+=So.GENPAGE_LOOKUP_CHUNK){let a=n.slice(o,o+So.GENPAGE_LOOKUP_CHUNK),s="/uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,zg.odataQuery)([["$select","uxagentprojectid"],["$filter",a.map(u=>`uxagentprojectid eq ${u}`).join(" or ")]]),l=await(0,L5.collectPages)(e,s,r);for(let u of l){let c=u.uxagentprojectid;typeof c=="string"&&c.trim()!==""&&i.add((0,zg.normalizeGuid)(c,"uxagentprojectid"))}}return n.filter(o=>!i.has(o))}So.findMissingGenPages=k5});var vu=v(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.assertSystemFormKind=Pt.readSystemFormType=Pt.decodeCode=Pt.assertSystemFormRecordKind=Pt.describeSystemFormType=Pt.systemFormKindOf=Pt.SYSTEMFORM_KIND_MISMATCH_CODE=void 0;var xN=Q(),$5=fe(),$N=oe();Pt.SYSTEMFORM_KIND_MISMATCH_CODE="SYSTEMFORM_KIND_MISMATCH";var x5={0:"dashboard",10:"dashboard",2:"form",6:"form",7:"form",11:"form"},F5={0:"dashboard",1:"appointment book",2:"Main form",3:"mini campaign form",4:"preview form",5:"mobile express form",6:"Quick View form",7:"Quick Create form",8:"dialog",9:"task flow form",10:"interactive dashboard",11:"card form",12:"interactive Main form",13:"contextual dashboard",100:"other form",101:"Main form backup",102:"appointment book backup",103:"Power BI dashboard"};function jd(e){return Number.isInteger(e)?x5[e]:void 0}Pt.systemFormKindOf=jd;function FN(e){var t;return Number.isFinite(e)?`a ${(t=F5[e])!==null&&t!==void 0?t:"systemform"} (type ${e})`:"a systemform whose type could not be read"}Pt.describeSystemFormType=FN;function MN(e,t,r,n){let i=FN(r),o=jd(r);switch(n){case"fetch":return`Refusing to fetch systemform '${e}' as a ${t}: it is ${i}. Nothing was read into the workspace. `+(o?`Fetch it as a ${o}.`:Number.isFinite(r)?"The SDK does not model that kind: check the id.":"Check the id.");case"write":return`Refusing to write systemform '${e}' as a ${t}: it is ${i}. Nothing was written. Check the id: a local copy fetched by an SDK that did not check the kind can name a row of another kind \u2014 discard it with deleteArtifact('${t}', '${e}').`;case"delete":return`Refusing to delete systemform '${e}' as a ${t}: it is ${i}. Nothing was changed. Check the id.`;default:return`Refusing to ${n} systemform '${e}': it is ${i}, not a ${t}.`+(n==="set the security roles of"?" Nothing was written.":"")+" Check the id."}}function M5(e,t,r,n){let i=Hg(e?.type);if(jd(i)!==r)throw new xN.SdkError(Pt.SYSTEMFORM_KIND_MISMATCH_CODE,MN(t,r,i,n));return i}Pt.assertSystemFormRecordKind=M5;function Hg(e){if(typeof e=="number")return Number.isInteger(e)?e:NaN;if(typeof e!="string"||!/^\s*-?\d+\s*$/.test(e))return NaN;let t=Number(e);return Number.isInteger(t)?t:NaN}Pt.decodeCode=Hg;async function U5(e,t){return await UN(e,t,!1)}Pt.readSystemFormType=U5;async function B5(e,t){return UN(e,t,!0)}async function UN(e,t,r){var n;let o=`/systemforms(${(0,$N.normalizeGuid)(t,"formId")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,$N.odataQuery)([["$select","type"]]),a=await e.get(o);if(!(r&&a.status===404))return(0,$5.ensureSuccess)(a,e.apiUrl(o)),Hg((n=a.body)===null||n===void 0?void 0:n.type)}async function q5(e,t,r){let n=await B5(e,t);if(!(n===void 0||jd(n)===r))throw new xN.SdkError(Pt.SYSTEMFORM_KIND_MISMATCH_CODE,MN(t,r,n,"delete"))}Pt.assertSystemFormKind=q5});var Jg=v(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.patchSystemForm=Yr.assertSystemFormContentUnchanged=Yr.readSystemFormRowEtag=Yr.unpublishedSystemFormPath=Yr.FORM_TYPE_IMMUTABLE_CODE=void 0;var fn=fe(),V5=oe(),Hd=Q(),No=vu();Yr.FORM_TYPE_IMMUTABLE_CODE="FORM_TYPE_IMMUTABLE";function Kg(e,t="formid"){return`/systemforms(${e})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,V5.odataQuery)([["$select",t]])}Yr.unpublishedSystemFormPath=Kg;function BN(e,t){return(0,fn.readRowEtag)(e,"systemforms","formid",t)}Yr.readSystemFormRowEtag=BN;async function qN(e,t,r,n,i){(0,fn.requireEtag)(i,r,t);let o=(0,fn.ensureSuccess)(await e.get(n),e.apiUrl(n)),a=(0,No.assertSystemFormRecordKind)(o.body,t,r,"write"),s=(0,fn.readEtag)(o);if(s===null)throw new Hd.SdkError(fn.VERSION_CONFLICT_CODE,`Refusing to write ${r} '${t}': its current version could not be read, so the write could not be verified as conditional and would risk silently overwriting a concurrent edit.`);if(s!==i)throw new Hd.SdkError(fn.VERSION_CONFLICT_CODE,`Version conflict writing ${r} '${t}': its formxml changed on the server since it was read (held ${i}, server ${s}). Re-fetch the ${r} and re-apply the change.`);return a}Yr.assertSystemFormContentUnchanged=qN;async function G5(e,t,r,n,i,o){(0,fn.requireEtag)(i,r,t);let a=await BN(e,t);if(a===null)throw new Hd.SdkError(fn.VERSION_CONFLICT_CODE,`Refusing to write ${r} '${t}': its row version could not be read, so the write could not be made conditional and would risk silently overwriting a concurrent edit.`);let s=await qN(e,t,r,Kg(t,"formid,type"),i);if(n.type!==void 0&&(0,No.decodeCode)(n.type)!==s)throw new Hd.SdkError(Yr.FORM_TYPE_IMMUTABLE_CODE,`Refusing to push ${r} '${t}': it would change it from ${(0,No.describeSystemFormType)(s)} to ${(0,No.describeSystemFormType)((0,No.decodeCode)(n.type))}. The platform ignores a type change on an existing ${r}, so the push would report a change that did not happen. Nothing was written. Create a new ${r} of that type instead.`);let l=(0,fn.echoWrite)("formid",{"If-Match":a}),u=`/systemforms(${t})${l.query}`;return(0,fn.ensureSuccess)(await e.patch(u,n,l.options),e.apiUrl(u)),W5(e,t,r,o)}Yr.patchSystemForm=G5;async function W5(e,t,r,n){let i;try{let o=Kg(t,n.select),a=(0,fn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=a.body,l=(0,fn.readEtag)(a),u=typeof s?.formid=="string"&&s.formid.replace(/[{}]/g,"").toLowerCase()===t,c=typeof s?.formxml=="string"&&s.formxml.trim()!=="",d=n.required.filter(p=>s?.[p]===void 0||s?.[p]===null),f=(0,No.decodeCode)(s?.type),m=(0,No.systemFormKindOf)(f)===r;if(l&&u&&c&&d.length===0&&m)return{id:t,etag:l,readBack:s};i=l?!u||!c?`the read did not return this ${r}'s document`:d.length>0?`the read did not return its ${d.join(", ")}`:`the read returned ${(0,No.describeSystemFormType)(f)}, not a ${r}`:"the read returned no version"}catch(o){i=o instanceof Error?o.message:String(o)}return{id:t,etag:null,warnings:[`The ${r} was saved, but its new version could not be read (${i}). The SDK holds no version for it now, so the next push is refused: re-fetch the ${r} before editing it again.`]}}});var e0=v(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.getFormSecurityRoles=qt.setFormSecurityRoles=qt.formApi=qt.readPrimaryCreateRefusal=qt.FORM_GENPAGE_TARGET_UNVERIFIABLE=qt.FORM_GENPAGE_TARGET_NOT_FOUND=void 0;var z5=Tt(),Rt=fe(),pn=oe(),da=Q(),Yg=Eo(),GN=zd(),j5=jg(),Qg=Jg(),wu=vu();qt.FORM_GENPAGE_TARGET_NOT_FOUND="FORM_GENPAGE_TARGET_NOT_FOUND";qt.FORM_GENPAGE_TARGET_UNVERIFIABLE="FORM_GENPAGE_TARGET_UNVERIFIABLE";var WN="formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber",H5={select:WN,required:["name","type","objecttypecode"]},K5="formid,name,type,objecttypecode",J5=2,Y5={Main:J5,QuickView:6,QuickCreate:7,Card:11},zN=new WeakMap;function Q5(e){return typeof e=="object"&&e!==null?zN.get(e):void 0}qt.readPrimaryCreateRefusal=Q5;qt.formApi={async get(e,t){let r=(0,pn.normalizeGuid)(t,"id"),n=`/systemforms(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,pn.odataQuery)([["$select",WN]]),i=(0,Rt.ensureSuccess)(await e.get(n),e.apiUrl(n));return(0,wu.assertSystemFormRecordKind)(i.body,r,"form","fetch"),{raw:i.body,etag:(0,Rt.readEtag)(i)}},async list(e,t){var r;let n=!((r=t?.formTypes)===null||r===void 0)&&r.length?t.formTypes:["Main"],i=[...new Set(n.map(u=>Y5[u]))],a=[i.length===1?`type eq ${i[0]}`:`(${i.map(u=>`type eq ${u}`).join(" or ")})`];t?.entityLogicalName&&a.push(`objecttypecode eq '${(0,pn.odataLiteral)(t.entityLogicalName)}'`);let s=`/systemforms${(0,pn.odataQuery)([["$select",K5],["$filter",a.join(" and ")]])}`;return(await(0,z5.collectPages)(e,s,"listArtifacts('form')")).map(u=>{var c,d;return{type:"form",id:(c=u.formid)!==null&&c!==void 0?c:"",name:(d=u.name)!==null&&d!==void 0?d:"",entityLogicalName:u.objecttypecode,isDirty:!1}})},async create(e,t,r){let n=VN(t);n!==void 0&&await jN(e,Zg(n,"payload"),[]);let i=(0,Rt.echoWrite)("formid"),o=`/systemforms${i.query}`,a=(0,Rt.withClientMintedId)(t,"formid",r),s=Object.freeze({...a}),l=await(0,Rt.resendDeadlockVictim)(()=>e.post(o,{...s},i.options));try{(0,Rt.ensureSuccess)(l,e.apiUrl(o))}catch(u){throw typeof u=="object"&&u!==null&&zN.set(u,{status:l.status,sent:s,desiredId:r}),u}return{id:(0,Rt.resolveCreatedId)(l,"formid","form",r),etag:(0,Rt.readEtag)(l)}},async update(e,t,r,n){let i=(0,pn.normalizeGuid)(t,"id"),o=VN(r);return o!==void 0&&await Z5(e,i,o,n),(0,Qg.patchSystemForm)(e,i,"form",r,n,H5)},readContentThenToken(e,t){return qt.formApi.get(e,t)},async delete(e,t){let r=(0,pn.normalizeGuid)(t,"id");return await(0,wu.assertSystemFormKind)(e,r,"form"),(0,Rt.deleteRecord)(e,"systemforms",r)}};var Xg="DisplayConditions";async function X5(e,t,r){var n,i,o,a;if(r.everyone&&r.roleIds&&r.roleIds.length>0)throw new da.InvalidArgumentError("setFormSecurityRoles: `everyone` and `roleIds` are mutually exclusive \u2014 the platform models <Everyone /> as a replacement for the <Role> list, not an addition to it.");let s=(0,pn.normalizeGuid)(t,"formId"),l=`/systemforms(${s})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,pn.odataQuery)([["$select","formid,formxml,type"]]),u=(0,Rt.ensureSuccess)(await e.get(l),e.apiUrl(l));(0,wu.assertSystemFormRecordKind)(u.body,s,"form","set the security roles of");let c=(0,Rt.readEtag)(u),d=u.body,f=d?.formxml;if(!f)throw new da.InvalidArgumentError(`form '${s}' returned no formxml, so its roles cannot be set`);let m=(0,Yg.parseXmlRoot)(f,"<form/>"),p=m.ownerDocument;if(!p)throw new da.InvalidArgumentError(`form '${s}' produced no owner document`);let h=HN(m,Xg),g=h?.hasAttribute("Order")&&(n=h.getAttribute("Order"))!==null&&n!==void 0?n:void 0,b=h?.getAttribute("FallbackForm")||void 0;h&&m.removeChild(h);let w=!!r.everyone||((o=(i=r.roleIds)===null||i===void 0?void 0:i.length)!==null&&o!==void 0?o:0)>0;if(!w&&(r.order!==void 0||r.fallbackForm!==void 0)){if(!h)throw new da.InvalidArgumentError("setFormSecurityRoles: `order`/`fallbackForm` were supplied without `roleIds` or `everyone`, but this form has no <DisplayConditions> to attach them to. Pass the roles as well.");r.order!==void 0&&h.setAttribute("Order",String(r.order)),r.fallbackForm!==void 0&&h.setAttribute("FallbackForm",String(r.fallbackForm)),m.appendChild(h)}else if(w){let I=p.createElement(Xg),D=r.order!==void 0?String(r.order):g;D!==void 0&&I.setAttribute("Order",D);let P=r.fallbackForm!==void 0?String(r.fallbackForm):b??"false";if(I.setAttribute("FallbackForm",P),r.everyone)I.appendChild(p.createElement("Everyone"));else for(let x of(a=r.roleIds)!==null&&a!==void 0?a:[]){let K=p.createElement("Role");K.setAttribute("Id",`{${(0,pn.normalizeGuid)(x,"roleId")}}`),I.appendChild(K)}m.appendChild(I)}let S=(0,Yg.serializeNode)(m);await(0,Qg.assertSystemFormContentUnchanged)(e,s,"form",l,c);let O=await(0,Qg.readSystemFormRowEtag)(e,s),L=`/systemforms(${s})`;(0,Rt.ensureSuccess)(await e.patch(L,{formxml:S},{headers:{"Content-Type":"application/json","If-Match":(0,Rt.requireEtag)(O,"form",s)}}),e.apiUrl(L))}qt.setFormSecurityRoles=X5;function VN(e){let t=e?.formxml;return typeof t=="string"&&t.includes(GN.GENPAGE_CONTROL_NAME)?t:void 0}function Zg(e,t){try{return(0,GN.activeEmbedBindings)(e)}catch(r){throw new da.SdkError(qt.FORM_GENPAGE_TARGET_UNVERIFIABLE,`Refusing to push the form: the ${t} formxml could not be parsed, so the generative pages it embeds cannot be verified (${r instanceof Error?r.message:String(r)}).`)}}async function jN(e,t,r){let n=new Set(r.map(([a,s])=>`${a}|${s}`)),i=t.filter(([a,s])=>!n.has(`${a}|${s}`)).map(([,a])=>a);if(i.length===0)return;let o=await(0,j5.findMissingGenPages)(e,i,"form generative-page preflight");if(o.length>0)throw new da.SdkError(qt.FORM_GENPAGE_TARGET_NOT_FOUND,`Refusing to push the form: it embeds generative page(s) ${o.map(a=>`'${a}'`).join(", ")} that do not exist in this environment. Push the page before the form that embeds it.`)}async function Z5(e,t,r,n){var i;(0,Rt.requireEtag)(n,"form",t);let o=`/systemforms(${t})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,pn.odataQuery)([["$select","formid,formxml,type"]]),a=(0,Rt.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,wu.assertSystemFormRecordKind)(a.body,t,"form","write");let s=(0,Rt.readEtag)(a);if(s===null||s!==n)throw new da.SdkError(Rt.VERSION_CONFLICT_CODE,`Version conflict writing form '${t}': its formxml changed on the server since it was read (held ${n}, server ${s??"(unreadable)"}). Re-fetch the form and re-apply the change.`);let l=(i=a.body)===null||i===void 0?void 0:i.formxml,u=typeof l=="string"&&l!==""?Zg(l,"server"):[];await jN(e,Zg(r,"payload"),u)}function HN(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 eW(e,t){var r,n;let i=(0,pn.normalizeGuid)(t,"formId"),o=`/systemforms(${i})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,pn.odataQuery)([["$select","formid,formxml,type"]]),a=(0,Rt.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,wu.assertSystemFormRecordKind)(a.body,i,"form","read the security roles of");let s=(r=a.body)===null||r===void 0?void 0:r.formxml;if(!s)return;let l=(0,Yg.parseXmlRoot)(s,"<form/>"),u=HN(l,Xg);if(!u)return;let c=[],d=!1,f=u.childNodes;for(let p=0;p<f.length;p+=1){let h=f[p];if(h.nodeType!==1)continue;let g=h;if(g.tagName==="Everyone")d=!0;else if(g.tagName==="Role"){let b=(n=g.getAttribute("Id"))!==null&&n!==void 0?n:"";b&&c.push(b.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)}:{}}}qt.getFormSecurityRoles=eW});var Jd=v(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.deleteSolution=ye.getDeploymentSettingsTemplate=ye.importSolution=ye.exportSolution=ye.removeSolutionComponent=ye.addSolutionComponent=ye.setSolutionVersion=ye.createSolution=ye.createPublisher=ye.getSolution=ye.fetchSolutionComponents=ye.resolveGenPageComponentType=ye.SolutionComponentType=void 0;var tW=Tt(),Gt=fe(),mr=oe(),rW=ct(),er=Q();ye.SolutionComponentType={SavedQuery:26,Workflow:29,SavedQueryVisualization:59,SystemForm:60,AppModule:80};var nW=[ye.SolutionComponentType.SavedQuery,ye.SolutionComponentType.Workflow,ye.SolutionComponentType.SavedQueryVisualization,ye.SolutionComponentType.SystemForm,ye.SolutionComponentType.AppModule],KN="uxagentproject",JN=new WeakMap;async function t_(e){var t;let r=JN.get(e);if(r!==void 0)return r;let n=`/EntityDefinitions(LogicalName='${KN}')${(0,mr.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status===404)return;(0,Gt.ensureSuccess)(i,e.apiUrl(n));let o=(t=i.body)===null||t===void 0?void 0:t.ObjectTypeCode;if(typeof o!="number"||!Number.isInteger(o)||o<=0)throw new er.SdkError("GENPAGE_COMPONENT_TYPE_UNRESOLVED",`A generative page's solution component type \u2014 the ObjectTypeCode of '${KN}' \u2014 could not be read: its metadata answered without a usable value (${JSON.stringify(o)}). Without it a solution's generative pages cannot be told apart from other components. Retry.`);return JN.set(e,o),o}ye.resolveGenPageComponentType=t_;var YN=1,QN=0;async function iW(e,t){let r=(0,mr.normalizeGuid)(t,"solutionId"),n=await t_(e),o=[YN,...nW,...n===void 0?[]:[n]].map(c=>`componenttype eq ${c}`).join(" or "),a=`/solutioncomponents${(0,mr.odataQuery)([["$select","objectid,componenttype,rootcomponentbehavior"],["$filter",`_solutionid_value eq ${r} and (${o})`]])}`,s=await(0,tW.collectPages)(e,a,"fetchSolutionComponents"),l=[];for(let c of s){if(typeof c.objectid!="string")continue;let d=Number(c.componenttype);if(d===YN){let f=c.rootcomponentbehavior;(f===QN||f===String(QN))&&l.push({objectId:c.objectid,componentType:d,includesAllSubcomponents:!0});continue}l.push({objectId:c.objectid,componentType:d,...n!==void 0&&d===n?{genPage:!0}:{}})}let u=c=>c.objectId.toLowerCase().replace(/^\{|\}$/g,"");return l.sort((c,d)=>c.componentType-d.componentType||(u(c)<u(d)?-1:u(c)>u(d)?1:0))}ye.fetchSolutionComponents=iW;function oW(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 aW(e,t){var r,n,i,o,a,s,l,u,c,d;let f=String(t??"").trim();if(!f)throw new er.InvalidArgumentError("getSolution: a solution unique name or id is required.");let m=oW(f)?`solutionid eq ${(0,mr.normalizeGuid)(f,"solutionId")}`:`uniquename eq '${(0,mr.odataLiteral)(f)}'`,p=`/solutions${(0,mr.odataQuery)([["$select","solutionid,uniquename,friendlyname,version,ismanaged"],["$expand","publisherid($select=publisherid,uniquename,customizationprefix,customizationoptionvalueprefix)"],["$filter",m]])}`,b=((n=(r=(0,Gt.ensureSuccess)(await e.get(p),e.apiUrl(p)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0];if(!b?.solutionid)throw new er.InvalidArgumentError(`No solution found for '${t}'.`);let w=b.publisherid;if(!w?.publisherid)throw new er.InvalidArgumentError(`Solution '${(i=b.uniquename)!==null&&i!==void 0?i:t}' returned no owning publisher, so its customization prefix cannot be determined; refusing to report an empty prefix that could be mistaken for "no prefix".`);if(!("customizationprefix"in w))throw new er.InvalidArgumentError(`Solution '${(o=b.uniquename)!==null&&o!==void 0?o:t}' returned a publisher without a customizationprefix property (partial expansion), so its prefix cannot be determined.`);return{solutionId:(0,mr.normalizeGuid)(b.solutionid,"solutionId"),uniqueName:(a=b.uniquename)!==null&&a!==void 0?a:"",friendlyName:(s=b.friendlyname)!==null&&s!==void 0?s:"",version:(l=b.version)!==null&&l!==void 0?l:"",isManaged:!!b.ismanaged,publisherId:(0,mr.normalizeGuid)(w.publisherid,"publisherId"),publisherUniqueName:(u=w.uniquename)!==null&&u!==void 0?u:"",publisherPrefix:(c=w.customizationprefix)!==null&&c!==void 0?c:"",publisherOptionValuePrefix:(d=w.customizationoptionvalueprefix)!==null&&d!==void 0?d:0}}ye.getSolution=aW;async function sW(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,Gt.ensureSuccess)(await(0,Gt.resendDeadlockVictim)(()=>e.post("/publishers",{...n})),e.apiUrl("/publishers")),o=(0,Gt.readCreatedId)(i,"publisherid");if(!o)throw new er.InvalidArgumentError(`Dataverse did not return an id for publisher '${t.uniqueName}'`);return{id:o,uniqueName:t.uniqueName}}ye.createPublisher=sW;async function lW(e,t){var r;let n=(0,mr.normalizeGuid)(t.publisherId,"publisherId"),i={uniquename:t.uniqueName,friendlyname:t.friendlyName,version:(r=t.version)!==null&&r!==void 0?r:"1.0.0.0","[email protected]":`/publishers(${n})`};t.description&&(i.description=t.description);let o=(0,Gt.ensureSuccess)(await e.post("/solutions",i),e.apiUrl("/solutions")),a=(0,Gt.readCreatedId)(o,"solutionid");if(!a)throw new er.InvalidArgumentError(`Dataverse did not return an id for solution '${t.uniqueName}'`);return{id:a,uniqueName:t.uniqueName}}ye.createSolution=lW;async function uW(e,t,r){let i=`/solutions(${(0,mr.normalizeGuid)(t,"solutionId")})`;(0,Gt.ensureSuccess)(await e.patch(i,{version:r}),e.apiUrl(i))}ye.setSolutionVersion=uW;async function cW(e,t){var r;let i={ComponentId:(0,mr.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,Gt.ensureSuccess)(await e.post("/AddSolutionComponent",i),e.apiUrl("/AddSolutionComponent"))}ye.addSolutionComponent=cW;async function dW(e,t,r,n){let o={SolutionComponent:{"@odata.type":"Microsoft.Dynamics.CRM.solutioncomponent",solutioncomponentid:(0,mr.normalizeGuid)(t,"componentId")},ComponentType:r,SolutionUniqueName:n};(0,Gt.ensureSuccess)(await e.post("/RemoveSolutionComponent",o),e.apiUrl("/RemoveSolutionComponent"))}ye.removeSolutionComponent=dW;async function fW(e,t){var r,n;let i={SolutionName:t.solutionName,Managed:(r=t.managed)!==null&&r!==void 0?r:!1},a=(n=(0,Gt.ensureSuccess)(await e.post("/ExportSolution",i),e.apiUrl("/ExportSolution")).body)===null||n===void 0?void 0:n.ExportSolutionFile;if(!a)throw new er.InvalidArgumentError(`ExportSolution returned no file for '${t.solutionName}'`);return{base64:a}}ye.exportSolution=fW;async function pW(e,t){let r=[["overwriteUnmanagedCustomizations","overwrote unmanaged customizations made over the solution's components"],["publishWorkflows","activated the solution's workflows"]];for(let[a,s]of r)if(typeof t?.[a]!="boolean")throw new er.InvalidArgumentError(`importSolution: '${a}' is required and must be true or false (it was ${String(t?.[a])}). It used to default to true, which ${s} unless the caller said otherwise. Nothing was imported.`);let n=t.deploymentSettings===void 0?void 0:SW(t.deploymentSettings),i={OverwriteUnmanagedCustomizations:t.overwriteUnmanagedCustomizations,PublishWorkflows:t.publishWorkflows,CustomizationFile:t.base64,ImportJobId:t.importJobId?(0,mr.normalizeGuid)(t.importJobId,"importJobId"):(0,rW.newId)()};if(!n)return(0,Gt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{};if(n.variables.length===0&&n.references.length===0)return(0,Gt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:{environmentVariables:[],connectionReferences:[]}};let o=[];try{let a=await r_(e,t.base64,Cu,o),{parameters:s,applied:l}=NW(a,n);return i.ComponentParameters=s,(0,Gt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:l,...o.length>0?{warnings:o}:{}}}catch(a){throw(0,er.withCleanupWarnings)(a,o)}}ye.importSolution=pW;var Cu="importSolution",XN="getDeploymentSettingsTemplate";async function mW(e,t){var r;let n=t?.base64;if(typeof n!="string"||n.length===0)throw new er.InvalidArgumentError(`${XN}: 'base64' must be the solution package \u2014 a non-empty base64 string, e.g. exportSolution's result (it was ${(r=JSON.stringify(n))!==null&&r!==void 0?r:String(n)})`);let i=[];try{let o=await r_(e,n,XN,i),a=Kd(o.variables,l=>l.SchemaName).map(({SchemaName:l,DefaultValue:u,TypeId:c,IsRequired:d})=>({SchemaName:l,Value:"",...u!==void 0?{DefaultValue:u}:{},...c!==void 0?{TypeId:c}:{},...d!==void 0?{IsRequired:d}:{}})),s=Kd(o.references,l=>l.LogicalName).map(({LogicalName:l,ConnectorId:u})=>({LogicalName:l,ConnectionId:"",...u!==void 0?{ConnectorId:u}:{}}));return{settings:{EnvironmentVariables:a,ConnectionReferences:s},...i.length>0?{warnings:i}:{}}}catch(o){throw(0,er.withCleanupWarnings)(o,i)}}ye.getDeploymentSettingsTemplate=mW;function Kd(e,t){return[...e].sort((r,n)=>{let i=t(r).toLowerCase(),o=t(n).toLowerCase();return i<o?-1:i>o?1:0})}function fa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Vt(e,t=120){var r;let n=(r=JSON.stringify(e))!==null&&r!==void 0?r:String(e);return n.length>t?`${n.slice(0,t)}\u2026`:n}async function r_(e,t,r,n){var i;let a=(i=(0,Gt.ensureSuccess)(await e.post("/StageSolution",{CustomizationFile:t}),e.apiUrl("/StageSolution")).body)===null||i===void 0?void 0:i.StageSolutionResults;try{return gW(a,r)}finally{await hW(e,fa(a)?a.StageSolutionUploadId:void 0,n)}}async function hW(e,t,r){let n;try{n=(0,mr.normalizeGuid)(t,"StageSolutionUploadId")}catch{r.push(`StageSolution's reply named no usable staging upload id (${Vt(t,60)}), so the staged copy of the package it may have stored (a stagesolutionupload row of yours) could not be deleted.`);return}let i=`/stagesolutionuploads(${n})`;try{let o=await e.delete(i);o.status!==404&&(0,Gt.ensureSuccess)(o,e.apiUrl(i))}catch(o){r.push(`The staged copy of the package (stagesolutionupload ${n}) could not be deleted: ${o instanceof Error?o.message:String(o)}. It stays until it is deleted (DELETE ${i}).`)}}function pr(e,t){return new er.SdkError("SOLUTION_STAGING_UNREADABLE",`${e}: StageSolution's reply could not be read \u2014 ${t}.${e===Cu?" Nothing was imported.":""}`)}function ZN(e){return!Array.isArray(e)||e.length===0?"none":`${e.slice(0,5).map(r=>fa(r)&&typeof r.Message=="string"?r.Message:Vt(r,200)).join("; ")}${e.length>5?` (+${e.length-5} more)`:""}`}function gW(e,t){if(!fa(e))throw pr(t,`it holds no StageSolutionResults (${Vt(e,60)})`);let r=e.StageSolutionStatus;if(r==="Failed"||r===0)throw new er.SdkError("SOLUTION_STAGING_FAILED",`${t}: the package did not pass StageSolution in this environment (status ${Vt(r)}). Missing dependencies: ${ZN(e.MissingDependencies)}. Validation: ${ZN(e.SolutionValidationResults)}.${t===Cu?" Its components cannot be checked against deploymentSettings. Nothing was imported.":" Stage it in the environment it was exported from."}`);if(r!=="Passed"&&r!==1)throw pr(t,`StageSolutionStatus is ${Vt(r)}, neither "Passed" nor "Failed"`);let n=e.SolutionComponentsDetails;if(!Array.isArray(n))throw pr(t,`SolutionComponentsDetails is not a list (${Vt(n,60)})`);let i=[],o=[],a=new Set,s=new Set;return n.forEach((l,u)=>{let c=`SolutionComponentsDetails[${u}]`;if(!fa(l))throw pr(t,`${c} is not an object`);if(typeof l.ComponentTypeName!="string")throw pr(t,`${c}.ComponentTypeName is not a string`);let d=l.ComponentTypeName.toLowerCase();if(d!=="environmentvariabledefinition"&&d!=="connectionreference")return;let f=yW(l.Attributes,`${c}.Attributes`,t),m=(p,h)=>{let g=f.get(p);if(g==null){if(h)throw pr(t,`${c}.${p} is missing`);return}if(typeof g!="string"||h&&g.length===0)throw pr(t,`${c}.${p} is not ${h?"a non-empty string":"a string"}`);return g};if(d==="environmentvariabledefinition"){let p=m("schemaname",!0);if(a.has(p.toLowerCase()))throw pr(t,`${c}.schemaname '${p}' is listed twice`);a.add(p.toLowerCase());let h=m("defaultvalue",!1),g=bW(f.get("type"),`${c}.type`,t),b=vW(f.get("isrequired"),`${c}.isrequired`,t);i.push({SchemaName:p,...h!==void 0?{DefaultValue:h}:{},...g!==void 0?{TypeId:g}:{},...b!==void 0?{IsRequired:b}:{}})}else{let p=m("connectionreferencelogicalname",!0);if(s.has(p.toLowerCase()))throw pr(t,`${c}.connectionreferencelogicalname '${p}' is listed twice`);s.add(p.toLowerCase());let h=m("connectorid",!1);o.push({LogicalName:p,...h!==void 0?{ConnectorId:h}:{}})}}),{variables:i,references:o}}function yW(e,t,r){if(!fa(e)||!Array.isArray(e.Keys)||!Array.isArray(e.Values))throw pr(r,`${t} is not { Keys: [...], Values: [...] }`);let{Keys:n,Values:i}=e;if(n.length!==i.length)throw pr(r,`${t} has ${n.length} keys but ${i.length} values`);let o=new Map;return n.forEach((a,s)=>{if(typeof a!="string")throw pr(r,`${t}.Keys[${s}] is not a string`);if(o.has(a))throw pr(r,`${t}.Keys lists '${a}' twice`);o.set(a,i[s])}),o}function bW(e,t,r){if(e!=null){if(typeof e=="number"&&Number.isSafeInteger(e))return e;if(typeof e=="string"&&/^\d{1,15}$/.test(e))return Number(e);throw pr(r,`${t} is not a whole number (${Vt(e,40)})`)}}function vW(e,t,r){if(e!=null){if(typeof e=="boolean")return e;if(typeof e=="string"&&/^(true|false)$/i.test(e))return e.toLowerCase()==="true";throw pr(r,`${t} is not true or false (${Vt(e,40)})`)}}var wW=new Set(["EnvironmentVariables","ConnectionReferences","Workflows","CanvasApps","CopilotAgents","$schema"]),CW=["Workflows","CanvasApps","CopilotAgents"],EW=new Set(["SchemaName","Value","DefaultValue","TypeId","IsRequired","Name"]),AW=new Set(["LogicalName","ConnectionId","ConnectorId"]);function fr(e,t){return new er.InvalidArgumentError(`${Cu}: deploymentSettings is not a deployment-settings file this SDK applies \u2014 ${e} ${t}. Nothing was imported.`)}function SW(e){let t="deploymentSettings";if(!fa(e))throw fr(t,`must be an object \u2014 the settings file, parsed (it was ${Vt(e,40)})`);for(let l of Object.keys(e))if(!wW.has(l))throw fr(`${t}.${l}`,"is not part of the format (EnvironmentVariables, ConnectionReferences; Workflows, CanvasApps and CopilotAgents only empty; $schema)");for(let l of CW){let u=e[l];if(u!==void 0&&!(Array.isArray(u)&&u.length===0))throw fr(`${t}.${l}`,"is a pac feature this SDK does not apply: only an empty list is accepted")}if(e.$schema!==void 0&&typeof e.$schema!="string")throw fr(`${t}.$schema`,"must be a string");let r=l=>{let u=e[l];if(u===void 0)return[];if(!Array.isArray(u))throw fr(`${t}.${l}`,`must be a list (it was ${Vt(u,40)})`);return u.map((c,d)=>{if(!fa(c))throw fr(`${t}.${l}[${d}]`,`must be an object (it was ${Vt(c,40)})`);return c})},n=(l,u,c)=>{let d=l[u];if(typeof d!="string"||d.length===0)throw fr(c,`must be a non-empty string (it was ${Vt(d,40)})`);if(d.trim()!==d)throw fr(c,`must not begin or end with whitespace (it was ${Vt(d,60)})`);return d},i=(l,u,c)=>{if(l.has(u.toLowerCase()))throw fr(c,`names '${u}' a second time (names are case-insensitive)`);l.add(u.toLowerCase())},o={variables:[],references:[]},a=new Set;r("EnvironmentVariables").forEach((l,u)=>{let c=`${t}.EnvironmentVariables[${u}]`;for(let f of Object.keys(l))if(!EW.has(f))throw fr(`${c}.${f}`,"is not part of a variable (SchemaName, Value; DefaultValue, TypeId, IsRequired, Name)");let d=n(l,"SchemaName",`${c}.SchemaName`);if(i(a,d,`${c}.SchemaName`),typeof l.Value!="string")throw fr(`${c}.Value`,`must be a string \u2014 empty to override nothing (it was ${Vt(l.Value,40)})`);l.Value.length>0&&o.variables.push({name:d,value:l.Value})});let s=new Set;return r("ConnectionReferences").forEach((l,u)=>{let c=`${t}.ConnectionReferences[${u}]`;for(let m of Object.keys(l))if(!AW.has(m))throw fr(`${c}.${m}`,m==="ConnectionInstance"?"is pac's connection-instance feature, which this SDK does not apply":"is not part of a connection reference (LogicalName, ConnectionId, ConnectorId)");let d=n(l,"LogicalName",`${c}.LogicalName`);i(s,d,`${c}.LogicalName`);let f=l.ConnectionId;if(typeof f!="string")throw fr(`${c}.ConnectionId`,`must be a string \u2014 empty to bind nothing (it was ${Vt(f,40)})`);if(f.trim()!==f)throw fr(`${c}.ConnectionId`,`must not begin or end with whitespace (it was ${Vt(f,60)})`);if(l.ConnectorId!==void 0&&typeof l.ConnectorId!="string")throw fr(`${c}.ConnectorId`,`must be a string (it was ${Vt(l.ConnectorId,40)})`);f.length>0&&o.references.push({name:d,connectionId:f,...l.ConnectorId?{connectorId:l.ConnectorId}:{}})}),o}function e_(e,t=20){return e.length===0?"none":`${e.slice(0,t).join(", ")}${e.length>t?` (+${e.length-t} more)`:""}`}function NW(e,t){var r;let n=new Map(e.variables.map(l=>[l.SchemaName.toLowerCase(),l])),i=new Map(e.references.map(l=>[l.LogicalName.toLowerCase(),l])),o=[],a=[],s={environmentVariables:[],connectionReferences:[]};for(let l of t.variables){let u=n.get(l.name.toLowerCase());if(!u){o.push(`EnvironmentVariables: '${l.name}' is not a variable of the package`);continue}a.push({"@odata.type":"Microsoft.Dynamics.CRM.environmentvariablevalue",schemaname:u.SchemaName,value:l.value}),s.environmentVariables.push(u.SchemaName)}for(let l of t.references){let u=i.get(l.name.toLowerCase());if(!u){o.push(`ConnectionReferences: '${l.name}' is not a connection reference of the package`);continue}if(l.connectorId!==void 0&&l.connectorId.toLowerCase()!==((r=u.ConnectorId)===null||r===void 0?void 0:r.toLowerCase())){o.push(`ConnectionReferences: '${l.name}' names connector '${l.connectorId}', but the package's reference is for ${u.ConnectorId?`'${u.ConnectorId}'`:"no connector"}`);continue}a.push({"@odata.type":"Microsoft.Dynamics.CRM.connectionreference",connectionreferencelogicalname:u.LogicalName,connectionid:l.connectionId,...u.ConnectorId!==void 0?{connectorid:u.ConnectorId}:{}}),s.connectionReferences.push(u.LogicalName)}if(o.length>0){let l=o.join("; "),u=e_(Kd(e.variables,d=>d.SchemaName).map(d=>d.SchemaName)),c=e_(Kd(e.references,d=>d.LogicalName).map(d=>d.LogicalName));throw new er.InvalidArgumentError(`${Cu}: deploymentSettings does not match the package \u2014 ${l}. The package's variables: ${u}; its connection references: ${c}. Nothing was imported.`)}return{parameters:a,applied:s}}async function _W(e,t){let n=`/solutions(${(0,mr.normalizeGuid)(t,"solutionId")})`;(0,Gt.ensureSuccess)(await e.delete(n),e.apiUrl(n))}ye.deleteSolution=_W});var l_=v(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.recoverFormCreate=yt.solutionMembershipProblem=yt.formWriteMismatches=yt.validateExistingForm=yt.formExistsAtId=yt.isFormRecordAt=yt.MAIN_FORM_TYPE=void 0;var Ts=oe(),n_=Tt(),i_=Jd();yt.MAIN_FORM_TYPE=2;function Yd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Qd(e){return e instanceof Error?e.message:String(e)}function t0(e,t){if(typeof e!="string"||typeof t!="string")return!1;try{return(0,Ts.normalizeGuid)(e,"a GUID")===(0,Ts.normalizeGuid)(t,"a GUID")}catch{return!1}}function r0(e,t){return Yd(e)&&t0(e.formid,t)}yt.isFormRecordAt=r0;async function TW(e,t){try{return r0((await e()).raw,t)}catch{return!1}}yt.formExistsAtId=TW;function o_(e,t){let r=e.raw;if(!Yd(r))return{problem:"it is not a record"};if(!r0(r,t))return{problem:"its formid is not the id this create sent"};if(r.type!==yt.MAIN_FORM_TYPE)return{problem:`its type is not ${yt.MAIN_FORM_TYPE} (a Main form)`};if(typeof r.objecttypecode!="string")return{problem:"its objecttypecode is not a string"};if(typeof r.name!="string")return{problem:"its name is not a string"};if(typeof r.formxml!="string"||r.formxml.length===0)return{problem:"its formxml is not a non-empty string"};if(typeof r.formpresentation!="number")return{problem:"its formpresentation is not a number"};if(typeof r.formactivationstate!="number")return{problem:"its formactivationstate is not a number"};for(let o of["uniquename","description"]){let a=r[o];if(a!=null&&typeof a!="string")return{problem:`its ${o} is neither a string nor null`}}let n=r["@odata.etag"];if(n!==void 0&&typeof n!="string")return{problem:"its @odata.etag is not a string"};if(n!==void 0&&e.etag!==null&&e.etag!==n)return{problem:"the ETag header and the @odata.etag of the body disagree"};let i=e.etag;return i===null?{problem:"the read carries no concurrency token"}:i.trim()===""||i.trim()==="*"?{problem:"its concurrency token is blank or a wildcard"}:{record:r,etag:i}}yt.validateExistingForm=o_;function a_(e,t){let r=[];for(let i of["formxml","name","objecttypecode","type"])e[i]!==t[i]&&r.push(i);let n=t.description;if(n!==void 0){let i=e.description;typeof n=="string"&&(n===""?i==null||i==="":i===n)||r.push("description")}return r}yt.formWriteMismatches=a_;async function s_(e,t){let r=e.solutionName;if(r)try{let n=await(0,n_.collectPages)(e,`/solutions${(0,Ts.odataQuery)([["$select","solutionid,uniquename"],["$filter",`uniquename eq '${(0,Ts.odataLiteral)(r)}'`]])}`,"createRecovery solution lookup");if(n.length!==1)return`the configured solution '${r}' resolves to ${n.length} solutions, not exactly one`;let[i]=n,o;return Yd(i)&&typeof i.uniquename=="string"&&typeof i.solutionid=="string"&&i.uniquename.toLowerCase()===r.toLowerCase()&&(o=(0,Ts.normalizeGuid)(i.solutionid,"solutionid")),o===void 0?`the configured solution '${r}' did not resolve to a valid solution of that name`:(await(0,n_.collectPages)(e,`/solutioncomponents${(0,Ts.odataQuery)([["$select","objectid,componenttype,_solutionid_value"],["$filter",`_solutionid_value eq ${o} and componenttype eq ${i_.SolutionComponentType.SystemForm} and objectid eq ${t}`]])}`,"createRecovery solution membership")).some(l=>Yd(l)&&l.componenttype===i_.SolutionComponentType.SystemForm&&t0(l.objectid,t)&&t0(l._solutionid_value,o))?void 0:`the form is not a component of the configured solution '${r}'`}catch(n){return`membership in the configured solution '${r}' could not be established (${Qd(n)})`}}yt.solutionMembershipProblem=s_;async function DW(e){try{return await IW(e)}catch(t){return{refused:`the recovery could not be completed (${Qd(t)})`}}}yt.recoverFormCreate=DW;async function IW(e){let{client:t,read:r,sent:n,authoredFormType:i,project:o}=e;if(i!=="Main"||n.type!==yt.MAIN_FORM_TYPE)return{refused:`only a Main form is adopted (this one is authored as ${String(i)})`};let a=n.formid;if(typeof a!="string")return{refused:"the create sent no formid to look for"};let s;try{s=await r()}catch(f){return{refused:`the existing row could not be read (${Qd(f)})`}}let l=o_(s,a);if("problem"in l)return{refused:`the existing row cannot be trusted: ${l.problem}`};let u=a_(l.record,n);if(u.length>0)return{refused:`the existing row is not what this create wrote (it differs in ${u.join(", ")})`};let c;try{c=o(l.record)}catch(f){return{refused:`the existing row could not be read into a form (${Qd(f)})`}}let d=await s_(t,a);return d!==void 0?{refused:d}:{adopted:{artifact:c,etag:l.etag}}}});var Zd=v(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.disassociateRecords=Ye.associateRecords=Ye.createRecordsBulk=Ye.upsertRecord=Ye.queryAllRecords=Ye.queryRecords=Ye.getRecord=Ye.deleteRecord=Ye.updateRecord=Ye.createRecord=void 0;var n0=Tt(),Rn=fe(),tr=oe(),Ds=Q(),ni=$d();function Xd(e){let t=e,r=!1,n={};for(let i of Object.keys(t)){let o=t[i];Array.isArray(o)&&o.every(a=>typeof a=="number")?(n[i]=o.join(","),r=!0):n[i]=o}return r?n:e}async function OW(e,t,r){let i=`/${await(0,ni.resolveEntitySetName)(e,t)}`,o=(0,Rn.ensureSuccess)(await e.post(i,Xd(r)),e.apiUrl(i)),a=(0,Rn.readCreatedId)(o,`${t}id`);if(!a)throw new Ds.InvalidArgumentError(`Dataverse did not return an id for the created '${t}' row`);return{id:a,entityType:t}}Ye.createRecord=OW;async function PW(e,t,r,n){let i=(0,tr.normalizeGuid)(r,"id"),a=`/${await(0,ni.resolveEntitySetName)(e,t)}(${i})`;(0,Rn.ensureSuccess)(await e.patch(a,Xd(n)),e.apiUrl(a))}Ye.updateRecord=PW;async function RW(e,t,r){let n=(0,tr.normalizeGuid)(r,"id"),o=`/${await(0,ni.resolveEntitySetName)(e,t)}(${n})`;(0,Rn.ensureSuccess)(await e.delete(o),e.apiUrl(o))}Ye.deleteRecord=RW;async function LW(e,t,r,n){let i=(0,tr.normalizeGuid)(r,"id"),o=await(0,ni.resolveEntitySetName)(e,t),a=(0,tr.odataQuery)([["$select",n&&n.length>0?n.join(","):void 0]]),s=`/${o}(${i})${a}`,l=(0,Rn.ensureSuccess)(await e.get(s),e.apiUrl(s)),u=l.body;if(u===null||typeof u!="object"||Array.isArray(u))throw new Ds.ConnectionError(e.apiUrl(s),l.status,`getRecord: read returned a malformed row \u2014 expected an OData entity object but got ${Array.isArray(u)?"an array":(0,n0.describeMalformedValue)(u)}; refusing to read it as a row.`);return u}Ye.getRecord=LW;function kW(e){return e?.fetchXml?(0,tr.odataQuery)([["fetchXml",e.fetchXml]]):(0,tr.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 u_(e,t,r){var n;if(r?.paginate){if(r.top!==void 0)throw new Ds.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 Ds.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,ni.resolveEntitySetName)(e,t)}${kW(r)}`;if(r?.paginate)return(0,n0.collectPages)(e,o,"queryRecords");let a=(0,Rn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(n=a.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(s))throw new Ds.ConnectionError(e.apiUrl(o),a.status,`queryRecords: read returned a malformed page \u2014 expected an OData 'value' array but got ${(0,n0.describeMalformedValue)(s)}; refusing to read it as rows.`);return s}Ye.queryRecords=u_;async function $W(e,t,r){return u_(e,t,{...r,paginate:!0})}Ye.queryAllRecords=$W;function xW(e){if("id"in e)return`(${(0,tr.normalizeGuid)(e.id,"id")})`;let t=typeof e.value=="string"?`'${(0,tr.odataPathLiteral)(e.value)}'`:e.value;return`(${(0,tr.assertODataName)(e.key,"alternate key name")}=${t})`}async function FW(e,t,r,n){let i=xW(r),a=`/${await(0,ni.resolveEntitySetName)(e,t)}${i}`,s=(0,Rn.ensureSuccess)(await e.patch(a,Xd(n)),e.apiUrl(a)),l=s.status===201,u=(0,Rn.readCreatedId)(s,`${t}id`);return{id:u??("id"in r?(0,tr.normalizeGuid)(r.id,"id"):""),created:l}}Ye.upsertRecord=FW;async function MW(e,t,r){var n,i;if(r.length===0)return[];let o=await(0,ni.resolveEntitySetName)(e,t),a=r.map(c=>({"@odata.type":`Microsoft.Dynamics.CRM.${t}`,...Xd(c)})),s=`/${o}/Microsoft.Dynamics.CRM.CreateMultiple`,u=(i=(n=(0,Rn.ensureSuccess)(await e.post(s,{Targets:a}),e.apiUrl(s)).body)===null||n===void 0?void 0:n.Ids)!==null&&i!==void 0?i:[];if(u.length!==r.length)throw new Ds.InvalidArgumentError(`CreateMultiple on '${t}' returned ${u.length} id(s) for ${r.length} row(s)`);return u}Ye.createRecordsBulk=MW;async function UW(e,t,r,n){let i=(0,tr.normalizeGuid)(r,"id"),o=(0,tr.normalizeGuid)(n.targetId,"targetId"),a=await(0,ni.resolveEntitySetName)(e,t),s=await(0,ni.resolveEntitySetName)(e,n.targetEntity),l=(0,tr.assertODataName)(n.relationshipName,"relationshipName"),u=`/${a}(${i})/${l}/$ref`,c={"@odata.id":e.apiUrl(`/${s}(${o})`)};(0,Rn.ensureSuccess)(await e.post(u,c),e.apiUrl(u))}Ye.associateRecords=UW;async function BW(e,t,r,n,i){let o=(0,tr.normalizeGuid)(r,"id"),a=(0,tr.normalizeGuid)(i,"targetId"),s=await(0,ni.resolveEntitySetName)(e,t),l=(0,tr.assertODataName)(n,"relationshipName"),u=`/${s}(${o})/${l}(${a})/$ref`;(0,Rn.ensureSuccess)(await e.delete(u),e.apiUrl(u))}Ye.disassociateRecords=BW});var pa=v(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.base64ToUtf8=mn.base64ToBytes=mn.bytesToBase64=mn.utf8ToBase64=mn.utf8ToBytes=void 0;var i0=32768,Lr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Eu(){return globalThis}function c_(e){let t=[];for(let r=0;r<e.length;r+=1){let n=e.charCodeAt(r);if(n>=55296&&n<=56319){let i=r+1<e.length?e.charCodeAt(r+1):0;i>=56320&&i<=57343?(n=(n-55296<<10)+(i-56320)+65536,r+=1):n=65533}else n>=56320&&n<=57343&&(n=65533);n<128?t.push(n):n<2048?t.push(192|n>>6,128|n&63):n<65536?t.push(224|n>>12,128|n>>6&63,128|n&63):t.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|n&63)}return Uint8Array.from(t)}function qW(e){let t="";for(let r=0;r<e.length;r+=i0)t+=String.fromCharCode(...e.subarray(r,r+i0));return t}function VW(e){let t="";for(let r=0;r<e.length;r+=1){let n=String.fromCharCode(e.charCodeAt(r)&255);if(n==="=")break;n==="-"?t+="+":n==="_"?t+="/":Lr.indexOf(n)>=0&&(t+=n)}for(t.length%4===1&&(t=t.slice(0,-1));t.length%4!==0;)t+="=";return t}function GW(e){let t="",r=0;for(;r+2<e.length;r+=3){let i=e[r]<<16|e[r+1]<<8|e[r+2];t+=Lr[i>>18&63]+Lr[i>>12&63]+Lr[i>>6&63]+Lr[i&63]}let n=e.length-r;if(n===1){let i=e[r]<<16;t+=`${Lr[i>>18&63]}${Lr[i>>12&63]}==`}else if(n===2){let i=e[r]<<16|e[r+1]<<8,o=Lr[i>>18&63],a=Lr[i>>12&63],s=Lr[i>>6&63];t+=`${o}${a}${s}=`}return t}function WW(e){let t=e.endsWith("==")?2:e.endsWith("=")?1:0,r=e.length/4*3-t,n=new Uint8Array(r>0?r:0),i=0;for(let o=0;o<e.length;o+=4){let a=Lr.indexOf(e[o])<<18|Lr.indexOf(e[o+1])<<12|(e[o+2]==="="?0:Lr.indexOf(e[o+2]))<<6|(e[o+3]==="="?0:Lr.indexOf(e[o+3]));i<r&&(n[i++]=a>>16&255),i<r&&(n[i++]=a>>8&255),i<r&&(n[i++]=a&255)}return n}function zW(e){let t=Eu();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"utf8"));let r=t.TextEncoder;return r?new r().encode(e):c_(e)}mn.utf8ToBytes=zW;function jW(e){let t=Eu();if(t.Buffer)return t.Buffer.from(e,"utf8").toString("base64");let r=t.TextEncoder;return d_(r?new r().encode(e):c_(e))}mn.utf8ToBase64=jW;function d_(e){let t=Eu();return t.Buffer?t.Buffer.from(e).toString("base64"):t.btoa?t.btoa(qW(e)):GW(e)}mn.bytesToBase64=d_;function f_(e){let t=Eu();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"base64"));let r=VW(e);if(t.atob){let n=t.atob(r);return Uint8Array.from(n,i=>i.charCodeAt(0))}return WW(r)}mn.base64ToBytes=f_;function HW(e){let t=[],r="",n=()=>{r+=String.fromCharCode(...t),t.length=0},i=a=>{if(a>65535){let s=a-65536;t.push(55296+(s>>10),56320+(s&1023))}else t.push(a);t.length>=i0&&n()},o=0;for(;o<e.length;){let a=e[o],s=0,l=0,u=128,c=191;if(a<128){i(a),o+=1;continue}else if(a>=194&&a<=223)s=1,l=a&31;else if(a>=224&&a<=239)s=2,l=a&15,u=a===224?160:128,c=a===237?159:191;else if(a>=240&&a<=244)s=3,l=a&7,u=a===240?144:128,c=a===244?143:191;else{i(65533),o+=1;continue}let d=o+1,f=!0;for(let m=0;m<s;m+=1,d+=1){let p=d<e.length?e[d]:-1;if(p<u||p>c){f=!1;break}u=128,c=191,l=l<<6|p&63}f?(i(l),o=d):(i(65533),o=d)}return n(),r}function KW(e){let t=Eu();return t.Buffer?t.Buffer.from(e,"base64").toString("utf8"):HW(f_(e))}mn.base64ToUtf8=KW});var g_=v(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.deleteWebResource=ii.getWebResource=ii.updateWebResource=ii.createWebResource=void 0;var JW=jr(),Au=fe(),ef=oe(),YW=pa(),p_=Q(),QW={html:1,css:2,js:3,xml:4,png:5,jpg:6,gif:7,xsl:9,ico:10,svg:11,resx:12};function m_(e){if(e.contentBase64!==void 0)return e.contentBase64;if(e.content!==void 0)return(0,YW.utf8ToBase64)(e.content)}async function h_(e,t){return(0,JW.publishWebResourceById)(e,t)}async function XW(e,t){var r;let n=m_(t);if(n===void 0)throw new p_.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:QW[t.type],content:n};t.description&&(i.description=t.description);let o=(0,Au.ensureSuccess)(await e.post("/webresourceset",i),e.apiUrl("/webresourceset")),a=(0,Au.readCreatedId)(o,"webresourceid");if(!a)throw new p_.InvalidArgumentError(`Dataverse did not return an id for web resource '${t.name}'`);return t.publish!==!1&&await h_(e,a),{id:a,name:t.name}}ii.createWebResource=XW;async function ZW(e,t,r){let n=(0,ef.normalizeGuid)(t,"id"),i={},o=m_(r);o!==void 0&&(i.content=o),r.displayName!==void 0&&(i.displayname=r.displayName),r.description!==void 0&&(i.description=r.description);let a=`/webresourceset(${n})`;(0,Au.ensureSuccess)(await e.patch(a,i),e.apiUrl(a)),r.publish!==!1&&await h_(e,n)}ii.updateWebResource=ZW;async function e6(e,t){var r;let i=`/webresourceset(${(0,ef.normalizeGuid)(t,"id")})${(0,ef.odataQuery)([["$select","name,displayname,webresourcetype,content,description"]])}`;return(r=(0,Au.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)!==null&&r!==void 0?r:{}}ii.getWebResource=e6;async function t6(e,t){let n=`/webresourceset(${(0,ef.normalizeGuid)(t,"id")})`;(0,Au.ensureSuccess)(await e.delete(n),e.apiUrl(n))}ii.deleteWebResource=t6});var tf=v(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.applyAppSettings=Lt.setAppSetting=Lt.readAppSettings=Lt.resolveSettingDefinitions=Lt.APP_SETTING_UNSET=Lt.APP_SETTING_OFF=Lt.APP_SETTING_ON=Lt.HEADER_AND_NAVIGATION_REFRESH=void 0;var Is=fe(),qi=oe();Lt.HEADER_AND_NAVIGATION_REFRESH="HeaderAndNavigationRefresh";Lt.APP_SETTING_ON="2";Lt.APP_SETTING_OFF="1";Lt.APP_SETTING_UNSET="0";function v_(e,t){return"/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,qi.odataQuery)([["$select",e],["$filter",t]])}async function w_(e,t){var r,n;let i=[...new Set(t.filter(Boolean))],o=new Map;if(i.length===0)return o;let a=i.map(c=>`uniquename eq '${(0,qi.odataLiteral)(c)}'`).join(" or "),s=`/settingdefinitions${(0,qi.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",a]])}`,u=((n=(r=(0,Is.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]).filter(Boolean);for(let c of u)c.uniquename&&o.set(c.uniquename,c);return o}Lt.resolveSettingDefinitions=w_;async function r6(e,t){var r,n,i,o;let a=(0,qi.normalizeGuid)(t,"App id"),s=v_("appsettingid,value,_settingdefinitionid_value",`_parentappmoduleid_value eq ${a}`),u=((n=(r=(0,Is.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(f=>f._settingdefinitionid_value).filter(Boolean))],d=new Map;if(c.length>0){let f=c.map(h=>`settingdefinitionid eq ${(0,qi.normalizeGuid)(h,"Setting definition id")}`).join(" or "),m=`/settingdefinitions${(0,qi.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",f]])}`,p=(0,Is.ensureSuccess)(await e.get(m),e.apiUrl(m));for(let h of((o=(i=p.body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[]).filter(Boolean))h.settingdefinitionid&&d.set(h.settingdefinitionid.toLowerCase(),h)}return u.map(f=>{var m,p,h,g,b;let w=d.get(((m=f._settingdefinitionid_value)!==null&&m!==void 0?m:"").toLowerCase());return{id:(p=f.appsettingid)!==null&&p!==void 0?p:"",name:(g=(h=w?.uniquename)!==null&&h!==void 0?h:f._settingdefinitionid_value)!==null&&g!==void 0?g:"",value:(b=f.value)!==null&&b!==void 0?b:"",...w?.displayname?{displayName:w.displayname}:{}}})}Lt.readAppSettings=r6;async function y_(e,t,r){var n,i,o;let a=v_("appsettingid,value",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${r}`),l=((i=(n=(0,Is.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]).filter(Boolean)[0];return l?.appsettingid?{id:l.appsettingid,value:(o=l.value)!==null&&o!==void 0?o:""}:void 0}async function C_(e,t,r,n){let i=(0,qi.normalizeGuid)(t,"App id"),a=(await w_(e,[r])).get(r),s=a?.settingdefinitionid;if(!s)throw new Error(`App setting '${r}' is not available in this environment: no settingdefinition row has that uniquename. The feature may be version-gated or its solution may not be installed.`);let l=(0,qi.normalizeGuid)(s,"Setting definition id"),u=await y_(e,i,l);if(u)return b_(e,u,n);let c="/appsettings",d={"[email protected]":`/appmodules(${i})`,"[email protected]":`/settingdefinitions(${l})`,value:n},f,m;try{if(f=await e.post(c,d),f.status>=200&&f.status<300)return"created"}catch(h){m=h}let p;try{p=await y_(e,i,l)}catch{p=void 0}if(p)return b_(e,p,n);throw f&&(0,Is.ensureSuccess)(f,e.apiUrl(c)),m}Lt.setAppSetting=C_;async function b_(e,t,r){if(t.value===r)return"unchanged";let n=`/appsettings(${(0,qi.normalizeGuid)(t.id,"App setting id")})`;return(0,Is.ensureSuccess)(await e.patch(n,{value:r}),e.apiUrl(n)),"updated"}async function n6(e,t,r){var n;let i=[];for(let[o,a]of Object.entries(r??{}))try{await C_(e,t,o,a)}catch(s){i.push(`App setting '${o}' was not applied: ${(n=s?.message)!==null&&n!==void 0?n:String(s)} The app was created; set it later with setAppSetting().`)}return i}Lt.applyAppSettings=n6});var nf=v(rf=>{"use strict";Object.defineProperty(rf,"__esModule",{value:!0});rf.HEADER_NAV_BOOLEAN_RULE=void 0;rf.HEADER_NAV_BOOLEAN_RULE="headerAndNavigationRefresh-must-be-boolean"});var o0=v(af=>{"use strict";Object.defineProperty(af,"__esModule",{value:!0});af.asUint8Array=void 0;var i6=Object.getPrototypeOf(Uint8Array.prototype);function of(e){let t=Object.getOwnPropertyDescriptor(i6,e);if(!t?.get)throw new Error(`this JavaScript engine has no %TypedArray%.prototype getter for ${String(e)}`);return t.get}var o6=of(Symbol.toStringTag),a6=of("buffer"),s6=of("byteOffset"),l6=of("byteLength");function u6(e){if(o6.call(e)==="Uint8Array")return new Uint8Array(a6.call(e),s6.call(e),l6.call(e))}af.asUint8Array=u6});var I_=v(Os=>{"use strict";Object.defineProperty(Os,"__esModule",{value:!0});Os.zipStored=Os.crc32=void 0;var c6=Q(),d6=pa(),f6=o0(),p6=67324752,m6=33639248,h6=101010256,sf=30,a0=46,g6=22,E_=10,y6=20,A_=2048,S_=0,N_=0,__=33,b6=65535,v6=65535,T_=4294967295,w6=3988292384,lf;function C6(){if(!lf){lf=new Uint32Array(256);for(let e=0;e<256;e+=1){let t=e;for(let r=0;r<8;r+=1)t=t&1?w6^t>>>1:t>>>1;lf[e]=t}}return lf}function D_(e){let t=C6(),r=4294967295;for(let n=0;n<e.length;n+=1)r=t[(r^e[n])&255]^r>>>8;return(r^4294967295)>>>0}Os.crc32=D_;function oi(e){return new c6.InvalidArgumentError(`zip: ${e}`)}function E6(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))return!1;t+=1}else if(r>=56320&&r<=57343)return!1}return!0}function A6(e){if(typeof e!="string"||e.length===0)throw oi("every entry needs a non-empty name.");if(e.includes("\\"))throw oi(`'${e}' contains a backslash; ZIP paths use '/'.`);if(/^[A-Za-z]:/.test(e))throw oi(`'${e}' starts with a drive letter; ZIP paths are relative.`);if(e.split("/").some(t=>t===""||t==="."||t===".."))throw oi(`'${e}' is not a relative path of named segments (no leading, trailing or doubled '/', no '.' or '..').`);if(!E6(e))throw oi(`'${e}' contains an unpaired surrogate, which has no UTF-8 form.`);return e}function S6(e,t=T_){if(e.length>b6)throw oi(`${e.length} entries is more than the 65,535 a ZIP can count without ZIP64.`);let r=Math.min(t,T_),n=new Set,i=[],o=g6;for(let f of e){let m=A6(f.name);if(n.has(m))throw oi(`'${m}' appears twice.`);n.add(m);let p=(0,f6.asUint8Array)(f.data);if(!p)throw oi(`the data for '${m}' must be a Uint8Array.`);let h=(0,d6.utf8ToBytes)(m);if(h.length>v6)throw oi(`a name of ${h.length} UTF-8 bytes is more than the 65,535 a header can record.`);o+=sf+a0+2*h.length+p.byteLength,i.push({nameBytes:h,data:p})}if(o>r)throw oi(`the archive would be ${o} bytes, more than the ${r} allowed.`);let a=new Uint8Array(o),s=new DataView(a.buffer),l=[],u=[],c=0;for(let{nameBytes:f,data:m}of i){let p=D_(m);l.push(c),u.push(p),s.setUint32(c,p6,!0),s.setUint16(c+4,E_,!0),s.setUint16(c+6,A_,!0),s.setUint16(c+8,S_,!0),s.setUint16(c+10,N_,!0),s.setUint16(c+12,__,!0),s.setUint32(c+14,p,!0),s.setUint32(c+18,m.byteLength,!0),s.setUint32(c+22,m.byteLength,!0),s.setUint16(c+26,f.length,!0),a.set(f,c+sf),a.set(m,c+sf+f.length),c+=sf+f.length+m.byteLength}let d=c;return i.forEach(({nameBytes:f,data:m},p)=>{s.setUint32(c,m6,!0),s.setUint16(c+4,y6,!0),s.setUint16(c+6,E_,!0),s.setUint16(c+8,A_,!0),s.setUint16(c+10,S_,!0),s.setUint16(c+12,N_,!0),s.setUint16(c+14,__,!0),s.setUint32(c+16,u[p],!0),s.setUint32(c+20,m.byteLength,!0),s.setUint32(c+24,m.byteLength,!0),s.setUint16(c+28,f.length,!0),s.setUint32(c+42,l[p],!0),a.set(f,c+a0),c+=a0+f.length}),s.setUint32(c,h6,!0),s.setUint16(c+8,i.length,!0),s.setUint16(c+10,i.length,!0),s.setUint32(c+12,c-d,!0),s.setUint32(c+16,d,!0),a}Os.zipStored=S6});var W_=v($e=>{"use strict";Object.defineProperty($e,"__esModule",{value:!0});$e.pcfManifestsEquivalent=$e.buildPcfSolutionZip=$e.pcfContentTypesXml=$e.pcfCustomizationsXml=$e.pcfSolutionXml=$e.pcfWebResourceName=$e.pcfControlName=$e.checkPcfControlPackage=$e.unboundPrefixes=$e.PCF_WEB_RESOURCE_TYPES=void 0;var N6=Q(),Qr=cu(),uf=pa(),_6=o0(),T6=I_();$e.PCF_WEB_RESOURCE_TYPES={html:1,htm:1,css:2,js:3,xml:4,png:5,jpg:6,jpeg:6,gif:7,xsl:9,xslt:9,ico:10,svg:11,resx:12};var D6=["code","css","resx","img","html"],O_=/^[A-Za-z_][A-Za-z0-9_]*$/,I6=/^\d+\.\d+\.\d+$/,O6=/^[A-Za-z0-9_.-]+$/;function bt(e){return new N6.InvalidArgumentError(`registerPcfControl: ${e}`)}function x_(e){return(0,Qr.elementChildren)(e).filter(t=>t.localName==="control"&&!t.namespaceURI)}function F_(e){let t=[],r=n=>{n.prefix&&!n.namespaceURI&&t.push(`<${n.tagName}>`);for(let i=0;i<n.attributes.length;i+=1){let o=n.attributes.item(i);o.prefix&&!o.namespaceURI&&t.push(`${o.name}="\u2026" on <${n.tagName}>`)}(0,Qr.elementChildren)(n).forEach(r)};return r(e),t}$e.unboundPrefixes=F_;function s0(e){let t=(0,Qr.parseManifestRoot)(e),r=F_(t);if(r.length>0)throw new Error(`the manifest uses a prefix no namespace declaration binds: ${r.join(", ")}.`);if(t.localName!=="manifest")throw new Error(`the manifest's root element is <${t.tagName}>, not <manifest>.`);if(t.namespaceURI)throw new Error(`the manifest's root element is <manifest> in the namespace '${t.namespaceURI}', not in no namespace.`);let n=x_(t)[0];if(!n)throw new Error("the control manifest has no <control> element");return{root:t,control:n}}function P6(e){let t=e.split("/");if(!t.every(a=>O6.test(a)&&a!=="."&&a!==".."))throw bt(`the resource path '${e}' is not a web resource name: use letters, digits, '_', '.' and '-' in '/'-separated segments, with no '.' or '..' segment.`);let r=t[t.length-1],n=r.lastIndexOf("."),i=n>0?r.slice(n+1).toLowerCase():"",o=Object.prototype.hasOwnProperty.call($e.PCF_WEB_RESOURCE_TYPES,i)?$e.PCF_WEB_RESOURCE_TYPES[i]:void 0;if(o===void 0)throw bt(`the resource path '${e}' has no web resource type; the extensions are ${Object.keys($e.PCF_WEB_RESOURCE_TYPES).join(", ")}.`);return o}function R6(e){var t,r,n;if(typeof e!="object"||e===null)throw bt("the control package must be an object with a manifest and files.");let{manifest:i,files:o}=e;if(typeof i!="string"||i.length===0)throw bt("the manifest must be the built ControlManifest.xml, as a string.");if(typeof o!="object"||o===null||Array.isArray(o))throw bt("files must be an object mapping each resource path to its bytes.");let a,s;try{({root:a,control:s}=s0(i))}catch(b){throw bt(b.message)}if(x_(a).length!==1)throw bt("the manifest must hold exactly one <control>.");let l=(t=(0,Qr.attr)(s,"namespace"))!==null&&t!==void 0?t:"",u=(r=(0,Qr.attr)(s,"constructor"))!==null&&r!==void 0?r:"",c=(n=(0,Qr.attr)(s,"version"))!==null&&n!==void 0?n:"";if(!l.split(".").every(b=>O_.test(b)))throw bt(`the control's namespace '${l}' is not a dotted identifier.`);if(!O_.test(u))throw bt(`the control's constructor '${u}' is not an identifier.`);if(!I6.test(c))throw bt(`the control's version '${c}' is not major.minor.patch.`);let d=(0,Qr.firstLevel)(s,"resources");if(d.length!==1)throw bt("the manifest must hold exactly one <resources> element.");let f=[],m=0;for(let b of(0,Qr.elementChildren)(d[0])){let w=(0,Qr.attr)(b,"path");if(!D6.includes(b.tagName)){if(w!==null)throw bt(`<${b.tagName} path="${w}"> is not a resource kind the SDK registers.`);continue}if(!w)throw bt(`a <${b.tagName}> resource has no path.`);m+=b.tagName==="code"?1:0,f.push(w)}if(m!==1)throw bt(`the manifest must name exactly one <code> resource; it names ${m}.`);let p=new Map,h=[];for(let b of f){let w=P6(b),C=b.toLowerCase();if(C==="controlmanifest.xml")throw bt(`the resource path '${b}' is where the package puts the manifest itself.`);let S=p.get(C);if(S!==void 0)throw bt(`the manifest names '${b}' and '${S}', which are the same web resource.`);if(p.set(C,b),!Object.prototype.hasOwnProperty.call(o,b))throw bt(`the manifest names '${b}', but files has no such key.`);let O=(0,_6.asUint8Array)(o[b]);if(!O)throw bt(`files['${b}'] must be a Uint8Array.`);h.push({path:b,data:O,webResourceType:w})}let g=Object.keys(o).filter(b=>!f.includes(b));if(g.length>0)throw bt(`files holds ${g.map(b=>`'${b}'`).join(", ")}, which the manifest does not name.`);return{namespace:l,constructorName:u,version:c,manifest:i,files:h}}$e.checkPcfControlPackage=R6;function L6(e,t){return`${e}_${t.namespace}.${t.constructorName}`}$e.pcfControlName=L6;function k6(e,t){return`cc_${e.namespace}.${e.constructorName}/${t}`}$e.pcfWebResourceName=k6;function Ps(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}var $6=["City","County","Country","Fax","FreightTermsCode","ImportSequenceNumber","Latitude","Line1","Line2","Line3","Longitude","Name","PostalCode","PostOfficeBox","PrimaryContactName"],x6=["StateOrProvince","Telephone1","Telephone2","Telephone3","TimeZoneRuleVersionNumber","UPSZone","UTCOffset","UTCConversionTimeZoneCode"];function P_(e){let t=r=>r.map(n=>`<${n} xsi:nil="true"></${n}>`).join("");return`<Address><AddressNumber>${e}</AddressNumber><AddressTypeCode>1</AddressTypeCode>${t($6)}<ShippingMethodCode>1</ShippingMethodCode>${t(x6)}</Address>`}function M_(e){let t=Ps(e.solutionUniqueName),r=Ps(e.publisherUniqueName);return`<ImportExportXml version="9.1.0.643" SolutionPackageVersion="9.1" languagecode="1033" generatedBy="CrmLive" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><SolutionManifest><UniqueName>${t}</UniqueName><LocalizedNames><LocalizedName description="${t}" languagecode="1033" /></LocalizedNames><Descriptions /><Version>1.0</Version><Managed>0</Managed><Publisher><UniqueName>${r}</UniqueName><LocalizedNames><LocalizedName description="${r}" languagecode="1033" /></LocalizedNames><Descriptions><Description description="${r}" languagecode="1033" /></Descriptions><EMailAddress xsi:nil="true"></EMailAddress><SupportingWebsiteUrl xsi:nil="true"></SupportingWebsiteUrl><CustomizationPrefix>${Ps(e.prefix)}</CustomizationPrefix><CustomizationOptionValuePrefix>${e.optionValuePrefix}</CustomizationOptionValuePrefix><Addresses>${P_(1)}${P_(2)}</Addresses></Publisher><RootComponents><RootComponent type="66" schemaName="${Ps(e.controlName)}" behavior="0" /></RootComponents><MissingDependencies /></SolutionManifest></ImportExportXml>`}$e.pcfSolutionXml=M_;function U_(e){let t=Ps(e);return`<ImportExportXml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><Entities></Entities><Roles></Roles><Workflows></Workflows><FieldSecurityProfiles></FieldSecurityProfiles><Templates /><EntityMaps /><EntityRelationships /><OrganizationSettings /><optionsets /><CustomControls><CustomControl><Name>${t}</Name><FileName>/Controls/${t}/ControlManifest.xml</FileName><ForceUpdate>true</ForceUpdate></CustomControl></CustomControls><EntityDataProviders /><Languages><Language>1033</Language></Languages></ImportExportXml>`}$e.pcfCustomizationsXml=U_;function B_(e){let t=["xml"];for(let n of e){let i=n.slice(n.lastIndexOf(".")+1).toLowerCase();t.includes(i)||t.push(i)}return`<?xml version="1.0" encoding="utf-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">${t.map(n=>`<Default Extension="${Ps(n)}" ContentType="application/octet-stream" />`).join("")}</Types>`}$e.pcfContentTypesXml=B_;function F6(e){let t=`Controls/${e.controlName}`,r=[{name:"customizations.xml",data:(0,uf.utf8ToBytes)(U_(e.controlName))},{name:"solution.xml",data:(0,uf.utf8ToBytes)(M_(e))},...e.control.files.map(n=>({name:`${t}/${n.path}`,data:n.data})),{name:`${t}/ControlManifest.xml`,data:(0,uf.utf8ToBytes)(e.control.manifest)},{name:"[Content_Types].xml",data:(0,uf.utf8ToBytes)(B_(e.control.files.map(n=>n.path)))}];return(0,T6.zipStored)(r)}$e.buildPcfSolutionZip=F6;var M6=/^[ \t\r\n]*$/,q_=1,c0=3,U6=4,V_=7;function cf(e,t){let r=(0,Qr.attr)(e,"xml:space");return r==="preserve"?!0:r==="default"?!1:t}function R_(e,t){var r;let n=[],i=e.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];(a.nodeType===q_||a.nodeType===U6||a.nodeType===V_||a.nodeType===c0&&(t||!M6.test((r=a.nodeValue)!==null&&r!==void 0?r:"")))&&n.push(a)}return n}function L_(e){return e.length>0&&e.every(t=>t.nodeType===c0)?e.map(t=>{var r;return(r=t.nodeValue)!==null&&r!==void 0?r:""}).join(""):void 0}function k_(e,t){var r;let n="",i=t;for(;i<e.length&&e[i].nodeType===c0;)n+=(r=e[i].nodeValue)!==null&&r!==void 0?r:"",i+=1;return{text:n,next:i}}function l0(e,t){return(e.namespaceURI||null)===(t.namespaceURI||null)&&e.localName===t.localName}function B6(e,t,r,n){if(e.nodeType!==t.nodeType)return!1;if(e.nodeType===q_)return G_(e,t,r,n);if(e.nodeType===V_){let i=e,o=t;return i.target===o.target&&i.data===o.data}return e.nodeValue===t.nodeValue}function q6(e,t,r,n){let i=L_(e);if(i!==void 0)return i===L_(t);if(e.length===0)return t.length===0;let o=0,a=0;for(;;){let s=k_(e,o),l=k_(t,a);if(s.text!==l.text)return!1;if(o=s.next,a=l.next,o>=e.length&&a>=t.length)return!0;if(o>=e.length||a>=t.length||!B6(e[o],t[a],r,n))return!1;o+=1,a+=1}}function G_(e,t,r,n){if(!l0(e,t)||e.attributes.length!==t.attributes.length)return!1;for(let a=0;a<e.attributes.length;a+=1){let s=e.attributes.item(a),l=t.attributes.item(a);if(!l0(s,l)||s.value!==l.value)return!1}let i=cf(e,r),o=cf(t,n);return q6(R_(e,i),R_(t,o),i,o)}function u0(e){return(0,Qr.elementChildren)(e).reduce((t,r)=>t+1+u0(r),0)}function $_(e){return cf(e,cf(e.parentNode,!1))}function V6(e,t){let r,n;try{r=s0(t).control,n=s0(e).control}catch{return!1}if(r.attributes.length!==n.attributes.length)return!1;for(let u=0;u<r.attributes.length;u+=1){let c=r.attributes.item(u),d;for(let m=0;m<n.attributes.length&&!d;m+=1){let p=n.attributes.item(m);d=l0(c,p)?p:void 0}if(!d||!(c.localName==="version"&&!c.namespaceURI)&&c.value!==d.value)return!1}if(u0(r)!==u0(n))return!1;let i=(0,Qr.elementChildren)(r),o=(0,Qr.elementChildren)(n),a=$_(r),s=$_(n),l=Math.min(i.length,o.length);for(let u=0;u<l;u+=1)if(!G_(i[u],o[u],a,s))return!1;return!0}$e.pcfManifestsEquivalent=V6});var z_=v(df=>{"use strict";Object.defineProperty(df,"__esModule",{value:!0});df.sha256Hex=void 0;var G6=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ai=(e,t)=>e>>>t|e<<32-t;function W6(e){let t=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),r=new Uint8Array(Math.ceil((e.length+9)/64)*64);r.set(e),r[e.length]=128;let n=new DataView(r.buffer);n.setUint32(r.length-8,Math.floor(e.length/536870912)),n.setUint32(r.length-4,e.length%536870912*8);let i=new Uint32Array(64);for(let o=0;o<r.length;o+=64){for(let p=0;p<16;p+=1)i[p]=n.getUint32(o+p*4);for(let p=16;p<64;p+=1){let h=ai(i[p-15],7)^ai(i[p-15],18)^i[p-15]>>>3,g=ai(i[p-2],17)^ai(i[p-2],19)^i[p-2]>>>10;i[p]=i[p-16]+h+i[p-7]+g>>>0}let[a,s,l,u,c,d,f,m]=t;for(let p=0;p<64;p+=1){let h=m+(ai(c,6)^ai(c,11)^ai(c,25))+(c&d^~c&f)+G6[p]+i[p]>>>0,g=(ai(a,2)^ai(a,13)^ai(a,22))+(a&s^a&l^s&l)>>>0;m=f,f=d,d=c,c=u+h>>>0,u=l,l=s,s=a,a=h+g>>>0}t[0]+=a,t[1]+=s,t[2]+=l,t[3]+=u,t[4]+=c,t[5]+=d,t[6]+=f,t[7]+=m}return Array.from(t,o=>o.toString(16).padStart(8,"0")).join("")}df.sha256Hex=W6});var aT=v(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.registerPcfControl=Ne.readJobVerdict=Ne.PCF_REGISTRATION_UNVERIFIED_CODE=Ne.PCF_MANIFEST_CHANGE_NEEDS_PUBLISH_ALL_CODE=Ne.PCF_RESOURCE_NAME_TAKEN_CODE=Ne.PCF_CONTROL_MANAGED_CODE=Ne.PCF_CONTROL_AMBIGUOUS_CODE=Ne.PCF_CONTROL_NAME_TAKEN_CODE=Ne.PCF_TARGET_SOLUTION_MANAGED_CODE=void 0;var z6=Es(),_o=Tt(),Vi=W_(),X_=jr(),d0=Jd(),We=Q(),j6=cu(),Su=pa(),To=fe(),Z_=ct(),nt=oe(),H6=z_();Ne.PCF_TARGET_SOLUTION_MANAGED_CODE="PCF_TARGET_SOLUTION_MANAGED";Ne.PCF_CONTROL_NAME_TAKEN_CODE="PCF_CONTROL_NAME_TAKEN";Ne.PCF_CONTROL_AMBIGUOUS_CODE="PCF_CONTROL_AMBIGUOUS";Ne.PCF_CONTROL_MANAGED_CODE="PCF_CONTROL_MANAGED";Ne.PCF_RESOURCE_NAME_TAKEN_CODE="PCF_RESOURCE_NAME_TAKEN";Ne.PCF_MANIFEST_CHANGE_NEEDS_PUBLISH_ALL_CODE="PCF_MANIFEST_CHANGE_NEEDS_PUBLISH_ALL";Ne.PCF_REGISTRATION_UNVERIFIED_CODE="PCF_REGISTRATION_UNVERIFIED";var it="registerPcfControl",f0=66,K6=5e3,j_=300*1e3,J6={hash:"webresourceid,name,ismanaged,webresourcetype,contenthash",tokens:"webresourceid,name,ismanaged,webresourcetype",content:"webresourceid,name,ismanaged,webresourcetype,content"},ff=new WeakMap;function pf(e){return new We.InvalidArgumentError(`${it}: ${e}`)}function Rs(e,t){return e.toLowerCase()===t.toLowerCase()}function si(e){return e.map(t=>`'${t}'`).join(", ")}function Y6(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function Nu(e){return e instanceof We.ConnectionError&&(e.statusCode===0||To.AMBIGUOUS_WRITE_STATUSES.has(e.statusCode))}function Q6(e,t){var r;if(e!==void 0&&(typeof e!="object"||e===null))throw pf("options must be an object.");let{solutionUniqueName:n,publishAll:i}=e??{};if(i!==void 0&&i!==!0)throw pf(`publishAll must be absent or the literal true (it was ${String(i)}): it consents to PublishAllXml, which publishes every pending customization in the org. Nothing was sent.`);if(n!==void 0&&(typeof n!="string"||!n.trim()))throw pf("solutionUniqueName must be a non-empty string. Nothing was sent.");let o=(r=n)!==null&&r!==void 0?r:t;if(!o)throw pf("name the solution the control joins \u2014 options.solutionUniqueName or MakerSdkOptions.solutionUniqueName: its publisher's prefix names the control, and the SDK never guesses one. Nothing was sent.");return{target:o,publishAll:i===!0}}function eT(e,t,r){let n=e?.["@odata.etag"];if(!(0,To.isVersionToken)(n))throw new We.ConnectionError(r,200,`${it}: ${t} came back without a version token (@odata.etag ${n===void 0?"missing":JSON.stringify(n)}), so a change since it was read could not be detected`);return n}function tT(e,t){var r,n,i,o;let a=e,s=String((r=a?.name)!==null&&r!==void 0?r:"");return{id:(0,nt.normalizeGuid)(String((n=a?.customcontrolid)!==null&&n!==void 0?n:""),"customcontrolid"),name:s,version:String((i=a?.version)!==null&&i!==void 0?i:""),manifest:String((o=a?.manifest)!==null&&o!==void 0?o:""),managed:a?.ismanaged===!0,etag:eT(e,`the control '${s}'`,t)}}function X6(e,t){var r,n;let i=e,o=String((r=i?.name)!==null&&r!==void 0?r:"");return{id:(0,nt.normalizeGuid)(String((n=i?.webresourceid)!==null&&n!==void 0?n:""),"webresourceid"),name:o,managed:i?.ismanaged===!0,type:Number(i?.webresourcetype),content:typeof i?.content=="string"?i.content:"",contentHash:typeof i?.contenthash=="string"?i.contenthash.toLowerCase():"",etag:eT(e,`the web resource '${o}'`,t)}}async function p0(e){let t=(0,nt.odataLiteral)(e.key),r=`/customcontrols${(0,nt.odataQuery)([["$select","customcontrolid,name,version,manifest,ismanaged"],["$filter",`endswith(name,'_${t}') or name eq '${t}'`]])}`,n=e.client.apiUrl(r),i=e.key.toLowerCase();return(await(0,_o.collectPages)(e.client,r,it)).filter(o=>{let a=typeof o.name=="string"?o.name.toLowerCase():"";return a===i||a.slice(a.indexOf("_")+1)===i}).map(o=>tT(o,n))}async function mf(e,t){let r=`cc_${e.key}/`,n=`/webresourceset${(0,nt.odataQuery)([["$select",J6[t]],["$filter",`startswith(name,'${(0,nt.odataLiteral)(r)}')`]])}`,i=e.client.apiUrl(n);return(await(0,_o.collectPages)(e.client,n,it)).filter(o=>typeof o.name=="string"&&o.name.toLowerCase().startsWith(r.toLowerCase())).map(o=>X6(o,i))}function Z6(e){let t=ff.get(e.sdkClient);if(t)return t;let r=`/EntityDefinitions(LogicalName='webresource')/Attributes${(0,nt.odataQuery)([["$select","LogicalName"],["$filter","LogicalName eq 'contenthash'"]])}`,n=e.client.apiUrl(r),i=e.client.get(r).then(o=>{var a;let s=(a=(0,To.ensureSuccess)(o,n).body)===null||a===void 0?void 0:a.value;if(!Array.isArray(s))throw new We.ConnectionError(n,o.status,`${it}: the columns of webresource came back unreadable`);return s.some(l=>l?.LogicalName==="contenthash")}).catch(o=>{throw ff.get(e.sdkClient)===i&&ff.delete(e.sdkClient),o});return ff.set(e.sdkClient,i),i}async function rT(e,t){let r=await(0,_o.collectPages)(e.client,`/customcontrols(${t})/customcontrol_resource_id${(0,nt.odataQuery)([["$select","webresourceid,name"]])}`,it);return new Set(r.map(n=>n.webresourceid).filter(n=>typeof n=="string"&&n!=="").map(n=>n.toLowerCase()))}async function m0(e,t){let r=`/customcontrols(${t})${(0,nt.odataQuery)([["$select","customcontrolid,name,version,manifest,ismanaged"]])}`,n=await e.client.get(r);if(n.status!==404)return(0,To.ensureSuccess)(n,e.client.apiUrl(r)),tT(n.body,e.client.apiUrl(r))}function H_(e,t,r){return new We.SdkError(Ne.PCF_RESOURCE_NAME_TAKEN_CODE,`${it}: ${si(t.map(n=>n.name))} ${t.length===1?"is":"are"} named as a file of ${e.name} but ${r}. An import would create a second web resource of the same name (the runtime loads by name); rename or delete ${t.length===1?"it":"them"} first. Nothing was written.`)}async function ez(e){let t=await p0(e),r=t.filter(u=>!Rs(u.name,e.name));if(r.length>0)throw new We.SdkError(Ne.PCF_CONTROL_NAME_TAKEN_CODE,`${it}: the control ${e.key} is registered as ${si(r.map(u=>u.name))}, under another publisher prefix \u2014 the platform keeps one control per namespace and constructor. Target a solution whose publisher has that prefix, or remove that control. Nothing was written.`);if(t.length>1)throw new We.SdkError(Ne.PCF_CONTROL_AMBIGUOUS_CODE,`${it}: ${t.length} control rows are named ${e.name}; the SDK cannot tell which one to update. Nothing was written.`);let n=t[0];if(n?.managed)throw new We.SdkError(Ne.PCF_CONTROL_MANAGED_CODE,`${it}: ${n.name} is managed; a managed control is changed by its solution's upgrade, not in place. Nothing was written.`);let i=await mf(e,await Z6(e)?"hash":"tokens");if(!n){if(i.length>0)throw H_(e,i,"no control of that name exists");return}e.progress.customControlId=n.id;let o=await rT(e,n.id),a=i.filter(u=>!o.has(u.id));if(a.length>0)throw H_(e,a,`${n.name} does not reference ${a.length===1?"it":"them"}`);let s=i.filter(u=>u.managed);if(s.length>0)throw new We.SdkError(Ne.PCF_CONTROL_MANAGED_CODE,`${it}: ${si(s.map(u=>u.name))} of ${n.name} ${s.length===1?"is":"are"} managed. Nothing was written.`);let l=new Map;for(let u of e.checked.files){let c=(0,Vi.pcfWebResourceName)(e.checked,u.path),d=i.filter(f=>Rs(f.name,c));if(d.length>1)throw new We.SdkError(Ne.PCF_CONTROL_AMBIGUOUS_CODE,`${it}: ${n.name} references ${d.length} web resources named '${c}'; the SDK cannot tell which one the runtime loads. Nothing was written.`);d.length===1&&l.set(u.path,d[0])}return{control:n,folder:i,files:l}}function tz(e){return(0,H6.sha256Hex)((0,Su.utf8ToBytes)((0,Su.bytesToBase64)(e.data)))}function rz(e,t){if(!t)return{mode:"created"};let{control:r}=t,n=(0,Vi.pcfManifestsEquivalent)(r.manifest,e.checked.manifest),i=e.checked.files.filter(s=>!t.files.has(s.path)).map(s=>s.path),o=e.checked.files.map(s=>({file:s,row:t.files.get(s.path)})).filter(({file:s,row:l})=>l!==void 0&&l.type!==s.webResourceType).map(({file:s,row:l})=>`'${l.name}' (type ${l.type}, not ${s.webResourceType})`);if(!n||i.length>0||o.length>0){if(!e.publishAll){let s=n?i.length>0?`${r.name} lacks ${si(i)}, which only a re-import restores`:`${r.name}'s ${o.join(", ")} cannot be repaired by a files-only write \u2014 only a re-import may`:`the manifest of ${r.name} changed`;throw new We.SdkError(Ne.PCF_MANIFEST_CHANGE_NEEDS_PUBLISH_ALL_CODE,`${it}: ${s}, and a re-imported control is applied only by PublishAllXml \u2014 which publishes EVERY pending customization in the org. Pass publishAll: true to consent. Nothing was written.`)}return{mode:"reimported",snapshot:t}}if(r.version!==e.checked.version){if(e.publishAll)return{mode:"reimported",snapshot:t};e.warnings.push(`${r.name} keeps version ${r.version}: a files-only update does not change it (pac's --incremental neither); applying ${e.checked.version} needs publishAll: true.`)}let a=e.checked.files.map(s=>({file:s,row:t.files.get(s.path)})).filter(({file:s,row:l})=>l.contentHash!==tz(s));return a.length>0?{mode:"updated",snapshot:t,changed:a}:{mode:"unchanged",snapshot:t}}async function hf(e,t){var r;if(!t){let s=await p0(e),l=await mf(e,"tokens");if(s.length>0||l.length>0)throw new We.VersionConflictError("customcontrol",e.name,null,null,`Since this registration first read the org, ${si([...s.map(u=>u.name),...l.map(u=>u.name)])} appeared. Nothing was written; retry the registration.`);return}let n=[],i=await m0(e,t.control.id);i?i.etag!==t.control.etag&&n.push(i.name):n.push(`${t.control.name} (deleted)`);let o=await mf(e,"tokens"),a=new Map(t.folder.map(s=>[s.id,s.etag]));for(let s of o)a.has(s.id)?a.get(s.id)!==s.etag&&n.push(s.name):n.push(`${s.name} (new)`);for(let s of t.folder)o.some(l=>l.id===s.id)||n.push(`${s.name} (deleted)`);if(n.length>0)throw new We.VersionConflictError("customcontrol",e.name,t.control.etag,(r=i?.etag)!==null&&r!==void 0?r:null,`Changed since this registration read it: ${si(n)} \u2014 by another writer, or by the platform touching them (an import or publish elsewhere in the org can move these tokens with no change). Nothing was written; retry the registration.`)}function nT(e){let t;try{t=(0,j6.parseManifestRoot)(typeof e=="string"?e:"")}catch{return{state:"unknown",reason:"settled, but its data log does not parse"}}if(t.tagName!=="importexportxml"||t.namespaceURI)return{state:"unknown",reason:`settled, but its data log's root is <${t.tagName}>`};let r=(0,Vi.unboundPrefixes)(t);if(r.length>0)return{state:"unknown",reason:`settled, but its data log uses a prefix no declaration binds (${r.join(", ")})`};let n=t.getAttribute("succeeded");return n==="success"||n==="warning"?{state:"success"}:n==="failure"?{state:"failure",message:t.getAttribute("status")||"the import failed"}:{state:"unknown",reason:"settled without a success, warning or failure verdict"}}Ne.readJobVerdict=nT;function nz(e,t){return new Promise(r=>{let n=setTimeout(()=>r("late"),t);e.then(i=>{clearTimeout(n),r({value:i})},i=>{clearTimeout(n),r({error:i})})})}async function iz(e,t){let r=`/importjobs(${t})${(0,nt.odataQuery)([["$select","completedon,data"]])}`,n=Date.now()+j_,i={state:"unknown",reason:`had not settled after ${j_/6e4} minutes`};for(;;){let o=Math.min(K6,n-Date.now());if(o<=0)return i;await new Promise(c=>setTimeout(c,o));let a=n-Date.now();if(a<=0)return i;let s=await nz(e.client.get(r),a);if(s==="late")return i;if("error"in s){if(Nu(s.error))continue;return{state:"unknown",reason:`could not be read (${s.error.message})`}}let l=s.value;if(l.status===404)continue;if(l.status<200||l.status>=300)return{state:"unknown",reason:`could not be read (HTTP ${l.status})`};let u=l.body;if(u?.completedon)return nT(u.data)}}async function oz(e,t,r){let n=(0,Z_.newId)(),i=e.checked.files.map(s=>s.path),o=r?i.filter(s=>!r.files.has(s)):i;e.progress.phase="import",e.progress.importJobId=n,e.started=!0;let a;try{await(0,d0.importSolution)(e.client,{base64:(0,Su.bytesToBase64)(t),overwriteUnmanagedCustomizations:!1,publishWorkflows:!1,importJobId:n})}catch(s){if(!Nu(s))throw s;a=s}if(a){let s=await iz(e,n);if(s.state==="failure")throw new We.ConnectionError(a.url,a.statusCode,`the import's answer was lost, and its job ${n} reports that it FAILED: ${s.message}`,a);if(s.state==="unknown")throw e.progress.imported="unknown",e.progress.unconfirmed=[...i],e.progress.publishedUnknown=[...o],new We.ConnectionError(a.url,a.statusCode,`the import's answer was lost, and its job ${n} ${s.reason}: whether it committed is unknown. Read importjobs(${n}), then retry the registration.`,a)}e.progress.imported="yes",e.progress.written=[...i],e.progress.published=[...o]}async function az(e){e.progress.phase="publish-all";let t=e.checked.files.map(r=>r.path).filter(r=>!e.progress.published.includes(r));try{await(0,X_.publishAllXml)(e.client)}catch(r){throw Nu(r)?(e.progress.publishAll="unknown",e.progress.publishedUnknown=[...e.progress.publishedUnknown,...t]):e.progress.publishAll="failed",r}e.progress.publishAll="succeeded",e.progress.published=[...e.progress.published,...t]}async function K_(e,t){var r,n;if(e.progress.imported==="unknown")return e.progress.temporaries.push(t.solution,t.publisher),[`The temporary solution '${t.solution}' and publisher '${t.publisher}' were left in place: the import's outcome is unknown, and an import still running may be using them. Delete them once importjobs(${e.progress.importJobId}) has settled.`];let i=(o,a)=>(e.progress.temporaries.push(...a),[`${si(a)} ${a.length===1?"was":"were"} left in place: ${o}. Delete ${a.length===1?"it":"them"} when convenient.`]);try{let o=await(0,_o.collectPages)(e.client,`/solutions${(0,nt.odataQuery)([["$select","solutionid"],["$filter",`uniquename eq '${(0,nt.odataLiteral)(t.solution)}'`]])}`,it);for(let a of o){let s=(0,nt.normalizeGuid)(String((r=a.solutionid)!==null&&r!==void 0?r:""),"solutionid");if(!await sz(e,s))return i(`the temporary solution holds components other than ${e.name}`,[t.solution,t.publisher]);let l=`/solutions(${s})`;(0,To.ensureSuccess)(await e.client.delete(l),e.client.apiUrl(l))}}catch(o){return i(`the temporary solution could not be removed (${o.message})`,[t.solution,t.publisher])}try{let o=await(0,_o.collectPages)(e.client,`/publishers${(0,nt.odataQuery)([["$select","publisherid"],["$filter",`uniquename eq '${(0,nt.odataLiteral)(t.publisher)}'`]])}`,it);for(let a of o){let s=(0,nt.normalizeGuid)(String((n=a.publisherid)!==null&&n!==void 0?n:""),"publisherid");if((await(0,_o.collectPages)(e.client,`/solutions${(0,nt.odataQuery)([["$select","solutionid"],["$filter",`_publisherid_value eq ${s}`]])}`,it)).length>0)return i("a solution uses the temporary publisher",[t.publisher]);let u=`/publishers(${s})`;(0,To.ensureSuccess)(await e.client.delete(u),e.client.apiUrl(u))}}catch(o){return i(`the temporary publisher could not be removed (${o.message})`,[t.publisher])}return[]}async function sz(e,t){var r,n;let i=await(0,_o.collectPages)(e.client,`/solutioncomponents${(0,nt.odataQuery)([["$select","objectid,componenttype"],["$filter",`_solutionid_value eq ${t}`]])}`,it);for(let o of i){if(o.componenttype!==f0||typeof o.objectid!="string")return!1;let a=(0,nt.normalizeGuid)(o.objectid,"objectid");if(a!==e.progress.customControlId&&!Rs((n=(r=await m0(e,a))===null||r===void 0?void 0:r.name)!==null&&n!==void 0?n:"",e.name))return!1}return!0}async function J_(e,t,r){let n=(0,Z_.newId)().replace(/-/g,"").slice(0,12),i={solution:`CdsMakerSdkPcf${n}`,publisher:`CdsMakerSdkPcfPub${n}`},o=(0,Vi.buildPcfSolutionZip)({controlName:e.name,solutionUniqueName:i.solution,publisherUniqueName:i.publisher,prefix:e.solution.publisherPrefix,optionValuePrefix:e.solution.publisherOptionValuePrefix,control:e.checked});await hf(e,r);let a;try{await oz(e,o,r),t==="reimported"&&await az(e);let s=await fz(e,r),l=await h0(e,s.id);a=g0(e,t,s,l,e.checked.files.map(u=>u.path),[])}catch(s){throw(0,We.withCleanupWarnings)(s,await K_(e,i))}return a.warnings.push(...await K_(e,i)),a}async function Y_(e,t,r){try{return await r()}catch(n){throw Nu(n)&&e.progress.unconfirmed.push(...t),n}}function lz(e){return e instanceof We.SdkError&&e.code===To.VERSION_CONFLICT_CODE&&!(e instanceof We.VersionConflictError)}async function uz(e,t,r){let n=({file:a})=>({content:(0,Su.bytesToBase64)(a.data)}),i=r.map(({file:a})=>a.path);if(e.client.supportsAtomicBatch){let a=s=>Y_(e,i,()=>(0,z6.sendChangeSet)(e.client,r.map(l=>({method:"PATCH",path:`/webresourceset(${l.row.id})`,body:n(l),etag:s?l.row.etag:"*"})),`the files of ${e.name}`));try{await a(!0)}catch(s){if(!lz(s))throw s;await hf(e,t),await a(!1)}e.progress.written.push(...i);return}let o;for(let a of r){let s=`/webresourceset(${a.row.id})`,l=c=>Y_(e,[a.file.path],async()=>{let d=await e.client.patch(s,n(a),{headers:{"If-Match":c}});return d.status===412?d:(0,To.ensureSuccess)(d,e.client.apiUrl(s))}),u=await l(o===!1?"*":a.row.etag);if(u.status===412&&o===void 0&&(await hf(e,t),o=!1,u=await l("*")),u.status===412)throw new We.VersionConflictError("webresource",a.row.id,a.row.etag,null,`'${a.row.name}' changed after this registration read it${e.progress.written.length>0?`; ${si(e.progress.written)} had been written before it`:""}. Retry the registration once the other writer is done.`);o=o??!0,e.progress.written.push(a.file.path)}}async function cz(e,t){e.progress.phase="publish";let r=t.map(({file:i})=>i.path),n=t.map(({row:i})=>`<webresource>${(0,nt.xmlText)(i.id)}</webresource>`).join("");try{await(0,X_.publishXml)(e.client,`<importexportxml><webresources>${n}</webresources></importexportxml>`)}catch(i){throw Nu(i)&&e.progress.publishedUnknown.push(...r),i}e.progress.published.push(...r)}async function dz(e,t,r){await hf(e,t),e.progress.phase="write",e.started=!0,await uz(e,t,r),await cz(e,r),e.progress.phase="verify";let n=await m0(e,t.control.id);if(!n)throw gf(e,"updated",["the control was deleted"]);let i=[];if((n.version!==t.control.version||n.manifest!==t.control.manifest)&&i.push("its control row changed since it was read \u2014 another registration re-imported it"),i.push(...await oT(e,n.id)),i.length>0)throw gf(e,"updated",i);let o=await h0(e,n.id);return g0(e,"updated",n,o,[...e.progress.written],[...e.progress.published])}function gf(e,t,r){return new We.SdkError(Ne.PCF_REGISTRATION_UNVERIFIED_CODE,`${it}: ${e.name} did not verify after it was ${t}: ${r.join("; ")}. Retrying the registration is safe.`)}function iT(e,t){let r=new Set(e.checked.files.map(n=>(0,Vi.pcfWebResourceName)(e.checked,n.path).toLowerCase()));for(let n of t){let i=`'${n.name}' is a file of ${e.name} that its manifest no longer names; the platform keeps it after a re-import, and the SDK does not delete it.`;!r.has(n.name.toLowerCase())&&!e.warnings.includes(i)&&e.warnings.push(i)}}async function oT(e,t){let r=await rT(e,t),n=await mf(e,"content"),i=[],o=n.filter(s=>!r.has(s.id));o.length>0&&i.push(`${si(o.map(s=>s.name))} in its folder ${o.length===1?"is":"are"} not its own`);let a=n.filter(s=>r.has(s.id));for(let s of e.checked.files){let l=(0,Vi.pcfWebResourceName)(e.checked,s.path),u=a.filter(d=>Rs(d.name,l));if(u.length!==1){i.push(`it references ${u.length} web resources named '${l}'`);continue}let[c]=u;c.type!==s.webResourceType&&i.push(`'${c.name}' has the web resource type ${c.type}, not ${s.webResourceType}`),c.managed&&i.push(`'${c.name}' is managed`),Y6((0,Su.base64ToBytes)(c.content),s.data)||i.push(`the published content of '${c.name}' is not the file sent`)}return iT(e,a),i}async function fz(e,t){e.progress.phase="verify";let r=t?"reimported":"created",n=await p0(e),i=n.filter(l=>Rs(l.name,e.name)),o=[],a=n.filter(l=>!Rs(l.name,e.name));if(a.length>0&&o.push(`${si(a.map(l=>l.name))} also ${a.length===1?"holds":"hold"} ${e.key}`),i.length!==1)throw gf(e,r,[...o,`${i.length} control rows are named ${e.name}`]);let[s]=i;if(e.progress.customControlId=s.id,t&&s.id!==t.control.id&&o.push(`its row is ${s.id}, not the re-imported ${t.control.id}`),s.managed&&o.push("it is managed"),s.version!==e.checked.version&&o.push(`its version is ${s.version}, not ${e.checked.version}`),(0,Vi.pcfManifestsEquivalent)(s.manifest,e.checked.manifest)||o.push("its stored manifest is not equivalent to the one sent"),o.push(...await oT(e,s.id)),o.length>0)throw gf(e,r,o);return s}async function Q_(e,t){return(await(0,_o.collectPages)(e.client,`/solutioncomponents${(0,nt.odataQuery)([["$select","solutioncomponentid"],["$filter",`_solutionid_value eq ${e.solution.solutionId} and objectid eq ${t} and componenttype eq ${f0}`]])}`,it)).length>0}async function h0(e,t){if(e.progress.phase="membership",await Q_(e,t))return"present";if(e.started=!0,await(0,d0.addSolutionComponent)(e.client,{componentId:t,componentType:f0,solutionUniqueName:e.solution.uniqueName,addRequiredComponents:!1}),!await Q_(e,t))throw new We.SdkError(Ne.PCF_REGISTRATION_UNVERIFIED_CODE,`${it}: ${e.name} is not in the solution '${e.solution.uniqueName}' after AddSolutionComponent. Retrying the registration is safe.`);return"added"}function g0(e,t,r,n,i,o){return{name:r.name,customControlId:r.id,mode:t,written:i,published:o,publishedAll:t==="reimported",storedVersion:r.version,membership:n,warnings:[...e.warnings]}}async function pz(e,t,r){let n=(0,Vi.checkPcfControlPackage)(t),{target:i,publishAll:o}=Q6(r,e.solutionName),a=e.withSolutionScope(void 0),s=await(0,d0.getSolution)(a,i);if(s.isManaged||!s.publisherPrefix)throw new We.SdkError(Ne.PCF_TARGET_SOLUTION_MANAGED_CODE,`${it}: the solution '${s.uniqueName}' ${s.isManaged?"is managed; a control joins an unmanaged solution":"has a publisher without a customization prefix, which would leave the control's name unprefixed"}. Nothing was written.`);let l=(0,Vi.pcfControlName)(s.publisherPrefix,n),u={client:a,sdkClient:e,checked:n,key:`${n.namespace}.${n.constructorName}`,name:l,solution:s,publishAll:o,progress:{phase:"import",name:l,imported:"no",written:[],unconfirmed:[],published:[],publishedUnknown:[],publishAll:"not-sent",temporaries:[]},warnings:[],started:!1};try{let c=rz(u,await ez(u));switch(c.mode){case"created":return await J_(u,"created",void 0);case"reimported":return await J_(u,"reimported",c.snapshot);case"updated":return await dz(u,c.snapshot,c.changed);default:{iT(u,c.snapshot.folder);let d=await h0(u,c.snapshot.control.id);return g0(u,"unchanged",c.snapshot.control,d,[],[])}}}catch(c){throw u.started?(0,We.withPcfRegistrationProgress)(c,u.progress):c}}Ne.registerPcfControl=pz});var v0=v(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.compileGenPage=Re.legacyEnumsNeeded=Re.createGenPageTypeScriptLoader=Re.acceptGenPageTypeScript=Re.isLoadableGenPageOutput=Re.runtimeTypesImportSpans=Re.GENPAGE_RUNTIME_TYPES_END=Re.GENPAGE_RUNTIME_TYPES_BEGIN=Re.GENPAGE_TYPESCRIPT_VERSION=void 0;var Ls=Q();Re.GENPAGE_TYPESCRIPT_VERSION="5.8.3";Re.GENPAGE_RUNTIME_TYPES_BEGIN="// --- BEGIN GENERATED RUNTIME TYPES ---";Re.GENPAGE_RUNTIME_TYPES_END="// --- END GENERATED RUNTIME TYPES ---";var Ln="./RuntimeTypes",mz="'\"`",sT=/\s/;function hz(e){return e===10||e===13||e===8232||e===8233}function gz(e,t){let r=[];e.lastIndex=0;for(let n=e.exec(t);n!==null;n=e.exec(t))r.push(n.index);return r}function dT(e){let t=[],r=Ln.length;for(let l=e.indexOf(Ln);l!==-1;l=e.indexOf(Ln,l+1)){let u=l-1;u>=0&&mz.includes(e[u])&&e[u+1+r]===e[u]&&t.push(u)}let n=[];if(t.length===0)return n;let i=-1,o=l=>{if(i<l)for(i=l;i<e.length&&e[i]!=="'"&&e[i]!=='"';)i+=1;return i},a=-1,s=l=>{for(;a+1<t.length&&t[a+1]<=l;)a+=1;return a>=0?t[a]:-1/0};for(let l=e.indexOf("import");l!==-1;){let u=l+1;if(l+6<e.length&&sT.test(e[l+6])){let c=s(o(l+6));if(c>=l+8){let d=c+2+r;for(e[d]===";"&&(d+=1);d<e.length&&sT.test(e[d]);)d+=1;n.push({start:l,end:d}),u=d}}l=e.indexOf("import",u)}return n}Re.runtimeTypesImportSpans=dT;var yz=/\b(?:import\s*['"]|export\s)/;function bz(e){let t=gz(/from\s+['"]/g,e);if(t.length===0)return!1;let r=/\bimport\s/g,n=-1,i=0;for(let o=r.exec(e);o!==null;o=r.exec(e)){let a=o.index+7;if(a>n)for(n=a;n<e.length&&!hz(e.charCodeAt(n));)n+=1;for(;i<t.length&&t[i]<a+1;)i+=1;if(i<t.length&&t[i]<n)return!0}return!1}function vz(e){return e!==void 0&&e!==""&&(yz.test(e)||bz(e))}Re.isLoadableGenPageOutput=vz;var lT=["transpileModule","createSourceFile","createProgram","getParseTreeNode","flattenDiagnosticMessageText","forEachChild","getModifiers","canHaveModifiers","isImportDeclaration","isExportDeclaration","isExportAssignment","isStringLiteral"];function fT(e){var t;let r=s=>s!==null&&(typeof s=="object"||typeof s=="function")?s:void 0,n=r(e);n&&typeof n.transpileModule!="function"&&(n=(t=r(n.default))!==null&&t!==void 0?t:n);let i=n?lT.filter(s=>typeof n?.[s]!="function"):[...lT];if(!n||i.length>0)throw new Ls.SdkError("GENPAGE_COMPILER_INVALID",`The TypeScript compiler supplied as MakerSdkOptions.typescript is not the typescript module (missing ${i.join(", ")}). Pass the 'typescript' package's module object, loadNodeTypeScript from '@maker-studio/cds-maker-sdk/node', or \u2014 in a bare engine \u2014 globalThis.ts after evaluating typescript@${Re.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js.`);let o=typeof n.version=="string"?n.version:"",a=Re.GENPAGE_TYPESCRIPT_VERSION.split(".").slice(0,2).join(".");if(o.split(".").slice(0,2).join(".")!==a)throw new Ls.SdkError("GENPAGE_COMPILER_VERSION",`The TypeScript compiler supplied as MakerSdkOptions.typescript is version '${o||"unknown"}', but generative pages are compiled with ${a}.x \u2014 the version the maker portal itself uses (${Re.GENPAGE_TYPESCRIPT_VERSION}). Another version can emit different JavaScript for the same page. Supply typescript@${Re.GENPAGE_TYPESCRIPT_VERSION}.`);return n}Re.acceptGenPageTypeScript=fT;function wz(e){let t;return()=>{if(!t){if(e===void 0)return Promise.reject(new Ls.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`This push must compile a generative page, but no TypeScript compiler was supplied. Pass MakerSdkOptions.typescript \u2014 in Node, loadNodeTypeScript from '@maker-studio/cds-maker-sdk/node'; in a bare engine, globalThis.ts after evaluating typescript@${Re.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js. Nothing was written.`));t=Promise.resolve().then(()=>typeof e=="function"?e():e).then(fT).catch(r=>{throw t=void 0,r instanceof Ls.SdkError?r:new Ls.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`The TypeScript compiler could not be loaded, so a generative page cannot be compiled (${r instanceof Error?r.message:String(r)}). Nothing was written.`)})}return t}}Re.createGenPageTypeScriptLoader=wz;var pT=e=>`${e.kind}:${e.pos}:${e.end}`;function Cz(e,t){return()=>r=>{let n=i=>{let o=e.getParseTreeNode(i);o&&t.add(pT(o)),e.forEachChild(i,n)};return n(r),r}}function b0(e){return{target:e.ScriptTarget.ES5,module:e.ModuleKind.ES2020,jsx:e.JsxEmit.React}}var Ez=2301;function uT(e,t,r){var n;let i=e.transpileModule(t,{compilerOptions:b0(e),reportDiagnostics:!0,...r?{transformers:{after:[Cz(e,r)]}}:{}}),o=((n=i.diagnostics)!==null&&n!==void 0?n:[]).filter(a=>a.category===e.DiagnosticCategory.Error).map(a=>{let s=a.file&&typeof a.start=="number"?a.file.getLineAndCharacterOfPosition(a.start):{line:0,character:0};return{line:s.line+1,column:s.character+1,rule:"genpage-source-syntax",code:a.code,message:e.flattenDiagnosticMessageText(a.messageText,`+`)}});return{code:i.outputText,diagnostics:o}}var cT=e=>e.startsWith(".")||e.startsWith("/"),yf={line:1,column:1};function y0(e,t){let r=o=>{let a=t.getLineAndCharacterOfPosition(o.getStart(t));return{line:a.line+1,column:a.character+1}},n=o=>(e.isImportDeclaration(o)||e.isExportDeclaration(o))&&o.moduleSpecifier&&e.isStringLiteral(o.moduleSpecifier)?o.moduleSpecifier.text:void 0,i=o=>t.statements.filter(a=>e.isImportDeclaration(a)&&n(a)===o);return{statement(o,a){let s=t.statements.find(l=>n(l)===o&&(a==="import"?e.isImportDeclaration(l):e.isExportDeclaration(l)));return s?r(s):yf},element(o,a){var s;for(let l of i(o)){let u=(s=l.importClause)===null||s===void 0?void 0:s.namedBindings,c=u&&e.isNamedImports(u)?u.elements.find(d=>d.name.text===a):void 0;if(c)return r(c)}return this.statement(o,"import")},binding(o){var a,s;for(let l of t.statements)if(e.isImportDeclaration(l)&&l.importClause){let u=l.importClause,c=u.namedBindings,d=((a=u.name)===null||a===void 0?void 0:a.text)===o?u.name:c&&e.isNamespaceImport(c)&&c.name.text===o?c.name:c&&e.isNamedImports(c)?c.elements.find(f=>f.name.text===o):void 0;if(d)return r(d)}else{if((e.isFunctionDeclaration(l)||e.isClassDeclaration(l))&&((s=l.name)===null||s===void 0?void 0:s.text)===o)return r(l.name);if(e.isVariableStatement(l)){let u=l.declarationList.declarations.find(c=>e.isIdentifier(c.name)&&c.name.text===o);if(u)return r(u.name)}}return yf}}}function Az(e,t,r,n){var i,o;let a=[],s=y0(e,r),l=(p,h,g)=>{a.push({...p,rule:h,code:0,message:g})},u=(p,h)=>{var g;return(e.canHaveModifiers(p)?(g=e.getModifiers(p))!==null&&g!==void 0?g:[]:[]).some(b=>b.kind===h)},c=(p,h)=>l(p,"genpage-relative-import",`'${h}' cannot resolve at runtime: the page is loaded as a single module from a blob URL, so the only relative import it may have is './RuntimeTypes'`),d="genpage-runtime-types-import-form",f=!1,m=new Set;for(let p of t.statements){if(e.isExportAssignment(p)){f=f||!p.isExportEquals;continue}if(e.isFunctionDeclaration(p)||e.isClassDeclaration(p)){u(p,e.SyntaxKind.ExportKeyword)&&u(p,e.SyntaxKind.DefaultKeyword)&&(f=!0),p.name&&m.add(p.name.text);continue}if(e.isExportDeclaration(p)){let w=p.exportClause;w&&e.isNamedExports(w)&&w.elements.some(S=>S.name.text==="default")&&(f=!0);let C=p.moduleSpecifier&&e.isStringLiteral(p.moduleSpecifier)?p.moduleSpecifier.text:void 0;C===Ln?l(s.statement(C,"export"),d,"a page cannot re-export from './RuntimeTypes': that module does not exist at runtime"):C!==void 0&&cT(C)&&c(s.statement(C,"export"),C);continue}if(!e.isImportDeclaration(p)||!e.isStringLiteral(p.moduleSpecifier))continue;let h=p.moduleSpecifier.text,g=p.importClause;if(h!==Ln){cT(h)&&c(s.statement(h,"import"),h),g?.name&&m.add(g.name.text);let w=g?.namedBindings;w&&e.isNamespaceImport(w)?m.add(w.name.text):w&&e.isNamedImports(w)&&w.elements.forEach(C=>m.add(C.name.text));continue}if(!g){l(s.statement(h,"import"),d,"a side-effect import of './RuntimeTypes' cannot resolve at runtime; import the names it declares");continue}g.name&&l(s.binding(g.name.text),d,"'./RuntimeTypes' has no default export at runtime; import its names");let b=g.namedBindings;if(b&&e.isNamespaceImport(b))l(s.binding(b.name.text),d,"a namespace import of './RuntimeTypes' is undefined at runtime \u2014 its enums are inlined under their own names; import the names instead");else if(b&&e.isNamedImports(b))for(let w of b.elements){let C=w.name.text,S=(o=(i=w.propertyName)===null||i===void 0?void 0:i.text)!==null&&o!==void 0?o:C,O=s.element(h,C);S!==C?l(O,d,`'${S} as ${C}' would be undefined at runtime: the enum is inlined as '${S}', so import it under its own name`):n?.text?n.enums.has(C)||l(O,"genpage-runtime-types-unresolved",`'${C}' is imported from './RuntimeTypes' as a VALUE, but the runtime types define no value of that name \u2014 only the choice enums of the page's data sources are values. Import a type with 'import type'.`):l(O,"genpage-runtime-types-unresolved",`'${C}' is imported from './RuntimeTypes' as a VALUE, but the page has no data sources, so no runtime types are inlined and the import reaches the runtime, which cannot load it. Import it with 'import type', or add the table it belongs to to dataSources.`)}}if(f||l(yf,"genpage-no-default-export","the page has no default export \u2014 the runtime renders the module's default export as the page component"),n?.text)for(let p of m)n.enums.has(p)&&l(s.binding(p),"genpage-runtime-types-collision",`'${p}' is declared at the page's module scope and is also one of its inlined choice enums, so the compiled page would declare it twice and fail to load. Rename the page's binding, or import the enum from './RuntimeTypes'.`);return a}function mT(e,t,r){let n,i=()=>{if(!n){let p={getSourceFile:g=>g===t.fileName?t:void 0,getDefaultLibFileName:()=>"lib.d.ts",writeFile:()=>{},getCurrentDirectory:()=>"",getCanonicalFileName:g=>g,useCaseSensitiveFileNames:()=>!0,getNewLine:()=>`+`,fileExists:g=>g===t.fileName,readFile:()=>{},directoryExists:()=>!0,getDirectories:()=>[]},h={...r,noLib:!0,noResolve:!0,allowJs:!0,types:[],alwaysStrict:!0,moduleDetection:e.ModuleDetectionKind.Force};n=e.createProgram({rootNames:[t.fileName],options:h,host:p})}return n},o,a=()=>(o||(o=i().getTypeChecker()),o),s,l=()=>{if(!s){s=new Map;try{for(let p of i().getSemanticDiagnostics(t))p.code===Ez&&typeof p.start=="number"&&s.set(p.start,e.flattenDiagnosticMessageText(p.messageText," "))}catch{}}return s},u=p=>e.isImportSpecifier(p)?p.parent.parent.parent:e.isImportClause(p)?p.parent:e.isNamespaceImport(p)?p.parent.parent:void 0,c=p=>{let h=u(p);return h!==void 0&&e.isImportDeclaration(h)&&e.isStringLiteral(h.moduleSpecifier)&&h.moduleSpecifier.text===Ln},d=p=>{var h;for(let g=p;g;g=g.parent)if(e.canHaveModifiers(g)&&((h=e.getModifiers(g))!==null&&h!==void 0?h:[]).some(b=>b.kind===e.SyntaxKind.DeclareKeyword))return!0;return!1},f=p=>d(p)||e.isImportEqualsDeclaration(p)&&(p.isTypeOnly||e.isExternalModuleReference(p.moduleReference))||e.isImportClause(p)&&p.isTypeOnly||e.isNamespaceImport(p)&&p.parent.isTypeOnly||e.isImportSpecifier(p)&&(p.isTypeOnly||p.parent.parent.isTypeOnly),m=p=>{var h;return((h=p?.declarations)!==null&&h!==void 0?h:[]).some(g=>!c(g)&&!f(g))};return{pageOwns:p=>{let h=p.parent;return m(e.isShorthandPropertyAssignment(h)&&h.name===p?a().getShorthandAssignmentValueSymbol(h):a().getSymbolAtLocation(p))},pageOwnsLocalExport:p=>m(a().getExportSpecifierLocalTargetSymbol(p)),initializerShadow:p=>l().get(p.getStart(t))}}function Sz(e,t,r,n){let i=[],o=r?.enums;if(!o||o.size===0)return i;let a=(u,c,d)=>{let f=t.getLineAndCharacterOfPosition(u.getStart(t));i.push({line:f.line+1,column:f.character+1,rule:c,code:0,message:d})},s=mT(e,t,b0(e)),l=u=>{let c,d;if(e.isPropertyAccessExpression(u)&&e.isIdentifier(u.expression))c=u.expression,d=u.name.text;else if(e.isElementAccessExpression(u)&&e.isIdentifier(u.expression)){let m=u.argumentExpression;e.isStringLiteral(m)||e.isNoSubstitutionTemplateLiteral(m)?(c=u.expression,d=m.text):e.isNumericLiteral(m)&&(c=u.expression,d=String(Number(m.text)))}let f=c&&o.has(c.text)&&n.has(pT(u))&&!s.pageOwns(c)?o.get(c.text):void 0;if(c&&f&&d!==void 0){let m=e.isPropertyAccessExpression(u)?`${f.name}.${d}`:`${f.name}[${JSON.stringify(d)}]`,p=Object.prototype.hasOwnProperty.call(f.runtime,d)?f.runtime[d]:void 0,h=f.labels.get(d),g;p===void 0?g={rule:"genpage-enum-member-unknown",message:`${m} is undefined at runtime: '${f.name}' has no member '${d}' in this environment's metadata \u2014 members are the column's choice labels, so a renamed or differently localized label no longer matches. Known: ${[...f.labels.keys()].map(w=>`'${w}'`).join(", ")}`}:h&&typeof p!="number"?g={rule:"genpage-enum-member-clobbered",message:`${m} is the string '${String(p)}' at runtime, not a choice value: the label '${d}' looks like a number, and another option's reverse mapping overwrites it. Use the choice's numeric value instead.`}:h&&h.length>1&&(g={rule:"genpage-enum-member-ambiguous",message:`${m} labels more than one choice (${h.join(", ")}); the compiled value is whichever option comes last. Use the choice's numeric value instead.`});let b=g?s.initializerShadow(c):void 0;g&&b!==void 0?a(u,"genpage-enum-initializer-shadowed",`${m} does not read the choice enum at runtime. ${b} (TS2301): the ES5 emit moves an instance field's initializer into the constructor, where that parameter or local shadows '${c.text}'. If you meant the constructor's '${c.text}', move the assignment into the constructor body, or make it a parameter property and read \`this.${c.text}\`. If you meant the choice enum, rename the constructor's parameter or local.`):g&&a(u,g.rule,g.message)}e.forEachChild(u,l)};return l(t),i}function Nz(e,t){return e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!1,e.ScriptKind.JS).statements.some(n=>(e.isImportDeclaration(n)||e.isExportDeclaration(n))&&n.moduleSpecifier!==void 0&&e.isStringLiteral(n.moduleSpecifier)&&n.moduleSpecifier.text===Ln)}function hT(e,t){return t.statements.filter(r=>e.isImportDeclaration(r)&&e.isStringLiteral(r.moduleSpecifier)&&r.moduleSpecifier.text===Ln).map(r=>r.getStart(t))}function _z(e,t){let r=e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),n=hT(e,r),i=new Set(n),o,a="",s=0;for(let l of dT(t))!o&&!i.has(l.start)&&(o={swallows:n.some(u=>u>l.start&&u<l.end),text:t.slice(l.start,l.end).trimEnd()}),a+=t.slice(s,l.start),s=l.end;return a+=t.slice(s),{code:a,inexact:o}}function Tz(e,t,r){let n=new Set(hT(e,t));for(let i=t.text.indexOf(r);i!==-1;i=t.text.indexOf(r,i+1))if(!n.has(i)){let o=t.getLineAndCharacterOfPosition(i);return{line:o.line+1,column:o.character+1}}return yf}function gT(e,t,r){if(!r||r.size===0)return[];let n=mT(e,t,{...b0(e),target:e.ScriptTarget.ESNext}),i=new Set,o=s=>{var l,u;let c=s.parent;if(e.isImportSpecifier(c)){let d=c.parent.parent.parent;e.isImportDeclaration(d)&&e.isStringLiteral(d.moduleSpecifier)&&d.moduleSpecifier.text===Ln&&((l=c.propertyName)!==null&&l!==void 0?l:c.name)===s&&i.add(s.text);return}if(e.isExportSpecifier(c)){!(c.parent.parent.moduleSpecifier!==void 0)&&((u=c.propertyName)!==null&&u!==void 0?u:c.name)===s&&!n.pageOwnsLocalExport(c)&&i.add(s.text);return}e.isPropertyAccessExpression(c)&&c.name===s||e.isBindingElement(c)&&c.propertyName===s||e.isLabeledStatement(c)||e.isBreakOrContinueStatement(c)||n.pageOwns(s)||i.add(s.text)},a=s=>{e.isIdentifier(s)&&r.has(s.text)&&o(s),e.forEachChild(s,a)};return a(t),[...r.keys()].filter(s=>i.has(s))}Re.legacyEnumsNeeded=gT;function Dz(e,t,r){if(!e?.text||!t||r.length===0)return e;let n=new Map(e.enums),i=e.text;for(let o of r){let a=t.get(o);a&&(i+=a.declaration,n.set(o,a.model))}return{text:i,enums:n}}function Iz(e,t,r,n){var i;let o=new Set,a=uT(e,t,o);if(a.diagnostics.length>0)return a;let s=e.createSourceFile("page.tsx",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.TSX),l=e.createSourceFile("page.js",a.code,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),u=Dz(r,n,gT(e,l,n)),c=[...Az(e,l,s,u),...Sz(e,s,u,o)];if(!u?.text)return{code:a.code,diagnostics:c};let d=uT(e,u.text);if(d.diagnostics.length>0)throw new Ls.SdkError("GENPAGE_RUNTIME_TYPES_INVALID",`The generated runtime types do not compile (${d.diagnostics.map(h=>`${h.line}:${h.column} ${h.message}`).join("; ")}). This is an SDK defect: the page was not written.`);let f=_z(e,a.code),m=f.code;if(c.length===0&&(!((i=f.inexact)===null||i===void 0)&&i.swallows))c.push({...y0(e,s).statement(Ln,"import"),rule:"genpage-runtime-types-import-form",code:0,message:"the maker portal's patch would remove more than this './RuntimeTypes' import: a comment or other text before it contains the word 'import', and the pattern would delete from there \u2014 taking the code in between with it. Reword or move that text."});else if(c.length===0&&f.inexact){let{text:h}=f.inexact;c.push({...Tz(e,s,h),rule:"genpage-runtime-types-import-form",code:0,message:`the maker portal's patch would delete \`${h.length>80?`${h.slice(0,79)}\u2026`:h}\` from text that only looks like an import of './RuntimeTypes' \u2014 in a string, a template or a comment \u2014 so the page it ships would differ from this source. Reword that text so it no longer reads as such an import.`})}else c.length===0&&Nz(e,m)&&c.push({...y0(e,s).statement(Ln,"import"),rule:"genpage-runtime-types-import-form",code:0,message:"this './RuntimeTypes' import is not one the maker portal's patch can remove (a comment holding a quote inside it stops the pattern), so it would reach the runtime, which cannot load it. Write it on one line, as 'import { name } from './RuntimeTypes';'."});return{code:[Re.GENPAGE_RUNTIME_TYPES_BEGIN,d.code,Re.GENPAGE_RUNTIME_TYPES_END,m].join(`-`),diagnostics:u}}Oe.compileGenPage=p8});var Eg=v(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});ps.isFailureAfterPrimaryWrite=ps.failedAfterPrimaryWrite=void 0;var NN=Symbol.for("cds-maker-sdk.createFailedAfterPrimaryWrite");function m8(e){return typeof e=="object"&&e!==null&&(e[NN]=!0),e}ps.failedAfterPrimaryWrite=m8;function h8(e){return typeof e=="object"&&e!==null&&e[NN]===!0}ps.isFailureAfterPrimaryWrite=h8});var Fd=v(Jn=>{"use strict";Object.defineProperty(Jn,"__esModule",{value:!0});Jn.appApi=Jn.deleteAppResolvingOnce=Jn.mainFormSetShapeIssues=Jn.unpublishedAppModulesQuery=void 0;var ms=Xt(),g8=Ig(),y8=og(),_N=Kr(),b8=Id(),v8=Eg(),pe=ye(),Ee=ue(),Sg=lt(),UN=Wl(),Se=Q(),w8=(0,Ee.odataQuery)([["$select","appmoduleid,name,uniquename,description,aiappdescription"]]),Ng="appmoduleid,name,uniquename,description,aiappdescription";function kd(e,t,r){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ee.odataQuery)([["$select",e],["$filter",t],["$top",r]])}Jn.unpublishedAppModulesQuery=kd;function _g(e,t){return kd(e,t?`appmoduleid eq ${t}`:void 0,t?1:void 0)}function xd(e,t){return"/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ee.odataQuery)([["$select",t],["$filter",`sitemapid eq ${e}`],["$top",1]])}function nu(e){var t;let r=(t=e.body)===null||t===void 0?void 0:t.value;if(Array.isArray(r))return r[0]}function C8(e){let t=e?.["@odata.etag"];return typeof t=="string"?t:null}function $d(e,t){if(typeof e!="string")return!1;try{return(0,Ee.normalizeGuid)(e,"sitemapid")===t}catch{return!1}}function ea(e){let t=new Set,r=[];for(let n of e??[])n&&!t.has(n)&&(t.add(n),r.push(n));return r}function E8(e){return`cdsapp_${(e||"").replace(/[^a-zA-Z0-9]/g,"")||"app"}`}async function BN(e,t){var r,n;let i=u=>{throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`The sitemap lookup for app uniquename '${t??""}' ${u}, so it cannot be determined whether this app has a sitemap. Retry; if the app is newly created, publish it first (an unpublished app is not readable).`)};if(!t)return i("cannot run because the app record carried no uniquename");let o=`/sitemaps${(0,Ee.odataQuery)([["$select","sitemapid"],["$filter",`sitemapnameunique eq '${(0,Ee.odataLiteral)(t)}'`],["$top",1]])}`,a;try{a=await e.get(o)}catch(u){return i(`failed (${u.message})`)}if(a.status<200||a.status>=300)return i(`returned HTTP ${a.status}`);let s=(r=a.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(s))return i("returned a malformed body");let l=(n=s[0])===null||n===void 0?void 0:n.sitemapid;return s.length>0&&!l?i("returned a row with no sitemapid"):l}async function A8(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,Ee.odataQuery)([["$select","webresourceid"],["$top",1],["$filter",s]])}`,n="(webresourcetype eq 5 or webresourcetype eq 6 or webresourcetype eq 7 or webresourcetype eq 10 or webresourcetype eq 11)",i=t(await e.get(r("webresourcetype eq 5 and ismanaged eq false and contains(name,'icon')")));if(i)return{id:i,managed:!1};let o=t(await e.get(r(`${n} and ismanaged eq false`)));if(o)return{id:o,managed:!1};let a=t(await e.get(r(n)));return a?{id:a,managed:!0}:void 0}var TN="627090ff-40a3-4053-8790-584edc5be201";function Ii(e){return e instanceof Error?e.message:String(e)}async function S8(e,t){var r;try{let n=`/roles${(0,Ee.odataQuery)([["$select","roleid,_parentrootroleid_value"],["$filter",`_roletemplateid_value eq ${TN}`]])}`,i=await(0,ms.collectPages)(e,n,"the System Administrator role"),o=i.find(l=>typeof l.roleid=="string"&&typeof l._parentrootroleid_value=="string"&&l.roleid.toLowerCase()===l._parentrootroleid_value.toLowerCase()),a=(r=o??i.find(l=>typeof l.roleid=="string"))===null||r===void 0?void 0:r.roleid;if(!a)return`App roles: no 'System Administrator' role (template ${TN}) was found in this environment, so the SDK did not associate one with the app \u2014 it may not be visible or playable until a role is granted access to it.`;let s=`/appmodules(${t})/appmoduleroles_association/$ref`;return(0,pe.ensureSuccess)(await e.post(s,{"@odata.id":e.apiUrl(`/roles(${a})`)}),e.apiUrl(s)),null}catch(n){return`App roles: could not associate the 'System Administrator' role with the app (${Ii(n)}); it will not be visible or playable until a role is granted access to it.`}}async function N8(e,t,r=!0){let n=[];async function i(l,u,c){try{return(await(0,ms.collectPages)(e,l,`app assets (${c} for '${t}')`)).map(f=>String(f[u])).filter(f=>f&&f!=="undefined")}catch(d){return n.push(`App components: could not enumerate ${c} for table '${t}' (${Ii(d)}); they were NOT added to the app.`),[]}}let[o,a,s]=await Promise.all([r?i(`/systemforms${(0,Ee.odataQuery)([["$select","formid"],["$filter",`objecttypecode eq '${(0,Ee.odataLiteral)(t)}' and type eq 2 and formactivationstate eq 1`]])}`,"formid","forms"):Promise.resolve([]),i(`/savedqueries${(0,Ee.odataQuery)([["$select","savedqueryid"],["$filter",`returnedtypecode eq '${(0,Ee.odataLiteral)(t)}' and querytype eq 0 and statecode eq 0`]])}`,"savedqueryid","views"),i(`/savedqueryvisualizations${(0,Ee.odataQuery)([["$select","savedqueryvisualizationid"],["$filter",`primaryentitytypecode eq '${(0,Ee.odataLiteral)(t)}'`]])}`,"savedqueryvisualizationid","charts")]);return{forms:o,views:a,charts:s,warnings:n}}var DN=new WeakMap;async function _8(e,t){let r=DN.get(e);r||(r=new Map,DN.set(e,r));let n=r.get(t);if(n!==void 0)return n;let i=await T8(e,t);return i&&r.set(t,i),i}async function IN(e,t,r){let n=new Array(e.length),i=0;async function o(){for(let a=i;a<e.length;a=i)i=a+1,n[a]=await r(e[a])}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>o())),n}async function T8(e,t){let r=`/EntityDefinitions(LogicalName='${(0,Ee.odataPathLiteral)(t)}')${(0,Ee.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 ON(e,t,r){let n=[],i=ea(t.entities),o=4,a=await IN(i,o,g=>_8(e,g)),s=i.filter((g,b)=>!a[b]);if(s.length>0)throw new Se.SdkError("APP_ENTITY_COMPONENT_UNRESOLVED",`Refusing to build app components: table(s) ${s.map(g=>`'${g}'`).join(", ")} could not be resolved to an EntityDefinitions MetadataId + EntitySetName. Pinning the rest would produce an app whose navigation references a table the app does not contain. Verify the table name(s) exist in this environment and retry.`);let l=a.filter(g=>!!g);for(let g of l)n.push({"@odata.id":`${g.entitySetName}(${g.metadataId})`});for(let g of ea(t.components.forms))n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});for(let g of ea(t.components.views))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:g});for(let g of ea(t.components.charts))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:g});for(let g of ea(t.components.dashboards))n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});let u=new Set(t.components.forms),c=new Set(t.components.views),d=new Set(t.components.charts),f=new Map((r??[]).map(g=>[g.table,g])),p=await IN(i,o,g=>N8(e,g,!f.has(g.toLowerCase()))),m=p.flatMap(g=>g.warnings),h=new Set([...ea(t.components.forms),...ea(t.components.dashboards)].map(Ur));return p.forEach((g,b)=>{let w=f.get(i[b].toLowerCase());if(w)for(let E of w.allowed)h.has(E)||(h.add(E),u.add(E),n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:E}));else for(let E of g.forms)u.has(E)||(u.add(E),n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:E}));for(let E of g.views)c.has(E)||(c.add(E),n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:E}));for(let E of g.charts)d.has(E)||(d.add(E),n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:E}))}),{components:n,tables:l,warnings:m}}function Ur(e){let t=String(e).trim();return(t.startsWith("{")&&t.endsWith("}")?t.slice(1,-1):t).toLowerCase()}var Dg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Tg="/components/mainFormsByTable",PN=50;function qN(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function VN(e,t){if(e===void 0)return[];if(e===null||typeof e!="object"||Array.isArray(e))return[{pointer:Tg,rule:"app-main-form-set-shape",message:"must be an object mapping a table logical name to its Main form ids"}];let r=[],n=new Set(t.map(o=>o.toLowerCase())),i=new Set;for(let[o,a]of Object.entries(e)){let s=o.toLowerCase(),l=`${Tg}/${qN(o)}`;if(i.has(s)){r.push({pointer:l,rule:"app-main-form-set-shape",message:`table '${o}' is listed twice (logical names compare case-insensitively)`});continue}if(i.add(s),n.has(s)||r.push({pointer:l,rule:"app-main-form-set-table",message:`'${o}' is not a table this app's sitemap navigates to (Entity subareas: ${[...n].join(", ")||"none"})`}),!Array.isArray(a)){r.push({pointer:l,rule:"app-main-form-set-shape",message:"must be an array of Main form ids"});continue}if(a.length===0){r.push({pointer:l,rule:"app-main-form-set-empty",message:`an empty list is refused: an app with no Main form of '${o}' offers every form of the table`});continue}let u=new Set;a.forEach((c,d)=>{let f=`${l}/${d}`;typeof c!="string"||!Dg.test(Ur(c))?r.push({pointer:f,rule:"app-main-form-set-shape",message:`'${String(c)}' is not a form id`}):u.has(Ur(c))?r.push({pointer:f,rule:"app-main-form-set-shape",message:`form '${c}' is listed twice`}):u.add(Ur(c))})}return r}Jn.mainFormSetShapeIssues=VN;async function RN(e,t,r){let n=t.components.mainFormsByTable;if(n===void 0)return;let i=VN(n,t.entities);if(i.length>0)throw new Se.ValidationError("app",r,i);if(Object.keys(n).length===0)return;let o=[],a=[];for(let[l,u]of Object.entries(n)){let c=l.toLowerCase(),d=await(0,ms.collectPages)(e,`/systemforms${(0,Ee.odataQuery)([["$select","formid,formactivationstate"],["$filter",`objecttypecode eq '${(0,Ee.odataLiteral)(c)}' and type eq 2`]])}`,`app Main-form allow-list ('${c}')`),f=new Set,p=new Set;for(let h of d)typeof h.formid=="string"&&(f.add(Ur(h.formid)),Number(h.formactivationstate)===1&&p.add(Ur(h.formid)));let m=u.map(Ur);m.forEach((h,g)=>{let b=`${Tg}/${qN(l)}/${g}`;f.has(h)?p.has(h)||o.push({pointer:b,rule:"app-main-form-set-inactive",message:`Main form '${u[g]}' of '${c}' is inactive, so no app can offer it`}):o.push({pointer:b,rule:"app-main-form-set-not-main-form",message:`'${u[g]}' is not a Main form of '${c}'`})}),a.push({table:c,allowed:m,catalog:f})}let s=[...t.components.forms.map((l,u)=>({id:l,pointer:`/components/forms/${u}`})),...t.components.dashboards.map((l,u)=>({id:l,pointer:`/components/dashboards/${u}`}))];for(let l of s){let u=Ur(l.id);for(let c of a)c.catalog.has(u)&&!c.allowed.includes(u)&&o.push({pointer:l.pointer,rule:"app-main-form-set-conflict",message:`'${l.id}' is a Main form of '${c.table}' outside its allow-list, and this pin (an explicit form or dashboard, or a sitemap DashBoard subarea) would add it. Remove the pin, or list the form.`})}if(o.length>0)throw new Se.ValidationError("app",r,o);return a}async function D8(e,t){var r,n;let i=u=>({kind:"inconclusive",reason:u}),o=await e.get(kd("appmoduleid,appmoduleidunique,componentstate",`appmoduleid eq ${t}`));if(o.status<200||o.status>=300)return i(`reading the app returned HTTP ${o.status}`);let a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a)||a.length===0)return i("reading the app returned no row");let s=a.length===1?a:a.filter(u=>Number(u?.componentstate)===1),l=s.length===1?(n=s[0])===null||n===void 0?void 0:n.appmoduleidunique:"";return typeof l!="string"||!Dg.test(Ur(l))?i(`no single current layer among ${a.length} app row(s)`):{kind:"read",unique:Ur(l)}}function Rd(e,t){let r;return()=>r??(r=D8(e,t))}async function GN(e,t,r,n=Rd(e,t)){let i=p=>({kind:"inconclusive",reason:p}),o=await n();if(o.kind==="inconclusive")return o;let a=o.unique,s;try{let p=await(0,ms.collectPages)(e,`/appmodulecomponents${(0,Ee.odataQuery)([["$select","objectid"],["$filter",`_appmoduleidunique_value eq ${Ur(a)} and componenttype eq 60`]])}`,`app Main-form membership ('${t}')`);if(p.some(m=>typeof m.objectid!="string"))return i("a form component carries no object id");s=p.map(m=>Ur(String(m.objectid)))}catch(p){return i(`reading its form components failed (${Ii(p)})`)}let l=new Map,u=[];for(let p of new Set(s)){let m=r.find(h=>h.catalog.has(p));m?l.set(p,m.table):u.push(p)}if(u.some(p=>!Dg.test(p)))return i("a form component carries an object id that is not a GUID");let c=new Set(r.map(p=>p.table)),d=new Set;for(let p=0;p<u.length;p+=PN){let m=u.slice(p,p+PN);try{let h=await(0,ms.collectPages)(e,`/systemforms${(0,Ee.odataQuery)([["$select","formid,type,objecttypecode"],["$filter",m.map(g=>`formid eq ${g}`).join(" or ")]])}`,`app Main-form membership ('${t}': classifying components)`);for(let g of h){if(typeof g.formid!="string"||typeof g.type!="number"||g.type===2&&(typeof g.objecttypecode!="string"||g.objecttypecode===""))continue;let b=Ur(g.formid);d.add(b);let w=g.type===2?String(g.objecttypecode).toLowerCase():"";c.has(w)&&l.set(b,w)}}catch(h){return i(`classifying its form components failed (${Ii(h)})`)}}let f=u.filter(p=>!d.has(p));return f.length>0?i(`form component(s) ${f.join(", ")} could not be classified`):{kind:"read",tables:r.map(p=>{let m=[...l].filter(([,h])=>h===p.table).map(([h])=>h);return{table:p.table,members:m,extras:m.filter(h=>!p.allowed.includes(h)),missing:p.allowed.filter(h=>!m.includes(h))}})}}async function I8(e,t,r,n){let i=await GN(e,t,r,n);if(i.kind==="inconclusive")throw new Se.SdkError("APP_MAIN_FORM_SET_UNVERIFIED",`App '${t}': its Main-form allow-list was written but could not be verified \u2014 ${i.reason}.`);let o=i.tables.filter(a=>a.extras.length>0||a.missing.length>0);if(o.length>0)throw new Se.SdkError("APP_MAIN_FORM_SET_NOT_APPLIED",`App '${t}': its Main forms do not match the allow-list after the write \u2014 ${o.map(a=>`'${a.table}': unexpected [${a.extras.join(", ")}], missing [${a.missing.join(", ")}]`).join("; ")}.`)}async function O8(e,t,r,n){let i;try{i=await GN(e,t,r,n)}catch(a){i={kind:"inconclusive",reason:Ii(a)}}if(i.kind==="inconclusive")return[`Main-form membership of app '${t}' could not be verified (${i.reason}).`];let o=[];for(let a of i.tables)a.extras.length>0&&o.push(`Main-form components outside the allow-list remain for table '${a.table}': [${a.extras.join(", ")}]. This option controls additions only; it does not remove existing components. Runtime form availability has not been verified.`),a.missing.length>0&&o.push(`Allow-listed Main forms are not in app '${t}' after the push for table '${a.table}': [${a.missing.join(", ")}]; re-push to retry.`);return o}async function LN(e,t,r){if(r.length===0)return;let n="/AddAppComponents";(0,pe.ensureSuccess)(await e.post(n,{AppId:t,Components:r}),e.apiUrl(n))}async function kN(e,t,r,n=Rd(e,t)){var i;if(r.length===0)return;let o=await n();if(o.kind==="inconclusive")throw new Se.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its components were written but could not be verified \u2014 ${o.reason}. Re-push to retry.`);let a=`/appmodulecomponents${(0,Ee.odataQuery)([["$select","objectid,componenttype"],["$filter",`_appmoduleidunique_value eq ${o.unique} and componenttype eq 1`]])}`,s=await e.get(a);if(s.status<200||s.status>=300)throw new Se.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 reading them back returned HTTP ${s.status}. Re-push to retry.`);let l=(i=s.body)===null||i===void 0?void 0:i.value;if(!Array.isArray(l))throw new Se.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 the read-back returned no readable result set. Re-push to retry.`);let u=new Set(l.map(d=>d.objectid).filter(d=>typeof d=="string").map(d=>d.toLowerCase())),c=r.filter(d=>!u.has(d.metadataId.toLowerCase()));if(c.length>0)throw new Se.SdkError("APP_COMPONENTS_NOT_PERSISTED",`App '${t}': ${c.length} declared table(s) are NOT components of the app after AddAppComponents reported success \u2014 ${c.map(d=>`'${d.logicalName}' (expected objectid ${d.metadataId})`).join(", ")}. The app's navigation would reference content the app does not contain.`)}async function P8(e,t,r){let n=`/appmodules(${t})`,i=`/sitemaps(${r.sitemapId})`,o;try{o=await L8(e,r.sitemapId,r.sitemapNameUnique)}catch(l){return{outcome:"kept",reason:`whether its sitemap row exists could not be determined (${Ii(l)})`}}let a=o==="foreign",s=l=>l.kind==="deleted"?{outcome:"removed",foreignSitemap:a}:l.kind==="refused"?{outcome:"kept",foreignSitemap:a,reason:`its delete was refused (${Ii(l.error)})`}:{outcome:"unconfirmed",foreignSitemap:a,reason:`its delete was sent but its outcome is unknown (${Ii(l.error)})`};try{if(o==="absent"||o==="foreign"){if(!r.serverRefusedSitemap)return{outcome:"kept",foreignSitemap:a,reason:"the sitemap write's outcome was never observed, so its row may still appear"};let l=await(0,pe.resendAppSearchIndexRace)(()=>e.delete(n));return s(l.status===404?{kind:"deleted"}:zN(l,e.apiUrl(n)))}return e.supportsAtomicBatch?r.sitemapWriteToken?s(await jN(e,[{path:n},{path:i,etag:r.sitemapWriteToken}])):{outcome:"kept",reason:"the sitemap write returned no token of its own, and deleting the row without one could destroy another writer's change"}:{outcome:"kept",reason:"the HttpClient cannot send an atomic change set (no `postRaw`), and deleting the two rows one at a time could strand the sitemap"}}catch(l){return s({kind:"unknown",error:l})}}function R8(e,t,r){if(!(e instanceof Error))return e;let n=t.foreignSitemap?` Sitemap id '${r.sitemapId}' already belongs to ANOTHER app's sitemap, which was left untouched and must not be deleted: supply a sitemapId no other app uses, or omit it so one is minted.`:"";if(t.outcome==="removed")return e.message+=` The partial app this create wrote was removed.${n}`,e;let i=t.foreignSitemap?`appmodule '${r.appId}' (unique name '${r.uniqueName}')`:`appmodule '${r.appId}' (unique name '${r.uniqueName}') and, if it was written, sitemap '${r.sitemapId}'`,a=`a create with that unique name is refused \u2014 remove it in the maker portal, or, once you have confirmed the rows are this create's own, with ${t.foreignSitemap?`deleteRecord('appmodule', '${r.appId}')`:`deleteRecord('appmodule', '${r.appId}') and deleteRecord('sitemap', '${r.sitemapId}')`}.`;return e.message+=t.outcome==="kept"?` The partial app this create wrote was KEPT, because ${t.reason}: ${i}. While it exists, ${a}`:` Whether the partial app this create wrote was removed could not be confirmed, because ${t.reason}. Check for ${i}: while any of it exists, ${a}`,e.message+=n,e}async function L8(e,t,r){var n,i,o;let a=xd(t,"sitemapid,sitemapnameunique"),s=await e.get(a);if(s.status<200||s.status>=300)throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned HTTP ${s.status}, so it cannot be determined whether the row exists.`);let l=(n=s.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(l))throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned no readable result set, so it cannot be determined whether the row exists.`);return l.length===0?"absent":String((o=(i=l[0])===null||i===void 0?void 0:i.sitemapnameunique)!==null&&o!==void 0?o:"")===r?"ours":"foreign"}async function k8(e,t){var r;let n;try{n=await e.get(kd("appmoduleid,uniquename,componentstate",`appmoduleid eq ${t}`))}catch(s){return{kind:"unsettled",why:`its unpublished read failed (${s.message})`}}if(n.status<200||n.status>=300)return{kind:"unsettled",why:`its unpublished read returned HTTP ${n.status}`};let i=(r=n.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(i)||i.length!==1)return{kind:"unsettled",why:`its unpublished read returned ${Array.isArray(i)?i.length:"no"} row(s), not exactly one`};let o=i[0],a=o?.uniquename;return!$d(o?.appmoduleid,t)||o?.componentstate!==1||typeof a!="string"||!a?{kind:"unsettled",why:"its unpublished row is not this app as a never-published draft"}:{kind:"draft",uniquename:a}}async function WN(e,t){var r;let n=(0,Ee.normalizeGuid)(t,"id"),i=b=>{throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${n}': ${b} Deleting the app would destroy the only pointer to its sitemap, stranding that row and reserving its unique name forever. Retry.`)},o=`/appmodules(${n})${w8}`,a;try{a=await e.get(o)}catch(b){return i(`reading the app failed (${b.message}).`)}let s,l=!1;if(a.status===404){let b=await k8(e,n);if(b.kind!=="draft")return i(`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; ${b.why}.`);s=b.uniquename,l=!0}else{if(a.status<200||a.status>=300)return i(`reading the app returned HTTP ${a.status}.`);s=(r=a.body)===null||r===void 0?void 0:r.uniquename}if(!s)return i("the app record carried no uniquename, so its sitemap cannot be located.");let u=l?{draft:!0}:{appEtag:(0,pe.readEtag)(a)},c=await BN(e,s);if(!c)return{uniquename:s,...u};let d=(0,Ee.normalizeGuid)(c,"sitemapId"),f=await Ld(e,d),p=xd(d,"sitemapid,sitemapnameunique,sitemapxml"),m;try{m=await e.get(p)}catch(b){return i(`reading sitemap '${d}' failed (${b.message}).`)}if(m.status<200||m.status>=300)return i(`reading sitemap '${d}' returned HTTP ${m.status}.`);let h=nu(m);if(!h)return i(`sitemap '${d}' was not returned by the unpublished-aware read.`);if(h.sitemapnameunique!==s)return i(`sitemap '${d}' now carries sitemapnameunique '${String(h.sitemapnameunique)}', not '${s}', so it is no longer this app's sitemap.`);if(!$d(h.sitemapid,d))return i(`sitemap '${d}' was read back as a row carrying sitemapid '${String(h.sitemapid)}'.`);let g=h.sitemapxml;return typeof g!="string"?i(`sitemap '${d}' returned no sitemapxml.`):{sitemapId:d,uniquename:s,sitemapXml:g,...u,sitemapEtag:f}}async function x8(e,t,r){let n=(0,Ee.normalizeGuid)(t,"id"),i=await WN(e,n);await r?.(i.sitemapXml),await KN(e,n,i)}Jn.deleteAppResolvingOnce=x8;async function $8(e,t){let r=await jN(e,t);if(r.kind!=="deleted")throw r.error}function zN(e,t){try{return(0,pe.ensureSuccess)(e,t),{kind:"deleted"}}catch(r){return HN(e.status)?{kind:"refused",error:r}:{kind:"unknown",error:r}}}function F8(e,t){var r;if(e.status!==400&&(e.status<200||e.status>=300))return!1;let n=(r=(0,UN.parseChangeSetParts)(e.body,t))===null||r===void 0?void 0:r.filter(i=>i.status<200||i.status>=300);return n!==void 0&&n.length>0&&n.every(i=>i.status===400&&(0,pe.namesAppSearchIndexRace)(i.text))}async function jN(e,t){let r=`batch_${(0,Sg.newId)()}`,n=`changeset_${(0,Sg.newId)()}`,i=t.map((p,m)=>[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${m+1}`,"",`DELETE ${e.apiUrl(p.path)} HTTP/1.1`,...p.etag?[`If-Match: ${p.etag}`]:[],""].join(`\r+`),diagnostics:c}}Re.compileGenPage=Iz});var w0=v(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});ks.isFailureAfterPrimaryWrite=ks.failedAfterPrimaryWrite=void 0;var yT=Symbol.for("cds-maker-sdk.createFailedAfterPrimaryWrite");function Oz(e){return typeof e=="object"&&e!==null&&(e[yT]=!0),e}ks.failedAfterPrimaryWrite=Oz;function Pz(e){return typeof e=="object"&&e!==null&&e[yT]===!0}ks.isFailureAfterPrimaryWrite=Pz});var Af=v(li=>{"use strict";Object.defineProperty(li,"__esModule",{value:!0});li.appApi=li.deleteAppResolvingOnce=li.mainFormSetShapeIssues=li.unpublishedAppModulesQuery=void 0;var $s=Tt(),Rz=T0(),Lz=jg(),bT=jr(),kz=tf(),$z=w0(),ge=fe(),Ae=oe(),E0=ct(),PT=Es(),_e=Q(),xz=(0,Ae.odataQuery)([["$select","appmoduleid,name,uniquename,description,aiappdescription"]]),A0="appmoduleid,name,uniquename,description,aiappdescription";function wf(e,t,r){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ae.odataQuery)([["$select",e],["$filter",t],["$top",r]])}li.unpublishedAppModulesQuery=wf;function S0(e,t){return wf(e,t?`appmoduleid eq ${t}`:void 0,t?1:void 0)}function Cf(e,t){return"/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ae.odataQuery)([["$select",t],["$filter",`sitemapid eq ${e}`],["$top",1]])}function _u(e){var t;let r=(t=e.body)===null||t===void 0?void 0:t.value;if(Array.isArray(r))return r[0]}function Fz(e){let t=e?.["@odata.etag"];return typeof t=="string"?t:null}function Ef(e,t){if(typeof e!="string")return!1;try{return(0,Ae.normalizeGuid)(e,"sitemapid")===t}catch{return!1}}function ma(e){let t=new Set,r=[];for(let n of e??[])n&&!t.has(n)&&(t.add(n),r.push(n));return r}function Mz(e){return`cdsapp_${(e||"").replace(/[^a-zA-Z0-9]/g,"")||"app"}`}async function RT(e,t){var r,n;let i=u=>{throw new _e.SdkError("APP_SITEMAP_UNRESOLVED",`The sitemap lookup for app uniquename '${t??""}' ${u}, so it cannot be determined whether this app has a sitemap. Retry; if the app is newly created, publish it first (an unpublished app is not readable).`)};if(!t)return i("cannot run because the app record carried no uniquename");let o=`/sitemaps${(0,Ae.odataQuery)([["$select","sitemapid"],["$filter",`sitemapnameunique eq '${(0,Ae.odataLiteral)(t)}'`],["$top",1]])}`,a;try{a=await e.get(o)}catch(u){return i(`failed (${u.message})`)}if(a.status<200||a.status>=300)return i(`returned HTTP ${a.status}`);let s=(r=a.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(s))return i("returned a malformed body");let l=(n=s[0])===null||n===void 0?void 0:n.sitemapid;return s.length>0&&!l?i("returned a row with no sitemapid"):l}async function Uz(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,Ae.odataQuery)([["$select","webresourceid"],["$top",1],["$filter",s]])}`,n="(webresourcetype eq 5 or webresourcetype eq 6 or webresourcetype eq 7 or webresourcetype eq 10 or webresourcetype eq 11)",i=t(await e.get(r("webresourcetype eq 5 and ismanaged eq false and contains(name,'icon')")));if(i)return{id:i,managed:!1};let o=t(await e.get(r(`${n} and ismanaged eq false`)));if(o)return{id:o,managed:!1};let a=t(await e.get(r(n)));return a?{id:a,managed:!0}:void 0}var vT="627090ff-40a3-4053-8790-584edc5be201";function Gi(e){return e instanceof Error?e.message:String(e)}async function Bz(e,t){var r;try{let n=`/roles${(0,Ae.odataQuery)([["$select","roleid,_parentrootroleid_value"],["$filter",`_roletemplateid_value eq ${vT}`]])}`,i=await(0,$s.collectPages)(e,n,"the System Administrator role"),o=i.find(l=>typeof l.roleid=="string"&&typeof l._parentrootroleid_value=="string"&&l.roleid.toLowerCase()===l._parentrootroleid_value.toLowerCase()),a=(r=o??i.find(l=>typeof l.roleid=="string"))===null||r===void 0?void 0:r.roleid;if(!a)return`App roles: no 'System Administrator' role (template ${vT}) was found in this environment, so the SDK did not associate one with the app \u2014 it may not be visible or playable until a role is granted access to it.`;let s=`/appmodules(${t})/appmoduleroles_association/$ref`;return(0,ge.ensureSuccess)(await e.post(s,{"@odata.id":e.apiUrl(`/roles(${a})`)}),e.apiUrl(s)),null}catch(n){return`App roles: could not associate the 'System Administrator' role with the app (${Gi(n)}); it will not be visible or playable until a role is granted access to it.`}}async function qz(e,t,r=!0){let n=[];async function i(l,u,c){try{return(await(0,$s.collectPages)(e,l,`app assets (${c} for '${t}')`)).map(f=>String(f[u])).filter(f=>f&&f!=="undefined")}catch(d){return n.push(`App components: could not enumerate ${c} for table '${t}' (${Gi(d)}); they were NOT added to the app.`),[]}}let[o,a,s]=await Promise.all([r?i(`/systemforms${(0,Ae.odataQuery)([["$select","formid"],["$filter",`objecttypecode eq '${(0,Ae.odataLiteral)(t)}' and type eq 2 and formactivationstate eq 1`]])}`,"formid","forms"):Promise.resolve([]),i(`/savedqueries${(0,Ae.odataQuery)([["$select","savedqueryid"],["$filter",`returnedtypecode eq '${(0,Ae.odataLiteral)(t)}' and querytype eq 0 and statecode eq 0`]])}`,"savedqueryid","views"),i(`/savedqueryvisualizations${(0,Ae.odataQuery)([["$select","savedqueryvisualizationid"],["$filter",`primaryentitytypecode eq '${(0,Ae.odataLiteral)(t)}'`]])}`,"savedqueryvisualizationid","charts")]);return{forms:o,views:a,charts:s,warnings:n}}var wT=new WeakMap;async function Vz(e,t){let r=wT.get(e);r||(r=new Map,wT.set(e,r));let n=r.get(t);if(n!==void 0)return n;let i=await Gz(e,t);return i&&r.set(t,i),i}async function CT(e,t,r){let n=new Array(e.length),i=0;async function o(){for(let a=i;a<e.length;a=i)i=a+1,n[a]=await r(e[a])}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>o())),n}async function Gz(e,t){let r=`/EntityDefinitions(LogicalName='${(0,Ae.odataPathLiteral)(t)}')${(0,Ae.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 ET(e,t,r){let n=[],i=ma(t.entities),o=4,a=await CT(i,o,g=>Vz(e,g)),s=i.filter((g,b)=>!a[b]);if(s.length>0)throw new _e.SdkError("APP_ENTITY_COMPONENT_UNRESOLVED",`Refusing to build app components: table(s) ${s.map(g=>`'${g}'`).join(", ")} could not be resolved to an EntityDefinitions MetadataId + EntitySetName. Pinning the rest would produce an app whose navigation references a table the app does not contain. Verify the table name(s) exist in this environment and retry.`);let l=a.filter(g=>!!g);for(let g of l)n.push({"@odata.id":`${g.entitySetName}(${g.metadataId})`});for(let g of ma(t.components.forms))n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});for(let g of ma(t.components.views))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:g});for(let g of ma(t.components.charts))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:g});for(let g of ma(t.components.dashboards))n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});let u=new Set(t.components.forms),c=new Set(t.components.views),d=new Set(t.components.charts),f=new Map((r??[]).map(g=>[g.table,g])),m=await CT(i,o,g=>qz(e,g,!f.has(g.toLowerCase()))),p=m.flatMap(g=>g.warnings),h=new Set([...ma(t.components.forms),...ma(t.components.dashboards)].map(Xr));return m.forEach((g,b)=>{let w=f.get(i[b].toLowerCase());if(w)for(let C of w.allowed)h.has(C)||(h.add(C),u.add(C),n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:C}));else for(let C of g.forms)u.has(C)||(u.add(C),n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:C}));for(let C of g.views)c.has(C)||(c.add(C),n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:C}));for(let C of g.charts)d.has(C)||(d.add(C),n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:C}))}),{components:n,tables:l,warnings:p}}function Xr(e){let t=String(e).trim();return(t.startsWith("{")&&t.endsWith("}")?t.slice(1,-1):t).toLowerCase()}var _0=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,N0="/components/mainFormsByTable",AT=50;function LT(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function kT(e,t){if(e===void 0)return[];if(e===null||typeof e!="object"||Array.isArray(e))return[{pointer:N0,rule:"app-main-form-set-shape",message:"must be an object mapping a table logical name to its Main form ids"}];let r=[],n=new Set(t.map(o=>o.toLowerCase())),i=new Set;for(let[o,a]of Object.entries(e)){let s=o.toLowerCase(),l=`${N0}/${LT(o)}`;if(i.has(s)){r.push({pointer:l,rule:"app-main-form-set-shape",message:`table '${o}' is listed twice (logical names compare case-insensitively)`});continue}if(i.add(s),n.has(s)||r.push({pointer:l,rule:"app-main-form-set-table",message:`'${o}' is not a table this app's sitemap navigates to (Entity subareas: ${[...n].join(", ")||"none"})`}),!Array.isArray(a)){r.push({pointer:l,rule:"app-main-form-set-shape",message:"must be an array of Main form ids"});continue}if(a.length===0){r.push({pointer:l,rule:"app-main-form-set-empty",message:`an empty list is refused: an app with no Main form of '${o}' offers every form of the table`});continue}let u=new Set;a.forEach((c,d)=>{let f=`${l}/${d}`;typeof c!="string"||!_0.test(Xr(c))?r.push({pointer:f,rule:"app-main-form-set-shape",message:`'${String(c)}' is not a form id`}):u.has(Xr(c))?r.push({pointer:f,rule:"app-main-form-set-shape",message:`form '${c}' is listed twice`}):u.add(Xr(c))})}return r}li.mainFormSetShapeIssues=kT;async function ST(e,t,r){let n=t.components.mainFormsByTable;if(n===void 0)return;let i=kT(n,t.entities);if(i.length>0)throw new _e.ValidationError("app",r,i);if(Object.keys(n).length===0)return;let o=[],a=[];for(let[l,u]of Object.entries(n)){let c=l.toLowerCase(),d=await(0,$s.collectPages)(e,`/systemforms${(0,Ae.odataQuery)([["$select","formid,formactivationstate"],["$filter",`objecttypecode eq '${(0,Ae.odataLiteral)(c)}' and type eq 2`]])}`,`app Main-form allow-list ('${c}')`),f=new Set,m=new Set;for(let h of d)typeof h.formid=="string"&&(f.add(Xr(h.formid)),Number(h.formactivationstate)===1&&m.add(Xr(h.formid)));let p=u.map(Xr);p.forEach((h,g)=>{let b=`${N0}/${LT(l)}/${g}`;f.has(h)?m.has(h)||o.push({pointer:b,rule:"app-main-form-set-inactive",message:`Main form '${u[g]}' of '${c}' is inactive, so no app can offer it`}):o.push({pointer:b,rule:"app-main-form-set-not-main-form",message:`'${u[g]}' is not a Main form of '${c}'`})}),a.push({table:c,allowed:p,catalog:f})}let s=[...t.components.forms.map((l,u)=>({id:l,pointer:`/components/forms/${u}`})),...t.components.dashboards.map((l,u)=>({id:l,pointer:`/components/dashboards/${u}`}))];for(let l of s){let u=Xr(l.id);for(let c of a)c.catalog.has(u)&&!c.allowed.includes(u)&&o.push({pointer:l.pointer,rule:"app-main-form-set-conflict",message:`'${l.id}' is a Main form of '${c.table}' outside its allow-list, and this pin (an explicit form or dashboard, or a sitemap DashBoard subarea) would add it. Remove the pin, or list the form.`})}if(o.length>0)throw new _e.ValidationError("app",r,o);return a}async function Wz(e,t){var r,n;let i=u=>({kind:"inconclusive",reason:u}),o=await e.get(wf("appmoduleid,appmoduleidunique,componentstate",`appmoduleid eq ${t}`));if(o.status<200||o.status>=300)return i(`reading the app returned HTTP ${o.status}`);let a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a)||a.length===0)return i("reading the app returned no row");let s=a.length===1?a:a.filter(u=>Number(u?.componentstate)===1),l=s.length===1?(n=s[0])===null||n===void 0?void 0:n.appmoduleidunique:"";return typeof l!="string"||!_0.test(Xr(l))?i(`no single current layer among ${a.length} app row(s)`):{kind:"read",unique:Xr(l)}}function bf(e,t){let r;return()=>r??(r=Wz(e,t))}async function $T(e,t,r,n=bf(e,t)){let i=m=>({kind:"inconclusive",reason:m}),o=await n();if(o.kind==="inconclusive")return o;let a=o.unique,s;try{let m=await(0,$s.collectPages)(e,`/appmodulecomponents${(0,Ae.odataQuery)([["$select","objectid"],["$filter",`_appmoduleidunique_value eq ${Xr(a)} and componenttype eq 60`]])}`,`app Main-form membership ('${t}')`);if(m.some(p=>typeof p.objectid!="string"))return i("a form component carries no object id");s=m.map(p=>Xr(String(p.objectid)))}catch(m){return i(`reading its form components failed (${Gi(m)})`)}let l=new Map,u=[];for(let m of new Set(s)){let p=r.find(h=>h.catalog.has(m));p?l.set(m,p.table):u.push(m)}if(u.some(m=>!_0.test(m)))return i("a form component carries an object id that is not a GUID");let c=new Set(r.map(m=>m.table)),d=new Set;for(let m=0;m<u.length;m+=AT){let p=u.slice(m,m+AT);try{let h=await(0,$s.collectPages)(e,`/systemforms${(0,Ae.odataQuery)([["$select","formid,type,objecttypecode"],["$filter",p.map(g=>`formid eq ${g}`).join(" or ")]])}`,`app Main-form membership ('${t}': classifying components)`);for(let g of h){if(typeof g.formid!="string"||typeof g.type!="number"||g.type===2&&(typeof g.objecttypecode!="string"||g.objecttypecode===""))continue;let b=Xr(g.formid);d.add(b);let w=g.type===2?String(g.objecttypecode).toLowerCase():"";c.has(w)&&l.set(b,w)}}catch(h){return i(`classifying its form components failed (${Gi(h)})`)}}let f=u.filter(m=>!d.has(m));return f.length>0?i(`form component(s) ${f.join(", ")} could not be classified`):{kind:"read",tables:r.map(m=>{let p=[...l].filter(([,h])=>h===m.table).map(([h])=>h);return{table:m.table,members:p,extras:p.filter(h=>!m.allowed.includes(h)),missing:m.allowed.filter(h=>!p.includes(h))}})}}async function zz(e,t,r,n){let i=await $T(e,t,r,n);if(i.kind==="inconclusive")throw new _e.SdkError("APP_MAIN_FORM_SET_UNVERIFIED",`App '${t}': its Main-form allow-list was written but could not be verified \u2014 ${i.reason}.`);let o=i.tables.filter(a=>a.extras.length>0||a.missing.length>0);if(o.length>0)throw new _e.SdkError("APP_MAIN_FORM_SET_NOT_APPLIED",`App '${t}': its Main forms do not match the allow-list after the write \u2014 ${o.map(a=>`'${a.table}': unexpected [${a.extras.join(", ")}], missing [${a.missing.join(", ")}]`).join("; ")}.`)}async function jz(e,t,r,n){let i;try{i=await $T(e,t,r,n)}catch(a){i={kind:"inconclusive",reason:Gi(a)}}if(i.kind==="inconclusive")return[`Main-form membership of app '${t}' could not be verified (${i.reason}).`];let o=[];for(let a of i.tables)a.extras.length>0&&o.push(`Main-form components outside the allow-list remain for table '${a.table}': [${a.extras.join(", ")}]. This option controls additions only; it does not remove existing components. Runtime form availability has not been verified.`),a.missing.length>0&&o.push(`Allow-listed Main forms are not in app '${t}' after the push for table '${a.table}': [${a.missing.join(", ")}]; re-push to retry.`);return o}async function NT(e,t,r){if(r.length===0)return;let n="/AddAppComponents";(0,ge.ensureSuccess)(await e.post(n,{AppId:t,Components:r}),e.apiUrl(n))}async function _T(e,t,r,n=bf(e,t)){var i;if(r.length===0)return;let o=await n();if(o.kind==="inconclusive")throw new _e.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its components were written but could not be verified \u2014 ${o.reason}. Re-push to retry.`);let a=`/appmodulecomponents${(0,Ae.odataQuery)([["$select","objectid,componenttype"],["$filter",`_appmoduleidunique_value eq ${o.unique} and componenttype eq 1`]])}`,s=await e.get(a);if(s.status<200||s.status>=300)throw new _e.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 reading them back returned HTTP ${s.status}. Re-push to retry.`);let l=(i=s.body)===null||i===void 0?void 0:i.value;if(!Array.isArray(l))throw new _e.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 u=new Set(l.map(d=>d.objectid).filter(d=>typeof d=="string").map(d=>d.toLowerCase())),c=r.filter(d=>!u.has(d.metadataId.toLowerCase()));if(c.length>0)throw new _e.SdkError("APP_COMPONENTS_NOT_PERSISTED",`App '${t}': ${c.length} declared table(s) are NOT components of the app after AddAppComponents reported success \u2014 ${c.map(d=>`'${d.logicalName}' (expected objectid ${d.metadataId})`).join(", ")}. The app's navigation would reference content the app does not contain.`)}async function Hz(e,t,r){let n=`/appmodules(${t})`,i=`/sitemaps(${r.sitemapId})`,o;try{o=await Jz(e,r.sitemapId,r.sitemapNameUnique)}catch(l){return{outcome:"kept",reason:`whether its sitemap row exists could not be determined (${Gi(l)})`}}let a=o==="foreign",s=l=>l.kind==="deleted"?{outcome:"removed",foreignSitemap:a}:l.kind==="refused"?{outcome:"kept",foreignSitemap:a,reason:`its delete was refused (${Gi(l.error)})`}:{outcome:"unconfirmed",foreignSitemap:a,reason:`its delete was sent but its outcome is unknown (${Gi(l.error)})`};try{if(o==="absent"||o==="foreign"){if(!r.serverRefusedSitemap)return{outcome:"kept",foreignSitemap:a,reason:"the sitemap write's outcome was never observed, so its row may still appear"};let l=await(0,ge.resendAppSearchIndexRace)(()=>e.delete(n));return s(l.status===404?{kind:"deleted"}:FT(l,e.apiUrl(n)))}return e.supportsAtomicBatch?r.sitemapWriteToken?s(await MT(e,[{path:n},{path:i,etag:r.sitemapWriteToken}])):{outcome:"kept",reason:"the sitemap write returned no token of its own, and deleting the row without one could destroy another writer's change"}:{outcome:"kept",reason:"the HttpClient cannot send an atomic change set (no `postRaw`), and deleting the two rows one at a time could strand the sitemap"}}catch(l){return s({kind:"unknown",error:l})}}function Kz(e,t,r){if(!(e instanceof Error))return e;let n=t.foreignSitemap?` Sitemap id '${r.sitemapId}' already belongs to ANOTHER app's sitemap, which was left untouched and must not be deleted: supply a sitemapId no other app uses, or omit it so one is minted.`:"";if(t.outcome==="removed")return e.message+=` The partial app this create wrote was removed.${n}`,e;let i=t.foreignSitemap?`appmodule '${r.appId}' (unique name '${r.uniqueName}')`:`appmodule '${r.appId}' (unique name '${r.uniqueName}') and, if it was written, sitemap '${r.sitemapId}'`,a=`a create with that unique name is refused \u2014 remove it in the maker portal, or, once you have confirmed the rows are this create's own, with ${t.foreignSitemap?`deleteRecord('appmodule', '${r.appId}')`:`deleteRecord('appmodule', '${r.appId}') and deleteRecord('sitemap', '${r.sitemapId}')`}.`;return e.message+=t.outcome==="kept"?` The partial app this create wrote was KEPT, because ${t.reason}: ${i}. While it exists, ${a}`:` Whether the partial app this create wrote was removed could not be confirmed, because ${t.reason}. Check for ${i}: while any of it exists, ${a}`,e.message+=n,e}async function Jz(e,t,r){var n,i,o;let a=Cf(t,"sitemapid,sitemapnameunique"),s=await e.get(a);if(s.status<200||s.status>=300)throw new _e.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned HTTP ${s.status}, so it cannot be determined whether the row exists.`);let l=(n=s.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(l))throw new _e.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned no readable result set, so it cannot be determined whether the row exists.`);return l.length===0?"absent":String((o=(i=l[0])===null||i===void 0?void 0:i.sitemapnameunique)!==null&&o!==void 0?o:"")===r?"ours":"foreign"}async function Yz(e,t){var r;let n;try{n=await e.get(wf("appmoduleid,uniquename,componentstate",`appmoduleid eq ${t}`))}catch(s){return{kind:"unsettled",why:`its unpublished read failed (${s.message})`}}if(n.status<200||n.status>=300)return{kind:"unsettled",why:`its unpublished read returned HTTP ${n.status}`};let i=(r=n.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(i)||i.length!==1)return{kind:"unsettled",why:`its unpublished read returned ${Array.isArray(i)?i.length:"no"} row(s), not exactly one`};let o=i[0],a=o?.uniquename;return!Ef(o?.appmoduleid,t)||o?.componentstate!==1||typeof a!="string"||!a?{kind:"unsettled",why:"its unpublished row is not this app as a never-published draft"}:{kind:"draft",uniquename:a}}async function xT(e,t){var r;let n=(0,Ae.normalizeGuid)(t,"id"),i=b=>{throw new _e.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${n}': ${b} Deleting the app would destroy the only pointer to its sitemap, stranding that row and reserving its unique name forever. Retry.`)},o=`/appmodules(${n})${xz}`,a;try{a=await e.get(o)}catch(b){return i(`reading the app failed (${b.message}).`)}let s,l=!1;if(a.status===404){let b=await Yz(e,n);if(b.kind!=="draft")return i(`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; ${b.why}.`);s=b.uniquename,l=!0}else{if(a.status<200||a.status>=300)return i(`reading the app returned HTTP ${a.status}.`);s=(r=a.body)===null||r===void 0?void 0:r.uniquename}if(!s)return i("the app record carried no uniquename, so its sitemap cannot be located.");let u=l?{draft:!0}:{appEtag:(0,ge.readEtag)(a)},c=await RT(e,s);if(!c)return{uniquename:s,...u};let d=(0,Ae.normalizeGuid)(c,"sitemapId"),f=await vf(e,d),m=Cf(d,"sitemapid,sitemapnameunique,sitemapxml"),p;try{p=await e.get(m)}catch(b){return i(`reading sitemap '${d}' failed (${b.message}).`)}if(p.status<200||p.status>=300)return i(`reading sitemap '${d}' returned HTTP ${p.status}.`);let h=_u(p);if(!h)return i(`sitemap '${d}' was not returned by the unpublished-aware read.`);if(h.sitemapnameunique!==s)return i(`sitemap '${d}' now carries sitemapnameunique '${String(h.sitemapnameunique)}', not '${s}', so it is no longer this app's sitemap.`);if(!Ef(h.sitemapid,d))return i(`sitemap '${d}' was read back as a row carrying sitemapid '${String(h.sitemapid)}'.`);let g=h.sitemapxml;return typeof g!="string"?i(`sitemap '${d}' returned no sitemapxml.`):{sitemapId:d,uniquename:s,sitemapXml:g,...u,sitemapEtag:f}}async function Qz(e,t,r){let n=(0,Ae.normalizeGuid)(t,"id"),i=await xT(e,n);await r?.(i.sitemapXml),await BT(e,n,i)}li.deleteAppResolvingOnce=Qz;async function Xz(e,t){let r=await MT(e,t);if(r.kind!=="deleted")throw r.error}function FT(e,t){try{return(0,ge.ensureSuccess)(e,t),{kind:"deleted"}}catch(r){return UT(e.status)?{kind:"refused",error:r}:{kind:"unknown",error:r}}}function Zz(e,t){var r;if(e.status!==400&&(e.status<200||e.status>=300))return!1;let n=(r=(0,PT.parseChangeSetParts)(e.body,t))===null||r===void 0?void 0:r.filter(i=>i.status<200||i.status>=300);return n!==void 0&&n.length>0&&n.every(i=>i.status===400&&(0,ge.namesAppSearchIndexRace)(i.text))}async function MT(e,t){let r=`batch_${(0,E0.newId)()}`,n=`changeset_${(0,E0.newId)()}`,i=t.map((m,p)=>[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${p+1}`,"",`DELETE ${e.apiUrl(m.path)} HTTP/1.1`,...m.etag?[`If-Match: ${m.etag}`]:[],""].join(`\r`)),o=[`--${r}`,`Content-Type: multipart/mixed;boundary=${n}`,"",...i,`--${n}--`,`--${r}--`,""].join(`\r-`),a=e.apiUrl("/$batch"),s=i.map((p,m)=>String(m+1)),l;try{l=await(0,pe.resendWhile)(p=>F8(p,s),()=>e.postBatch(o,r),pe.DEADLOCK_BACKOFF_MS)}catch(p){return{kind:"unknown",error:p}}let u=zN(l,a);if(u.kind!=="deleted")return u;let c=`app '${t[0].path}'`;if(typeof l.body!="string"||l.body.length===0)return{kind:"unknown",error:new Se.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`)};let d=(0,UN.parseChangeSetStatuses)(l.body,s);if(d===void 0)return{kind:"unknown",error:new Se.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`)};let f=d.find(p=>p<200||p>=300);return f!==void 0?{kind:"refused",error:new Se.ConnectionError(a,f,`atomic delete of ${c} was rolled back: the change set reported HTTP ${f}`)}:d.length!==i.length?{kind:"unknown",error:new Se.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response reported ${d.length} operation result(s), expected exactly ${i.length}`)}:{kind:"deleted"}}async function Ld(e,t){try{let r=await e.get(`/sitemaps(${t})?$select=sitemapid`);return r.status<200||r.status>=300?null:(0,pe.readEtag)(r)}catch{return null}}async function xN(e,t){let r=`/appmodules(${t})?$select=appmoduleid`,n=await e.get(r);if(n.status!==404)return(0,pe.ensureSuccess)(n,e.apiUrl(r)),(0,pe.readEtag)(n)}async function Ag(e,t,r,n){if(!n)return null;let i=await Ld(e,t);if(!i)return null;try{let o=await e.get(xd(t,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"));if(o.status<200||o.status>=300)return null;let a=nu(o);return!a||!$d(a.sitemapid,t)||a.sitemapnameunique!==n||a.sitemapxml!==r.sitemapxml||a.sitemapname!==r.sitemapname?null:i}catch{return null}}function HN(e){return e>=400&&e<500&&e!==408&&e!==429}function $N(e,t,r){if(!e)throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${t}': the ${r} read returned no ETag, so the delete cannot be made conditional on the row that was actually inspected. Without that condition a row renamed or re-pointed between the read and the delete would be destroyed. Retry.`);return e}async function KN(e,t,r){let n=`/appmodules(${t})`,i=r.draft?void 0:$N(r.appEtag,t,"app");if(!r.sitemapId){if(r.draft){(0,pe.ensureSuccess)(await(0,pe.resendAppSearchIndexRace)(()=>e.delete(n)),e.apiUrl(n));return}await M8(e,n,i);return}if(!e.supportsAtomicBatch)throw new Se.SdkError("APP_DELETE_NOT_ATOMIC",`Refusing to delete app '${t}': it owns a sitemap, and the injected HttpClient cannot send a raw body, so the two rows would have to be deleted as separate requests. A failure between them strands the sitemap and permanently reserves the app's unique name. Implement HttpClient.postRaw so the SDK can delete them atomically.`);await $8(e,[{path:n,etag:i},{path:`/sitemaps(${r.sitemapId})`,etag:$N(r.sitemapEtag,t,"sitemap")}])}async function M8(e,t,r){(0,pe.ensureSuccess)(await(0,pe.resendAppSearchIndexRace)(()=>e.delete(t,{headers:{"If-Match":r}})),e.apiUrl(t))}async function FN(e,t){if(!/GenPageId/i.test(t))return;let r;try{r=[...new Set((0,g8.collectGenPageIds)(t))]}catch(i){throw new Se.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 (${Ii(i)}).`)}if(r.length===0)return;let n=await(0,y8.findMissingGenPages)(e,r,"sitemap generative-page preflight");if(n.length>0)throw new Se.SdkError("SITEMAP_TARGET_NOT_FOUND",`Refusing to push the app: its sitemap navigates to generative page(s) ${n.map(i=>`'${i}'`).join(", ")} that do not exist in this environment. Push the page before the app that links to it.`)}function U8(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")}async function MN(e,t,r){var n;let i=(0,Ee.normalizeGuid)(t,"id"),o=r==="tokens-first",a=o?await xN(e,i):null,s=_g(Ng,i),l=(0,pe.ensureSuccess)(await e.get(s),e.apiUrl(s)),u=(n=nu(l))!==null&&n!==void 0?n:{};if(!u.appmoduleid)throw new Se.SdkError("APP_NOT_FOUND",`App '${i}' was not found (checked the unpublished-aware projection, which includes drafts).`);let c=await BN(e,u.uniquename),d=c?(0,Ee.normalizeGuid)(c,"sitemapId"):void 0,f=null;if(d){o&&(f=await Ld(e,d));let m=xd(d,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"),h=(0,pe.ensureSuccess)(await e.get(m),e.apiUrl(m)),g=nu(h),b=w=>{throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': its sitemap '${d}' was located by unique name, but ${w}, so the sitemap cannot be read. Persisting the app without it would misreport it as having no sitemap, or write an empty one over its navigation. Retry.`)};if(!g)return b("the by-id read returned no row");if(g.sitemapnameunique!==u.uniquename)throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': sitemap '${d}' now carries sitemapnameunique '${String(g.sitemapnameunique)}', not '${String(u.uniquename)}', so it is no longer this app's sitemap. Retry.`);if(!$d(g.sitemapid,d))return b(`the by-id read returned a row carrying sitemapid '${String(g.sitemapid)}'`);if(typeof g.sitemapxml!="string")return b("the by-id read returned no sitemapxml");u.$sitemap=g,o||(f=await Ld(e,d))}o||(a=await xN(e,i));let p=a??C8(u);return{raw:u,etag:f,...u.appmoduleid?{siblingEtags:{[(0,Ee.normalizeGuid)(u.appmoduleid,"appmoduleid")]:p}}:{}}}Jn.appApi={get(e,t){return MN(e,t,"tokens-first")},readContentThenToken(e,t){return MN(e,t,"content-first")},async list(e,t){let r=_g(Ng);return(await(0,ms.collectPages)(e,r,"listArtifacts('app')")).map(i=>{var o,a;return{type:"app",id:(o=i.appmoduleid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",isDirty:!1}})},async create(e,t,r){let n=t;await FN(e,n.sitemapxml);let i=await RN(e,n,n.appModuleId),o=n.iconWebResourceId?void 0:await A8(e),a=n.iconWebResourceId||o?.id;if(!a)throw new Se.SdkError("APP_ICON_UNRESOLVED",`Cannot create app '${n.appModuleName}': its icon (\`appmodule.webresourceid\`) is a REQUIRED attribute and this environment has no image web resource to use. Pass \`iconWebResourceId\` explicitly, or add an image (PNG/JPG/GIF/ICO/SVG) web resource to the environment.`);let s=null;o?.managed&&(s=`No unmanaged image web resource was available, so the app icon resolved to a MANAGED one (${o.id}). That creates a cross-solution dependency which can fail to import into an environment without the owning managed solution. Pass \`iconWebResourceId\` with an in-solution image to avoid it.`);let l=n.appModuleUniqueName||E8(n.appModuleId),u={name:n.appModuleName,uniquename:l,clienttype:4,formfactor:1,navigationtype:0};n.appModuleDescription&&(u.description=n.appModuleDescription),n.appModuleAiDescription&&(u.aiappdescription=n.appModuleAiDescription),a&&(u.webresourceid=a);let c="/appmodules",d=(0,pe.ensureSuccess)(await(0,pe.resendDeadlockVictim)(()=>e.post(c,(0,pe.withClientMintedId)(u,"appmoduleid",r))),e.apiUrl(c)),f=(0,pe.resolveCreatedId)(d,"appmoduleid","app module",r),p=null,m=null,h=[];s&&h.push(s);let g={kind:"notRequested"},b=n.sitemapId?(0,Ee.normalizeGuid)(n.sitemapId,"sitemapId"):(0,Sg.newId)(),w=!1,E={sitemapxml:n.sitemapxml,sitemapname:n.sitemapname};try{let L="/sitemaps",R=(0,pe.echoWrite)("sitemapid"),I=await e.post(`${L}${R.query}`,{sitemapid:b,sitemapnameunique:l,...E},R.options);w=HN(I.status);let D=(0,pe.ensureSuccess)(I,e.apiUrl(L));m=(0,pe.readEtag)(D),p=m??await Ag(e,b,E,l);let O=await ON(e,n,i);h.push(...O.warnings);let $=O.components;$.unshift({"@odata.type":"Microsoft.Dynamics.CRM.sitemap",sitemapid:b}),await LN(e,f,$);let K=Rd(e,f);await kN(e,f,O.tables,K),i&&await I8(e,f,i,K);let Re=await S8(e,f);Re&&h.push(Re),n.appSettings&&Object.keys(n.appSettings).length>0&&h.push(...await(0,b8.applyAppSettings)(e,f,n.appSettings)),n.published!==!1&&(await(0,_N.publishAppModule)(e,f),g={kind:"submitted"})}catch(L){let R=await P8(e,f,{sitemapId:b,sitemapNameUnique:l,serverRefusedSitemap:w,sitemapWriteToken:m});throw(0,v8.failedAfterPrimaryWrite)(R8(L,R,{appId:f,sitemapId:b,uniqueName:l}))}let A=null;if(g.kind==="submitted")try{let L=await e.get(`/appmodules(${f})?$select=appmoduleid`);L.status>=200&&L.status<300&&(A=(0,pe.readEtag)(L))}catch{}return{id:f,etag:p,serverIdentity:{sitemapId:b},siblingEtags:{[f]:A},publish:g,...h.length>0?{warnings:h}:{}}},async update(e,t,r,n,i,o){var a,s,l,u,c,d,f,p,m;let h=r,g=(0,Ee.normalizeGuid)(t,"id");if(await FN(e,h.sitemapxml),!h.sitemapId)throw new Se.ValidationError("app",g,[{pointer:"/sitemapId",rule:"app-sitemap-identity-missing",message:`missing sitemap identity \u2014 re-fetch the app before pushing edits: fetchArtifact('app', '${g}', { overwrite: true }) (it REPLACES the local copy \u2014 keep outstanding changes aside), push that refreshed copy UNTOUCHED, then re-apply your changes and push again. If the untouched push is refused with this same rule, the app has NO sitemap on the server \u2014 an earlier create committed its appmodule but not its sitemap \u2014 and it can be neither updated, published nor removed with deleteRemoteArtifact (an unpublished app reads back 404). Only for an app you have confirmed is your own abandoned partial create, with nothing else provisioning it: remove its appmodule row with deleteRecord('appmodule', '${g}'), clear the local copy with deleteArtifact('app', '${g}'), then author the app again and push.`}]);let b=(0,Ee.normalizeGuid)(h.sitemapId,"sitemapId");if(!(0,pe.isVersionToken)(n))throw new Se.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${g}': ${n?`the concurrency token held for its sitemap row ('${n}') is not a version`:"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 RN(e,h,g),E=await ON(e,h,w),A=`/appmodules(${g})`,L=(a=o?.[g])!==null&&a!==void 0?a:null,R=!0,I;try{let Ot=_g(Ng,g),di=await e.get(Ot);if(di.status>=200&&di.status<300){let Ra=(s=nu(di))!==null&&s!==void 0?s:{};I=typeof Ra.uniquename=="string"&&Ra.uniquename?Ra.uniquename:void 0,R=String((l=Ra.name)!==null&&l!==void 0?l:"")!==String((u=h.appModuleName)!==null&&u!==void 0?u:"")||String((c=Ra.description)!==null&&c!==void 0?c:"")!==String((d=h.appModuleDescription)!==null&&d!==void 0?d:"")||h.appModuleAiDescription!==void 0&&String((f=Ra.aiappdescription)!==null&&f!==void 0?f:"")!==String(h.appModuleAiDescription)}}catch{}let D=L;if(R){if(!(0,pe.isVersionToken)(L))throw new Se.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${g}': ${L?`the concurrency token held for its appmodule header ('${L}') is not a version`:"no concurrency token is held for its appmodule header"}, so its header edit could not be made conditional and would silently overwrite a concurrent edit. Nothing was modified. Re-fetch the app (fetchArtifact('app', '${g}', { overwrite: true })) and re-apply the change.`);let Ot=(0,pe.echoWrite)("appmoduleid",{"If-Match":L}),di=await e.patch(`${A}${Ot.query}`,{name:h.appModuleName,description:h.appModuleDescription,...h.appModuleAiDescription!==void 0?{aiappdescription:h.appModuleAiDescription}:{}},Ot.options);if(U8(di))throw new Se.SdkError("APP_DRAFT_HEADER_NOT_WRITABLE",`Refusing to update app '${g}': its appmodule row is UNPUBLISHED, and Dataverse cannot resolve version numbers for a draft appmodule (HTTP 400). A draft header cannot be PATCHed at all \u2014 a plain retry fails too, as an upsert-create ("webresourceid cannot be NULL"). Publish the app first, then push the header edit. Nothing was modified by this call.`);(0,pe.ensureSuccess)(di,e.apiUrl(A)),D=(0,pe.readEtag)(di)}let O={sitemapxml:h.sitemapxml,sitemapname:h.sitemapname},$=I||h.appModuleUniqueName||void 0,K=(0,pe.echoWrite)("sitemapid",{"If-Match":n}),Re=`/sitemaps(${b})`,It;try{It=(0,pe.ensureSuccess)(await e.patch(`${Re}${K.query}`,{...O},K.options),e.apiUrl(Re))}catch(Ot){throw(0,Se.withPartialTokens)(Ot,{siblingEtags:{[g]:D}})}let Le=[...E.warnings],at=Rd(e,g);try{await LN(e,g,E.components),await kN(e,g,E.tables,at)}catch(Ot){Le.push(`App '${g}': one or more components were not pinned (${Ot.message}). Navigation may reference content not included in the app; re-push to retry.`)}w&&Le.push(...await O8(e,g,w,at));let ge={kind:"notRequested"},ht=D,Ro=(p=(0,pe.readEtag)(It))!==null&&p!==void 0?p:await Ag(e,b,O,$);if(h.published===!0){try{await(0,_N.publishAppModule)(e,g),ge={kind:"submitted"}}catch(Ot){ge={kind:"failed",error:Ot},Le.push(`App '${g}': saved, but publishing failed (${Ot.message}). The app remains unpublished; re-push to retry.`)}if(ge.kind==="submitted"){ht=null;try{let Ot=await e.get(`/appmodules(${g})?$select=appmoduleid`);Ot.status>=200&&Ot.status<300&&(ht=(0,pe.readEtag)(Ot)),Ro=(m=await Ag(e,b,O,$))!==null&&m!==void 0?m:Ro}catch{}}}return{id:g,etag:Ro,siblingEtags:{[g]:ht},publish:ge,...Le.length>0?{warnings:Le}:{}}},async delete(e,t){let r=(0,Ee.normalizeGuid)(t,"id");await KN(e,r,await WN(e,r))}}});var Ig=v(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.deleteAppCascade=hs.collectGenPageIds=void 0;var B8=Fd(),q8=Q(),Og=ue(),V8=rs();function JN(e){let t=[],r=s=>l=>t.push(`${s}: ${l}`),i=new V8.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml").documentElement;if(!i||t.length>0)throw new q8.InvalidArgumentError(`The app sitemap xml could not be parsed cleanly, so its generative-page children cannot be determined${t.length>0?` (${t[0]})`:""}`);let o=[],a=s=>{if(s.nodeName==="SubArea"){let u=s.getAttribute("GenPageId");u&&o.push((0,Og.normalizeGuid)(u,"GenPageId"))}let l=s.childNodes;for(let u=0;u<l.length;u+=1){let c=l[u];c.nodeType===1&&a(c)}};return a(i),o}hs.collectGenPageIds=JN;async function G8(e,t,r){let n=(0,Og.normalizeGuid)(t,"appModuleId");(0,Og.normalizeGuid)(r,"appModuleIdUnique");let i=[],o=[],a=[];await(0,B8.deleteAppResolvingOnce)(e,n,l=>{l!==void 0&&a.push(...JN(l))}),i.push({type:"app",id:n});let s=[...new Set(a)].map(l=>({type:"genPage",id:l}));return{success:o.length===0,deleted:i,failures:o,retained:s}}hs.deleteAppCascade=G8});var YN={};jr(YN,{Guid:()=>U});var U,ct=k(()=>{"use strict";U=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 q,zt=k(()=>{"use strict";et();q=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(!P.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 P.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 QN={};jr(QN,{ScriptUtilities:()=>P});var P,et=k(()=>{"use strict";ct();zt();P=class e{static IsNullOrUndefined(t){return t==null||t===void 0}static IsMacMachine(){return navigator.platform.indexOf("Mac")!==-1}static IsNullOrEmptyGuid(t){return q.IsNullOrEmpty(t.ToString())?!0:U.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:q.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 Md,Ud,ta,Bd,Pg,qd,Rg=k(()=>{"use strict";(function(e){e[e.FormElementNodeChange=0]="FormElementNodeChange",e[e.FormElementAttributeChange=1]="FormElementAttributeChange"})(Md||(Md={}));Ud=class{type;targetNode;constructor(t,r){this.type=t,this.targetNode=r}},ta=class extends Ud{key;oldValue;newValue;constructor(t,r,n,i){super(Md.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)}},Bd=class extends Ud{property;oldValue;newValue;constructor(t,r,n,i){super(Md.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)}},Pg=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()})}},qd=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 Pg(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 XN={};jr(XN,{ChartGridMode:()=>nn,ColumnLayoutWidths:()=>K8,ComponentCategory:()=>Gd,ComponentType:()=>Lg,ControlLayoutTypes:()=>Bg,DisplayConditionsInfo:()=>j8,ElementNames:()=>C,ElementProperties:()=>y,ElementType:()=>xg,EntityAttributeProperty:()=>$g,EventType:()=>iu,FormActivationState:()=>Ug,FormCanvasServiceScope:()=>aW,FormDesignerSideBarTab:()=>kg,FormPresentation:()=>Fg,FormState:()=>Vd,FormType:()=>dt,HeaderDensityType:()=>po,LookUpTable:()=>Yn,MORE_TAB_PREFIX:()=>Y8,NavBarChildElementType:()=>Mg,PREVIEW_ID_HEADER_FLYOUT:()=>eW,PREVIEW_ID_HEADER_OVERFLOW_BUTTON:()=>rW,PREVIEW_ID_NAVIGATION_AREA:()=>X8,PREVIEW_ID_QUICKCREATE_ROOT:()=>iW,PREVIEW_ID_TAB:()=>nW,PREVIEW_ID_TAB_LIST:()=>tW,PREVIEW_ID_TAB_PANEL:()=>Z8,PropertyModelKeys:()=>Gg,PropertyModelSectionKeys:()=>J8,RELATED_TAB_ID:()=>Wg,RELATED_TAB_PREFIX:()=>Q8,SectionDefaultProperties:()=>H8,SectionLayoutTypes:()=>Ge,TabContentType:()=>qg,TabDefaultProperties:()=>mo,TabLayoutTypes:()=>Ve,TelemetryPropertyNames:()=>oW,UnboundControlPropertyKeys:()=>Vg,compositeAddressFields:()=>z8,compositeFieldNames:()=>Br,compositeFields:()=>W8});var dt,Lg,kg,C,y,xg,Br,W8,z8,$g,Yn,Vd,po,Fg,j8,Mg,Ug,Ve,H8,mo,Ge,Bg,qg,K8,Vg,Gg,J8,iu,nn,Wg,Y8,Q8,X8,Z8,eW,tW,rW,nW,iW,oW,Gd,aW,se=k(()=>{"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"})(dt||(dt={}));(function(e){e[e.Form=0]="Form",e[e.Dialog=1]="Dialog"})(Lg||(Lg={}));(function(e){e[e.Components=0]="Components",e[e.Properties=1]="Properties",e[e.Relationship=2]="Relationship",e[e.BusinessRules=3]="BusinessRules"})(kg||(kg={}));(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"})(C||(C={}));y={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"})(xg||(xg={}));Br={fullname:"fullname",yomifullname:"yomifullname",address1_composite:"address1_composite",address2_composite:"address2_composite",address3_composite:"address3_composite",billto:"billto_composite",shipto:"shipto_composite"},W8=[Br.fullname,Br.yomifullname,Br.address1_composite,Br.address2_composite,Br.address3_composite,Br.billto,Br.shipto],z8=[Br.address1_composite,Br.address2_composite,Br.address3_composite,Br.billto,Br.shipto];(function(e){e[e.IsValidForForm=0]="IsValidForForm",e[e.IsValidForCreate=1]="IsValidForCreate"})($g||($g={}));(function(e){e[e.DependencyFieldTable=0]="DependencyFieldTable",e[e.LockedFieldTable=1]="LockedFieldTable"})(Yn||(Yn={}));(function(e){e[e.Published=0]="Published",e[e.Draft=1]="Draft",e[e.New=2]="New",e[e.SaveAs=3]="SaveAs"})(Vd||(Vd={}));(function(e){e.Low="Low",e.HighReadOnlyValues="HighReadOnlyValues",e.HighWithControls="HighWithControls"})(po||(po={}));(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(Fg||(Fg={}));j8={TopOrderFormId:"topOrderFormId",NextDisplayOrder:"nextDisplayOrder"};(function(e){e[e.NavBarRelationShipItem=0]="NavBarRelationShipItem",e[e.NavBarItem=1]="NavBarItem"})(Mg||(Mg={}));(function(e){e[e.InActive=0]="InActive",e[e.Active=1]="Active"})(Ug||(Ug={}));(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"})(Ve||(Ve={}));H8={ShowLabel:"false",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_"},mo={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"})(Ge||(Ge={}));(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"})(Bg||(Bg={}));(function(e){e.cardSections="cardSections",e.singleComponent="singleComponent",e.default="default",e.expandAvailableSpace="expandAvailableSpace"})(qg||(qg={}));K8={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"})(Vg||(Vg={}));(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"})(Gg||(Gg={}));J8={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"})(iu||(iu={}));(function(e){e.All="All",e.Chart="Chart",e.Grid="Grid"})(nn||(nn={}));Wg="tab_related3b554255-7717-4d17-bb7f-9936fb1e75ca",Y8="more_tab_",Q8="related_tab_",X8="preview_id_navigation_area",Z8="tab-section",eW="headerFieldsFlyout",tW="tablist",rW="header_overflowButton",nW="tab",iW="quickCreateRoot",oW={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"})(Gd||(Gd={}));aW="CellCanvasServiceScope"});var ZN={};jr(ZN,{Attribute:()=>Wd,FormElementNode:()=>te});var Wd,te,St=k(()=>{"use strict";et();zt();Rg();se();ct();Wd=class{key;value;constructor(t,r){this.key=t,this.value=r}},te=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-${U.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(C.form);r&&r.raiseMetadataChange(t)}trackPropertyAddition(t,r){this.trackPropertyCollectionChange(()=>{this.properties.push(new Wd(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 ta(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 ta(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 ta(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 Bd(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 ta(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){P.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(P.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:q.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=P.IsNullOrUndefined(r)?this.childrenNodes.length:r,this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(t,r)})}deleteGrandChildren(t,r,n){this.getChildren(t)[0].deleteChildren(r,n)}addGrandChild(t,r){let n=this.getChildren(t),i=null;n.length===0?(i=new e(t,this),this.addChild(i)):i=n[0],i.addChild(r)}addGrandChildAtIndex(t,r,n){let i=this.getChildren(t),o=null;i.length===0?(o=new e(t,this),this.addChild(o)):o=i[0],o.insertChildAtIndex(r,n)}GetPropertyByParameter(t){return this.getProperty(t)}getSemanticParent(){switch(this.getNodeName()){case C.formCell:let t=this.getAncestor(C.formSection);return t||(t=this.getAncestor(C.formHeader),t)||(t=this.getAncestor(C.formFooter),t)?t:null;case C.formSection:return this.getAncestor(C.formTab);case C.formTab:return this.getAncestor(C.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(C.form);return t?t.changeTracker():null}}});var e_={};jr(e_,{ControlClassId:()=>N,ControlNamePrefixes:()=>zd,getControlDisplayNames:()=>sW});function sW(e){return{[N.AccessPrivilegeControl]:e("controls.controlNames.accessPrivilege"),[N.AccessTeamTablePickerControl]:e("controls.controlNames.accessTeamTablePicker"),[N.ACIControl]:e("controls.controlNames.aci"),[N.ActivitiesContainerControl]:e("controls.controlNames.activitiesContainer"),[N.ActivitiesWallControl]:e("controls.controlNames.activitiesWall"),[N.AppliedFiltersControl]:e("controls.controlNames.appliedFilters"),[N.ArticleContentControl]:e("controls.controlNames.articleContent"),[N.BooleanControl]:e("controls.controlNames.twoOption"),[N.ButtonControl]:e("controls.controlNames.button"),[N.CheckboxControl]:e("controls.controlNames.checkbox"),[N.CompositionLinkControl]:e("controls.controlNames.compositionLink"),[N.ConnectionControl]:e("controls.controlNames.connection"),[N.ConnectionRoleObjectTypeListControl]:e("controls.controlNames.connectionRoleObjectTypeList"),[N.CoverageChoiceControl]:e("controls.controlNames.coverageChoice"),[N.DashboardControl]:e("controls.controlNames.dashboard"),[N.DynamicPropertyListControl]:e("controls.controlNames.dynamicPropertyList"),[N.EditFilterControl]:e("controls.controlNames.editFilter"),[N.ErrorStatusControl]:e("controls.controlNames.errorStatus"),[N.GlobalFilterControl]:e("controls.controlNames.globalFilter"),[N.HiddenInputControl]:e("controls.controlNames.hiddenInput"),[N.KBViewerControl]:e("controls.controlNames.kbViewer"),[N.LabelControl]:e("controls.controlNames.label"),[N.MailMergeLanguagePickerControl]:e("controls.controlNames.mailMergeLanguagePicker"),[N.MapLinkControl]:e("controls.controlNames.mapLink"),[N.OrgInsightsControl]:e("controls.controlNames.orgInsights"),[N.ChoiceLookupControl]:e("controls.controlNames.choiceLookup"),[N.PowerBIControl]:e("controls.controlNames.powerBI"),[N.ProcessControl]:e("controls.controlNames.process"),[N.RelatedInformationControl]:e("controls.controlNames.relatedInformation"),[N.RelationshipRoleChoiceControl]:e("controls.controlNames.relationshipRoleChoice"),[N.ReportControl]:e("controls.controlNames.report"),[N.StreamsControl]:e("controls.controlNames.streams"),[N.WebResourceSilverlightControl]:e("controls.controlNames.webResourceSilverlight"),[N.CurrencyControl]:e("controls.controlNames.currency"),[N.DateTimeControl]:e("controls.controlNames.dateAndTime"),[N.DecimalControl]:e("controls.controlNames.decimal"),[N.DurationControl]:e("controls.controlNames.duration"),[N.EmailAddressControl]:e("controls.controlNames.email"),[N.FileControl]:e("controls.controlNames.file"),[N.FloatingNumberControl]:e("controls.controlNames.floatingNumber"),[N.IframeControl]:e("controls.controlNames.iframe"),[N.ImageControl]:e("controls.controlNames.image"),[N.LookupControl]:e("controls.controlNames.lookup"),[N.MapsControl]:e("controls.controlNames.maps"),[N.PhoneNumberControl]:e("controls.controlNames.phoneNumber"),[N.ChoiceControl]:e("controls.controlNames.choice"),[N.QuickViewControl]:e("controls.controlNames.quickView"),[N.QuickFormControl]:e("controls.controlNames.quickForm"),[N.CustomControl]:e("controls.controlNames.customControl"),[N.SearchWidgetControl]:e("controls.controlNames.searchWidget"),[N.SocialInsightsControl]:e("controls.controlNames.socialInsights"),[N.SubgridControl]:e("controls.controlNames.subgrid"),[N.TextAreaControl]:e("controls.controlNames.textArea"),[N.TextboxControl]:e("controls.controlNames.textBox"),[N.TickerControl]:e("controls.controlNames.ticker"),[N.UrlControl]:e("controls.controlNames.url"),[N.WebResourceHTMLControl]:e("controls.controlNames.webResourceHTML"),[N.WebResourceImageControl]:e("controls.controlNames.webResourceImage"),[N.IntegerControl]:e("controls.controlNames.integer"),[N.TimerControl]:e("controls.controlNames.timer"),[N.TimelineControl]:e("controls.controlNames.timeline"),[N.EmailBodyControl]:e("controls.controlNames.emailBody"),[N.PartyListControl]:e("controls.controlNames.partyList"),[N.TimezoneControl]:e("controls.controlNames.timezone"),[N.LanguageControl]:e("controls.controlNames.language"),[N.ChoiceStatusControl]:e("controls.controlNames.choiceStatus"),[N.ChoicesControl]:e("controls.controlNames.choices"),[N.RegardingControl]:e("controls.controlNames.regarding"),[N.EmailEngagementActionsControl]:e("controls.controlNames.emailEngagementActions"),[N.EmailRecipientActivityControl]:e("controls.controlNames.emailRecipientActivity"),[N.ReferencePanelSearchWidgetControl]:e("controls.controlNames.referencePanelSearchWidget"),[N.ReferencePanelQuickViewControl]:e("controls.controlNames.referencePanelQuickView"),[N.ReferencePanelSubgridControl]:e("controls.controlNames.referencePanelSubgrid"),[N.KBEditorControl]:e("controls.controlNames.KBEditor"),[N.LinkControl]:e("controls.controlNames.link")}}var N,zd,ra=k(()=>{"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"})(N||(N={}));zd={[N.WebResourceHTMLControl]:"WebResource",[N.WebResourceImageControl]:"WebResource",[N.IframeControl]:"IFRAME",[N.SearchWidgetControl]:"Search widget",[N.SubgridControl]:"Subgrid",[N.TimelineControl]:"Timeline",[N.QuickViewControl]:"QuickviewControl"}});var na=v((tle,r_)=>{var ou=new Proxy(function(){return ou},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:ou},apply:function(){return ou},construct:function(){return{}}}),t_=function(){return ou};Object.setPrototypeOf(t_,ou);r_.exports=t_});var ir,Oi,n_,i_,gs=k(()=>{"use strict";ir="cds-designer-models",Oi="FormCustomControl",n_="FormCell",i_="Form"});var ia,zg=k(()=>{"use strict";Bl();se();ia=class e{static lockedFieldCount=new er;static dependencyFieldCount=new er;static getNecessaryLookUpTable(t){switch(t){case Yn.DependencyFieldTable:return e.dependencyFieldCount;case Yn.LockedFieldTable:return e.lockedFieldCount}}static initCanvasLockedFieldLookUp(t){switch(t){case Yn.DependencyFieldTable:e.dependencyFieldCount=new er;case Yn.LockedFieldTable:e.lockedFieldCount=new er}}}});var jd,o_=k(()=>{"use strict";ct();et();se();St();jd=class extends te{constructor(t){super(C.controlDescription,t)}get forControl(){let t=this.getProperty(y.ForControl);return P.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t))}set forControl(t){this.setProperty(y.ForControl,`{${t.ToString()}}`)}get customControls(){return this.getChildren(C.customControl)}set customControls(t){this.deleteAllChildren();for(let r of t)this.addChild(r)}get DefaultControlClassId(){for(let t of this.customControls)if(!P.IsNullOrUndefined(t.id))return t.id;return null}get DefaultCustomControl(){for(let t of this.customControls)if(!P.IsNullOrUndefined(t.id))return t;return null}get DefaultCustomControls(){let t=[];for(let r of this.customControls)P.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}}});function Pi(){return Qn||(Qn=window._makerConfig,Qn&&window?.location?.search?.indexOf("useProductionConfig")>-1&&(Qn={...Qn,region:"prod",graphQLEndpoint:"https://graph.make.powerapps.com/"}),Qn?.region==="prod"&&(Qn={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/"}}},...Qn}),Qn||{aadClientId:"a8f7a65c-f5ba-4859-b2d6-df772c264e9d",location:"cus",region:"test",publicPath:"/",graphQLEndpoint:"https://graph.make.test.powerapps.com/"})}var Qn,Hd=k(()=>{"use strict";});function a_(e,t,r){if(!e)return Kd.has(e)||(window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoIsEmpty"}),Kd.add("")),!1;if(e){if(e=e.toLowerCase(),Kd.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}}),Kd.add(e),!1}return!0}function lW(e){return a_(e,jg,"Location dictionary")?jg[e.toLowerCase()]:"us"}function uW(){let e=Pi().location.toLowerCase();return a_(e,jg,"Current location dictionary")?e:"us"}var Kd,jg,mle,s_=k(()=>{"use strict";Hd();Kd=new Set,jg={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"};mle=lW(uW())});var Y,gle,l_=k(()=>{"use strict";Y={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"},gle={[Y.USWest]:{geoName:"us",regionShortName:"wus"},[Y.USCentral]:{geoName:"us",regionShortName:"cus"},[Y.USEast]:{geoName:"us",regionShortName:"eus"},[Y.USEast2]:{geoName:"us",regionShortName:"eus2"},[Y.USWestCentral]:{geoName:"us",regionShortName:"wcus"},[Y.USWest2]:{geoName:"us",regionShortName:"wus2"},[Y.USSouthCentral]:{geoName:"br",regionShortName:"scus"},[Y.BrazilSouth]:{geoName:"br",regionShortName:"sbr"},[Y.UKSouth]:{geoName:"uk",regionShortName:"suk"},[Y.UKWest]:{geoName:"uk",regionShortName:"wuk"},[Y.JapanEast]:{geoName:"jp",regionShortName:"ejp"},[Y.JapanWest]:{geoName:"jp",regionShortName:"wjp"},[Y.IndiaCentral]:{geoName:"in",regionShortName:"cin"},[Y.IndiaSouth]:{geoName:"in",regionShortName:"sin"},[Y.ItalyNorth]:{geoName:"it",regionShortName:"nit"},[Y.GermanyWestCentral]:{geoName:"de",regionShortName:"wcde"},[Y.GermanyNorth]:{geoName:"de",regionShortName:"nde"},[Y.EuropeNorth]:{geoName:"eu",regionShortName:"neu"},[Y.EuropeWest]:{geoName:"eu",regionShortName:"weu"},[Y.AustraliaEast]:{geoName:"au",regionShortName:"eau"},[Y.AustraliaSouthEast]:{geoName:"au",regionShortName:"seau"},[Y.AsiaSouthEast]:{geoName:"as",regionShortName:"seas"},[Y.AsiaEast]:{geoName:"as",regionShortName:"eas"},[Y.CanadaCentral]:{geoName:"ca",regionShortName:"cca"},[Y.CanadaEast]:{geoName:"ca",regionShortName:"eca"},[Y.SouthAfricaNorth]:{geoName:"za",regionShortName:"nza"},[Y.SouthAfricaWest]:{geoName:"za",regionShortName:"wza"},[Y.FranceCentral]:{geoName:"fr",regionShortName:"cfr"},[Y.FranceSouth]:{geoName:"fr",regionShortName:"sfr"},[Y.UAENorth]:{geoName:"ae",regionShortName:"nae"},[Y.UAECentral]:{geoName:"ae",regionShortName:"cae"},[Y.SwedenCentral]:{geoName:"se",regionShortName:"cse"},[Y.SwitzerlandNorth]:{geoName:"ch",regionShortName:"nch"},[Y.SwitzerlandWest]:{geoName:"ch",regionShortName:"wch"},[Y.NorwayEast]:{geoName:"no",regionShortName:"eno"},[Y.NorwayWest]:{geoName:"no",regionShortName:"wno"},[Y.KoreaCentral]:{geoName:"kr",regionShortName:"ckr"},[Y.KoreaSouth]:{geoName:"kr",regionShortName:"skr"},[Y.SingaporeSouthEast]:{geoName:"sg",regionShortName:"seas"},[Y.PolandCentral]:{geoName:"pl",regionShortName:"cpl"},[Y.QatarCentral]:{geoName:"qa",regionShortName:"cqa"},[Y.NewZealandNorth]:{geoName:"nz",regionShortName:"nnz"},[Y.GovernmentUSTexas]:{geoName:"us",regionShortName:"ugtx"},[Y.GovernmentUSVirginia]:{geoName:"us",regionShortName:"ugva"},[Y.GovernmentUSDodCentral]:{regionShortName:"udc"},[Y.GovernmentUSDodEast]:{regionShortName:"ude"},[Y.ChinaEast]:{regionShortName:"cne"},[Y.ChinaEast2]:{regionShortName:"cne2"},[Y.ChinaEast3]:{regionShortName:"cne3"},[Y.ChinaNorth]:{regionShortName:"cnn"},[Y.ChinaNorth2]:{regionShortName:"cnn2"},[Y.ChinaNorth3]:{regionShortName:"cnn3"},[Y.UssecEast]:{geoName:"us",regionShortName:"erx"},[Y.UssecWest]:{geoName:"us",regionShortName:"wrx"},[Y.UsnatEast]:{geoName:"us",regionShortName:"eex"},[Y.UsnatWest]:{geoName:"us",regionShortName:"wex"}}});var u_=k(()=>{"use strict";Hd();});var au=k(()=>{"use strict";Hd();s_();l_();u_();});function su(e,t){return c_?c_.isOverridden(e,t):{overridden:!1}}var c_,lu=k(()=>{"use strict";});var Hg=k(()=>{"use strict";au();lu();});function cW(e,t){let{region:r}=Pi();return()=>{let n=e.settings[t];if(n.allowOverrides){let s=su(e.packageName,t);if(s.overridden)return typeof s.value=="string"?dW(s.value):s.value}let o=n.values,a=process.env.SETTINGS_FALLBACK_REGION?.[r];return o[r]!==void 0?o[r]:a&&o[a]!==void 0?o[a]:o.default}}function dW(e){return isNaN(Number(e))?e==="true"?!0:e==="false"?!1:e:Number(e)}function fW(e){let t=e.packageName;if(Jd.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=>Jg(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=>!Qd(i))){let i=`error parsing settings config for package ${t}, setting ${r} has invalid region`;throw console.error(i),new Error(i)}})}function uu(e){fW(e);let t={};return Object.keys(e.settings).forEach(r=>{t[r]={enumerable:!0,get:cW(e,r)}}),Jd.set(e.packageName,e),Object.defineProperties({},t)}function Kg(e,t){return Jd.has(e)?!!Jd.get(e).settings[t]:!1}var Jd,Yd=k(()=>{"use strict";au();lu();Yg();cu();Jd=new Map});function d_(e,t){let{region:r}=Pi();return()=>{let n=su(e.packageName,t);if(n.overridden)return n.value.toString()==="true";let i=e.features[t].enabledFor,o=process.env.SETTINGS_FALLBACK_REGION?.[r];return i[r]!==void 0?!!i[r]:o&&i[o]!==void 0?!!i[o]:!1}}function pW(e){let t=e.packageName;if(Xd.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=>Kg(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=>!Qd(i))){let i=`error parsing feature gates config for package ${t}, feature ${r} has invalid region`;throw console.error(i),new Error(i)}})}function Qg(e){pW(e);let t={};Object.keys(e.features).forEach(i=>{t[i]={enumerable:!0,configurable:!0,get:d_(e,i)}});let r={},n=new Set;return t.dangerouslySet={enumerable:!1,value:(i,o)=>{n.add(i),Object.defineProperty(r,i,{enumerable:!0,configurable:!0,value:o})}},t.dangerouslyReset={enumerable:!1,value:()=>{let i={};n.forEach(o=>{i[o.toString()]={enumerable:!0,configurable:!0,get:d_(e,o.toString())}}),Object.defineProperties(r,i),n.clear()}},Xd.set(e.packageName,e),Object.defineProperties(r,t)}function Jg(e,t){return Xd.has(e)?!!Xd.get(e).features[t]:!1}var Xd,Yg=k(()=>{"use strict";au();cu();lu();Yd();Xd=new Map});var p_=v((qle,f_)=>{"use strict";f_.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 g_=v(Xg=>{"use strict";var mW=Object.prototype.hasOwnProperty,hW;function m_(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch{return null}}function h_(e){try{return encodeURIComponent(e)}catch{return null}}function gW(e){for(var t=/([^=?#&]+)=?([^&]*)/g,r={},n;n=t.exec(e);){var i=m_(n[1]),o=m_(n[2]);i===null||o===null||i in r||(r[i]=o)}return r}function yW(e,t){t=t||"";var r=[],n,i;typeof t!="string"&&(t="?");for(i in e)if(mW.call(e,i)){if(n=e[i],!n&&(n===null||n===hW||isNaN(n))&&(n=""),i=h_(i),n=h_(n),i===null||n===null)continue;r.push(i+"="+n)}return r.length?t+r.join("&"):""}Xg.stringify=yW;Xg.parse=gW});var t0=v((Gle,E_)=>{"use strict";var b_=p_(),Zd=g_(),v_=/[\n\r\t]/g,bW=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,vW=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,wW=/^[a-zA-Z]:/,CW=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;function e0(e){return(e||"").toString().replace(CW,"")}var Zg=[["#","hash"],["?","query"],function(t,r){return Xn(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]],y_={hash:1,query:1};function w_(e){var t;typeof window<"u"?t=window:typeof global<"u"?t=global:typeof self<"u"?t=self:t={};var r=t.location||{};e=e||r;var n={},i=typeof e,o;if(e.protocol==="blob:")n=new Zn(unescape(e.pathname),{});else if(i==="string"){n=new Zn(e,{});for(o in y_)delete n[o]}else if(i==="object"){for(o in e)o in y_||(n[o]=e[o]);n.slashes===void 0&&(n.slashes=bW.test(e.href))}return n}function Xn(e){return e==="file:"||e==="ftp:"||e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function C_(e,t){e=e0(e),e=e.replace(v_,""),t=t||{};var r=vW.exec(e),n=r[1]?r[1].toLowerCase():"",i=!!r[2],o=!!r[3],a=0,s;return i?o?(s=r[2]+r[3]+r[4],a=r[2].length+r[3].length):(s=r[2]+r[4],a=r[2].length):o?(s=r[3]+r[4],a=r[3].length):s=r[4],n==="file:"?a>=2&&(s=s.slice(2)):Xn(n)?s=r[4]:n?i&&(s=s.slice(2)):a>=2&&Xn(t.protocol)&&(s=r[4]),{protocol:n,slashes:i||Xn(n),slashesCount:a,rest:s}}function EW(e,t){if(e==="")return t;for(var r=(t||"/").split("/").slice(0,-1).concat(e.split("/")),n=r.length,i=r[n-1],o=!1,a=0;n--;)r[n]==="."?r.splice(n,1):r[n]===".."?(r.splice(n,1),a++):a&&(n===0&&(o=!0),r.splice(n,1),a--);return o&&r.unshift(""),(i==="."||i==="..")&&r.push(""),r.join("/")}function Zn(e,t,r){if(e=e0(e),e=e.replace(v_,""),!(this instanceof Zn))return new Zn(e,t,r);var n,i,o,a,s,l,u=Zg.slice(),c=typeof t,d=this,f=0;for(c!=="object"&&c!=="string"&&(r=t,t=null),r&&typeof r!="function"&&(r=Zd.parse),t=w_(t),i=C_(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||wW.test(e))||!i.slashes&&(i.protocol||i.slashesCount<2||!Xn(d.protocol)))&&(u[3]=[/(.*)/,"pathname"]);f<u.length;f++){if(a=u[f],typeof a=="function"){e=a(e,d);continue}o=a[0],l=a[1],o!==o?d[l]=e:typeof o=="string"?(s=o==="@"?e.lastIndexOf(o):e.indexOf(o),~s&&(typeof a[2]=="number"?(d[l]=e.slice(0,s),e=e.slice(s+a[2])):(d[l]=e.slice(s),e=e.slice(0,s)))):(s=o.exec(e))&&(d[l]=s[1],e=e.slice(0,s.index)),d[l]=d[l]||n&&a[3]&&t[l]||"",a[4]&&(d[l]=d[l].toLowerCase())}r&&(d.query=r(d.query)),n&&t.slashes&&d.pathname.charAt(0)!=="/"&&(d.pathname!==""||t.pathname!=="")&&(d.pathname=EW(d.pathname,t.pathname)),d.pathname.charAt(0)!=="/"&&Xn(d.protocol)&&(d.pathname="/"+d.pathname),b_(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:"&&Xn(d.protocol)&&d.host?d.protocol+"//"+d.host:"null",d.href=d.toString()}function AW(e,t,r){var n=this;switch(e){case"query":typeof t=="string"&&t.length&&(t=(r||Zd.parse)(t)),n[e]=t;break;case"port":n[e]=t,b_(t,n.protocol)?t&&(n.host=n.hostname+":"+t):(n.host=n.hostname,n[e]="");break;case"hostname":n[e]=t,n.port&&(t+=":"+n.port),n.host=t;break;case"host":n[e]=t,/:\d+$/.test(t)?(t=t.split(":"),n.port=t.pop(),n.hostname=t.join(":")):(n.hostname=t,n.port="");break;case"protocol":n.protocol=t.toLowerCase(),n.slashes=!r;break;case"pathname":case"hash":if(t){var i=e==="pathname"?"/":"#";n[e]=t.charAt(0)!==i?i+t:t}else n[e]=t;break;case"username":case"password":n[e]=encodeURIComponent(t);break;case"auth":var o=t.indexOf(":");~o?(n.username=t.slice(0,o),n.username=encodeURIComponent(decodeURIComponent(n.username)),n.password=t.slice(o+1),n.password=encodeURIComponent(decodeURIComponent(n.password))):n.username=encodeURIComponent(decodeURIComponent(t))}for(var a=0;a<Zg.length;a++){var s=Zg[a];s[4]&&(n[s[1]]=n[s[1]].toLowerCase())}return n.auth=n.password?n.username+":"+n.password:n.username,n.origin=n.protocol!=="file:"&&Xn(n.protocol)&&n.host?n.protocol+"//"+n.host:"null",n.href=n.toString(),n}function SW(e){(!e||typeof e!="function")&&(e=Zd.stringify);var t,r=this,n=r.host,i=r.protocol;i&&i.charAt(i.length-1)!==":"&&(i+=":");var o=i+(r.protocol&&r.slashes||Xn(r.protocol)?"//":"");return r.username?(o+=r.username,r.password&&(o+=":"+r.password),o+="@"):r.password?(o+=":"+r.password,o+="@"):r.protocol!=="file:"&&Xn(r.protocol)&&!n&&r.pathname!=="/"&&(o+="@"),n[n.length-1]===":"&&(n+=":"),o+=n+r.pathname,t=typeof r.query=="object"?e(r.query):r.query,t&&(o+=t.charAt(0)!=="?"?"?"+t:t),r.hash&&(o+=r.hash),o}Zn.prototype={set:AW,toString:SW};Zn.extractProtocol=C_;Zn.location=w_;Zn.trimLeft=e0;Zn.qs=Zd;E_.exports=Zn});var NW,A_=k(()=>{"use strict";NW=we(t0());});function r0(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 ef=k(()=>{"use strict";});var n0,i0,o0=k(()=>{"use strict";ef();n0=class{features=new Map;register(t,r){let n=r0(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()}},i0=new n0});var a0=k(()=>{"use strict";});function Qd(e){return _W.has(e)}var _W,cu=k(()=>{"use strict";Hg();Yg();Yd();lu();Hg();A_();o0();ef();a0();_W=new Set(["tie","test","prod","preview","preprod","gov","high","dod","mooncake","ex","rx"])});var TW,S_=k(()=>{"use strict";cu();TW=uu({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 D_,l0,ys,oa,s0,tf,bs,Ri,Ue,N_,__,T_,An=k(()=>{"use strict";D_={ThreeEqColumn_FirstColumn:34,ThreeEqColumn_SecondColumn:33,ThreeEqColumn_ThirdColumn:33,FiveEqColumn:20},l0={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"})(ys||(ys={}));(function(e){e.Left="Left",e.Right="Right",e.Center="Center"})(oa||(oa={}));(function(e){e[e.Mobile=0]="Mobile",e[e.Tablet=1]="Tablet",e[e.Web=2]="Web"})(s0||(s0={}));tf=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"})(bs||(bs={}));Ri=class{static StartTag="<"},Ue={ShowLabel:"true",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_",labelAlignment:oa.Left,labelPosition:bs.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"})(N_||(N_={}));(function(e){e.TabWithLockedFieldRemoval="TabWithLockedFieldRemoval",e.SectionWithLockedFieldRemoval="SectionWithLockedFieldRemoval",e.LockedSectionRemoval="LockedSectionRemoval",e.LockedFieldRemoval="LockedFieldRemoval",e.RequiredFieldRemoval="RequiredFieldRemoval",e.LastRemainingTab="LastRemainingTab",e.UnknownRemoval="UnknownRemoval"})(__||(__={}));(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"})(T_||(T_={}))});var u0,I_=k(()=>{"use strict";(function(e){e.DefaultValue="defaultValue",e.Loaded="loaded"})(u0||(u0={}))});var R_,DW,O_,Mue,Uue,du,P_,Bue,que,L_=k(()=>{"use strict";R_=we(na());et();gs();S_();is();An();jo();se();DW=we(Ji());I_();(function(e){e.Model="Model",e.Canvas="Canvas",e.CustomPages="CustomPages"})(O_||(O_={}));Mue={Read:ro.Read,Edit:ro.Edit,Both:ro.Both,Container:ro.Container},Uue={input:zo.Input,bound:zo.Bound,output:zo.Output};(function(e){e[e.dataset=0]="dataset",e[e.property=1]="property",e[e.groups=2]="groups",e[e.group=3]="group"})(du||(du={}));(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"})(P_||(P_={}));Bue=new Set([F.Currency,F.Decimal,F.FP,F.Multiple,F.SingleLineEmail,F.SingleLinePhone,F.SingleLineText,F.SingleLineTextArea,F.SingleLineURL,F.SingleLineTickerSymbol,F.WholeNone,F.WholeDuration,F.WholeLanguage,F.WholeTimeZone,F.Enum,F.LookupSimple,F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.TwoOptions,F.Boolean,F.PowerBIReport,F.DateAndTimeDateAndTime,F.DateAndTimeDateOnly,F.OptionSet,F.MultiSelectOptionSet,F.CardForm]),que={numbers:[F.WholeNone,F.FP,F.Decimal,F.Currency],text:[F.SingleLineText,F.SingleLineTextArea,F.Multiple],lookup:[F.LookupSimple,F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding],dates:[F.DateAndTimeDateOnly,F.DateAndTimeDateAndTime],allFields:[F.TwoOptions,F.DateAndTimeDateOnly,F.DateAndTimeDateAndTime,F.FP,F.Decimal,F.WholeNone,F.WholeDuration,F.WholeTimeZone,F.WholeLanguage,F.LookupSimple,F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.Multiple,F.OptionSet,F.SingleLineText,F.SingleLineTextArea,F.SingleLineEmail,F.SingleLineURL,F.SingleLineTickerSymbol,F.SingleLinePhone]}});var Sn,rf,k_=k(()=>{"use strict";Sn=we(na());ct();et();zt();gs();jo();L_();is();se();St();An();rf=class extends te{constructor(t){super(C.customControl,t)}customControlId;get id(){let t=this.getProperty(y.id);return P.IsNullOrUndefined(t)?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new U(t.substr(1,t.length-2)):new U(t)}getParameters(){let t=new Map,r=this.getAllChildren();if(r&&r.length!==0&&r[0]){let n=r[0].getAllChildren();if(n!=null){for(let i of n)if(i&&i.getAllChildren().length>0){let o=i.getNodeName();t.get(o)?t.get(o).push(i):t.set(o,[i])}}}return t}getFormComponentValueByParameterName(t){let r=this.getParameters()?.get(qt.value);if(r?.length>0){let n=r[0],i=n?.getAllChildren()?.length>0?n.getAllChildren().find(a=>a.getNodeName()===t):null,o=i?.getAllChildren()?.length>0?i.getAllChildren()[0].getNodeName():"";return this.normalizePropertyValue(o)}}getParameterValue(t){let r=this.getParameterNodeChild(t);return r&&this.normalizePropertyValue(r.getNodeName())}getParameterNodeChild(t){let r=this.getParameters().get(t);return r?.length>0&&r[0].getAllChildren()?.length>0?r[0].getAllChildren()[0]:null}getDatasetName(t){return t.getAllProperties().find(r=>r.key===qt.name)?.value}getParameterChildrenValues(t,r,n){if(this.isDataSet(t)){let i=r.find(u=>u.key===qt.name)?.value,o={Name:i,Type:F.Grid,Columns:[]},l=this.getParameters().get(qt.dataset).find(u=>this.getDatasetName(u)===i).getAllChildren();for(let u of l){let c=u.getNodeName();if(u&&u.getAllChildren().length>0){let d=this.normalizePropertyValue(u.getAllChildren()[0].getNodeName());o[c]=d}}return o}}getParameterIsStatic(t){let r=!1,n=this.getParameters().get(t)[0],i=n&&n.getAllProperties();if(i){for(let o of i)if(o.key===y.static&&o.value==="true"){r=!0;break}}return r}get name(){return this.getProperty(y.Name)}get formFactor(){return this.getProperty(y.formFactor)}set formFactor(t){this.setProperty(y.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(Ri.StartTag)&&(t=t.substring(1)),t}async parametersToJSON(t){let r=[];if(!this.name)return r;try{let n=await t.formModelService.customControlDiscoveryService.getCustomControlMetadata(this.name);if(n)if(n.configurations){let i=n.configurations,o=this.getParameters();for(let[a,s]of o)if(this.isDataSet(a))for(let l of o.get(a)){let u=l.getAllProperties(),c=this.getDatasetName(l),d=i.get(c),f=await this.parameterJSON(a,u,d,t);r.push({Name:c,Value:f})}else if(this.isGroups(s))r.push({Name:a,Value:{Type:Dh.GroupDefinition,Value:this.normalizePropertyValue(this.getParameterNodeChild(s[0].NodeName).NodeName)}}),i.get(a).groupSet?.forEach(u=>{u.groupConfigurableProperties.forEach(async c=>{let d=c.name;c.propertyType===du.dataset?o.get(qt.dataset)?.some(p=>this.getDatasetName(p)===d)||r.push({Name:d,Value:{Name:d,Columns:[],Type:F.Grid}}):c.propertyType===du.property&&(o.has(d)||r.push({Name:d,Value:{Usage:c.usage}}))})});else{let l=s[0].getAllProperties(),u=i.get(a),c=await this.parameterJSON(a,l,u,t);if(c)r.push({Name:a,Value:c});else{(0,Sn.trackInfoTrace)(ir,{eventName:`${Oi}/parametersToJSON`,eventData:{message:`Configuration metadata for custom control parameter ${a} is not available for custom control : ${this.name}.`}}),r=[];break}}}else(0,Sn.trackErrorTrace)(ir,{eventName:`${Oi}/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,Sn.trackErrorTrace)(ir,{eventName:`${Oi}/parametersToJSON`,eventData:{message:"Custom Control Manifest not found"}},new Error(`No custom control manifest found for ${this.name}`))}catch(n){(0,Sn.trackErrorTrace)(ir,{eventName:`${Oi}/parametersToJSON`,eventData:{message:"parameters to json failed"}},n)}return r}async parameterJSON(t,r,n,i){if(this.isDataSet(t)){let o=n,a=r.find(s=>s.key===qt.name)?.value;if(o)return this.getParameterChildrenValues(t,r);{let s=new Error(`No dataset manifest info for ${a}`);(0,Sn.trackErrorTrace)(ir,{eventName:`${Oi}/parameterJSON`,eventData:{message:"Missing custom control manifest dataset info"}},s)}}else{let o=n,a=r&&r.find(l=>l.key===y.Type),s=o&&!o.ofTypeGroup.every(l=>!rd.includes(l));if(this.isLookupType(a?.value)||this.isLookupType(o?.ofType)||s)if(o){let l=o.usage,u=this.getParameterIsStatic(t),c=o.isPrimary;if(this.name===Si.FormComponent){let d=this.getFormComponentValueByParameterName(y.bindAttribute),f=await i.formModelService.loadLookupModel(d),p=f.lookupColumn,m=this.getLookupDataTypeFromAttributeMetadata(p);return{Name:t,Type:m,Usage:l,Static:u,Primary:c,EntityName:f.primaryTableName,Value:d,ViewId:this.getFormComponentValueByParameterName(Th.DefaultViewId),TargetEntityType:p.targets[0],FilterRelationshipName:this.getFormComponentValueByParameterName(y.FilterRelationshipName),AvailableViewIds:this.getFormComponentValueByParameterName(y.AvailableViewIds),DependentAttributeName:this.getFormComponentValueByParameterName(y.DependentAttributeName),DependentAttributeType:this.getFormComponentValueByParameterName(y.DependentAttributeType),AllowFilterOff:q.IsStrictTrue(this.getFormComponentValueByParameterName(y.AllowFilterOff)),DisableQuickFind:q.IsStrictTrue(this.getFormComponentValueByParameterName(y.DisableQuickFind)),EnableViewPicker:!q.IsStrictTrue(this.getFormComponentValueByParameterName(y.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,Sn.trackErrorTrace)(ir,{eventName:`${Oi}/parameterJSON`,eventData:{message:"Missing custom control manifest lookup property info"}},l)}if(o){let l=o.usage,u=this.getParameterIsStatic(t),c=this.getParameterValue(t),d=o.isPrimary;if(a){let p=a.value;return{Type:p,Static:u,Usage:l,Value:this.isNumberTypeProperty(o,p)&&Number(c)?Number(c):c,Primary:d}}if(o.ofType)return{Type:o.ofType,Static:u,Usage:l,Value:c,Primary:!0};if(o.ofTypeGroup)return{Static:u,Usage:l,Value:c,Primary:!0};let f=new Error(`No property type info for ${t}`);(0,Sn.trackErrorTrace)(ir,{eventName:`${Oi}/parameterJSON`,eventData:{message:"Missing property type info"}},f)}else{let l=new Error(`No property manifest info for ${t}`);(0,Sn.trackWarningTrace)(ir,{eventName:`${Oi}/parameterJSON`,eventData:{message:"Missing custom control manifest property info"}},l)}}return null}getLookupDataTypeFromAttributeMetadata(t){let{attributeType:r,format:n}=t;switch(r){case x.Customer:return F.LookupCustomer;case x.Owner:return F.LookupOwner;case x.PartyList:return F.LookupPartyList;default:return n===W.Regarding?F.LookupRegarding:F.LookupSimple}}isLookupType(t){return rd.includes(t)}isNumberTypeProperty(t,r){return nd.includes(r)||t.ofTypeGroup.some(n=>nd.includes(n))}isDataSet(t){return qt.dataset===t}isGroups(t){return!!t[0].getAllProperties().find(n=>n.key==="isGroup"&&n.value==="true")}}});var ee,c0=k(()=>{"use strict";ee=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_={};jr(x_,{CustomControlUniqueId:()=>aa,DeprecatedControlClassIds:()=>G,FieldControlTypes:()=>tt,mapFieldTypeToControl:()=>IW});function IW(e,t){switch(e){case x.TwoOptions:return N.BooleanControl;case x.Customer:case x.CustomerType:return N.LookupControl;case x.DateTime:return t===W.DateAndTime?N.DateTimeControl:N.DateTimeControl;case x.DecimalNumber:return N.DecimalControl;case x.FloatingPointNumber:return N.FloatingNumberControl;case x.WholeNumber:return t===W.Duration?N.DurationControl:t===W.Language?N.LanguageControl:t===W.TimeZone?N.TimezoneControl:N.IntegerControl;case x.CustomerType:case x.Lookup:case x.LookupType:return t===W.Regarding?N.RegardingControl:N.LookupControl;case x.MultipleLineofText:return t===W.Email?N.EmailBodyControl:N.TextAreaControl;case x.Currency:return N.CurrencyControl;case x.Owner:case x.OwnerType:return N.LookupControl;case x.PartyList:case x.PartyListType:return N.PartyListControl;case x.Status:case x.OptionSet:return N.ChoiceControl;case x.SingleLineofText:return t===W.Email?N.EmailAddressControl:t===W.Phone?N.PhoneNumberControl:t===W.Text?N.TextboxControl:t===W.TextArea?N.TextAreaControl:t===W.TickerSymbol?N.TickerControl:t===W.Url?N.UrlControl:t===W.PhoneticGuide?N.TextboxControl:N.TextboxControl;case x.MultiSelectOptionSet:return N.ChoicesControl;case x.Image:return N.ImageControl;case x.File:return N.FileControl;case x.State:return N.ChoiceControl;case x.Status:return N.ChoiceStatusControl;default:throw new Error(`Cannot get base control for ${e} field type`)}}var G,aa,tt,fu=k(()=>{"use strict";ct();Bl();et();zt();is();ra();c0();An();G=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"}};aa=class{static get RelationshipAssistant(){return"3ff9a528-dd50-4aca-8f10-2e5ed73513ad"}static get PredictiveLeadScoring(){return"6f503f2a-d033-4106-b62c-f8f2e5f01a57"}},tt=class e{static FieldControlIds=e.initializeFieldControls();static UnboundControlIds=e.initializeUnboundControls();static ControlsAllowedForReferencePanel=e.initializeReferencePanelControls();static ControlsAllowedForFooter=e.initializeFooterControls();static CustomControlIdMap=new er;static initializeFieldControls(){let t=new er,r=e.getControlName(x.SingleLineofText,W.Phone);t.add(r,new U(G.PhoneNumberControl));let n=e.getControlName(x.SingleLineofText,W.TextArea);t.add(n,new U(G.TextAreaControl));let i=e.getControlName(x.SingleLineofText,W.Text);t.add(i,new U(G.TextBoxControl));let o=e.getControlName(x.SingleLineofText,W.Email);t.add(o,new U(G.EmailAddressControl));let a=e.getControlName(x.SingleLineofText,W.Url);t.add(a,new U(G.UrlControl));let s=e.getControlName(x.SingleLineofText,W.TickerSymbol);t.add(s,new U(G.TickerControl));let l=e.getControlName(x.SingleLineofText,W.PhoneticGuide);t.add(l,new U(G.TextBoxControl));let u=e.getControlName(x.WholeNumber,W.Duration);t.add(u,new U(G.DurationControl));let c=e.getControlName(x.WholeNumber,W.Language);t.add(c,new U(G.LanguagePickerControl));let d=e.getControlName(x.WholeNumber,W.TimeZone);t.add(d,new U(G.TimeZonePicklistControl));let f=e.getControlName(x.WholeNumber,W.None);t.add(f,new U(G.IntegerControl));let p=e.getControlName(x.DateTime,W.DateOnly);t.add(p,new U(G.DateTimeControl));let m=e.getControlName(x.DateTime,W.DateAndTime);t.add(m,new U(G.DateTimeControl));let h=e.getControlName(x.LookupType,W.None);t.add(h,new U(G.LookupControl));let g=e.getControlName(x.CustomerType,W.None);t.add(g,new U(G.LookupControl));let b=e.getControlName(x.FloatingPointNumber,W.None);t.add(b,new U(G.FloatControl));let w=e.getControlName(x.DecimalNumber,W.None);t.add(w,new U(G.DecimalControl));let E=e.getControlName(x.Currency,W.None);t.add(E,new U(G.MoneyControl));let A=e.getControlName(x.MultipleLineofText,W.None);t.add(A,new U(G.TextAreaControl));let L=e.getControlName(x.MultipleLineofText,W.Text);t.add(L,new U(G.TextAreaControl));let R=e.getControlName(x.MultipleLineofText,W.TextArea);t.add(R,new U(G.TextAreaControl));let I=e.getControlName(x.MultipleLineofText,W.Email);t.add(I,new U(G.EmailBodyControl));let D=e.getControlName(x.OptionSet,W.None);t.add(D,new U(G.PicklistControl));let O=e.getControlName(x.TwoOptions,W.None);t.add(O,new U(G.RadioControl));let $=e.getControlName(x.Image,W.None);t.add($,new U(G.WebResourceImageControl));let K=e.getControlName(x.Image,W.None);t.add(K,new U(G.WebResourceHtmlControl));let Re=e.getControlName(x.TwoOptions,"Radio");t.add(Re,new U(G.RadioControl));let It=e.getControlName(x.TwoOptions,"CheckBox");t.add(It,new U(G.CheckBoxControl));let Le=e.getControlName(x.TwoOptions,"List");t.add(Le,new U(G.PicklistControl));let at=e.getControlName(x.State,W.None);t.add(at,new U(G.PicklistControl));let ge=e.getControlName(x.Status,W.None);t.add(ge,new U(G.PicklistStatusControl));let ht=e.getControlName(x.OwnerType,W.None);t.add(ht,new U(G.LookupControl));let Ro=e.getControlName(x.PartyListType,W.None);t.add(Ro,new U(G.PartyListControl));let Ot=e.getControlName(x.LookupType,W.Regarding);t.add(Ot,new U(G.RegardingControl));let di=e.getControlName(x.MultiSelectOptionSet,W.None);return t.add(di,new U(G.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(!P.IsNullOrEmptyGuid(t)){let r=e.getTypeAndFormatByControlOrUniqueId(t.guidString.toLowerCase());return r=P.IsNullOrUndefined(r)?e.getUnboundControlNameFromIdentifier(t):r.substring(0,r.indexOf("_")),r}return null}static isCustomControl(t){return P.IsNullOrUndefined(t.control)||P.IsNullOrUndefined(t.control.ClassId)||t.control.ClassId.guidString===G.CustomControl}static initializeUnboundControls(){let t=new er;return t.add(G.ACIControl,ee.ACIControl),t.add(G.IframeControl,ee.IframeControl),t.add(G.SearchWidgetControl,ee.SearchWidgetControl),t.add(G.MapsControl,ee.MapsControl),t.add(G.QuickFormCollectionControl,ee.QuickFormCollectionControl),t.add(G.GridControl,ee.SubGridControl),t.add(G.WebResourceImageControl,ee.WebResourceImageControl),t.add(G.WebResourceHtmlControl,ee.WebResourceHtmlControl),t.add(G.ReferencePanelSearchWidget,ee.SearchWidgetControl),t.add(G.ReferencePanelQuickFormCollectionControl,ee.QuickFormCollectionControl),t.add(G.ReferencePanelSubgridControl,ee.SubGridControl),t.add(G.TimerControl,ee.TimerControl),t.add(G.TimeLineControl,ee.NotesControl),t.add(G.TimeLineControlUC,ee.NotesControl),t.add(G.SocialInsightControl,ee.SocialInsightControl),t.add(aa.RelationshipAssistant,ee.CustomControl),t}static initializeReferencePanelControls(){let t=new er;return t.add(G.IframeControl,ee.IframeControl),t.add(G.ReferencePanelSearchWidget,ee.SearchWidgetControl),t.add(G.ReferencePanelQuickFormCollectionControl,ee.QuickFormCollectionControl),t.add(G.ReferencePanelSubgridControl,ee.SubGridControl),t.add(G.WebResourceHtmlControl,ee.WebResourceHtmlControl),t.add(G.WebResourceImageControl,ee.WebResourceHtmlControl),t}static initializeFooterControls(){let t=new ns;return t.add(ys.IFRAME,!0),t.add(ys.SPACER,!0),t.add(ys.WEB_RESOURCE_HTML,!0),t}static isUnboundFormControl(t){if(P.IsNullOrUndefined(t)||P.IsNullOrUndefined(t.control)||P.IsNullOrUndefined(t.control.ClassId))return!1;let r=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.containsKey(r.guidString)}static isReferencePanelSection(t){return!P.IsNullOrUndefined(t)&&!P.IsNullOrUndefined(t.Name)&&t.Name.indexOf(Ue.referencePanelNamePrefix)===0}static isUnboundFormControlByIdentifier(t){return P.IsNullOrUndefined(t)||P.IsNullOrUndefined(t.guidString)?!1:e.UnboundControlIds.containsKey(t.guidString)}static getUnboundFormControlName(t){let r=q.EmptyString;if(P.IsNullOrUndefined(t)||P.IsNullOrUndefined(t.control)||P.IsNullOrUndefined(t.control.ClassId))return r;let n=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.getValue(n.guidString).toString()}static getUnboundControlNameFromIdentifier(t){return P.IsNullOrUndefined(t)||P.IsNullOrUndefined(t.guidString)?q.EmptyString:e.UnboundControlIds.getValue(t.guidString).toString()}static isSpacerControl(t){return t===G.SpacerControl}static GetRowSpan(t){let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===G.CustomControl&&!P.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}switch(e.UnboundControlIds.getValue(r.guidString)){case ee.IframeControl:case ee.ACIControl:case ee.SocialInsightControl:return 6;case ee.SubGridControl:case ee.CustomControl:return 4;case ee.WebResourceImageControl:return 15;case ee.WebResourceHtmlControl:return 15;case ee.MapsControl:return 8;case ee.SearchWidgetControl:return 10;case ee.NotesControl:case ee.TimeLineControl:return 15;case ee.TimerControl:return 2;default:}}static isLookUpControl(t){return!P.IsNullOrUndefined(t)&&t.ClassId.guidString===G.LookupControl}static isRelationshipAssistantOrLeadScoringControl(t){return!P.IsNullOrUndefined(t)&&e.isRelationshipAssistantOrLeadScoring(t.UniqueId)}static isRelationshipAssistantOrLeadScoring(t){return!P.IsNullOrUndefined(t)&&(t.guidString===aa.RelationshipAssistant||t.guidString===aa.PredictiveLeadScoring)}static isRelationshipAssistantControl(t){return!P.IsNullOrUndefined(t)&&e.isRelationshipAssistant(t.UniqueId)}static isRelationshipAssistant(t){return!P.IsNullOrUndefined(t)&&t.guidString===aa.RelationshipAssistant}static getUniqueIdentifierForControl(t){if(P.IsNullOrUndefined(t))return null;let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===G.CustomControl&&!P.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}return r}}});var nf,$_=k(()=>{"use strict";nf=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 sa,vs,F_,M_,ho,U_,B_,d0=k(()=>{"use strict";(function(e){e[e.Center=0]="Center",e[e.Left=1]="Left",e[e.Right=2]="Right"})(sa||(sa={}));(function(e){e[e.Left=0]="Left",e[e.Top=1]="Top"})(vs||(vs={}));(function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle"})(F_||(F_={}));(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"})(M_||(M_={}));(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"})(ho||(ho={}));(function(e){e[e.None=0]="None",e[e.SystemRequired=1]="SystemRequired",e[e.ApplicationRequired=2]="ApplicationRequired",e[e.Recommended=3]="Recommended"})(U_||(U_={}));(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"})(B_||(B_={}))});var ws,q_=k(()=>{"use strict";cu();ws=Qg({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 V_(e){return{...e,extractConfig:t=>OW(t,Object.keys(e.fallback))}}function OW(e,t){let r={};for(let n of t)typeof e[n]<"u"&&(r[n]=e[n]);return r}var f0=k(()=>{"use strict";});var p0=v((mce,W_)=>{var pu=new Proxy(function(){return pu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:pu},apply:function(){return pu},construct:function(){return{}}}),G_=function(){return pu};Object.setPrototypeOf(G_,pu);W_.exports=G_});var H_=v((hce,j_)=>{var mu=new Proxy(function(){return mu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:mu},apply:function(){return mu},construct:function(){return{}}}),z_=function(){return mu};Object.setPrototypeOf(z_,mu);j_.exports=z_});var m0=v((gce,J_)=>{var hu=new Proxy(function(){return hu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:hu},apply:function(){return hu},construct:function(){return{}}}),K_=function(){return hu};Object.setPrototypeOf(K_,hu);J_.exports=K_});var Q_=v((yce,Y_)=>{function PW(){this.__data__=[],this.size=0}Y_.exports=PW});var Cs=v((bce,X_)=>{function RW(e,t){return e===t||e!==e&&t!==t}X_.exports=RW});var gu=v((vce,Z_)=>{var LW=Cs();function kW(e,t){for(var r=e.length;r--;)if(LW(e[r][0],t))return r;return-1}Z_.exports=kW});var tT=v((wce,eT)=>{var xW=gu(),$W=Array.prototype,FW=$W.splice;function MW(e){var t=this.__data__,r=xW(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():FW.call(t,r,1),--this.size,!0}eT.exports=MW});var nT=v((Cce,rT)=>{var UW=gu();function BW(e){var t=this.__data__,r=UW(t,e);return r<0?void 0:t[r][1]}rT.exports=BW});var oT=v((Ece,iT)=>{var qW=gu();function VW(e){return qW(this.__data__,e)>-1}iT.exports=VW});var sT=v((Ace,aT)=>{var GW=gu();function WW(e,t){var r=this.__data__,n=GW(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}aT.exports=WW});var yu=v((Sce,lT)=>{var zW=Q_(),jW=tT(),HW=nT(),KW=oT(),JW=sT();function Es(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])}}Es.prototype.clear=zW;Es.prototype.delete=jW;Es.prototype.get=HW;Es.prototype.has=KW;Es.prototype.set=JW;lT.exports=Es});var cT=v((Nce,uT)=>{var YW=yu();function QW(){this.__data__=new YW,this.size=0}uT.exports=QW});var fT=v((_ce,dT)=>{function XW(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}dT.exports=XW});var mT=v((Tce,pT)=>{function ZW(e){return this.__data__.get(e)}pT.exports=ZW});var gT=v((Dce,hT)=>{function e6(e){return this.__data__.has(e)}hT.exports=e6});var h0=v((Ice,yT)=>{var t6=typeof global=="object"&&global&&global.Object===Object&&global;yT.exports=t6});var Nn=v((Oce,bT)=>{var r6=h0(),n6=typeof self=="object"&&self&&self.Object===Object&&self,i6=r6||n6||Function("return this")();bT.exports=i6});var bu=v((Pce,vT)=>{var o6=Nn(),a6=o6.Symbol;vT.exports=a6});var AT=v((Rce,ET)=>{var wT=bu(),CT=Object.prototype,s6=CT.hasOwnProperty,l6=CT.toString,vu=wT?wT.toStringTag:void 0;function u6(e){var t=s6.call(e,vu),r=e[vu];try{e[vu]=void 0;var n=!0}catch{}var i=l6.call(e);return n&&(t?e[vu]=r:delete e[vu]),i}ET.exports=u6});var NT=v((Lce,ST)=>{var c6=Object.prototype,d6=c6.toString;function f6(e){return d6.call(e)}ST.exports=f6});var la=v((kce,DT)=>{var _T=bu(),p6=AT(),m6=NT(),h6="[object Null]",g6="[object Undefined]",TT=_T?_T.toStringTag:void 0;function y6(e){return e==null?e===void 0?g6:h6:TT&&TT in Object(e)?p6(e):m6(e)}DT.exports=y6});var Li=v((xce,IT)=>{function b6(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}IT.exports=b6});var of=v(($ce,OT)=>{var v6=la(),w6=Li(),C6="[object AsyncFunction]",E6="[object Function]",A6="[object GeneratorFunction]",S6="[object Proxy]";function N6(e){if(!w6(e))return!1;var t=v6(e);return t==E6||t==A6||t==C6||t==S6}OT.exports=N6});var RT=v((Fce,PT)=>{var _6=Nn(),T6=_6["__core-js_shared__"];PT.exports=T6});var xT=v((Mce,kT)=>{var g0=RT(),LT=(function(){var e=/[^.]+$/.exec(g0&&g0.keys&&g0.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function D6(e){return!!LT&< in e}kT.exports=D6});var y0=v((Uce,$T)=>{var I6=Function.prototype,O6=I6.toString;function P6(e){if(e!=null){try{return O6.call(e)}catch{}try{return e+""}catch{}}return""}$T.exports=P6});var MT=v((Bce,FT)=>{var R6=of(),L6=xT(),k6=Li(),x6=y0(),$6=/[\\^$.*+?()[\]{}|]/g,F6=/^\[object .+?Constructor\]$/,M6=Function.prototype,U6=Object.prototype,B6=M6.toString,q6=U6.hasOwnProperty,V6=RegExp("^"+B6.call(q6).replace($6,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function G6(e){if(!k6(e)||L6(e))return!1;var t=R6(e)?V6:F6;return t.test(x6(e))}FT.exports=G6});var BT=v((qce,UT)=>{function W6(e,t){return e?.[t]}UT.exports=W6});var go=v((Vce,qT)=>{var z6=MT(),j6=BT();function H6(e,t){var r=j6(e,t);return z6(r)?r:void 0}qT.exports=H6});var af=v((Gce,VT)=>{var K6=go(),J6=Nn(),Y6=K6(J6,"Map");VT.exports=Y6});var wu=v((Wce,GT)=>{var Q6=go(),X6=Q6(Object,"create");GT.exports=X6});var jT=v((zce,zT)=>{var WT=wu();function Z6(){this.__data__=WT?WT(null):{},this.size=0}zT.exports=Z6});var KT=v((jce,HT)=>{function ez(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}HT.exports=ez});var YT=v((Hce,JT)=>{var tz=wu(),rz="__lodash_hash_undefined__",nz=Object.prototype,iz=nz.hasOwnProperty;function oz(e){var t=this.__data__;if(tz){var r=t[e];return r===rz?void 0:r}return iz.call(t,e)?t[e]:void 0}JT.exports=oz});var XT=v((Kce,QT)=>{var az=wu(),sz=Object.prototype,lz=sz.hasOwnProperty;function uz(e){var t=this.__data__;return az?t[e]!==void 0:lz.call(t,e)}QT.exports=uz});var eD=v((Jce,ZT)=>{var cz=wu(),dz="__lodash_hash_undefined__";function fz(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=cz&&t===void 0?dz:t,this}ZT.exports=fz});var rD=v((Yce,tD)=>{var pz=jT(),mz=KT(),hz=YT(),gz=XT(),yz=eD();function As(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])}}As.prototype.clear=pz;As.prototype.delete=mz;As.prototype.get=hz;As.prototype.has=gz;As.prototype.set=yz;tD.exports=As});var oD=v((Qce,iD)=>{var nD=rD(),bz=yu(),vz=af();function wz(){this.size=0,this.__data__={hash:new nD,map:new(vz||bz),string:new nD}}iD.exports=wz});var sD=v((Xce,aD)=>{function Cz(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}aD.exports=Cz});var Cu=v((Zce,lD)=>{var Ez=sD();function Az(e,t){var r=e.__data__;return Ez(t)?r[typeof t=="string"?"string":"hash"]:r.map}lD.exports=Az});var cD=v((ede,uD)=>{var Sz=Cu();function Nz(e){var t=Sz(this,e).delete(e);return this.size-=t?1:0,t}uD.exports=Nz});var fD=v((tde,dD)=>{var _z=Cu();function Tz(e){return _z(this,e).get(e)}dD.exports=Tz});var mD=v((rde,pD)=>{var Dz=Cu();function Iz(e){return Dz(this,e).has(e)}pD.exports=Iz});var gD=v((nde,hD)=>{var Oz=Cu();function Pz(e,t){var r=Oz(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}hD.exports=Pz});var sf=v((ide,yD)=>{var Rz=oD(),Lz=cD(),kz=fD(),xz=mD(),$z=gD();function Ss(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])}}Ss.prototype.clear=Rz;Ss.prototype.delete=Lz;Ss.prototype.get=kz;Ss.prototype.has=xz;Ss.prototype.set=$z;yD.exports=Ss});var vD=v((ode,bD)=>{var Fz=yu(),Mz=af(),Uz=sf(),Bz=200;function qz(e,t){var r=this.__data__;if(r instanceof Fz){var n=r.__data__;if(!Mz||n.length<Bz-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new Uz(n)}return r.set(e,t),this.size=r.size,this}bD.exports=qz});var b0=v((ade,wD)=>{var Vz=yu(),Gz=cT(),Wz=fT(),zz=mT(),jz=gT(),Hz=vD();function Ns(e){var t=this.__data__=new Vz(e);this.size=t.size}Ns.prototype.clear=Gz;Ns.prototype.delete=Wz;Ns.prototype.get=zz;Ns.prototype.has=jz;Ns.prototype.set=Hz;wD.exports=Ns});var ED=v((sde,CD)=>{var Kz="__lodash_hash_undefined__";function Jz(e){return this.__data__.set(e,Kz),this}CD.exports=Jz});var SD=v((lde,AD)=>{function Yz(e){return this.__data__.has(e)}AD.exports=Yz});var _D=v((ude,ND)=>{var Qz=sf(),Xz=ED(),Zz=SD();function lf(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new Qz;++t<r;)this.add(e[t])}lf.prototype.add=lf.prototype.push=Xz;lf.prototype.has=Zz;ND.exports=lf});var DD=v((cde,TD)=>{function ej(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}TD.exports=ej});var OD=v((dde,ID)=>{function tj(e,t){return e.has(t)}ID.exports=tj});var v0=v((fde,PD)=>{var rj=_D(),nj=DD(),ij=OD(),oj=1,aj=2;function sj(e,t,r,n,i,o){var a=r&oj,s=e.length,l=t.length;if(s!=l&&!(a&&l>s))return!1;var u=o.get(e),c=o.get(t);if(u&&c)return u==t&&c==e;var d=-1,f=!0,p=r&aj?new rj:void 0;for(o.set(e,t),o.set(t,e);++d<s;){var m=e[d],h=t[d];if(n)var g=a?n(h,m,d,t,e,o):n(m,h,d,e,t,o);if(g!==void 0){if(g)continue;f=!1;break}if(p){if(!nj(t,function(b,w){if(!ij(p,w)&&(m===b||i(m,b,r,n,o)))return p.push(w)})){f=!1;break}}else if(!(m===h||i(m,h,r,n,o))){f=!1;break}}return o.delete(e),o.delete(t),f}PD.exports=sj});var w0=v((pde,RD)=>{var lj=Nn(),uj=lj.Uint8Array;RD.exports=uj});var kD=v((mde,LD)=>{function cj(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}LD.exports=cj});var $D=v((hde,xD)=>{function dj(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}xD.exports=dj});var qD=v((gde,BD)=>{var FD=bu(),MD=w0(),fj=Cs(),pj=v0(),mj=kD(),hj=$D(),gj=1,yj=2,bj="[object Boolean]",vj="[object Date]",wj="[object Error]",Cj="[object Map]",Ej="[object Number]",Aj="[object RegExp]",Sj="[object Set]",Nj="[object String]",_j="[object Symbol]",Tj="[object ArrayBuffer]",Dj="[object DataView]",UD=FD?FD.prototype:void 0,C0=UD?UD.valueOf:void 0;function Ij(e,t,r,n,i,o,a){switch(r){case Dj:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case Tj:return!(e.byteLength!=t.byteLength||!o(new MD(e),new MD(t)));case bj:case vj:case Ej:return fj(+e,+t);case wj:return e.name==t.name&&e.message==t.message;case Aj:case Nj:return e==t+"";case Cj:var s=mj;case Sj:var l=n&gj;if(s||(s=hj),e.size!=t.size&&!l)return!1;var u=a.get(e);if(u)return u==t;n|=yj,a.set(e,t);var c=pj(s(e),s(t),n,i,o,a);return a.delete(e),c;case _j:if(C0)return C0.call(e)==C0.call(t)}return!1}BD.exports=Ij});var GD=v((yde,VD)=>{function Oj(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}VD.exports=Oj});var yo=v((bde,WD)=>{var Pj=Array.isArray;WD.exports=Pj});var jD=v((vde,zD)=>{var Rj=GD(),Lj=yo();function kj(e,t,r){var n=t(e);return Lj(e)?n:Rj(n,r(e))}zD.exports=kj});var KD=v((wde,HD)=>{function xj(e,t){for(var r=-1,n=e==null?0:e.length,i=0,o=[];++r<n;){var a=e[r];t(a,r,e)&&(o[i++]=a)}return o}HD.exports=xj});var YD=v((Cde,JD)=>{function $j(){return[]}JD.exports=$j});var ZD=v((Ede,XD)=>{var Fj=KD(),Mj=YD(),Uj=Object.prototype,Bj=Uj.propertyIsEnumerable,QD=Object.getOwnPropertySymbols,qj=QD?function(e){return e==null?[]:(e=Object(e),Fj(QD(e),function(t){return Bj.call(e,t)}))}:Mj;XD.exports=qj});var tI=v((Ade,eI)=>{function Vj(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}eI.exports=Vj});var bo=v((Sde,rI)=>{function Gj(e){return e!=null&&typeof e=="object"}rI.exports=Gj});var iI=v((Nde,nI)=>{var Wj=la(),zj=bo(),jj="[object Arguments]";function Hj(e){return zj(e)&&Wj(e)==jj}nI.exports=Hj});var E0=v((_de,sI)=>{var oI=iI(),Kj=bo(),aI=Object.prototype,Jj=aI.hasOwnProperty,Yj=aI.propertyIsEnumerable,Qj=oI((function(){return arguments})())?oI:function(e){return Kj(e)&&Jj.call(e,"callee")&&!Yj.call(e,"callee")};sI.exports=Qj});var uI=v((Tde,lI)=>{function Xj(){return!1}lI.exports=Xj});var uf=v((Eu,_s)=>{var Zj=Nn(),e7=uI(),fI=typeof Eu=="object"&&Eu&&!Eu.nodeType&&Eu,cI=fI&&typeof _s=="object"&&_s&&!_s.nodeType&&_s,t7=cI&&cI.exports===fI,dI=t7?Zj.Buffer:void 0,r7=dI?dI.isBuffer:void 0,n7=r7||e7;_s.exports=n7});var cf=v((Dde,pI)=>{var i7=9007199254740991,o7=/^(?:0|[1-9]\d*)$/;function a7(e,t){var r=typeof e;return t=t??i7,!!t&&(r=="number"||r!="symbol"&&o7.test(e))&&e>-1&&e%1==0&&e<t}pI.exports=a7});var A0=v((Ide,mI)=>{var s7=9007199254740991;function l7(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=s7}mI.exports=l7});var gI=v((Ode,hI)=>{var u7=la(),c7=A0(),d7=bo(),f7="[object Arguments]",p7="[object Array]",m7="[object Boolean]",h7="[object Date]",g7="[object Error]",y7="[object Function]",b7="[object Map]",v7="[object Number]",w7="[object Object]",C7="[object RegExp]",E7="[object Set]",A7="[object String]",S7="[object WeakMap]",N7="[object ArrayBuffer]",_7="[object DataView]",T7="[object Float32Array]",D7="[object Float64Array]",I7="[object Int8Array]",O7="[object Int16Array]",P7="[object Int32Array]",R7="[object Uint8Array]",L7="[object Uint8ClampedArray]",k7="[object Uint16Array]",x7="[object Uint32Array]",xe={};xe[T7]=xe[D7]=xe[I7]=xe[O7]=xe[P7]=xe[R7]=xe[L7]=xe[k7]=xe[x7]=!0;xe[f7]=xe[p7]=xe[N7]=xe[m7]=xe[_7]=xe[h7]=xe[g7]=xe[y7]=xe[b7]=xe[v7]=xe[w7]=xe[C7]=xe[E7]=xe[A7]=xe[S7]=!1;function $7(e){return d7(e)&&c7(e.length)&&!!xe[u7(e)]}hI.exports=$7});var bI=v((Pde,yI)=>{function F7(e){return function(t){return e(t)}}yI.exports=F7});var wI=v((Au,Ts)=>{var M7=h0(),vI=typeof Au=="object"&&Au&&!Au.nodeType&&Au,Su=vI&&typeof Ts=="object"&&Ts&&!Ts.nodeType&&Ts,U7=Su&&Su.exports===vI,S0=U7&&M7.process,B7=(function(){try{var e=Su&&Su.require&&Su.require("util").types;return e||S0&&S0.binding&&S0.binding("util")}catch{}})();Ts.exports=B7});var df=v((Rde,AI)=>{var q7=gI(),V7=bI(),CI=wI(),EI=CI&&CI.isTypedArray,G7=EI?V7(EI):q7;AI.exports=G7});var N0=v((Lde,SI)=>{var W7=tI(),z7=E0(),j7=yo(),H7=uf(),K7=cf(),J7=df(),Y7=Object.prototype,Q7=Y7.hasOwnProperty;function X7(e,t){var r=j7(e),n=!r&&z7(e),i=!r&&!n&&H7(e),o=!r&&!n&&!i&&J7(e),a=r||n||i||o,s=a?W7(e.length,String):[],l=s.length;for(var u in e)(t||Q7.call(e,u))&&!(a&&(u=="length"||i&&(u=="offset"||u=="parent")||o&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||K7(u,l)))&&s.push(u);return s}SI.exports=X7});var ff=v((kde,NI)=>{var Z7=Object.prototype;function eH(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||Z7;return e===r}NI.exports=eH});var _0=v((xde,_I)=>{function tH(e,t){return function(r){return e(t(r))}}_I.exports=tH});var DI=v(($de,TI)=>{var rH=_0(),nH=rH(Object.keys,Object);TI.exports=nH});var OI=v((Fde,II)=>{var iH=ff(),oH=DI(),aH=Object.prototype,sH=aH.hasOwnProperty;function lH(e){if(!iH(e))return oH(e);var t=[];for(var r in Object(e))sH.call(e,r)&&r!="constructor"&&t.push(r);return t}II.exports=lH});var Nu=v((Mde,PI)=>{var uH=of(),cH=A0();function dH(e){return e!=null&&cH(e.length)&&!uH(e)}PI.exports=dH});var LI=v((Ude,RI)=>{var fH=N0(),pH=OI(),mH=Nu();function hH(e){return mH(e)?fH(e):pH(e)}RI.exports=hH});var xI=v((Bde,kI)=>{var gH=jD(),yH=ZD(),bH=LI();function vH(e){return gH(e,bH,yH)}kI.exports=vH});var MI=v((qde,FI)=>{var $I=xI(),wH=1,CH=Object.prototype,EH=CH.hasOwnProperty;function AH(e,t,r,n,i,o){var a=r&wH,s=$I(e),l=s.length,u=$I(t),c=u.length;if(l!=c&&!a)return!1;for(var d=l;d--;){var f=s[d];if(!(a?f in t:EH.call(t,f)))return!1}var p=o.get(e),m=o.get(t);if(p&&m)return p==t&&m==e;var h=!0;o.set(e,t),o.set(t,e);for(var g=a;++d<l;){f=s[d];var b=e[f],w=t[f];if(n)var E=a?n(w,b,f,t,e,o):n(b,w,f,e,t,o);if(!(E===void 0?b===w||i(b,w,r,n,o):E)){h=!1;break}g||(g=f=="constructor")}if(h&&!g){var A=e.constructor,L=t.constructor;A!=L&&"constructor"in e&&"constructor"in t&&!(typeof A=="function"&&A instanceof A&&typeof L=="function"&&L instanceof L)&&(h=!1)}return o.delete(e),o.delete(t),h}FI.exports=AH});var BI=v((Vde,UI)=>{var SH=go(),NH=Nn(),_H=SH(NH,"DataView");UI.exports=_H});var VI=v((Gde,qI)=>{var TH=go(),DH=Nn(),IH=TH(DH,"Promise");qI.exports=IH});var WI=v((Wde,GI)=>{var OH=go(),PH=Nn(),RH=OH(PH,"Set");GI.exports=RH});var jI=v((zde,zI)=>{var LH=go(),kH=Nn(),xH=LH(kH,"WeakMap");zI.exports=xH});var eO=v((jde,ZI)=>{var T0=BI(),D0=af(),I0=VI(),O0=WI(),P0=jI(),XI=la(),Ds=y0(),HI="[object Map]",$H="[object Object]",KI="[object Promise]",JI="[object Set]",YI="[object WeakMap]",QI="[object DataView]",FH=Ds(T0),MH=Ds(D0),UH=Ds(I0),BH=Ds(O0),qH=Ds(P0),ua=XI;(T0&&ua(new T0(new ArrayBuffer(1)))!=QI||D0&&ua(new D0)!=HI||I0&&ua(I0.resolve())!=KI||O0&&ua(new O0)!=JI||P0&&ua(new P0)!=YI)&&(ua=function(e){var t=XI(e),r=t==$H?e.constructor:void 0,n=r?Ds(r):"";if(n)switch(n){case FH:return QI;case MH:return HI;case UH:return KI;case BH:return JI;case qH:return YI}return t});ZI.exports=ua});var lO=v((Hde,sO)=>{var R0=b0(),VH=v0(),GH=qD(),WH=MI(),tO=eO(),rO=yo(),nO=uf(),zH=df(),jH=1,iO="[object Arguments]",oO="[object Array]",pf="[object Object]",HH=Object.prototype,aO=HH.hasOwnProperty;function KH(e,t,r,n,i,o){var a=rO(e),s=rO(t),l=a?oO:tO(e),u=s?oO:tO(t);l=l==iO?pf:l,u=u==iO?pf:u;var c=l==pf,d=u==pf,f=l==u;if(f&&nO(e)){if(!nO(t))return!1;a=!0,c=!1}if(f&&!c)return o||(o=new R0),a||zH(e)?VH(e,t,r,n,i,o):GH(e,t,l,r,n,i,o);if(!(r&jH)){var p=c&&aO.call(e,"__wrapped__"),m=d&&aO.call(t,"__wrapped__");if(p||m){var h=p?e.value():e,g=m?t.value():t;return o||(o=new R0),i(h,g,r,n,o)}}return f?(o||(o=new R0),WH(e,t,r,n,i,o)):!1}sO.exports=KH});var fO=v((Kde,dO)=>{var JH=lO(),uO=bo();function cO(e,t,r,n,i){return e===t?!0:e==null||t==null||!uO(e)&&!uO(t)?e!==e&&t!==t:JH(e,t,r,n,cO,i)}dO.exports=cO});var mO=v((Jde,pO)=>{var YH=fO();function QH(e,t){return YH(e,t)}pO.exports=QH});var L0=v((Yde,hO)=>{var XH=go(),ZH=(function(){try{var e=XH(Object,"defineProperty");return e({},"",{}),e}catch{}})();hO.exports=ZH});var mf=v((Qde,yO)=>{var gO=L0();function eK(e,t,r){t=="__proto__"&&gO?gO(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}yO.exports=eK});var k0=v((Xde,bO)=>{var tK=mf(),rK=Cs();function nK(e,t,r){(r!==void 0&&!rK(e[t],r)||r===void 0&&!(t in e))&&tK(e,t,r)}bO.exports=nK});var wO=v((Zde,vO)=>{function iK(e){return function(t,r,n){for(var i=-1,o=Object(t),a=n(t),s=a.length;s--;){var l=a[e?s:++i];if(r(o[l],l,o)===!1)break}return t}}vO.exports=iK});var EO=v((efe,CO)=>{var oK=wO(),aK=oK();CO.exports=aK});var TO=v((_u,Is)=>{var sK=Nn(),_O=typeof _u=="object"&&_u&&!_u.nodeType&&_u,AO=_O&&typeof Is=="object"&&Is&&!Is.nodeType&&Is,lK=AO&&AO.exports===_O,SO=lK?sK.Buffer:void 0,NO=SO?SO.allocUnsafe:void 0;function uK(e,t){if(t)return e.slice();var r=e.length,n=NO?NO(r):new e.constructor(r);return e.copy(n),n}Is.exports=uK});var OO=v((tfe,IO)=>{var DO=w0();function cK(e){var t=new e.constructor(e.byteLength);return new DO(t).set(new DO(e)),t}IO.exports=cK});var RO=v((rfe,PO)=>{var dK=OO();function fK(e,t){var r=t?dK(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}PO.exports=fK});var kO=v((nfe,LO)=>{function pK(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}LO.exports=pK});var FO=v((ife,$O)=>{var mK=Li(),xO=Object.create,hK=(function(){function e(){}return function(t){if(!mK(t))return{};if(xO)return xO(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})();$O.exports=hK});var x0=v((ofe,MO)=>{var gK=_0(),yK=gK(Object.getPrototypeOf,Object);MO.exports=yK});var BO=v((afe,UO)=>{var bK=FO(),vK=x0(),wK=ff();function CK(e){return typeof e.constructor=="function"&&!wK(e)?bK(vK(e)):{}}UO.exports=CK});var VO=v((sfe,qO)=>{var EK=Nu(),AK=bo();function SK(e){return AK(e)&&EK(e)}qO.exports=SK});var zO=v((lfe,WO)=>{var NK=la(),_K=x0(),TK=bo(),DK="[object Object]",IK=Function.prototype,OK=Object.prototype,GO=IK.toString,PK=OK.hasOwnProperty,RK=GO.call(Object);function LK(e){if(!TK(e)||NK(e)!=DK)return!1;var t=_K(e);if(t===null)return!0;var r=PK.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&GO.call(r)==RK}WO.exports=LK});var $0=v((ufe,jO)=>{function kK(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}jO.exports=kK});var F0=v((cfe,HO)=>{var xK=mf(),$K=Cs(),FK=Object.prototype,MK=FK.hasOwnProperty;function UK(e,t,r){var n=e[t];(!(MK.call(e,t)&&$K(n,r))||r===void 0&&!(t in e))&&xK(e,t,r)}HO.exports=UK});var JO=v((dfe,KO)=>{var BK=F0(),qK=mf();function VK(e,t,r,n){var i=!r;r||(r={});for(var o=-1,a=t.length;++o<a;){var s=t[o],l=n?n(r[s],e[s],s,r,e):void 0;l===void 0&&(l=e[s]),i?qK(r,s,l):BK(r,s,l)}return r}KO.exports=VK});var QO=v((ffe,YO)=>{function GK(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}YO.exports=GK});var ZO=v((pfe,XO)=>{var WK=Li(),zK=ff(),jK=QO(),HK=Object.prototype,KK=HK.hasOwnProperty;function JK(e){if(!WK(e))return jK(e);var t=zK(e),r=[];for(var n in e)n=="constructor"&&(t||!KK.call(e,n))||r.push(n);return r}XO.exports=JK});var M0=v((mfe,eP)=>{var YK=N0(),QK=ZO(),XK=Nu();function ZK(e){return XK(e)?YK(e,!0):QK(e)}eP.exports=ZK});var rP=v((hfe,tP)=>{var eJ=JO(),tJ=M0();function rJ(e){return eJ(e,tJ(e))}tP.exports=rJ});var lP=v((gfe,sP)=>{var nP=k0(),nJ=TO(),iJ=RO(),oJ=kO(),aJ=BO(),iP=E0(),oP=yo(),sJ=VO(),lJ=uf(),uJ=of(),cJ=Li(),dJ=zO(),fJ=df(),aP=$0(),pJ=rP();function mJ(e,t,r,n,i,o,a){var s=aP(e,r),l=aP(t,r),u=a.get(l);if(u){nP(e,r,u);return}var c=o?o(s,l,r+"",e,t,a):void 0,d=c===void 0;if(d){var f=oP(l),p=!f&&lJ(l),m=!f&&!p&&fJ(l);c=l,f||p||m?oP(s)?c=s:sJ(s)?c=oJ(s):p?(d=!1,c=nJ(l,!0)):m?(d=!1,c=iJ(l,!0)):c=[]:dJ(l)||iP(l)?(c=s,iP(s)?c=pJ(s):(!cJ(s)||uJ(s))&&(c=aJ(l))):d=!1}d&&(a.set(l,c),i(c,l,n,o,a),a.delete(l)),nP(e,r,c)}sP.exports=mJ});var U0=v((yfe,cP)=>{var hJ=b0(),gJ=k0(),yJ=EO(),bJ=lP(),vJ=Li(),wJ=M0(),CJ=$0();function uP(e,t,r,n,i){e!==t&&yJ(t,function(o,a){if(i||(i=new hJ),vJ(o))bJ(e,t,a,r,uP,n,i);else{var s=n?n(CJ(e,a),o,a+"",e,t,i):void 0;s===void 0&&(s=o),gJ(e,a,s)}},wJ)}cP.exports=uP});var B0=v((bfe,dP)=>{function EJ(e){return e}dP.exports=EJ});var pP=v((vfe,fP)=>{function AJ(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)}fP.exports=AJ});var gP=v((wfe,hP)=>{var SJ=pP(),mP=Math.max;function NJ(e,t,r){return t=mP(t===void 0?e.length-1:t,0),function(){for(var n=arguments,i=-1,o=mP(n.length-t,0),a=Array(o);++i<o;)a[i]=n[t+i];i=-1;for(var s=Array(t+1);++i<t;)s[i]=n[i];return s[t]=r(a),SJ(e,this,s)}}hP.exports=NJ});var bP=v((Cfe,yP)=>{function _J(e){return function(){return e}}yP.exports=_J});var CP=v((Efe,wP)=>{var TJ=bP(),vP=L0(),DJ=B0(),IJ=vP?function(e,t){return vP(e,"toString",{configurable:!0,enumerable:!1,value:TJ(t),writable:!0})}:DJ;wP.exports=IJ});var AP=v((Afe,EP)=>{var OJ=800,PJ=16,RJ=Date.now;function LJ(e){var t=0,r=0;return function(){var n=RJ(),i=PJ-(n-r);if(r=n,i>0){if(++t>=OJ)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}EP.exports=LJ});var NP=v((Sfe,SP)=>{var kJ=CP(),xJ=AP(),$J=xJ(kJ);SP.exports=$J});var TP=v((Nfe,_P)=>{var FJ=B0(),MJ=gP(),UJ=NP();function BJ(e,t){return UJ(MJ(e,t,FJ),e+"")}_P.exports=BJ});var IP=v((_fe,DP)=>{var qJ=Cs(),VJ=Nu(),GJ=cf(),WJ=Li();function zJ(e,t,r){if(!WJ(r))return!1;var n=typeof t;return(n=="number"?VJ(r)&&GJ(t,r.length):n=="string"&&t in r)?qJ(r[t],e):!1}DP.exports=zJ});var q0=v((Tfe,OP)=>{var jJ=TP(),HJ=IP();function KJ(e){return jJ(function(t,r){var n=-1,i=r.length,o=i>1?r[i-1]:void 0,a=i>2?r[2]:void 0;for(o=e.length>3&&typeof o=="function"?(i--,o):void 0,a&&HJ(r[0],r[1],a)&&(o=i<3?void 0:o,i=1),t=Object(t);++n<i;){var s=r[n];s&&e(t,s,n,o)}return t})}OP.exports=KJ});var RP=v((Dfe,PP)=>{var JJ=U0(),YJ=q0(),QJ=YJ(function(e,t,r,n){JJ(e,t,r,n)});PP.exports=QJ});var on,Tu=k(()=>{"use strict";(function(e){e[e.NotLoaded=0]="NotLoaded",e[e.Initialized=1]="Initialized",e[e.ConfigsLoaded=2]="ConfigsLoaded",e[e.Error=3]="Error"})(on||(on={}))});function kP(e,t,r="PROD"){let n=i=>`ShellSettings_ECS_ClientCache_${e}_${LP.EcsConfigType[i]}_${r}`;return{getData:i=>{let o=t.getItem(n(i));return Promise.resolve(o?JSON.parse(o):void 0)},putData:(i,o)=>(t.setItem(n(i),JSON.stringify(o)),Promise.resolve())}}var LP,XJ,xP=k(()=>{"use strict";LP=we(m0()),XJ=we(p0());});var V0,$P=k(()=>{"use strict";Yd();V0=uu({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 MP,UP,BP,qP,G0,ZJ,hf,FP,W0=k(()=>{"use strict";MP=we(p0()),UP=we(H_()),BP=we(m0()),qP=we(mO()),G0=we(RP());Tu();xP();$P();ZJ=60*1e3,hf=class{clientName;logger;ecsEndpoint;resolveLoadingPromise;loadingPromise=new Promise(t=>this.resolveLoadingPromise=t);_status=on.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"?V0.prodEcsEndpoint:V0.integrationEcsEndpoint}client=new UP.default;init=async({clientVersion:t,getFilters:r,cacheStorage:n=MP.StorageHelper.transientWithGlobalFallback,updateIntervalInMinutes:i,overrideEcsInitParams:o})=>{this.client.telemetryEventAdded.subscribe(this.logger.logEvent),this.client.configUpdated.subscribe(this.handleConfigUpdated);let a=(async()=>{let s=await r();return this.logEvent("FeaturesClient/configRequested",{ecsClientName:this.clientName,filters:s}),s});try{await this.client.initialize({clientName:this.clientName,clientVersion:t??"1.0.0.0",configsToFetch:[BP.EcsConfigType.Default],hosts:[this.ecsEndpoint],initialAppActiveState:!0,getEcsParameters:a,databaseInterface:kP(this.clientName,n,this.endpointType),...o}),this.client.requestUpdate(),this._status===on.NotLoaded&&(this._status=on.Initialized)}catch(s){this._status=on.Error,this.resolveLoadingPromise(),this.logEvent("FeaturesClient/initializationFailed",{ecsClientName:this.clientName,error:s},"Error")}i&&window.setInterval(()=>this.client.requestUpdate(),i*ZJ)};getConfig=t=>{let r=this.getMergedClientConfigByTeamName(t.teamName),n=r?t.extractConfig(r):{};return(0,G0.default)({},t.fallback,n,t.override,FP)};getAllConfigs=()=>this.getMergedClientConfig();getAllConfigsByTeamName=t=>this.getMergedClientConfigByTeamName(t);requestConfigUpdate=()=>{this.client.requestUpdate()};subscribe=(t,r)=>{let n=this.getConfig(t),i=this.client.configUpdated.subscribe(()=>{let o=this.getConfig(t);(0,qP.default)(o,n)||(n={...o},r(o))});return{unsubscribe:()=>i.unsubscribe()}};waitUntilLoaded=async t=>{if(t!==void 0){let r,n=new Promise((i,o)=>{r=window.setTimeout(()=>{o(new Error("Timed out waiting for configuration to load"))},t)});await Promise.race([this.loadingPromise,n]),clearTimeout(r)}else await this.loadingPromise};overrideClientConfig(t){this.logger.logEvent("FeaturesClient/overrideClientConfig",{clientConfigOverride:t}),this.clientConfigOverride=t}undoClientConfigOverride(){this.clientConfigOverride=void 0,this.logger.logEvent("FeaturesClient/undoClientConfigOverride")}getMergedClientConfig=()=>(0,G0.default)({},this.client.getConfig()?.config,this.clientConfigOverride,FP);getMergedClientConfigByTeamName=t=>this.getMergedClientConfig()?.[t];handleConfigUpdated=()=>{let t=this.client.getConfig();if(t===void 0)return;this.resolveLoadingPromise(),this._status=on.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})}},FP=(e,t)=>{if(Array.isArray(t))return t}});var GP=v((Ffe,VP)=>{"use strict";var eY=()=>{let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e};VP.exports=eY});var z0=v((Mfe,zP)=>{var Du=new Proxy(function(){return Du},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Du},apply:function(){return Du},construct:function(){return{}}}),WP=function(){return Du};Object.setPrototypeOf(WP,Du);zP.exports=WP});var KP=v((Ufe,HP)=>{var Iu=new Proxy(function(){return Iu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Iu},apply:function(){return Iu},construct:function(){return{}}}),jP=function(){return Iu};Object.setPrototypeOf(jP,Iu);HP.exports=jP});var tR=v((Bfe,eR)=>{"use strict";var j0=KP(),tY={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},rY={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},nY={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},XP={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},H0={};H0[j0.ForwardRef]=nY;H0[j0.Memo]=XP;function JP(e){return j0.isMemo(e)?XP:H0[e.$$typeof]||tY}var iY=Object.defineProperty,oY=Object.getOwnPropertyNames,YP=Object.getOwnPropertySymbols,aY=Object.getOwnPropertyDescriptor,sY=Object.getPrototypeOf,QP=Object.prototype;function ZP(e,t,r){if(typeof t!="string"){if(QP){var n=sY(t);n&&n!==QP&&ZP(e,n,r)}var i=oY(t);YP&&(i=i.concat(YP(t)));for(var o=JP(e),a=JP(t),s=0;s<i.length;++s){var l=i[s];if(!rY[l]&&!(r&&r[l])&&!(a&&a[l])&&!(o&&o[l])){var u=aY(t,l);try{iY(e,l,u)}catch{}}}}return e}eR.exports=ZP});function nR(e,t,r){let[n,i]=(0,Os.useState)(e.getConfig(t));return(0,Os.useEffect)(()=>{if(!r?.subscribe&&e.status===on.ConfigsLoaded)return;let o=e.subscribe(t,a=>{i(a),r?.subscribe||o.unsubscribe()});return o?.unsubscribe},[]),n}function iR(e){return function(t,r){return nR(e,t,r)}}function oR(e,t,r,n){let i=o=>{let a=nR(e,t,n),s={...o,...a};return Os.default.createElement(r,{...s})};return(0,rR.default)(i,r),i.displayName=`WithFeature(${r.name})`,i}function aR(e,t,r,n){return t.reduce((i,o)=>oR(e,o,i,n),r)}function sR(e){return function(t,r,n){return oR(e,t,r,n)}}var rR,Os,K0=k(()=>{"use strict";rR=we(tR()),Os=we(z0());Tu();});var uR=v((Gfe,lR)=>{var lY=U0(),uY=q0(),cY=uY(function(e,t,r){lY(e,t,r)});lR.exports=cY});var gf=v((Wfe,cR)=>{var dY=la(),fY=bo(),pY="[object Symbol]";function mY(e){return typeof e=="symbol"||fY(e)&&dY(e)==pY}cR.exports=mY});var fR=v((zfe,dR)=>{var hY=yo(),gY=gf(),yY=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,bY=/^\w*$/;function vY(e,t){if(hY(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||gY(e)?!0:bY.test(e)||!yY.test(e)||t!=null&&e in Object(t)}dR.exports=vY});var hR=v((jfe,mR)=>{var pR=sf(),wY="Expected a function";function J0(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(wY);var r=function(){var n=arguments,i=t?t.apply(this,n):n[0],o=r.cache;if(o.has(i))return o.get(i);var a=e.apply(this,n);return r.cache=o.set(i,a)||o,a};return r.cache=new(J0.Cache||pR),r}J0.Cache=pR;mR.exports=J0});var yR=v((Hfe,gR)=>{var CY=hR(),EY=500;function AY(e){var t=CY(e,function(n){return r.size===EY&&r.clear(),n}),r=t.cache;return t}gR.exports=AY});var vR=v((Kfe,bR)=>{var SY=yR(),NY=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,_Y=/\\(\\)?/g,TY=SY(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(NY,function(r,n,i,o){t.push(i?o.replace(_Y,"$1"):n||r)}),t});bR.exports=TY});var CR=v((Jfe,wR)=>{function DY(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}wR.exports=DY});var TR=v((Yfe,_R)=>{var ER=bu(),IY=CR(),OY=yo(),PY=gf(),RY=1/0,AR=ER?ER.prototype:void 0,SR=AR?AR.toString:void 0;function NR(e){if(typeof e=="string")return e;if(OY(e))return IY(e,NR)+"";if(PY(e))return SR?SR.call(e):"";var t=e+"";return t=="0"&&1/e==-RY?"-0":t}_R.exports=NR});var IR=v((Qfe,DR)=>{var LY=TR();function kY(e){return e==null?"":LY(e)}DR.exports=kY});var PR=v((Xfe,OR)=>{var xY=yo(),$Y=fR(),FY=vR(),MY=IR();function UY(e,t){return xY(e)?e:$Y(e,t)?[e]:FY(MY(e))}OR.exports=UY});var LR=v((Zfe,RR)=>{var BY=gf(),qY=1/0;function VY(e){if(typeof e=="string"||BY(e))return e;var t=e+"";return t=="0"&&1/e==-qY?"-0":t}RR.exports=VY});var $R=v((epe,xR)=>{var GY=F0(),WY=PR(),zY=cf(),kR=Li(),jY=LR();function HY(e,t,r,n){if(!kR(e))return e;t=WY(t,e);for(var i=-1,o=t.length,a=o-1,s=e;s!=null&&++i<o;){var l=jY(t[i]),u=r;if(l==="__proto__"||l==="constructor"||l==="prototype")return e;if(i!=a){var c=s[l];u=n?n(c,l,s):void 0,u===void 0&&(u=kR(c)?c:zY(t[i+1])?[]:{})}GY(s,l,u),s=s[l]}return e}xR.exports=HY});var MR=v((tpe,FR)=>{var KY=$R();function JY(e,t,r){return e==null?e:KY(e,t,r)}FR.exports=JY});function VR(e){let{query:t}=(0,qR.default)(window.location.href,!0);return QY(e,t),e}function QY(e,t){let r=YY+e.clientName,n=Object.keys(t).filter(o=>o.startsWith(r));if(!n)return;let i={};n.forEach(o=>{let a=t[o];if(a)try{let s=JSON.parse(a),l=r+GR,u={};if(o===r)u=s;else if(o.startsWith(l)){let c=o.substring(l.length);(0,BR.default)(u,c,s)}(0,UR.default)(i,u)}catch{}}),Object.keys(i).length>0&&e.overrideClientConfig(i)}var UR,BR,qR,GR,YY,WR=k(()=>{"use strict";UR=we(uR()),BR=we(MR()),qR=we(t0());GR=".",YY="ecs"+GR});function bf(e,t,r){let n=VR(new hf(e,t,r));function i(o){(0,yf.useEffect)(()=>{n.init(o)},[])}return{featuresClient:n,createFeature:ZY(n),useFeaturesClientInitParams:i,withFeatures:(o,a,s)=>aR(n,o,a,s)}}function ZY(e){let t=iR(e),r=sR(e);return function(i){let o=V_(i);return o.getConfig=()=>e.getConfig(o),o.isLoaded=()=>e.status===on.ConfigsLoaded,i0.register(o,e.clientName),{useFeature:a=>t(o,a),withFeature:(a,s)=>r(o,a,s),feature:o}}}var XY,yf,Y0=k(()=>{"use strict";XY=we(GP()),yf=we(z0());f0();W0();Tu();K0();WR();o0();});var zR=k(()=>{"use strict";f0();W0();Y0();Tu();K0();ef();a0();});function vf(e){return{logEvent:(t,r,n)=>{switch(n){case"Error":(0,Ps.trackErrorTrace)(e,{eventName:t,eventData:r});break;case"Warning":(0,Ps.trackWarningTrace)(e,{eventName:t,eventData:r});break;default:(0,Ps.trackInfoTrace)(e,{eventName:t,eventData:r});break}}}}var Ps,Q0=k(()=>{"use strict";Ps=we(na());});var Cpe,Epe,Ape,jR=k(()=>{"use strict";zR();Q0();({featuresClient:Cpe,createFeature:Epe,useFeaturesClientInitParams:Ape}=bf("PowerApps-Shell-Test",vf("shell-features")))});var JR=v((Npe,KR)=>{var Ou=new Proxy(function(){return Ou},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Ou},apply:function(){return Ou},construct:function(){return{}}}),HR=function(){return Ou};Object.setPrototypeOf(HR,Ou);KR.exports=HR});var eQ,tQ,YR=k(()=>{"use strict";au();eQ=we(JR()),tQ=we(na());});var QR=k(()=>{"use strict";jR();Q0();YR();});var kpe,Rs,xpe,XR=k(()=>{"use strict";QR();Y0();({featuresClient:kpe,createFeature:Rs,useFeaturesClientInitParams:xpe}=bf("PowerApps-MakerPortal",vf("powerapps-features")))});var ZR,e2,Upe,Bpe,qpe,Vpe,X0=k(()=>{"use strict";q_();XR();({feature:ZR}=Rs({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:ws.enableAutoInsertionOfCellInRow}})),{feature:e2}=Rs({teamName:"MakerPortal",owners:["aansu"],description:"Enable the one grid events for form designer",createdOn:"08/21/2024",fallback:{enableOneGridEventsForFormDesigner:ws.enableOneGridEvents}}),{feature:Upe}=Rs({teamName:"MakerPortal",owners:["adekulkarni"],description:"Disables PBI components and cleans them up from the form",createdOn:"01/03/2023",fallback:{enableFallbackFormTemplate:ws.disablePBIComponents}}),{feature:Bpe}=Rs({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:ws.enableAgentResponse}}),{feature:qpe,useFeature:Vpe}=Rs({teamName:"MakerPortal",owners:["aansu"],description:"Enables delayed localization of custom control",createdOn:"06/08/2025",fallback:{enableDelayedLocalizationForCustomControls:ws.enableDelayedLocalizationForCustomControls}})});var n2=v((Wpe,r2)=>{var Pu=new Proxy(function(){return Pu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Pu},apply:function(){return Pu},construct:function(){return{}}}),t2=function(){return Pu};Object.setPrototypeOf(t2,Pu);r2.exports=t2});var jt,vo=k(()=>{"use strict";ct();et();zt();fu();se();St();jt=class extends te{static HighestUsedIndexByClass=new Map;get colspan(){let t=this.getProperty(y.colspan);return P.IsNullOrUndefined(t)?null:parseInt(t,10)}set colspan(t){P.IsNullOrUndefined(t)||this.setProperty(y.colspan,String(t))}constructor(t,r){super(t,r)}get id(){let t=this.getProperty(y.id);return t==null?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new U(t.substr(1,t.length-2)):new U(t)}set id(t){this.setProperty(y.id,`{${t.ToString()}}`)}set labelId(t){this.setProperty(y.labelId,`{${t.ToString()}}`)}get labelId(){let t=this.getProperty(y.labelId);return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new U(t.substr(1,t.length-2)):new U(t)}get Name(){return this.getProperty(y.Name)}set Name(t){this.setProperty(y.Name,t)}setDisplayName(t,r){for(let i of this.getAllLabels())if(+i.getProperty(y.languagecode)===r){i.setProperty(y.description,t);return}let n=new te(C.formLabel,null);n.setProperty(y.description,t),n.setProperty(y.languagecode,String(r)),this.addGrandChild("labels",n)}getDisplayName(t){for(let r of this.getAllLabels())if(+r.getProperty(y.languagecode)===t)return r.getProperty(y.description)}getAllLabels(){let t=this.getChildren("labels");return t.length!==1?[]:t[0].getChildren("label")}get isLocked(){return+this.getProperty(y.locklevel)==1}set isLocked(t){!this.IsUnboundControl&&this.setProperty(y.locklevel,t?"1":"0")}get availableforphone(){return this.getProcessedValue(y.availableforphone)}set availableforphone(t){P.IsNullOrUndefined(t)||!this.IsAllowedUBCForAvailableOnPhone()||this.setProperty(y.availableforphone,String(t))}get visible(){return this.getProcessedValue(y.visible)}set visible(t){P.IsNullOrUndefined(t)||!this.IsAllowedUBCForVisibleByDefault()||this.setProperty(y.visible,String(t))}isLockLevelSettable(){return!this.IsUnboundControl}get showlabel(){return this.getProcessedValue(y.showlabel)}set showlabel(t){P.IsNullOrUndefined(t)||this.setProperty(y.showlabel,String(t))}isAvailableForPhoneSettable(){return this.IsAllowedUBCForAvailableOnPhone()}isVisibleSettable(){return this.IsAllowedUBCForVisibleByDefault()}getProcessedValue(t){let r=this.getProperty(t);return P.IsNullOrUndefined(r)||this.getProperty(t)==="true"}get readonly(){let t=this.getFirstChild(C.formControl);return t?t.disabled:!1}set readonly(t){let r=this.getFirstChild(C.formControl);r&&(r.disabled=t)}get allowfilteroff(){let t=this.getFirstChild(C.formControl);if(t)return t.getParam(y.AllowFilterOff)==="true"}set allowfilteroff(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AllowFilterOff,t)}get autoresolve(){let t=this.getFirstChild(C.formControl);if(t)return t.getParam(y.AutoResolve)==="true"}set autoresolve(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AutoResolve,t)}get defaultviewid(){let t=this.getFirstChild(C.formControl);return t?t.getParam(y.DefaultViewId):q.EmptyString}set defaultviewid(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DefaultViewId,t)}get dependentattributename(){let t=this.getFirstChild(C.formControl);return t?t.getParam(y.DependentAttributeName):q.EmptyString}set dependentattributename(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DependentAttributeName,t)}get dependentattributetype(){let t=this.getFirstChild(C.formControl);return t?t.getParam(y.DependentAttributeType):q.EmptyString}set dependentattributetype(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DependentAttributeType,t)}get disablequickfind(){let t=this.getFirstChild(C.formControl);if(t)return t.getParam(y.DisableQuickFind)==="true"}set disablequickfind(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DisableQuickFind,t)}get disableviewpicker(){let t=this.getFirstChild(C.formControl);if(t)return t.getParam(y.DisableViewPicker)==="true"}set disableviewpicker(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DisableViewPicker,t)}get filterrelationshipname(){let t=this.getFirstChild(C.formControl);return t?t.getParam(y.FilterRelationshipName):q.EmptyString}set filterrelationshipname(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.FilterRelationshipName,t)}get availableviewids(){let t=this.getFirstChild(C.formControl);return t?t.getParam(y.AvailableViewIds):q.EmptyString}set availableviewids(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AvailableViewIds,t)}get IsUnboundControl(){let t=this.getFirstChild(C.formControl);if(t&&t.ClassId){let r=tt.getUniqueIdentifierForControl(t);return!P.IsNullOrUndefined(r)&&tt.isUnboundFormControlByIdentifier(r)}else return!1}IsAllowedUBCForAvailableOnPhone(){let t=this.getFirstChild(C.formControl);if(t){let n=tt.getUniqueIdentifierForControl(t).guidString,i=n===G.GridControl||n===G.TimeLineControl||n===G.TimeLineControlUC;return this.IsUnboundControl?i:!0}return this.NodeName===C.formSection||this.NodeName===C.formTab}IsAllowedUBCForVisibleByDefault(){let t=this.getFirstChild(C.formControl);if(t){let n=tt.getUniqueIdentifierForControl(t).guidString,i=n===G.MapsControl||n===G.WebResourceHtmlControl||n===G.WebResourceImageControl||n===G.IframeControl||n===G.SocialInsightControl;return this.IsUnboundControl?i:!0}else return!0}get events(){let t=this.getChildren(C.formEvents);return t.length===1?t[0].getAllChildren():[]}addEvent(t){this.addGrandChild(C.formEvents,t)}getUsedNodeNameSet(t){return null}getHighestIndexById(t,r){return null}}});var Ls,Z0=k(()=>{"use strict";zt();se();St();Ls=class extends te{constructor(t,r){super(C.dependency,t),q.IsNullOrEmpty(r)||this.setDefaultProperties(r)}set id(t){this.setProperty(y.id,t)}get id(){return this.getProperty(y.id)}setDefaultProperties(t){this.id=t}}});var i2,ks,ey=k(()=>{"use strict";et();Z0();se();St();vo();(function(e){e[e.Form=0]="Form",e[e.Cell=1]="Cell",e[e.Tab=2]="Tab",e[e.Control=3]="Control"})(i2||(i2={}));ks=class extends jt{constructor(t,r){super(C.formEvent,t),r&&(this.eventName=r,this.application="false",this.active="false")}set eventName(t){this.setProperty(y.Name,t)}get eventName(){return this.getProperty(y.Name)}set application(t){this.setProperty(y.application,t)}get application(){return this.getProperty(y.application)}set attribute(t){this.setProperty(y.EventAttribute,t)}get attribute(){return this.getProperty(y.EventAttribute)}set relationship(t){this.setProperty(y.Relationship,t)}get relationship(){return this.getProperty(y.Relationship)}set control(t){this.setProperty(y.Control,t)}get control(){return this.getProperty(y.Control)}set active(t){this.setProperty(y.EventActive,t)}get active(){return this.getProperty(y.EventActive)}getAllHandlers(){let t=this.getChildren(C.EventHandlers);return t&&t.length?t[0].getChildren(C.handler):[]}getAllDependencies(){let t=this.getChildren(C.formDependencies);return t.length===0?[]:t[0].getAllChildren()}setDependencies(t){let r=this.getFirstChild(C.formDependencies);if(P.IsNullOrUndefined(r)){if(t.length===0)return;this.addChild(new te(C.formDependencies,this)),r=this.getFirstChild(C.formDependencies)}if(t.length===0)r.getParentNode().deleteChild(r);else{r.deleteAllChildren();for(let n of t)r.addChild(new Ls(r,n.toString()))}}}});var _n,Ru=k(()=>{"use strict";ct();Bl();et();ra();se();St();An();_n=class extends te{previewVersion;constructor(t){super(C.formControl,t)}updatePreview(){this.previewVersion=Date.now()}get ClassId(){let t=this.getProperty(y.classid);return t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t)}set ClassId(t){this.setProperty(y.classid,`{${t.ToString()}}`)}get dataFieldName(){return this.getProperty(y.datafieldname)}set dataFieldName(t){this.setProperty(y.datafieldname,t)}set id(t){this.setProperty(y.id,t)}get id(){return this.getProperty(y.id)}get UniqueId(){let t=this.getProperty(y.uniqueid);return P.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t))}set UniqueId(t){this.setProperty(y.uniqueid,`{${t.ToString()}}`)}get isRequired(){return this.getProperty(y.isRequired)==="true"}set isRequired(t){P.IsNullOrUndefined(t)||this.setProperty(y.isRequired,String(t))}get disableMru(){return this.getParam(y.DisableMru)==="true"}set disableMru(t){P.IsNullOrUndefined(t)||this.setParameter(y.DisableMru,t)}get useMFDForCreate(){return this.getParam(y.UseMFDForCreate)==="true"}set useMFDForCreate(t){P.IsNullOrUndefined(t)||this.setParameter(y.UseMFDForCreate,t)}get useMFDForEdit(){return this.getParam(y.UseMFDForEdit)==="true"}set useMFDForEdit(t){P.IsNullOrUndefined(t)||this.setParameter(y.UseMFDForEdit,t)}get disabled(){return this.getProperty(y.disabled)==="true"}set disabled(t){P.IsNullOrUndefined(t)||this.setProperty(y.disabled,String(t))}get indicationOfSubgrid(){return this.getProperty(y.indicationOfSubgrid)==="true"}set indicationOfSubgrid(t){this.setProperty(y.indicationOfSubgrid,String(t))}getAllParameters(){let t=new er,r=this.getFirstChild(y.parameters);return r&&r.getAllChildren().forEach(n=>{if(n){let i=n.getAllChildren(),o=i&&i.length>0&&i[0];o&&t.add(n.getNodeName(),o.getNodeName())}}),t}setParameter(t,r){let n=!1;r===null&&(n=!0);let i=(Ri.StartTag+r).toString(),o=this.parametersNode;if(o){let a=o.findFirst(s=>s&&s.getNodeName()===t);if(a)if(n){this.deleteFirstGrandChildOfName(C.controlParameters,a);return}else{let s=a.getAllChildren();s&&s.length>0&&s[0]?s[0].setNodeName(i):a.addChild(new te(i,a))}else n||(a=new te(t,o),a.addChild(new te(i,a)),o.addChild(a))}else if(!n){o=new te("parameters",this);let a=new te(t,o);a.addChild(new te(i,a)),o.addChild(a),this.addChild(o)}}getParam(t){if(this.parametersNode){let r=this.parametersNode.findFirst(n=>n&&n.getNodeName()===t);if(r){let n=r.getAllChildren(),i=n&&n.length>0&&n[0];if(i){let o=i.getNodeName();return o.charAt(0)===Ri.StartTag?o.substring(1):o}}}return null}get parametersNode(){let t=this.getChildren(y.parameters);return t.length===0?null:t[0]}async serializeParameters(t,r){let n=new er;switch(this.ClassId.guidString.toUpperCase()){case N.LookupControl:if(t&&t.getKeys())if(t.getKeys().forEach(a=>{n.add(a,this.getParam(a))}),t&&t.containsKey("DefaultViewId")){let a=this.getParam("DefaultViewId").replace("{","").replace("}","");n.upsert("DefaultViewId",a)}else{let a=this.getParent(),s=await r.formModelService.lookupControlService.populateDefaultView(this,a.getParentForm().entityName);s&&s.id&&n.upsert("DefaultViewId",s.id.replace("{","").replace("}",""))}break;default:t&&t.getKeys()&&t.getKeys().forEach(a=>{n.add(a,this.getParam(a))});break}let i=n.getInternalObject(),o=[];for(let a in i)i.hasOwnProperty(a)&&o.push({Name:a,Value:i[a]});return o}getIsUnbound(){return this.getProperty(y.isUnbound)==="true"}getAttributeTypeFromClassId(t){if(t)switch(t.toUpperCase()){case N.BooleanControl:case N.CheckboxControl:return 0;case N.DateTimeControl:return 2;case N.DecimalControl:return 3;case N.FloatingNumberControl:return 4;case N.IntegerControl:case N.DurationControl:case N.LanguageControl:case N.TimezoneControl:return 5;case N.LookupControl:return 6;case N.CurrencyControl:return 8;case N.PartyListControl:return 10;case N.ChoiceControl:case N.RelationshipRoleChoiceControl:return 11;case N.ChoiceStatusControl:return 13;case N.TextAreaControl:case N.TextboxControl:case N.LabelControl:case N.EmailAddressControl:case N.UrlControl:case N.TickerControl:case N.ButtonControl:case N.PhoneNumberControl:return 14;case N.ChoicesControl:return 24;default:return}return 14}async toJSON(t){let r=this.getParent(),n=t&&t.formModelService&&t.formModelService.getFormType()===dt.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 xs,ty=k(()=>{"use strict";zt();jo();Ru();se();St();xs=class extends _n{constructor(t){super(t)}get targetEntityType(){return this.getParam(y.targetEntityType)||q.EmptyString}set targetEntityType(t){this.setParameter(y.targetEntityType,t)}get viewId(){return q.StripBraces(this.getParam(y.viewId))||q.EmptyString}set viewId(t){this.setParameter(y.viewId,q.AddBraces(t))}get viewIds(){return this.getParam(y.viewIds)||q.EmptyString}set viewIds(t){this.setParameter(y.viewIds,t)}get relationshipName(){return this.getParam(y.RelationshipName)||q.EmptyString}set relationshipName(t){this.setParameter(y.RelationshipName,t)}get isUserView(){return q.IsStrictTrue(this.getParam(y.isUserView))}set isUserView(t){this.setParameter(y.isUserView,t.toString())}get enableViewPicker(){return q.IsStrictTrue(this.getParam(y.enableViewPicker))}set enableViewPicker(t){this.setParameter(y.enableViewPicker,t)}get autoExpand(){return this.getParent().autoexpand&&this.getParam(y.autoExpand)===y.Auto}set autoExpand(t){let r=this.getParent();this.setParameter(y.autoExpand,t?y.Auto:y.Fixed),r.autoexpand=t}get recordsPerPage(){return this.getParam(y.recordsPerPage)?Number(this.getParam(y.recordsPerPage)):Number(y.RecordsPerPageRAControlDefault)}set recordsPerPage(t){this.setParameter(y.recordsPerPage,String(t))}get enableQuickFind(){return q.IsStrictTrue(this.getParam(y.enableQuickFind))}set enableQuickFind(t){this.setParameter(y.enableQuickFind,t)}get teamTemplateId(){return q.StripBraces(this.getParam(y.teamTemplateId))||q.EmptyString}set teamTemplateId(t){this.setParameter(y.teamTemplateId,q.AddBraces(t))}get chartId(){return this.getParam(y.visualizationId)||q.EmptyString}set chartId(t){this.setParameter(y.visualizationId,t)}get enableChartPicker(){return q.IsStrictTrue(this.getParam(y.enableChartPicker))}set enableChartPicker(t){this.setParameter(y.enableChartPicker,t)}get chartGridMode(){switch(this.getParam(y.chartGridMode)){case nn.Chart:return nn.Chart;case nn.Grid:return nn.Grid;default:return nn.All}}set chartGridMode(t){this.setParameter(y.chartGridMode,t)}updateChartGridMode(t){t?this.chartGridMode=nn.Chart:this.chartGridMode=this.enableChartPicker?nn.All:nn.Grid}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case y.targetEntityType:n.getAllChildren()[0].setNodeName("<"+r.targetEntityType);break;case y.viewId:n.getAllChildren()[0].setNodeName("<"+q.AddBraces(r.viewId));break;case y.isUserView:n.getAllChildren()[0].setNodeName("<"+r.isUserView);break;case y.enableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.enableViewPicker);break;case y.RelationshipName:let i=n.getAllChildren(),o="<"+r.relationshipName;i.length?n.getAllChildren()[0].setNodeName(o):n.addChild(new te(o,n));break;default:break}}updateControlDescription(t){let r=t.getControlDescriptionByForControl(this.UniqueId);if(r){let n=r.customControls;for(let i=0;i<n.length;i++){let o=n[i].getParameters().get(qt.dataset)?n[i].getParameters().get(qt.dataset)[0]:null;if(o){let a=o.getAllChildren();this.updateDefaultProperties(a,this)}else{let a=n[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(a,this)}}}}}});var $s,ry=k(()=>{"use strict";zt();jo();Ru();se();$s=class extends _n{constructor(t){super(t)}get defaultViewId(){return q.StripBraces(this.getParam(y.DefaultViewId))||q.EmptyString}set defaultViewId(t){this.setParameter(y.DefaultViewId,q.AddBraces(t))}get autoResolve(){return q.IsStrictTrue(this.getParam(y.AutoResolve))}set autoResolve(t){this.setParameter(y.AutoResolve,t)}get disableQuickFind(){return q.IsStrictTrue(this.getParam(y.DisableQuickFind))}set disableQuickFind(t){this.setParameter(y.DisableQuickFind,t)}get disableViewPicker(){return q.IsStrictTrue(this.getParam(y.DisableViewPicker))}set disableViewPicker(t){this.setParameter(y.DisableViewPicker,t)}get allowFilterOff(){return q.IsStrictTrue(this.getParam(y.AllowFilterOff))}set allowFilterOff(t){this.setParameter(y.AllowFilterOff,t)}get disableMru(){return q.IsStrictTrue(this.getParam(y.DisableMru))}set disableMru(t){this.setParameter(y.DisableMru,t)}get dependentAttributeName(){return this.getParam(y.DependentAttributeName)||q.EmptyString}set dependentAttributeName(t){this.setParameter(y.DependentAttributeName,t)}get dependentAttributeType(){return this.getParam(y.DependentAttributeType)||q.EmptyString}set dependentAttributeType(t){this.setParameter(y.DependentAttributeType,t)}get filterRelationshipName(){return this.getParam(y.FilterRelationshipName)||q.EmptyString}set filterRelationshipName(t){this.setParameter(y.FilterRelationshipName,t)}get availableViewIds(){return this.getParam(y.AvailableViewIds)||q.EmptyString}set availableViewIds(t){this.setParameter(y.AvailableViewIds,t)}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case y.datafieldname:case y.bindAttribute:n.getAllChildren()[0].setNodeName("<"+r.dataFieldName);break;case y.DefaultViewId:n.getAllChildren()[0].setNodeName("<"+q.AddBraces(r.defaultViewId));break;case y.AllowFilterOff:n.getAllChildren()[0].setNodeName("<"+r.allowFilterOff);break;case y.DisableQuickFind:n.getAllChildren()[0].setNodeName("<"+r.disableQuickFind);break;case y.DisableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.disableViewPicker);break;case y.FilterRelationshipName:n.getAllChildren()[0].setNodeName("<"+r.filterRelationshipName);break;case y.DependentAttributeName:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeName);break;case y.DependentAttributeType:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeType);break;case y.AvailableViewIds:n.getAllChildren()[0].setNodeName("<"+r.availableViewIds);break;case y.DisableMru:n.getAllChildren()[0].setNodeName("<"+r.disableMru);break;case y.AutoResolve:n.getAllChildren()[0].setNodeName("<"+r.autoResolve);break;default:break}}updateControlDescription(t){let r=t.getControlDescriptionByForControl(this.UniqueId);if(r){let n=r.customControls;for(let i=0;i<n.length;i++){let o=n[i].getParameters().get(qt.value)?n[i].getParameters().get(qt.value)[0]:null;if(o){let a=o.getAllChildren();this.updateDefaultProperties(a,this)}else{let a=n[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(a,this)}}}}}});var o2,ny,Ar,Lu=k(()=>{"use strict";o2=we(n2());vo();se();et();ct();ey();Ru();fu();c0();zg();An();ra();gs();ty();ry();iy();is();ny="_",Ar=class e extends jt{fieldPlaceholder;fieldRequiredLevel;isNewField;cellColType;dependentFields=[];constructor(t){super(C.formCell,t),this.isNewField=!1}get cellType(){return this.cellColType}set cellType(t){this.cellColType=t}setDefaultProperties(t){this.showlabel=t,this.isLocked=!1,P.IsNullOrUndefined(this.getProperty(y.id))&&(this.id=new U(U.NewGuid()))}addControl(t,r,n,i,o,a,s){n instanceof _n?this.addChild(n):n instanceof U&&this.addChild(this.getControlWithControlSpecificProperties(t,r,n,i,o,a,s))}removeControl(){return this.deleteChild(this.control)>=0}get isIndependent(){if(!P.IsNullOrUndefined(this.control))return P.IsNullOrUndefined(this.control.dataFieldName)?P.IsNullOrUndefined(this.control.id)?!0:!ia.dependencyFieldCount.containsKey(this.control.id):!ia.dependencyFieldCount.containsKey(this.control.dataFieldName)}createOnLoadEvent(){this.addEvent(new ks(this,iu.onLoad))}get dependencies(){let t=this.getChildren(C.formEvents);for(let r of t){let n=r.getChildren(C.formEvent);for(let i of n)this.buildDependencyList(i,this.dependentFields)}return this.dependentFields}getNextAvailableControlName(t,r,n,i){let o;if(i&&zd[i])o=zd[i].replace(/ /g,ny)+ny;else{o="Control_";let u=new Error("Control class id does not exist or is undefined");(0,o2.trackErrorTrace)(ir,{eventName:`${n_}/getNextAvailableControlName`},u)}let a="new_",s=this.getHighestIndexById(t,i)+1,l=`${o}${a}${s}`;for(;n.has(l);)s++,l=`${o}${a}${s}`;return l}getUnboundControlProperties(t){e.prototype.setProperty.call(t,y.isUnbound,"true"),e.prototype.setProperty.call(t,y.isRequired,"false")}getControlWithControlSpecificProperties(t,r,n,i,o,a,s){let l;o===an.Grid?(l=new xs(this),l.indicationOfSubgrid=!0):o===an.Lookup?l=new $s(this):l=new _n(this);let u=n.guidString,c=a||this.getNextAvailableControlName(t,i,this.getUsedNodeNameSet(t),u);if(e.prototype.setProperty.call(l,y.id,c),l.ClassId=n,!P.IsNullOrUndefined(s)&&(l.UniqueId=s),!a&&r)this.getUnboundControlProperties(l);else{let d=tt.getUniqueIdentifierForControl(l);P.IsNullOrUndefined(d)||(tt.getControlDataTypeByControlOrUniqueId(d)===ee.QuickFormCollectionControl||!tt.isUnboundFormControlByIdentifier(d)?o!==an.Grid&&a&&u!==N.IframeControl&&u!==N.SubgridControl&&u!==N.ReferencePanelSubgridControl&&(l.dataFieldName=a,e.prototype.setProperty.call(l,y.disabled,"false")):(this.rowspan=tt.GetRowSpan(l),(tt.getControlDataTypeByControlOrUniqueId(d)===ee.NotesControl||tt.getControlDataTypeByControlOrUniqueId(d)===ee.TimeLineControl)&&(e.prototype.setProperty.call(l,y.disabled,"false"),l.id=ee.NotesControl)),(tt.getUnboundControlNameFromIdentifier(n)===ee.SubGridControl||tt.getUnboundControlNameFromIdentifier(n)===ee.NotesControl||tt.getUnboundControlNameFromIdentifier(n)===ee.TimeLineControl)&&(this.availableforphone=!0))}return l}buildDependencyList(t,r){if(P.IsNullOrUndefined(t))return;let n=t.getAllChildren();for(let i of n){let o=i.getAllChildren();for(let a of o){let s=a.GetPropertyByParameter(y.id);a.getNodeName()===C.dependency&&s?r.push(s):this.buildDependencyList(a,r)}}}get control(){return this.getFirstChild(C.formControl)}set rowspan(t){this.setProperty(y.rowspan,String(t))}get rowspan(){let t=this.getProperty(y.rowspan);return P.IsNullOrUndefined(t)?1:parseInt(t,10)}set autoexpand(t){this.setProperty(y.auto,String(t))}get autoexpand(){return this.getProperty(y.auto)==="true"}set colspan(t){let r=Number(l0.ONE_COLUMN),n=Number(l0.FOUR_COLUMN);P.IsNullOrUndefined(t)||t>n||t<r||this.setProperty(y.colspan,String(t))}get colspan(){let t=this.getProperty(y.colspan);return P.IsNullOrUndefined(t)?1:parseInt(t,10)}getParentRow(){return this.getAncestor(C.formRow)}getParentSection(){return this.getAncestor(C.formSection)}getParentTab(){return this.getAncestor(C.formTab)}getParentForm(){return this.getAncestor(C.form)}isInHeader(){let t=this.getAncestor(C.formHeader);return!P.IsNullOrUndefined(t)}isInFooter(){let t=this.getAncestor(C.formFooter);return!P.IsNullOrUndefined(t)}isEmpty(){return P.IsNullOrUndefined(this.control)&&!this.IsUserSpacer}getHeaderFooter(){return this.isInHeader()?this.getAncestor(C.formHeader):this.isInFooter()?this.getAncestor(C.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(y.userspacer);return P.IsNullOrUndefined(t)?!1:t==="true"}SetUserSpacer(){this.setProperty(y.userspacer,"true")}ClearUserSpacer(){this.setProperty(y.userspacer,"false")}get columns(){let t=this.getProperty(y.columnName);return P.IsNullOrUndefined(t)?null:parseInt(t,10)}getColumnLayoutValue(t){let r;switch(t){case Ge.TWO_COLUMN:r="11";break;case Ge.THREE_COLUMN:r="111";break;case Ge.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(!P.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();P.IsNullOrUndefined(t)||(t.autoExpandCell=this,t.tabContainsAutoExpandControl=!0)}isCellRequiredOrLocked(t,r,n){let i=this.getParentForm();if(this?.control){if(this.IsUserSpacer)return!1;{if(this.isLocked||r().has(this.control.dataFieldName))return!0;let o=i.isDuplicateCell(this,n),a=this.getRequiredLevel(t);if((a===no.ApplicationRequired||a===no.SystemRequired)&&!o||this.isCellLockedByExternal(t)&&!o)return!0}}return!1}getRequiredLevel(t){return!this.control?.dataFieldName||!this.control?.id||this.IsNewField||!this.control?.ClassId?no.None:t.getEntityAttributeByName(this.control.dataFieldName)?.requiredLevel?.toString()??no.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()===C.formCell){let i=n;i.control&&i!==this&&r.add(n.control.id)}return!1}),r}getHighestIndexById(t,r){let n=t.findAll(o=>o.getNodeName()===C.formCell&&o.control&&o.control.ClassId.guidString===r),i=0;return n.forEach(o=>{i=Math.max(this.parseControlNameIndex(o.control.id),i)}),i}parseControlNameIndex(t){let r=t.length-1,n=0;for(;r>0&&parseInt(t.charAt(r),10);)r--;return r>0&&r!==t.length-1&&t.charAt(r)===ny&&(r++,n=parseInt(t.substr(r,t.length-r),10)),n}}});var Fs,oy=k(()=>{"use strict";zt();se();St();Fs=class extends te{isInternal;constructor(t,r,n,i){super(C.library,t),this.isInternal=!!i,q.IsNullOrEmpty(n)||(this.name=r,this.libraryUniqueId=n)}get libraryUniqueId(){let t=this.getProperty(y.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(y.libraryUniqueId,t)}get name(){return this.getProperty(y.libraryName)}set name(t){this.setProperty(y.libraryName,t)}get displayName(){return this.getProperty(y.displayName)}set displayName(t){this.setProperty(y.displayName,t)}get description(){return this.getProperty(y.description)}set description(t){this.setProperty(y.description,t)}}});var ca,ay=k(()=>{"use strict";et();Lu();se();St();ca=class extends te{isRowAddedOnDragOver;constructor(t){super(C.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 P.IsNullOrUndefined(t)?!1:this.deleteChild(t)>=0}insertCellAtIndex(t,r){return P.IsNullOrUndefined(t)?!1:(this.insertChildAtIndex(t,r),!0)}isEmpty(){return!this.cells||this.cells.every(t=>t.isEmpty())}getParentSection(){return this.getAncestor(C.formSection)}insertPaddingCellAtIndex(t){let r=new Ar(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(C.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 rQ(e){switch(e){case oa.Left:return sa.Left;case oa.Right:return sa.Right;case oa.Center:return sa.Center;default:return sa.Left}}function nQ(e){switch(e){case bs.Left:return vs.Left;case bs.Top:return vs.Top;default:return vs.Left}}function a2(e){switch(e){case 1:return 1;case 2:return 11;case 3:return 111;case 4:return 1111;default:return 1}}var iQ,ei,ku=k(()=>{"use strict";d0();ct();et();zt();X0();Lu();se();An();vo();ay();iQ=115,ei=class e extends jt{colSpan=1;constructor(t,r){super(t,r)}getSectionType(){let t;switch(this.columns){case 1:t=Ge.ONE_COLUMN;break;case 11:t=Ge.TWO_COLUMN;break;case 111:t=Ge.THREE_COLUMN;break;case 1111:t=Ge.FOUR_COLUMN;break;default:t=this.colSpan-1}return t}setUniqueName(){let t=this.getParentTab(),r=Ue.namePrefix;if(t){let n=t.Name,i=t.TotalSectionsCount+1;r=n+Ue.namePrefix+i.toString()}else r+=Math.floor(Math.random()*1e3);this.setProperty(y.Name,r)}initializeDefaultProperties(t,r,n){if(n===Ge.REFERENCE_PANEL){this.addProperty(y.rowheight,"25");let i=`${Ue.referencePanelNamePrefix}${U.NewGuid()}${Ue.namePrefix}`;this.addProperty(y.Name,i)}else this.setUniqueName();if(this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.IsUserDefined,Ue.IsUserDefined),this.addProperty(y.locklevel,Ue.LockLevel),this.addProperty(y.showlabel,Ue.ShowLabel),this.addProperty(y.showbar,Ue.ShowBar),this.addProperty(y.layout,Ue.Layout),this.addProperty(y.Fieldlabelalignment,Ue.labelAlignment),this.addProperty(y.Fieldlabelposition,Ue.labelPosition),P.IsNullOrUndefined(n))this.addProperty(y.columnName,Ue.columns);else{let i=this.getColumnLayoutValue(n);this.addProperty(y.columnName,i)}this.addProperty(y.LabelWidth,Ue.LabelWidth),this.setDisplayName(r,t)}getColumnLayoutValue(t){let r;switch(t){case Ge.TWO_COLUMN:r="11";break;case Ge.THREE_COLUMN:r="111";break;case Ge.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 P.IsNullOrUndefined(this.columns)?t=this.ColSpan:this.columns.toString().split(q.EmptyString).forEach(r=>{t+=parseInt(r,10)}),t}get ColSpan(){return this.colSpan}initializeRow(t){if(t>0&&t<5){let r=new ca(null);if(this.addGrandChild(C.formRows,r),ZR.getConfig().enableAutoInsertionOfCellInRow)for(let n=0;n<t;n++){let i=new Ar(r);i.setDefaultProperties(!1),r.addCell(i)}}}initialize(t,r,n){this.initializeDefaultProperties(t,r,n),n===Ge.REFERENCE_PANEL&&(n=Ge.ONE_COLUMN),this.initializeRow(n+1)}setColSpan(t){this.colSpan=t}appendRow(t){this.addGrandChild(C.formRows,t)}insertRowAtIndex(t,r){this.addGrandChildAtIndex(C.formRows,t,r)}insertRowsAtIndex(t,r){if(t&&t.length>0)for(let n=0;n<t.length;n++)this.addGrandChildAtIndex(C.formRows,t[n],r+n)}indexOfRow(t){return this.rows.indexOf(t)}deleteRow(t){return this.deleteFirstGrandChildOfName(C.formRows,t)}deleteRows(t,r){this.deleteGrandChildren(C.formRows,t,r)}get rows(){return this.getRows()}getRows(){let t=this.getChildren(C.formRows);return t.length===0?[]:t[0].getChildren(C.formRow)}get columns(){let t=this.getProperty(y.columnName),r=P.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 a2(n)}return r}set columns(t){P.IsNullOrUndefined(t)||this.setProperty(y.columnName,String(t))}get rowHeight(){let t=this.getProperty(y.rowheight);return P.IsNullOrUndefined(t)?null:parseInt(t,10)}set rowHeight(t){this.setProperty(y.rowheight,String(t))}set autoexpand(t){this.setProperty(y.autoExpand.toLowerCase(),String(t))}get autoexpand(){return this.getProperty(y.autoExpand.toLowerCase())==="true"}get isUserDefined(){return+this.getProperty(y.IsUserDefined)!=0}set isUserDefined(t){t?this.setProperty(y.IsUserDefined,"1"):this.setProperty(y.IsUserDefined,"0")}getParentColumn(){return this.getAncestor(C.formColumn)}getParentTab(){return this.getAncestor(C.formTab)}get hasMultiColumnRow(){return this.getColumnCountValue()>1}get showlabel(){return this.getProperty(y.showlabel)==="true"}set showlabel(t){P.IsNullOrUndefined(t)||this.setProperty(y.showlabel,String(t))}get fieldLabelAlignment(){let t=Ue.labelAlignment,r=this.getProperty(y.Fieldlabelalignment);return P.IsNullOrUndefined(r)?t:r}set fieldLabelAlignment(t){P.IsNullOrUndefined(t)||this.setProperty(y.Fieldlabelalignment,t)}get fieldLabelPosition(){let t=this.getProperty(y.Fieldlabelposition);return P.IsNullOrUndefined(t)?Ue.labelPosition:t}set fieldLabelPosition(t){P.IsNullOrUndefined(t)||this.setProperty(y.Fieldlabelposition,String(t))}get showbar(){return this.getProperty(y.showbar)==="true"}set showbar(t){P.IsNullOrUndefined(t)||this.setProperty(y.showbar,String(t))}get labelwidth(){let t=+this.getProperty(y.LabelWidth);return t===0?iQ:t}set labelwidth(t){P.IsNullOrUndefined(t)||t>283&&t<57||this.setProperty(y.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:rQ(this.fieldLabelAlignment),Position:nQ(this.fieldLabelPosition)},Columns:a2(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()===C.formSection){let i=n;i.Name&&!q.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}isReferencePanelSection(){return!P.IsNullOrUndefined(this)&&!P.IsNullOrUndefined(this.Name)&&this.Name.indexOf(Ue.referencePanelNamePrefix)===0}getAllMultiRowCells(){return this.findAll(t=>{if(t.getNodeName()===C.formCell){let r=t;return!r.isEmpty()&&r.rowspan>1}return!1})}isHeaderOrFooterSection(){return this.NodeName===C.formFooter||this.NodeName===C.formHeader}}});var wo,wf=k(()=>{"use strict";se();St();ku();wo=class e extends te{constructor(t){super(C.formColumn,t)}initializeDefaultProperties(t){this.addProperty(y.width,t.toString()+"%")}insertSectionAtIndex(t,r){this.addGrandChildAtIndex(C.formSections,t,r)}static createAndInitNewSection(t,r,n){let i=new ei(C.formSection,null);return i.initialize(t,r,n),i}addSectionAtIndex(t,r){this.addGrandChildAtIndex(C.formSections,t,r)}initialize(t,r,n,i=Ge.ONE_COLUMN){this.initializeDefaultProperties(t);let o=e.createAndInitNewSection(r,n,i);this.addSectionAtIndex(o,this.sections.length),o.setUniqueName()}get parentTab(){return this.getAncestor(C.formTab)}get sections(){let t=this.getChildren("sections");return t.length!==1?[]:t[0].getChildren(C.formSection)}get width(){return this.getProperty(y.width)}set width(t){this.setProperty(y.width,t)}deleteSection(t){return this.deleteFirstGrandChildOfName(C.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(y.Name),Id:this.getProperty(y.id),Label:null,ShowLabel:!1,Visible:!0,LabelId:null,PreviewId:this.getProperty(y.id),Sections:await this.getSectionsJSON(t),Width:this.width}}}});var Cf,s2=k(()=>{"use strict";ct();se();An();ku();Cf=class extends ei{initializeNavArea(t,r,n){this.initializeNavAreaProps(t,r,n)}get AreaName(){return this.Name}initializeNavAreaProps(t,r,n){this.addProperty(y.Name,n),this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.columnName,Ue.columns),this.setDisplayName(r,t)}}});var Ef,l2=k(()=>{"use strict";wf();se();s2();Ef=class extends wo{addAndIntializeNavBarSection(t,r,n,i){let o=new Cf(C.formSection,null);return o.initializeNavArea(t,r,i),this.addGrandChildAtIndex(C.formSections,o,n),o}}});var ki,Af=k(()=>{"use strict";ct();et();zt();wf();se();St();vo();ki=class extends jt{tabContainsAutoExpandControl;autoExpandCell;constructor(t,r){super(C.formTab,t),this.tabContainsAutoExpandControl=!1}getParentForm(){return this.getAncestor(C.form)}getTabLayoutType(){let t;switch(this.columns.length){case 1:t=Ve.ONE_COLUMN;break;case 2:if(parseInt(this.columns[0].width,10)===50&&parseInt(this.columns[1].width,10)===50){t=Ve.TWO_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===67&&parseInt(this.columns[1].width,10)===33){t=Ve.TWO_COLUMN_WIDER_LEFT;break}if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===66){t=Ve.TWO_COLUMN_WIDER_RIGHT;break}t=Ve.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=Ve.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=Ve.THREE_COLUMN_WIDER_MID;break}t=Ve.THREE_COLUMN_CUSTOM_LAYOUT;break;default:}return t}initializeProperties(t,r,n){this.addProperty(y.Name,mo.namePrefix+t.toString()),this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.IsUserDefined,mo.IsUserDefined),this.addProperty(y.locklevel,mo.LockLevel),this.addProperty(y.showlabel,mo.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=Ge.ONE_COLUMN,o=!0,a){let s=this.getChildren(C.formColumns)[0],l=[];switch(t){case Ve.ONE_COLUMN:l.push(100);break;case Ve.TWO_COLUMN_EQUAL:l.push(50),l.push(50);break;case Ve.TWO_COLUMN_WIDER_LEFT:l.push(67),l.push(33);break;case Ve.TWO_COLUMN_WIDER_RIGHT:l.push(34),l.push(66);break;case Ve.THREE_COLUMN_EQUAL:l.push(34),l.push(33),l.push(33);break;case Ve.THREE_COLUMN_WIDER_MID:l.push(28),l.push(44),l.push(28);break;default:}for(let u of l){let c=new wo(s);c.initialize(u,r,n,i),this.addGrandChild(C.formColumns,c)}}initialize(t,r,n,i,o,a=Ge.ONE_COLUMN,s=!0,l){this.addChild(new te(C.formColumns,this)),this.initializeProperties(r,n,i),this.initializeColumns(t,n,o,a,s,l)}get columns(){let t=this.getChildren(C.formColumns);return t.length!==1?[]:t[0].getChildren(C.formColumn)}get expanded(){return this.getProcessedValue(y.expanded)}set expanded(t){P.IsNullOrUndefined(t)||this.setProperty(y.expanded,String(t))}get groupName(){return this.getProperty(y.groupName)}get contentType(){return this.getProperty(y.contentType)}set contentType(t){this.setProperty(y.contentType,t)}insertNewColumnAtIndex(t,r,n,i,o){t.initialize(n,i,o),this.addGrandChildAtIndex(C.formColumns,t,r)}insertColumnAtIndex(t,r){this.addGrandChildAtIndex(C.formColumns,t,r)}deleteColumn(t){return this.deleteFirstGrandChildOfName(C.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()===C.formTab){let i=n;i.Name&&!q.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}}});var da,sy=k(()=>{"use strict";ct();se();St();An();l2();Af();da=class extends ki{constructor(t,r,n){super(t,Ve.THREE_COLUMN_EQUAL),this.setDisplayName(r,n),this.id=new U(U.NewGuid())}initializeDefaultProps(){this.addChild(new te(C.formColumns,this)),this.initializeFiveColumns()}get columns(){let t=this.getChildren("columns");return t.length!==1?[]:t[0].getChildren(C.formColumn)}getNavSectionForArea(t){for(let r of this.columns)for(let n of r.sections)if(n.AreaName===t)return n;return null}getNavCellFromNavId(t){for(let r of this.columns)for(let n of r.sections)for(let i of n.rows)for(let o of i.cells)if(o.NavId===t)return o;return null}initializeFiveColumns(){for(let t=0;t<tf.FIVE_COLUMN;t++){let r=new Ef(this.getChildren(C.formColumns)[0]);r.initializeDefaultProperties(D_.FiveEqColumn),this.addGrandChild(C.formColumns,r)}}}});function aQ(e){switch(e){case dt.Main:return ho.Main;case dt.QuickCreate:return ho.QuickCreate;case dt.QuickViewForm:return ho.Quick;case dt.Dialog:return ho.Dialog;default:return ho.None}}function sQ(e,t){if(t===dt.Main){if(e)switch(e.toLowerCase()){case"low":return po.Low;case"highreadonlyvalues":return po.HighReadOnlyValues;default:return po.HighWithControls}return po.Low}}var Nf,oQ,Sf,u2=k(()=>{"use strict";$_();Nf=we(na());d0();et();zt();gs();X0();se();jo();Rg();ra();Lu();se();vo();oy();sy();Af();oQ="1920";Sf=class e extends jt{_formUniqueName;isHeaderDefaulted;consistencyStrong=!1;_formId;_rawFormXml;_entityName;_entityDisplayName;_status;_formName;_langCode;_description;_formType;_formPresentation;parameters=[];_formactivationstate;_changeTracker;_metadataChangeEvent;_etag;constructor(t,r,n,i,o,a,s,l,u){super(C.form,null),this._formUniqueName=o,this._formId=t,this._entityName=r,this._status=n,this._formName=i,this._description=l,this._formType=a,this._formPresentation=s,this._formactivationstate=u,this._changeTracker=new qd,this._metadataChangeEvent=new nf}get FormLibraries(){let t=this.getFirstChild(C.formLibraries),r=t?t.getAllChildren():[],n=this._getInternalLibraries();return r.concat(n)}getAllEvents(){let t=[],r=this.events;r&&(t=t.concat(r));for(let n of this.tabs){let i=n.events;i&&(t=t.concat(i)),n.findAll(o=>o instanceof Ar).forEach(o=>{let a=o.events;a&&(t=t.concat(a))})}return t}getEventsForNode(t){if(t instanceof e){let r=t.events;return r?r.filter(n=>!n.control&&!n.attribute):null}else if(t instanceof Ar){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()===C.internalLibraries),r=[],n="src";return t.length>0&&(r=t.map(i=>{let o=i.GetPropertyByParameter(n).replace("$webresource:",""),a=new Fs(void 0,void 0,"",!0);return a.name=o,a.displayName=o,a})),r}getDependentFields(){let t=this.getAllEvents(),r=new Set;return t.forEach(n=>{try{n.getAllDependencies().forEach(o=>{r.add(o.id)})}catch(i){throw(0,Nf.trackErrorTrace)(i_,{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 q.IsNullOrEmpty(this.getProperty(y.ShowImage))?!0:this.getProperty(y.ShowImage)!=="false"}set ShowImagecheck(t){t?this.setProperty(y.ShowImage,String(t)):this.setProperty(y.ShowImage,"false")}get ShowNavigation(){return q.IsNullOrEmpty(this.getProperty(y.ShowNavigationbar))?!0:this.getProperty(y.ShowNavigationbar)!=="false"}set ShowNavigation(t){t?this.setProperty(y.ShowNavigationbar,String(t)):this.setProperty(y.ShowNavigationbar,"false")}get MaxWidth(){return q.IsNullOrEmpty(this.getProperty(y.MaxWidth))?oQ:this.getProperty(y.MaxWidth)}set MaxWidth(t){this.setProperty(y.MaxWidth,t)}get headerDensityType(){return this.getProperty(y.HeaderDensityType)}set headerDensityType(t){t&&this.formType===dt.Main?this.setProperty(y.HeaderDensityType,t):this.formType!==dt.Main&&this.headerDensityType&&this.removeProperty(y.HeaderDensityType)}IsMainOrQuickCreateForm(){return this.formType===dt.Main||this.formType===dt.QuickCreate}get FormPresentation(){return this._formPresentation}get LanguageCode(){return this._langCode}set LanguageCode(t){this._langCode=t}get header(){let t=this.getChildren(C.formHeader);return t.length!==1?null:t[0]}set header(t){P.IsNullOrUndefined(t)||(this.deleteChild(this.header),this.addChild(t))}getAllDependencies(){return this.getChildren(C.quickFormDependencies).length===0?[]:this.ConvertModelToArray(this.getChildren(C.quickFormDependencies)[0].getAllChildren())}ConvertModelToArray(t){let r=[];return P.IsNullOrUndefined(t)||t.forEach(n=>{r.push(n.id)}),r}get footer(){let t=this.getChildren(C.formFooter);return t.length!==1?null:t[0]}set footer(t){P.IsNullOrUndefined(t)||(this.deleteChild(this.footer),this.addChild(t))}createAndInitNewTab(t,r,n){let i=new ki(null,t),o=this.getNextTabCounter(this.tabs.length+1);return i.initialize(t,o,this.LanguageCode,r,n),i}addTabAtIndex(t,r){this.addGrandChildAtIndex(C.formTabs,t,r)}createAndInitNewTabWithMarginalControl(t,r,n,i,o){let a=new ki(null,Ve.ONE_COLUMN),s=this.getNextTabCounter(this.tabs.length+1);a.initialize(Ve.ONE_COLUMN,s,this.LanguageCode,r,n,o,!1),this.addGrandChildAtIndex(C.formTabs,a,i);let l=a.columns[0].sections[0];for(let u=0;u<t.rows.length;u++)l.appendRow(t.rows[u])}getNextTabCounter(t){for(let r=0;r<this.tabs.length;r++)if(this.tabs[r].Name===mo.namePrefix+t.toString())return this.getNextTabCounter(t+1);return t}get allTabs(){let t=this.getChildren(C.formTabs);return t.length!==1?[]:t[0].getChildren(C.formTab)}get CanvasNavigationTab(){if(this.tabs.length>0){let t=this.tabs[this.tabs.length-1];if(t instanceof da)return t}return null}get NavigationNode(){let t=this.getChildren(C.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(C.formTabs,t)}insertTabAtIndex(t,r){this.addGrandChildAtIndex(C.formTabs,t,r)}insertRelatedTab(t){let r=this.getAllGrandChildren(C.formTabs);if(!P.IsNullOrUndefined(r)){let n=r.length;this.insertTabAtIndex(t,n)}}get isfooterPresent(){return this.getChildren(C.formFooter).length>0}get displayCondition(){let t=this.getChildren(C.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(C.formTabs).indexOf(t)}get ControlDescriptions(){return this.getAllGrandChildren(C.controlDescriptions)}addControlDescriptionNode(t){this.addGrandChild(C.controlDescriptions,t)}deleteControlDescByForControlId(t){let r=this.getControlDescriptionByForControl(t);P.IsNullOrUndefined(r)||this.deleteFirstGrandChildOfName(C.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 Ar))return!1;let o=!0;return r==="Tab"?o=i.getParentTab()!==t.getParentTab():r==="Section"?o=i.getParentSection()!==t.getParentSection():o=i!==t,i instanceof Ar&&i.control&&t.control&&o&&i.control.dataFieldName===t.control.dataFieldName})}isCellEditableGridControl(t){return!t?.control?.indicationOfSubgrid||t.control.ClassId.guidString.toUpperCase()!==N.CustomControl?!1:this.cellHasCustomControlWithName(t,Si.EditableGridControl)||e2.getConfig()?.enableOneGridEventsForFormDesigner&&this.cellHasCustomControlWithName(t,Si.PowerAppsOneGrid)}isCellCanvasAppControl(t){return t?.control?.ClassId.guidString.toUpperCase()===N.CustomControl&&this.cellHasCustomControlWithName(t,Si.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()===C.formCell){let i=n;return i&&i.control&&i.control.ClassId.guidString===t}return!1}):null}async getTabsJSON(t){let r=this.tabs,n=[],i=[];if(r){for(let o of r)if(!(o instanceof da)){let a=o.toJSON(t);n.push(a)}for(let o of n)i.push(await o)}return i}async getControlDescriptionsToJSON(t){let r=[];for(let n of this.ControlDescriptions){let i=await n.toJSON(t);i&&r.push(i)}return r}async toJSON(t){let r=[];r=await this.getControlDescriptionsToJSON(t);let n=this.NavigationNode&&await this.NavigationNode.toJSON(t);return{Id:this._formId.guidString,Name:this.formName,Label:this.getDisplayName(t.langCode),ShowLabel:this.showlabel,Visible:this.visible,LabelId:this.labelId&&this.labelId.guidString,PreviewId:this._formId.guidString,PreviewSessionId:(0,Nf.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===dt.Main?{HeaderDensity:sQ(this.headerDensityType,this.formType)}:{},InlineEditGridRow:[],InlineQuickForms:[],QuickFormEntities:[],EventHandlers:[],LinkControlSections:[],FormType:aQ(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 _f,ly,c2=k(()=>{"use strict";ct();et();se();St();vo();_f=class extends jt{constructor(t){super(C.formDisplayConditions,t)}get Order(){let t=this.getProperty(y.Order);return P.IsNullOrUndefined(t)?null:parseInt(t,10)}set Order(t){this.setProperty(y.Order,t.toString())}get FallbackForm(){return this.getProperty(y.FallbackForm)==="true"}set FallbackForm(t){this.setProperty(y.FallbackForm,t.toString())}addRoles(t){this.deleteAllChildren();for(let r=0;r<t.length;r++)this.addChild(t[r])}isRoleEveryone(){return!!(this.getChildren(C.formEveryOne)&&this.getChildren(C.formEveryOne)[0])}setRoleEveryone(){this.deleteAllChildren(),this.addChild(new ly(this))}},ly=class extends te{constructor(t){super(C.formEveryOne,t)}}});var Tf,d2=k(()=>{"use strict";se();St();Tf=class extends te{constructor(t,r){super(C.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(y.HandlerUniqueId)}set HandlerUniqueID(t){this.setProperty(y.HandlerUniqueId,t)}get FunctionName(){return this.getProperty(y.functionName)}set FunctionName(t){this.setProperty(y.functionName,t)}get LibraryName(){return this.getProperty(y.libraryNameEventHandler)}set LibraryName(t){this.setProperty(y.libraryNameEventHandler,t)}get Enabled(){return this.getProperty(y.enabledForField)}set Enabled(t){this.setProperty(y.enabledForField,t)}get PassExecutionContext(){return this.getProperty(y.passExecutionContext)}set PassExecutionContext(t){this.setProperty(y.passExecutionContext,t)}get Parameters(){return this.getProperty(y.parameters)}set Parameters(t){this.setProperty(y.parameters,t)}}});var Ms,uy=k(()=>{"use strict";se();ku();Ms=class extends ei{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(C.formCell);for(let o of i)r.push(o)}}return r}get occupiedCells(){return this.cells.filter(t=>!t.isEmpty())}get maxColumns(){return super.getColumnCountValue()}}});var xu,f2=k(()=>{"use strict";se();uy();xu=class extends Ms{_customFooter;constructor(t,r){super(C.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 $u,p2=k(()=>{"use strict";se();uy();$u=class extends Ms{_customHeader;constructor(t,r){super(C.formHeader,t),this._customHeader=r}get customHeader(){return this._customHeader}set customHeader(t){this._customHeader=t}get showCommandBar(){return this.getProcessedValue(y.showCommandBar)}set showCommandBar(t){t!=null&&this.setProperty(y.showCommandBar,String(t))}get showBody(){return this.getProcessedValue(y.showBody)}set showBody(t){t!=null&&this.setProperty(y.showBody,String(t))}get showTabNavigator(){return this.getProcessedValue(y.showTabNavigator)}set showTabNavigator(t){t!=null&&this.setProperty(y.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 Sr,fa=k(()=>{"use strict";ct();zt();se();vo();Sr=class e extends jt{constructor(t,r){super(t,r)}getTitle(t){for(let r of this.getAllTitles())if(+r.getProperty(y.LCID)===t)return r.getProperty(y.text);return null}getAllTitles(){let t=this.getChildren(C.Titles);return t.length===0?[]:t[0].getChildren(C.Title)}setTitle(t,r){for(let i of this.getAllTitles())if(+i.getProperty(y.LCID)===r){i.setProperty(y.text,t);return}let n=new e(C.Title,null);n.setProperty(y.text,t),n.setProperty(y.LCID,String(r)),this.addGrandChild(C.Titles,n)}get Sequence(){return+this.getProperty(y.Sequence)}set Sequence(t){this.setProperty(y.Sequence,t.toString())}get Area(){return this.getProperty(y.Area)}set Area(t){this.setProperty(y.Area,t)}set Id(t){this.setProperty(y.Id,t)}get Id(){return this.getProperty(y.Id)}get id(){return new U(this.Id??"",!0)}set id(t){this.Id=t.guidString}get Show(){return!0}get Icon(){return this.getProperty(y.icon)}set Icon(t){t=t||q.EmptyString,this.setProperty(y.icon,t)}updateCommonProperties(t,r){this.Area=t.Area,this.Sequence=t.Sequence,this.setTitle(t.getDisplayName(r),r)}}});var Fu,m2=k(()=>{"use strict";(function(e){e[e.NavLinkNotAvailable=-1]="NavLinkNotAvailable",e[e.NavLinkIdConflict=-2]="NavLinkIdConflict",e[e.NavBarNotAvailable=-3]="NavBarNotAvailable"})(Fu||(Fu={}))});var Df,h2=k(()=>{"use strict";et();se();fa();m2();Df=class extends Sr{constructor(t){super(C.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 P.IsNullOrUndefined(r)?Fu.NavLinkNotAvailable:r.length===1?this.deleteChild(r[0]):Fu.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 $e,lQ,g2,Lge,Us,cy=k(()=>{"use strict";ct();se();fa();(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"})($e||($e={}));lQ=new Map([[$e.Info,"Info"],[$e.Sales,"Sales"],[$e.Service,"Service"],[$e.Marketing,"Marketing"],[$e.ProcessCenter,"ProcessCenter"]]),g2=new Map([["Info",$e.Info],["Sales",$e.Sales],["Service",$e.Service],["Marketing",$e.Marketing],["ProcessCenter",$e.ProcessCenter]]),Lge=new Map([[$e.Info,9e3],[$e.Sales,9200],[$e.Service,9400],[$e.Marketing,9600],[$e.ProcessCenter,9800],[$e.InternetMarketing,1e4],[$e.Async,10200]]),Us=class extends Sr{constructor(t,r){super(C.formNavBarArea,r)}setDefaultPropertiesByType(t,r,n){this.AreaId=lQ.get(t);let i=n?.(`navBarArea.title.${this.AreaId}`)??this.AreaId;this.setTitle(i,r)}get ParentNavigation(){return this.getAncestor(C.formNavigation)}get AreaId(){return this.getProperty(y.Id)}set AreaId(t){this.setProperty(y.Id,t)}get id(){return new U(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 Bs,dy=k(()=>{"use strict";se();fa();Bs=class extends Sr{constructor(t,r){super(C.formNavBarAreas,r)}get AllNavBarAreaItems(){return this.getChildren(C.formNavBarArea)}get ParentNavigation(){return this.getAncestor(C.formNavigation)}addNavBarArea(t){this.addChild(t)}}});var If,y2=k(()=>{"use strict";et();se();fa();If=class extends Sr{RelationshipNameUCIRuntime;constructor(t){super(C.formNavBarByRelationshipItem,t)}get RelationshipName(){return this.getProperty(y.RelationshipName)}set RelationshipName(t){this.setProperty(y.RelationshipName,t)}set Show(t){this.setProperty(y.Show,String(t))}get Show(){let t=this.getProperty(y.Show);return P.IsNullOrUndefined(t)||t==="true"}get TitleResourceId(){return this.getProperty(y.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 Of,b2=k(()=>{"use strict";se();fa();Of=class extends Sr{constructor(t){super(C.formNavBarItem,t)}get Url(){return this.getProperty(y.url)}set Url(t){this.setProperty(y.url,t)}}});var Pf,v2=k(()=>{"use strict";ct();se();cy();dy();fa();Pf=class extends Sr{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(C.formNavBarAreas)}setDefaultNavBarAreas(t,r){let n=[$e.Info,$e.Sales,$e.Service,$e.Marketing,$e.ProcessCenter];if(this.navBarAreas){let i=this.navBarAreas?.AllNavBarAreaItems;if(i&&i.length>0){let o=new Set(i.map(a=>g2.get(a.AreaId)));n=n.filter(a=>!o.has(a))}}else{let i=new Bs(C.formNavBarAreas,this);i.isTransient=!0,this.addChild(i)}return n.length>0?(n.forEach(i=>{let o=new Us(C.formNavBarArea,this.navBarAreas);o.setDefaultPropertiesByType(i,t,r),this.navBarAreas.addNavBarArea(o)}),!0):!1}get navBar(){return this.getFirstChild(C.formNavBar)}get id(){return new U(Wg,!0)}replaceNavAreaToGivenIndex(t,r){this.navBarAreas?.AllNavBarAreaItems.indexOf(r)!==-1&&(this.deleteFirstGrandChildOfName(C.formNavBarAreas,r),this.addGrandChildAtIndex(C.formNavBarAreas,r,t))}async getNavBarAreasJSON(t){let r=[],n=[];if(this.navBarAreas?.AllNavBarAreaItems){for(let o of this.navBarAreas.AllNavBarAreaItems)n.push(o.toJSON(t));r=await Promise.all(n)}return r}async getNavBarRelationshipItemsJSON(t){let r=[],n=[];if(this.navBar?.AllRelationShipItems){for(let i of this.navBar.AllRelationShipItems)n.push(i.toJSON(t));r=await Promise.all(n)}return r}async toJSON(t){let r=await this.getNavBarAreasJSON(t),n=await this.getNavBarRelationshipItemsJSON(t);return{NavBarAreas:{NavBarAreas:r},NavBarByRelationshipItems:n,NavBarItems:[],NavPaneIsvItems:{NavBarIsvItems:[]},ShowEmptyNavBarAreas:t.formModelService.showHiddenElements}}}});var w2={};jr(w2,{ControlType:()=>an,DeserializationService:()=>my,DeserializationServiceScope:()=>py,DeserializedFormElementNode:()=>Nr});var fy,Nr,py,an,my,iy=k(()=>{"use strict";fy=we(na());ct();et();zt();gs();zg();ra();o_();k_();fu();u2();Lu();wf();Ru();Z0();se();se();c2();St();An();ey();d2();f2();ty();ry();p2();oy();ay();ku();Af();h2();cy();dy();y2();b2();v2();Nr=class extends te{constructor(t,r){super(t,r)}insertProperty(t,r){this.addProperty(t,r)}insertChild(t){this.addChild(t)}},py="DeserializationService";(function(e){e.Grid="Grid",e.Lookup="Lookup",e.Base="Base"})(an||(an={}));my=class{lcid;constructor(t){this.lcid=t}deSerializeFormXml(t,r,n,i,o,a,s,l,u,c){if(!t)throw new Error("Formxml could not be parsed.");let d=t.getElementsByTagName("form");if(d.length!==1){let p="";throw d.length===0?p="FormXml has no form node.":p="FormXml has multiple form nodes.",(0,fy.trackErrorTrace)(ir,{eventName:py,eventData:{error:p}}),new Error(p)}let f=this.createFormModel(d.item(0),r,n,i,o,a,s,l,u,c);return P.IsNullOrUndefined(f.displayCondition)&&s!==dt.Dialog&&this.appendDefaultDisplayCondition(f),f}upsertFieldCount(t,r){let n=ia.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(!P.IsNullOrUndefined(t)){let n=P.ParseXml(r);n!==null&&this.populateElementChildren(t,n.childNodes)}}createFormModel(t,r,n,i,o,a,s,l,u,c){let d=new Sf(r,n,i,o,a,s,l,u,c);return this.populateElementProperties(d,t.attributes),this.populateElementChildren(d,t.childNodes),s===dt.Main&&(this.insertHeaderFooterElementProperties(C.formHeader,d,d.header),this.insertHeaderFooterElementProperties(C.formFooter,d,d.footer)),d}insertHeaderFooterElementProperties(t,r,n){if(P.IsNullOrUndefined(n)){let i=t===C.formHeader?new $u(r,!0):new xu(r,!0);Nr.prototype.insertProperty.call(i,y.id,"{"+U.NewGuid()+"}"),Nr.prototype.insertProperty.call(i,y.Fieldlabelposition,"Top"),Nr.prototype.insertProperty.call(i,y.columnName,Ue.MarginalControlColumns),Nr.prototype.insertProperty.call(i,y.LabelWidth,Ue.LabelWidth),Nr.prototype.insertProperty.call(i,y.Fieldlabelalignment,"Left");let o=null,a=new ca(o);for(let s=0;s<i.maxColumns;s++){let l=new Ar(a);Nr.prototype.insertProperty.call(l,y.id,"{"+U.NewGuid()+"}"),l.setDisplayName(q.EmptyString,this.lcid),Nr.prototype.insertProperty.call(l,y.showlabel,"false"),a.addCell(l)}i.appendRow(a),t===C.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 Nr(`<${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,fy.trackErrorTrace)(ir,{eventName:py,eventData:{error:n}}),new Error(n)}for(let n=0;n<r.length;n++){let i=r.item(n);i&&(Nr.prototype.insertProperty.call(t,i.name,i.value),t.getNodeName()===C.formCell&&i.name===y.auto&&i.value==="true"&&t.setAutoExpandDetailsForTab())}}populateElementChildren(t,r){for(let n=0;n<r.length;n++){let i=r.item(n),o=this.deSerializeFormXmlNode(i,t);o&&Nr.prototype.insertChild.call(t,o)}}createModelNode(t,r){switch(t.nodeName){case C.form:throw new Error("Form node shouldn't be created using this method");case C.formTab:return new ki(r);case C.formColumn:return new wo(r);case C.formHeader:return new $u(r,!1);case C.formFooter:return new xu(r,!1);case C.formSection:return new ei(C.formSection,r);case C.formRow:return new ca(r);case C.formCell:return new Ar(r);case C.formControl:let n=t.attributes,i=t.childNodes.length>0?t.childNodes[0].childNodes:null,o;for(let s=0;s<n.length;s++){let l=n.item(s);if(l.name===y.indicationOfSubgrid&&l.value==="true"||l.name===y.classid&&(l.value?.toLocaleUpperCase()===`{${N.SubgridControl}}`||l.value?.toLocaleUpperCase()===`{${N.ReferencePanelSubgridControl}}`))o=an.Grid;else if(l.name===y.classid&&l.value?.toLocaleUpperCase()===`{${N.LookupControl}}`)o=an.Lookup;else if(l.name===y.classid&&l.value?.toLocaleUpperCase()===`{${N.CustomControl}}`)for(let u=0;u<i?.length;u++)i[u].nodeName===y.DefaultViewId&&(o=an.Lookup)}return o===an.Grid?new xs(r):o===an.Lookup?new $s(r):new _n(r);case C.formEvent:return new ks(r,q.EmptyString);case C.dependency:return this.populateDependencyTable(t),new Ls(r,q.EmptyString);case C.Handler:let a=[];return new Tf(a,r);case C.formNavigation:return new Pf(t.nodeName,r);case C.formNavBarArea:return new Us(t.nodeName,r);case C.formNavBarAreas:return new Bs(t.nodeName,r);case C.formNavBar:return new Df(r);case C.formNavBarByRelationshipItem:return new If(r);case C.formNavBarItem:return new Of(r);case C.formDisplayConditions:return new _f(r);case C.library:return new Fs(r,q.EmptyString,q.EmptyString);case C.controlDescription:return new jd(r);case C.customControl:return this.populateCustomControlConfigurationId(t),new rf(r);default:return new Nr(t.nodeName,r)}}populateDependencyTable(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);i.name===y.id&&this.upsertFieldCount(i.value,Yn.DependencyFieldTable)}}populateCustomControlConfigurationId(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);if(i.name===y.id){let o=new U(i.value.substr(1,i.value.length-2));for(let a=0;a<t.parentNode.attributes.length;a++){let s=t.parentNode.attributes.item(a);if(s.name===y.ForControl){let l=s.value.substr(1,i.value.length-2);tt.CustomControlIdMap.upsert(l,o);break}}break}}}}});var C2={};jr(C2,{SerializationService:()=>hy,SerializationServiceScope:()=>uQ,SerializedFormElementNode:()=>qs});var uQ,qs,hy,E2=k(()=>{"use strict";zt();St();An();sy();uQ="SerializationService",qs=class extends te{fetchNodeName(){return this.getNodeName()}enumerateProperties(){return this.getAllProperties()}enumerateChildren(){return this.getAllChildren()}},hy=class{langCode;constructor(t){this.langCode=t}serializeFormXmlNode(t){let r=qs.prototype.fetchNodeName.call(t);if(r.charAt(0)===Ri.StartTag)return q.EscapeXml(r.substr(1),!1);if(t.isTransient&&!t.isDirty())return q.EmptyString;let n=qs.prototype.enumerateProperties.call(t),i=qs.prototype.enumerateChildren.call(t);if(!(t instanceof da)){let o=`<${r}`;if(n.length!==0&&(o+=` ${this.getPropertiesString(n)}`),i.length===0)o+=" />";else{let a=q.EmptyString;for(let s of i)a+=this.serializeFormXmlNode(s);o+=`>${a}</${r}>`}return o}return q.EmptyString}getPropertiesString(t){let r=q.EmptyString;return t.forEach((n,i)=>{i!==0&&(r+=" "),r+=`${n.key}="${q.EscapeXml(n.value,!0)}"`}),r}}});var vy=v(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});Vs.completeRecordAsStored=Vs.completeLabelsAsStored=void 0;var gy=lo(),cQ="E7A81278-8635-4D9E-8D4D-59480B391C5B",dQ=new Set(["tab","section","cell"]);function Tn(e){let t=[];for(let r=e.firstChild;r;r=r.nextSibling)r.nodeType===1&&t.push(r);return t}function Co(e,t){return Tn(e).find(r=>r.tagName===t)}function S2(e,t){return e.length===t.length&&e.every((r,n)=>r.tagName===t[n].tagName)}function yy(e){let t=Co(e,"control");return t?(t.getAttribute("datafieldname")||"")!==""?!0:(t.getAttribute("classid")||"").replace(/[{}]/g,"").toUpperCase()===cQ:!1}function by(e,t){var r,n;let i=((r=Co(e,"control"))===null||r===void 0?void 0:r.getAttribute("id"))||"";return i!==""&&i===(((n=Co(t,"control"))===null||n===void 0?void 0:n.getAttribute("id"))||"")}function fQ(e,t){if(Co(e,"labels"))return;let r=Tn(e),n=Tn(t),i=n[0];if(!i||i.tagName!=="labels"||n.length!==r.length+1||!S2(r,n.slice(1)))return;let o=Tn(i);if(!(o.length===0||o.some(s=>s.tagName!=="label"||!s.hasAttribute("description")||!s.hasAttribute("languagecode"))||!(e.tagName==="cell"&&yy(e)&&by(e,t))&&o.some(s=>s.getAttribute("description")!=="")))return i}function pQ(e,t){let r=mQ(e.ownerDocument,t),n=Tn(e)[0];n?e.insertBefore(r,n):e.appendChild(r)}function mQ(e,t){let r=e.createElement("labels");for(let n of Tn(t))r.appendChild(N2(e,n));return r}function N2(e,t){let r=e.createElement("label");for(let n=0;n<t.attributes.length;n+=1){let{name:i,value:o}=t.attributes[n];(i==="description"||i==="languagecode")&&r.setAttribute(i,o)}return r}function A2(e,t){let r=Co(e,"labels");return r?Tn(r).find(n=>n.tagName==="label"&&n.getAttribute("languagecode")===String(t)):void 0}function hQ(e,t,r){if(e.tagName!=="cell"||!yy(e)||!by(e,t))return!1;let n=A2(e,r),i=A2(t,r),o=i?.getAttribute("description")||"";return!n||!n.hasAttribute("description")||(n.getAttribute("description")||"")!==""||o===""?!1:(n.setAttribute("description",o),!0)}function gQ(e,t){if(e.tagName!=="cell"||!yy(e)||!by(e,t))return;let r=Co(e,"labels"),n=Co(t,"labels");if(!r||!n)return;let i=Tn(r),o=Tn(n),a=f=>f.tagName==="label"&&f.hasAttribute("description")&&f.hasAttribute("languagecode");if(o.length<=i.length||!i.every(a)||!o.every(a))return;let s=new Map(i.map(f=>[f.getAttribute("languagecode")||"",f]));if(s.size!==i.length)return;let l=new Set,u=0,c=[],d=[];for(let f of o){let p=f.getAttribute("languagecode")||"";if(l.has(p))return;l.add(p);let m=s.get(p);if(!m){d.push(f);continue}if((m.getAttribute("description")||"")!==(f.getAttribute("description")||""))return;u+=1,c.push(...d.map(h=>({label:h,before:m}))),d=[]}return c.push(...d.map(f=>({label:f}))),u===i.length?c:void 0}function _2(e,t,r,n){if(e.tagName!==t.tagName)return;if(dQ.has(e.tagName)){let a=fQ(e,t);a&&(pQ(e,a),n.changed=!0),hQ(e,t,r)&&(n.changed=!0);let s=gQ(e,t),l=Co(e,"labels");if(s&&l){for(let{label:u,before:c}of s){let d=N2(e.ownerDocument,u);c?l.insertBefore(d,c):l.appendChild(d)}n.changed=!0}}let i=Tn(e),o=Tn(t);S2(i,o)&&i.forEach((a,s)=>_2(a,o[s],r,n))}function T2(e,t,r){if(e===t)return e;let n,i;try{n=(0,gy.parseXmlRoot)(e,""),i=(0,gy.parseXmlRoot)(t,"")}catch{return e}let o={changed:!1};return _2(n,i,r,o),o.changed?(0,gy.serializeNode)(n):e}Vs.completeLabelsAsStored=T2;function yQ(e,t,r){let n=e?.formxml,i=t?.formxml;if(typeof n!="string"||typeof i!="string")return e;let o=T2(n,i,r);return o===n?e:{...e,formxml:o}}Vs.completeRecordAsStored=yQ});var H2=v(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.pcfReadIssues=le.pcfBindingIssues=le.commitPcfState=le.mayCommitPcfState=le.reconcilePcfDescriptions=le.customControlNeeds=le.mintPcfIdentity=le.planPcfBinding=le.projectPcfBindings=le.supportsPcfFormType=le.storedBindingOf=le.hasCustomControl=le.sameAsStored=le.readPcfDescription=le.newPcfDescription=le.editorText=le.nativeClassFor=le.pcfEntryLayout=void 0;var bQ=(fu(),kr(x_)),vQ=Q(),D2=lt(),V=yd(),wQ=Lh(),ve=Zr(),Fi=["web","phone","tablet"],Mu={web:"2",phone:"0",tablet:"1"},L2=new Map([["2","web"],["0","phone"],["1","tablet"]]),CQ=["phone","web","tablet"];function Lf(e){let t=new Set(e),r=CQ.filter(n=>!t.has(n));return{defaults:r.length===0?[null]:r,named:Fi.filter(n=>t.has(n))}}le.pcfEntryLayout=Lf;function or(e){return Array.isArray(e)?e:[]}function rt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Uu(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Cy(e){return{n:`<${e}`,a:[],c:[]}}function k2(e){return typeof e?.n=="string"&&e.n.startsWith("<")}function I2(e){let t=or(e.c);return t.length===1&&k2(t[0])&&(0,V.rawText)(e)!==""?(0,V.rawText)(e):void 0}function ln(e,t){return JSON.stringify(e)===JSON.stringify(t)}function x2(e){return`{${e.replace(/^\{|\}$/g,"").toUpperCase()}}`}function Ey(e){try{let t=(0,bQ.mapFieldTypeToControl)(e.attributeTypeName,e.format);return t?x2(String(t)):void 0}catch{return}}le.nativeClassFor=Ey;var Ay=new Map([["Whole.None",{digits:0,min:-2147483648,max:2147483647}],["Whole.Duration",{digits:0,min:0,max:2147483647}],["Decimal",{digits:7,min:-922337203685477,max:922337203685477}],["FP",{digits:5,min:-1e11,max:1e11}],["Currency",{digits:4,min:-1e11,max:1e11}]]),$2=new Set(["TwoOptions","Boolean"]),F2=new Set(["SingleLine.Text","SingleLine.TextArea","SingleLine.Email","SingleLine.Phone","SingleLine.URL","SingleLine.Ticker","Multiple"]),EQ=new Map([...[...F2].map(e=>[e,100]),["SingleLine.TextArea",2e3],["Multiple",1048576]]),AQ=/^[A-Za-z_][A-Za-z0-9_.-]*$/;function M2(e){return AQ.test(e)&&e!=="__proto__"}function Sy(e){return e!==void 0&&(e==="Enum"||Ay.has(e)||$2.has(e)||F2.has(e))}function U2(e){return typeof e=="number"?e:e!==""&&!Number.isNaN(Number(e))?Number(e):void 0}function Bu(e,t){let r=e!==void 0?Ay.get(e):void 0;if(r&&typeof t!="boolean"){let n=U2(t);if(n!==void 0)return n.toFixed(r.digits)}return typeof t=="boolean"?t?"true":"false":String(t)}le.editorText=Bu;function SQ(e,t,r){var n;let i=[];for(let o of e.properties){let a=o.name,s;if(o.isPrimary?s=t:o.usage==="input"&&Uu(r,a)?s=Bu(o.defaultType,r[a]):s=(n=o.defaultValue)!==null&&n!==void 0?n:"",s==="")continue;let l=[];o.defaultType&&l.push(["type",o.defaultType]),!o.isPrimary&&(o.defaultType==="Enum"||o.usage==="input")&&l.push(["static","true"]),i.push({n:a,a:l,c:[Cy(s)]})}return i}function B2(e,t,r,n,i){var o,a;let s=(o=n.formFactors)!==null&&o!==void 0?o:Fi.filter(d=>Ny(i).has(d)),l=Lf(s),u=SQ(i,t,(a=n.parameters)!==null&&a!==void 0?a:{}),c=d=>JSON.parse(JSON.stringify(d));return{n:"controlDescription",a:[["forControl",e]],c:[...l.defaults.map(d=>({n:"customControl",a:d===null?[["id",r]]:[["id",r],["formFactor",Mu[d]]],c:[{n:"parameters",a:[],c:[{n:"datafieldname",a:[],c:[Cy(t)]}]}]})),...l.named.map(d=>({n:"customControl",a:[["name",n.name],["formFactor",Mu[d]]],c:[{n:"parameters",a:[],c:c(u)}]}))]}}le.newPcfDescription=B2;function Ny(e){return new Set(Fi.filter(t=>e.availableOn[t]))}function Rf(e){var t;let r=or(e.c);if(r.length!==1||((t=r[0])===null||t===void 0?void 0:t.n)!=="parameters"||or(r[0].a).length>0)return;let n=or(r[0].c);return n.every(i=>rt(i)&&!k2(i))?n:void 0}function pa(e){let t=or(e?.c);if(t.length===0||!t.every(m=>rt(m)&&m.n==="customControl"))return;let r=t.findIndex(m=>(0,V.rawAttr)(m,"name")!==void 0);if(r<=0)return;let n=t.slice(r),i=(0,V.rawAttr)(n[0],"name"),o=[];for(let m of n){let h=or(m.a),g=h.length===2?L2.get(h[1][1]):void 0;if(!g||h[0][0]!=="name"||h[0][1]!==i||h[1][0]!=="formFactor"||o.includes(g))return;o.push(g)}let a=Lf(o);if(!ln(a.named,o)||i==="")return;let s=Rf(n[0]);if(!s||!n.every(m=>ln(Rf(m),s)))return;let l=t.slice(0,r);if(l.length!==a.defaults.length)return;let u=(0,V.rawAttr)(l[0],"id"),c;for(let m=0;m<l.length;m+=1){let h=a.defaults[m],g=h===null?[["id",u??""]]:[["id",u??""],["formFactor",Mu[h]]],b=Rf(l[m]),w=b?.length===1&&b[0].n==="datafieldname"&&or(b[0].a).length===0?I2(b[0]):void 0;if(!u||!ln(or(l[m].a),g)||w===void 0||c!==void 0&&w!==c)return;c=w}let d={},f={},p;for(let m of s){let h=or(m.a),g=I2(m),b=h.map(w=>w[0]);if(g===void 0||!M2(m.n)||Uu(d,m.n)||m.n===p)return;if((0,V.rawAttr)(m,"static")===void 0){if(p!==void 0||g!==c||!(b.length===0||ln(b,["type"])))return;p=m.n;continue}if((0,V.rawAttr)(m,"static")!=="true"||!(ln(b,["static"])||ln(b,["type","static"])))return;d[m.n]=g,f[m.n]=(0,V.rawAttr)(m,"type")}if(!(p===void 0||c===void 0||u===void 0))return{binding:{name:i,...Object.keys(d).length>0?{parameters:d}:{},...o.length===Fi.length?{}:{formFactors:o}},fieldName:c,nativeClass:u,parameterTypes:f,boundProperty:p}}le.readPcfDescription=pa;function q2(e,t,r){return e===t?!0:typeof e!="string"&&(t===String(e)||t===Bu(r,e))}function V2(e){let t=e.formFactors;return t===void 0?[...Fi]:Array.isArray(t)?Fi.filter(r=>t.includes(r)):[]}function wy(e,t){var r,n,i;if(e.name!==t.binding.name||!ln(V2(e),(r=t.binding.formFactors)!==null&&r!==void 0?r:Fi))return!1;let o=(n=e.parameters)!==null&&n!==void 0?n:{},a=(i=t.binding.parameters)!==null&&i!==void 0?i:{},s=Object.keys(o);return s.length!==Object.keys(a).length?!1:s.every(l=>Uu(a,l)&&q2(o[l],a[l],t.parameterTypes[l]))}le.sameAsStored=wy;function ft(e){return rt(e)&&e.customControl!==void 0}le.hasCustomControl=ft;function $i(e,t){var r;return t?or((r=(0,V.descriptionsRegion)(e))===null||r===void 0?void 0:r.node.c).filter(n=>n?.n==="controlDescription"&&(0,V.normGuid)((0,V.rawAttr)(n,"forControl"))===t):[]}function _y(e,t){let r=$i(e.bag,(0,V.controlUniqueId)(t));return r.length===1?pa(r[0]):void 0}le.storedBindingOf=_y;function Ty(e){let t=(0,V.effectiveFormType)(e);return t==="Main"||t==="QuickCreate"}le.supportsPcfFormType=Ty;function NQ(e){if(!Ty(e))return;let t=(0,V.controlUniqueIds)(e);for(let{cell:r}of(0,V.typedCellSites)(e)){let n=r.control;if(!rt(n)||!n.fieldName||!xi(n.classId)||t.get((0,V.controlUniqueId)(n))!==1)continue;let i=_y(e,n);i&&i.fieldName===n.fieldName&&(n.customControl=JSON.parse(JSON.stringify(i.binding)))}}le.projectPcfBindings=NQ;function xi(e){return typeof e=="string"&&e.replace(/^\{|\}$/g,"").toUpperCase()===V.CUSTOM_CONTROL_CLASS_ID}var sn=(e,t)=>({kind:"refused",rule:e,message:t});function _Q(e){let t=e.replace(/^\{|\}$/g,"");return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)&&!xi(e)}function O2(e,t,r){var n,i;let o=pa(r);if(!o)return sn("pcf-binding-other-control","the control already has a description the SDK cannot read as a binding; adding would replace it");if(o.fieldName!==e.fieldName)return sn("pcf-binding-rebind",`the binding is filed for "${o.fieldName}": remove it, push, then bind the new column`);if(t.name!==o.binding.name)return sn("pcf-binding-control-swap",`the binding uses "${o.binding.name}": to use another control, remove customControl, push, then add it`);let a=rt(t.parameters)?t.parameters:{},s=(n=o.binding.parameters)!==null&&n!==void 0?n:{},l=Object.keys(a).sort();if(!ln(l,Object.keys(s).sort()))return sn("pcf-binding-edit-parameter-set",`an edit changes parameter values only \u2014 the binding stores exactly ${Object.keys(s).sort().map(g=>`"${g}"`).join(", ")||"none"}: to add or remove one, remove the binding, push, then add it`);let u=l.filter(g=>!q2(a[g],s[g],o.parameterTypes[g])),c=u.find(g=>Bu(o.parameterTypes[g],a[g]).trim()==="");if(c!==void 0)return sn("pcf-binding-edit-parameter-set",`"${c}" cannot be cleared in place \u2014 an empty value is not written, which removes the parameter: remove the binding, push, then add it`);let d=V2(t),f=(i=o.binding.formFactors)!==null&&i!==void 0?i:[...Fi],p=d.filter(g=>!f.includes(g)),m=f.filter(g=>!d.includes(g));if(u.length===0&&p.length===0&&m.length===0)return{kind:"unchanged"};let h=u.find(g=>!Sy(o.parameterTypes[g]));if(h!==void 0){let g=o.parameterTypes[h];return sn("pcf-binding-edit-stored-type",`"${h}" is stored ${g===void 0?"with no type":`as type "${g}"`}, which the property editor does not write: remove the binding, push, then add it`)}return(p.length>0||m.length>0)&&!_Q(o.nativeClass)?sn("pcf-binding-edit-fallback",`the factors the control leaves fall back to "${o.nativeClass}", which is not a native control class: remove the binding, push, then add it`):{kind:"edit",description:r,stored:o,changed:u,factors:d,added:p,removed:m}}function TQ(e,t){return t&&(0,V.typedCellSites)(e).find(({cell:n})=>ft(n.control)&&(0,V.controlUniqueId)(n.control)===t)?{descriptions:$i(e.bag,t)}:void 0}function G2(e,t){let r=new Map,n=DQ(e),i=new Set,o=new Map,a=u=>{let c=o.get(u);return c||(c={before:[],now:[]},o.set(u,c)),c},s=(u,c)=>({cell:PQ(u),uid:(0,V.controlUniqueId)(c),bound:ft(c)});for(let{cell:u}of(0,V.typedCellSites)(e)){let c=u.control;rt(c)&&typeof c.id=="string"&&c.id&&a(c.id).now.push({...s(u,c),control:c})}for(let{cell:u}of(0,V.typedCellSites)(t)){let c=u.control;if(!rt(c))continue;let d=s(u,c);d.bound&&d.uid&&i.add(d.uid),typeof c.id=="string"&&c.id&&a(c.id).before.push(d)}let l=(u,c)=>{let d=u.filter(f=>f.cell===c);return d.length===1?d[0]:void 0};for(let[u,{before:c,now:d}]of o){let f=c.filter(D=>D.bound&&D.uid!==""&&!n.has(D.uid));if(f.length===0||d.length===0)continue;let p=[...c],m=D=>{let O=p.findIndex(D);return O<0?void 0:p.splice(O,1)[0]},g=d.filter(D=>!D.bound||D.uid===""?!0:m(O=>O.bound&&O.uid===D.uid)!==void 0?!1:!i.has(D.uid)).filter(D=>{let O=D.cell?l(c,D.cell):void 0;return!O||!l(d,D.cell)||!p.includes(O)?!0:(p.splice(p.indexOf(O),1),f.includes(O)&&D.uid!==O.uid&&P2(D.control)&&r.set(D.control,R2(O.uid)),!1)}),b=[],w=(D,O)=>{let $=D.uid===""?void 0:m(K=>K.uid===D.uid&&(!O||K.bound===D.bound));return $&&f.includes($)&&b.push($),$!==void 0},A=g.filter(D=>!w(D,!0)).filter(D=>!w(D,!1)&&P2(D.control)),L=f.filter(D=>p.includes(D));if(A.length===0||L.length===0&&b.length===0)continue;let R=[...L,...b],I=L.length===1&&A.length===1&&p.length===1?R2(L[0].uid):`the controls with id "${u}" cannot all be matched to those last synced \u2014 their cells do not tell them apart \u2014 and ${R.map(D=>`{${D.uid}}`).join(", ")} no longer ${R.length===1?"names":"name"} a control: which control held ${R.length===1?"that binding":"those bindings"} is ambiguous. Re-fetch the form; to drop a bound control, remove its customControl and push before removing the control`;for(let D of A)r.set(D.control,I)}return r}function DQ(e){let t=(0,V.controlUniqueIds)(e),r=new Map;for(let{cell:i}of(0,V.typedCellSites)(e)){let o=rt(i.control)?(0,V.controlUniqueId)(i.control):"";o&&!r.has(o)&&r.set(o,i.control)}let n=new Set;for(let[i,o]of t){let a=r.get(i);(a===void 0||ft(a)||o>1)&&n.add(i)}return n}function P2(e){return ft(e)||e.genPage===void 0&&xi((0,V.effectiveClassId)(e))}function IQ(e,t){let r=o=>(0,V.typedCellSites)(o).flatMap(({cell:a,pointer:s})=>{let l=a.control;if(!rt(l)||ft(l)||l.genPage!==void 0||!xi((0,V.effectiveClassId)(l)))return[];let u=(0,V.controlUniqueId)(l);return u===""||$i(o.bag,u).length===0?[{control:l,pointer:`${s}/control`}]:[]}),n=o=>`${String(o.id)}\0${(0,V.controlUniqueId)(o)}`,i=r(t).map(({control:o})=>n(o));return r(e).filter(({control:o})=>{let a=i.indexOf(n(o));return a<0?!0:(i.splice(a,1),!1)})}var OQ="this control would keep the custom-control class with no binding (its customControl and uniqueid are gone): remove the binding from an unchanged copy \u2014 keep its uniqueid, and the native control comes back \u2014 or set classId to the column's native control";function R2(e){return`this control's uniqueid changed since it was last synced (it was {${e}}), and a binding is linked to its description by it: restore it (re-fetch the form), or remove the binding, push, then add the new one`}function PQ(e){let t=typeof e.id=="string"?e.id.trim():"";return(0,V.normGuid)(t)||t.toLowerCase()}function qu(e,t,r,n){let i=t.customControl,o=(0,V.controlUniqueId)(t),a=$i(e.bag,o),s=r?G2(e,r).get(t):void 0;if(s!==void 0)return sn("pcf-binding-unique-id",s);let l=r?TQ(r,o):void 0;if(l){let c=l.descriptions,d=c.length===1?pa(c[0]):void 0;if(d&&d.fieldName!==t.fieldName)return sn("pcf-binding-rebind",`the binding is filed for "${d.fieldName}": remove it, push, then bind the new column`);if(c.length===1&&a.length===1&&ln(c[0],a[0]))return O2(t,i,a[0]);let f=a.length===1?pa(a[0]):void 0;return d&&f&&f.fieldName===t.fieldName&&wy(i,d)&&wy(i,f)?{kind:"unchanged"}:sn("pcf-binding-edit-changed-description","the binding\u2019s description changed since it was last synced (edited in the bag, re-keyed or deleted): re-fetch the form before changing the binding")}if(a.length===0)return{kind:"new"};if(a.length>1)return sn("pcf-binding-other-control","the control already has a description the SDK cannot read as a binding; adding would replace it");let u=O2(t,i,a[0]);return n&&(u.kind==="edit"||u.kind==="unchanged")?u.kind==="unchanged"?u:sn("pcf-binding-edit","this binding\u2019s description was never synced from the server (no baseline): changing it in place is not supported \u2014 remove customControl, push, then add the new one"):u}le.planPcfBinding=qu;function W2(e){return e.kind==="edit"&&(e.changed.length>0||e.added.length>0)}function RQ(e){let t=n=>ft(n.control)&&(!n.control.id||!n.id||(0,V.authoredUniqueId)(n.control)===void 0);if(!(0,V.typedCellSites)(e).some(({cell:n})=>t(n)))return e;let r=JSON.parse(JSON.stringify(e));for(let{cell:n}of(0,V.typedCellSites)(r)){if(!t(n))continue;let i=n.control;i.id||(i.id=(0,D2.newId)()),n.id||(n.id=(0,D2.newId)()),(0,V.authoredUniqueId)(i)===void 0&&(0,V.setUniqueId)(i)}return r}le.mintPcfIdentity=RQ;function LQ(e,t){let r=new Set,n=new Set;for(let{cell:i}of(0,V.typedCellSites)(e)){let o=i.control;if(!ft(o)||!rt(o.customControl))continue;let a=o.customControl.name;if(typeof a!="string"||a===""||typeof o.fieldName!="string"||!o.fieldName)continue;let s=qu(e,o,t,!0);s.kind==="new"?(r.add(a),n.add(o.fieldName)):W2(s)&&r.add(a)}return{controls:[...r],columns:[...n],...n.size>0&&(0,V.effectiveFormType)(e)==="QuickCreate"?{requireCreateEligibility:!0}:{}}}le.customControlNeeds=LQ;function kQ(e,t,r){var n,i,o,a,s,l;let u=e.bag,c=new Map;for(let{cell:f,pointer:p}of(0,V.typedCellSites)(e)){let m=f.control;if(!ft(m)||!rt(m.customControl))continue;let h=(0,V.controlUniqueId)(m);h&&$i(u,h).length>0&&c.set(m,{plan:qu(e,m,t,!0),pointer:`${p}/control/customControl`})}let d=(0,V.descriptionsRegion)(u);if(d&&t){let f=(0,V.controlUniqueIds)(e),p=new Set,m=new Map;for(let{cell:h}of(0,V.typedCellSites)(e)){let g=rt(h.control)?(0,V.controlUniqueId)(h.control):"";g&&!m.has(g)&&m.set(g,h.control)}for(let{cell:h}of(0,V.typedCellSites)(t)){let g=h.control;if(!ft(g))continue;let b=(0,V.controlUniqueId)(g),w=$i(t.bag,b),E=$i(u,b);if(w.length!==1||E.length!==1||!ln(w[0],E[0])||!pa(E[0]))continue;let A=m.get(b);if(A&&!ft(A)){if(((n=f.get(b))!==null&&n!==void 0?n:0)>1)continue;let L=(o=(i=pa(E[0]))===null||i===void 0?void 0:i.nativeClass)!==null&&o!==void 0?o:"";A.classId=L.replace(/^\{|\}$/g,"").toUpperCase(),xQ(A,"uniqueid"),p.add(b)}else!A&&!f.has(b)&&p.add(b)}p.size>0&&(d.node.c=or(d.node.c).filter(h=>!(h?.n==="controlDescription"&&p.has((0,V.normGuid)((0,V.rawAttr)(h,"forControl"))))))}for(let{cell:f}of(0,V.typedCellSites)(e)){let p=f.control;if(!ft(p)||!rt(p.customControl))continue;xi(p.classId)||(p.classId=V.CUSTOM_CONTROL_CLASS_ID);let m=(0,V.controlUniqueId)(p);if(!m){if((0,V.authoredUniqueId)(p)!==void 0)continue;m=(0,V.setUniqueId)(p)}let h=c.get(p);if(h){if(h.plan.kind==="refused")throw new vQ.ValidationError("form",e.id,[(0,ve.issue)(h.pointer,h.plan.rule,h.plan.message)]);h.plan.kind==="edit"&&$Q(h.plan,p.customControl);continue}let g=r?.control(p.customControl.name),b=r?.column(e.entityLogicalName,p.fieldName),w=b?.kind==="found"?Ey(b.value):void 0;if(g?.kind!=="found"||!w)continue;d||(d={i:(0,V.embedAppendIndex)(u),node:{n:"controlDescriptions",a:[],c:[]}},u.c.push(d));let E=((l=(s=or((a=p.bag)===null||a===void 0?void 0:a.a).find(L=>L[0]==="uniqueid"))===null||s===void 0?void 0:s[1])!==null&&l!==void 0?l:"").trim(),A=E.startsWith("{")?E:`{${m}}`;d.node.c.push(B2(A,p.fieldName,w,p.customControl,g.value))}}le.reconcilePcfDescriptions=kQ;function xQ(e,t){rt(e.bag)&&(e.bag.a=or(e.bag.a).filter(r=>r[0]!==t))}function $Q(e,t){var r,n;let i=or(e.description.c),o=i.findIndex(g=>(0,V.rawAttr)(g,"name")!==void 0),a=i.slice(0,o),s=i.slice(o),l=(r=t.parameters)!==null&&r!==void 0?r:{};for(let g of s)for(let b of(n=Rf(g))!==null&&n!==void 0?n:[])e.changed.includes(b.n)&&(b.c=[Cy(Bu(e.stored.parameterTypes[b.n],l[b.n]))]);if(e.added.length===0&&e.removed.length===0)return;let u=g=>JSON.parse(JSON.stringify(g)),c=g=>{var b;let w=(0,V.rawAttr)(g,"formFactor");return w===void 0?null:(b=L2.get(w))!==null&&b!==void 0?b:null},d=(0,V.rawAttr)(a[0],"id"),f=(0,V.rawAttr)(s[0],"name"),p=Lf(e.factors),m=p.defaults.map(g=>{let b=a.find(E=>c(E)===g);if(b)return b;let w=u(a[0]);return w.a=g===null?[["id",d]]:[["id",d],["formFactor",Mu[g]]],w}),h=p.named.map(g=>{let b=s.find(E=>c(E)===g);if(b)return b;let w=u(s[0]);return w.a=[["name",f],["formFactor",Mu[g]]],w});e.description.c=[...m,...h]}function FQ(e){return(0,V.typedCellSites)(e).some(({cell:t})=>ft(t.control))}le.mayCommitPcfState=FQ;function MQ(e,t){var r;let n=JSON.parse(JSON.stringify(e)),i=!1;for(let{cell:o}of(0,V.typedCellSites)(n)){let a=o.control;if(!ft(a))continue;let s=_y(n,a);if(!s||s.fieldName!==a.fieldName)continue;let l=t(V.CUSTOM_CONTROL_CLASS_ID),u=or((r=a.bag)===null||r===void 0?void 0:r.a).find(c=>c[0]==="classid");(!xi(a.classId)||a.type!==l||u!==void 0&&!xi(u[1])||!ln(a.customControl,s.binding))&&(xi(a.classId)||(a.classId=V.CUSTOM_CONTROL_CLASS_ID),a.type=l,u&&!xi(u[1])&&(u[1]=x2(V.CUSTOM_CONTROL_CLASS_ID)),a.customControl=JSON.parse(JSON.stringify(s.binding)),i=!0)}return i?n:e}le.commitPcfState=MQ;var UQ=new Set(["name","parameters","formFactors"]);function BQ(e,t,r){let n=[],i=(0,V.controlUniqueIds)(e);for(let{cell:o,pointer:a}of(0,V.typedCellSites)(e)){let s=o.control;ft(s)&&VQ(e,s,`${a}/control`,i,n,t,r?.atPush===!0)}return t&&GQ(e,t,n),n}le.pcfBindingIssues=BQ;function qQ(e,t,r){let n=r.length;if(!rt(e))return r.push((0,ve.issue)(t,"pcf-binding-shape","customControl must be an object")),!1;for(let i of Object.keys(e))UQ.has(i)||r.push((0,ve.issue)(`${t}/${i}`,"pcf-binding-unknown-key",`customControl has no "${i}"`));if((typeof e.name!="string"||e.name.trim()==="")&&r.push((0,ve.issue)(`${t}/name`,"pcf-binding-shape","name must be the control's non-empty customcontrols name")),e.parameters!==void 0)if(!rt(e.parameters))r.push((0,ve.issue)(`${t}/parameters`,"pcf-binding-shape","parameters must be an object"));else for(let[i,o]of Object.entries(e.parameters))typeof o=="string"||typeof o=="boolean"||typeof o=="number"&&Number.isFinite(o)||r.push((0,ve.issue)(`${t}/parameters/${i}`,"pcf-binding-shape","a parameter must be a string, a finite number or a boolean"));if(e.formFactors!==void 0){let i=e.formFactors;Array.isArray(i)&&i.length>0&&i.every(a=>typeof a=="string"&&Fi.includes(a))&&new Set(i).size===i.length||r.push((0,ve.issue)(`${t}/formFactors`,"pcf-binding-shape","formFactors must be distinct 'web', 'phone' and 'tablet', at least one"))}return r.length===n}function VQ(e,t,r,n,i,o,a){var s;let l=`${r}/customControl`,u=qQ(t.customControl,l,i);t.fieldName||i.push((0,ve.issue)(l,"pcf-binding-unbound","a PCF binding needs a control bound to a column (fieldName)")),t.genPage!==void 0&&i.push((0,ve.issue)(l,"pcf-binding-with-genpage","a control cannot embed a page and bind a PCF control")),Ty(e)||i.push((0,ve.issue)(l,"pcf-binding-form-type","PCF bindings are supported on Main and Quick Create forms only (not Quick View or Card)")),t.classId!==void 0&&typeof t.classId!="string"&&i.push((0,ve.issue)(`${r}/classId`,"pcf-binding-class-id","classId must be a string"));let c=(0,V.authoredUniqueId)(t),d=(0,V.controlUniqueId)(t);if(c!==void 0&&!d?i.push((0,ve.issue)(`${r}/bag`,"pcf-binding-unique-id","the control's uniqueid must be a GUID")):d&&((s=n.get(d))!==null&&s!==void 0?s:0)>1&&i.push((0,ve.issue)(`${r}/bag`,"pcf-binding-unique-id","another control carries the same uniqueid")),!u)return;let f=qu(e,t,o,a);f.kind==="refused"&&i.push((0,ve.issue)(l,f.rule,f.message))}function GQ(e,t,r){var n;let i=new Map,o=G2(e,t);for(let{cell:l,pointer:u}of(0,V.typedCellSites)(e)){let c=rt(l.control)?(0,V.controlUniqueId)(l.control):"";if(c&&!i.has(c)&&i.set(c,{control:l.control,pointer:`${u}/control`}),rt(l.control)&&!ft(l.control)){let d=o.get(l.control);d!==void 0&&r.push((0,ve.issue)(`${u}/control`,"pcf-binding-unique-id",d))}}let a=(0,V.controlUniqueIds)(e);for(let{cell:l}of(0,V.typedCellSites)(t)){if(!ft(l.control))continue;let u=(0,V.controlUniqueId)(l.control),c=i.get(u);!c||ft(c.control)||(((n=a.get(u))!==null&&n!==void 0?n:0)>1?r.push((0,ve.issue)(c.pointer,"pcf-binding-unique-id","another control carries this binding\u2019s uniqueid; removing the binding would delete its description too")):ln($i(t.bag,u),$i(e.bag,u))?c.control.fieldName!==l.control.fieldName&&r.push((0,ve.issue)(c.pointer,"pcf-binding-rebind","remove the binding, push, then bind the new column")):r.push((0,ve.issue)(c.pointer,"pcf-binding-removed-changed","the binding changed since it was last pushed; remove it from an unchanged copy (re-fetch)")))}let s=new Set(r.map(l=>l.pointer));for(let{pointer:l}of IQ(e,t))s.has(l)||r.push((0,ve.issue)(l,"pcf-binding-unique-id",OQ))}var WQ=new Set(["Form.Card"]),zQ="MscrmControls.ModelForm.ModelFormControl";function z2(e,t){var r;if(e.hasDataset||e.hasGroups)return"it has a data-set or groups";if(!e.isBound)return"its first property is not bound to a column";let n=e.properties;if(n.filter(s=>s.usage==="bound").length!==1)return"it has more than one bound property";let i=n.map(s=>s.name);if(i.some(s=>!s)||new Set(i).size!==i.length)return"a property has no name, or two share one";let o=i.find(s=>!M2(s));if(o!==void 0)return`the property name "${o}" cannot be written as an element`;if(t===zQ||n.some(s=>s.defaultType!==void 0&&WQ.has(s.defaultType)))return"a property needs a special encoding";if(n.some(s=>s.usage==="output"&&s.defaultValue!==null&&s.defaultValue!==""))return"an output property has a default";let a=n.find(s=>s.usage==="input"&&!Sy(s.defaultType));return a?`input "${a.name}" has a type the property editor does not write as text (${(r=a.defaultType)!==null&&r!==void 0?r:"none"})`:void 0}function jQ(e){return e.ofType!==null?[e.ofType]:e.ofTypeGroup}function j2(e,t,r=e.defaultType){if(r==="Enum")return e.enumValues.some(o=>o.value===String(t))?void 0:`must be one of ${e.enumValues.map(o=>`"${o.value}"`).join(", ")}`;let n=r!==void 0?Ay.get(r):void 0;if(n){let o=typeof t=="boolean"?void 0:U2(t);return o===void 0||o<n.min||o>n.max?`must be a number from ${n.min.toFixed(n.digits)} through ${n.max.toFixed(n.digits)}`:void 0}if(r!==void 0&&$2.has(r))return t===!0||t===!1||t==="true"||t==="false"?void 0:"must be true or false";let i=r!==void 0?EQ.get(r):void 0;return i!==void 0&&String(t).length>i?`must be at most ${i} characters`:e.required&&String(t)===""?"is required":void 0}function HQ(e,t,r){var n,i,o,a;let s={issues:[]},l=s.issues;for(let{cell:u,pointer:c}of(0,V.typedCellSites)(e)){let d=u.control;if(!ft(d)||!d.fieldName)continue;let f=d.customControl;if(!rt(f)||typeof f.name!="string")continue;let p=`${c}/control/customControl`,m=qu(e,d,r,!0);if(m.kind==="edit"){W2(m)&&YQ(m,f,p,t,s);continue}if(m.kind!=="new")continue;let h=t?.control(f.name),g=t?.column((n=e.entityLogicalName)!==null&&n!==void 0?n:"",d.fieldName);if(!h||h.kind==="unavailable"){(i=s.unavailable)!==null&&i!==void 0||(s.unavailable={code:"PCF_MANIFEST_UNAVAILABLE",message:`the manifest of "${f.name}" could not be read`,...h?.kind==="unavailable"?{cause:h.error}:{}});continue}if(h.kind!=="found"){l.push((0,ve.issue)(`${p}/name`,"PCF_CONTROL_NOT_FOUND",`no single installed control is named "${f.name}" (${h.kind})`));continue}if(!g||g.kind==="unavailable"){(o=s.unavailable)!==null&&o!==void 0||(s.unavailable={code:"PCF_COLUMN_UNAVAILABLE",message:`the column "${d.fieldName}" could not be read`,...g?.kind==="unavailable"?{cause:g.error}:{}});continue}let b=z2(h.value,f.name);if(b){l.push((0,ve.issue)(`${p}/name`,"pcf-binding-unsupported-control",`"${f.name}" is not supported: ${b}`));continue}let w=h.value.properties.find($=>$.isPrimary),E=g.kind==="found"?g.value:void 0,A=E?(a=(0,wQ.manifestTypesForColumn)(E.attributeTypeName,E.format,E.formatName))!==null&&a!==void 0?a:[]:[];E!==void 0&&!E.isPrimaryId&&E.isValidForForm&&Ey(E)!==void 0&&jQ(w).some($=>A.includes($))?(0,V.effectiveFormType)(e)==="QuickCreate"&&E?.isValidForCreate!==!0&&l.push((0,ve.issue)(p,"pcf-binding-quick-create-column",`"${d.fieldName}" cannot be set when a record is created, so a Quick Create form cannot bind it`)):l.push((0,ve.issue)(p,"pcf-binding-incompatible-column",`"${f.name}" cannot be bound to "${d.fieldName}"`));let R=new Map(h.value.properties.filter($=>$.usage==="input").map($=>[$.name,$])),I=rt(f.parameters)?f.parameters:{};for(let[$,K]of Object.entries(I)){let Re=R.get($);if(!Re){l.push((0,ve.issue)(`${p}/parameters/${$}`,"pcf-binding-unknown-parameter",`"${f.name}" has no input "${$}"`));continue}let It=j2(Re,K);It&&l.push((0,ve.issue)(`${p}/parameters/${$}`,"pcf-binding-parameter-value",`"${$}" ${It}`))}for(let $ of R.values())$.required&&!Uu(I,$.name)&&!$.defaultValue&&l.push((0,ve.issue)(`${p}/parameters`,"pcf-binding-missing-parameter",`"${$.name}" is required`));let D=Ny(h.value),O=Array.isArray(f.formFactors)?f.formFactors:void 0;(O?O.some($=>!D.has($)):D.size===0)&&l.push((0,ve.issue)(`${p}/formFactors`,"pcf-binding-form-factor",`"${f.name}" is available on ${D.size===0?"no form factor":[...D].join(", ")}`))}return s}le.pcfReadIssues=HQ;function KQ(e,t){return t===void 0||!Sy(t)?!1:e.ofType!==null?e.ofType===t:e.ofTypeGroup.includes(t)}function JQ(e,t,r){var n,i;let o=z2(e,t);if(o)return`it is no longer supported (${o})`;let a=e.properties.find(d=>d.isPrimary);if(a?.name!==r.boundProperty)return`its bound property is now "${(n=a?.name)!==null&&n!==void 0?n:"none"}", not "${r.boundProperty}"`;let s=(i=r.binding.parameters)!==null&&i!==void 0?i:{},l=new Set(e.properties.filter(d=>d.usage==="input").map(d=>d.name)),u=Object.keys(s).find(d=>!l.has(d));if(u!==void 0)return`"${u}" is no longer one of its inputs`;let c=e.properties.find(d=>d.usage==="input"&&d.required&&!d.defaultValue&&!Uu(s,d.name));return c?`it now requires "${c.name}", which the binding does not store`:void 0}function YQ(e,t,r,n,i){var o,a,s;let l=i.issues,u=n?.control(t.name);if(!u||u.kind==="unavailable"){(o=i.unavailable)!==null&&o!==void 0||(i.unavailable={code:"PCF_MANIFEST_UNAVAILABLE",message:`the manifest of "${t.name}" could not be read`,...u?.kind==="unavailable"?{cause:u.error}:{}});return}if(u.kind!=="found"){l.push((0,ve.issue)(`${r}/name`,"PCF_CONTROL_NOT_FOUND",`no single installed control is named "${t.name}" (${u.kind})`));return}let c=JQ(u.value,t.name,e.stored);if(c){l.push((0,ve.issue)(r,"pcf-binding-edit-manifest-changed",`"${t.name}" changed since this binding was written: ${c} \u2014 remove the binding, push, then add it`));return}let d=new Map(u.value.properties.filter(h=>h.usage==="input").map(h=>[h.name,h])),f=l.length;for(let h of Object.keys((a=e.stored.binding.parameters)!==null&&a!==void 0?a:{})){let g=e.stored.parameterTypes[h];KQ(d.get(h),g)||l.push((0,ve.issue)(`${r}/parameters/${h}`,"pcf-binding-edit-stored-type",`"${h}" is stored ${g===void 0?"with no type":`as type "${g}"`}, which "${t.name}" does not take for it now: remove the binding, push, then add it`))}if(l.length>f)return;let p=(s=t.parameters)!==null&&s!==void 0?s:{};for(let h of e.changed){let g=j2(d.get(h),p[h],e.stored.parameterTypes[h]);g&&l.push((0,ve.issue)(`${r}/parameters/${h}`,"pcf-binding-parameter-value",`"${h}" ${g}`))}let m=Ny(u.value);e.added.some(h=>!m.has(h))&&l.push((0,ve.issue)(`${r}/formFactors`,"pcf-binding-form-factor",`"${t.name}" is available on ${m.size===0?"no form factor":[...m].join(", ")}`))}});var uL=v(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0});Tr.classIdForAttributeType=Tr.QUICK_VIEW_CLASS_ID=Tr.NOTES_CLASS_ID=Tr.SUBGRID_CLASS_ID=Tr.formRegistration=Tr.FormAdapter=void 0;var Mi=(ct(),kr(YN)),K2=(et(),kr(QN)),QQ=(St(),kr(ZN)),Nt=(se(),kr(XN)),nt=(ra(),kr(e_)),XQ=(iy(),kr(w2)),ZQ=(E2(),kr(C2)),pt=ao(),J2=Kr(),_r=Zr(),eX=pg(),Ws=lt(),tX=vy(),Ht=yd(),ti=H2(),Gs=Q(),Ry=ue(),Dy=so(),rL=Ko(),rX={[Nt.FormType.Main]:"Main",[Nt.FormType.QuickCreate]:"QuickCreate",[Nt.FormType.QuickViewForm]:"QuickView",[Nt.FormType.Card]:"Card"},kf={Main:Nt.FormType.Main,QuickCreate:Nt.FormType.QuickCreate,QuickView:Nt.FormType.QuickViewForm,Card:Nt.FormType.Card},nX=new Map(Object.entries(nt.ControlClassId).map(([e,t])=>[String(t).toUpperCase(),e]));function Ly(e){var t;return e&&(t=nX.get(e.toUpperCase()))!==null&&t!==void 0?t:"Unknown"}function Vu(e){return e.getAllProperties().map(t=>[t.key,t.value])}function ma(e){let t=new Map;for(let r of e.getAllProperties())t.has(r.key)||t.set(r.key,r.value);return t}function nL(e,t){return e.getAllChildren().find(r=>r.getNodeName()===t)}function ky(e,t){var r,n;let i=nL(e,"labels");if(!i)return"";let o=i.getAllChildren().filter(s=>s.getNodeName()==="label"),a=(r=o.find(s=>ma(s).get("languagecode")===String(t)))!==null&&r!==void 0?r:o[0];return a&&(n=ma(a).get("description"))!==null&&n!==void 0?n:""}function iX(e){let t=nL(e,"parameters"),r={};if(!t)return r;for(let n of t.getAllChildren()){let i=n.getNodeName();if(i.charAt(0)==="<"||i.charAt(0)==="#")continue;let o=n.getAllChildren()[0],a=o?o.getNodeName():"";a.charAt(0)==="<"&&(a=a.substring(1)),r[i]=a}return r}function iL(e){return/^1+$/.test(e)&&e.length>=1&&e.length<=4?e.length:1}function Iy(e){let t=Math.min(Math.max(Math.trunc(e),1),4);return"1".repeat(t)}function Gu(e){return String(e??"").replace(/[{}]/g,"")}function Oy(e){return`{${Gu(e)}}`}function Y2(e,t){if(e===void 0||e==="")return t;let r=Number(e);return Number.isNaN(r)?t:r}function $f(e,t,r){let n=e.getAllChildren(),i=n.findIndex(u=>u.getNodeName()===t),o=[];if(n.forEach((u,c)=>{c!==i&&o.push({i:c,node:(0,pt.rawFromNode)(u)})}),i<0)return{modeled:[],bag:{a:Vu(e),c:o}};let a=n[i],s=[],l=[];return a.getAllChildren().forEach((u,c)=>{u.getNodeName()===r?s.push(u):l.push({i:c,node:(0,pt.rawFromNode)(u)})}),{modeled:s,bag:{a:Vu(e),c:o,w:{n:a.getNodeName(),a:Vu(a),c:l}}}}function oL(e,t,r){let n=[],i=[];return e.getAllChildren().forEach((o,a)=>{o.getNodeName()===t&&(!r||n.length===0)?n.push(o):i.push({i:a,node:(0,pt.rawFromNode)(o)})}),{modeled:n,bag:{a:Vu(e),c:i}}}function Q2(e,t){let{modeled:r,bag:n}=$f(e,"tabs","tab");return{tabs:r.map(i=>oX(i,t)),bag:n}}function oX(e,t){var r,n;let i=ma(e),{modeled:o,bag:a}=$f(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:ky(e,t),expanded:i.get("expanded")==="true",visible:i.has("visible")?i.get("visible")==="true":!0,columns:o.map(s=>aX(s,t)),bag:a}}function aX(e,t){let r=ma(e),{modeled:n,bag:i}=$f(e,"sections","section");return{width:r.get("width"),sections:n.map(o=>sX(o,t)),bag:i}}function sX(e,t){var r,n,i;let o=ma(e),{modeled:a,bag:s}=$f(e,"rows","row");return{id:(r=o.get("id"))!==null&&r!==void 0?r:"",name:(n=o.get("name"))!==null&&n!==void 0?n:"",label:ky(e,t),visible:o.has("visible")?o.get("visible")==="true":!0,showLabel:o.get("showlabel")==="true",columns:iL((i=o.get("columns"))!==null&&i!==void 0?i:"1"),rows:a.map(l=>lX(l,t)),bag:s}}function lX(e,t){let{modeled:r,bag:n}=oL(e,"cell",!1);return{cells:r.map(i=>uX(i,t)),bag:n}}function uX(e,t){var r;let n=ma(e),{modeled:i,bag:o}=oL(e,"control",!0),a=ky(e,t),s=n.get("showlabel")==="true",l=i[0]?cX(i[0],a,s):null;return{id:(r=n.get("id"))!==null&&r!==void 0?r:"",visible:n.has("visible")?n.get("visible")==="true":!0,colspan:Y2(n.get("colspan"),1),rowspan:Y2(n.get("rowspan"),1),control:l,bag:o}}function cX(e,t,r){var n,i;let o=ma(e),a=Gu((n=o.get("classid"))!==null&&n!==void 0?n:""),s=o.get("datafieldname");return{id:(i=o.get("id"))!==null&&i!==void 0?i:"",classId:a,fieldName:s||null,type:Ly(a),isRequired:o.get("isrequired")==="true",isReadOnly:o.get("disabled")==="true",label:t,showLabel:r,parameters:iX(e),bag:{a:Vu(e),c:e.getAllChildren().map((l,u)=>({i:u,node:(0,pt.rawFromNode)(l)}))}}}function So(e){return e.a.length===0&&e.c.length===0&&!e.w}function aL(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function ha(e,t){var r;let n=new Set(e.a.map(a=>a[0])),i=So(e),o=[];for(let a of t)if(n.has(a.key)){let s=(r=aL(e,a.key))!==null&&r!==void 0?r:"";a.matches(s)||o.push([a.key,a.render()])}else i?o.push([a.key,a.render()]):a.matches(a.absentDefault)||o.push([a.key,a.render()]);return(0,pt.mergeAttrs)(e.a,o)}var Eo=(e,t)=>({key:e,matches:r=>r===t,render:()=>t,absentDefault:""}),Ao=(e,t,r=!1)=>({key:e,matches:n=>n==="true"===t,render:()=>String(t),absentDefault:String(r)}),X2=(e,t,r=1)=>({key:e,matches:n=>Number(n)===t,render:()=>String(t),absentDefault:String(r)});function xy(e,t){return{n:"labels",a:[],c:[{n:"label",a:[["description",e],["languagecode",String(t)]],c:[]}]}}function Py(e){return{n:"parameters",a:[],c:Object.keys(e).map(t=>({n:(0,Ry.assertXmlName)(t,"Form control parameter name"),a:[],c:[{n:`<${e[t]}`,a:[],c:[]}]}))}}function dX(e,t){var r,n;let i=e.c.find(a=>a.n==="label"&&a.a.some(s=>s[0]==="languagecode"&&s[1]===String(t))),o=i??e.c.find(a=>a.n==="label");return(n=(r=o?.a.find(a=>a[0]==="description"))===null||r===void 0?void 0:r[1])!==null&&n!==void 0?n:""}function fX(e,t,r){let n=!1,i=e.c.map(o=>o.n!=="label"||!o.a.some(s=>s[0]==="languagecode"&&s[1]===String(r))?o:(n=!0,{...o,a:o.a.map(s=>s[0]==="description"?["description",t]:s)}));return n||i.push({n:"label",a:[["description",t],["languagecode",String(r)]],c:[]}),{...e,c:i}}function $y(e,t,r){let n=e.c.findIndex(o=>o.node.n==="labels");if(n<0){if(!t||So(e))return e;let a=e.c.some(s=>s.i===0)?e.c.map(s=>({...s,i:s.i+1})):e.c;return{...e,c:[{i:0,node:xy(t,r)},...a]}}if(dX(e.c[n].node,r)===t)return e;let i=fX(e.c[n].node,t,r);return{...e,c:e.c.map((o,a)=>a===n?{...o,node:i}:o)}}function pX(e){let t={};for(let r of e.c){let n=r.n;if(n.charAt(0)==="<"||n.charAt(0)==="#")continue;let i=r.c[0],o=i?i.n:"";o.charAt(0)==="<"&&(o=o.substring(1)),t[n]=o}return t}function mX(e,t){let r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every(i=>e[i]===t[i])}function hX(e,t){return e.a.some(r=>r[0]===t)?{...e,a:e.a.filter(r=>r[0]!==t)}:e}function gX(e,t){let r=e.c.findIndex(i=>i.node.n==="parameters");if(r<0){if(Object.keys(t).length===0||So(e))return e;let i=e.c.reduce((o,a)=>a.i>o?a.i:o,-1);return{...e,c:[...e.c,{i:i+1,node:Py(t)}]}}if(mX(pX(e.c[r].node),t))return e;let n=Py(t);return{...e,c:e.c.map((i,o)=>o===r?{...i,node:n}:i)}}function Ff(e,t,r,n){if(e.w){let a={n:e.w.n,a:e.w.a.map(s=>[s[0],s[1]]),c:(0,pt.spliceChildren)(e.w.c,r)};return(0,pt.spliceChildren)(e.c,[a])}let i=n(),o={n:t,a:[],c:r};return e.c.length===0?[...i,o]:(0,pt.spliceChildren)(e.c,[...i,o])}function yX(e,t){let r=e.tabs.map(n=>bX(n,t));return{n:"form",a:ha(e.bag,[]),c:e.tabs.length===0&&So(e.bag)?[]:Ff(e.bag,"tabs",r,()=>[])}}function sL(e,t,r){return t&&!e.c.some(n=>n.node.n==="labels")?[xy(t,r)]:[]}function bX(e,t){let r=[Eo("id",e.id),Eo("name",e.name),Ao("expanded",e.expanded),Ao("visible",e.visible,!0)],n=e.columns.map(o=>vX(o,t)),i=$y(e.bag,e.label,t);return{n:"tab",a:ha(i,r),c:Ff(i,"columns",n,()=>sL(i,e.label,t))}}function vX(e,t){let r=e.width!==void 0?[Eo("width",e.width)]:[],n=e.sections.map(i=>wX(i,t));return{n:"column",a:ha(e.bag,r),c:Ff(e.bag,"sections",n,()=>[])}}function wX(e,t){let r=[Eo("id",e.id),Eo("name",e.name),Ao("showlabel",e.showLabel),Ao("visible",e.visible,!0),{key:"columns",matches:o=>iL(o)===e.columns,render:()=>Iy(e.columns),absentDefault:Iy(1)}],n=e.rows.map(o=>CX(o,t)),i=$y(e.bag,e.label,t);return{n:"section",a:ha(i,r),c:Ff(i,"rows",n,()=>sL(i,e.label,t))}}function CX(e,t){let r=e.cells.map(n=>EX(n,t));return{n:"row",a:ha(e.bag,[]),c:So(e.bag)?r:(0,pt.assembleChildren)(e.bag,r)}}function EX(e,t){let r=e.control?e.control.showLabel:aL(e.bag,"showlabel")==="true",n=[Eo("id",e.id),Ao("showlabel",r),Ao("visible",e.visible,!0),X2("colspan",e.colspan),X2("rowspan",e.rowspan)],i=e.control?[AX(e.control)]:[],o;if(So(e.bag))o=[...e.control&&e.control.label?[xy(e.control.label,t)]:[],...i];else{let a=e.control?$y(e.bag,e.control.label,t):e.bag;o=(0,pt.assembleChildren)(a,i)}return{n:"cell",a:ha(e.bag,n),c:o}}function AX(e){let t=[Eo("id",e.id),{key:"classid",matches:i=>Gu(i)===e.classId,render:()=>Oy(e.classId),absentDefault:""}];e.fieldName!==null&&t.push(Eo("datafieldname",e.fieldName)),t.push(Ao("disabled",e.isReadOnly)),t.push(Ao("isrequired",e.isRequired));let r=e.fieldName===null?hX(e.bag,"datafieldname"):e.bag,n;return So(r)?n=Object.keys(e.parameters).length>0?[Py(e.parameters)]:[]:n=(0,pt.assembleChildren)(gX(r,e.parameters),[]),{n:"control",a:ha(r,t),c:n}}var SX={make:(e,t)=>new QQ.FormElementNode(e,t),setProp:(e,t,r)=>e.setProperty(t,r),addChild:(e,t)=>e.addChild(t)};function Z2(e,t,r,n){(0,Dy.installDomShim)();let i=_X(e,r);(0,Ht.reconcileEmbedDescriptions)(i,n),(0,ti.reconcilePcfDescriptions)(i,n,r?.pcf);let o=(0,pt.rebuildRaw)(yX(i,t),SX,null);return new ZQ.SerializationService(t).serializeFormXmlNode(o)}function NX(e){return JSON.parse(JSON.stringify(e))}function _X(e,t){var r;let n=NX(e);n.bag||(n.bag=(0,pt.emptyBag)()),kX(n.bag),t&&TX(n,t);for(let i of(r=n.tabs)!==null&&r!==void 0?r:[])DX(i);return n}function TX(e,t){var r;let n=(r=e.entityLogicalName)!==null&&r!==void 0?r:"";Fy(e,i=>{let o=i.fieldName,a=i;if(!o||a.label!==void 0&&a.classId!==void 0)return;let s=t.resolveField(n,o);s&&(a.label===void 0&&s.displayName&&(a.label=s.displayName),a.classId===void 0&&s.attributeType&&(a.classId=lL(s.attributeType)))})}function eL(e){let t=[];return Fy(e,r=>t.push(r)),t}function Fy(e,t){var r,n,i,o,a;for(let s of(r=e.tabs)!==null&&r!==void 0?r:[])for(let l of(n=s.columns)!==null&&n!==void 0?n:[])for(let u of(i=l.sections)!==null&&i!==void 0?i:[])for(let c of(o=u.rows)!==null&&o!==void 0?o:[])for(let d of(a=c.cells)!==null&&a!==void 0?a:[])d.control&&t(d.control)}function DX(e){e.id||(e.id=Mi.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)IX(t);e.bag||(e.bag=(0,pt.emptyBag)())}function IX(e){e.sections||(e.sections=[]);for(let t of e.sections)OX(t);e.bag||(e.bag=(0,pt.emptyBag)()),e.width===void 0&&So(e.bag)&&(e.width="100%")}function OX(e){e.id||(e.id=Mi.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)PX(t);e.bag||(e.bag=(0,pt.emptyBag)())}function PX(e){e.cells||(e.cells=[]);for(let t of e.cells)RX(t);e.bag||(e.bag=(0,pt.emptyBag)())}function RX(e){(0,Ht.hasGenPage)(e.control)&&(0,Ht.applyEmbedCellDefaults)(e),e.id||(e.id=Mi.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&&LX(e.control),e.bag||(e.bag=(0,pt.emptyBag)())}function LX(e){var t;(0,Ht.hasGenPage)(e)&&(0,Ht.applyEmbedControlDefaults)(e),e.id||(e.id=Mi.Guid.NewGuid()),e.classId===void 0&&(e.classId=String(nt.ControlClassId.TextboxControl)),e.fieldName===void 0&&(e.fieldName=null),e.type===void 0&&(e.type=e.fieldName?"Field":Ly(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,Ry.assertXmlName)(r,"Form control parameter name");e.bag||(e.bag=(0,pt.emptyBag)())}function kX(e){for(let t of e.c){let r=t.node;if(r.n==="events"){for(let n of r.c)if(n.n==="event"){for(let i of n.c)if(i.n==="Handlers")for(let o of i.c)o.n==="Handler"&&!tL(o,"handlerUniqueId")&&o.a.push(["handlerUniqueId",Oy(Mi.Guid.NewGuid())])}}else if(r.n==="formLibraries")for(let n of r.c)n.n==="Library"&&!tL(n,"libraryUniqueId")&&n.a.push(["libraryUniqueId",Oy(Mi.Guid.NewGuid())])}}var xf=class{constructor(t=rL.DEFAULT_LCID){this.lcid=t}toArtifact(t,r){var n,i,o;let{tabs:a,bag:s}=Q2(t,this.lcid),l={id:t.formId?t.formId.guidString:"",name:(n=t.formName)!==null&&n!==void 0?n:"",entityLogicalName:(i=t.entityName)!==null&&i!==void 0?i:"",formType:(o=rX[t.formType])!==null&&o!==void 0?o:"Main",status:this.readActivationStatus(t),...r!==void 0&&r!==""?{description:r}:{},tabs:a,bag:s};return(0,Ht.projectGenPageEmbeds)(l),(0,ti.projectPcfBindings)(l),l}fromArtifact(t){var r;return this.deserialize({formxml:Z2(t,this.lcid),formid:t.id||(0,Ws.newId)(),objecttypecode:t.entityLogicalName,type:kf[t.formType],name:t.name,uniquename:t.name,description:(r=t.description)!==null&&r!==void 0?r:"",formpresentation:Nt.FormPresentation.AirForm,formactivationstate:t.status==="Active"?Nt.FormActivationState.Active:Nt.FormActivationState.InActive})}fromApiResponse(t){var r,n,i,o,a,s,l;let u=t,c=(r=u.formxml)!==null&&r!==void 0?r:"",d={formxml:c,formid:(n=u.formid)!==null&&n!==void 0?n:(0,Ws.newId)(),objecttypecode:(i=u.objecttypecode)!==null&&i!==void 0?i:"",type:u.type,name:(o=u.name)!==null&&o!==void 0?o:"",uniquename:(a=u.uniquename)!==null&&a!==void 0?a:"",description:(s=u.description)!==null&&s!==void 0?s:"",formpresentation:u.formpresentation,formactivationstate:u.formactivationstate};(0,Dy.installDomShim)();let f=K2.ScriptUtilities.ParseXml(c),p=xX(f),m=this.deserializeDocument(d,f);return $X(this.toArtifact(m,(l=u.description)!==null&&l!==void 0?l:void 0),p)}toApiPayload(t,r,n){let i=(0,Ht.genPageEmbedIssues)(t);if(i.length>0)throw new Gs.ValidationError("form",t.id,i);let o=(0,ti.pcfBindingIssues)(t,r,{atPush:!0});if(o.length>0)throw new Gs.ValidationError("form",t.id,o);let a=(0,ti.pcfReadIssues)(t,n?.pcf,r);if(a.unavailable)throw(0,Gs.attachCause)(new Gs.SdkError(a.unavailable.code,a.unavailable.message),a.unavailable.cause);if(a.issues.length>0)throw new Gs.ValidationError("form",t.id,a.issues);return{formxml:Z2(t,this.lcid,n,r),name:t.name,type:kf[t.formType],objecttypecode:t.entityLogicalName,...t.description!==void 0?{description:t.description}:{}}}metadataNeeds(t){let r=t.entityLogicalName;if(!r)return[];let n=new Map;return Fy(t,i=>{var o;let a=i.fieldName,s=i;if(!a||s.label!==void 0&&s.classId!==void 0)return;let l=(o=n.get(a))!==null&&o!==void 0?o:{entityLogicalName:r,fieldName:a};s.label===void 0&&(l.needsLabel=!0),n.set(a,l)}),[...n.values()]}customControlNeeds(t,r){var n;return{entityLogicalName:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",...(0,ti.customControlNeeds)(t,r)}}createDefault(t){var r,n,i,o,a,s,l,u,c,d,f;let p=[...(0,Ht.genPageEmbedIssues)(t),...(0,ti.pcfBindingIssues)(t)];if(p.length>0)throw new Gs.ValidationError("form",t.id||"(new)",p);let m=t.tabs&&t.tabs.length>0?void 0:jX(this.lcid),h=m!==void 0?m:t.tabs.map(w=>FX(w,this.lcid)).join(""),g=this.deserialize({formxml:`<form><tabs>${h}</tabs></form>`,formid:t.id||(0,Ws.newId)(),objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",type:kf[(n=t.formType)!==null&&n!==void 0?n:"Main"],name:(i=t.name)!==null&&i!==void 0?i:"New Form",uniquename:(o=t.name)!==null&&o!==void 0?o:"New Form",description:(a=t.description)!==null&&a!==void 0?a:"",formpresentation:Nt.FormPresentation.AirForm,formactivationstate:((s=t.status)!==null&&s!==void 0?s:"Active")==="Active"?Nt.FormActivationState.Active:Nt.FormActivationState.InActive}),b=this.toArtifact(g,t.description);if(t.tabs&&t.tabs.length>0){let w=eL(t);eL(b).forEach((E,A)=>{w[A]&&w[A].label===void 0&&delete E.label,w[A]&&w[A].genPage!==void 0&&(E.genPage=JSON.parse(JSON.stringify(w[A].genPage))),w[A]&&w[A].customControl!==void 0&&(E.customControl=JSON.parse(JSON.stringify(w[A].customControl)))})}return{id:(l=t.id)!==null&&l!==void 0?l:b.id,name:(u=t.name)!==null&&u!==void 0?u:"New Form",entityLogicalName:(c=t.entityLogicalName)!==null&&c!==void 0?c:"",formType:(d=t.formType)!==null&&d!==void 0?d:"Main",status:(f=t.status)!==null&&f!==void 0?f:"Active",...t.description!==void 0?{description:t.description}:{},tabs:b.tabs,bag:b.bag}}assignMissingIds(t){return(0,Ws.assignMissingIds)(t)}completeAsStored(t,r){return(0,tX.completeRecordAsStored)(t,r,this.lcid)}normalize(t){return(0,ti.mintPcfIdentity)((0,Ht.mintEmbedIdentity)(t))}committed(t,r){var n,i,o,a,s,l;let u=r?.formxml;if(typeof u!="string"||!((0,Ht.mayCommitEmbedState)(t)||(0,ti.mayCommitPcfState)(t)))return{artifact:t,baseline:t};let c=this.deserialize({formxml:u,formid:t.id||(0,Ws.newId)(),objecttypecode:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",type:kf[(i=t.formType)!==null&&i!==void 0?i:"Main"],name:(o=t.name)!==null&&o!==void 0?o:"",uniquename:(a=t.name)!==null&&a!==void 0?a:"",description:(s=t.description)!==null&&s!==void 0?s:"",formpresentation:Nt.FormPresentation.AirForm,formactivationstate:Nt.FormActivationState.Active}),{bag:d}=Q2(c,this.lcid),f=(0,ti.commitPcfState)((0,Ht.commitEmbedState)(t,(l=(0,Ht.descriptionsRegion)(d))===null||l===void 0?void 0:l.node),Ly);return{artifact:f,baseline:f}}validate(t){return tZ(t)}deserialize(t){return(0,Dy.installDomShim)(),this.deserializeDocument(t,K2.ScriptUtilities.ParseXml(t.formxml))}deserializeDocument(t,r){let n=new XQ.DeserializationService(this.lcid).deSerializeFormXml(r,new Mi.Guid(t.formid),t.objecttypecode,Nt.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===Nt.FormActivationState.InActive?"Inactive":"Active"}};Tr.FormAdapter=xf;function xX(e){var t;let r=e?.getElementsByTagName("form")[0],n=new Set;for(let i=(t=r?.firstChild)!==null&&t!==void 0?t:null;i;i=i.nextSibling)i.nodeType===1&&(i.nodeName==="header"||i.nodeName==="footer")&&n.add(i.nodeName);return n}function $X(e,t){var r;if(!(!((r=e.bag)===null||r===void 0)&&r.c))return e;let n=["header","footer"].filter(o=>!t.has(o)),i=e.bag.c.filter(o=>{var a;return n.includes((a=o?.node)===null||a===void 0?void 0:a.n)}).map(o=>o.i);return i.length>0&&(e.bag.c=e.bag.c.filter(o=>{var a;return!n.includes((a=o?.node)===null||a===void 0?void 0:a.n)}).map(o=>({...o,i:o.i-i.filter(a=>a<o.i).length}))),e}function Dn(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function My(e,t){return e?`<labels><label description="${Dn(e)}" languagecode="${t}" /></labels>`:""}function Uy(e){return e&&e.length>0?Gu(e):(0,Ws.newId)()}function FX(e,t){var r,n,i,o;let a=(r=e.columns)!==null&&r!==void 0?r:[],s=(a.length>0?a:[zX()]).map(l=>MX(l,t)).join("");return`<tab id="{${Dn(Uy(e.id))}}" name="${Dn((n=e.name)!==null&&n!==void 0?n:"")}" expanded="${(i=e.expanded)!==null&&i!==void 0?i:!0}" visible="${(o=e.visible)!==null&&o!==void 0?o:!0}">${My(e.label,t)}<columns>${s}</columns></tab>`}function MX(e,t){var r,n;let i=((r=e.sections)!==null&&r!==void 0?r:[]).map(o=>UX(o,t)).join("");return`<column width="${Dn((n=e.width)!==null&&n!==void 0?n:"100%")}"><sections>${i}</sections></column>`}function UX(e,t){var r,n,i,o,a;let s=((r=e.rows)!==null&&r!==void 0?r:[]).map(l=>BX(l,t)).join("");return`<section id="{${Dn(Uy(e.id))}}" name="${Dn((n=e.name)!==null&&n!==void 0?n:"")}" showlabel="${(i=e.showLabel)!==null&&i!==void 0?i:!1}" visible="${(o=e.visible)!==null&&o!==void 0?o:!0}" columns="${Iy((a=e.columns)!==null&&a!==void 0?a:1)}">${My(e.label,t)}<rows>${s}</rows></section>`}function BX(e,t){var r;return`<row>${((r=e.cells)!==null&&r!==void 0?r:[]).map(n=>qX(n,t)).join("")}</row>`}function qX(e,t){var r,n,i,o,a;let s=VX(e),l=s.control,u=l?My((r=l.label)!==null&&r!==void 0?r:"",t):"",c=l?GX(l):"";return`<cell id="{${Dn(Uy(s.id))}}" showlabel="${l?(n=l.showLabel)!==null&&n!==void 0?n:!0:!1}" visible="${(i=s.visible)!==null&&i!==void 0?i:!0}" colspan="${(o=s.colspan)!==null&&o!==void 0?o:1}" rowspan="${(a=s.rowspan)!==null&&a!==void 0?a:1}">${u}${c}</cell>`}function VX(e){if(!(0,Ht.hasGenPage)(e.control))return e;let t={...e.control};(0,Ht.applyEmbedControlDefaults)(t);let r={...e,control:t};return(0,Ht.applyEmbedCellDefaults)(r),r}function GX(e){var t,r,n;let i=e.fieldName?` datafieldname="${Dn(e.fieldName)}"`:"",o=WX(e.parameters),a=e.classId?Gu(e.classId):String(nt.ControlClassId.TextboxControl);return`<control id="${Dn((t=e.id)!==null&&t!==void 0?t:"")}" classid="{${Dn(a)}}"${i} disabled="${(r=e.isReadOnly)!==null&&r!==void 0?r:!1}" isrequired="${(n=e.isRequired)!==null&&n!==void 0?n:!1}">${o}</control>`}function WX(e){let t=Object.keys(e??{});return t.length===0?"":(t.forEach(n=>(0,Ry.assertXmlName)(n,"Form control parameter name")),`<parameters>${t.map(n=>`<${n}>${Dn(e[n])}</${n}>`).join("")}</parameters>`)}function zX(){return{width:"100%",sections:[],bag:{a:[],c:[]}}}function jX(e){return`<tab id="{${Mi.Guid.NewGuid()}}" name="tab_general" expanded="true" visible="true"><labels><label description="General" languagecode="${e}" /></labels><columns><column width="100%"><sections><section id="{${Mi.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 HX(e=rL.DEFAULT_LCID){return{adapter:new xf(e),api:eX.formApi,languageSensitive:!0,publish:(t,r,n)=>(0,J2.publishBoundEntity)(t,n),publishScope:(t,r)=>(0,J2.boundEntityPublishScope)(r),rebaselineAfterPublish:"bracket"}}Tr.formRegistration=HX;var KX=new Set(["id","name","label","expanded","visible","columns","bag"]),JX=new Set(["id","width","sections","bag"]),YX=new Set(["id","name","label","visible","showLabel","columns","rows","bag"]),QX=new Set(["id","cells","bag"]),XX=new Set(["id","visible","colspan","rowspan","control","bag"]),ZX=new Set(["id","classId","fieldName","type","isRequired","isReadOnly","label","showLabel","parameters","genPage","customControl","bag"]),eZ={elsewhere:{isReadOnly:"control",isRequired:"control",fieldName:"control",classId:"control",label:"control",showLabel:"control",parameters:"control"},unsupported:{createOnly:"FormXml has no create-only concept; gate the field with a business rule instead. Raise it with the SDK owners if you need it modeled.",updateOnly:"FormXml has no update-only concept; gate the field with a business rule instead. Raise it with the SDK owners if you need it modeled."}};function tZ(e){let t=[];return(0,_r.childObjects)(e,"tabs","","tab",t).forEach(({node:n,index:i})=>{let o=`/tabs/${i}`;(0,_r.rejectUnknownKeys)(n,KX,o,"tab",t),(0,_r.childObjects)(n,"columns",o,"column",t).forEach(({node:s,index:l})=>{let u=`${o}/columns/${l}`;(0,_r.rejectUnknownKeys)(s,JX,u,"column",t),(0,_r.childObjects)(s,"sections",u,"section",t).forEach(({node:d,index:f})=>{let p=`${u}/sections/${f}`;(0,_r.rejectUnknownKeys)(d,YX,p,"section",t),(0,_r.childObjects)(d,"rows",p,"row",t).forEach(({node:h,index:g})=>{let b=`${p}/rows/${g}`;(0,_r.rejectUnknownKeys)(h,QX,b,"row",t),(0,_r.childObjects)(h,"cells",b,"cell",t).forEach(({node:E,index:A})=>{let L=`${b}/cells/${A}`;(0,_r.rejectUnknownKeys)(E,XX,L,"cell",t,eZ);let R=E.control;R!=null&&!(0,_r.isJsonObject)(R)?t.push((0,_r.issue)(`${L}/control`,"control-must-be-object-or-null",`a cell control must be a JSON object or null, got ${typeof R}`)):(0,_r.isJsonObject)(R)&&(0,_r.rejectUnknownKeys)(R,ZX,`${L}/control`,"control",t)})})})})}),t.push(...(0,Ht.genPageEmbedIssues)(e)),t.push(...(0,ti.pcfBindingIssues)(e)),t}Tr.SUBGRID_CLASS_ID=nt.ControlClassId.SubgridControl;Tr.NOTES_CLASS_ID=nt.ControlClassId.TimelineControl;Tr.QUICK_VIEW_CLASS_ID=nt.ControlClassId.QuickViewControl;var rZ={Lookup:String(nt.ControlClassId.LookupControl),Customer:String(nt.ControlClassId.LookupControl),Owner:String(nt.ControlClassId.LookupControl),PartyList:String(nt.ControlClassId.PartyListControl),Boolean:String(nt.ControlClassId.BooleanControl),DateTime:String(nt.ControlClassId.DateTimeControl),Decimal:String(nt.ControlClassId.DecimalControl),Double:String(nt.ControlClassId.FloatingNumberControl),Money:String(nt.ControlClassId.CurrencyControl),Integer:String(nt.ControlClassId.IntegerControl),BigInt:String(nt.ControlClassId.IntegerControl),Memo:String(nt.ControlClassId.TextAreaControl),String:String(nt.ControlClassId.TextboxControl)},nZ="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE";function lL(e){return e==="Picklist"||e==="State"||e==="Status"?nZ:e&&rZ[e]||String(nt.ControlClassId.TextboxControl)}Tr.classIdForAttributeType=lL;function tL(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}});var By=v(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.viewApi=zs.findDefaultViews=void 0;var pL=Xt(),ar=ye(),In=ue(),iZ=rs(),cL="savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault",oZ="savedqueryid,name,returnedtypecode,querytype,isdefault",aZ=60*1e3;function Mf(e){return(e.localName||e.nodeName).toLowerCase()}function Wu(e,t){let r;for(let n=0;n<e.attributes.length;n+=1){let i=e.attributes[n];i.nodeName.toLowerCase()===t&&(r=r===void 0?i.value:null)}return r}function sZ(e){if(!e)return;let t=!0,r=()=>{t=!1},n=new iZ.DOMParser({errorHandler:{warning:r,error:r,fatalError:r}}).parseFromString(e,"text/xml").documentElement;return t&&n&&Mf(n)==="fetch"?n:void 0}function lZ(e){for(let t=e.parentNode;t;t=t.parentNode)if(Mf(t)==="link-entity")return!0;return!1}function dL(e,t){var r,n,i;if(((r=e.canbedeleted)===null||r===void 0?void 0:r.Value)!==!1)return!1;let o=sZ(e.fetchxml);if(!o)return!1;let a=Array.from(o.getElementsByTagName("*")),s=a.filter(u=>Mf(u)==="condition"),l=s.length===1?s[0]:void 0;return l!==void 0&&a.filter(u=>Mf(u)==="link-entity").every(u=>{var c;return((c=Wu(u,"link-type"))===null||c===void 0?void 0:c.toLowerCase())==="outer"})&&!lZ(l)&&Wu(l,"entityname")===void 0&&((n=Wu(l,"attribute"))===null||n===void 0?void 0:n.toLowerCase())==="statecode"&&((i=Wu(l,"operator"))===null||i===void 0?void 0:i.toLowerCase())==="eq"&&Wu(l,"value")===String(t)}function uZ(e,t){let r=String(e??"").trim().toLowerCase().split(/\s+/),n=String(t??"").trim().toLowerCase().split(/\s+/);return r.length===n.length&&r.filter((i,o)=>i!==n[o]).length===1}function cZ(e){var t,r;let n=e.filter(a=>dL(a,0)),i=e.filter(a=>dL(a,1)),o=[];for(let a of n)for(let s of i)Math.abs(Date.parse(String((t=s.createdon)!==null&&t!==void 0?t:""))-Date.parse(String((r=a.createdon)!==null&&r!==void 0?r:"")))<=aZ&&uZ(a.name,s.name)&&o.push({active:a,inactive:s});return o.length===1?o[0]:void 0}async function dZ(e,t,r={}){var n;let i=new Set(((n=r.excludeViewIds)!==null&&n!==void 0?n:[]).filter(Boolean)),o=`returnedtypecode eq '${(0,In.odataLiteral)(t)}' and querytype eq 0`,a=`/savedqueries${(0,In.odataQuery)([["$select","savedqueryid,name,canbedeleted,fetchxml,createdon"],["$filter",o]])}`,s=await(0,pL.collectPages)(e,a,`findDefaultViews('${t}')`),l=cZ(s),u=new Set(l?[l.active,l.inactive]:[]);return s.filter(c=>c.savedqueryid&&!i.has(c.savedqueryid)&&u.has(c)).map(c=>{var d;return{id:String(c.savedqueryid),name:String((d=c.name)!==null&&d!==void 0?d:"")}})}zs.findDefaultViews=dZ;async function fZ(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,In.odataPathLiteral)(t)}')${(0,In.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status>=200&&i.status<300){let o=(r=i.body)===null||r===void 0?void 0:r.ObjectTypeCode;return typeof o=="number"?o:void 0}}async function fL(e,t,r){if(!r||!/<grid\b/.test(t)||/<grid[^>]*\bobject=/.test(t))return t;let n=await fZ(e,r);return n===void 0?t:t.replace(/<grid\b/,`<grid object="${n}"`)}zs.viewApi={async get(e,t){let r=(0,In.normalizeGuid)(t,"id"),n=await(0,ar.readRowEtag)(e,"savedqueries","savedqueryid",r),i=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,In.odataQuery)([["$select",cL]]);return{raw:(0,ar.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},async readContentThenToken(e,t){let r=(0,In.normalizeGuid)(t,"id"),n=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,In.odataQuery)([["$select",cL]]),i=(0,ar.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=await(0,ar.readRowEtag)(e,"savedqueries","savedqueryid",r);return{raw:i.body,etag:o}},async list(e,t){let r=`/savedqueries${(0,In.odataQuery)([["$select",oZ],["$filter",t?.entityLogicalName?`returnedtypecode eq '${(0,In.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,pL.collectPages)(e,r,"listArtifacts('view')")).map(i=>{var o,a;return{type:"view",id:(o=i.savedqueryid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",entityLogicalName:i.returnedtypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,ar.echoWrite)("savedqueryid"),o=`/savedqueries${i.query}`,a=await fL(e,n.layoutxml,n.returnedtypecode),s=Object.freeze((0,ar.withClientMintedId)({name:n.name,description:n.description,fetchxml:n.fetchxml,layoutxml:a,returnedtypecode:n.returnedtypecode,querytype:n.querytype,isdefault:n.isdefault},"savedqueryid",r)),l=(0,ar.ensureSuccess)(await(0,ar.resendDeadlockVictim)(()=>e.post(o,{...s},i.options)),e.apiUrl(o));return{id:(0,ar.resolveCreatedId)(l,"savedqueryid","view",r),etag:(0,ar.readEtag)(l)}},async update(e,t,r,n){let i=r,o=(0,In.normalizeGuid)(t,"id"),a=(0,ar.echoWrite)("savedqueryid",{"If-Match":(0,ar.requireEtag)(n,"view",o)}),s=`/savedqueries(${o})${a.query}`,l=await fL(e,i.layoutxml,i.returnedtypecode),u=(0,ar.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,fetchxml:i.fetchxml,layoutxml:l},a.options),e.apiUrl(s));return{id:o,etag:(0,ar.readEtag)(u)}},delete(e,t){return(0,ar.deleteRecord)(e,"savedqueries",t)}}});var DL=v(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});js.viewRegistration=js.ViewAdapter=void 0;var wL=Q(),qr=Zr(),qy=ao(),ga=lo(),mL=Kr(),pZ=By(),Vy=so(),mZ=lt(),CL=100,Bf=class{toArtifact(t){var r,n,i,o,a,s,l,u;(0,Vy.installDomShim)();let c=(r=t.fetchxml)!==null&&r!==void 0?r:"",d=(n=t.layoutxml)!==null&&n!==void 0?n:"",f=(0,ga.parseXmlRoot)(c,"<fetch/>"),p=(0,ga.parseXmlRoot)(d,"<grid/>"),m=AL(f);return{id:(i=t.savedqueryid)!==null&&i!==void 0?i:"",name:(o=t.name)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",entityLogicalName:(s=t.returnedtypecode)!==null&&s!==void 0?s:gZ(f),queryType:(l=t.querytype)!==null&&l!==void 0?l:0,isDefault:(u=t.isdefault)!==null&&u!==void 0?u:!1,columns:EL(p,f),filters:NL(f),sort:SL(f),...m.length>0?{linkEntities:m}:{},fetchBag:c?(0,ga.projectElementBag)(f):void 0,layoutBag:d?(0,ga.projectElementBag)(p):void 0}}fromArtifact(t){(0,Vy.installDomShim)();let{fetchxml:r,layoutxml:n}=hL(t);return{savedqueryid:t.id,name:t.name,description:t.description,returnedtypecode:t.entityLogicalName,querytype:t.queryType,isdefault:t.isDefault,fetchxml:r,layoutxml:n}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){var r,n,i,o,a;(0,Vy.installDomShim)();let{fetchxml:s,layoutxml:l}=hL(t);return{name:(r=t.name)!==null&&r!==void 0?r:"",description:(n=t.description)!==null&&n!==void 0?n:"",fetchxml:s,layoutxml:l,returnedtypecode:(i=t.entityLogicalName)!==null&&i!==void 0?i:"",querytype:(o=t.queryType)!==null&&o!==void 0?o:0,isdefault:(a=t.isDefault)!==null&&a!==void 0?a:!1}}createDefault(t){var r,n,i,o,a,s,l,u;let c=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,mZ.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New View",description:(o=t.description)!==null&&o!==void 0?o:"",entityLogicalName:c,queryType:(a=t.queryType)!==null&&a!==void 0?a:0,isDefault:(s=t.isDefault)!==null&&s!==void 0?s:!1,columns:t.columns&&t.columns.length>0?t.columns:[{name:`${c}id`,width:300,order:0}],filters:(l=t.filters)!==null&&l!==void 0?l:{type:"and",conditions:[],groups:[]},sort:(u=t.sort)!==null&&u!==void 0?u:[],...t.linkEntities&&t.linkEntities.length>0?{linkEntities:t.linkEntities}:{}}}assignMissingIds(t){return t}validate(t){let r=[],n=t;(0,qr.childObjects)(n,"columns","","column",r),(0,qr.childObjects)(n,"sort","","sort",r),(0,qr.childObjects)(n,"linkEntities","","linkEntity",r),hZ(n.linkEntities,r);let i=n.filters;return i!=null&&((0,qr.isJsonObject)(i)?Gy(i,"/filters",r):r.push((0,qr.issue)("/filters","filters-must-be-object",`filters must be a JSON object, got ${typeof i}`))),r}};js.ViewAdapter=Bf;function hZ(e,t){Array.isArray(e)&&e.forEach((r,n)=>{if(!(0,qr.isJsonObject)(r))return;for(let o of["name","from","to"]){let a=r[o];(typeof a!="string"||a.trim()==="")&&t.push((0,qr.issue)(`/linkEntities/${n}/${o}`,"linkentity-needs-keys",`a join needs a non-empty '${o}' \u2014 'from'/'to' are what DEFINE the relationship, and a link without them is unresolvable. Got ${JSON.stringify(a)}.`))}let i=r.filters;i!=null&&((0,qr.isJsonObject)(i)?Gy(i,`/linkEntities/${n}/filters`,t):t.push((0,qr.issue)(`/linkEntities/${n}/filters`,"filters-must-be-object",`filters must be a JSON object, got ${typeof i}`)))})}function Gy(e,t,r){(0,qr.childObjects)(e,"conditions",t,"condition",r),(0,qr.childObjects)(e,"groups",t,"filterGroup",r).forEach(({node:i,index:o})=>Gy(i,`${t}/groups/${o}`,r))}function gZ(e){var t;let r=e.getElementsByTagName("entity")[0];return(t=r?.getAttribute("name"))!==null&&t!==void 0?t:""}function EL(e,t){var r;let n=Wy(t),i=e.getElementsByTagName("cell"),o=[],a=0;for(let s=0;s<i.length;s+=1){let l=i[s];if(l.getAttribute("ishidden")==="1")continue;let u=l.getAttribute("name");if(!u)continue;let c=parseInt((r=l.getAttribute("width"))!==null&&r!==void 0?r:"",10),d={name:u,width:Number.isNaN(c)?CL:c,order:a},f=n.get(u);f&&(d.relatedEntity=f.linkKey,f.attributeName&&f.attributeName!==u&&(d.sourceAttribute=f.attributeName)),a+=1,o.push(d)}return o}function Wy(e){let t=new Map,r=e.getElementsByTagName("link-entity");for(let n=0;n<r.length;n+=1){let i=r[n],o=i.getAttribute("name");if(!o)continue;let a=i.getElementsByTagName("attribute");for(let s=0;s<a.length;s+=1){let l=a[s],u=l.getAttribute("name")||"",c=l.getAttribute("alias")||u;c&&t.set(c,{linkKey:i.getAttribute("alias")||o,linkName:o,attributeName:u,link:i})}}return t}function AL(e){let t=e.getElementsByTagName("entity")[0];if(!t)return[];let r=[];for(let n of Kt(t,"link-entity")){let i=n.getAttribute("name"),o=n.getAttribute("from"),a=n.getAttribute("to");if(!i||!o||!a)continue;let s=n.getAttribute("alias"),l=n.getAttribute("link-type"),u=Kt(n,"filter").find(c=>!qf(c));r.push({name:i,from:o,to:a,...s?{alias:s}:{},...l==="inner"||l==="outer"?{linkType:l}:{},...u?{filters:zy(u)}:{}})}return r}function SL(e){var t;let r=e.getElementsByTagName("entity")[0];if(!r)return[];let n=[],i=r.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];if(a.nodeType===1&&a.tagName==="order"){let s=a.getAttribute("attribute");s&&n.push({attribute:s,descending:((t=a.getAttribute("descending"))!==null&&t!==void 0?t:"").toLowerCase()==="true",entityname:a.getAttribute("entityname")||""})}}return n}function NL(e){let t=e.getElementsByTagName("entity")[0],r={type:"and",conditions:[],groups:[]};if(!t)return r;let n=Kt(t,"filter").filter(i=>!qf(i)).map(zy);return n.length===0?r:n.length===1?n[0]:{type:"and",conditions:[],groups:n}}function qf(e){if(e.getAttribute("isquickfindfields")==="1")return!0;if(Kt(e,"filter").length>0)return!1;let t=Kt(e,"condition");return t.length===0?!1:t.some(r=>r.getAttribute("isquickfindfields")==="1"||Kt(r,"value").length>0||bZ(r))}var yZ=new Set(["attribute","operator","value","entityname","uiname","uitype"]);function bZ(e){var t;let r=e.attributes;for(let n=0;n<r.length;n+=1){let i=(t=r[n])===null||t===void 0?void 0:t.name;if(i&&!yZ.has(i))return!0}return!1}function zy(e){var t,r;let n=((t=e.getAttribute("type"))!==null&&t!==void 0?t:"and").toLowerCase()==="or"?"or":"and",i=[],o=[],a=e.childNodes;for(let s=0;s<a.length;s+=1){let l=a[s];if(l.nodeType===1)if(l.tagName==="condition"){if(l.getAttribute("isquickfindfields")==="1")continue;let u=l.getAttribute("attribute");if(!u)continue;let c={attribute:u,operator:(r=l.getAttribute("operator"))!==null&&r!==void 0?r:""},d=l.getAttribute("value");d!==null&&(c.value=d);let f=l.getAttribute("entityname")||"";f&&(c.entityname=f),i.push(c)}else l.tagName==="filter"&&o.push(zy(l))}return{type:n,conditions:i,groups:o}}function Kt(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName===t&&r.push(o)}return r}var jy=e=>{var t,r;return`${(t=e.relatedEntity)!==null&&t!==void 0?t:""}::${(r=e.sourceAttribute)!==null&&r!==void 0?r:e.name}`};function vZ(e,t){let r=Wy(e),n=new Map;for(let i of t){if(!i.relatedEntity)continue;let o=r.get(i.name);if(o){let a=jy(i),s=n.get(a);s?s.push(o.link):n.set(a,[o.link])}}return n}function wZ(e,t,r,n){if(!n||n.size===0)return;let i=new Set,o=t.getElementsByTagName("link-entity");for(let s=0;s<o.length;s+=1)i.add(o[s]);let a=r.filter(s=>{if(!s.relatedEntity)return!1;let l=n.get(jy(s));return!!l&&l.some(u=>!i.has(u))});if(a.length!==0)throw new wL.ValidationError("view",e.id,a.map(s=>(0,qr.issue)(`/columns/${r.indexOf(s)}`,"view-column-orphaned-by-join-removal",`column '${s.name}' came from a join this push REMOVED. Another join matching '${s.relatedEntity}' still exists, but nothing can say whether it is the one the column belonged to \u2014 re-attaching it there would silently change the data the column shows. Remove the column too, keep the join it came from, or point the column at the join you want by setting relatedEntity to that join's alias.`)))}function hL(e){let t=CZ(e.columns);if(!gL(e.fetchBag)||!gL(e.layoutBag))return{fetchxml:LZ({...e,columns:t}),layoutxml:kZ({...e,columns:t},`${e.entityLogicalName}id`)};let r=new DOMParser().parseFromString("<root/>","text/xml"),n=yL(e.fetchBag,"fetch",r),i=yL(e.layoutBag,"grid",r),o=EL(i,n),a=!Uf(t,o),s=!Uf(e.sort,SL(n)),l=!Uf(e.filters,NL(n)),u=e.linkEntities,c=u!==void 0&&!Uf(u,AL(n)),d=c?vZ(n,o):void 0;return c&&OZ(r,n,u),c&&(RZ(e,n,t,d),wZ(e,n,t,d)),a?(bL(r,n,t,o),NZ(r,i,t)):c&&bL(r,n,t,o),s&&DZ(r,n,e.sort),l&&IZ(r,n,e.filters),{fetchxml:(0,ga.serializeNode)(n),layoutxml:(0,ga.serializeNode)(i)}}function CZ(e){return(e??[]).map((t,r)=>{var n,i;return{name:String(t.name).toLowerCase(),width:(n=t.width)!==null&&n!==void 0?n:CL,order:(i=t.order)!==null&&i!==void 0?i:r,...t.relatedEntity?{relatedEntity:t.relatedEntity}:{},...t.sourceAttribute?{sourceAttribute:String(t.sourceAttribute).toLowerCase()}:{}}})}function gL(e){return!!e&&(e.c.length>0||e.a.length>0)}function yL(e,t,r){let n={n:t,a:(0,qy.mergeAttrs)(e.a,[]),c:(0,qy.spliceChildren)(e.c,[])};return(0,qy.rebuildRaw)(n,(0,ga.domEngine)(r),null)}function bL(e,t,r,n){var i,o;let a=t.getElementsByTagName("entity")[0];if(!a)return;let s=d=>{var f,p;return`${(f=d.relatedEntity)!==null&&f!==void 0?f:""}:${d.name}:${(p=d.sourceAttribute)!==null&&p!==void 0?p:d.name}`},l=new Set(r.map(s));for(let d of n)l.has(s(d))||EZ(a,d);let u=Wy(t),c=new Set(Kt(a,"attribute").map(d=>d.getAttribute("name")).filter(d=>!!d));for(let d of[...r].sort((f,p)=>f.order-p.order))if(d.relatedEntity){let f=u.get(d.name);if(f&&f.attributeName===((i=d.sourceAttribute)!==null&&i!==void 0?i:d.name)&&(f.linkKey===d.relatedEntity||f.linkName===d.relatedEntity||!TL(a,d.relatedEntity)))continue;let p=AZ(e,a,d.relatedEntity),m=e.createElement("attribute");_L(m,d),p.appendChild(m),u.set(d.name,{linkKey:d.relatedEntity,linkName:p.getAttribute("name")||d.relatedEntity,attributeName:(o=d.sourceAttribute)!==null&&o!==void 0?o:d.name,link:p})}else{if(c.has(d.name))continue;let f=e.createElement("attribute");f.setAttribute("name",d.name),SZ(a,f),c.add(d.name)}}function _L(e,t){if(t.sourceAttribute&&t.sourceAttribute!==t.name){e.setAttribute("name",t.sourceAttribute),e.setAttribute("alias",t.name);return}e.setAttribute("name",t.name)}function EZ(e,t){if(t.relatedEntity){for(let r of Kt(e,"link-entity"))if(!(r.getAttribute("alias")!==t.relatedEntity&&r.getAttribute("name")!==t.relatedEntity)){for(let n of Kt(r,"attribute"))if((n.getAttribute("alias")||n.getAttribute("name"))===t.name){r.removeChild(n);return}}return}for(let r of Kt(e,"attribute"))if(r.getAttribute("name")===t.name){e.removeChild(r);return}}function TL(e,t,r=!1){let n=o=>o.getAttribute("alias")===t||o.getAttribute("name")===t;for(let o of Kt(e,"link-entity"))if(n(o))return o;if(r)return;let i=e.getElementsByTagName("link-entity");for(let o=0;o<i.length;o+=1)if(n(i[o]))return i[o]}function AZ(e,t,r){let n=TL(t,r);if(n)return n;let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function SZ(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 NZ(e,t,r){let n=t.getElementsByTagName("row")[0];if(!n)return;let i=[...r].sort((s,l)=>s.order-l.order),o=_Z(n);if(TZ(o,i)){for(let s=0;s<i.length;s+=1){let l=String(i[s].width);o[s].getAttribute("width")!==l&&o[s].setAttribute("width",l)}return}let a=new Map;for(let s of o){let l=s.getAttribute("name");l&&a.set(l,s),n.removeChild(s)}for(let s of i){let l=a.get(s.name);l||(l=e.createElement("cell"),l.setAttribute("name",s.name)),l.setAttribute("width",String(s.width)),n.appendChild(l)}}function _Z(e){return Kt(e,"cell").filter(t=>!!t.getAttribute("name")&&t.getAttribute("ishidden")!=="1")}function TZ(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 DZ(e,t,r){let n=t.getElementsByTagName("entity")[0];if(!n)return;let i=(f,p)=>`${f.toLowerCase()}\0${p.toLowerCase()}`,o=new Map,a=new Map,s=(f,p,m)=>{let h=f.get(p);h?h.push(m):f.set(p,[m])};for(let f of Kt(n,"order")){let p=f.getAttribute("attribute")||"";p&&(s(o,i(f.getAttribute("entityname")||"",p),f),s(a,p.toLowerCase(),f)),n.removeChild(f)}let l=new Set,u=(f,p)=>{let m=f.get(p);for(;m&&m.length>0;){let h=m.shift();if(!l.has(h))return l.add(h),h}},c=f=>{var p;let m=a.get(f.toLowerCase());if(!m)return;let h=m.filter(b=>!l.has(b)),g=(p=h.find(b=>!b.getAttribute("entityname")))!==null&&p!==void 0?p:h[0];return g&&l.add(g),g},d=r.map(f=>{let p=String(f.attribute);return f.entityname===void 0?{expression:f,element:void 0}:{expression:f,element:u(o,i(f.entityname,p))}});for(let f of d)f.expression.entityname===void 0&&(f.element=c(String(f.expression.attribute)));for(let{expression:f,element:p}of d){let m=p??e.createElement("order");m.setAttribute("attribute",f.attribute),m.setAttribute("descending",String(f.descending)),f.entityname?m.setAttribute("entityname",f.entityname):f.entityname===""&&m.removeAttribute("entityname"),n.appendChild(m)}}function IZ(e,t,r){let n=t.getElementsByTagName("entity")[0];if(n){for(let i of Kt(n,"filter"))qf(i)||n.removeChild(i);(r.conditions.length>0||r.groups.length>0)&&n.appendChild(zu(e,r))}}function Uf(e,t){return JSON.stringify(e)===JSON.stringify(t)}function OZ(e,t,r){var n;let i=t.getElementsByTagName("entity")[0];if(!i)return;let o=Kt(i,"link-entity").filter(m=>m.getAttribute("name")&&m.getAttribute("from")&&m.getAttribute("to")),a=(m,h)=>m.getAttribute(h)||"",s=new Array(r.length),l=new Set,u=m=>{r.forEach((h,g)=>{if(s[g])return;let b=o.filter(A=>!l.has(A)&&m(A,h));if(b.length!==1)return;let w=b[0];r.some((A,L)=>L!==g&&!s[L]&&m(w,A))||(s[g]=w,l.add(w))})};u((m,h)=>!!h.alias&&a(m,"name")===h.name&&a(m,"alias")===h.alias),u((m,h)=>a(m,"name")===h.name&&a(m,"from")===h.from&&a(m,"to")===h.to),u((m,h)=>a(m,"name")===h.name&&a(m,"from")===h.from),u((m,h)=>a(m,"name")===h.name&&a(m,"to")===h.to),u((m,h)=>a(m,"name")===h.name);let c=r.map((m,h)=>h).filter(m=>!s[m]),d=o.filter(m=>!l.has(m)),f=new Map;for(let m of d){let h=f.get(a(m,"name"));h?h.push(m):f.set(a(m,"name"),[m])}let p=new Map;for(let m of c){let h=p.get(r[m].name);h?h.push(m):p.set(r[m].name,[m])}for(let[m,h]of p){let g=(n=f.get(m))!==null&&n!==void 0?n:[];g.length===h.length&&h.forEach((b,w)=>{s[b]=g[w],l.add(g[w])})}r.forEach((m,h)=>{let g=s[h];if(g){vL(e,g,m);return}let b=e.createElement("link-entity");vL(e,b,m),i.appendChild(b)});for(let m of o)l.has(m)||i.removeChild(m)}var PZ=new Set(["inner","outer"]);function RZ(e,t,r,n){if(!t.getElementsByTagName("entity")[0])return;let o=new Set,a=t.getElementsByTagName("link-entity");for(let c=0;c<a.length;c+=1){let d=a[c],f=d.getAttribute("name"),p=d.getAttribute("alias");f&&o.add(f),p&&o.add(p)}let s=new Set;for(let c=0;c<a.length;c+=1)s.add(a[c]);let l=c=>{let d=n?.get(jy(c));return!!d&&d.every(f=>s.has(f))},u=r.filter(c=>c.relatedEntity&&!o.has(c.relatedEntity)&&!l(c));if(u.length!==0)throw new wL.ValidationError("view",e.id,u.map(c=>{var d;let f=((d=e.linkEntities)!==null&&d!==void 0?d:[]).some(p=>p.name===c.relatedEntity||p.alias===c.relatedEntity);return(0,qr.issue)(`/columns/${r.indexOf(c)}`,"view-column-dangling-link",`column '${c.name}' has relatedEntity '${c.relatedEntity}', but no matching join remains in linkEntities. `+(f?"Remove the column too, or keep the join.":"That join is NESTED (a join off a join), which the typed layer does not model, so it cannot be re-declared in linkEntities \u2014 it only survives while the join above it does. Remove the column, or restore the parent join this push replaced."))}))}function vL(e,t,r){t.setAttribute("name",r.name),t.setAttribute("from",r.from),t.setAttribute("to",r.to),r.alias?t.setAttribute("alias",r.alias):t.removeAttribute("alias"),r.linkType?t.setAttribute("link-type",r.linkType):PZ.has(t.getAttribute("link-type")||"")&&t.removeAttribute("link-type");let n=Kt(t,"filter").find(o=>!qf(o)),i=r.filters&&(r.filters.conditions.length>0||r.filters.groups.length>0)?zu(e,r.filters):null;n&&i?t.replaceChild(i,n):n?t.removeChild(n):i&&t.appendChild(i)}function LZ(e){var t;let r=new DOMParser().parseFromString("<fetch/>","text/xml"),n=r.documentElement;n.setAttribute("version","1.0"),n.setAttribute("mapping","logical");let i=r.createElement("entity");i.setAttribute("name",e.entityLogicalName),n.appendChild(i);let o=new Map;for(let a of(t=e.linkEntities)!==null&&t!==void 0?t:[]){let s=r.createElement("link-entity");s.setAttribute("name",a.name),s.setAttribute("from",a.from),s.setAttribute("to",a.to),a.alias&&s.setAttribute("alias",a.alias),a.linkType&&s.setAttribute("link-type",a.linkType),a.filters&&(a.filters.conditions.length>0||a.filters.groups.length>0)&&s.appendChild(zu(r,a.filters)),i.appendChild(s);for(let l of[a.alias||a.name,a.name])o.has(l)||o.set(l,s)}for(let a of[...e.columns].sort((s,l)=>s.order-l.order)){let s=r.createElement("attribute");if(a.relatedEntity){_L(s,a);let l=o.get(a.relatedEntity);l||(l=r.createElement("link-entity"),l.setAttribute("name",a.relatedEntity),i.appendChild(l),o.set(a.relatedEntity,l)),l.appendChild(s)}else s.setAttribute("name",a.name),i.appendChild(s)}for(let a of e.sort){let s=r.createElement("order");s.setAttribute("attribute",a.attribute),s.setAttribute("descending",String(a.descending)),a.entityname&&s.setAttribute("entityname",a.entityname),i.appendChild(s)}return(e.filters.conditions.length>0||e.filters.groups.length>0)&&i.appendChild(zu(r,e.filters)),new XMLSerializer().serializeToString(r)}function zu(e,t){let r=e.createElement("filter");r.setAttribute("type",t.type);for(let n of t.conditions){let i=e.createElement("condition");i.setAttribute("attribute",n.attribute),i.setAttribute("operator",n.operator),n.entityname&&i.setAttribute("entityname",n.entityname),n.value!==void 0&&i.setAttribute("value",n.value),r.appendChild(i)}for(let n of t.groups)r.appendChild(zu(e,n));return r}function kZ(e,t){var r;let n=new DOMParser().parseFromString("<grid/>","text/xml"),i=n.documentElement,o=[...e.columns].sort((s,l)=>s.order-l.order);i.setAttribute("name","resultset"),i.setAttribute("jump",((r=o[0])===null||r===void 0?void 0:r.name)||t||`${e.entityLogicalName}id`),i.setAttribute("select","1"),i.setAttribute("icon","1"),i.setAttribute("preview","1");let a=n.createElement("row");a.setAttribute("name","result"),a.setAttribute("id",t||`${e.entityLogicalName}id`),i.appendChild(a);for(let s of o){let l=n.createElement("cell");l.setAttribute("name",s.name),l.setAttribute("width",String(s.width)),a.appendChild(l)}return new XMLSerializer().serializeToString(n)}function xZ(){return{adapter:new Bf,api:pZ.viewApi,publish:(e,t,r)=>(0,mL.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,mL.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}js.viewRegistration=xZ});function Vf(e,t){return e==="SetFieldValue"&&t!==void 0&&$Z.has(t.attributeType)&&(t.requiredLevel==="None"||t.requiredLevel==="Recommended")}var $Z,Hy=k(()=>{"use strict";$Z=new Set(["Integer","Double","Decimal","Money","String","Memo","DateTime","Picklist","Lookup"])});function IL(e){return e!=="Entity"&&e!=="AllForms"&&typeof e=="string"&&e.trim()!==""}function Ky(e){return e==="AllForms"||IL(e)?1:2}function Jy(e){return IL(e)?e:null}function OL(e,t){return{"@odata.type":"#Microsoft.Dynamics.CRM.workflow",name:e.name,description:e.description,workflowid:t,ondemand:!1,subprocess:!1,triggeroncreate:!1,triggerondelete:!1,category:Hs.WorkflowCategory.BusinessRule,type:Hs.WorkflowTypeCode.Definition,mode:1,scope:Hs.WorkflowScope.Organization,primaryentity:e.entityLogicalName,iscrmuiworkflow:!0,processtriggerscope:Ky(e.scope),processtriggerformid:Jy(e.scope)}}var Hs,PL=k(()=>{"use strict";Hs=we(Ji());});function RL(e,t=0){return(kt[e[t+0]]+kt[e[t+1]]+kt[e[t+2]]+kt[e[t+3]]+"-"+kt[e[t+4]]+kt[e[t+5]]+"-"+kt[e[t+6]]+kt[e[t+7]]+"-"+kt[e[t+8]]+kt[e[t+9]]+"-"+kt[e[t+10]]+kt[e[t+11]]+kt[e[t+12]]+kt[e[t+13]]+kt[e[t+14]]+kt[e[t+15]]).toLowerCase()}var kt,LL=k(()=>{kt=[];for(let e=0;e<256;++e)kt.push((e+256).toString(16).slice(1))});function Yy(){return Gf>Wf.length-16&&((0,kL.randomFillSync)(Wf),Gf=0),Wf.slice(Gf,Gf+=16)}var kL,Wf,Gf,xL=k(()=>{kL=require("crypto"),Wf=new Uint8Array(256),Gf=Wf.length});var $L,Qy,FL=k(()=>{$L=require("crypto"),Qy={randomUUID:$L.randomUUID}});function FZ(e,t,r){if(Qy.randomUUID&&!t&&!e)return Qy.randomUUID();e=e||{};let n=e.random??e.rng?.()??Yy();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 RL(n)}var sr,ML=k(()=>{FL();xL();LL();sr=FZ});var Xy=k(()=>{ML()});var UL=k(()=>{"use strict";});function BL(e){return e!=null&&MZ.has(e)}function zf(e){if(e==null)return!1;let t=e.trim();if(!/^[+-]?\d+$/.test(t))return!1;let r=Number(t);return Number.isInteger(r)&&r>=-2147483648&&r<=2147483647}var MZ,Zy=k(()=>{"use strict";MZ=new Set(["Picklist","State","Status"])});var jf=v(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.WorkflowConditionOperator=un.WorkflowAttributeType=un.SystemStep=un.FieldRequiredLevelTypes=un.AttributeDateTimeBehavior=void 0;un.AttributeDateTimeBehavior={None:0,Dynamic:1,DateOnly:2,StaticTimeZoneInvariant:3,UserLocal:4};un.FieldRequiredLevelTypes={None:"0",Required:"1",Recommended:"2"};un.SystemStep={IdentifyContact:"IdentifyContact",IdentifyAccount:"IdentifyAccount",IdentifyCustomer:"IdentifyCustomer",IdentifyCase:"IdentifyCase",Solution:"Solution",Resolve:"Resolve"};un.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"};un.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 Hf(e){return e!=null&&VL.includes(e)}function eb(e){return e===oe.WorkflowAttributeType.Integer}function tb(e,t){return t===oe.WorkflowConditionOperator.Equal||t===oe.WorkflowConditionOperator.NotEqual?e:UZ.includes(t)?VL.includes(e)||e===oe.WorkflowAttributeType.DateTime?e:oe.WorkflowAttributeType.String:t===oe.WorkflowConditionOperator.On||t===oe.WorkflowConditionOperator.NotOn?e===oe.WorkflowAttributeType.DateTime?e:oe.WorkflowAttributeType.String:oe.WorkflowAttributeType.String}function GL(e){let t=e.leftWorkflowType??e.valueWorkflowType??oe.WorkflowAttributeType.String,r=ju[e.operator]??oe.WorkflowConditionOperator.Equal;return tb(t,r)}function WL(e,t){let r=e.trim(),i=(r.startsWith("+")||r.startsWith("-")?r.slice(1):r).split(".");if(i.length>2)return!1;let[o,a=""]=i;return o.length===0&&a.length===0||!qL.test(o)||!qL.test(a)||o.length>1&&o.startsWith("0")||o.length>BZ?!1:t!==oe.WorkflowAttributeType.Integer||i.length===1}var oe,ju,VL,UZ,qL,BZ,rb=k(()=>{"use strict";oe=we(jf());ju={Equals:oe.WorkflowConditionOperator.Equal,DoesNotEqual:oe.WorkflowConditionOperator.NotEqual,IsGreaterThan:oe.WorkflowConditionOperator.GreaterThan,IsLessThan:oe.WorkflowConditionOperator.LessThan,IsGreaterThanEqualTo:oe.WorkflowConditionOperator.GreaterThanOrEqual,IsLessThanEqualTo:oe.WorkflowConditionOperator.LessThanOrEqual,Contains:oe.WorkflowConditionOperator.Contains,DoesNotContain:oe.WorkflowConditionOperator.DoesNotContain,BeginsWith:oe.WorkflowConditionOperator.BeginsWith,DoesNotBeginWith:oe.WorkflowConditionOperator.DoesNotBeginWith,EndsWith:oe.WorkflowConditionOperator.EndsWith,DoesNotEndWith:oe.WorkflowConditionOperator.DoesNotEndWith,On:oe.WorkflowConditionOperator.On,NotOn:oe.WorkflowConditionOperator.NotOn,ContainsData:oe.WorkflowConditionOperator.NotNull,DoesNotContainData:oe.WorkflowConditionOperator.IsNull},VL=[oe.WorkflowAttributeType.Decimal,oe.WorkflowAttributeType.Float,oe.WorkflowAttributeType.Integer,oe.WorkflowAttributeType.Money],UZ=[oe.WorkflowConditionOperator.GreaterThan,oe.WorkflowConditionOperator.GreaterThanOrEqual,oe.WorkflowConditionOperator.LessThan,oe.WorkflowConditionOperator.LessThanOrEqual];qL=/^\d*$/,BZ=28});var zL=k(()=>{"use strict";});function On(e){return!qZ.has(e)}function nb(e){return e==="Equals"||e==="DoesNotEqual"}function Kf(e){return HL.has(e)?VZ:HZ.has(e)?GZ:KL.has(e)?WZ:JZ.has(e)?jZ:zZ}function JL(e){return Kf(e)[0]}function YL(e,t){return Kf(t).includes(e)}function jL(e){return HL.has(e)?"string":e==="Money"?"money":e==="Integer"||e==="BigInt"?"integer":e==="Decimal"||e==="Double"?"decimal":KL.has(e)?"date":KZ.has(e)?"boolean":"other"}function Jf(e,t){let r=jL(e),n=jL(t);return r==="other"||n==="other"?e===t:r===n}var qZ,VZ,GZ,WZ,zZ,jZ,HL,HZ,KL,KZ,JZ,Yf=k(()=>{"use strict";zL();qZ=new Set(["ContainsData","DoesNotContainData"]);VZ=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],GZ=["Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],WZ=["On","NotOn","Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],zZ=["Equals","DoesNotEqual","ContainsData","DoesNotContainData"],jZ=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],HL=new Set(["String","Memo","EntityName"]),HZ=new Set(["Integer","BigInt","Money","Decimal","Double"]),KL=new Set(["DateTime"]),KZ=new Set(["Boolean"]),JZ=new Set(["Lookup","Owner","Customer"])});function e1(e){switch(e){case"Boolean":return Fe.WorkflowAttributeType.Boolean;case"Customer":return Fe.WorkflowAttributeType.Customer;case"DateTime":return Fe.WorkflowAttributeType.DateTime;case"Decimal":return Fe.WorkflowAttributeType.Decimal;case"Double":return Fe.WorkflowAttributeType.Float;case"Integer":return Fe.WorkflowAttributeType.Integer;case"Lookup":return Fe.WorkflowAttributeType.Lookup;case"Money":return Fe.WorkflowAttributeType.Money;case"Owner":return Fe.WorkflowAttributeType.Owner;case"Picklist":return Fe.WorkflowAttributeType.Picklist;case"State":return Fe.WorkflowAttributeType.State;case"Status":return Fe.WorkflowAttributeType.Status;case"Uniqueidentifier":case"UniqueIdentifier":return Fe.WorkflowAttributeType.UniqueIdentifier;case"BigInt":return Fe.WorkflowAttributeType.BigType;default:return Fe.WorkflowAttributeType.String}}function s1(e){return e&&e!==Fe.WorkflowAttributeType.String?e:void 0}function XZ(e){return{__class:a1,parameterName:"primaryEntity",entityName:e}}function QL(e){return{__class:ob,type:ib,typeSet:!1,behavior:Fe.AttributeDateTimeBehavior.None,method:t1,parameters:[e]}}function XL(e,t,r=Fe.WorkflowAttributeType.String){return{__class:n1,type:r,behavior:Fe.AttributeDateTimeBehavior.None,typeSet:!1,entity:XZ(t),attributeName:e}}function ZZ(e,t=Fe.WorkflowAttributeType.String){return{__class:i1,type:t,behavior:Fe.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function eee(e){return{__class:o1,type:ib,typeSet:!1,behavior:Fe.AttributeDateTimeBehavior.None,days:e,hours:"0",minutes:"0",months:"0",years:"0"}}function l1(e,t){let r=YZ[e.operator],n=QL(XL(e.leftField,t,e.leftWorkflowType)),i;e.dateArithmetic?i=eee(e.right.value??"0"):e.right.kind==="field"?i=XL(e.right.field??"",t,e.right.workflowType):i=ZZ(e.right.value??"",e.right.workflowType??e.leftWorkflowType);let o=QL(i);return{__class:ob,type:ib,typeSet:!1,behavior:Fe.AttributeDateTimeBehavior.None,method:r1,parameters:[r,n,o]}}function u1(e){return typeof e=="object"&&e.__class===ob}function tee(e){return typeof e=="object"&&e.__class===o1}function Qf(e){return u1(e)&&e.method===t1&&e.parameters.length>0?Qf(e.parameters[0]):e}function ZL(e){if(typeof e!="object"||e.__class!==n1)return null;let t=e.entity;if(t&&t.__class&&t.__class!==a1)return null;let r=e.attributeName;return r?{field:r,workflowType:s1(e.type)}:null}function c1(e){if(!e)return null;let t=Qf(e);if(!u1(t)||t.method!==r1||t.parameters.length!==3)return null;let r=t.parameters[0],n=QZ[String(r)];if(!n)return null;let i=ZL(Qf(t.parameters[1]));if(!i)return null;let o=Qf(t.parameters[2]);if(tee(o))return n!=="+"&&n!=="-"?null:{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:String(o.days??"")},dateArithmetic:!0};let a=ZL(o);if(a)return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"field",field:a.field,workflowType:a.workflowType}};if(typeof o=="object"&&o.__class===i1){let s=o.primitiveValue;return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:s!=null?String(s):"",workflowType:s1(o.type)}}}return null}function sb(e){let t=(e??"").trim();if(!/^\d+$/.test(t))return!1;let r=Number(t);return Number.isSafeInteger(r)&&r>=ab&&r<=Ks}function ya(e){if(!e||!e.leftField)return"incomplete";if(e.right.kind==="field")return e.right.field&&e.right.field.trim()?null:"incomplete";let t=e.right.value;return!t||!t.trim()?"incomplete":e.dateArithmetic&&!sb(t)?"invalidDayCount":null}function Js(e){return ya(e)===null}var Fe,t1,r1,ib,n1,i1,ob,o1,a1,YZ,QZ,ab,Ks,Hu=k(()=>{"use strict";Fe=we(jf());Yf();t1="0",r1="3",ib="0",n1="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",i1="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",ob="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",o1="TimeSpanExpression:#Microsoft.Crm.Workflow.Expressions",a1="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions";YZ={"+":0,"-":1,"*":2,"/":3},QZ={0:"+",1:"-",2:"*",3:"/"};ab=0,Ks=2147483647});function nee(e){return e.startsWith("__")&&!ree.has(e)}function iee(e){let t=Object.create(null);return Object.keys(e).forEach(r=>{nee(r)&&(t[r]=e[r])}),Object.keys(t).length>0?t:void 0}function S1(e){return e.__class==="BinaryExpression:#Microsoft.Crm.Workflow.Expressions"}function va(e){return e.__class==="UnaryExpression:#Microsoft.Crm.Workflow.Expressions"}function Xf(e){return S1(e)||va(e)}function oee(e){return e.__class==="ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel"}function Ku(){return{list:[]}}function lb(e,t,r){return e&&e.list.length>0?{list:[{...e.list[0],description:t},...e.list.slice(1)]}:{list:[{labelId:sr(),languageCode:r,description:t}]}}function cb(e){return{__class:"PrimaryEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:"primaryEntity",entityName:e}}function rp(e,t,r,n=z.AttributeDateTimeBehavior.None){return{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:n,typeSet:!1,entity:cb(t),attributeName:e}}function ba(e,t,r=z.AttributeDateTimeBehavior.None){return{__class:"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",type:t,behavior:r,typeSet:!1,primitiveValue:e}}function lee(e){return e.bpfField==="StageCategory"?e.stageType==="SelectedStage"?T1:_1:N1}function D1(e){return e.bpfField==="StageCategory"?z.WorkflowAttributeType.BpfStageCategory:z.WorkflowAttributeType.BpfProcess}function uee(e,t){let r=D1(e),n=e.bpfField==="StageCategory"?{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,entity:{__class:"RelatedEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:`related_${f1}_${d1}`,entityName:d1,relatedAttributeName:f1},attributeName:see}:rp(aee,t,r);return{__class:"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,method:pb,parameters:[lee(e),n]}}function I1(e){let t=e;if(t.__class!=="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"||String(t.method)!==pb)return null;let r=(t.parameters??[])[0];if(typeof r!="string")return null;let n=r.replace(/^"+|"+$/g,"");return n===_1?{bpfField:"StageCategory",stageType:"ActiveStage"}:n===T1?{bpfField:"StageCategory",stageType:"SelectedStage"}:n===N1?{bpfField:"ProcessName"}:null}function Zf(e){if(!e)return!1;let t=e;if(t.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"&&String(t.method)===pb){let r=(t.parameters??[])[0];if(typeof r=="string"&&cee.has(r.replace(/^"+|"+$/g,"")))return!0}return va(e)?Zf(e.operand):S1(e)?Zf(e.left)||(e.right??[]).some(Zf):!1}function O1(e){if(e?.__class!=="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions")return!1;let t=e.entity;return t==null||t.__class==="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions"}function dee(e){if(e?.__class!=="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions")return!1;let t=e.primitiveValue;return t===!0||typeof t=="string"&&t.toLowerCase()==="true"}function p1(e){if(!e)return!1;switch(e.__class){case"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions":return O1(e);case"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions":return e.primitiveValue!=null||e.type!==void 0;case"LookupExpression:#Microsoft.Crm.Workflow.Expressions":case"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions":return!0;default:return!1}}function fee(e){let t=fb[e.conditionOperatoroperator];if(!t)return!1;let r=t==="ContainsData"||t==="DoesNotContainData";if(va(e))return r&&m1(e.operand,!0);let n=e.right??[];return n.length!==(r?0:1)?!1:m1(e.left,r,n[0])}function m1(e,t,r){return I1(e)||O1(e)?t||p1(r):!1}function db(e){if(!e||!Xf(e))return!1;let t=e.conditionOperatoroperator;if(!va(e)&&(t===z.WorkflowConditionOperator.LogicalAnd||t===z.WorkflowConditionOperator.LogicalOr)){let r=e.right??[];return r.length>0&&db(e.left)&&r.every(db)}return fee(e)}function h1(e){return!e||dee(e)?!1:Zf(e)||!db(e)}function P1(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:ba(e.id.replace(/[{}]/g,""),z.WorkflowAttributeType.UniqueIdentifier)}}function mee(e){return e===z.WorkflowAttributeType.DateTime?z.AttributeDateTimeBehavior.DateOnly:z.AttributeDateTimeBehavior.None}function hee(e,t){if(t!==z.WorkflowAttributeType.DateTime)return z.AttributeDateTimeBehavior.None;let r=e.leftDateTimeBehavior;return r!==void 0&&r!==z.AttributeDateTimeBehavior.None?r:mee(t)}function gee(e,t,r){if(t!==z.WorkflowAttributeType.DateTime)return z.AttributeDateTimeBehavior.None;let n=e.valueFieldDateTimeBehavior;return n!==void 0&&n!==z.AttributeDateTimeBehavior.None?n:r}function bee(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return"1";if(t==="false"||t==="0")return"0"}function _ee(e){let t=Nee.exec(e);if(t)return`${t[1]}T${t[2]}`;let r=See.exec(e);if(!r)return;let[,n,i,o,a,s,l]=r,u=Aee.indexOf(i.toLowerCase());if(u<0)return;let c=String(u+1).padStart(2,"0");return`${o}-${c}-${n}T${a}:${s}:${l}`}function Tee(e){let t=_ee(e.trim());return t!==void 0&&R1(t)?t:e}function R1(e){let t=e.trim(),r=t.indexOf("T")>=0?"T":" ",n=t.indexOf(r),i=n>=0?t.slice(0,n):t,o=n>=0?t.slice(n+1):"";if(!vee.test(i)||o.length>0&&!wee.test(o)&&!Cee.test(o)&&!Eee.test(o))return!1;let[a,s,l]=i.split("-"),u=new Date(`${a}-${s}-${l}T00:00:00Z`);return!Number.isNaN(u.getTime())&&u.getUTCFullYear()===Number(a)&&u.getUTCMonth()+1===Number(s)&&u.getUTCDate()===Number(l)}function Dee(e,t){let r={value:e,type:z.WorkflowAttributeType.String};if(t===z.WorkflowAttributeType.String||yee.includes(t)||e.trim().length===0)return r;if(t===z.WorkflowAttributeType.Boolean){let n=bee(e);return n==null?r:{value:n,type:t}}return pee.includes(t)?zf(e)?{value:e.trim(),type:t}:r:Hf(t)?{value:e.trim(),type:t}:t===z.WorkflowAttributeType.DateTime&&R1(e)?{value:e.trim(),type:t}:r}function g1(e){return e==="ContainsData"||e==="DoesNotContainData"}function y1(e){return Iee.has(e)}function b1(e,t){return{__class:"UnaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:t,operand:e}}function v1(e,t){let r=e.leftWorkflowType??e.valueWorkflowType??z.WorkflowAttributeType.String,n=ju[e.operator]??z.WorkflowConditionOperator.Equal,i=hee(e,r),o=tb(r,n);if(e.source==="BusinessProcess"){let l=uee(e,t);if(g1(e.operator))return b1(l,n);let u=D1(e);return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:l,right:[ba(e.value??"",u)]}}let a=rp(e.field,t,r,i);if(g1(e.operator))return b1(a,n);let s;if(e.valueType==="Field"&&e.valueField){let l=y1(o)&&y1(e.valueFieldWorkflowType??"")?e.valueFieldWorkflowType:o;s=[rp(e.valueField,t,l,gee(e,l,i))]}else if(e.valueType==="Lookup"){if(!e.lookupValue)throw new Error("Lookup condition is missing its record value.");s=[P1(e.lookupValue)]}else if(e.valueType==="Clear")s=[ba(null,z.WorkflowAttributeType.String,i)];else if(e.valueType==="Expression")s=[tp(e.valueType,e.value,e.valueField,t,e.expression,e.rawExpression)];else{let l=Dee(e.value??"",o);s=[ba(l.value,l.type,i)]}return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:a,right:s}}function Oee(){return ba(!0,z.WorkflowAttributeType.Boolean)}function Pee(e,t,r){if(e.length===0)return null;let n=v1(e[0],r);for(let i=1;i<e.length;i++){let o=e[i].connector??t;n={__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:o==="AND"?z.WorkflowConditionOperator.LogicalAnd:z.WorkflowConditionOperator.LogicalOr,left:n,right:[v1(e[i],r)]}}return n}function ep(e){if(!e)return{valueType:"Value",value:""};if(e.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions")return{valueType:"Field",valueField:e.attributeName,valueFieldWorkflowType:e.type};if(e.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"){if(e.primitiveValue==null)return{valueType:"Clear",valueWorkflowType:e.type};let t=String(e.primitiveValue);if(e.type===z.WorkflowAttributeType.Boolean){let r=t.trim().toLowerCase();if(r==="1"||r==="true")return{valueType:"Value",value:"true",valueWorkflowType:e.type};if(r==="0"||r==="false")return{valueType:"Value",value:"false",valueWorkflowType:e.type}}return e.type===z.WorkflowAttributeType.DateTime?{valueType:"Value",value:Tee(t),valueWorkflowType:e.type}:{valueType:"Value",value:t,valueWorkflowType:e.type}}if(e.__class==="LookupExpression:#Microsoft.Crm.Workflow.Expressions"){let t=e.staticValue,r=typeof t=="object"&&t?.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"?t.primitiveValue:t;return{valueType:"Lookup",lookupValue:{entityType:e.entityType,id:String(r??""),label:e.label,...e.type!==z.WorkflowAttributeType.Lookup?{workflowType:e.type}:{}}}}if(e.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"){let t=c1(e);return t?{valueType:"Expression",expression:t}:{valueType:"Expression",rawExpression:e}}return{valueType:"Value",value:""}}function Ree(e){let t=fb[e.conditionOperatoroperator]??"Equals",r=t==="ContainsData"||t==="DoesNotContainData",n=va(e)?e.operand:e.left,i=va(e)?[]:e.right??[],o=I1(n);if(o){let g=i[0];return{id:sr(),field:"",fieldDisplayName:"",source:"BusinessProcess",bpfField:o.bpfField,...o.stageType?{stageType:o.stageType}:{},operator:t,valueType:"Value",value:g?.primitiveValue!=null&&!r?String(g.primitiveValue):""}}let a=n.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",s=n.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"?n.attributeName:"",l=a?n.type:void 0,u=r?{valueType:"Value"}:ep(i[0]),c=l,d=a&&n.type===z.WorkflowAttributeType.DateTime&&n.behavior!==z.AttributeDateTimeBehavior.None?n.behavior:void 0,f=u.valueWorkflowType??l,p=r?void 0:i[0],h=p?.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"&&p.type===z.WorkflowAttributeType.DateTime&&p.behavior!==z.AttributeDateTimeBehavior.None?p.behavior:void 0;return{id:sr(),field:s,fieldDisplayName:s,operator:t,...u,...f?{valueWorkflowType:f}:{},...c?{leftWorkflowType:c}:{},...d!==void 0?{leftDateTimeBehavior:d}:{},...h!==void 0?{valueFieldDateTimeBehavior:h}:{}}}function w1(e){if(!e||!Xf(e))return{clauses:[],logic:"AND"};let t=[],r=(o,a)=>{let s=o.conditionOperatoroperator;if(va(o)||s!==z.WorkflowConditionOperator.LogicalAnd&&s!==z.WorkflowConditionOperator.LogicalOr){t.push({...Ree(o),...a?{connector:a}:{}});return}let l=s===z.WorkflowConditionOperator.LogicalAnd?"AND":"OR";Xf(o.left)&&r(o.left,a),(o.right??[]).filter(Xf).forEach(u=>r(u,l))};r(e,void 0);let i=t.slice(1).map(o=>o.connector??"AND")[0]??"AND";return{clauses:t,logic:i}}function tp(e,t,r,n,i,o,a,s){if(e==="Field"&&r)return rp(r,n,z.WorkflowAttributeType.String);if(e==="Expression"){if(i)return l1(i,n);if(o!=null)return o}return e==="Lookup"&&a?P1(a):e==="Clear"?ba(null,s??z.WorkflowAttributeType.String):ba(t??"",z.WorkflowAttributeType.String)}function ub(e,t){return{propertyName:e,propertyValueExpr:t}}function Ys(e){return`Step_${e.value++}`}function cn(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 C1(e,t,r){return e&&!r.used.has(e)?(r.used.add(e),e):cn(t,r)}function Lee(e){return e===A1.StateCode.Activated?"Active":"Draft"}function kee(e,t){let r=e.processtriggerscope,n=e.processtriggerformid;return r===1?n&&n.trim()!==""?n:"AllForms":r===2?"Entity":t??"Entity"}function L1(e,t=1033){return new Qs({languageCode:t}).serialize(e)}function k1(e){return new Qs().deserialize(e)}var A1,z,ree,fb,pb,N1,_1,T1,aee,see,d1,f1,cee,pee,yee,vee,wee,Cee,Eee,Aee,See,Nee,Iee,mb,Qs,hb=k(()=>{"use strict";Xy();A1=we(Ji());UL();Zy();rb();Hu();z=we(jf());ree=new Set(["__class"]);fb={};for(let e of Object.keys(ju))fb[ju[e]]=e;pb="23",N1="BpfProcess",_1="ActiveStageCategory",T1="SelectedStageCategory",aee="processid",see="stagecategory",d1="processstage",f1="stageid";cee=new Set(["ActiveStage","SelectedStage","Stage"]);pee=[z.WorkflowAttributeType.Picklist,z.WorkflowAttributeType.State,z.WorkflowAttributeType.Status];yee=[z.WorkflowAttributeType.Lookup,z.WorkflowAttributeType.Customer,z.WorkflowAttributeType.Owner];vee=/^\d{4}-\d{2}-\d{2}$/,wee=/^\d{2}:\d{2}$/,Cee=/^\d{2}:\d{2}:\d{2}$/,Eee=/^\d{2}:\d{2}:\d{2}\.\d{1,7}$/,Aee=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],See=/^[A-Za-z]{3}, (\d{2}) ([A-Za-z]{3}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/,Nee=/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}:\d{2}\.\d{1,7}|\d{2}:\d{2}:\d{2}|\d{2}:\d{2})Z$/;Iee=new Set([z.WorkflowAttributeType.Lookup,z.WorkflowAttributeType.Owner,z.WorkflowAttributeType.Customer]);mb={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"};Qs=class{resolveLabel;languageCode;entityName="";stepCounter={value:0};idCounter={counts:{},used:new Set};constructor(t={}){this.resolveLabel=t.resolveLabel??(r=>mb[r]),this.languageCode=t.languageCode??1033}label(t){return this.resolveLabel(t)}serialize(t){let r=t.wfomRoot;this.entityName=t.entityLogicalName,this.stepCounter={value:r?Number(r.nextStepIndex):1},this.idCounter={counts:{},used:new Set};let n=t.scope!=="Entity"&&t.scope!=="AllForms"?t.scope:null,i=t.rootCondition?[this.serializeConditionNode(t.rootCondition)]:[],o={...r?.reservedProperties??{},__class:"WorkflowStep:#Microsoft.Crm.Workflow.ObjectModel",id:r?.id??t.ruleId??sr(),name:r?.name??"Step_0",description:r!==void 0?r.description:t.description||null,stepLabels:Ku(),argumentsArray:[],primaryEntityName:r?.primaryEntityName??this.entityName,nextStepIndex:String(this.stepCounter.value),isCrmUIWorkflow:!0,category:r?.category??"2",businessProcessType:r?.businessProcessType??"0",mode:r?.mode??"0",title:r?.title??t.name,formId:n,workflowEntityId:r?.workflowEntityId??t.ruleId??"",variables:r?.variables??[],inputs:r?.inputs??[],steps:{list:i}};return JSON.stringify(o)}makeApplyActionStep(t){return{__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",id:cn("SetAttributeValueStep",this.idCounter),description:t.displayName||"New Action",name:t.stepName??Ys(this.stepCounter),stepLabels:{list:[]},specification:ub(t.field,tp(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType)),entity:cb(this.entityName)}}makeRecommendationActionStep(t,r,n){let i=r.map(l=>this.makeApplyActionStep(l)),o=t??"",a=n?.stepLabels,s=lb(a,o,this.languageCode);return{__class:"ActionStep:#Microsoft.Crm.Workflow.ObjectModel",id:C1(n?.id,"ActionStep",this.idCounter),name:n?.name??Ys(this.stepCounter),description:n?.description??"Action step",stepLabels:s,steps:{list:i},actionId:null,actionType:n?.actionType??"4",processId:n?.processId??sr(),uniqueName:n?.uniqueName??`id_${sr().replace(/-/g,"")}ActionStep`}}serializeAction(t){let r=cb(this.entityName),n=t.stepName??Ys(this.stepCounter),i=t.stepLabels??Ku(),o={name:n,stepLabels:i,description:t.displayName},a=t.type;switch(a){case"SetFieldValue":return{...o,id:cn("SetAttributeValueStep",this.idCounter),__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:ub(t.field,tp(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"SetDefaultValue":return{...o,id:cn("SetDefaultValueStep",this.idCounter),__class:"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:ub(t.field,tp(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"LockUnlock":return{...o,id:cn("SetDisplayModeStep",this.idCounter),__class:"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isReadOnly:t.lock,entity:r};case"SetBusinessRequired":return{...o,id:cn("SetFieldRequiredLevelStep",this.idCounter),__class:"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",requiredLevel:t.required?z.FieldRequiredLevelTypes.Required:z.FieldRequiredLevelTypes.None,entity:r};case"SetVisibility":return{...o,id:cn("SetVisibilityStep",this.idCounter),__class:"SetVisibilityStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isVisible:t.visible,entity:r};case"ShowErrorMessage":{let s=t.errorMessage||t.displayName,l=lb(t.stepLabels,s,this.languageCode);return{...o,id:cn("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=lb(t.stepLabels,s,this.languageCode),u={list:[this.makeRecommendationActionStep(t.acceptanceText,t.applyActions??[],t.recommendationActionStepMeta)]};return{...o,id:cn("SetMessageStep",this.idCounter),__class:"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel",stepLabels:l,description:t.recommendationTitle||t.displayName,controlId:t.field,entity:r,level:"RECOMMENDATION",actionSteps:u}}default:throw new Error(`Unsupported action type: ${a}`)}}serializeConditionNode(t){let r=t.stepName??Ys(this.stepCounter),n=cn("ConditionStep",this.idCounter),i=[],o=t,a=!0;for(;o;){let s=o.rawConditionExpression??Pee(o.clauses,o.logic,this.entityName),l=a?o.branchName??Ys(this.stepCounter):Ys(this.stepCounter),c={__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:a?C1(o.branchId,"ConditionBranchStep",this.idCounter):cn("ConditionBranchStep",this.idCounter),name:l,description:o.displayName,stepLabels:Ku(),conditionExpression:s??(a?Oee():void 0),steps:{list:o.trueBranch.map(f=>this.serializeBranchItem(f))}};i.push(c);let d=o.falseBranch;if(d.length===1&&d[0].kind==="condition"){o=d[0],a=!1;continue}d.length>0&&i.push(this.makeTerminalElseBranch(d)),o=void 0}return{__class:"ConditionStep:#Microsoft.Crm.Workflow.ObjectModel",id:n,name:r,description:"",stepLabels:Ku(),containsElsebranch:i.length>1,steps:{list:i}}}makeTerminalElseBranch(t){return{__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:cn("ConditionBranchStep",this.idCounter),name:"Else",description:null,stepLabels:Ku(),conditionExpression:void 0,steps:{list:t.map(r=>this.serializeBranchItem(r))}}}serializeBranchItem(t){return t.kind==="condition"?this.serializeConditionNode(t):this.serializeAction(t)}deserialize(t){let r=t,n=null,i;if(t.wfomJson)try{let o=JSON.parse(t.wfomJson);i={id:o.id==="WorkflowStep0"||!o.id?t.workflowid??sr():o.id,name:o.name,description:o.description,nextStepIndex:o.nextStepIndex,category:o.category==="0"||o.category===0?"2":o.category,businessProcessType:o.businessProcessType,mode:o.mode,title:o.title||t.name||"",primaryEntityName:o.primaryEntityName==="1"||!o.primaryEntityName?t.primaryentity??"":o.primaryEntityName,workflowEntityId:o.workflowEntityId==="00000000-0000-0000-0000-000000000000"||!o.workflowEntityId?t.workflowid??"":o.workflowEntityId,formId:o.formId,variables:o.variables,inputs:o.inputs,reservedProperties:iee(o)};let s=(o.steps?.list??[]).find(l=>l.__class==="ConditionStep:#Microsoft.Crm.Workflow.ObjectModel");s&&(n=this.deserializeConditionStep(s))}catch{}return{ruleId:t.workflowid??null,name:t.name??"",description:t.description??"",entityLogicalName:t.primaryentity??"",scope:kee(r,i?.formId),status:Lee(t.statecode),rootCondition:n,wfomRoot:i}}deserializeConditionStep(t){let r=(t.steps?.list??[]).filter(oee);return this.buildConditionNodeFromBranches(r,t,!0)}buildConditionNodeFromBranches(t,r,n){let[i,...o]=t,{clauses:a,logic:s}=w1(i?.conditionExpression),l=this.deserializeBranch(i?.steps?.list??[]),u=this.deserializeElseChain(o,r),c=i?.description||i?.name||r.description||r.name||this.label("condition");return{kind:"condition",id:(n?r.id:i?.id)??sr(),displayName:c,clauses:a,logic:s,trueBranch:l,falseBranch:u,isCollapsed:!1,stepName:n?r.name:void 0,branchId:n?i?.id:void 0,branchName:n?i?.name:void 0,...h1(i?.conditionExpression)?{rawConditionExpression:i?.conditionExpression}:{}}}deserializeElseChain(t,r){if(t.length===0)return[];let[n]=t,{clauses:i}=w1(n.conditionExpression);return i.length===0&&!h1(n.conditionExpression)?this.deserializeBranch(n.steps?.list??[]):[this.buildConditionNodeFromBranches(t,r,!1)]}deserializeBranch(t){return t.map(r=>r.__class==="ConditionStep:#Microsoft.Crm.Workflow.ObjectModel"?this.deserializeConditionStep(r):this.deserializeAction(r)).filter(r=>r!==null)}parseRecommendationApplyActions(t){let n=(t?.list??[])[0];if(!n)return{applyActions:[]};let i={id:n.id,name:n.name,description:n.description??void 0,stepLabels:n.stepLabels,processId:n.processId,uniqueName:n.uniqueName,actionType:n.actionType},o=n.stepLabels?.list,a=o&&o.length>0?o[0].description??"":"";return{applyActions:(n.steps?.list??[]).filter(l=>l.__class==="SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel").map(l=>{let u=l.specification;return{id:l.id||sr(),field:u?.propertyName??"",stepName:l.name??void 0,displayName:l.description??void 0,...ep(u?.propertyValueExpr)}}),meta:i,acceptanceText:a}}deserializeAction(t){switch(t.__class){case"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=ep(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=ep(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:o,acceptanceText:a}=this.parseRecommendationApplyActions(t.actionSteps);return{kind:"action",id:t.id,type:"Recommendation",displayName:t.description||this.label("recommendation"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,recommendationTitle:t.description||"",messageText:n,acceptanceText:a,applyActions:i,recommendationActionStepMeta:o}}return{kind:"action",id:t.id,type:"ShowErrorMessage",displayName:t.description||this.label("showErrorMessage"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,errorMessage:n||t.name||"",messageLevel:t.level??void 0,messageActionSteps:t.actionSteps}}case"ActionStep:#Microsoft.Crm.Workflow.ObjectModel":{let{applyActions:r,meta:n,acceptanceText:i}=this.parseRecommendationApplyActions({list:[t]});return{kind:"action",id:t.id,type:"Recommendation",displayName:t.name||this.label("recommendation"),stepName:t.name,stepLabels:t.stepLabels,field:t.actionControl?.controlId??"",recommendationTitle:t.name||"",messageText:t.description||"",acceptanceText:i,applyActions:r,recommendationActionStepMeta:n}}default:return null}}}});var x1=k(()=>{"use strict";});function Uee(e){return typeof e=="object"&&e!==null?e:null}function Xs(e){let t=Uee(e);if(!t)return!1;if(t.__class===Fee){let r=t;return String(r.method)===Mee?!0:Array.isArray(r.parameters)&&r.parameters.some(Xs)}if(t.__class===$ee)return Xs(t.operand);if(t.__class===xee){let r=t;return Xs(r.left)||Array.isArray(r.right)&&r.right.some(Xs)}return!1}var xee,$ee,Fee,Mee,$1=k(()=>{"use strict";x1();xee="BinaryExpression:#Microsoft.Crm.Workflow.Expressions",$ee="UnaryExpression:#Microsoft.Crm.Workflow.Expressions",Fee="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",Mee="23"});function vb(e){return Bee.has(e.type)}function gb(e,t,r,n,i,o,a){let s=i.get(r);!s||!U1.has(s.attributeType)||n!=="Value"||a?.operator&&!nb(a.operator)||o.push({nodeId:e,kind:"INVALID_VALUE_TYPE_FOR_FIELD",message:`${t}: please select a record for this lookup field; a typed text value cannot be saved.`,target:a?.target,itemId:a?.itemId,messageKey:"Validation.InvalidValueTypeForField",messageParams:{label:t}})}function qee(e,t){let r=t.get(e.field);return!!r&&U1.has(r.attributeType)&&nb(e.operator)}function yb(e){return!!(e?.entityType?.trim()&&e.id?.trim())}function bb(e,t,r){return{nodeId:e,kind:"INVALID_DAY_COUNT",message:`Please enter a whole number of days between 0 and ${Ks}.`,target:t,itemId:r,messageKey:"Validation.InvalidDayCount",messageParams:{max:Ks}}}function F1(e,t,r,n,i,o,a,s){if(i!=="Clear")return;let l=o.get(n);Vf(r,l)||a.push({nodeId:e,kind:"INVALID_CLEAR_FOR_FIELD",message:`${t}: Clear is only supported for optional fields with a legacy-compatible type.`,target:s?.target,itemId:s?.itemId,messageKey:"Validation.InvalidClearForField",messageParams:{label:t}})}function ip(e){if(!e)return!1;for(let t of[...e.trueBranch,...e.falseBranch])if(t.kind==="action"){if(vb(t))return!0}else if(ip(t))return!0;return!1}function wb(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=wb(r,t);if(n)return n}}return null}function Vee(e){if(!e||typeof e!="object")return!1;let{__class:t,primitiveValue:r}=e;return t!=="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"?!1:r===!0||typeof r=="string"&&r.toLowerCase()==="true"}function Gee(e){return e.clauses.length===0&&(e.rawConditionExpression===void 0||Vee(e.rawConditionExpression))}function zee(e){return!!e.clauses?.some(t=>t.source==="BusinessProcess")||Xs(e.rawConditionExpression)}function Zs(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=Zs(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=Zs(n,t);if(i)return i}}return null}function Cb(e,t){return{...e,trueBranch:M1(e.trueBranch,t),falseBranch:M1(e.falseBranch,t)}}function M1(e,t){return e.filter(r=>r.id!==t).map(r=>r.kind==="condition"?Cb(r,t):r)}function No(e,t,r){return e.id===t?r(e):{...e,trueBranch:e.trueBranch.map(n=>n.kind==="condition"?No(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="condition"?No(n,t,r):n)}}function np(e,t,r){return{...e,trueBranch:e.trueBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?np(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?np(n,t,r):n)}}function B1(e,t,r,n){return No(e,t,i=>({...i,trueBranch:r==="true"?[...i.trueBranch,n]:i.trueBranch,falseBranch:r==="false"?[...i.falseBranch,n]:i.falseBranch}))}function Eb(e){return e.length===1&&e[0].kind==="condition"}function Hee(e){let t=0,r=e??void 0;for(;r;){t+=1;let{falseBranch:n}=r;if(Eb(n)){r=n[0];continue}n.length>0&&(t+=1),r=void 0}return t}function Kee(e){return!!e&&Hee(e)<jee}function Jee(e,t){if(!e)return;let r=(n,i)=>{if(n.id===t)return i;let o=[];if(Eb(n.falseBranch)){let a=r(n.falseBranch[0],i);if(a)return a}else o.push(...n.falseBranch.filter(a=>a.kind==="condition"));o.push(...n.trueBranch.filter(a=>a.kind==="condition"));for(let a of o){let s=r(a,a);if(s)return s}};return r(e,e)}function q1(e,t,r){let n=Jee(e,t);return!n||!Kee(n)?e:No(e,t,i=>V1(i,r))}function V1(e,t){if(Eb(e.falseBranch))return{...e,falseBranch:[V1(e.falseBranch[0],t)]};let r=Ab(t);return r.falseBranch=e.falseBranch,{...e,falseBranch:[r]}}function G1(e,t){let r=Zs(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 No(e,r.node.id,o=>({...o,falseBranch:i}))}function W1(e,t,r){let n=Zs(e,t);if(!n)return e;let i=o=>{let a=[...o],s=a[n.index+r];return s?(a[n.index+r]=a[n.index],a[n.index]=s,a):o};return No(e,n.node.id,o=>({...o,trueBranch:n.branch==="true"?i(o.trueBranch):o.trueBranch,falseBranch:n.branch==="false"?i(o.falseBranch):o.falseBranch}))}function Ab(e){return{kind:"condition",id:sr(),displayName:e??"New Condition",clauses:[],logic:"AND",trueBranch:[],falseBranch:[],isCollapsed:!1}}function z1(e,t){let r={kind:"action",id:sr(),type:e,displayName:t??`New ${e}`};switch(e){case"Recommendation":return{...r,type:"Recommendation",field:"",recommendationTitle:"",messageText:"",applyActions:[{id:sr(),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 j1(e){if(!e)return[];let t=[];return H1(e,t),[...new Set(t)]}function H1(e,t){e.clauses.forEach(r=>{r.field&&t.push(r.field)}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"?H1(r,t):"field"in r&&r.field&&t.push(r.field)})}function K1(e,t=[],r){if(!e)return[{nodeId:"root",kind:"NO_CONDITION",message:"A business rule must include at least one condition.",target:"node"}];let n=[],i=new Map(t.map(o=>[o.logicalName,o]));return Y1(e,n,i,!0),r==="Entity"&&J1(e,n),ip(e)||n.push({nodeId:"root",kind:"NO_ACTION",message:"A business rule must include at least one action step.",target:"node"}),n}function J1(e,t){zee(e)&&t.push({nodeId:e.id,kind:"BPF_IN_ENTITY_SCOPE",message:"Process based conditions are not allowed in Entity scope.",target:"node",messageKey:"Validation.ProcessConditionNotAllowedInEntityScope"}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"&&J1(r,t)})}function Y1(e,t,r,n=!1){let i=n&&Gee(e),o=!!e.rawConditionExpression;e.clauses.length===0&&!n&&!o&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Add at least one clause to this condition.",target:"node",messageKey:"Validation.AddClause"}),i&&e.falseBranch.length>0&&t.push({nodeId:e.id,kind:"UNREACHABLE_ELSE",message:"Add a condition to the IF clause, or delete the ELSE clause it can never reach.",target:"node",messageKey:"Validation.UnreachableElse"}),e.clauses.forEach(a=>{if(o)return;if(a.source==="BusinessProcess"){a.bpfField?a.value||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:a.id}):t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a business process field for this clause.",target:"clauseField",itemId:a.id,messageKey:"Validation.SelectBusinessProcessField"});return}let s=a.valueType==="Expression"&&!a.rawExpression?ya(a.expression):null;if(!a.field)t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a field for this clause.",target:"clauseField",itemId:a.id});else if(On(a.operator)&&a.valueType==="Value"&&!a.value&&!qee(a,r))t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:a.id});else if(On(a.operator)&&a.valueType==="Value"&&a.value){let u=r.get(a.field);u?.maxLength&&a.value.length>u.maxLength&&t.push({nodeId:e.id,kind:"CLAUSE_VALUE_TOO_LONG",message:`Value exceeds the field's maximum length of ${u.maxLength} characters.`,target:"clauseValue",itemId:a.id,messageParams:{maxLength:u.maxLength}})}else On(a.operator)&&a.valueType==="Expression"&&!a.rawExpression&&!Js(a.expression)?t.push(s==="invalidDayCount"?bb(e.id,"clauseValue",a.id):{nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please complete the formula for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.CompleteClauseFormula"}):On(a.operator)&&a.valueType==="Field"&&!a.valueField&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a field to compare to for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.EmptyClauseCompareField"});On(a.operator)&&a.valueType==="Value"&&a.value&&BL(r.get(a.field)?.attributeType)&&!zf(a.value)&&t.push({nodeId:e.id,kind:"INVALID_CLAUSE_OPTION_VALUE",message:"Please enter a whole number option value for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.InvalidClauseOptionValue"});let l=GL(a);On(a.operator)&&a.valueType==="Value"&&a.value&&Hf(l)&&!WL(a.value,l)&&t.push({nodeId:e.id,kind:"INVALID_CLAUSE_NUMERIC_VALUE",message:eb(l)?"Please enter a whole number for this clause.":"Please enter a valid number for this clause.",target:"clauseValue",itemId:a.id,messageKey:eb(l)?"Validation.InvalidClauseWholeNumberValue":"Validation.InvalidClauseNumericValue"}),On(a.operator)&&a.valueType==="Lookup"&&(yb(a.lookupValue)||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a lookup record for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.EmptyClauseLookupValue"})),On(a.operator)&&gb(e.id,"Condition",a.field,a.valueType,r,t,{operator:a.operator,target:"clauseValue",itemId:a.id})}),i&&e.trueBranch.forEach(a=>{a.kind==="action"&&Wee.has(a.type)&&t.push({nodeId:a.id,kind:"ACTION_REQUIRES_CONDITION",message:"Set field value, Show error message, and Recommendation actions require a condition. Add a condition to the IF clause, or use a different action.",target:"node",messageKey:"Validation.ActionRequiresCondition",messageParams:{actionType:a.type}})}),[...e.trueBranch,...e.falseBranch].forEach(a=>{if(a.kind==="condition")Y1(a,t,r);else{if(!("field"in a)||!a.field)t.push({nodeId:a.id,kind:"EMPTY_ACTION_FIELD",message:`${a.type}: a target field is required.`,target:"actionField",messageParams:{actionType:a.type}});else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&(a.valueType??"Value")==="Value"&&!a.value?.trim())t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please provide a value.`,target:"actionValue",messageParams:{actionType:a.type}});else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Value"&&a.value){let s=r.get(a.field);s?.maxLength&&a.value.length>s.maxLength&&t.push({nodeId:a.id,kind:"ACTION_VALUE_TOO_LONG",message:`${a.type}: value exceeds the field's maximum length of ${s.maxLength} characters.`,target:"actionValue",messageParams:{actionType:a.type,maxLength:s.maxLength}})}else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Field"){if(!a.valueField)t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please select a field to copy from.`,target:"actionValue",messageKey:"Validation.SelectActionSourceField",messageParams:{actionType:a.type}});else if(r.size>0){let s=r.get(a.field),l=r.get(a.valueField);s&&l&&!Jf(s.attributeType,l.attributeType)&&t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: the source field's type is not compatible with the target field.`,target:"actionValue",messageKey:"Validation.IncompatibleActionSourceField",messageParams:{actionType:a.type}})}}else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Expression"){let s=a.rawExpression?null:ya(a.expression);!a.rawExpression&&!Js(a.expression)&&t.push(s==="invalidDayCount"?bb(a.id,"actionValue"):{nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please complete the formula.`,target:"actionValue",messageKey:"Validation.CompleteActionFormula",messageParams:{actionType:a.type}})}else(a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Lookup"&&!yb(a.lookupValue)&&t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please complete the lookup record.`,target:"actionValue",messageKey:"Validation.EmptyActionLookupValue",messageParams:{actionType:a.type}});if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.field&&(gb(a.id,a.type,a.field,a.valueType,r,t,{target:"actionValue"}),F1(a.id,a.type,a.type,a.field,a.valueType,r,t,{target:"actionValue"})),a.type==="ShowErrorMessage"&&!a.errorMessage?.trim()&&t.push({nodeId:a.id,kind:"EMPTY_ACTION_MESSAGE",message:"Show error message: please enter an error message.",target:"actionMessage"}),a.type==="Recommendation"){let s=a.applyActions??[];a.recommendationTitle?.trim()||t.push({nodeId:a.id,kind:"EMPTY_RECOMMENDATION_TITLE",message:"Recommendation: please enter a recommendation title.",target:"recommendationTitle"}),a.messageText?.trim()||t.push({nodeId:a.id,kind:"EMPTY_RECOMMENDATION_MESSAGE",message:"Recommendation: please enter a recommendation message.",target:"recommendationMessage"}),s.length===0&&t.push({nodeId:a.id,kind:"RECOMMENDATION_NO_APPLY_ACTION",message:"Recommendation: add at least one action to apply.",target:"node"}),s.forEach(l=>{if(!l.field)t.push({nodeId:a.id,kind:"EMPTY_ACTION_FIELD",message:"Recommendation: a target field is required for each action to apply.",target:"applyActionField",itemId:l.id,messageKey:"Validation.RecommendationApplyField"});else if(l.valueType==="Field")l.valueField||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please select a field to copy from.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplySourceField"});else if(l.valueType==="Expression"){let u=l.rawExpression?null:ya(l.expression);!l.rawExpression&&!Js(l.expression)&&t.push(u==="invalidDayCount"?bb(a.id,"applyActionValue",l.id):{nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the formula.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplyFormula"})}else l.valueType==="Lookup"?yb(l.lookupValue)||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the lookup record.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplyLookupValue"}):l.valueType==="Clear"||l.value?.trim()||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please enter a value for each action to apply.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplyValue"});l.field&&(gb(a.id,"Recommendation",l.field,l.valueType,r,t,{target:"applyActionValue",itemId:l.id}),F1(a.id,"Recommendation","SetFieldValue",l.field,l.valueType,r,t,{target:"applyActionValue",itemId:l.id}))})}}})}var Bee,U1,Wee,jee,Sb=k(()=>{"use strict";Xy();Hy();Yf();Hu();$1();rb();Zy();Bee=new Set(["LockUnlock","ShowErrorMessage","Recommendation","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]);U1=new Set(["Lookup","Customer","Owner"]);Wee=new Set(["SetFieldValue","ShowErrorMessage","Recommendation"]);jee=10});var Q1={};jr(Q1,{DAY_COUNT_MAX:()=>Ks,DAY_COUNT_MIN:()=>ab,DEFAULT_DESERIALIZE_LABELS:()=>mb,WorkflowJsonMapper:()=>Qs,addElseIfInTree:()=>q1,appendToBranch:()=>B1,areFieldKindsCompatible:()=>Jf,attributeTypeToWorkflowType:()=>e1,buildWorkflowEntity:()=>OL,collectUsedFields:()=>j1,createEmptyAction:()=>z1,createEmptyCondition:()=>Ab,deserializeWorkflowJson:()=>k1,findNode:()=>wb,findParent:()=>Zs,getDefaultOperatorForFieldType:()=>JL,getExpressionModelIssue:()=>ya,getOperatorsForFieldType:()=>Kf,hasAnyTriggerGeneratingAction:()=>ip,isDayCountValid:()=>sb,isExpressionModelComplete:()=>Js,isOperatorCompatible:()=>YL,isTriggerGeneratingAction:()=>vb,moveBranchItemInTree:()=>W1,operatorNeedsValue:()=>On,processTriggerFormIdFromScope:()=>Jy,processTriggerScopeFromScope:()=>Ky,removeElseIfInTree:()=>G1,removeNodeFromTree:()=>Cb,serializeToWorkflowJson:()=>L1,supportsClearForActionType:()=>Vf,updateActionInTree:()=>np,updateConditionInTree:()=>No,validateBusinessRule:()=>K1});var X1=k(()=>{"use strict";Hy();PL();hb();hb();Sb();Sb();Yf();Hu();Hu();});var Nb=v(op=>{"use strict";Object.defineProperty(op,"__esModule",{value:!0});op.cloneJson=void 0;function Yee(e){return JSON.parse(JSON.stringify(e))}op.cloneJson=Yee});var ck=v(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:!0});_o.BUSINESS_RULE_NULL_GUID=_o.businessRuleRegistration=_o.BusinessRuleAdapter=void 0;var Z1=lt(),Ju=(X1(),kr(Q1)),ek=Kr(),tk=Q(),Qee=Nb(),ri=Zr(),Xee=Sm(),Zee=lt(),ete=Ko(),tte=new Set(["ShowErrorMessage","Recommendation"]);function ok(e){var t,r;return e?[...(t=e.trueBranch)!==null&&t!==void 0?t:[],...(r=e.falseBranch)!==null&&r!==void 0?r:[]].some(n=>Array.isArray(n.trueBranch)||Array.isArray(n.falseBranch)?ok(n):tte.has(String(n.type))):!1}function rte(e){return ak((0,Qee.cloneJson)(e))}function ak(e){var t,r;let n=i=>(i??[]).map(o=>nte(o)?ak(o):o);return{...e,logic:(t=e.logic)!==null&&t!==void 0?t:"AND",clauses:(r=e.clauses)!==null&&r!==void 0?r:[],trueBranch:n(e.trueBranch),falseBranch:n(e.falseBranch)}}function nte(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 ite(e){var t;if(e===null||typeof e!="object"||Array.isArray(e))throw new tk.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 tk.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 ote="00000000-0000-0000-0000-000000000000";_o.BUSINESS_RULE_NULL_GUID=ote;var ate=new Set(["Recommendation","LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]),ste=["ruleId","name","description","entityLogicalName","scope","status","rootCondition"],lte=["kind","id","displayName","logic","clauses","trueBranch","falseBranch"],ute=["id","field","fieldDisplayName","operator","valueType","value","valueField","lookupValue","expression","rawExpression","valueWorkflowType"];function Pn(e,t){return e===void 0?t:{...e,...t}}var wa=["kind","id","type","displayName","field","stepName","stepLabels"],rk=["valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression"],cte={Recommendation:[...wa,"recommendationTitle","messageText","acceptanceText","applyActions","recommendationActionStepMeta"],LockUnlock:[...wa,"lock"],ShowErrorMessage:[...wa,"errorMessage","messageLevel","messageActionSteps"],SetFieldValue:[...wa,...rk],SetDefaultValue:[...wa,...rk],SetBusinessRequired:[...wa,"required"],SetVisibility:[...wa,"visible"]};function re(e,t){return t===void 0?{}:{[e]:t}}function sk(e){var t;return e===void 0?void 0:{...e,label:(t=e.label)!==null&&t!==void 0?t:""}}function _b(e){return{valueType:e.valueType,...re("valueWorkflowType",e.valueWorkflowType),...re("value",e.value),...re("valueField",e.valueField),...re("lookupValue",sk(e.lookupValue)),...re("expression",e.expression),...re("rawExpression",e.rawExpression)}}function lk(e,t){let r=new Set(t),n={};for(let[i,o]of Object.entries(e))r.has(i)||o!==void 0&&(n[i]=o);return Object.keys(n).length>0?n:void 0}var dte=["id","field","valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression","stepName","displayName"];function fte(e){return Pn(e.bag,{id:e.id,field:e.field,..._b(e),...re("stepName",e.stepName),...re("displayName",e.displayName)})}function pte(e){let t=lk(e,dte);return{id:e.id,field:e.field,valueType:e.valueType,...re("valueWorkflowType",e.valueWorkflowType),...re("value",e.value),...re("valueField",e.valueField),...re("lookupValue",e.lookupValue),...re("expression",e.expression),...re("rawExpression",e.rawExpression),...re("stepName",e.stepName),...re("displayName",e.displayName),...re("bag",t)}}function nk(e){return{valueType:e.valueType,...re("valueWorkflowType",e.valueWorkflowType),...re("value",e.value),...re("valueField",e.valueField),...re("lookupValue",e.lookupValue),...re("expression",e.expression),...re("rawExpression",e.rawExpression)}}function ik(e){throw new Error(`Unsupported business-rule action type: ${e.type}`)}var mte=new Set(["INVALID_CLEAR_FOR_FIELD","INVALID_VALUE_TYPE_FOR_FIELD","CLAUSE_VALUE_TOO_LONG","ACTION_VALUE_TOO_LONG"]),hte=new Set,gte="INVALID_CLEAR_FOR_FIELD";function yte(e){let t=n=>{var i;return(0,ri.isJsonObject)(n)&&(n.label===""||n.label===void 0)?{...n,label:String((i=n.id)!==null&&i!==void 0?i:"")}:n},r=n=>{if(!(0,ri.isJsonObject)(n))return n;let i={...n};"lookupValue"in i&&(i.lookupValue=t(i.lookupValue)),Array.isArray(i.applyActions)&&(i.applyActions=i.applyActions.map(r));for(let o of["clauses","trueBranch","falseBranch"])Array.isArray(i[o])&&(i[o]=i[o].map(r));return i};return r(e)}var ap=class{toArtifact(t){let r=this.residualBag(t,ste),n={id:t.ruleId,name:t.name,description:t.description,entityLogicalName:t.entityLogicalName,scope:t.scope,status:t.status,rootCondition:t.rootCondition?this.conditionToJson(t.rootCondition):null};return r&&(n.bag=r),n}fromArtifact(t){let r=t.rootCondition?this.conditionFromJson(t.rootCondition):null;return Pn(t.bag,{ruleId:t.id,name:t.name,description:t.description,entityLogicalName:t.entityLogicalName,scope:t.scope,status:t.status,rootCondition:r})}fromApiResponse(t){var r;let n=t??{},i={...(r=n.Entity)!==null&&r!==void 0?r:{},wfomJson:n.WfomJson},o=(0,Ju.deserializeWorkflowJson)(i);return this.toArtifact(o)}needsBaseLanguage(t){return ok(t.rootCondition)}toApiPayload(t,r,n){var i,o;let a=this.fromArtifact(t);a.wfomRoot&&(a.wfomRoot={...a.wfomRoot,name:t.name,title:t.name,primaryEntityName:t.entityLogicalName||a.wfomRoot.primaryEntityName});let s=(0,Ju.serializeToWorkflowJson)(a,(i=n?.baseLanguageCode)!==null&&i!==void 0?i:ete.DEFAULT_LCID),l=(o=a.ruleId)!==null&&o!==void 0?o:(0,Z1.newId)();return{Entity:this.buildWorkflowEntity(a,l),WfomJson:s,status:t.status}}createDefault(t){var r,n,i,o,a,s;let l={ruleId:(r=t.id)!==null&&r!==void 0?r:null,name:(n=t.name)!==null&&n!==void 0?n:"New business rule",description:(i=t.description)!==null&&i!==void 0?i:"",entityLogicalName:(o=t.entityLogicalName)!==null&&o!==void 0?o:"",scope:(a=t.scope)!==null&&a!==void 0?a:"Entity",status:(s=t.status)!==null&&s!==void 0?s:"Draft",rootCondition:t.rootCondition===void 0?(0,Ju.createEmptyCondition)():t.rootCondition===null?null:this.conditionFromJson(rte(ite(t.rootCondition)))},u=this.toArtifact(l);return u.id||(u.id=(0,Z1.newId)()),u}assignMissingIds(t){return(0,Zee.assignMissingIds)(t)}validate(t){let r=[],n=t.rootCondition;return n==null?r:(0,ri.isJsonObject)(n)?(uk(n,"/rootCondition",r),r):(r.push((0,ri.issue)("/rootCondition","condition-must-be-object",`rootCondition must be a JSON object or null, got ${typeof n}`)),r)}semanticIssues(t,r=[]){let n;try{n=this.fromArtifact(t)}catch(a){return[(0,ri.issue)("/rootCondition","rule-not-representable",a instanceof Error?a.message:String(a))]}let i=n.rootCondition===null?null:yte(n.rootCondition),o;return r.length===0?o=mte:r.some(a=>a.requiredLevel!==void 0)?o=hte:o=new Set([gte]),(0,Ju.validateBusinessRule)(i,r).filter(a=>!o.has(a.kind)).map(a=>(0,ri.issue)(`/rootCondition (${a.nodeId})`,`business-rule-${a.kind}`,a.message))}issuesBlockingPush(t,r=[],n){return this.semanticIssues(t,r)}columnsCheckedAtPush(t){let r;try{r=this.fromArtifact(t)}catch{return[]}let n=new Set,i=a=>{a&&n.add(a)},o=a=>{var s;for(let l of a.clauses)i(l.field),i(l.valueField);for(let l of[...a.trueBranch,...a.falseBranch]){if(l.kind==="condition"){o(l);continue}if(i(l.field),l.type==="SetFieldValue"||l.type==="SetDefaultValue")i(l.valueField);else if(l.type==="Recommendation")for(let u of(s=l.applyActions)!==null&&s!==void 0?s:[])i(u.field),i(u.valueField)}};return r.rootCondition&&o(r.rootCondition),[...n]}residualBag(t,r){return lk(t,r)}buildWorkflowEntity(t,r){return(0,Ju.buildWorkflowEntity)(t,r)}conditionToJson(t){let r=this.residualBag(t,lte),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,ute),n={id:t.id,field:t.field,fieldDisplayName:t.fieldDisplayName,operator:t.operator,valueType:t.valueType,...t.value!==void 0?{value:t.value}:{},...t.valueField!==void 0?{valueField:t.valueField}:{},...t.lookupValue!==void 0?{lookupValue:t.lookupValue}:{},...t.expression!==void 0?{expression:t.expression}:{},...t.rawExpression!==void 0?{rawExpression:t.rawExpression}:{},...t.valueWorkflowType!==void 0?{valueWorkflowType:t.valueWorkflowType}:{}};return r&&(n.bag=r),n}branchItemToJson(t){return t.kind==="condition"?this.conditionToJson(t):this.actionToJson(t)}actionToJson(t){let r=this.residualBag(t,cte[t.type]),n={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...re("stepName",t.stepName),...re("stepLabels",t.stepLabels),...re("bag",r)};switch(t.type){case"Recommendation":return{...n,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...re("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(pte),...re("recommendationActionStepMeta",t.recommendationActionStepMeta)};case"LockUnlock":return{...n,type:"LockUnlock",lock:t.lock};case"ShowErrorMessage":return{...n,type:"ShowErrorMessage",errorMessage:t.errorMessage,...re("messageLevel",t.messageLevel),...re("messageActionSteps",t.messageActionSteps)};case"SetFieldValue":return{...n,type:"SetFieldValue",...nk(t)};case"SetDefaultValue":return{...n,type:"SetDefaultValue",...nk(t)};case"SetBusinessRequired":return{...n,type:"SetBusinessRequired",required:t.required};case"SetVisibility":return{...n,type:"SetVisibility",visible:t.visible};default:return ik(t)}}conditionFromJson(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:{};return Pn(n,{kind:"condition",isCollapsed:typeof n.isCollapsed=="boolean"?n.isCollapsed:!1,id:t.id,displayName:t.displayName,logic:t.logic,clauses:t.clauses.map(i=>this.clauseFromJson(i)),trueBranch:t.trueBranch.map(i=>this.branchItemFromJson(i)),falseBranch:t.falseBranch.map(i=>this.branchItemFromJson(i))})}clauseFromJson(t){var r;return Pn(t.bag,{id:t.id,field:t.field,fieldDisplayName:(r=t.fieldDisplayName)!==null&&r!==void 0?r:t.field,operator:t.operator,valueType:t.valueType,...re("value",t.value),...re("valueField",t.valueField),...re("lookupValue",sk(t.lookupValue)),...re("expression",t.expression),...re("rawExpression",t.rawExpression),...re("valueWorkflowType",t.valueWorkflowType)})}branchItemFromJson(t){return this.isConditionJson(t)?this.conditionFromJson(t):this.actionFromJson(t)}actionFromJson(t){if(!ate.has(t.type))throw new Error(`Unsupported business-rule action type: ${t.type}`);vte(t);let r={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...re("stepName",t.stepName),...re("stepLabels",t.stepLabels)};switch(t.type){case"Recommendation":return Pn(t.bag,{...r,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...re("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(fte),...re("recommendationActionStepMeta",t.recommendationActionStepMeta)});case"LockUnlock":return Pn(t.bag,{...r,type:"LockUnlock",lock:t.lock});case"ShowErrorMessage":return Pn(t.bag,{...r,type:"ShowErrorMessage",errorMessage:t.errorMessage,...re("messageLevel",t.messageLevel),...re("messageActionSteps",t.messageActionSteps)});case"SetFieldValue":return Pn(t.bag,{...r,type:"SetFieldValue",..._b(t)});case"SetDefaultValue":return Pn(t.bag,{...r,type:"SetDefaultValue",..._b(t)});case"SetBusinessRequired":return Pn(t.bag,{...r,type:"SetBusinessRequired",required:t.required});case"SetVisibility":return Pn(t.bag,{...r,type:"SetVisibility",visible:t.visible});default:return ik(t)}}isConditionJson(t){return Object.prototype.hasOwnProperty.call(t,"clauses")&&Object.prototype.hasOwnProperty.call(t,"logic")&&!Object.prototype.hasOwnProperty.call(t,"type")}};_o.BusinessRuleAdapter=ap;function uk(e,t,r){(0,ri.optionalEnum)(e,"logic",["AND","OR"],t,"condition-logic-invalid",r),(0,ri.childObjects)(e,"clauses",t,"clause",r);for(let n of["trueBranch","falseBranch"])(0,ri.childObjects)(e,n,t,"branchItem",r).forEach(({node:o,index:a})=>{"clauses"in o||"trueBranch"in o||"falseBranch"in o?uk(o,`${t}/${n}/${a}`,r):bte(o,`${t}/${n}/${a}`,r)})}function bte(e,t,r){e.type==="SetDefaultValue"&&e.valueType==="Clear"&&r.push((0,ri.issue)(`${t}/valueType`,"clear-only-set-field-value","Clear is only supported for SetFieldValue actions."))}function vte(e){if(e.type==="SetDefaultValue"&&e.valueType==="Clear")throw new Error("Clear is only supported for SetFieldValue actions.")}function wte(){return{adapter:new ap,api:Xee.businessRuleApi,publish:(e,t,r)=>(0,ek.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,ek.boundEntityPublishScope)(t)}}_o.businessRuleRegistration=wte});var Tk=v(To=>{"use strict";Object.defineProperty(To,"__esModule",{value:!0});To.appRegistration=To.AppAdapter=To.HEADER_NAV_BOOLEAN_RULE=void 0;var Ui=Zr(),_t=ao(),Qu=lo(),Cte=Kr(),wk=Fd(),Tb=Id(),Db=so(),Ete=lt(),Ate=ue(),Ck=Ko(),Ek=Q(),Ak=Pd();Object.defineProperty(To,"HEADER_NAV_BOOLEAN_RULE",{enumerable:!0,get:function(){return Ak.HEADER_NAV_BOOLEAN_RULE}});var cp="7.0.0.0",dk=`<SiteMap IntroducedVersion="${cp}"></SiteMap>`,fk="/_imgs/imagestrips/transparent_spacer.gif",pk="/_imgs/TableIconsFluentV9/document_one_page_sparkle.svg",Ste=["Entity","Url","DefaultDashboard","Page","GenPageId"],Yu="sitemapId",mk="sitemapName",Nte="sitemapNameUnique",hk="aiDescription",gk="[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}",_te=new RegExp(`^(?:\\{${gk}\\}|${gk})$`);function yk(e,t){if(!_te.test(e.trim()))throw new Ek.ValidationError("app",t,[{pointer:"/sitemapId",rule:"app-sitemapid-guid",message:`sitemapId must be a GUID; received '${e}'.`}]);return e.trim()}function bk(e,t,r){if(e===void 0)return r;if(typeof e!="boolean")throw new Ek.ValidationError("app",t,[Sk(e)]);return e}function Sk(e){return(0,Ui.issue)("/headerAndNavigationRefresh",Ak.HEADER_NAV_BOOLEAN_RULE,`headerAndNavigationRefresh must be a boolean, got ${typeof e}`)}function Tte(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,Ate.normalizeGuid)(i,n)}catch{return}};switch(e.type){case"Entity":return t("entity")&&`Entity:${t("entity").toLowerCase()}`;case"URL":return t("url")&&`URL:${t("url").toLowerCase()}`;case"DashBoard":return r("dashboardId")&&`DashBoard:${r("dashboardId")}`;case"CustomPage":return t("page")&&`CustomPage:${t("page").toLowerCase()}`;case"GenPage":return r("genPageId")&&`GenPage:${r("genPageId")}`;default:return}}function Dte(e){var t,r,n,i;let o=[];for(let a of(r=(t=e.siteMap)===null||t===void 0?void 0:t.areas)!==null&&r!==void 0?r:[])for(let s of(n=a.groups)!==null&&n!==void 0?n:[])for(let l of(i=s.subAreas)!==null&&i!==void 0?i:[])l.type==="Entity"&&l.entity&&o.push(l.entity);return o}var dp=class{constructor(t=Ck.DEFAULT_LCID){this.lcid=t}toArtifact(t){let{bag:r,modeledEls:n}=sp(t,"Area");return{id:"",name:"",uniqueName:"",description:"",siteMap:{areas:n.map(i=>this.areaToJson(i)),bag:r},bag:(0,_t.emptyBag)()}}fromArtifact(t){(0,Db.installDomShim)();let r=this.assignMissingIds(JSON.parse(JSON.stringify(t))),n=new DOMParser().parseFromString("<root/>","text/xml"),i=this.rootToRaw(r);return(0,_t.rebuildRaw)(i,(0,Qu.domEngine)(n),null)}fromApiResponse(t){var r,n,i,o,a,s,l,u,c,d,f;(0,Db.installDomShim)();let p=t??{},m=(r=p.$sitemap)!==null&&r!==void 0?r:p,h=(0,Qu.parseXmlRoot)((n=m.sitemapxml)!==null&&n!==void 0?n:dk,dk),g=this.toArtifact(h);return g.id=(i=p.appmoduleid)!==null&&i!==void 0?i:"",g.name=(o=p.name)!==null&&o!==void 0?o:"",g.uniqueName=(a=p.uniquename)!==null&&a!==void 0?a:"",g.description=(s=p.description)!==null&&s!==void 0?s:"",p.aiappdescription&&(g.aiDescription=p.aiappdescription),g.bag={a:[[Yu,(u=(l=m.sitemapid)!==null&&l!==void 0?l:p._sitemapid_value)!==null&&u!==void 0?u:""],[mk,(c=m.sitemapname)!==null&&c!==void 0?c:""],[Nte,(d=m.sitemapnameunique)!==null&&d!==void 0?d:""],[hk,(f=p.aiappdescription)!==null&&f!==void 0?f:""]],c:[]},g}toApiPayload(t,r){var n,i,o,a,s,l,u,c,d,f,p,m,h,g,b;(0,Db.installDomShim)();let w=(0,Qu.serializeNode)(this.fromArtifact(t)),E=[],A=[];for(let R of(i=(n=t.siteMap)===null||n===void 0?void 0:n.areas)!==null&&i!==void 0?i:[])for(let I of(o=R.groups)!==null&&o!==void 0?o:[])for(let D of(a=I.subAreas)!==null&&a!==void 0?a:[])D.type==="Entity"&&D.entity?E.push(D.entity):D.type==="DashBoard"&&D.dashboardId&&A.push(D.dashboardId);let L=(s=t.bag)!==null&&s!==void 0?s:(0,_t.emptyBag)();return{sitemapId:Ob(L,Yu)||(t.sitemapId?yk(t.sitemapId,t.id):""),sitemapxml:w,sitemapname:Ob(L,mk)||t.name,appModuleId:t.id,appModuleName:t.name,appModuleDescription:t.description,...t.aiDescription!==void 0&&t.aiDescription!==(r?r.aiDescription:Ob(L,hk))?{appModuleAiDescription:t.aiDescription}:{},appModuleUniqueName:t.uniqueName,...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},...t.headerAndNavigationRefresh===void 0?{}:{appSettings:{[Tb.HEADER_AND_NAVIGATION_REFRESH]:bk(t.headerAndNavigationRefresh,(l=t.id)!==null&&l!==void 0?l:"(unknown)",!0)?Tb.APP_SETTING_ON:Tb.APP_SETTING_OFF}},...typeof t.published=="boolean"?{published:t.published}:{},entities:E,components:{forms:(c=(u=t.components)===null||u===void 0?void 0:u.forms)!==null&&c!==void 0?c:[],views:(f=(d=t.components)===null||d===void 0?void 0:d.views)!==null&&f!==void 0?f:[],charts:(m=(p=t.components)===null||p===void 0?void 0:p.charts)!==null&&m!==void 0?m:[],dashboards:[...(g=(h=t.components)===null||h===void 0?void 0:h.dashboards)!==null&&g!==void 0?g:[],...A],...((b=t.components)===null||b===void 0?void 0:b.mainFormsByTable)!==void 0?{mainFormsByTable:t.components.mainFormsByTable}:{}}}}createDefault(t){var r,n,i,o,a,s;let l=!((r=t.siteMap)===null||r===void 0)&&r.areas&&t.siteMap.areas.length>0?t.siteMap.areas:[{id:"",title:"Area",groups:[{id:"",title:"Group",subAreas:[]}]}],u=(n=t.id)!==null&&n!==void 0?n:(0,Ete.newId)();return{id:u,name:(i=t.name)!==null&&i!==void 0?i:"New App",uniqueName:(o=t.uniqueName)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",...t.aiDescription?{aiDescription:t.aiDescription}:{},siteMap:{areas:l},...t.sitemapId?{sitemapId:yk(t.sitemapId,u)}:{},...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},headerAndNavigationRefresh:bk(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(Rb):Array.isArray(r.areas)?r.areas.forEach(Rb):Array.isArray(r.groups)?Rb(r):Array.isArray(r.subAreas)?_k(r):"type"in r&&fp(r,"subarea"),t}validate(t){let r=[],n=t.published;n!==void 0&&typeof n!="boolean"&&r.push((0,Ui.issue)("/published","published-must-be-boolean",`published must be a boolean, got ${typeof n}`));let i=t.siteMap,o=t.headerAndNavigationRefresh;if(o!==void 0&&typeof o!="boolean"&&r.push(Sk(o)),i==null)return r;if(!(0,Ui.isJsonObject)(i))return r.push((0,Ui.issue)("/siteMap","sitemap-must-be-object",`siteMap must be a JSON object, got ${typeof i}`)),r;let a=(0,Ui.childObjects)(i,"areas","/siteMap","area",r),s=new Map;return a.forEach(({node:l,index:u})=>{let c=`/siteMap/areas/${u}`;(0,Ui.childObjects)(l,"groups",c,"group",r).forEach(({node:f,index:p})=>{let m=`${c}/groups/${p}`;(0,Ui.childObjects)(f,"subAreas",m,"subArea",r).forEach(({node:g,index:b})=>{let w=`${m}/subAreas/${b}`;(0,Ui.optionalEnum)(g,"type",["Entity","URL","DashBoard","CustomPage","GenPage"],w,"subarea-type-invalid",r);let E=Tte(g);if(!E)return;let A=s.get(E);if(A===void 0){s.set(E,w);return}r.push((0,Ui.issue)(w,"subarea-duplicate-target",`the sitemap already navigates to this target at ${A}; a duplicate SubArea would pin it twice and a single removeElement would leave one behind`))})})}),r}issuesBlockingPush(t){var r;return(0,wk.mainFormSetShapeIssues)((r=t.components)===null||r===void 0?void 0:r.mainFormsByTable,Dte(t))}applyServerIdentity(t,r){let n=r[Yu];if(!n)return;t.bag||(t.bag=(0,_t.emptyBag)());let i=t.bag.a.find(o=>o[0]===Yu);i?i[1]=n:t.bag.a.push([Yu,n])}areaToJson(t){var r;let{bag:n,modeledEls:i}=sp(t,"Group"),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:Ib(t,this.lcid),groups:i.map(l=>this.groupToJson(l)),bag:n},a=t.getAttribute("Icon");a&&(o.icon=a);let s=t.getAttribute("VectorIcon");return s&&(o.vectorIcon=s),o}groupToJson(t){var r;let{bag:n,modeledEls:i}=sp(t,"SubArea");return{id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:Ib(t,this.lcid),subAreas:i.map(o=>this.subAreaToJson(o)),bag:n}}subAreaToJson(t){var r;let{bag:n}=sp(t,null),i=Ite(t),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",type:i,title:Ib(t,this.lcid),bag:n};if(i==="Entity"){let l=t.getAttribute("Entity");l&&(o.entity=l)}else if(i==="DashBoard"){let l=t.getAttribute("DefaultDashboard");l&&(o.dashboardId=l);let u=t.getAttribute("Url");u&&(o.dashboardUrl=u)}else if(i==="CustomPage"){let l=t.getAttribute("Page");l&&(o.page=l)}else if(i==="GenPage"){let l=t.getAttribute("GenPageId");l&&(o.genPageId=l)}else{let l=t.getAttribute("Url");l&&(o.url=l)}let a=t.getAttribute("Icon");a&&a!==fk&&(o.icon=a);let s=t.getAttribute("VectorIcon");return s&&(o.vectorIcon=s),o}rootToRaw(t){var r,n,i,o;let a=(n=(r=t.siteMap)===null||r===void 0?void 0:r.bag)!==null&&n!==void 0?n:(0,_t.emptyBag)(),l=lp(a)?[["IntroducedVersion",cp]]:[],u=((o=(i=t.siteMap)===null||i===void 0?void 0:i.areas)!==null&&o!==void 0?o:[]).map(c=>this.areaToRaw(c));return{n:"SiteMap",a:(0,_t.mergeAttrs)(a.a,l),c:(0,_t.spliceChildren)(a.c,u)}}areaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,_t.emptyBag)(),i=lp(n),o=[],a=[];t.id&&o.push(["Id",t.id]),i&&o.push(["ShowGroups","true"],["ResourceId","SitemapDesigner.NewTitle"],["DescriptionResourceId","SitemapDesigner.NewTitle"],["IntroducedVersion",cp]),t.icon!==void 0?o.push(["Icon",t.icon]):up(n.a,"Icon")&&a.push("Icon"),t.vectorIcon!==void 0?o.push(["VectorIcon",t.vectorIcon]):up(n.a,"VectorIcon")&&a.push("VectorIcon");let s=t.groups.map(u=>this.groupToRaw(u)),l=Pb((0,_t.spliceChildren)(n.c,s),t.title,i,this.lcid);return{n:"Area",a:(0,_t.mergeAttrs)(n.a,o,a),c:l}}groupToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,_t.emptyBag)(),i=lp(n),o=[];t.id&&o.push(["Id",t.id]),i&&o.push(["ResourceId","SitemapDesigner.NewGroup"],["DescriptionResourceId","SitemapDesigner.NewGroup"],["ToolTipResourseId","SitemapDesigner.Unknown"],["IntroducedVersion",cp],["IsProfile","false"]);let a=t.subAreas.map(l=>this.subAreaToRaw(l)),s=Pb((0,_t.spliceChildren)(n.c,a),t.title,i,this.lcid);return{n:"Group",a:(0,_t.mergeAttrs)(n.a,o),c:s}}subAreaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,_t.emptyBag)(),i=lp(n),o=Pte(n.a,t.type),a=[],s=[];t.id&&a.push(["Id",t.id]),Lte(a,t),i?(a.push(["ResourceId","SitemapDesigner.NewSubArea"],["Client","All,Outlook,OutlookLaptopClient,OutlookWorkstationClient,Web"],["Sku","All,OnPremise,Live,SPLA"],["AvailableOffline","true"],["PassParams","false"]),t.icon&&a.push(["Icon",t.icon])):t.icon!==void 0?a.push(["Icon",t.icon]):up(o,"Icon",fk)&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):up(o,"VectorIcon")?t.type==="GenPage"?a.push(["VectorIcon",pk]):s.push("VectorIcon"):t.type==="GenPage"&&!Ote(o,"VectorIcon")&&a.push(["VectorIcon",pk]);let l=Pb((0,_t.spliceChildren)(n.c,[]),t.title,i,this.lcid);return{n:"SubArea",a:(0,_t.mergeAttrs)(o,a,s),c:l}}};To.AppAdapter=dp;function sp(e,t){let r=(0,Qu.nodeLikeFromDom)(e).getAllProperties().map(s=>[s.key,s.value]),n=[],i=[],o=e.childNodes,a=0;for(let s=0;s<o.length;s+=1){let l=o[s];l.nodeType!==1&&l.nodeType!==3||(l.nodeType===1&&t!==null&&l.tagName===t?i.push(l):n.push({i:a,node:(0,_t.rawFromNode)((0,Qu.nodeLikeFromDom)(l))}),a+=1)}return{bag:{a:r,c:n},modeledEls:i}}function vk(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName===t&&r.push(o)}return r}function Ib(e,t){var r;let n=vk(e,"Titles")[0];if(!n)return"";let o=vk(n,"Title").find(a=>a.getAttribute("LCID")===String(t));return o&&(r=o.getAttribute("Title"))!==null&&r!==void 0?r:""}function Ite(e){return e.getAttribute("GenPageId")?"GenPage":e.getAttribute("Entity")?"Entity":e.getAttribute("Page")?"CustomPage":e.getAttribute("DefaultDashboard")?"DashBoard":"URL"}function lp(e){return e.a.length===0&&e.c.length===0}function Ote(e,t){return e.some(([r])=>r===t)}function up(e,t,r){let n=e.find(([o])=>o===t),i=n?.[1];return!!i&&i!==r}function Ob(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function Pte(e,t){let r=Rte(t);return e.filter(([n])=>!Ste.includes(n)||r.has(n)).map(n=>[n[0],n[1]])}function Rte(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 Lte(e,t){var r,n,i,o,a;switch(t.type){case"Entity":e.push(["Entity",(r=t.entity)!==null&&r!==void 0?r:""]);break;case"URL":e.push(["Url",(n=t.url)!==null&&n!==void 0?n:""]);break;case"DashBoard":e.push(["DefaultDashboard",(i=t.dashboardId)!==null&&i!==void 0?i:""]),t.dashboardUrl!==void 0&&e.push(["Url",t.dashboardUrl]);break;case"CustomPage":e.push(["Page",(o=t.page)!==null&&o!==void 0?o:""]);break;case"GenPage":e.push(["GenPageId",(a=t.genPageId)!==null&&a!==void 0?a:""]);break;default:break}}function Pb(e,t,r,n){if(!t)return e;let i=e.findIndex(o=>o.n==="Titles");if(i>=0){let o=e.slice();return o[i]=kte(e[i],t,n),o}return r?[xte(t,n),...e]:e}function kte(e,t,r){let n=!1,i=e.c.map(o=>!n&&o.n==="Title"&&$te(o,"LCID")===String(r)?(n=!0,{n:o.n,a:(0,_t.mergeAttrs)(o.a,[["Title",t]]),c:o.c}):o);return n||i.unshift(Nk(t,r)),{n:e.n,a:e.a.map(o=>[o[0],o[1]]),c:i}}function xte(e,t){return{n:"Titles",a:[],c:[Nk(e,t)]}}function Nk(e,t){return{n:"Title",a:[["LCID",String(t)],["Title",e]],c:[]}}function $te(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function Fte(e){let t="0123456789abcdef",r="";for(let n=0;n<e;n+=1)r+=t[Math.floor(Math.random()*t.length)];return r}function fp(e,t){e&&(typeof e.id!="string"||e.id.length===0)&&(e.id=`${t}_${Fte(8)}`)}function Rb(e){var t;fp(e,"area");for(let r of(t=e.groups)!==null&&t!==void 0?t:[])_k(r)}function _k(e){var t;fp(e,"group");for(let r of(t=e.subAreas)!==null&&t!==void 0?t:[])fp(r,"subarea")}function Mte(e=Ck.DEFAULT_LCID){return{adapter:new dp(e),api:wk.appApi,languageSensitive:!0,publish:(t,r)=>(0,Cte.publishAppModule)(t,r),publishScope:t=>({envelope:"appmodule",targetIds:[t]}),rebaselineAfterPublish:"bracket"}}To.appRegistration=Mte});var Dk={};jr(Dk,{ActionType:()=>kb,AppActionOrigin:()=>Vb,AppActionVisibilityType:()=>qb,ButtonType:()=>$b,CannotUpdateAppActionColumns:()=>Ute,Context:()=>Mb,IconType:()=>xb,Location:()=>Fb,OnClickEventType:()=>Bb,Scope:()=>Ub,VisibilityType:()=>Lb});var Lb,kb,xb,$b,Fb,Mb,Ub,Bb,qb,Vb,Ute,Ik=k(()=>{"use strict";(function(e){e[e.NotSupported=0]="NotSupported",e[e.Show=1]="Show",e[e.ClassicRules=2]="ClassicRules",e[e.Expression=3]="Expression"})(Lb||(Lb={}));(function(e){e[e.NotSupported=0]="NotSupported",e[e.None=1]="None",e[e.JavaScript=2]="JavaScript",e[e.Expression=3]="Expression"})(kb||(kb={}));(function(e){e[e.NoIcon=0]="NoIcon",e[e.UseIcon=1]="UseIcon",e[e.UseWebResource=2]="UseWebResource"})(xb||(xb={}));(function(e){e[e.Standard=0]="Standard",e[e.Dropdown=1]="Dropdown",e[e.Split=2]="Split",e[e.Group=3]="Group"})($b||($b={}));(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"})(Fb||(Fb={}));(function(e){e[e.All=0]="All",e[e.Entity=1]="Entity"})(Mb||(Mb={}));(function(e){e[e.App=0]="App",e[e.Entity=1]="Entity",e[e.Global=2]="Global"})(Ub||(Ub={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.JavaScript=2]="JavaScript"})(Bb||(Bb={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.ClassicRules=2]="ClassicRules"})(qb||(qb={}));(function(e){e[e.Default=0]="Default",e[e.Migrated=1]="Migrated",e[e.MigratedClone=2]="MigratedClone"})(Vb||(Vb={}));Ute=["appactionid","appmoduleid","context","contextvalue","location","name","type","uniquename","isdisabled","origin"]});var $k=v(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.commandApi=Vr.COMMAND_ROW_NOT_IN_BAR_CODE=Vr.COMMAND_TABLE_MISMATCH_CODE=void 0;var Gb=Xt(),Dr=ye(),Do=Q(),Ir=ue();Vr.COMMAND_TABLE_MISMATCH_CODE="COMMAND_TABLE_MISMATCH";Vr.COMMAND_ROW_NOT_IN_BAR_CODE="COMMAND_ROW_NOT_IN_BAR";var Bte="OnClickEventJavaScriptWebResourceId($select=name,webresourceid),IconWebResourceId($select=name,webresourceid)";async function Wb(e,t){let r=`/EntityDefinitions(LogicalName='${(0,Ir.odataPathLiteral)(t)}')${(0,Ir.odataQuery)([["$select","MetadataId"]])}`,i=(0,Dr.ensureSuccess)(await e.get(r),e.apiUrl(r)).body,o=i?.MetadataId;return o?(0,Ir.normalizeGuid)(o,"entityMetadataId"):""}function zb(e,t){return t?`_contextentity_value eq ${t}`:`contextvalue eq '${(0,Ir.odataLiteral)(e)}'`}function Xu(e){return`Nothing was written. Re-fetch the command with fetchArtifact('command', '${e}', { overwrite: true }) \u2014 this discards local edits \u2014 and re-apply the change.`}function Ok(e,t){let r=e.entityLogicalName;if(t===void 0)return r;if(typeof r!="string"||r.toLowerCase()!==t.toLowerCase())throw new Do.SdkError(Vr.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': its JSON names table '${String(r)}'. A command's id is its table, so the push would write another table's command bar. Nothing was written. Fix its entityLogicalName, or push it under that table's id.`);return t}async function Pk(e,t,r){let n=await Wb(e,t);if(r){let i=(0,Ir.normalizeGuid)(r,"entityMetadataId");if(i!==n)throw new Do.SdkError(Vr.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': it was fetched for table id ${i}, but table '${t}' is ${n||"not resolvable"} on the server \u2014 the table was re-created, or the local copy edited. `+Xu(t))}return n}Vr.commandApi={async get(e,t){let r=t,n=await Wb(e,r),i=zb(r,n),o=`/appactions${(0,Ir.odataQuery)([["$expand",Bte],["$filter",i]])}`,a,s=await(0,Gb.collectPages)(e,o,"fetchArtifact('command')",c=>{a=c}),l={entityLogicalName:r,entityMetadataId:n,appActions:s},u={};for(let c of s){let d=typeof c.appactionid=="string"?c.appactionid:void 0;if(d){let f=c["@odata.etag"];u[(0,Ir.normalizeGuid)(d,"appactionid")]=typeof f=="string"?f:null}}return{raw:l,etag:a?(0,Dr.readEtag)(a):null,memberEtags:u}},async list(e,t){let r=t?.entityLogicalName;return r?[{type:"command",id:r,name:`${r} commands`,entityLogicalName:r,isDirty:!1}]:[]},async create(e,t,r){let n=t,i=Ok(n,r),o=await Pk(e,i,n.entityMetadataId);return Rk(e,i,{...n,entityMetadataId:o},!1)},async update(e,t,r,n,i){let o=r,a=Ok(o,t),s=await Pk(e,a,o.entityMetadataId);return Rk(e,a,{...o,entityMetadataId:s},!0,i)},async delete(e,t){let r=await Wb(e,t),n=`/appactions${(0,Ir.odataQuery)([["$select","appactionid"],["$filter",zb(t,r)]])}`,i=await(0,Gb.collectPages)(e,n,"deleteArtifact('command')");for(let o of i)o.appactionid&&await(0,Dr.deleteRecord)(e,"appactions",o.appactionid)}};async function Rk(e,t,r,n,i){let o=r.entityMetadataId?(0,Ir.normalizeGuid)(r.entityMetadataId,"entityMetadataId"):"",a=await Vte(e,t,r,o,n,i),s={};try{await Wte(e,a,o,s)}catch(l){throw(0,Do.withPartialTokens)(l,{memberEtags:s})}return{id:r.entityLogicalName,etag:null,memberEtags:s}}function xk(e){return e.replace(/[{}]/g,"").toLowerCase()}var qte={entities:/^\/entities\(([^()]+)\)$/,appactions:/^\/appactions\(([^()]+)\)$/};function Lk(e,t){let r=qte[t].exec(e);return r?xk(r[1]):void 0}async function Vte(e,t,r,n,i,o){var a,s;let l=zte(r.rows),u=new Set(l.map(f=>xk(f.appactionid))),c={writes:[],deletes:[]};for(let f of l){let p=f.body["[email protected]"];if(p!==void 0&&!(typeof p=="string"&&n!==""&&Lk(p,"entities")===n))throw new Do.SdkError(Vr.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': app action '${f.appactionid}' binds to ${typeof p=="string"?`'${p}'`:String(p)}, not to table '${t}' (${n?`/entities(${n})`:"whose id is not resolvable"}). `+Xu(t));let m=f.body["[email protected]"];if(typeof m=="string"){let h=Lk(m,"appactions");if(h===void 0||!u.has(h))throw new Do.SdkError(Vr.COMMAND_ROW_NOT_IN_BAR_CODE,`Refusing to push command '${t}': app action '${f.appactionid}' would be placed under '${m}', which is not a row of this command. `+Xu(t))}if(i&&f.exists){let h=(0,Ir.normalizeGuid)(f.appactionid,"id"),g=(a=o?.[h])!==null&&a!==void 0?a:f.etag;if(!(0,Dr.isVersionToken)(g))throw kk(t,h,"update",g);c.writes.push({kind:"patch",row:f,id:h,token:g})}else{if(p===void 0&&!n)throw new Do.SdkError("COMMAND_CONTEXT_ENTITY_UNRESOLVED",`Cannot create app action '${f.appactionid}' for entity '${r.entityLogicalName}': the entity MetadataId could not be resolved, so the required ContextEntity bind cannot be set. A row written without it is created but is permanently unreadable \u2014 commandApi.get filters on _contextentity_value. Verify the entity logical name exists and is readable, then retry.`);c.writes.push({kind:"post",row:f})}}for(let f of(s=r.deletedRowIds)!==null&&s!==void 0?s:[]){let p=(0,Ir.normalizeGuid)(f,"id"),m=o?.[p];if(!(0,Dr.isVersionToken)(m))throw kk(t,p,"delete",m);c.deletes.push({id:p,token:m})}let d=[...c.writes.flatMap(f=>f.kind==="patch"?[{id:f.id,verb:"update"}]:[]),...c.deletes.map(f=>({id:f.id,verb:"delete"}))];if(d.length>0){let f=await Gte(e,t,n),p=d.find(m=>!f.has(m.id));if(p)throw new Do.SdkError(Vr.COMMAND_ROW_NOT_IN_BAR_CODE,`Refusing to push command '${t}': it would ${p.verb} app action '${p.id}', which is not in table '${t}''s command bar on the server \u2014 a row of another table, or one deleted since the fetch. `+Xu(t))}return c}function kk(e,t,r,n){return new Do.SdkError(Dr.UPDATE_NO_ETAG_CODE,`Refusing to push command '${e}': ${typeof n=="string"&&n!==""?`the token held for app action '${t}' ('${n}') is not a version`:`no token is held for app action '${t}'`}, so its ${r} could not be made conditional and would overwrite or remove a concurrent edit. `+Xu(e))}async function Gte(e,t,r){let n=`/appactions${(0,Ir.odataQuery)([["$select","appactionid"],["$filter",zb(t,r)]])}`,i=await(0,Gb.collectPages)(e,n,"pushArtifact('command') bar membership"),o=new Set;for(let a of i)typeof a.appactionid=="string"&&o.add((0,Ir.normalizeGuid)(a.appactionid,"appactionid"));return o}async function Wte(e,t,r,n){for(let i of t.writes)if(i.kind==="patch"){let o=(0,Dr.echoWrite)("appactionid",{"If-Match":i.token}),a=`/appactions(${i.id})${o.query}`,s=(0,Dr.ensureSuccess)(await e.patch(a,i.row.body,o.options),e.apiUrl(a));n[i.id]=(0,Dr.readEtag)(s)}else{let o=(0,Dr.echoWrite)("appactionid"),a=`/appactions${o.query}`,s={...i.row.body};s["[email protected]"]===void 0&&(s["[email protected]"]=`/entities(${r})`);let l=(0,Dr.ensureSuccess)(await e.post(a,s,o.options),e.apiUrl(a)),u=(0,Dr.readCreatedId)(l,"appactionid");u&&(n[(0,Ir.normalizeGuid)(u,"appactionid")]=(0,Dr.readEtag)(l))}for(let{id:i,token:o}of[...t.deletes].reverse())await(0,Dr.deleteRecord)(e,"appactions",i,o),delete n[i]}function zte(e){let t=new Map(e.map(o=>[o.appactionid,o])),r=new Set,n=[],i=o=>{if(r.has(o.appactionid))return;let a=o.body["[email protected]"];if(typeof a=="string"){let s=/\(([^)]+)\)/.exec(a),l=s?t.get(s[1]):void 0;l&&i(l)}r.add(o.appactionid),n.push(o)};return e.forEach(i),n}});var Jk=v(el=>{"use strict";Object.defineProperty(el,"__esModule",{value:!0});el.commandRegistration=el.CommandAdapter=void 0;var it=(Ik(),kr(Dk)),Fk=Kr(),dn=Zr(),jte=$k(),Hte=lt(),tl=ue(),Kb="$ClientSvg:",Jb=".svg",Kte=2,Jte=1,Yte=1,Bk="entityMetadataId",Qte=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"]),pp=class{toArtifact(t){var r,n,i,o,a,s;let l=(r=t.appActions)!==null&&r!==void 0?r:[],u=(n=t.entityLogicalName)!==null&&n!==void 0?n:"",c=new Map;for(let p of l){let m=typeof p._parentappactionid_value=="string"&&p._parentappactionid_value?p._parentappactionid_value:"",h=(i=c.get(m))!==null&&i!==void 0?i:[];h.push(p),c.set(m,h)}let d=new Map;for(let p of(o=c.get(""))!==null&&o!==void 0?o:[]){let m=rre(p.location),h=(a=d.get(m))!==null&&a!==void 0?a:[];h.push(p),d.set(m,h)}let f=[];for(let[p,m]of d)f.push({location:p,groups:Zte(m,c,zk(p),u)});return{id:u,entityLogicalName:u,commandBars:tre(f),bag:{a:[[Bk,(s=t.entityMetadataId)!==null&&s!==void 0?s:""]]}}}fromArtifact(t){return{entityLogicalName:t.entityLogicalName,entityMetadataId:Qb(t),appActions:jb(t).map(r=>r.row)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t,r){let n=new Set(r?jb(r).map(l=>l.appactionid):[]),i=jb(t,new Set([...n].map(l=>l.toLowerCase()))),o=new Set(i.map(l=>l.appactionid)),a=i.map(l=>{let u=l.exists||n.has(l.appactionid);return{appactionid:l.appactionid,exists:u,etag:l.etag,body:u?mre(l.row):Kk(l.row)}}),s=[...n].filter(l=>!o.has(l));return{entityLogicalName:t.entityLogicalName,entityMetadataId:Qb(t),rows:a,...s.length>0?{deletedRowIds:s}:{}}}createDefault(t){var r,n,i,o;let a=(n=(r=t.entityLogicalName)!==null&&r!==void 0?r:t.id)!==null&&n!==void 0?n:"";return{id:(i=t.id)!==null&&i!==void 0?i:a,entityLogicalName:a,commandBars:(o=t.commandBars)!==null&&o!==void 0?o:[]}}assignMissingIds(t){return(0,Hte.assignMissingIds)(t)}validate(t){let r=[];return(0,dn.childObjects)(t,"commandBars","","commandBar",r).forEach(({node:i,index:o})=>{let a=`/commandBars/${o}`;(0,dn.optionalEnum)(i,"location",["MainTab","ContextualTab","HomeTab"],a,"bar-location-invalid",r),(0,dn.childObjects)(i,"groups",a,"group",r).forEach(({node:l,index:u})=>{let c=`${a}/groups/${u}`;qk(l.bag)||((0,dn.optionalGuidId)(l,"id",c,"group-id-invalid",r),typeof l.title=="string"&&l.title.length>0&&r.push({pointer:`${c}/title`,rule:"group-toplevel-title-unsupported",message:"a new top-level command group cannot have a title: Dataverse rejects a Group row with no parent (0x80040265). Leave the title empty to hold the commands without creating a group row, or nest them under a FlyoutAnchor control, which supplies the parent a group needs."})),Vk((0,dn.childObjects)(l,"controls",c,"control",r),`${c}/controls`,r)})}),r}};el.CommandAdapter=pp;function qk(e){let t=e?.a;return Array.isArray(t)&&t.length>0}function Vk(e,t,r){e.forEach(({node:n,index:i})=>{let o=`${t}/${i}`;qk(n.bag)||(0,dn.optionalGuidId)(n,"id",o,"control-id-invalid",r),(0,dn.optionalEnum)(n,"type",["Button","FlyoutAnchor","SplitButton"],o,"control-type-invalid",r);let a=n.location;a!==void 0&&(typeof a!="number"||!Number.isInteger(a)||a<0||a>6)&&r.push((0,dn.issue)(`${o}/location`,"control-location-invalid",`location must be an integer 0-6 when present, got ${JSON.stringify(a)}`)),n.action!==void 0&&n.action!==null&&((0,dn.isJsonObject)(n.action)?(0,dn.optionalEnum)(n.action,"type",["javascript"],`${o}/action`,"action-type-invalid",r):r.push((0,dn.issue)(`${o}/action`,"control-action-must-be-object",`a control action must be a JSON object when present, got ${typeof n.action}`)));let s=(0,dn.childObjects)(n,"children",o,"control",r);s.length>0&&Vk(s,`${o}/children`,r)})}function Yb(e){return{a:Object.entries(e)}}function Xte(e){return Object.fromEntries(e.a)}function mp(e,t){if(e){for(let[r,n]of e.a)if(r===t)return n}}function Qb(e){let t=mp(e.bag,Bk);return typeof t=="string"?t:""}function Zte(e,t,r,n){var i,o;let a=[],s=[];for(let l of gp(e))l.type===it.ButtonType.Group?a.push({id:Wk(l.name,n),title:typeof l.grouptitle=="string"?l.grouptitle:"",controls:gp((o=t.get((i=l.appactionid)!==null&&i!==void 0?i:""))!==null&&o!==void 0?o:[]).map(u=>hp(u,t,r,n)),bag:Yb(l)}):s.push(hp(l,t,r,n));return s.length>0&&a.unshift({id:pre(n,r),title:"",controls:s}),a}function Xb(e){let t=e.bag?mp(e.bag,"appactionid"):void 0;return typeof t=="string"&&t.trim()!==""?t:e.id}function hp(e,t,r,n){var i,o,a,s,l;let u=Wk(e.name,n),c={id:u,type:nre(e.type),label:typeof e.buttonlabeltext=="string"?e.buttonlabeltext:"",command:typeof e.appactionid=="string"?e.appactionid:u,bag:Yb(e)},d=Gk(e);d&&(c.icon=d);let f=ere(e);f&&(c.action=f),typeof e.hidden=="boolean"&&(c.hidden=e.hidden),typeof e.isdisabled=="boolean"&&(c.disabled=e.isdisabled),typeof e.location=="number"&&e.location!==r&&(c.location=e.location);let p=t.get((i=e.appactionid)!==null&&i!==void 0?i:"");if(p&&p.length>0){let m=[],h=[];for(let g of gp(p))if(g.type===it.ButtonType.Group){let b=(o=g.appactionid)!==null&&o!==void 0?o:"",w=Yb(g);c.flyoutGroupId===void 0&&(c.flyoutGroupId=(a=g.appactionid)!==null&&a!==void 0?a:void 0,c.flyoutGroupBag=w);let E=[];for(let A of gp((l=t.get((s=g.appactionid)!==null&&s!==void 0?s:""))!==null&&l!==void 0?l:[])){let L=hp(A,t,r,n);m.push(L),E.push(Xb(L))}h.push({id:b,bag:w,childIds:E})}else m.push(hp(g,t,r,n));c.children=m,h.length>1&&(c.flyoutGroups=h)}return c}function Gk(e){var t;if(!((t=e.IconWebResourceId)===null||t===void 0)&&t.name)return e.IconWebResourceId.name;if(e.fonticon)return e.fonticon.startsWith(Kb)?e.fonticon.slice(Kb.length)+Jb:e.fonticon}function ere(e){var t;let r=e.onclickeventjavascriptfunctionname;if(typeof r!="string"||!r)return;let n=e.OnClickEventJavaScriptWebResourceId,i=e._onclickeventjavascriptwebresourceid_value,o={type:"javascript",webResourceId:(t=typeof i=="string"?i:n?.webresourceid)!==null&&t!==void 0?t:"",functionName:r};n?.name&&(o.libraryName=n.name);let a=e.onclickeventjavascriptparameters;return typeof a=="string"&&a&&(o.parameters=a),o}function Mk(e){return typeof e.sequence=="number"?e.sequence:typeof e.buttonsequencepriority=="number"?e.buttonsequencepriority:0}function gp(e){return[...e].sort((t,r)=>Mk(t)-Mk(r))}function tre(e){let t={MainTab:0,ContextualTab:1,HomeTab:2};return[...e].sort((r,n)=>{var i,o;return((i=t[r.location])!==null&&i!==void 0?i:9)-((o=t[n.location])!==null&&o!==void 0?o:9)})}function Wk(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 rre(e){switch(e){case it.Location.Form:case it.Location.QuickForm:return"MainTab";case it.Location.HomePageGrid:case it.Location.Dashboard:return"HomeTab";default:return"ContextualTab"}}function zk(e){switch(e){case"MainTab":return it.Location.Form;case"HomeTab":return it.Location.HomePageGrid;default:return it.Location.SubGridStandard}}function nre(e){switch(e){case it.ButtonType.Dropdown:return"FlyoutAnchor";case it.ButtonType.Split:return"SplitButton";default:return"Button"}}function ire(e){switch(e){case"FlyoutAnchor":return it.ButtonType.Dropdown;case"SplitButton":return it.ButtonType.Split;default:return it.ButtonType.Standard}}function ore(e){var t;return e.bag&&e.bag.a.length>0?!0:((t=e.title)!==null&&t!==void 0?t:"").length>0}function jk(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 jb(e,t=new Set){var r,n,i,o;let a=[],s=Qb(e);for(let l of(r=e.commandBars)!==null&&r!==void 0?r:[]){let u=zk(l.location),c=((n=l.groups)!==null&&n!==void 0?n:[]).flatMap(p=>{var m;return(m=p.controls)!==null&&m!==void 0?m:[]}),d=c.length>0&&c.every(p=>!jk(p,t)),f=0;for(let p of(i=l.groups)!==null&&i!==void 0?i:[]){let m;if(ore(p)){let h=sre(p,u,void 0,e,s);a.push(h),m=h.appactionid}for(let h of(o=p.controls)!==null&&o!==void 0?o:[])Hk(h,u,m,e,s,a,d?f:void 0,t),f+=1}}return a}function Hk(e,t,r,n,i,o,a,s=new Set){var l;let u=are(e,t,r,n,i,a);o.push(u);let c=(l=e.children)!==null&&l!==void 0?l:[];if(c.length===0&&!(e.flyoutGroups&&e.flyoutGroups.length>0))return;let d=c.every(h=>!jk(h,s)),f=(h,g,b)=>{Hk(h,t,g,n,i,o,d?b:void 0,s)},p=e.flyoutGroups;if(p&&p.length>0){let h=new Map(c.map(A=>[Xb(A),A])),g=new Set,b=0,w;for(let[A,L]of p.entries()){let R=L.id||(A===0?Hb(u.appactionid):ev("flyout-group",`${u.appactionid}#${A}`)),I=Uk(R,t,u.appactionid,n,i,L.bag);o.push(I);let D=I.appactionid;w===void 0&&(w=D);for(let O of L.childIds){let $=h.get(O);!$||g.has(O)||(g.add(O),f($,D,b),b+=1)}}let E=w??Hb(u.appactionid);for(let A of c){let L=Xb(A);g.has(L)||(g.add(L),f(A,E,b),b+=1)}return}let m=e.flyoutGroupId||Hb(u.appactionid);o.push(Uk(m,t,u.appactionid,n,i,e.flyoutGroupBag));for(let[h,g]of c.entries())f(g,m,h)}function are(e,t,r,n,i,o){let a=Zb(e,t,r,n,i),s=a.row;o!==void 0&&typeof s.sequence!="number"&&(s.sequence=o);let l=Gk(s);return e.location!==void 0&&(s.location=e.location),s.type=ire(e.type),s.buttonlabeltext=e.label,ure(s,e.icon,l),dre(s,e.action),cre(s),e.hidden!==void 0&&(s.hidden=e.hidden),e.disabled!==void 0&&(s.isdisabled=e.disabled),{...a,row:s}}function sre(e,t,r,n,i){let o=Zb(e,t,r,n,i);return o.row.type=it.ButtonType.Group,o.row.grouptitle=e.title,o}function Uk(e,t,r,n,i,o){let a=Zb({id:e,bag:o},t,r,n,i),s=a.row;return s["[email protected]"]=`/appactions(${(0,tl.normalizeGuid)(r,"Command flyout group id")})`,s.type=it.ButtonType.Group,s.grouptitle===void 0&&(s.grouptitle=""),s.isgrouptitlehidden===void 0&&(s.isgrouptitlehidden=!0),a}function Zb(e,t,r,n,i){let o,a,s,l;if(e.bag&&e.bag.a.length>0){o=Xte(e.bag),a=!0;let u=mp(e.bag,"@odata.etag");s=typeof u=="string"?u:null;let c=mp(e.bag,"appactionid");l=typeof c=="string"&&c?c:e.id}else l=e.id,o=lre(l,t,n,i),a=!1,s=null;return r?o["[email protected]"]=`/appactions(${(0,tl.normalizeGuid)(r,"Command parent appaction id")})`:a&&typeof o._parentappactionid_value=="string"&&o._parentappactionid_value&&o.type!==it.ButtonType.Group&&(o["[email protected]"]=null),delete o._parentappactionid_value,{appactionid:l,exists:a,etag:s,row:o}}function lre(e,t,r,n){let i={appactionid:e,name:`${e}!${e.replace(/-/g,"").slice(0,32)}`,uniquename:"",location:t,context:it.Context.Entity,contextvalue:r.entityLogicalName,scope:it.Scope.Entity};return n&&(i["[email protected]"]=`/entities(${(0,tl.normalizeGuid)(n,"Command context entity metadata id")})`),i}function ure(e,t,r){if(t===r){let n=e._iconwebresourceid_value;typeof n=="string"&&n&&!e.fonticon&&(e["[email protected]"]=`/webresourceset(${(0,tl.normalizeGuid)(n,"Command icon web resource id")})`);return}if(t===void 0){e.fonticon="",e.IconWebResourceId=null;return}e.fonticon=t.toLowerCase().endsWith(Jb)?Kb+t.slice(0,t.length-Jb.length):t,e.IconWebResourceId=null}function cre(e){let t=(n,i)=>{let o=e[n];if(typeof o!="string"||o.length===0||e[`${i}@odata.bind`]!==void 0)return;let a=(0,tl.normalizeGuid)(o,`Command ${i}`);e[`${i}@odata.bind`]=`/canvasapps(${a})`};e.onclickeventtype===Jte&&t("_onclickeventformulacomponentlibraryid_value","OnClickEventFormulaComponentLibraryId");let r=e.visibilitytype;(!r||r===Yte)&&t("_visibilityformulacomponentlibraryid_value","VisibilityFormulaComponentLibraryId")}function dre(e,t){if(!(!t||t.type!=="javascript")){if(e.onclickeventtype=Kte,t.webResourceId){let r=(0,tl.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 fre(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 ev(e,t){let r="";for(let n=0;n<4;n+=1)r+=fre(`${n}:${e}:${t}`).toString(16).padStart(8,"0");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`}function Hb(e){return ev("flyout-group",e)}function pre(e,t){return ev("loose-group",`${e}|${t}`)}function Kk(e){let t={...e};for(let r of Qte)delete t[r];return t}function mre(e){let t=Kk(e);for(let r of it.CannotUpdateAppActionColumns)delete t[r];return t}function hre(){return{adapter:new pp,api:jte.commandApi,publish:(e,t,r)=>(0,Fk.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,Fk.boundEntityPublishScope)(t)}}el.commandRegistration=hre});var Qk=v(yp=>{"use strict";Object.defineProperty(yp,"__esModule",{value:!0});yp.chartApi=void 0;var gre=Xt(),Or=ye(),Ca=ue(),Yk="savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault",yre="savedqueryvisualizationid,name,primaryentitytypecode,charttype,isdefault";yp.chartApi={async get(e,t){let r=(0,Ca.normalizeGuid)(t,"id"),n=await(0,Or.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r),i=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Ca.odataQuery)([["$select",Yk]]);return{raw:(0,Or.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},async readContentThenToken(e,t){let r=(0,Ca.normalizeGuid)(t,"id"),n=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Ca.odataQuery)([["$select",Yk]]),i=(0,Or.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=await(0,Or.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r);return{raw:i.body,etag:o}},async list(e,t){let r=`/savedqueryvisualizations${(0,Ca.odataQuery)([["$select",yre],["$filter",t?.entityLogicalName?`primaryentitytypecode eq '${(0,Ca.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,gre.collectPages)(e,r,"listArtifacts('chart')")).map(i=>{var o,a;return{type:"chart",id:(o=i.savedqueryvisualizationid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",entityLogicalName:i.primaryentitytypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,Or.echoWrite)("savedqueryvisualizationid"),o=`/savedqueryvisualizations${i.query}`,a=(0,Or.ensureSuccess)(await e.post(o,(0,Or.withClientMintedId)({name:n.name,description:n.description,datadescription:n.datadescription,presentationdescription:n.presentationdescription,primaryentitytypecode:n.primaryentitytypecode,charttype:n.charttype,isdefault:n.isdefault},"savedqueryvisualizationid",r),i.options),e.apiUrl(o));return{id:(0,Or.resolveCreatedId)(a,"savedqueryvisualizationid","chart",r),etag:(0,Or.readEtag)(a)}},async update(e,t,r,n){let i=r,o=(0,Ca.normalizeGuid)(t,"id"),a=(0,Or.echoWrite)("savedqueryvisualizationid",{"If-Match":(0,Or.requireEtag)(n,"chart",o)}),s=`/savedqueryvisualizations(${o})${a.query}`,l=(0,Or.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,datadescription:i.datadescription,presentationdescription:i.presentationdescription},a.options),e.apiUrl(s));return{id:o,etag:(0,Or.readEtag)(l)}},delete(e,t){return(0,Or.deleteRecord)(e,"savedqueryvisualizations",t)}}});var hx=v(nl=>{"use strict";Object.defineProperty(nl,"__esModule",{value:!0});nl.chartRegistration=nl.ChartAdapter=void 0;var tv=ao(),Xk=Zr(),ni=lo(),Zk=Kr(),bre=Qk(),rv=so(),vre=lt(),wre=["Column","StackedColumn","StackedColumn100","Bar","StackedBar","StackedBar100","Area","StackedArea","StackedArea100","Line","Pie","Doughnut","Funnel","Tag"],Cre=new Map(wre.map(e=>[e.toLowerCase(),e]));function ix(e){var t;return e&&(t=Cre.get(e.toLowerCase()))!==null&&t!==void 0?t:"Column"}function Ere(){return'<Chart Palette="BrightPastel"><Series><Series ChartType="Column" ChartArea="Default" /></Series><ChartAreas><ChartArea Name="Default" /></ChartAreas><Legends><Legend Name="Default" /></Legends></Chart>'}function Are(e){var t,r;let n=e.entityLogicalName,i=e.series.map((h,g)=>({alias:`agg_${g}`,series:h})),o=e.categories.map((h,g)=>({alias:`grp_${g}`,category:h})),a=h=>`<attribute alias="${h.alias}" name="${rl(h.series.attribute)}" aggregate="${rl(h.series.aggregate)}" />`,s=h=>`<attribute alias="${h.alias}" name="${rl(h.category.attribute)}" groupby="true"${h.category.dateGrouping?` dategrouping="${rl(h.category.dateGrouping)}"`:""} />`,l=[],u=new Map,c=(h,g)=>{if(!h){l.push(g);return}let b=u.get(h);b?b.push(g):u.set(h,[g])};i.forEach(h=>c(h.series.relatedEntity,a(h))),o.forEach(h=>c(h.category.relatedEntity,s(h)));let d=[...u.entries()].map(([h,g])=>`<link-entity name="${rl(h)}">${g.join("")}</link-entity>`).join(""),f=l.join("")+d,p=i.map(h=>`<measurecollection><measure alias="${h.alias}" /></measurecollection>`).join(""),m=(r=(t=o[0])===null||t===void 0?void 0:t.alias)!==null&&r!==void 0?r:"";return`<datadefinition><fetchcollection><fetch mapping="logical" aggregate="true"><entity name="${rl(n)}">${f}</entity></fetch></fetchcollection><categorycollection><category alias="${m}">${p}</category></categorycollection></datadefinition>`}var bp=class{toArtifact(t){var r,n,i,o,a,s,l;(0,rv.installDomShim)();let u=(r=t.datadescription)!==null&&r!==void 0?r:"",c=(n=t.presentationdescription)!==null&&n!==void 0?n:"",d=(0,ni.parseXmlRoot)(u,"<datadefinition/>"),f=(0,ni.parseXmlRoot)(c,"<Chart/>");return{id:(i=t.savedqueryvisualizationid)!==null&&i!==void 0?i:"",name:(o=t.name)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",entityLogicalName:(s=t.primaryentitytypecode)!==null&&s!==void 0?s:"",chartType:ox(f),isDefault:(l=t.isdefault)!==null&&l!==void 0?l:!1,series:lx(d),categories:ux(d),presentation:ax(f),dataBag:u?(0,ni.projectElementBag)(d):void 0,presentationBag:c?(0,ni.projectElementBag)(f):void 0,rowBag:Sre(t.charttype,t.type)}}fromArtifact(t){(0,rv.installDomShim)();let{datadescription:r,presentationdescription:n}=Nre(t);return{savedqueryvisualizationid:t.id,name:t.name,description:t.description,primaryentitytypecode:t.entityLogicalName,datadescription:r,presentationdescription:n,charttype:ex(t.rowBag,"charttype"),type:ex(t.rowBag,"type"),isdefault:t.isDefault}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){var r,n,i,o,a,s,l;let u=this.fromArtifact(t);return{name:(r=u.name)!==null&&r!==void 0?r:"",description:(n=u.description)!==null&&n!==void 0?n:"",datadescription:(i=u.datadescription)!==null&&i!==void 0?i:"",presentationdescription:(o=u.presentationdescription)!==null&&o!==void 0?o:"",primaryentitytypecode:(a=u.primaryentitytypecode)!==null&&a!==void 0?a:"",charttype:(s=u.charttype)!==null&&s!==void 0?s:0,isdefault:(l=u.isdefault)!==null&&l!==void 0?l:!1}}createDefault(t){var r,n,i,o,a,s,l;(0,rv.installDomShim)();let u=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,vre.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New Chart",description:(o=t.description)!==null&&o!==void 0?o:"",entityLogicalName:u,chartType:(a=t.chartType)!==null&&a!==void 0?a:"Column",isDefault:(s=t.isDefault)!==null&&s!==void 0?s:!1,series:t.series&&t.series.length>0?t.series:[{attribute:"createdon",aggregate:"count"}],categories:t.categories&&t.categories.length>0?t.categories:[{attribute:"createdon",dateGrouping:"month"}],presentation:(l=t.presentation)!==null&&l!==void 0?l:{palette:"BrightPastel",showLegend:!0}}}assignMissingIds(t){return t}validate(t){let r=[],n=t;return(0,Xk.childObjects)(n,"series","","series",r),(0,Xk.childObjects)(n,"categories","","category",r),r}};nl.ChartAdapter=bp;function Sre(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 ex(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 ox(e){let t=e.getElementsByTagName("Series");for(let r=0;r<t.length;r+=1)if(t[r].getAttribute("ChartType"))return ix(t[r].getAttribute("ChartType"));return"Column"}function ax(e){var t;let r={showLegend:e.getElementsByTagName("Legend").length>0},n=e.getAttribute("Palette");n&&(r.palette=n);let i=e.getElementsByTagName("Title")[0],o=((t=i?.textContent)!==null&&t!==void 0?t:"").trim();return o&&(r.title=o),r}function vp(e){return e.getElementsByTagName("fetch")[0]}function sx(e){let t=new Map;if(!e)return t;let r=e.getElementsByTagName("link-entity");for(let n=0;n<r.length;n+=1){let i=r[n],o=i.getAttribute("name");if(!o)continue;let a=i.getElementsByTagName("attribute");for(let s=0;s<a.length;s+=1){let l=a[s],u=l.getAttribute("alias")||l.getAttribute("name");u&&t.set(u,o)}}return t}function lx(e){let t=vp(e);if(!t)return[];let r=sx(t),n=t.getElementsByTagName("attribute"),i=[];for(let o=0;o<n.length;o+=1){let a=n[o],s=a.getAttribute("aggregate");if(!s)continue;let l=a.getAttribute("name");if(!l)continue;let u={attribute:l,aggregate:s},c=a.getAttribute("charttype");c&&(u.seriesType=ix(c));let d=a.getAttribute("alias");d&&(u.alias=d);let f=d??l,p=r.get(f);p&&(u.relatedEntity=p),i.push(u)}return i}function ux(e){var t;let r=vp(e);if(!r)return[];let n=sx(r),i=r.getElementsByTagName("attribute"),o=[];for(let a=0;a<i.length;a+=1){let s=i[a];if(((t=s.getAttribute("groupby"))!==null&&t!==void 0?t:"").toLowerCase()!=="true")continue;let l=s.getAttribute("name");if(!l)continue;let u={attribute:l},c=s.getAttribute("dategrouping");c&&(u.dateGrouping=c);let d=s.getAttribute("alias");d&&(u.alias=d);let f=d??l,p=n.get(f);p&&(u.relatedEntity=p),o.push(u)}return o}function Nre(e){if(!tx(e.dataBag)||!tx(e.presentationBag)){let o=Are(e);return{datadescription:o,presentationdescription:Wre(e,o)}}let t=new DOMParser().parseFromString("<root/>","text/xml"),r=rx(e.dataBag,"datadefinition",t),n=rx(e.presentationBag,"Chart",t),i=lx(r);if(!nv(e.series,i)){let o=iv(r);_re(t,r,e.series);let a=iv(r),s=a.length>0?a:e.series.map(()=>"");cx(t,n,s,o,e.chartType)}return nv(e.categories,ux(r))||Tre(t,r,e.categories),e.chartType!==ox(n)&&px(n,e.chartType),nv(e.presentation,ax(n))||mx(n,e.presentation),{datadescription:(0,ni.serializeNode)(r),presentationdescription:(0,ni.serializeNode)(n)}}function tx(e){return!!e&&(e.c.length>0||e.a.length>0)}function cx(e,t,r,n,i){let o,a=t.childNodes;for(let d=0;d<a.length;d+=1)if(a[d].nodeType===1&&a[d].tagName==="Series"){o=a[d];break}o||(o=e.createElement("Series"),t.insertBefore(o,t.firstChild));let s=[],l=o.childNodes;for(let d=0;d<l.length;d+=1)l[d].nodeType===1&&l[d].tagName==="Series"&&s.push(l[d]);let u=new Map;n.forEach((d,f)=>{let p=s[f];if(!p)return;let m=u.get(d);m?m.push(p):u.set(d,[p])});let c=r.map(d=>{let f=u.get(d),p=f&&f.length>0?f.shift():void 0;if(p)return p;let m=e.createElement("Series");m.setAttribute("ChartType",i);let h=s.length>0?s[0].getAttribute("ChartArea"):null;return h&&m.setAttribute("ChartArea",h),m});for(let d of s)o.removeChild(d);for(let d of c)o.appendChild(d)}function iv(e){let t=[],r=e.getElementsByTagName("measure");for(let n=0;n<r.length;n+=1)t.push(r[n].getAttribute("alias")||"");return t}function rx(e,t,r){let n={n:t,a:(0,tv.mergeAttrs)(e.a,[]),c:(0,tv.spliceChildren)(e.c,[])};return(0,tv.rebuildRaw)(n,(0,ni.domEngine)(r),null)}function _re(e,t,r){let n=vp(t),i=n?.getElementsByTagName("entity")[0];!n||!i||dx(e,t,i,kre(n),r,$re,{aliasPrefix:"aggregate_column",addRef:Ore,removeRef:Lre})}function Tre(e,t,r){let n=vp(t),i=n?.getElementsByTagName("entity")[0];!n||!i||dx(e,t,i,xre(n),r,Fre,{aliasPrefix:"groupby_column",addRef:Pre,removeRef:Rre})}function dx(e,t,r,n,i,o,a){let s=new Map;for(let p of n){let m=p.getAttribute("alias");m&&s.set(m,p)}let l=new Set,u=[],c=(p,m)=>{var h;let g=Mre(r,p),b=m.relatedEntity;(g??void 0)!==(b??void 0)&&((h=p.parentNode)===null||h===void 0||h.removeChild(p),nx(e,r,p,b))};for(let p of i){let m=p.alias?s.get(p.alias):void 0;m&&!l.has(m)?(o(m,p),c(m,p),l.add(m)):u.push(p)}let d=n.filter(p=>!l.has(p)),f=0;for(let p of u)if(f<d.length){let m=d[f];o(m,p),c(m,p),l.add(m),f+=1}else{let m=e.createElement("attribute"),h=p.alias||Ire(t,a.aliasPrefix);m.setAttribute("alias",h),o(m,p),nx(e,r,m,p.relatedEntity),a.addRef(e,t,h)}for(let p of n)if(!l.has(p)){let m=p.getAttribute("alias");m&&a.removeRef(t,m),Bre(p)}}function Dre(e){let t=new Set;for(let r of["attribute","measure","category"]){let n=e.getElementsByTagName(r);for(let i=0;i<n.length;i+=1){let o=n[i].getAttribute("alias");o&&t.add(o)}}return t}function Ire(e,t){let r=Dre(e);if(!r.has(t))return t;for(let n=2;;n+=1){let i=`${t}_${n}`;if(!r.has(i))return i}}function fx(e,t){let r=t.getElementsByTagName("categorycollection")[0];if(r)return r;let n=e.createElement("categorycollection");return t.appendChild(n),n}function Ore(e,t,r){let n=fx(e,t),i=n.getElementsByTagName("category")[0];i||(i=e.createElement("category"),n.appendChild(i));let o=e.createElement("measurecollection"),a=e.createElement("measure");a.setAttribute("alias",r),o.appendChild(a),i.appendChild(o)}function Pre(e,t,r){let n=fx(e,t),i=e.createElement("category");i.setAttribute("alias",r),n.appendChild(i)}function Rre(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 Lre(e,t){var r;let n=e.getElementsByTagName("measure"),i=[];for(let o=0;o<n.length;o+=1)n[o].getAttribute("alias")===t&&i.push(n[o]);for(let o of i){let a=o.parentNode;a?.removeChild(o),a&&a.tagName==="measurecollection"&&!Vre(a)&&((r=a.parentNode)===null||r===void 0||r.removeChild(a))}}function kre(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 xre(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 $re(e,t){e.setAttribute("name",t.attribute),e.setAttribute("aggregate",t.aggregate),t.seriesType&&e.setAttribute("charttype",t.seriesType)}function Fre(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 Mre(e,t){let r=t.parentNode;for(;r&&r!==e;){let n=r;if(n.nodeType===1&&n.tagName==="link-entity")return n.getAttribute("name")||void 0;r=n.parentNode}}function nx(e,t,r,n){n?Ure(e,t,n).appendChild(r):t.appendChild(r)}function Ure(e,t,r){let n=t.getElementsByTagName("link-entity");for(let o=0;o<n.length;o+=1)if(n[o].getAttribute("name")===r)return n[o];let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function Bre(e){let t=e.parentNode;if(t&&(t.removeChild(e),t.tagName==="link-entity"&&!qre(t))){let r=t.parentNode;r&&r.removeChild(t)}}function qre(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 Vre(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1)if(t[r].nodeType===1)return!0;return!1}function px(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(!Gre(r[i])){r[i].setAttribute("ChartType",t);return}}}function Gre(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 mx(e,t){var r;let n=e.ownerDocument;if(t.palette!==void 0&&e.setAttribute("Palette",t.palette),t.showLegend!==void 0){let i=[],o=e.getElementsByTagName("Legends");for(let a=0;a<o.length;a+=1)i.push(o[a]);if(t.showLegend&&i.length===0){let a=n.createElement("Legends"),s=n.createElement("Legend");s.setAttribute("Name","Default"),a.appendChild(s),e.appendChild(a)}else if(!t.showLegend)for(let a of i)(r=a.parentNode)===null||r===void 0||r.removeChild(a)}if(t.title!==void 0){let i=e.getElementsByTagName("Title")[0];i&&(i.textContent=t.title)}}function Wre(e,t){let r=(0,ni.parseXmlRoot)(Ere(),"<Chart/>");px(r,e.chartType),mx(r,e.presentation);let n=iv((0,ni.parseXmlRoot)(t,"<datadefinition/>"));return n.length>0&&cx(r.ownerDocument,r,n,n.slice(0,1),e.chartType),(0,ni.serializeNode)(r)}function nv(e,t){return JSON.stringify(e)===JSON.stringify(t)}function rl(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function zre(){return{adapter:new bp,api:bre.chartApi,publish:(e,t,r)=>(0,Zk.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,Zk.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}nl.chartRegistration=zre});var vx=v(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});Ea.dashboardApi=Ea.dashboardEntity=void 0;var jre=Xt(),Io=ye(),il=ue(),Hre=lg(),gx=Zl();function yx(e){return e&&e.toLowerCase()!=="none"?e:void 0}Ea.dashboardEntity=yx;var bx="formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber",Kre={select:bx,required:["name","type","objecttypecode","istabletenabled"]},Jre="formid,name,type,objecttypecode",Yre=0,Qre=10;Ea.dashboardApi={async get(e,t){let r=(0,il.normalizeGuid)(t,"id"),n=`/systemforms(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,il.odataQuery)([["$select",bx]]),i=(0,Io.ensureSuccess)(await e.get(n),e.apiUrl(n));return(0,gx.assertSystemFormRecordKind)(i.body,r,"dashboard","fetch"),{raw:i.body,etag:(0,Io.readEtag)(i)}},async list(e,t){let r=[`(type eq ${Yre} or type eq ${Qre})`];t?.entityLogicalName&&r.push(`objecttypecode eq '${(0,il.odataLiteral)(t.entityLogicalName)}'`);let n=`/systemforms${(0,il.odataQuery)([["$select",Jre],["$filter",r.join(" and ")]])}`;return(await(0,jre.collectPages)(e,n,"listArtifacts('dashboard')")).map(o=>{var a,s;let l=yx(o.objecttypecode);return{type:"dashboard",id:(a=o.formid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",...l?{entityLogicalName:l}:{},isDirty:!1}})},async create(e,t,r){let n=t,i=(0,Io.echoWrite)("formid"),o=`/systemforms${i.query}`,a={name:n.name,description:n.description,formxml:n.formxml,istabletenabled:n.istabletenabled,type:n.type};n.objecttypecode&&(a.objecttypecode=n.objecttypecode);let s=(0,Io.ensureSuccess)(await e.post(o,(0,Io.withClientMintedId)(a,"formid",r),i.options),e.apiUrl(o));return{id:(0,Io.resolveCreatedId)(s,"formid","dashboard",r),etag:(0,Io.readEtag)(s)}},async update(e,t,r,n){let i=r;return(0,Hre.patchSystemForm)(e,(0,il.normalizeGuid)(t,"id"),"dashboard",{name:i.name,description:i.description,formxml:i.formxml,istabletenabled:i.istabletenabled},n,Kre)},readContentThenToken(e,t){return Ea.dashboardApi.get(e,t)},async delete(e,t){let r=(0,il.normalizeGuid)(t,"id");return await(0,gx.assertSystemFormKind)(e,r,"dashboard"),(0,Io.deleteRecord)(e,"systemforms",r)}}});var Rx=v(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.dashboardRegistration=ii.TILE_CLASS_ID=ii.DashboardAdapter=void 0;var ec=ao(),fn=lo(),ov=Kr(),Zu=Zr(),Nx=vx(),av=so(),Aa=lt(),_x=ue(),Tx=Ko(),Xre=vy(),wx="0",sv="10",Zre=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"]]),ene="{3FF9A528-DD50-4ACA-8F10-2E5ED73513AD}",Cp=class{constructor(t=Tx.DEFAULT_LCID){this.lcid=t}toArtifact(t){var r,n,i,o,a;(0,av.installDomShim)();let s=(r=t.formxml)!==null&&r!==void 0?r:"",l=(0,fn.parseXmlRoot)(s,"<form/>");return{id:(n=t.formid)!==null&&n!==void 0?n:"",name:(i=t.name)!==null&&i!==void 0?i:"",description:(o=t.description)!==null&&o!==void 0?o:"",dashboardType:tne(t.type),entityLogicalName:(a=(0,Nx.dashboardEntity)(t.objecttypecode))!==null&&a!==void 0?a:null,enabledForMobile:!!t.istabletenabled,layoutType:rne(l),components:Cx(l,this.lcid),bag:(0,fn.projectElementBag)(l)}}fromArtifact(t){var r;return(0,av.installDomShim)(),{formid:t.id,name:t.name,description:t.description,type:t.dashboardType==="Interactive"?sv:wx,objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",istabletenabled:t.enabledForMobile,formxml:Ex(t,this.lcid)}}fromApiResponse(t){return this.toArtifact(t??{})}completeAsStored(t,r){return(0,Xre.completeRecordAsStored)(t,r,this.lcid)}toApiPayload(t){return{name:t.name,description:t.description,formxml:Ex(t,this.lcid),istabletenabled:t.enabledForMobile,type:t.dashboardType==="Interactive"?sv:wx,objecttypecode:t.entityLogicalName}}createDefault(t){var r,n,i,o,a,s,l,u;(0,av.installDomShim)();let c=(0,fn.parseXmlRoot)(hne(),"<form/>");return{id:(r=t.id)!==null&&r!==void 0?r:(0,Aa.newId)(),name:(n=t.name)!==null&&n!==void 0?n:"New Dashboard",description:(i=t.description)!==null&&i!==void 0?i:"",dashboardType:(o=t.dashboardType)!==null&&o!==void 0?o:"Standard",entityLogicalName:(a=t.entityLogicalName)!==null&&a!==void 0?a:null,enabledForMobile:(s=t.enabledForMobile)!==null&&s!==void 0?s:!1,layoutType:(l=t.layoutType)!==null&&l!==void 0?l:0,components:(u=t.components)!==null&&u!==void 0?u:Cx(c,this.lcid),bag:(0,fn.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,Aa.newId)())}return t}validate(t){let r=[],n=(0,Zu.childObjects)(t,"components","","component",r),i=new Set;return n.forEach(({node:o,index:a})=>{let s=`/components/${a}`;for(let l of["position","parameters"]){let u=o[l];u!==void 0&&!(0,Zu.isJsonObject)(u)&&r.push((0,Zu.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,Zu.isJsonObject)(o.position)){let l=tc(o.position);i.has(l)?r.push((0,Zu.issue)(`${s}/position`,"component-position-collision",`two components occupy the same dashboard position (${l}); move one to a free cell`)):i.add(l)}}),r}};ii.DashboardAdapter=Cp;function tne(e){return String(e??"")===sv?"Interactive":"Standard"}function rne(e){let t=e?.getAttribute("formLayout")||e?.getAttribute("layoutType"),r=parseInt(t??"",10);return Number.isNaN(r)?0:r}function ae(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName.toLowerCase()===t&&r.push(o)}return r}function Cx(e,t){let r=[];return ae(e,"tabs").flatMap(i=>ae(i,"tab")).forEach((i,o)=>{ae(i,"columns").flatMap(s=>ae(s,"column")).forEach((s,l)=>{ae(s,"sections").flatMap(c=>ae(c,"section")).forEach((c,d)=>{nne(c,{tabIndex:o,columnIndex:l,sectionIndex:d},r,t)})})}),r}function nne(e,t,r,n){ae(e,"rows").flatMap(o=>ae(o,"row")).forEach((o,a)=>{ae(o,"cell").forEach((s,l)=>{let u=ine(s,{...t,rowIndex:a,cellIndex:l},n);u&&r.push(u)})})}function ine(e,t,r){var n,i;let o=Ox((n=e.getAttribute("id"))!==null&&n!==void 0?n:"");if(o.toLowerCase().startsWith("spacer"))return null;let a=ae(e,"control")[0];if(!a)return null;let s=(i=a.getAttribute("classid"))!==null&&i!==void 0?i:"",l=sne(a),u=lne(s,l,a),c=one(a);return{id:a.getAttribute("id")||o,type:u,name:Ix(e,r),classId:s,position:t,colspan:lv(e,"colspan",1),rowspan:lv(e,"rowspan",1),parameters:l,bag:(0,fn.projectElementBag)(e),...c?{icProperties:c}:{}}}function Dx(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 one(e){let t=Dx(e);return t?(0,fn.serializeNode)(t):void 0}function ane(e,t,r){let n=Dx(t);if(!r){n&&t.removeChild(n);return}let i=new DOMParser().parseFromString(r,"text/xml").documentElement,o=(0,ec.rebuildRaw)((0,ec.rawFromNode)((0,fn.nodeLikeFromDom)(i)),(0,fn.domEngine)(e),null);n&&(0,fn.serializeNode)(n)===(0,fn.serializeNode)(o)||(n?t.replaceChild(o,n):t.appendChild(o))}function Ix(e,t){var r,n;let i=ae(e,"labels")[0];if(!i)return"";let o=ae(i,"label"),a=(r=o.find(s=>s.getAttribute("languagecode")===String(t)))!==null&&r!==void 0?r:o[0];return(n=a?.getAttribute("description"))!==null&&n!==void 0?n:""}function sne(e){var t;let r={},n=ae(e,"parameters")[0];if(!n)return r;let i=n.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];a.nodeType===1&&(r[a.tagName]=((t=a.textContent)!==null&&t!==void 0?t:"").trim())}return r}function lne(e,t,r){var n;let i=Zre.get(e.toUpperCase());return i?i==="chart"?t.ChartGridMode==="Chart"?"chart":"list":i==="assistant"&&((n=r.getAttribute("uniqueid"))!==null&&n!==void 0?n:"").toUpperCase()===ene?"assistant":i:"unknown"}function lv(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 Ox(e){return e.replace(/^\{/,"").replace(/\}$/,"")}function une(e,t){let r={n:"form",a:(0,ec.mergeAttrs)(e.bag.a,[]),c:(0,ec.spliceChildren)(e.bag.c,[])};return(0,ec.rebuildRaw)(r,(0,fn.domEngine)(t),null)}function Ex(e,t){let r=new DOMParser().parseFromString("<root/>","text/xml"),n=une(e,r);return fne(r,n,e.components,t),cne(r,n,e.components,t),(0,fn.serializeNode)(n)}function cne(e,t,r,n){let i=Px(t);for(let o of r)i.has(tc(o.position))||dne(e,t,o,n)}function dne(e,t,r,n){var i,o,a,s;let l=(o=(i=r.position)===null||i===void 0?void 0:i.sectionIndex)!==null&&o!==void 0?o:0,u=gne(t,e,l);for(let $ of ae(u,"row"))ae($,"cell").some(K=>ae(K,"control").length>0)||u.removeChild($);let c=r.classId||ii.TILE_CLASS_ID[r.type]||ii.TILE_CLASS_ID.iframe,d=r.rowspan&&r.rowspan>0?r.rowspan:4,f=r.bag&&Ax(r.bag,"id")?String(Ax(r.bag,"id")):wp((0,Aa.newId)()),p=r.id?wp(r.id):wp((0,Aa.newId)()),m=u.parentNode,h=Math.max(1,parseInt(m&&m.getAttribute&&m.getAttribute("columns")||"1",10)||1),g=Math.min(Math.max(1,r.colspan&&r.colspan>0?r.colspan:1),h),b=ae(u,"row"),w=b[b.length-1],E=w?ae(w,"cell").reduce(($,K)=>$+lv(K,"colspan",1),0):0;(!w||E+g>h)&&(w=e.createElement("row"),u.appendChild(w));let A=e.createElement("cell");A.setAttribute("id",f),A.setAttribute("colspan",String(g)),A.setAttribute("rowspan",String(d)),A.setAttribute("showlabel","true");let L=e.createElement("labels"),R=e.createElement("label");R.setAttribute("description",(a=r.name)!==null&&a!==void 0?a:""),R.setAttribute("languagecode",String(n)),L.appendChild(R),A.appendChild(L);let I=e.createElement("control");I.setAttribute("id",p),I.setAttribute("classid",wp(c));let D=e.createElement("parameters"),O=(s=r.parameters)!==null&&s!==void 0?s:{};for(let $ of Object.keys(O)){let K=(0,_x.createSafeXmlElement)(e,$,"dashboard tile parameter");K.textContent=O[$],D.appendChild(K)}I.appendChild(D),A.appendChild(I),w.appendChild(A)}function Ax(e,t){if(!e)return;let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function fne(e,t,r,n){var i;let o=Px(t),a=new Set(r.map(s=>tc(s.position)));for(let s of r){let l=o.get(tc(s.position));if(!l)continue;let u=ae(l,"control")[0];u&&(pne(e,l,s.name,n),mne(e,u,s.parameters),Sx(l,"colspan",s.colspan),Sx(l,"rowspan",s.rowspan),s.icProperties!==void 0&&ane(e,u,s.icProperties))}for(let[s,l]of o)a.has(s)||(i=l.parentNode)===null||i===void 0||i.removeChild(l)}function Px(e){let t=new Map;return ae(e,"tabs").flatMap(n=>ae(n,"tab")).forEach((n,i)=>{ae(n,"columns").flatMap(a=>ae(a,"column")).forEach((a,s)=>{ae(a,"sections").flatMap(u=>ae(u,"section")).forEach((u,c)=>{ae(u,"rows").flatMap(f=>ae(f,"row")).forEach((f,p)=>{ae(f,"cell").forEach((m,h)=>{var g;Ox((g=m.getAttribute("id"))!==null&&g!==void 0?g:"").toLowerCase().startsWith("spacer")||ae(m,"control")[0]&&t.set(tc({tabIndex:i,columnIndex:s,sectionIndex:c,rowIndex:p,cellIndex:h}),m)})})})})}),t}function tc(e){let t=e??{};return`${t.tabIndex}.${t.columnIndex}.${t.sectionIndex}.${t.rowIndex}.${t.cellIndex}`}function pne(e,t,r,n){if(r===Ix(t,n))return;let i=ae(t,"labels")[0];i||(i=e.createElement("labels"),t.appendChild(i));let o=ae(i,"label").find(a=>a.getAttribute("languagecode")===String(n));o||(o=e.createElement("label"),o.setAttribute("languagecode",String(n)),i.appendChild(o)),o.setAttribute("description",r)}function mne(e,t,r){var n;if(!r)return;let i=Object.keys(r);if(i.length===0)return;let o=ae(t,"parameters")[0];o||(o=e.createElement("parameters"),t.appendChild(o));let a=new Map,s=o.childNodes;for(let l=0;l<s.length;l+=1){let u=s[l];u.nodeType===1&&a.set(u.tagName,u)}for(let l of i){let u=r[l],c=a.get(l);if(c)((n=c.textContent)!==null&&n!==void 0?n:"")!==u&&(c.textContent=u);else{let d=(0,_x.createSafeXmlElement)(e,l,"dashboard component parameter");d.textContent=u,o.appendChild(d)}}}function Sx(e,t,r){var n;((n=e.getAttribute(t))!==null&&n!==void 0?n:"")!==String(r)&&e.setAttribute(t,String(r))}function hne(e=2){let t=`{${(0,Aa.newId)()}}`,r=`{${(0,Aa.newId)()}}`,n=`{${(0,Aa.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>`}ii.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 wp(e){return`{${e.replace(/[{}]/g,"")}}`}function gne(e,t,r){var n;let i=ae(e,"tabs").flatMap(u=>ae(u,"tab"))[0];if(!i)throw new Error("addDashboardTile: dashboard formxml has no <tab>");let o=ae(i,"columns").flatMap(u=>ae(u,"column"))[0];if(!o)throw new Error("addDashboardTile: dashboard formxml has no <column>");let a=ae(o,"sections").flatMap(u=>ae(u,"section")),s=(n=a[r])!==null&&n!==void 0?n:a[0];if(!s)throw new Error("addDashboardTile: dashboard formxml has no <section>");let l=ae(s,"rows")[0];return l||(l=t.createElement("rows"),s.appendChild(l)),l}function yne(e=Tx.DEFAULT_LCID){return{adapter:new Cp(e),api:Nx.dashboardApi,languageSensitive:!0,publish:(t,r,n)=>n?.entityLogicalName?(0,ov.publishBoundEntity)(t,n):(0,ov.publishDashboardById)(t,r),publishScope:(t,r)=>r?.entityLogicalName?(0,ov.boundEntityPublishScope)(r):{envelope:"dashboard",targetIds:[t]},rebaselineAfterPublish:"bracket"}}ii.dashboardRegistration=yne});var cv=v(Pr=>{"use strict";Object.defineProperty(Pr,"__esModule",{value:!0});Pr.readEveryInOrder=Pr.readInOrder=Pr.plainRead=Pr.resolveReadConcurrency=Pr.MAX_READ_CONCURRENCY=void 0;var Lx=Q();Pr.MAX_READ_CONCURRENCY=8;function bne(e){if(e===void 0)return 1;if(typeof e!="number"||!Number.isInteger(e)||e<1||e>Pr.MAX_READ_CONCURRENCY)throw new Lx.InvalidArgumentError(`readConcurrency must be a whole number from 1 to ${Pr.MAX_READ_CONCURRENCY} (got ${typeof e=="string"?`'${e}'`:String(e)})`);return e}Pr.resolveReadConcurrency=bne;var vne=e=>({ok:!0,value:e}),uv=e=>({ok:!1,error:e});function wne(e){let t=(async()=>e())().then(vne,uv);return{outcome:t,finish:async r=>{await r()},discard:async()=>{await t}}}Pr.plainRead=wne;async function kx(e,t,r,n,i){if(!Number.isInteger(t)||t<1)throw new Lx.InvalidArgumentError(`a read window holds a whole number of reads, at least 1 (got ${String(t)})`);let o=new Map,a=0,s=Promise.resolve(),l=!1,u=0,c,d=async f=>{if(l)return{refusal:new Error("The read was not started: an earlier read had already failed.")};try{let p=await r(e[f],f),m=p.outcome.catch(uv);return i==="stop"&&m.then(h=>{l=l||!h.ok}),{read:p,outcome:m}}catch(p){return l=l||i==="stop",{refusal:p}}};try{for(let f=0;f<e.length;f+=1){for(;a<e.length&&a<f+t;){let g=a;a+=1;let b=s.then(()=>d(g));o.set(g,b),s=b}let p=await o.get(f),m="read"in p?await p.outcome:uv(p.refusal);if(!m.ok&&i==="stop"){c={error:m.error};break}u=f+1,o.delete(f);let h=()=>n(m,e[f],f);"read"in p?await p.read.finish(h):await h()}}finally{l=!0;for(let f=u;f<a;f+=1){let p=await o.get(f);"read"in p&&await p.read.discard().catch(()=>{})}}if(c)throw c.error}function Cne(e,t,r,n){return kx(e,t,r,(i,o,a)=>n(i.value,o,a),"stop")}Pr.readInOrder=Cne;function Ene(e,t,r,n){return kx(e,t,r,n,"continue")}Pr.readEveryInOrder=Ene});var Qx=v(Ap=>{"use strict";Object.defineProperty(Ap,"__esModule",{value:!0});Ap.genPageApi=void 0;var Ep=Xt(),jx=Wl(),Be=ye(),he=ue(),Rn=Td(),Qe=Q(),Hx=lt(),xx=cv();function Ane(e){if(ArrayBuffer.isView(e)){let r=e;return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}if(Object.prototype.toString.call(e)==="[object ArrayBuffer]")return new Uint8Array(e);let t=globalThis;if(t.Buffer&&t.Buffer.isBuffer(e)){let r=e;return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}}var oi="uxagentprojects",Na="uxagentprojectfiles",ic="agentconversationmessages",oc="uxagentprojectid",xt="uxagentprojectfileid",_a="agentconversationmessageid",rc=`${oc},name`,Sne=`${xt},filename,filetype`,Kx=2e8,Jx=200000001,Ta={"MSCRM.IncludeUnpublished":"true"},dv={};function Sa(e,t){return{"MSCRM.VersioningChangeset":e,...Ta,...t}}async function mv(e,t,r,n){var i;let o=`/${t}(${r})`+(0,he.odataQuery)([["$select",n]]),a=(0,Be.ensureSuccess)(await e.get(o,{headers:{...Ta}}),e.apiUrl(o));return{row:(i=a.body)!==null&&i!==void 0?i:{},etag:(0,Be.readEtag)(a)}}async function ac(e,t,r=Ta){let n=`/${Na}(${t})/filecontent/$value`,i=await e.get(n,{headers:{...r}});if(i.status===404)return{status:"unavailable",reason:"missing"};(0,Be.ensureSuccess)(i,e.apiUrl(n));let o=i.body,a=Ane(o);if(a)return{status:"available",data:(0,Rn.bytesToBase64)(a)};if(typeof o=="string")return{status:"available",data:(0,Rn.utf8ToBase64)(o)};throw new Qe.SdkError("GENPAGE_CONTENT_UNREADABLE",`Read the content of file '${t}' but the injected HttpClient returned a body this SDK cannot encode (${typeof o}). Return the response as a string, Uint8Array, Buffer, or ArrayBuffer; a byte-returning transport is required to round-trip non-UTF8 assets.`)}function Yx(e){let t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}async function Nne(e,t,r,n,i,o){if(!e.supportsBinaryPatch)throw new Qe.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED",`Refusing to push generative-page file '${t}': its content cannot be written because the injected HttpClient does not implement patchRaw(). A Dataverse File column is not writable through a JSON body, so saving the row without its bytes would report success for a page whose source never uploaded.`);let a=`/${Na}(${t})/filecontent`,s=(0,Rn.base64ToBytes)(n);(0,he.assertNoControlChars)(r,"generative-page file name"),(0,Be.ensureSuccess)(await e.patchRaw(a,s,{headers:Sa(i,{"Content-Type":"application/octet-stream","Content-Length":String(s.byteLength),"x-ms-file-name":Yx(r),...o?{"If-Match":"*"}:{}})}),e.apiUrl(a))}async function nc(e,t,r=Ta){let n=`/${Na}`+(0,he.odataQuery)([["$select",Sne],["$filter",`_${oc}_value eq ${t}`]]);return(await(0,Ep.collectPages)(e,n,"fetchArtifact('genPage')",void 0,{headers:{...r}})).map(o=>({row:o,etag:typeof o["@odata.etag"]=="string"?o["@odata.etag"]:null}))}async function fv(e,t){let r=`/${ic}`+(0,he.odataQuery)([["$select",`${_a},message,messagesender,createdon`],["$filter",`_regardingobjectid_value eq ${t}`],["$orderby","createdon asc,versionnumber asc"]]);return(0,Ep.collectPages)(e,r,"fetchArtifact('genPage')",void 0,{headers:{...Ta}})}async function $x(e,t){var r,n,i;let{row:o,etag:a}=await mv(e,oi,t,rc),s=new Map;for(let{row:l,etag:u}of await nc(e,t))s.set((0,he.normalizeGuid)(String((r=l[xt])!==null&&r!==void 0?r:""),xt),{filename:String((n=l.filename)!==null&&n!==void 0?n:""),filetype:Number(l.filetype),etag:u});return{name:String((i=o.name)!==null&&i!==void 0?i:""),etag:a,rows:s}}function Fx(e,t,r){var n,i,o,a,s;let l=[];r||l.push({kind:"createProject",name:t.name});let u=new Set;for(let c of(n=t.files)!==null&&n!==void 0?n:[]){let d=(0,he.normalizeGuid)(c.id,"file id");u.add(d);let f=r?.rows.get(d);if(c.content.status==="retain"){if(!r)throw new Qe.SdkError("GENPAGE_RETAIN_ON_CREATE",`Refusing to create generative page '${e}': file '${c.name}' asks to keep content the page does not have yet. This is an SDK defect \u2014 the page's rows were not written.`);if(!f)throw new Qe.SdkError("GENPAGE_RETAINED_ROW_MISSING",`Refusing to write generative page '${e}': file '${c.name}' was to be kept unchanged but is not on the server. Re-fetch the page and retry.`);continue}f&&c.unchanged||(f?(f.filename!==c.name||f.filetype!==c.fileType)&&l.push({kind:"renameRow",file:c}):l.push({kind:"createRow",file:c}),c.content.status==="available"&&l.push({kind:"content",file:c,data:c.content.data,existing:f!==void 0}))}for(let c of(i=r?.rows.keys())!==null&&i!==void 0?i:[])u.has(c)||l.push({kind:"deleteRow",fileId:c});(!r||l.length>0||r.name!==t.name||((a=(o=t.messages)===null||o===void 0?void 0:o.length)!==null&&a!==void 0?a:0)>0)&&l.push({kind:"patchProject",name:t.name});for(let c of(s=t.messages)!==null&&s!==void 0?s:[])l.push({kind:"message",turn:c});return l}function hv(e){let t=(0,Rn.base64ToUtf8)(e);return(0,Rn.utf8ToBase64)(t)===(0,Rn.bytesToBase64)((0,Rn.base64ToBytes)(e))?t:void 0}function _ne(e,t,r,n){var i,o,a,s,l,u,c,d;let f=t.sender==="user"?{changeSet:n,dataSources:(o=(i=r.messageContext)===null||i===void 0?void 0:i.dataSources)!==null&&o!==void 0?o:[],model:(s=(a=r.messageContext)===null||a===void 0?void 0:a.model)!==null&&s!==void 0?s:"",enabledTools:(u=(l=r.messageContext)===null||l===void 0?void 0:l.enabledTools)!==null&&u!==void 0?u:[],configurableTools:(d=(c=r.messageContext)===null||c===void 0?void 0:c.configurableTools)!==null&&d!==void 0?d:[]}:{changeSet:n};return{...t.id?{[_a]:(0,he.normalizeGuid)(t.id,"message id")}:{},"[email protected]":`/${oi}(${e})`,message:t.message,messagecontext:JSON.stringify(f),messagesender:t.sender==="user"?Kx:Jx}}async function Tne(e,t,r){var n,i,o,a;let s=((n=r.messages)!==null&&n!==void 0?n:[]).map(f=>f.id).filter(f=>typeof f=="string"&&f!=="").map(f=>(0,he.normalizeGuid)(f,"message id"));if(s.length===0)return r;let l=`/${ic}`+(0,he.odataQuery)([["$select",`${_a},message,messagesender,_regardingobjectid_value`],["$filter",s.map(f=>`${_a} eq ${f}`).join(" or ")]]),u=await(0,Ep.collectPages)(e,l,"pushArtifact('genPage')",void 0,{headers:{...Ta}});if(u.length===0)return r;let c=new Map(u.map(f=>{var p;return[String((p=f[_a])!==null&&p!==void 0?p:"").toLowerCase(),f]})),d=[];for(let f of(i=r.messages)!==null&&i!==void 0?i:[]){let p=f.id?c.get((0,he.normalizeGuid)(f.id,"message id")):void 0;if(!p){d.push(f);continue}if(!(String((o=p.message)!==null&&o!==void 0?o:"")===f.message&&Number(p.messagesender)===(f.sender==="user"?Kx:Jx)&&String((a=p._regardingobjectid_value)!==null&&a!==void 0?a:"").toLowerCase()===t))throw new Qe.SdkError("GENPAGE_TURN_CONFLICT",`Refusing to push generative page '${t}': its pending turn's identity is already recorded \u2014 as a DIFFERENT ${f.sender} message. An earlier push of this turn did commit (its response was lost), and the turn was changed since. Nothing was written, and the turn is still pending. To record it as a new turn, remove '/newTurn/id' (a new identity is minted on the next push); to keep only what was recorded, remove '/newTurn'.`)}return{...r,messages:d}}function pv(e,t,r,n){switch(t.kind){case"createProject":return{method:"POST",path:`/${oi}`,body:(0,Be.withClientMintedId)({name:t.name},oc,e),headers:Sa(n)};case"createRow":return{method:"POST",path:`/${Na}`,body:(0,Be.withClientMintedId)({filename:t.file.name,filetype:t.file.fileType,[`${oc}@odata.bind`]:`/${oi}(${e})`},xt,(0,he.normalizeGuid)(t.file.id,"file id")),headers:Sa(n)};case"renameRow":return{method:"PATCH",path:`/${Na}(${(0,he.normalizeGuid)(t.file.id,"file id")})`,body:{filename:t.file.name,filetype:t.file.fileType},headers:Sa(n,{"If-Match":"*"})};case"content":{let i=hv(t.data);if(i===void 0)throw new Qe.SdkError("GENPAGE_CONTENT_NOT_TEXT",`File '${t.file.name}' is not UTF-8 text and cannot ride in a change set.`);return(0,he.assertNoControlChars)(t.file.name,"generative-page file name"),{method:"PATCH",path:`/${Na}(${(0,he.normalizeGuid)(t.file.id,"file id")})/filecontent`,rawBody:i,contentType:"application/octet-stream; charset=utf-8",headers:Sa(n,{"x-ms-file-name":Yx(t.file.name),...t.existing?{"If-Match":"*"}:{}})}}case"deleteRow":return{method:"DELETE",path:`/${Na}(${t.fileId})`,headers:Sa(n,{"If-Match":"*"})};case"patchProject":return{method:"PATCH",path:`/${oi}(${e})`,body:{name:t.name},headers:Sa(n,{"If-Match":"*"})};case"message":return{method:"POST",path:`/${ic}`,body:_ne(e,t.turn,r,n)};default:{let i=t;throw new Qe.SdkError("GENPAGE_WRITE_UNKNOWN",`Unknown generative-page write: ${JSON.stringify(i)}`)}}}function Mx(e,t){return e.supportsAtomicBatch&&t.every(r=>r.kind!=="content"||hv(r.data)!==void 0)}async function Ux(e,t,r,n,i){await(0,jx.postChangeSet)(e,r.map(o=>pv(t,o,n,i)),`generative page '${t}' (${r.length} operation(s))`)}async function Bx(e,t,r,n,i){var o;let a=[];for(let s of r){if(s.kind==="message"){a.push(s);continue}if(s.kind==="content"){await Nne(e,(0,he.normalizeGuid)(s.file.id,"file id"),s.file.name,s.data,i,s.existing);continue}let l=pv(t,s,n,i),u={headers:(o=l.headers)!==null&&o!==void 0?o:{}},c=l.method==="POST"?await e.post(l.path,l.body,u):l.method==="PATCH"?await e.patch(l.path,l.body,u):await e.delete(l.path,u);(0,Be.ensureSuccess)(c,e.apiUrl(l.path))}if(a.length===0)return{warnings:[],turnRecorded:!0};try{let s=a.map(l=>pv(t,l,n,i));if(e.supportsAtomicBatch)await(0,jx.postChangeSet)(e,s,`the conversation turn of generative page '${t}'`);else for(let l of s)(0,Be.ensureSuccess)(await e.post(l.path,l.body),e.apiUrl(l.path));return{warnings:[],turnRecorded:!0}}catch(s){return{warnings:[`Generative page '${t}' was saved, but its conversation turn could not be recorded (${s instanceof Error?s.message:String(s)}). The turn is kept: the next push of the page records it.`],turnRecorded:!1}}}async function qx(e,t,r,n,i,o,a){var s;let l=u=>({id:t,etag:null,memberEtags:{},warnings:[...a,u]});try{let u=await $x(e,t),c=new Map;for(let E of r)(E.kind==="createRow"||E.kind==="renameRow"||E.kind==="content")&&c.set((0,he.normalizeGuid)(E.file.id,"file id"),E.file);let d=[];u.name!==n.name&&d.push(`the page is named '${u.name}', not '${n.name}'`);for(let[E,A]of c){let L=u.rows.get(E);L&&(L.filename!==A.name||L.filetype!==A.fileType)&&d.push(`file '${A.name}' is stored as '${L.filename}' (type ${L.filetype})`)}for(let E of r){if(E.kind!=="content")continue;let A=await ac(e,(0,he.normalizeGuid)(E.file.id,"file id")),L=(0,Rn.bytesToBase64)((0,Rn.base64ToBytes)(E.data));(A.status!=="available"||A.data!==L)&&d.push(A.status==="available"?`file '${E.file.name}' holds ${(0,Rn.base64ToBytes)(A.data).byteLength} byte(s) that differ from the ${(0,Rn.base64ToBytes)(L).byteLength} written`:`file '${E.file.name}' holds no content`)}let f=new Set(r.filter(E=>E.kind==="content").map(E=>(0,he.normalizeGuid)(E.file.id,"file id")));for(let[E,A]of c)!f.has(E)&&(await ac(e,E)).status==="available"&&d.push(`file '${A.name}' holds content this push did not write`);if(d.length>0)return l(`Generative page '${t}' was written, but reading it back does not match what was sent: ${d.join("; ")}. The local baseline is now unusable: re-fetch the page to see what the server holds \u2014 the next push will refuse rather than overwrite blind.`);let p=await $x(e,t),m=[...p.rows.keys()],h=p.etag!==u.etag||p.rows.size!==u.rows.size||m.some(E=>{var A,L;return((A=u.rows.get(E))===null||A===void 0?void 0:A.etag)!==((L=p.rows.get(E))===null||L===void 0?void 0:L.etag)}),g=m.length!==i.size||m.some(E=>!i.has(E)),b={},w=[];for(let[E,A]of p.rows){let L=c.has(E)||!o?A.etag:(s=o.get(E))!==null&&s!==void 0?s:null;b[E]=L,L!==A.etag&&w.push(A.filename)}return h||g||!p.etag||Object.values(b).some(E=>!E)?l(`Generative page '${t}' was written, but its files changed on the server while the write was in progress, so the new concurrency tokens cannot be trusted. The local baseline is now unusable: re-fetch the page before editing it again \u2014 the next push will refuse rather than overwrite blind.`):Dne({id:t,etag:p.etag,memberEtags:b},[...a,...w.map(E=>`Generative page '${t}' was written, but its file '${E}' changed on the server while this push ran \u2014 another writer edited it. This push did not touch that file, so the next one refuses until you re-fetch the page and see their change.`)])}catch(u){return l(`The generative page was written, but reading it back failed (${u instanceof Error?u.message:String(u)}). The local baseline is unusable: re-fetch the page before editing it \u2014 the next push will refuse rather than overwrite blind.`)}}async function Vx(e,t,r,n=e.readConcurrency){var i;let o=(0,he.normalizeGuid)(t,"id"),{row:a,etag:s}=await mv(e,oi,o,rc),l=await nc(e,o),u={},c=[];if(n>1)await(0,xx.readInOrder)(l,n,({row:f})=>{var p;let m=(0,he.normalizeGuid)(String((p=f[xt])!==null&&p!==void 0?p:""),xt);return(0,xx.plainRead)(async()=>({fileId:m,content:await ac(e,m)}))},({fileId:f,content:p},{row:m,etag:h})=>{u[f]=h,c.push({...m,content:p})});else for(let{row:f,etag:p}of l){let m=(0,he.normalizeGuid)(String((i=f[xt])!==null&&i!==void 0?i:""),xt);u[m]=p;let h=await ac(e,m);c.push({...f,content:h})}return{raw:r?{project:a,files:c,conversation:await fv(e,o)}:{project:a,files:c},etag:s,memberEtags:u}}Ap.genPageApi={get(e,t,r){return Vx(e,t,!0,r?.fileConcurrency)},getForRebaseline(e,t){return Vx(e,t,!1)},async getPublished(e,t){var r,n;let i=(0,he.normalizeGuid)(t,"id"),o=`/${oi}(${i})`+(0,he.odataQuery)([["$select",rc]]),a=await e.get(o);if(a.status===404)return null;(0,Be.ensureSuccess)(a,e.apiUrl(o));let s=(r=a.body)!==null&&r!==void 0?r:{},l={},u=[],c=await nc(e,i,dv);for(let{row:g,etag:b}of c){let w=(0,he.normalizeGuid)(String((n=g[xt])!==null&&n!==void 0?n:""),xt);l[w]=b,u.push({...g,content:await ac(e,w,dv)})}let d=g=>g.map(({row:b,etag:w})=>`${String(b[xt])}@${String(w)}`).sort().join("|"),f=()=>new Qe.SdkError("GENPAGE_PUBLISHED_READ_MOVED",`The published projection of generative page '${i}' changed while it was being read, so what was read is not one published state. PublishXml is asynchronous \u2014 re-read shortly.`),p=await e.get(o);if(p.status===404)throw f();(0,Be.ensureSuccess)(p,e.apiUrl(o));let m=await nc(e,i,dv);if([(0,Be.readEtag)(a),(0,Be.readEtag)(p),...[...c,...m].map(g=>g.etag)].some(g=>!g))throw new Qe.SdkError("GENPAGE_PUBLISHED_READ_UNVERSIONED",`The published projection of generative page '${i}' answered without a version token for the page or one of its rows, so what was read cannot be proven to be one published state.`);if((0,Be.readEtag)(p)!==(0,Be.readEtag)(a)||d(m)!==d(c))throw f();return{raw:{project:s,files:u,conversation:[]},etag:(0,Be.readEtag)(a),memberEtags:l}},async list(e,t){let r=`/${oi}`+(0,he.odataQuery)([["$select",rc]]);return(await(0,Ep.collectPages)(e,r,"listArtifacts('genPage')",void 0,{headers:{...Ta}})).map(i=>{var o,a;return{type:"genPage",id:String((o=i[oc])!==null&&o!==void 0?o:""),name:String((a=i.name)!==null&&a!==void 0?a:""),isDirty:!1}})},async create(e,t,r){var n;let i=t;zx(e,i);let o=r?(0,he.normalizeGuid)(r,"id"):(0,Hx.newId)();Wx(e,o,i);let a=Fx(o,i,void 0),s=Gx(),l=[],u=!0;Mx(e,a)?await Ux(e,o,a,i,s):{warnings:l,turnRecorded:u}=await Bx(e,o,a,i,s);let c=new Set(((n=i.files)!==null&&n!==void 0?n:[]).map(f=>(0,he.normalizeGuid)(f.id,"file id"))),d=await qx(e,o,a,i,c,void 0,l);return u?d:{...d,intentPending:!0}},async update(e,t,r,n,i){var o,a;let s=r,l=(0,he.normalizeGuid)(t,"id");zx(e,s);let u=await Tne(e,l,s);Wx(e,l,u);let c=await nc(e,l),{row:d,etag:f}=await mv(e,oi,l,rc);if(n&&f&&n!==f)throw new Qe.SdkError(Be.VERSION_CONFLICT_CODE,`Generative page '${l}' changed on the server after it was fetched (baseline ${n}, server ${f}) \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||!f)throw new Qe.SdkError(Be.VERSION_CONFLICT_CODE,`Cannot verify generative page '${l}' before writing: ${n?"the server did not return the page's current token":"no baseline token was recorded"}. This entity accepts no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let p=new Map(c.map(({row:I})=>{var D,O;return[(0,he.normalizeGuid)(String((D=I[xt])!==null&&D!==void 0?D:""),xt),{filename:String((O=I.filename)!==null&&O!==void 0?O:""),filetype:Number(I.filetype)}]})),m=new Set(p.keys()),h=new Set(((o=u.files)!==null&&o!==void 0?o:[]).map(I=>(0,he.normalizeGuid)(I.id,"file id")));if(!i)throw new Qe.SdkError(Be.VERSION_CONFLICT_CODE,`Cannot verify the files of generative page '${l}' before writing: no child baseline was recorded. These rows accept no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let g=new Set(Object.keys(i).map(I=>I.toLowerCase()));for(let I of h)if(!m.has(I)&&g.has(I))throw new Qe.SdkError(Be.VERSION_CONFLICT_CODE,`Generative-page file '${I}' existed when this page was fetched but is gone from the server now \u2014 another writer deleted it. Refusing to recreate it, because a blind re-create would undo that delete. Re-fetch the page and re-apply the edit.`);for(let I of m)if(!g.has(I))throw new Qe.SdkError(Be.VERSION_CONFLICT_CODE,`Generative-page file '${I}' is on the server but absent from this page's baseline \u2014 another writer added it after the page was fetched, so its contents cannot be verified. Refusing to write over or delete it. Re-fetch the page so the addition is part of your baseline.`);let b=new Map(c.map(({row:I,etag:D})=>{var O;return[(0,he.normalizeGuid)(String((O=I[xt])!==null&&O!==void 0?O:""),xt),D]}));for(let[I,D]of Object.entries(i)){let O=I.toLowerCase();if(!m.has(O))continue;let $=b.get(O);if(!D||!$)throw new Qe.SdkError(Be.VERSION_CONFLICT_CODE,`Cannot verify generative-page file '${O}' before writing: ${D?"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(D!==$)throw new Qe.SdkError(Be.VERSION_CONFLICT_CODE,`Generative-page file '${O}' changed on the server after this page was fetched (baseline ${D}, server ${$}) \u2014 another writer edited it. A file row accepts no If-Match validator, so this push would silently overwrite that change. Re-fetch the page and re-apply the edit.`)}let w=Fx(l,u,{rows:p,name:String((a=d.name)!==null&&a!==void 0?a:"")});if(w.length===0)return{id:l,etag:f,memberEtags:Object.fromEntries(c.map(({row:I,etag:D})=>{var O;return[(0,he.normalizeGuid)(String((O=I[xt])!==null&&O!==void 0?O:""),xt),D]}))};let E=Gx(),A=[],L=!0;Mx(e,w)?await Ux(e,l,w,u,E):{warnings:A,turnRecorded:L}=await Bx(e,l,w,u,E);let R=await qx(e,l,w,u,h,b,A);return L?R:{...R,intentPending:!0}},async delete(e,t){var r;let n=(0,he.normalizeGuid)(t,"id"),i=await fv(e,n);await(0,Be.deleteRecord)(e,oi,n);let o=new Set(i.map(l=>{var u;return String((u=l[_a])!==null&&u!==void 0?u:"")}).filter(l=>l!=="")),a=!1;try{for(let l of await fv(e,n)){let u=String((r=l[_a])!==null&&r!==void 0?r:"");u!==""&&o.add(u)}}catch{a=!0}let s=[];for(let l of o)try{await(0,Be.deleteRecord)(e,ic,l)}catch(u){u instanceof Qe.ConnectionError&&u.statusCode===404||s.push(l)}if(s.length>0||a)throw new Qe.SdkError("GENPAGE_HISTORY_NOT_DELETED",`Generative page '${n}' was deleted, but its conversation history was not fully removed`+(s.length>0?` \u2014 ${s.length} of ${o.size} message(s) could not be (${s.join(", ")})`:"")+(a?" \u2014 and re-reading it after the delete failed, so a late turn may remain":"")+`. They no longer belong to any page; delete them as ${ic} rows regarding '${n}'.`)}};function Gx(){return`uxagentproject_${(0,Hx.newId)()}`}function Dne(e,t){var r;return t.length===0?e:{...e,warnings:[...(r=e.warnings)!==null&&r!==void 0?r:[],...t]}}function Wx(e,t,r){var n,i;if(((i=(n=r.messages)===null||n===void 0?void 0:n.length)!==null&&i!==void 0?i:0)>1&&!e.supportsAtomicBatch)throw new Qe.SdkError("GENPAGE_TURN_NOT_ATOMIC",`Refusing to write generative page '${t}': its new turn has a prompt AND a reply, which must be recorded together, and the injected HttpClient does not implement postRaw() \u2014 one request at a time, a failure between the two would leave half a turn. Implement postRaw(), or record the prompt alone (omit newTurn.agentMessage). Nothing was written.`)}function zx(e,t){var r,n;if(((r=t.files)!==null&&r!==void 0?r:[]).some(a=>a.content.status==="available"&&!a.unchanged)&&!e.supportsBinaryPatch&&!e.supportsAtomicBatch)throw new Qe.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: it has file content to upload, but the injected HttpClient implements neither patchRaw() nor postRaw(). A Dataverse File column is not writable through a JSON body, so proceeding would create the page and its rows and then fail, leaving a page whose source never uploaded.");if(((n=t.files)!==null&&n!==void 0?n:[]).some(a=>a.content.status==="available"&&!a.unchanged&&hv(a.content.data)===void 0)&&!e.supportsBinaryPatch)throw new Qe.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: a file's content is not UTF-8 text, which only the binary channel can carry, and the injected HttpClient does not implement patchRaw().")}});var m$=v(al=>{"use strict";Object.defineProperty(al,"__esModule",{value:!0});al.genPageRegistration=al.GenPageAdapter=void 0;var Ine=Qx(),One=Kr(),_e=Zr(),Dp=lt(),Ip=Td(),Da=Q(),l$=Cg(),gv=Gm(),Oo=2e8,u$=200000001,qi={source:{name:"src/pages/page.tsx",fileType:Oo},output:{name:"src/pages/page.compiled",fileType:u$},config:{name:"config.json",fileType:Oo},prompt:{name:"firstPrompt.json",fileType:Oo}},c$=Object.keys(qi),Pne=["dataSources","model","connectorBindings","actionBindings"],Rne=["userMessage","agentMessage"],Xx=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Lne={source:"6f1c2a4e9b3d47a1b85c0e2f7d914a63",output:"a8e53d17c2f64b09a1d7e4b8c3f2069d",config:"3b97f0c64e2a4d8f95b1c7a0e6d3f814",prompt:"d24e8b51f7a34c6e8b09d5f1a2c7e3b6"},kne="9c3e7a15d2b84f6e8a01c5d7b3f9e240";function d$(e,t){var r;let n=e.replace(/[{}-]/g,"").toLowerCase(),i=[];for(let a=0;a<32;a+=1)i.push(parseInt((r=n[a])!==null&&r!==void 0?r:"0",16)^parseInt(t[a],16));i[12]=4,i[16]=i[16]&3|8;let o=i.map(a=>(Number.isNaN(a)?0:a).toString(16)).join("");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}function Sp(e,t){return d$(e,Lne[t])}function xne(e,t){let r=d$(e,kne),n=parseInt(r.slice(24),16)%2**47+(t==="agent"?1:0);return`${r.slice(0,24)}${n.toString(16).padStart(12,"0")}`}function Zx(e){return typeof e=="string"&&e.trim()!==""?e:(0,Dp.newId)()}function Bi(e){return(0,_e.isJsonObject)(e)?e:{}}function ol(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function Np(e){return JSON.parse(JSON.stringify(e))}function $ne(e){let t=Bi(e);return t.status==="available"&&typeof t.data=="string"?{status:"available",data:t.data}:{status:"unavailable",reason:t.reason==="unpublished"?"unpublished":"missing"}}function lc(e){if(!e||e.status!=="available")return;let t=(0,Ip.base64ToUtf8)(e.data);return(0,Ip.utf8ToBase64)(t)===e.data?t:void 0}function f$(e,t,r){var n,i,o,a;return e.source!==void 0&&t!==void 0&&t?.source===e.source&&ol((n=t?.dataSources)!==null&&n!==void 0?n:[],(i=e.dataSources)!==null&&i!==void 0?i:[])&&((a=(o=e.bag)===null||o===void 0?void 0:o.rows)!==null&&a!==void 0?a:{}).output!==void 0&&(0,l$.isLoadableGenPageOutput)(r)}function Fne(e,t){var r;try{return f$(e,t,lc((r=e.bag)===null||r===void 0?void 0:r.output))}catch{return!1}}function _p(e){if(e!==void 0)try{let t=JSON.parse(e.replace(/^\uFEFF/,""));return(0,_e.isJsonObject)(t)?t:void 0}catch{return}}function e$(e,t){if(t===Oo&&e.includes("page.tsx"))return"source";if(t===u$&&e.includes(".compiled"))return"output";if(t===Oo&&e===qi.config.name)return"config";if(t===Oo&&e===qi.prompt.name)return"prompt"}function t$(e){let t=e.toLowerCase();return c$.some(r=>qi[r].name.toLowerCase()===t)}function yv(e){return Object.fromEntries(e)}function p$(e,t,r,n){let i=[],o=new Set,a=new Set(t),s=l=>{if(o.has(l))return;let u=a.has(l)?e[l]:r&&Object.prototype.hasOwnProperty.call(r,l)?r[l]:void 0;u!==void 0&&(o.add(l),i.push([l,u]))};return(n??[]).forEach(s),t.forEach(s),Object.keys(r??{}).forEach(s),yv(i)}function r$(e){var t,r,n;return p$({dataSources:(t=e.dataSources)!==null&&t!==void 0?t:[],model:e.model,connectorBindings:e.connectorBindings,actionBindings:e.actionBindings},Pne,(r=e.bag)===null||r===void 0?void 0:r.config,(n=e.bag)===null||n===void 0?void 0:n.configKeys)}function n$(e){var t,r;return p$({userMessage:e.firstPrompt,agentMessage:e.firstAgentMessage},Rne,(t=e.bag)===null||t===void 0?void 0:t.prompt,(r=e.bag)===null||r===void 0?void 0:r.promptKeys)}function i$(e,t,r){let n=[];for(let[i,o]of Object.entries(r))if(i==="dataSources"){if(!Array.isArray(o)||!o.every(a=>typeof a=="string"))return!1;e.dataSources=o}else if(i==="model"){if(typeof o!="string")return!1;e.model=o}else i==="connectorBindings"?e.connectorBindings=o:i==="actionBindings"?e.actionBindings=o:n.push([i,o]);return t.configKeys=Object.keys(r),n.length>0&&(t.config=yv(n)),!0}function o$(e,t,r){let n=[];for(let[i,o]of Object.entries(r))if(i==="userMessage"||i==="agentMessage"){if(typeof o!="string")return!1;i==="userMessage"?e.firstPrompt=o:e.firstAgentMessage=o}else n.push([i,o]);return t.promptKeys=Object.keys(r),n.length>0&&(t.prompt=yv(n)),!0}function uc(e){var t,r;return e.source!==void 0||Object.keys((r=(t=e.bag)===null||t===void 0?void 0:t.rows)!==null&&r!==void 0?r:{}).length>0}var Mne=["dataSources","model","connectorBindings","actionBindings","firstPrompt","firstAgentMessage"];function a$(e){return uc(e)?[]:Mne.filter(t=>e[t]!==void 0).map(t=>(0,_e.issue)(`/${t}`,"genpage-raw-structured-field",`${t} cannot be applied: this page is in raw-file mode \u2014 it has no source and no managed rows, so a push writes its files[] exactly as they are, and ${t} nowhere. Set source to make the page managed (the SDK then writes config.json and firstPrompt.json from the typed fields; a file in files[] holding one of those names must be removed first), or change the file that stores the value in files[] directly.`))}function s$(){return(0,_e.issue)("/source","genpage-source-required","the page's source cannot be removed: its source row still exists, and a page without one cannot run. Set a new source, or delete the page with deleteRemoteArtifact.")}function Tp(e){return{status:"available",data:(0,Ip.utf8ToBase64)(e)}}function sc(e,t){var r,n;return{id:String((r=e.uxagentprojectid)!==null&&r!==void 0?r:""),name:String((n=e.name)!==null&&n!==void 0?n:""),files:t}}var Op=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){let r=t,n=Bi(r?.project),i=(Array.isArray(r?.files)?r.files:[]).map(g=>{var b,w,E;let A=Bi(g);return{id:String((b=A.uxagentprojectfileid)!==null&&b!==void 0?b:""),name:String((w=A.filename)!==null&&w!==void 0?w:""),fileType:Number((E=A.filetype)!==null&&E!==void 0?E:Oo),content:$ne(A.content)}}),o=Array.isArray(r?.conversation)?r.conversation.map(g=>{var b,w;let E=Bi(g);return{sender:Number(E.messagesender)===200000001?"agent":"user",message:String((b=E.message)!==null&&b!==void 0?b:""),createdOn:String((w=E.createdon)!==null&&w!==void 0?w:"")}}):void 0,a=g=>o?{...g,conversation:o}:g,s=new Map,l=[],u=!0;for(let g of i){let b=e$(g.name,g.fileType);b?((s.has(b)||g.name!==qi[b].name)&&(u=!1),s.set(b,g)):(t$(g.name)&&(u=!1),l.push(g))}if(!u||s.size===0)return a(sc(n,i));let c=sc(n,l),d={rows:{}};for(let[g,b]of s)d.rows[g]=b.id;let f=s.get("source");if(f){let g=lc(f.content);if(g===void 0)return a(sc(n,i));c.source=g}let p=s.get("output");p&&(d.output=p.content);let m=s.get("config");if(m){let g=_p(lc(m.content));if(!g||!i$(c,d,g))return a(sc(n,i))}let h=s.get("prompt");if(h){let g=_p(lc(h.content));if(!g||!o$(c,d,g))return a(sc(n,i))}return c.bag=d,a(c)}async toApiPayload(t,r,n){var i,o,a,s,l,u,c,d,f,p,m,h,g;if(r&&!ol((i=t.conversation)!==null&&i!==void 0?i:[],(o=r.conversation)!==null&&o!==void 0?o:[]))throw new Da.ValidationError("genPage",t.id,[(0,_e.issue)("/conversation","genpage-conversation-read-only","conversation is the page's recorded history and cannot be edited. Record a new turn with newTurn; revert the edit to conversation before pushing.")]);let b=a$(t);if(b.length>0)throw new Da.ValidationError("genPage",t.id,b);let w=[],E=r===void 0,A=E&&t.firstPrompt===void 0&&t.newTurn?{...t,firstPrompt:t.newTurn.prompt,...t.newTurn.agentMessage!==void 0?{firstAgentMessage:t.newTurn.agentMessage}:{}}:t;if(uc(A)){let I=(s=(a=A.bag)===null||a===void 0?void 0:a.rows)!==null&&s!==void 0?s:{},D=Le=>{var at;return(at=I[Le])!==null&&at!==void 0?at:Sp(A.id,Le)},O=(Le,at,ge)=>{w.push({id:D(Le),name:qi[Le].name,fileType:qi[Le].fileType,content:at,unchanged:ge})};if(A.source!==void 0){O("source",Tp(A.source),!E&&r?.source===A.source&&I.source!==void 0);let Le=lc((l=A.bag)===null||l===void 0?void 0:l.output);f$(A,r,Le)?O("output",{status:"retain"},!0):O("output",Tp(await this.compile(A,A.source,n)),!1)}else{if(I.source!==void 0)throw new Da.ValidationError("genPage",A.id,[s$()]);if(I.output!==void 0){if(!E&&!ol((u=r?.dataSources)!==null&&u!==void 0?u:[],(c=A.dataSources)!==null&&c!==void 0?c:[]))throw new Da.ValidationError("genPage",A.id,[(0,_e.issue)("/dataSources","genpage-source-required","the page has no source row, so its output cannot be recompiled for new data sources; set a source to change them.")]);O("output",{status:"retain"},!0)}}let $=r$(A),K=!E&&r!==void 0&&ol(r$(r),$);(E||I.config!==void 0||!K)&&O("config",Tp(JSON.stringify($)),K&&I.config!==void 0);let Re=n$(A),It=!E&&r!==void 0&&ol(n$(r),Re);(I.prompt!==void 0||Object.keys(Re).length>0&&!It)&&O("prompt",Tp(JSON.stringify(Re)),It&&I.prompt!==void 0)}for(let I of(d=A.files)!==null&&d!==void 0?d:[]){let D=(f=r?.files)===null||f===void 0?void 0:f.find(O=>O.id===I.id);w.push({id:I.id,name:I.name,fileType:I.fileType,content:I.content,unchanged:D!==void 0&&ol(D,I)})}let L=[];if(A.newTurn){let I=A.newTurn.id,D=O=>I?{id:xne(I,O)}:{};L.push({...D("user"),sender:"user",message:A.newTurn.prompt}),A.newTurn.agentMessage&&L.push({...D("agent"),sender:"agent",message:A.newTurn.agentMessage})}let R=(m=(p=A.bag)===null||p===void 0?void 0:p.config)!==null&&m!==void 0?m:{};return{name:A.name,files:w,...L.length>0?{messages:L,messageContext:{dataSources:(h=A.dataSources)!==null&&h!==void 0?h:[],model:(g=A.model)!==null&&g!==void 0?g:"",enabledTools:Array.isArray(R.enabledTools)?R.enabledTools:[],configurableTools:Array.isArray(R.configurableTools)?R.configurableTools:[]}}:{}}}committed(t,r,n={intentPending:!1}){let i=this.serverState(t,r);return n.intentPending&&t.newTurn!==void 0?{artifact:{...i,newTurn:Np(t.newTurn)},baseline:i}:{artifact:i,baseline:i}}serverState(t,r){var n,i,o,a,s,l;if(!uc(t)&&!t.newTurn)return t;let u=Np(t);if(delete u.newTurn,!uc(t))return u;let c={...(n=u.bag)!==null&&n!==void 0?n:{},rows:{...(o=(i=u.bag)===null||i===void 0?void 0:i.rows)!==null&&o!==void 0?o:{}}};for(let d of(a=r.files)!==null&&a!==void 0?a:[]){let f=c$.find(m=>qi[m].name===d.name&&qi[m].fileType===d.fileType);if(!f||u.files.some(m=>m.id===d.id)||(c.rows[f]=d.id,d.content.status!=="available"))continue;let p=(0,Ip.base64ToUtf8)(d.content.data);f==="output"?c.output={status:"available",data:d.content.data}:f==="config"?(delete c.config,delete u.dataSources,delete u.model,delete u.connectorBindings,delete u.actionBindings,i$(u,c,(s=_p(p))!==null&&s!==void 0?s:{})):f==="prompt"&&(delete c.prompt,delete u.firstPrompt,delete u.firstAgentMessage,o$(u,c,(l=_p(p))!==null&&l!==void 0?l:{}))}return u.bag=c,u}baselineContent(t){var r;let n={...t};return delete n.conversation,delete n.newTurn,n.files=[...(r=t.files)!==null&&r!==void 0?r:[]].sort((i,o)=>i.id<o.id?-1:i.id>o.id?1:0),n}normalize(t){let r=t.newTurn;return!(0,_e.isJsonObject)(r)||typeof r.id=="string"&&Xx.test(r.id)?t:{...t,newTurn:{...r,id:(0,Dp.newId)()}}}async compile(t,r,n){var i;let o=(i=t.dataSources)!==null&&i!==void 0?i:[],a=[],s=[];if(o.forEach((f,p)=>{var m;let h=(m=n?.resolveEntity)===null||m===void 0?void 0:m.call(n,f);h&&h.columnDetailComplete===!0?a.push(h):s.push((0,_e.issue)(`/dataSources/${p}`,h?"genpage-data-source-incomplete":"genpage-data-source-unresolved",h?`the column metadata of data source '${f}' could not be read completely (a choice or lookup read failed, or returned options with no label), so the page cannot be compiled with its enums. Retry the push.`:`the metadata of data source '${f}' could not be read, so the page cannot be compiled with its enums. Check the table's logical name and that it exists in this environment.`))}),s.length>0)throw new Da.ValidationError("genPage",t.id,s);if(!n?.loadTypeScript)throw new Da.ValidationError("genPage",t.id,[(0,_e.issue)("/source","genpage-compiler-unavailable","no TypeScript compiler is available to compile the page")]);let l=await n.loadTypeScript(),u=a.length>0?(0,gv.buildGenPageRuntimeTypes)(a):void 0,c=a.length>0?(0,gv.buildGenPageLegacyEnums)(a):void 0,d=(0,l$.compileGenPage)(l,r,u,c);if(d.diagnostics.length>0)throw new Da.ValidationError("genPage",t.id,d.diagnostics.map(Une));return d.code}metadataNeeds(t,r){if(t.source===void 0||!Array.isArray(t.dataSources))return[];let n=Fne(t,r)?{fetchRequired:!1}:{};return t.dataSources.filter(i=>typeof i=="string"&&i!=="").map(i=>({entityLogicalName:i,fieldName:"",needsColumnDetail:!0,...n}))}createDefault(t){var r,n;let i=Zx(t.id),o={id:i,name:(r=t.name)!==null&&r!==void 0?r:"New page",files:((n=t.files)!==null&&n!==void 0?n:[]).map(a=>{var s,l,u;return{id:Zx(a.id),name:(s=a.name)!==null&&s!==void 0?s:"index.tsx",fileType:(l=a.fileType)!==null&&l!==void 0?l:Oo,content:(u=a.content)!==null&&u!==void 0?u:{status:"available",data:""}}})};t.source!==void 0&&(o.source=t.source),t.dataSources!==void 0&&(o.dataSources=[...t.dataSources]);for(let a of["model","firstPrompt","firstAgentMessage"])t[a]!==void 0&&(o[a]=t[a]);return t.newTurn!==void 0&&(o.newTurn={...t.newTurn}),t.connectorBindings!==void 0&&(o.connectorBindings=Np(t.connectorBindings)),t.actionBindings!==void 0&&(o.actionBindings=Np(t.actionBindings)),o.source!==void 0&&(o.bag={rows:{source:Sp(i,"source"),output:Sp(i,"output"),config:Sp(i,"config")}}),o}assignMissingIds(t){if(t==null)return{id:(0,Dp.newId)()};if(!(0,_e.isJsonObject)(t))return t;let r=t;return(Object.keys(r).length===0||"id"in r||"content"in r||"fileType"in r||Array.isArray(r.files))&&(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,Dp.newId)()),r}validate(t){let r=[],n=t;for(let s of["source","model","firstPrompt","firstAgentMessage"])n[s]!==void 0&&typeof n[s]!="string"&&r.push((0,_e.issue)(`/${s}`,"genpage-field-type",`${s} must be a string, got ${typeof n[s]}`));if(n.source===void 0&&Bi(Bi(n.bag).rows).source!==void 0&&r.push(s$()),r.push(...a$(t)),n.newTurn!==void 0){let s=Bi(n.newTurn);(!(0,_e.isJsonObject)(n.newTurn)||typeof s.prompt!="string"||s.prompt.trim()==="")&&r.push((0,_e.issue)("/newTurn/prompt","genpage-turn-prompt","newTurn needs a non-empty prompt")),s.agentMessage!==void 0&&typeof s.agentMessage!="string"&&r.push((0,_e.issue)("/newTurn/agentMessage","genpage-field-type","newTurn.agentMessage must be a string")),s.id!==void 0&&(typeof s.id!="string"||!Xx.test(s.id))&&r.push((0,_e.issue)("/newTurn/id","genpage-turn-id","newTurn.id is the turn's identity, which the SDK mints \u2014 remove it, or keep the GUID it minted"))}if(n.dataSources!==void 0)if(!Array.isArray(n.dataSources))r.push((0,_e.issue)("/dataSources","genpage-data-sources-array","dataSources must be an array of table logical names"));else{let s=new Set;n.dataSources.forEach((l,u)=>{typeof l!="string"||!gv.TABLE_LOGICAL_NAME.test(l)?r.push((0,_e.issue)(`/dataSources/${u}`,"genpage-data-source-name",`a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(l)}'`)):s.has(l)?r.push((0,_e.issue)(`/dataSources/${u}`,"genpage-data-source-duplicate",`data source '${l}' is listed twice`)):s.add(l)})}n.conversation!==void 0&&!Array.isArray(n.conversation)&&r.push((0,_e.issue)("/conversation","genpage-conversation-array","conversation must be an array"));let i=n.files;if(i!==void 0&&!Array.isArray(i))return r.push((0,_e.issue)("/files","files-must-be-array",`files must be an array, got ${typeof i}`)),r;let o=uc(t),a=new Map;return(Array.isArray(i)?i:[]).forEach((s,l)=>{let u=`/files/${l}`,c=Bi(s),d=typeof c.id=="string"?c.id.trim().toLowerCase():"";if(d==="")r.push((0,_e.issue)(u,"file-id-required","a generative-page file needs an id"));else{let g=a.get(d);g!==void 0?r.push((0,_e.issue)(u,"file-id-duplicate",`two files share the id '${c.id}' (also at /files/${g}); a file's id is its identity, so a duplicate makes an edit ambiguous`)):a.set(d,l)}let f=typeof c.name=="string"?c.name:"",p=f.split("/");f===""||/[\u0000-\u001F\u007F]/.test(f)||f.includes("\\")||p.some(g=>g===""||g==="."||g==="..")?r.push((0,_e.issue)(u+"/name","file-name-invalid",`a file name must be a relative path of non-empty '/'-separated segments (no '.', '..', backslash or control character \u2014 its last segment is sent as an HTTP header); got '${f}'`)):o&&(t$(f)||e$(f,Number(c.fileType))!==void 0)&&r.push((0,_e.issue)(u+"/name","file-name-reserved",`'${f}' would be read by the maker portal as one of the page's managed rows (its source, output, config or first prompt), which the SDK writes from source and the configuration fields; it cannot also be a file in files[]`));let m=c.content;if(m===void 0){r.push((0,_e.issue)(u+"/content","file-content-required","content is required: omitting it is indistinguishable from an empty file, and the two have opposite effects on the next push"));return}let h=Bi(m);h.status==="available"?typeof h.data!="string"&&r.push((0,_e.issue)(u+"/content/data","file-content-data-invalid","available content needs base64 `data`")):h.status!=="unavailable"&&r.push((0,_e.issue)(u+"/content/status","file-content-status-invalid",`content.status must be 'available' or 'unavailable', got ${String(h.status)}`))}),r}};al.GenPageAdapter=Op;function Une(e){let t=`line ${e.line}, column ${e.column}`;return e.rule==="genpage-source-syntax"?(0,_e.issue)("/source",e.rule,`${t}: ${e.message} (TS${e.code}) \u2014 the page cannot run, so it was not pushed`):(0,_e.issue)("/source",e.rule,`${t}: ${e.message}`)}function Bne(){return{adapter:new Op,api:Ine.genPageApi,publish:(e,t)=>(0,One.publishGenPageById)(e,t),publishScope:e=>({envelope:"uxagentproject",targetIds:[e]}),rebaselineAfterPublish:"snapshot"}}al.genPageRegistration=Bne});var g$=v(Lp=>{"use strict";Object.defineProperty(Lp,"__esModule",{value:!0});Lp.reconcileBpfSecurityRoles=void 0;var Rp=ye(),Pp=ue(),qne="Global",h$={create:"Create",read:"Read",write:"Write",delete:"Delete"};async function Vne(e,t){var r,n;let i=`/EntityDefinitions(LogicalName='${(0,Pp.odataPathLiteral)(t)}')?$select=LogicalName,Privileges`,a=(n=(r=(0,Rp.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(h$).forEach(u=>{let c=a.find(d=>d.PrivilegeType===h$[u]);if(c){let d=(0,Pp.normalizeGuid)(c.PrivilegeId,"PrivilegeId");s[u]=d,l.add(d)}}),{byAccess:s,all:l}}async function Gne(e,t){var r,n;let i=`/RetrieveRolePrivilegesRole(RoleId=${t})`,a=(n=(r=(0,Rp.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.RolePrivileges)!==null&&n!==void 0?n:[];return new Set(a.map(s=>(0,Pp.normalizeGuid)(s.PrivilegeId,"PrivilegeId")))}async function Wne(e,t,r){if(r.length===0)return;let n={Privileges:r.map(o=>({Depth:qne,PrivilegeId:o}))},i=`/roles(${t})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;(0,Rp.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function zne(e,t,r){let n={Privilege:{"@odata.type":"Microsoft.Dynamics.CRM.privilege",privilegeid:r}},i=`/roles(${t})/Microsoft.Dynamics.CRM.RemovePrivilegeRole`;(0,Rp.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function jne(e,t,r){var n;if(!r||r.length===0)return;let i=await Vne(e,t.toLowerCase());for(let o of r){let a=(0,Pp.normalizeGuid)(o.roleId,"roleId"),s=new Set(((n=o.access)!==null&&n!==void 0?n:[]).map(f=>i.byAccess[f]).filter(f=>!!f)),l=await Gne(e,a),u=new Set([...l].filter(f=>i.all.has(f))),c=[...s].filter(f=>!u.has(f)),d=[...u].filter(f=>!s.has(f));await Wne(e,a,c);for(let f of d)await zne(e,a,f)}}Lp.reconcileBpfSecurityRoles=jne});var I$=v(xp=>{"use strict";Object.defineProperty(xp,"__esModule",{value:!0});xp.bpfApi=void 0;var lr=Ji(),y$=Wl(),Hne=Xt(),He=Q(),ot=ye(),pn=ue(),Kne=g$(),Jne=Cm(),cc=Am(),Yne={"Content-Type":"application/json",Accept:"application/json"},vv={...Yne,Prefer:"return=representation"},Qne=`category eq ${lr.WorkflowCategory.BusinessProcessFlow} and type eq ${lr.WorkflowTypeCode.Definition} and businessprocesstype eq ${lr.BusinessProcessType.BusinessFlow}`,Xne="workflowid,name,description,primaryentity,statecode,category,type,businessprocesstype,processorder",Zne="workflowid,name,uniquename,description,primaryentity,statecode,statuscode,category,type,businessprocesstype,processorder,xaml,clientdata",eie=["xaml","name","description","processorder"];async function bv(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,Kne.reconcileBpfSecurityRoles)(e,n,t.securityRoles)}async function Cv(e,t,r){let n={statecode:lr.StateCode.Activated,statuscode:lr.StatusCode.Activated},i=`/workflows(${t})`,{response:o,resent:a}=await D$(e,i,n,r,null);try{return(0,ot.ensureSuccess)(o,e.apiUrl(i))}catch(s){throw a?_$(s):s}}var N$=new WeakSet;function _$(e){return typeof e=="object"&&e!==null&&N$.add(e),e}function T$(e){return typeof e=="object"&&e!==null&&N$.has(e)}function b$(e){return e instanceof He.ConnectionError&&(e.statusCode===0||ot.AMBIGUOUS_WRITE_STATUSES.has(e.statusCode))}async function D$(e,t,r,n,i){let o=n??i,a=0;try{return{response:await(0,ot.resendWhile)(ot.isConcurrencyLockRefusal,()=>{a+=1;let l=a===1?n:o,u={...vv};return l&&(u["If-Match"]=l),e.patch(t,r,{headers:u})},o?ot.LOCK_BACKOFF_MS:[]),resent:a>1}}catch(s){throw a>1?_$(s):s}}async function v$(e,t,r){return(0,ot.readEtag)(await Cv(e,t,r))}function w$(e,t){return new He.SdkError("BPF_WRITE_NOT_ECHOED",`The ${t} of business process flow '${e}' was applied, but the server returned no concurrency token for it (this environment did not honour 'Prefer: return=representation'), so the next step could not be conditioned on a token this push produced and was NOT sent. `+kp(e))}async function dc(e,t){var r;let n=`/workflows(${t})${(0,pn.odataQuery)([["$select","statecode"]])}`,i=(0,ot.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.statecode,a=Number(o);if(o==null||o===""||!Number.isFinite(a))throw new He.SdkError("BPF_STATE_UNREADABLE",`Reading the state of business process flow '${t}' answered HTTP ${i.status} without a usable statecode, so whether it is Active cannot be decided.`);return a}async function wv(e,t,r,n,i=null){if((n??await dc(e,t))!==lr.StateCode.Activated)return{deactivated:!1,etag:null};let o={statecode:lr.StateCode.Draft,statuscode:lr.StatusCode.Draft},a=`/workflows(${t})`,s,l;try{({response:s,resent:l}=await D$(e,a,o,r,i))}catch(c){return await C$(e,t,c,T$(c))}if(ot.AMBIGUOUS_WRITE_STATUSES.has(s.status))return await C$(e,t,new He.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",`Deactivating business process flow '${t}' answered HTTP ${s.status} from an intermediary, so whether it committed is unknown.`),l);let u=(0,ot.ensureSuccess)(s,e.apiUrl(a));return{deactivated:!0,etag:(0,ot.readEtag)(u)}}async function C$(e,t,r,n){let i;try{i=await dc(e,t)}catch{i=void 0}if(i===lr.StateCode.Draft&&!n)return{deactivated:!0,etag:null,uncertainCause:r};if(i===lr.StateCode.Activated)throw r;let o=new He.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",i===lr.StateCode.Draft?`Deactivating business process flow '${t}' waited for the platform's concurrency lock, and its last attempt ended without a definitive answer. The process now reads Draft, but whether this deactivate or another writer's change put it there is unknown \u2014 the row may even have been replaced at the same id \u2014 so nothing more was sent: no edit, no re-activation, no delete. It MAY be left DISABLED: read it before retrying. Original failure: ${r instanceof Error?r.message:String(r)}`:`Deactivating business process flow '${t}' did not complete, and its state could not be re-read \u2014 it MAY be left DISABLED and needs reconciling. Original failure: ${r instanceof Error?r.message:String(r)}`);throw(0,He.attachCause)(o,r),o}async function tie(e,t){let r=(0,pn.normalizeGuid)(t,"workflowid");try{return await Cv(e,r,null),"restored"}catch{return Ev(e,r)}}async function rie(e,t,r){let n=(0,pn.normalizeGuid)(t,"workflowid");try{return await Cv(e,n,r),"restored"}catch(i){return i instanceof He.SdkError&&i.code===ot.VERSION_CONFLICT_CODE?"changed":Ev(e,n)}}async function Ev(e,t){try{let r=await dc(e,t);return r===lr.StateCode.Activated?"restored":r===lr.StateCode.Draft?"disabled":"unknown"}catch{return"unknown"}}async function E$(e,t,r,n){return r?{outcome:await rie(e,t,r),attempted:!0}:n?{outcome:await Ev(e,(0,pn.normalizeGuid)(t,"workflowid")),attempted:!1}:{outcome:await tie(e,t),attempted:!0}}function nie(e,t){let r=new He.SdkError(cc.WORKFLOW_DELETE_UNSETTLED_CODE,`Deleting business process flow '${e}' failed${(0,cc.failedAfterResend)(t)?" after it was re-sent":""}, and re-activating the process this delete had deactivated was refused (HTTP 412): the row at that id is no longer the version this delete deactivated \u2014 it was edited, or deleted and re-created at the same id \u2014 so it was NOT re-activated, and it MAY be left DISABLED. Read the row before deleting it again. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,He.attachCause)(r,t),r}function A$(e,t,r,n,i=!0){let o=`Original failure: ${n instanceof Error?n.message:String(n)}`,a="it was NOT re-activated: it waited for the platform's concurrency lock, and no write of this operation proves the row is still its own, so a re-activation could have enabled another writer's edit",s;return r==="changed"?s=new He.SdkError("BPF_REACTIVATE_OUTCOME_UNKNOWN",`Business process flow '${e}' was deactivated ${t}, and re-activating it was refused (HTTP 412): the row is no longer the version this operation last wrote \u2014 another writer changed it, or replaced it at the same id \u2014 so it was NOT re-activated, and it MAY be left DISABLED. Read it before retrying. ${o}`):r==="disabled"?s=new He.SdkError("BPF_LEFT_DEACTIVATED",i?`Business process flow '${e}' was deactivated ${t}, and it could NOT be reactivated \u2014 it is left DISABLED. ${o}`:`Business process flow '${e}' was deactivated ${t}, and ${a} \u2014 it is left DISABLED. ${o}`):s=new He.SdkError("BPF_REACTIVATE_OUTCOME_UNKNOWN",i?`Business process flow '${e}' was deactivated ${t}, and whether it was reactivated could not be confirmed \u2014 it MAY be left DISABLED and needs checking. ${o}`:`Business process flow '${e}' was deactivated ${t}, and ${a}; its state could not be read \u2014 it MAY be left DISABLED and needs checking. ${o}`),(0,He.attachCause)(s,n),s}async function iie(e,t){try{return await dc(e,t),"survived"}catch(r){return r instanceof He.ConnectionError&&r.statusCode===404?"removed":"unknown"}}async function oie(e,t,r){if(r)try{let{deactivated:n,etag:i}=await wv(e,t,r),o=n?i:r;if(o)return await(0,cc.deleteWorkflowResending)(e,t,{bindingToken:o,kindName:"business process flow",resendDeadlockVictim:!0,ifMatchOnFirst:!0}),"removed"}catch{}return iie(e,t)}function kp(e){return`Adopt the server's copy with fetchArtifact('bpf', '${e}', { overwrite: true }) \u2014 it REPLACES the local copy, so keep any outstanding local changes aside first \u2014 then re-apply them and push.`}function S$(e,t){return new He.SdkError("BPF_CREATE_NO_TOKEN",`Created business process flow '${e}' but the server returned no concurrency token for it (this environment did not honour 'Prefer: return=representation'), so the next push would have nothing to condition on. ${t} It was NOT rolled back: deleting it without a token could remove an edit made since. ${kp(e)}`)}function aie(e,t){let r=new He.SdkError("BPF_CREATE_NOT_ROLLED_BACK",`Creating business process flow '${e}' failed part-way, and the rollback could NOT remove it \u2014 it still EXISTS, possibly Active and half-configured. (The rollback deletes only on a token this create produced, so a row somebody has since edited is left in place on purpose; a delete the platform refused or failed leaves it too.) ${kp(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,He.attachCause)(r,t),r}function sie(e,t){let r=new He.SdkError("BPF_CREATE_ROLLBACK_OUTCOME_UNKNOWN",`Creating business process flow '${e}' failed part-way, and whether its rollback removed the process could not be confirmed \u2014 it MAY still exist, possibly Active and half-configured. ${kp(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,He.attachCause)(r,t),r}function lie(e,t){let r=new He.SdkError("BPF_CREATE_REMOVED_AFTER_CONFLICT",`Creating business process flow '${e}' was interrupted: another writer changed it right after it was created, so this push's next step was refused rather than overwrite or activate their edit \u2014 and the process has since been removed. Nothing is left behind and there is nothing to fetch. If the removal was deliberate, stop here; otherwise push again to re-create it at the same id. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,He.attachCause)(r,t),r}function Av(e){let t={};for(let r of eie)e[r]!==void 0&&(t[r]=e[r]);return t}var uie=["name,processorder","description,name,processorder"];function cie(e){let{xaml:t,...r}=Av(e);return typeof t=="string"&&uie.includes(Object.keys(r).sort().join(","))}async function die(e,t,r,n){let{xaml:i,...o}=Av(r),[,a]=await(0,y$.sendChangeSet)(e,[{method:"PATCH",path:`/workflows(${t})`,body:o,etag:n},{method:"PATCH",path:`/workflows(${t})${(0,pn.odataQuery)([["$select","workflowid"]])}`,body:{xaml:i},headers:{Prefer:"return=representation"}}],`business process flow '${t}'`);return(0,ot.readEtag)((0,y$.partResponse)(a))}xp.bpfApi={async get(e,t){let n=`/workflows(${(0,pn.normalizeGuid)(t,"id")})${(0,pn.odataQuery)([["$select",Zne]])}`,i=(0,ot.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,ot.readEtag)(i)}},async list(e,t){let r=[Qne];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,pn.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,pn.odataQuery)([["$select",Xne],["$filter",r.join(" and ")]])}`;return(await(0,Hne.collectPages)(e,n,"listArtifacts('bpf')")).map(o=>{var a,s;return{type:"bpf",id:(a=o.workflowid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",entityLogicalName:o.primaryentity,isDirty:!1}})},async create(e,t){let r=t,n=(0,pn.normalizeGuid)(r.record.workflowid,"workflowid"),i="/workflows",o=(0,ot.ensureSuccess)(await e.post(i,r.record,{headers:vv}),e.apiUrl(i)),a=(0,ot.readEtag)(o);if(!a)throw S$(n,r.status==="Active"?"The process EXISTS as Draft and was NOT activated \u2014 an activation that cannot be conditioned on our own write could activate somebody else's edit.":"The process EXISTS as Draft.");let s=a;try{r.status==="Active"&&(s=await v$(e,n,a)),await bv(e,r)}catch(l){let u=await oie(e,n,s);throw u==="survived"?aie(n,l):u==="unknown"?sie(n,l):l instanceof He.SdkError&&l.code===ot.VERSION_CONFLICT_CODE?lie(n,l):l}if(!s)throw S$(n,"The process EXISTS and IS Active, but its activation returned no token.");return{id:n,etag:s}},async update(e,t,r,n){let i=r,o=(0,pn.normalizeGuid)(t,"id"),a=(0,ot.requireEtag)(n,"bpf",o),s=await dc(e,o);if(s===lr.StateCode.Activated&&i.status==="Active"&&e.supportsAtomicBatch&&cie(i.record)){let p=await die(e,o,i.record,a);return await bv(e,i),{id:o,etag:p}}let{deactivated:l,etag:u,uncertainCause:c}=await wv(e,o,a,s),d=u,f=!1;try{if(c!==void 0)throw c;let p=a;if(l){if(!u)throw w$(o,"deactivation");p=u}let m=`/workflows(${o})`,h;try{h=(0,ot.ensureSuccess)(await e.patch(m,Av(i.record),{headers:{...vv,"If-Match":p}}),e.apiUrl(m))}catch(b){throw b$(b)&&(d=null),b}let g=(0,ot.readEtag)(h);if(d=g,i.status==="Active"){if(!g)throw w$(o,"definition write");try{g=await v$(e,o,g)}catch(b){throw b$(b)&&(d=null),b}f=!0}return await bv(e,i),{id:o,etag:g}}catch(p){if(l&&!f){let{outcome:m,attempted:h}=await E$(e,o,d,T$(p));if(m!=="restored")throw A$(o,"to apply an edit, the edit failed",m,p,h)}throw p}},async delete(e,t){let r=(0,pn.normalizeGuid)(t,"id"),n=await(0,Jne.assertWorkflowKind)(e,r,lr.WorkflowCategory.BusinessProcessFlow),{deactivated:i,etag:o}=await wv(e,r,null,void 0,n);try{await(0,cc.deleteWorkflowResending)(e,r,{bindingToken:i?o:n,kindName:"business process flow",deactivated:i,resendDeadlockVictim:!0})}catch(a){if(i&&!(0,cc.isWorkflowDeleteUnsettled)(a)){let{outcome:s,attempted:l}=await E$(e,r,o,!1);if(s==="changed")throw nie(r,a);if(s!=="restored")throw A$(r,"so it could be deleted, the delete failed",s,a,l)}throw a}}}});var fF=v(ll=>{"use strict";Object.defineProperty(ll,"__esModule",{value:!0});ll.bpfRegistration=ll.BpfAdapter=void 0;var $p=Ji(),fie=I$(),Sv=ao(),Ia=lo(),V$=so(),Gr=Zr(),Rr=lt(),ai=Q(),pie=100,_v='<?xml version="1.0" encoding="utf-16"?>',O$=1033,G$="mxswa:Workflow",mie="mxswa:ActivityReference.Properties",hie="mcwo:StepLabel",gie="mcwb:Control",P$="mcwb:Control.ControlDisplayName",W$="mcwb:Control.DataFieldName",z$="DataFieldName",R$="ControlDisplayName",j$="Literal",Fp="x:Null",L$="x:String",Tv="x:Key",Dv="DisplayName",Up="Activities",yie="StepLabels",H$="StageId",K$="StageCategory",J$="NextStageId",Y$="ProcessStepId",Iv="IsProcessRequired",Q$="EntityComposite",X$="StageComposite",Z$="StepComposite";function Nv(e){return(0,Gr.isJsonObject)(e)?e:{}}function si(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 Oa(e,t){var r;return(r=si(e).find(n=>n.tagName===t))!==null&&r!==void 0?r:null}function li(e){return Oa(e,mie)}function ur(e,t){var r;return(r=si(e).find(n=>n.getAttribute(Tv)===t))!==null&&r!==void 0?r:null}function sl(e,t){var r;return((r=e.getAttribute("AssemblyQualifiedName"))!==null&&r!==void 0?r:"").includes(t)}function Gi(e){var t;return!e||!e.firstChild?"":(t=e.firstChild.nodeValue)!==null&&t!==void 0?t:""}function eF(e,t,r){e.firstChild?e.firstChild.nodeValue=r:e.appendChild(t.createTextNode(r))}function fc(e){var t;let r=(t=e.getAttribute(Dv))!==null&&t!==void 0?t:"",n=r.indexOf(": ");return n>=0?r.slice(n+2):r}function tF(e,t){var r;let n=(r=e.getAttribute(Dv))!==null&&r!==void 0?r:"",i=n.indexOf(": ");e.setAttribute(Dv,i>=0?n.slice(0,i+2)+t:t)}function rF(e,t){let r=ur(e,yie),n=Oa(r,hie);n&&n.setAttribute("Description",t)}function bie(e){let t=ur(e,K$);if(!t||t.tagName===Fp)return;let r=Gi(t).trim();return r===""?void 0:Number(r)}function vie(e){let t=ur(e,J$);if(!t||t.tagName===Fp)return;let r=Gi(t).trim();return r===""?void 0:r}function nF(e){let t=iF(e);if(!t)return;let r=aF(t,z$,W$);return r===""?void 0:r}function Ov(e,t){let r=si(e);for(;r.length>0;){let n=r.pop();if(n.tagName===t)return n;for(let i of si(n))r.push(i)}return null}function iF(e){let t=ur(li(e),Up);return t?Ov(t,gie):null}function oF(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 aF(e,t,r){var n;return oF(e,t)?(n=e.getAttribute(t))!==null&&n!==void 0?n:"":Sie(e,r)}function k$(e,t,r,n){if(oF(e,t)){e.setAttribute(t,n);return}if(Oa(e,r)){wie(e,r,n);return}throw new ai.InvalidArgumentError(`BPF step control exposes neither a '${t}' attribute nor a <${r}> wrapper to bind a column`)}function wie(e,t,r){let n=Oa(e,t),i=n?Ov(n,j$):null;i&&i.setAttribute("Value",r)}function sF(e){return fc(e)}function Bp(e){let t=Oa(e,G$),r=[];for(let n of si(t).filter(i=>sl(i,Q$))){let i=ur(li(n),Up);for(let o of si(i).filter(a=>sl(a,X$)))r.push({el:o,entity:sF(n)})}return r}function Pv(e){let t=ur(li(e),Up);return si(t).filter(r=>sl(r,Z$))}function Cie(e){let t=li(e),r=Gi(ur(t,Iv)).trim().toLowerCase(),n=nF(e),i={id:Gi(ur(t,Y$)),name:fc(e)};return n!==void 0&&(i.fieldName=n),r==="true"&&(i.required=!0),i}function Eie(e,t){let r=li(e),n=bie(r),i=vie(r),o={id:Gi(ur(r,H$)),name:fc(e),entityLogicalName:t,steps:Pv(e).map(Cie)};return n!==void 0&&(o.category=n),i!==void 0&&(o.nextStageId=i),o}function Aie(e){return Bp(e).map(({el:t,entity:r})=>Eie(t,r))}function Vi(e){return new ai.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 Sie(e,t){var r;let n=Oa(e,t),i=n?Ov(n,j$):null;return(r=i?.getAttribute("Value"))!==null&&r!==void 0?r:""}function Rv(e,t){var r;let n=e.createElement(t.tagName),i=t.attributes;for(let a=0;a<i.length;a+=1)n.setAttribute(i[a].name,i[a].value);let o=t.childNodes;for(let a=0;a<o.length;a+=1){let s=o[a];s.nodeType===1?n.appendChild(Rv(e,s)):s.nodeType===3&&n.appendChild(e.createTextNode((r=s.nodeValue)!==null&&r!==void 0?r:""))}return n}function lF(e){return ur(li(e),Up)}function Nie(e,t,r){var n;let i=t.entityLogicalName&&t.entityLogicalName.trim()!==""?t.entityLogicalName:r,o=!((n=t.steps[0])===null||n===void 0)&&n.id&&t.steps[0].id.trim()!==""?t.steps[0].id:(0,Rr.newId)(),{body:a}=qp(Lv(i,(0,Rr.newId)(),t.id,o));return Rv(e,Bp((0,Ia.parseXmlRoot)(a,"<Activity/>"))[0].el)}function _ie(e,t){let{body:r}=qp(Lv("account",(0,Rr.newId)(),(0,Rr.newId)(),t.id));return Rv(e,Pv(Bp((0,Ia.parseXmlRoot)(r,"<Activity/>"))[0].el)[0])}function uF(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);for(let r of t)e.appendChild(r)}function cF(e,t,r,n){let i=ur(e,r);if(!i||!i.parentNode){if(n!==void 0&&n!=="")throw Vi(`setting '${r}' on a stage whose xaml does not expose that slot`);return}let o=i.parentNode;if(n===void 0||n===""){if(i.tagName!==Fp){let s=t.createElement(Fp);s.setAttribute(Tv,r),o.replaceChild(s,i)}return}if(i.tagName===L$){Gi(i)!==n&&eF(i,t,n);return}let a=t.createElement(L$);a.setAttribute(Tv,r),a.appendChild(t.createTextNode(n)),o.replaceChild(a,i)}function Tie(e,t,r){cF(e,t,K$,r===void 0?void 0:String(r))}function Die(e,t,r){cF(e,t,J$,r)}function dF(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 x$(e){return Gi(ur(li(e),H$))}function $$(e){return Gi(ur(li(e),Y$))}function F$(e,t,r){var n,i,o,a;let s=li(e);r.name!==fc(e)&&(tF(e,r.name),rF(s,r.name));let l=Gi(ur(s,Iv)).trim().toLowerCase()==="true";if(((n=r.required)!==null&&n!==void 0?n:!1)!==l){let u=ur(s,Iv);u&&eF(u,t,r.required?"True":"False")}if(((i=r.fieldName)!==null&&i!==void 0?i:"")!==((o=nF(e))!==null&&o!==void 0?o:"")){let u=iF(e);if(!u)throw new ai.InvalidArgumentError("BPF step has no <mcwb:Control> element to bind a column to");let c=(a=r.fieldName)!==null&&a!==void 0?a:"";k$(u,z$,W$,c),c!==""&&aF(u,R$,P$)===""&&k$(u,R$,P$,c)}}function M$(e,t,r,n){var i;let o=li(e);if(!o)throw new ai.InvalidArgumentError("BPF stage composite has no <\u2026ActivityReference.Properties>");if(r.name!==fc(e)&&(tF(e,r.name),rF(o,r.name)),Tie(o,t,r.category),Die(o,t,n),r.relationshipName&&r.relationshipName.trim()!=="")throw Vi("a stage relationship / table change (multi-table authoring)");if(r.actions&&r.actions.length>0||r.branch)throw Vi("stage actions or conditional branching");let a=lF(e);if(!a)throw new ai.InvalidArgumentError("BPF stage has no [Activities] collection");let s=(i=r.steps)!==null&&i!==void 0?i:[];if(s.length===0)throw new ai.InvalidArgumentError(`BPF stage '${r.name}' must have at least one step`);let l=Pv(e);if(dF(l,s.map(d=>d.id),$$)){l.forEach((d,f)=>F$(d,t,s[f]));return}let u=new Map(l.map(d=>[$$(d),d]));if(si(a).some(d=>!sl(d,Z$)))throw Vi("adding, removing or reordering steps on a stage that also contains branching or actions");let c=s.map(d=>{var f;return(f=u.get(d.id))!==null&&f!==void 0?f:_ie(t,d)});uF(a,c),c.forEach((d,f)=>F$(d,t,s[f]))}function Iie(e,t,r){let n=Oa(e,G$);if(!n)throw new ai.InvalidArgumentError("BPF xaml has no <mxswa:Workflow> root activity");if(r.globalActions&&r.globalActions.length>0)throw Vi("global (process-completed/abandoned) actions");if(!r.stages||r.stages.length===0)throw new ai.InvalidArgumentError("a BPF must have at least one stage");let i=Bp(e),o=i.map(f=>f.el);if(dF(o,r.stages.map(f=>f.id),x$)){i.forEach(({el:f,entity:p},m)=>{let h=r.stages[m];if(h.entityLogicalName&&h.entityLogicalName.trim()!==""&&h.entityLogicalName!==p)throw Vi(`changing a stage's table ('${h.entityLogicalName}' vs the process's '${p}')`);M$(f,t,h,h.nextStageId)});return}let a=si(n).filter(f=>sl(f,Q$));if(a.length!==1)throw Vi("adding, removing or reordering stages on a multi-table process");let s=a[0],l=sF(s),u=lF(s);if(!u)throw new ai.InvalidArgumentError("BPF primary entity composite has no [Activities] collection");if(si(u).some(f=>!sl(f,X$)))throw Vi("adding, removing or reordering stages on a process whose primary composite holds non-stage activities (multi-table nesting or advanced constructs)");for(let f of r.stages)if(f.entityLogicalName&&f.entityLogicalName.trim()!==""&&f.entityLogicalName!==l)throw Vi(`a stage on a different table ('${f.entityLogicalName}') than the process primary ('${l}')`);let c=new Map(o.map(f=>[x$(f),f])),d=r.stages.map(f=>{var p;return(p=c.get(f.id))!==null&&p!==void 0?p:Nie(t,f,l)});uF(u,d),d.forEach((f,p)=>{let m=p<d.length-1?r.stages[p+1].id:void 0;M$(f,t,r.stages[p],m)})}function qp(e){let t=e.match(/^<\?xml[^>]*\?>\s*/),r=t?t[0]:"";return{prolog:r,body:e.slice(r.length)}}function Oie(e){var t,r,n,i,o,a;(0,V$.installDomShim)();let s=(t=e.bag)===null||t===void 0?void 0:t.xaml;if(s){let f=new DOMParser().parseFromString("<root/>","text/xml"),p={n:"Activity",a:(0,Sv.mergeAttrs)(s.a,[]),c:(0,Sv.spliceChildren)(s.c,[])};return{root:(0,Sv.rebuildRaw)(p,(0,Ia.domEngine)(f),null),prolog:(n=(r=e.bag)===null||r===void 0?void 0:r.xamlProlog)!==null&&n!==void 0?n:_v,eol:(o=(i=e.bag)===null||i===void 0?void 0:i.xamlEol)!==null&&o!==void 0?o:"lf"}}let l=e.stages[0],u=(a=l?.steps)===null||a===void 0?void 0:a[0],c=Lv(e.entityLogicalName,(0,Rr.newId)(),l?.id&&l.id.trim()!==""?l.id:(0,Rr.newId)(),u?.id&&u.id.trim()!==""?u.id:(0,Rr.newId)()),{body:d}=qp(c);return{root:(0,Ia.parseXmlRoot)(d,"<Activity/>"),prolog:_v,eol:"lf"}}function Pie(e){let{root:t,prolog:r,eol:n}=Oie(e);Iie(t,t.ownerDocument,e);let i=(0,Ia.serializeNode)(t);return n==="crlf"&&(i=i.replace(/\n/g,`\r-`)),r+i}function Rie(e){return e.uniqueName&&e.uniqueName.trim()!==""?e.uniqueName:`new_${(e.name||"businessprocessflow").toLowerCase().replace(/[^a-z0-9]/g,"")||"businessprocessflow"}`}var Mp=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var r,n;(0,V$.installDomShim)();let i=t,o=typeof i.xaml=="string"?i.xaml:"",a={id:i.workflowid?String(i.workflowid):null,name:String((r=i.name)!==null&&r!==void 0?r:""),entityLogicalName:String((n=i.primaryentity)!==null&&n!==void 0?n:""),status:Number(i.statecode)===1?"Active":"Draft",stages:[]};if(i.uniquename&&(a.uniqueName=String(i.uniquename)),i.description!=null&&i.description!==""&&(a.description=String(i.description)),i.processorder!=null&&i.processorder!==""&&(a.order=Number(i.processorder)),o.trim()!==""){let{prolog:s,body:l}=qp(o),u=(0,Ia.parseXmlRoot)(l,"<Activity/>");a.stages=Aie(u),a.bag={xaml:(0,Ia.projectElementBag)(u),xamlProlog:s,xamlEol:/\r\n/.test(o)?"crlf":"lf"}}return a}toApiPayload(t){var r;let n={workflowid:t.id&&t.id.trim()!==""?t.id:(0,Rr.newId)(),name:t.name,uniquename:Rie(t),primaryentity:t.entityLogicalName,xaml:Pie(t),category:$p.WorkflowCategory.BusinessProcessFlow,type:$p.WorkflowTypeCode.Definition,businessprocesstype:$p.BusinessProcessType.BusinessFlow,scope:$p.WorkflowScope.Organization,processorder:(r=t.order)!==null&&r!==void 0?r:pie};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 ai.InvalidArgumentError('securityRoles require the BPF to be Active \u2014 the backing table they grant access to is created on activation; set status to "Active" to wire security roles');i.securityRoles=t.securityRoles}return i}createDefault(t){var r,n,i;let o=t.stages&&t.stages.length>0?t.stages.map(B$):[B$({id:(0,Rr.newId)(),name:"New Stage",steps:[]})],a={id:t.id&&t.id.trim()!==""?t.id:(0,Rr.newId)(),name:(r=t.name)!==null&&r!==void 0?r:"New business process flow",entityLogicalName:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",status:(i=t.status)!==null&&i!==void 0?i:"Draft",stages:o};return t.uniqueName&&(a.uniqueName=t.uniqueName),t.description!==void 0&&(a.description=t.description),t.order!==void 0&&(a.order=t.order),t.globalActions!==void 0&&(a.globalActions=t.globalActions),t.securityRoles!==void 0&&(a.securityRoles=t.securityRoles),a}assignMissingIds(t){let r=Nv(t);(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,Rr.newId)());for(let n of["stages","steps","actions","globalActions"]){let i=r[n];Array.isArray(i)&&i.forEach(o=>this.assignMissingIds(o))}return r}validate(t){let r=[],n=t.stages;if(n!==void 0&&!Array.isArray(n))return r.push((0,Gr.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,Gr.issue)("/stages","too-many-stages",`a BPF allows at most 30 stages, got ${i.length}`));let o=new Set,a=new Map;i.forEach((l,u)=>{let c=`/stages/${u}`,d=Nv(l),f=typeof d.id=="string"?d.id.trim():"";f===""?r.push((0,Gr.issue)(`${c}/id`,"stage-id-required","a stage needs an id")):a.has(f.toLowerCase())?r.push((0,Gr.issue)(`${c}/id`,"stage-id-duplicate",`two stages share the id '${l.id}' (also at /stages/${a.get(f.toLowerCase())})`)):a.set(f.toLowerCase(),u),typeof l.entityLogicalName=="string"&&l.entityLogicalName!==""&&o.add(l.entityLogicalName);let p=Array.isArray(l.steps)?l.steps:[];p.length===0&&r.push((0,Gr.issue)(`${c}/steps`,"stage-needs-step","a BPF stage must have at least one step")),p.length>30&&r.push((0,Gr.issue)(`${c}/steps`,"too-many-steps",`a stage allows at most 30 steps, got ${p.length}`));let m=new Map;p.forEach((h,g)=>{let b=`${c}/steps/${g}`,w=typeof Nv(h).id=="string"?h.id.trim():"";w===""?r.push((0,Gr.issue)(`${b}/id`,"step-id-required","a step needs an id")):m.has(w.toLowerCase())?r.push((0,Gr.issue)(`${b}/id`,"step-id-duplicate",`two steps in this stage share the id '${h.id}'`)):m.set(w.toLowerCase(),g)}),l.branch&&!U$(i,l.branch.nextStageId)&&r.push((0,Gr.issue)(`${c}/branch/nextStageId`,"branch-target-unknown",`branch nextStageId '${l.branch.nextStageId}' does not match any stage id`)),typeof l.nextStageId=="string"&&l.nextStageId!==""&&!U$(i,l.nextStageId)&&r.push((0,Gr.issue)(`${c}/nextStageId`,"next-stage-unknown",`nextStageId '${l.nextStageId}' does not match any stage id`))}),o.size>5&&r.push((0,Gr.issue)("/stages","too-many-tables",`a BPF spans at most 5 tables, got ${o.size}`));let s=Lie(i);return s>=0&&r.push((0,Gr.issue)(`/stages/${s}/nextStageId`,"next-stage-cycle","the stage nextStageId links form a cycle; the flow must be acyclic")),r}};ll.BpfAdapter=Mp;function Lie(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 U$(e,t){return e.some(r=>r.id===t)}function B$(e){var t,r;let n=e.steps&&e.steps.length>0?e.steps.map(q$):[q$({id:(0,Rr.newId)(),name:"New Step"})],i={id:e.id&&e.id.trim()!==""?e.id:(0,Rr.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 q$(e){var t;let r={id:e.id&&e.id.trim()!==""?e.id:(0,Rr.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 Lv(e,t,r,n){return`${_v}<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="${O$}" /></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="${O$}" /></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 kie(){return{adapter:new Mp,api:fie.bpfApi,languageSensitive:!0}}ll.bpfRegistration=kie});var pF=v(Vp=>{"use strict";Object.defineProperty(Vp,"__esModule",{value:!0});Vp.buildRegistrations=void 0;var xie=uL(),$ie=DL(),Fie=ck(),Mie=Tk(),Uie=Jk(),Bie=hx(),qie=Rx(),Vie=m$(),Gie=fF();function Wie(e){let t=new Map;return t.set("form",(0,xie.formRegistration)(e)),t.set("view",(0,$ie.viewRegistration)()),t.set("businessRule",(0,Fie.businessRuleRegistration)()),t.set("app",(0,Mie.appRegistration)(e)),t.set("command",(0,Uie.commandRegistration)()),t.set("chart",(0,Bie.chartRegistration)()),t.set("dashboard",(0,qie.dashboardRegistration)(e)),t.set("genPage",(0,Vie.genPageRegistration)()),t.set("bpf",(0,Gie.bpfRegistration)()),t}Vp.buildRegistrations=Wie});var _F=v(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE=Pe.ROW_SUMMARY_MODEL_NOT_DELETED_CODE=Pe.removeRowSummary=Pe.configureRowSummary=Pe.buildGptDynamicPrompt=Pe.setAppAiFeatures=Pe.getAiReadiness=Pe.saveSettingValue=Pe.retrieveSetting=Pe.AI_GATE=void 0;var mn=ye(),We=ue(),mF=lt(),Wr=Q();Pe.AI_GATE={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabled",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"EnableNLGridSearch",nlChart:"NLChartVisualizationSetting",summaries:"EnableFormInsights",m365:"m365copilotmodelappenabled"};var wF={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabledOnByDefault",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"NLGridSearchSetting",nlChart:"NLChartDataVisualizationSetting",m365:"m365copilotmodelappenabled"},zie=new Set(Object.entries(Pe.AI_GATE).filter(([e,t])=>wF[e]===t).map(([e])=>e)),jie={formFill:{enabled:"2",disabled:"1"},formFillSuggestions:{enabled:"2",disabled:"1"},formFillSmartPaste:{enabled:"2",disabled:"1"},formFillFiles:{enabled:"2",disabled:"1"}};function kv(e){return jie[e]}var Gp=1e6;function Hie(e,t){let r=kv(t),n=()=>{throw new Wr.InvalidArgumentError(`setAppAiFeatures: '${t}' must be a boolean or an integer between 0 and ${Gp} (e.g. 0, 1, 2); got '${String(e)}'.`)},i=o=>r?o?r.enabled:r.disabled:o?"1":"0";if(typeof e=="boolean")return i(e);if(typeof e=="number")return!Number.isSafeInteger(e)||e<0||e>Gp?n():String(e);if(typeof e=="string"){let o=e.trim(),a=o.toLowerCase();if(a==="true")return i(!0);if(a==="false")return i(!1);if(/^[0-9]+$/.test(o)){let s=o.replace(/^0+(?=[0-9])/,"");return s.length>String(Gp).length||Number(s)>Gp?n():s}}return n()}function Kie(e,t){let r=kv(t);return r?e===r.enabled:e!=="0"}async function Jie(e,t){var r,n,i;let o=`/appmodules${(0,We.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,We.odataLiteral)(t)}'`]])}`,a=await e.get(o);return a.status>=200&&a.status<300?(i=((n=(r=a.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0])===null||i===void 0?void 0:i.appmoduleid:void 0}async function Yie(e,t){var r,n;let i=`/appmodules${(0,We.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,We.odataLiteral)(t)}'`]])}`,o;try{o=await e.get(i)}catch(l){throw new Wr.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup failed (${l.message}). Retry, or omit appModuleId to verify by name.`)}if(o.status<200||o.status>=300)throw new Wr.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned HTTP ${o.status}. Retry, or omit appModuleId to verify by name.`);let a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new Wr.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a malformed body.`);if(a.length===0)return;let s=(n=a[0])===null||n===void 0?void 0:n.appmoduleid;if(!s)throw new Wr.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a row with no appmoduleid.`);return s}var hF=new WeakMap;async function Qie(e,t){var r,n,i;let o=hF.get(e);if(o||(o=new Map,hF.set(e,o)),o.has(t))return o.get(t);let a=`/settingdefinitions${(0,We.odataQuery)([["$select","settingdefinitionid"],["$filter",`uniquename eq '${(0,We.odataLiteral)(t)}'`]])}`,s=await e.get(a),l=s.status>=200&&s.status<300?(i=((n=(r=s.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0])===null||i===void 0?void 0:i.settingdefinitionid:void 0;return l&&o.set(t,l),l}async function Xie(e,t,r){var n,i,o;let a=await Qie(e,r);if(!t||!a)return;let s=`/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()${(0,We.odataQuery)([["$select","value,componentstate"],["$filter",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${a}`]])}`,l=await e.get(s);if(l.status<200||l.status>=300)return;let u=(i=(n=l.body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[];if(u.length===0)return{exists:!1};let c=(o=u.find(d=>d?.componentstate===1))!==null&&o!==void 0?o:u[0];return{exists:!0,value:c.value,pendingPublish:c.componentstate===1}}var Zie=4,eoe=500,gF=20,yF=3e4;function toe(e){if(e===void 0)return Zie;if(!Number.isFinite(e))throw new Wr.InvalidArgumentError(`setAppAiFeatures: verifyAttempts must be a finite integer between 1 and ${gF}; got ${e}.`);return Math.min(gF,Math.max(1,Math.floor(e)))}function roe(e){if(e===void 0)return eoe;if(!Number.isFinite(e))throw new Wr.InvalidArgumentError(`setAppAiFeatures: verifyDelayMs must be a finite number between 0 and ${yF}; got ${e}.`);return Math.min(yF,Math.max(0,Math.floor(e)))}async function noe(e,t,r,n,i,o,a){let s,l,u,c=!1;for(let d=0;d<o;d+=1){d>0&&await new Promise(p=>setTimeout(p,a*d));let f;try{let p=await t();p?(f=await Xie(e,p,n),f===void 0&&(u="the app-scope override row could not be read (insufficient access or unresolvable ids)")):u=`the app '${r}' could not be resolved to an appmoduleid \u2014 a newly created app is not readable until it is published, so either publish it first or pass \`appModuleId\` in the options to verify without the lookup`}catch(p){f=void 0,u=p.message}c=f!==void 0,l=f?.exists;try{s=(await Wp(e,n,{appUniqueName:r})).value}catch{}if(f?.exists&&f.value===i)return{result:"proven",effectiveValue:f.value,appOverrideExists:!0,...f.pendingPublish?{pendingPublish:!0}:{}}}return c?{result:"absent",effectiveValue:s,appOverrideExists:l}:{result:"unverifiable",effectiveValue:s,appOverrideExists:void 0,reason:u}}function CF(e,t,r){if(t===2)return String(e).toLowerCase()==="true";let n=r?kv(r):void 0;return n?e===n.enabled:e!=null&&e!=="0"&&e!==""}async function Wp(e,t,r={}){var n,i;let o=[`SettingName='${(0,We.odataPathLiteral)(t)}'`];r.appUniqueName&&o.push(`AppUniqueName='${(0,We.odataPathLiteral)(r.appUniqueName)}'`);let a=`/RetrieveSetting(${o.join(",")})`,l=(i=(n=(0,mn.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.SettingDetail)!==null&&i!==void 0?i:{};return{value:l.Value,dataType:l.DataType}}Pe.retrieveSetting=Wp;async function EF(e,t,r,n={}){let i={SettingName:t,Value:r};n.appUniqueName&&(i.AppUniqueName=n.appUniqueName),n.solutionUniqueName&&(i.SolutionUniqueName=n.solutionUniqueName),(0,mn.ensureSuccess)(await e.post("/SaveSettingValue",i),e.apiUrl("/SaveSettingValue"))}Pe.saveSettingValue=EF;async function ioe(e,t={}){let r={};for(let[n,i]of Object.entries(Pe.AI_GATE)){let{value:o,dataType:a}=await Wp(e,i,t);r[n]={enabled:CF(o,a,n),setting:i,value:o}}return r}Pe.getAiReadiness=ioe;async function ooe(e,t,r,n={}){var i,o;if(!t||!t.trim())throw new Wr.InvalidArgumentError("setAppAiFeatures: a non-empty appUniqueName is required (an empty value would write the setting at organization scope, affecting every app).");let a=toe(n.verifyAttempts),s=roe(n.verifyDelayMs),l=[];for(let[h,g]of Object.entries(r)){if(g===void 0)continue;let b=wF[h];b&&l.push({feature:h,setting:b,requestedValue:Hie(g,h)})}let u=[],c=n.appModuleId?(0,We.normalizeGuid)(n.appModuleId,"appModuleId"):void 0;if(c){let h=await Yie(e,t);if(h&&(0,We.normalizeGuid)(h,"appModuleId")!==c)throw new Wr.InvalidArgumentError(`setAppAiFeatures: appModuleId '${c}' does not belong to app '${t}' (which resolves to '${h}'). Settings are written by unique name, so verifying against a different app would report success for a write that never landed.`)}let d,f=async()=>c||(d||(d=await Jie(e,t)),d),p=new Map,m=async h=>{if(zie.has(h))return;let g=Pe.AI_GATE[h];if(g){if(!p.has(g))try{let{value:b,dataType:w}=await Wp(e,g);p.set(g,{enabled:CF(b,w,h),setting:g,value:b})}catch{p.set(g,void 0)}return p.get(g)}};for(let{feature:h,setting:g,requestedValue:b}of l)try{await EF(e,g,b,{appUniqueName:t,solutionUniqueName:n.solutionUniqueName});let w=await noe(e,f,t,g,b,a,s),E={feature:h,setting:g,requestedValue:b,effectiveValue:w.effectiveValue,appOverrideExists:w.appOverrideExists};if(w.result==="proven")u.push({...E,status:"applied",...w.pendingPublish?{pendingPublish:!0}:{}});else if(w.result==="absent"){let A=Kie(b,h)?await m(h):void 0;A&&!A.enabled?u.push({...E,status:"skipped",reason:`the write was issued and no app-scope override holding '${b}' was observed for '${g}' after ${a} attempt(s); the org readiness gate '${A.setting}' reads '${A.value}', so an environment admin must enable it before this app can turn the feature on`}):u.push({...E,status:"notPersisted",reason:`the write reported success but no app-scope override holding '${b}' was observed for '${g}' after ${a} attempt(s) \u2014 it reads '${(i=w.effectiveValue)!==null&&i!==void 0?i:""}' for this app (Dataverse can accept an app-scope write without storing it)`})}else u.push({...E,status:"unverified",reason:`the write was issued but could not be confirmed: ${(o=w.reason)!==null&&o!==void 0?o:"the app-scope override row could not be read"}. The value may or may not be in force \u2014 verify manually before relying on it.`})}catch(w){u.push({feature:h,setting:g,requestedValue:b,status:"failed",reason:w.message})}return{applied:u.filter(h=>h.status==="applied").map(h=>h.feature),skipped:u.filter(h=>h.status==="skipped").map(h=>h.feature),notPersisted:u.filter(h=>h.status==="notPersisted").map(h=>h.feature),unverified:u.filter(h=>h.status==="unverified").map(h=>h.feature),failed:u.filter(h=>h.status==="failed").map(h=>h.feature),outcomes:u}}Pe.setAppAiFeatures=ooe;var aoe="GptPowerPrompt",soe='{ "consumptionSource": "Api", "partnerSource": "AIBuilder", "consumptionSourceVersion": "GptApiClient"}';function AF(e){var t,r,n,i;let o=e.entityLogicalName,a=[{type:"literal",text:e.instruction.replace(/\s*$/,"")+" "}];return e.columns.forEach((s,l)=>{a.push({type:"data",id:`${o}.${s.logical}`,text:s.display}),l<e.columns.length-1&&a.push({type:"literal",text:", "})}),{version:"GptDynamicPrompt-2",prompt:a,definitions:{inputs:[{id:"RecordId",text:"RecordId",type:"text"},{id:"LanguageCode",text:"LanguageCode",type:"text"}],formulas:[],data:[{id:o,displayName:o,type:"dataverseTable",filters:[{filterType:"equal",attribute:e.primaryKey,valueType:"inputVariable",value:"RecordId"}]}],output:{formats:[(t=e.outputFormat)!==null&&t!==void 0?t:"text"]}},modelParameters:{modelType:"default",gptParameters:{temperature:(r=e.temperature)!==null&&r!==void 0?r:0}},settings:{recordRetrievalLimit:(n=e.recordRetrievalLimit)!==null&&n!==void 0?n:30,shouldPreserveRecordLinks:null,runtime:null,enableReasoning:(i=e.enableReasoning)!==null&&i!==void 0?i:!0},code:"",signature:""}}Pe.buildGptDynamicPrompt=AF;async function loe(e,t){var r,n;let i=`/EntityDefinitions(LogicalName='${(0,We.odataPathLiteral)(t)}')${(0,We.odataQuery)([["$select","MetadataId"]])}`;return(n=(r=(0,mn.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.MetadataId)!==null&&n!==void 0?n:""}async function SF(e){var t,r,n;let i=`/msdyn_aitemplates${(0,We.odataQuery)([["$select","msdyn_aitemplateid"],["$filter",`msdyn_uniquename eq '${aoe}'`],["$top",1]])}`;return((n=(r=(t=(0,mn.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||t===void 0?void 0:t.value)===null||r===void 0?void 0:r[0])!==null&&n!==void 0?n:{}).msdyn_aitemplateid}function NF(e){return`${e} row summary`}async function uoe(e,t,r){var n;let i=`/msdyn_aimodels(${t})${(0,We.odataQuery)([["$select","msdyn_name,_msdyn_templateid_value"]])}`,o=await e.get(i);if(o.status===404)return!1;let a=(n=(0,mn.ensureSuccess)(o,e.apiUrl(i)).body)!==null&&n!==void 0?n:{},s=await SF(e);return typeof a.msdyn_name=="string"&&a.msdyn_name.toLowerCase()===NF(r).toLowerCase()&&typeof a._msdyn_templateid_value=="string"&&s!==void 0&&a._msdyn_templateid_value.toLowerCase()===s.toLowerCase()}async function coe(e,t,r={}){var n,i;let o=`ais_RowSummary_${t.entityLogicalName}`,a=`/aiskillconfigs${(0,We.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,We.odataLiteral)(o)}'`],["$top",1]])}`,s=((i=(n=(0,mn.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[])[0];if(s)return{modelId:s._aimodel_value,aiSkillConfigId:s.aiskillconfigid};let l=await SF(e),u=(0,mF.newId)(),c=(0,mF.newId)(),d=JSON.stringify(AF(t)),f={ModelId:u,RunConfigurationId:c,ModelName:NF(t.entityLogicalName),TemplateId:l,CustomConfiguration:d,Source:soe,RunConfiguration:""};(0,mn.ensureSuccess)(await e.post("/AIModelPublish",f),e.apiUrl("/AIModelPublish"));try{let p=await loe(e,t.entityLogicalName),m={uniquename:o,description:`${t.entityLogicalName} row summary`,"[email protected]":`/entities(${p})`,"[email protected]":`/msdyn_aimodels(${u})`,aiskill:"RowSummary"},h=(0,mn.ensureSuccess)(await e.post("/aiskillconfigs",m),e.apiUrl("/aiskillconfigs")),g=(0,mn.requireCreatedId)(h,"aiskillconfigid","row-summary skill");return{modelId:u,aiSkillConfigId:g}}catch(p){try{await e.delete(`/msdyn_aimodels(${u})`)}catch{}throw p}}Pe.configureRowSummary=coe;async function doe(e,t){var r,n;let i=`ais_RowSummary_${t.entityLogicalName}`,o=`/aiskillconfigs${(0,We.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,We.odataLiteral)(i)}'`],["$top",1]])}`,a=((n=(r=(0,mn.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0];if(!a)return;let s=(0,We.normalizeGuid)(a.aiskillconfigid,"aiskillconfigid"),l=a._aimodel_value?(0,We.normalizeGuid)(a._aimodel_value,"_aimodel_value"):void 0,u=l?await uoe(e,l,t.entityLogicalName):!1,c=t.entityLogicalName,d=`/aiskillconfigs(${s})`,f=await bF(e,d,`${d}${(0,We.odataQuery)([["$select","aiskillconfigid"]])}`);if(f.kind==="failed")throw f.stillThere===void 0&&l&&u?(0,Wr.attachCause)(new Wr.SdkError(Pe.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE,`Removing the row summary of '${c}' could not be confirmed: deleting its skill row failed (${vF(f.failure)}) and the row could not be read back. If it is gone, its AI model '${l}' is left behind, unreferenced. Retry removeRowSummary: while the skill row exists it removes both; once it is gone, delete that model.`),f.failure):f.failure;if(l&&u){let p=`/msdyn_aimodels(${l})`,m=await bF(e,p,`${p}${(0,We.odataQuery)([["$select","msdyn_aimodelid"]])}`,poe);if(m.kind==="failed")throw(0,Wr.attachCause)(new Wr.SdkError(Pe.ROW_SUMMARY_MODEL_NOT_DELETED_CODE,`The row summary of '${c}' was removed, but its AI model '${l}' ${m.stillThere?"was not deleted":"could not be confirmed deleted"} (${vF(m.failure)}). The model is no longer used by the row summary; delete it before configuring a row summary for '${c}' again, which needs its name.`),m.failure)}}Pe.removeRowSummary=doe;Pe.ROW_SUMMARY_MODEL_NOT_DELETED_CODE="ROW_SUMMARY_MODEL_NOT_DELETED";Pe.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE="ROW_SUMMARY_REMOVAL_UNCONFIRMED";var foe="0x8004f01f";function poe(e){var t,r;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return e.status===400&&typeof n=="string"&&n.toLowerCase()===foe}function moe(e){if(e.status!==400&&e.status!==500||e.body===void 0||e.body===null)return!1;let t=typeof e.body=="string"?e.body:JSON.stringify(e.body);return/chosen as the deadlock victim|\bSql Number:\s*1205\b/i.test(t)}async function bF(e,t,r,n=()=>!1){let i;try{let o=await(0,mn.resendWhile)(moe,()=>e.delete(t));if(o.status>=200&&o.status<300||o.status===404)return{kind:"gone"};if(n(o))return{kind:"kept"};try{(0,mn.ensureSuccess)(o,e.apiUrl(t))}catch(a){i=a}}catch(o){i=o}try{let o=await e.get(r);return o.status===404?{kind:"gone"}:{kind:"failed",failure:i,stillThere:o.status>=200&&o.status<300?!0:void 0}}catch{return{kind:"failed",failure:i,stillThere:void 0}}}function vF(e){return e instanceof Error?e.message:String(e)}});var IF=v(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});ul.findArtifact=ul.resolveArtifact=void 0;var $t=ue(),Wi=Nd(),hoe=Fd(),goe=Xt(),yoe=ye(),TF=Q();async function DF(e,t,r){let n="/uxagentprojects"+(0,$t.odataQuery)([["$select","uxagentprojectid,name"],["$filter",`name eq '${(0,$t.odataLiteral)(t)}'`],...r!==void 0?[["$top",String(r)]]:[]]);return(await(0,goe.collectPages)(e,n,"resolveArtifact('genPage')",void 0,{headers:{"MSCRM.IncludeUnpublished":"true"}})).map(o=>({id:String(o.uxagentprojectid),name:String(o.name)}))}async function boe(e,t,r){var n,i,o,a,s,l,u,c,d,f,p,m,h;switch(t){case"app":{let g=(0,hoe.unpublishedAppModulesQuery)("appmoduleid,name,appmoduleidunique",`uniquename eq '${(0,$t.odataLiteral)((n=r.uniqueName)!==null&&n!==void 0?n:"")}'`,1),w=(i=(0,yoe.ensureSuccess)(await e.get(g),e.apiUrl(g)).body)===null||i===void 0?void 0:i.value,E=w&&w[0];return E?[{id:String(E.appmoduleid),name:String(E.name),appModuleIdUnique:String(E.appmoduleidunique)}]:[]}case"dashboard":return(await(0,Wi.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,$t.odataLiteral)((o=r.name)!==null&&o!==void 0?o:"")}' and type eq 0`,top:10})||[]).map(b=>({id:String(b.formid),name:String(b.name)}));case"command":{let g=await(0,Wi.queryRecords)(e,"appaction",{select:["appactionid","buttonlabeltext"],filter:`contextvalue eq '${(0,$t.odataLiteral)((a=r.entity)!==null&&a!==void 0?a:"")}'`,top:1});return g&&g.length?[{id:String(r.entity),entity:String(r.entity)}]:[]}case"form":return(await(0,Wi.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,$t.odataLiteral)((s=r.name)!==null&&s!==void 0?s:"")}' and objecttypecode eq '${(0,$t.odataLiteral)((l=r.entity)!==null&&l!==void 0?l:"")}'`,top:10})||[]).map(b=>({id:String(b.formid),name:String(b.name)}));case"chart":return(await(0,Wi.queryRecords)(e,"savedqueryvisualization",{select:["savedqueryvisualizationid","name"],filter:`name eq '${(0,$t.odataLiteral)((u=r.name)!==null&&u!==void 0?u:"")}' and primaryentitytypecode eq '${(0,$t.odataLiteral)((c=r.entity)!==null&&c!==void 0?c:"")}'`,top:10})||[]).map(b=>({id:String(b.savedqueryvisualizationid),name:String(b.name)}));case"view":return(await(0,Wi.queryRecords)(e,"savedquery",{select:["savedqueryid","name"],filter:`name eq '${(0,$t.odataLiteral)((d=r.name)!==null&&d!==void 0?d:"")}' and returnedtypecode eq '${(0,$t.odataLiteral)((f=r.entity)!==null&&f!==void 0?f:"")}'`,top:10})||[]).map(b=>({id:String(b.savedqueryid),name:String(b.name)}));case"webResource":return(await(0,Wi.queryRecords)(e,"webresource",{select:["webresourceid","name"],filter:`name eq '${(0,$t.odataLiteral)((p=r.name)!==null&&p!==void 0?p:"")}'`,top:1})||[]).map(b=>({id:String(b.webresourceid),name:String(b.name)}));case"solution":return(await(0,Wi.queryRecords)(e,"solution",{select:["solutionid","uniquename"],filter:`uniquename eq '${(0,$t.odataLiteral)((m=r.uniqueName)!==null&&m!==void 0?m:"")}'`,top:1})||[]).map(b=>({id:String(b.solutionid),name:String(b.uniquename)}));case"genPage":return DF(e,(h=r.name)!==null&&h!==void 0?h:"");default:return[]}}ul.resolveArtifact=boe;async function voe(e,t,r){var n,i,o,a,s,l,u;let c=(0,$t.odataLiteral)((n=r.name)!==null&&n!==void 0?n:""),d=(0,$t.odataLiteral)((i=r.entity)!==null&&i!==void 0?i:"");if(t==="command"){let g=await(0,Wi.queryRecords)(e,"appaction",{select:["appactionid"],filter:`contextvalue eq '${(0,$t.odataLiteral)((o=r.entity)!==null&&o!==void 0?o:"")}'`,top:1});return g&&g.length?String(r.entity):null}if(t==="genPage"){let g=await DF(e,(a=r.name)!==null&&a!==void 0?a:"",2);if(g.length>1)throw new TF.AmbiguousArtifactError(t,(s=r.name)!==null&&s!==void 0?s:"",g.length);return g.length===1?g[0].id:null}let f=woe(t,c,d,r),p=t!=="app",m=await(0,Wi.queryRecords)(e,f.set,{select:[f.idField],filter:f.filter,top:p?2:1});if(p&&m&&m.length>1)throw new TF.AmbiguousArtifactError(t,(u=(l=r.name)!==null&&l!==void 0?l:r.uniqueName)!==null&&u!==void 0?u:"",m.length);let h=m&&m[0]&&m[0][f.idField];return h!=null?String(h):null}ul.findArtifact=voe;function woe(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,$t.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 PF=v(jp=>{"use strict";Object.defineProperty(jp,"__esModule",{value:!0});jp.seedRecordGraph=void 0;var OF=Nd(),Coe=sd(),zp=ue(),Eoe=Q();async function Aoe(e,t,r={}){var n,i,o,a,s;let l=(n=r.createdIds)!==null&&n!==void 0?n:{},u=(i=r.entitySetFor)!==null&&i!==void 0?i:(f=>(0,Coe.resolveEntitySetName)(e,f)),c={},d=f=>{var p;return(p=c[f])!==null&&p!==void 0?p:l[f]};for(let f of t){let p=f.entityLogical.toLowerCase(),m=(o=f.matchOn)===null||o===void 0?void 0:o.toLowerCase(),h=[];for(let R of f.records){let I={...R.body};for(let D of(a=R.binds)!==null&&a!==void 0?a:[]){let O=D.parentEntity.toLowerCase(),$=(s=d(O))===null||s===void 0?void 0:s[D.parentIndex];if(!$)throw new Eoe.InvalidArgumentError(`Cannot resolve bind '${D.navProperty}' on a '${p}' record: parent '${D.parentEntity}'[${D.parentIndex}] has no created id. Seed the parent group before the child, or supply it via options.createdIds.`);let K=(0,zp.assertODataName)(await u(O),`entity set for parent '${D.parentEntity}'`),Re=(0,zp.normalizeGuid)($,`parent id for bind '${D.navProperty}'`);I[`${D.navProperty}@odata.bind`]=`/${K}(${Re})`}h.push(I)}let g=m?h.map(R=>{let I=R[m];return I!=null&&I!==""?String(I):null}):h.map(()=>null),b=new Map;if(m){let R=(0,zp.assertODataName)(m,"RecordGraph matchOn key"),I=[...new Set(g.filter(D=>D!==null))];if(I.length){let D=I.map($=>`${R} eq '${(0,zp.odataLiteral)($)}'`).join(" or "),O=await(0,OF.queryRecords)(e,p,{select:[R,`${p}id`],filter:D,top:5e3});for(let $ of O??[]){let K=$[R];K!=null&&b.set(String(K).toLowerCase(),String($[`${p}id`]))}}}let w=[],E=new Map,A=h.map((R,I)=>{let D=g[I];if(D&&b.has(D.toLowerCase()))return null;if(D){let O=D.toLowerCase(),$=E.get(O);if($!==void 0)return $;let K=w.push(R)-1;return E.set(O,K),K}return w.push(R)-1}),L=w.length?await(0,OF.createRecordsBulk)(e,p,w):[];c[p]=h.map((R,I)=>{let D=g[I];return D&&b.has(D.toLowerCase())?b.get(D.toLowerCase()):L[A[I]]})}return{createdIds:c}}jp.seedRecordGraph=Aoe});var qF=v(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.getEntityPrivileges=Jt.addEntityPrivilegesToRole=Jt.deleteSecurityRole=Jt.createPersonaRole=Jt.createSecurityRole=Jt.SDK_ROLE_MARKER=void 0;var Ln=ye(),Tt=ue(),zr=Q(),Hp={read:"Read",create:"Create",write:"Write",delete:"Delete",append:"Append",appendTo:"AppendTo",assign:"Assign",share:"Share"},$v={user:"Basic",businessUnit:"Local",parentChild:"Deep",organization:"Global"},RF={user:1,businessUnit:2,parentChild:3,organization:4},xv={user:"CanBeBasic",businessUnit:"CanBeLocal",parentChild:"CanBeDeep",organization:"CanBeGlobal"};Jt.SDK_ROLE_MARKER="Authored by @maker-studio/cds-maker-sdk (persona/security role).";function Soe(e){return Object.prototype.hasOwnProperty.call(Hp,e)?Hp[e]:void 0}function Noe(e){return Object.prototype.hasOwnProperty.call($v,e)}var LF=new WeakMap,kF=new WeakMap;async function FF(e,t){var r,n;(0,Tt.assertODataName)(t,"entity logical name");let i=LF.get(e);i||(i=new Map,LF.set(e,i));let o=i.get(t);if(o)return o;let a=`/EntityDefinitions(LogicalName='${(0,Tt.odataPathLiteral)(t)}')${(0,Tt.odataQuery)([["$select","LogicalName,Privileges"]])}`,l=(n=(r=(0,Ln.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||r===void 0?void 0:r.Privileges)!==null&&n!==void 0?n:[];if(l.length===0)throw new zr.InvalidArgumentError(`Entity '${t}' exposes no privileges (unknown or non-securable entity).`);return i.set(t,l),l}async function _oe(e){var t,r,n;let i=kF.get(e);if(i)return i;let o=`/businessunits${(0,Tt.odataQuery)([["$select","businessunitid"],["$filter","_parentbusinessunitid_value eq null"],["$top",1]])}`,l=(n=((r=(t=(0,Ln.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||t===void 0?void 0:t.value)!==null&&r!==void 0?r:[])[0])===null||n===void 0?void 0:n.businessunitid;if(!l)throw new zr.InvalidArgumentError("Could not resolve the root business unit.");let u=(0,Tt.normalizeGuid)(l,"businessUnitId");return kF.set(e,u),u}async function MF(e,t){var r;let n=new Map;for(let i of t){if(!i.access||i.access.length===0)throw new zr.InvalidArgumentError(`Entity '${i.entity}' privilege request has no access levels.`);let o=(r=i.scope)!==null&&r!==void 0?r:"user";if(!Noe(o))throw new zr.InvalidArgumentError(`Unknown privilege scope '${o}' for entity '${i.entity}'.`);let a=await FF(e,i.entity);for(let s of i.access){let l=Soe(s);if(!l)throw new zr.InvalidArgumentError(`Unknown access level '${s}' for entity '${i.entity}'.`);let u=a.find(m=>m.PrivilegeType===l);if(!u)throw new zr.InvalidArgumentError(`Entity '${i.entity}' does not support '${s}' access.`);let c=xv[o];if(u[c]===!1)throw new zr.InvalidArgumentError(`Privilege '${u.Name}' on '${i.entity}' does not support the '${o}' scope.`);let d=(0,Tt.normalizeGuid)(u.PrivilegeId,"PrivilegeId"),f=n.get(d);if(!f){n.set(d,{privilegeName:u.Name,privilegeType:l,scope:o,entities:new Set([i.entity])});continue}if(f.scope===o){f.entities.add(i.entity);continue}if(!(f.entities.size===1&&f.entities.has(i.entity))){let m=[...f.entities].sort().join(", ");throw new zr.InvalidArgumentError(`Entities '${m}' and '${i.entity}' share the Dataverse privilege '${u.Name}' but request different scopes; a role holds one depth per privilege. Use the same scope for all entities that share this privilege, or split them.`)}f.scope=RF[o]>RF[f.scope]?o:f.scope}}return[...n.entries()].map(([i,o])=>({entity:[...o.entities].sort().join(", "),privilegeId:i,privilegeName:o.privilegeName,privilegeType:o.privilegeType,scope:o.scope}))}async function Toe(e,t,r,n){if(r.length===0&&!n)return;let i={Privileges:r.map(a=>({Depth:$v[a.scope],PrivilegeId:a.privilegeId}))},o=`/roles(${t})/Microsoft.Dynamics.CRM.ReplacePrivilegesRole`;(0,Ln.ensureSuccess)(await e.post(o,i),e.apiUrl(o))}async function xF(e,t,r,n,i){var o,a;let s=`/${t}(${r})/${n}${(0,Tt.odataQuery)([["$select","roleid"],["$filter",`roleid eq ${i}`]])}`;return((a=(o=(0,Ln.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||o===void 0?void 0:o.value)!==null&&a!==void 0?a:[]).length>0}async function Doe(e,t,r){var n,i;let o=[],a=[],s={"@odata.id":e.apiUrl(`/roles(${t})`)};for(let l of(n=r?.teams)!==null&&n!==void 0?n:[]){let u=(0,Tt.normalizeGuid)(l,"teamId");if(!await xF(e,"teams",u,"teamroles_association",t)){let c=`/teams(${u})/teamroles_association/$ref`;(0,Ln.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}o.push(u)}for(let l of(i=r?.users)!==null&&i!==void 0?i:[]){let u=(0,Tt.normalizeGuid)(l,"userId");if(!await xF(e,"systemusers",u,"systemuserroles_association",t)){let c=`/systemusers(${u})/systemuserroles_association/$ref`;(0,Ln.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}a.push(u)}return{teams:o,users:a}}async function $F(e,t,r){var n,i;let o=`/roles${(0,Tt.odataQuery)([["$select","roleid,description,ismanaged"],["$filter",`name eq '${(0,Tt.odataLiteral)(t)}' and _businessunitid_value eq ${r}`]])}`,l=((i=(n=(0,Ln.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]).filter(d=>!!d.roleid);if(l.length===0)return;let u=d=>{var f;return d.ismanaged!==!0&&((f=d.description)!==null&&f!==void 0?f:"")===Jt.SDK_ROLE_MARKER};if(l.some(d=>!u(d)))throw new zr.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 zr.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,Tt.normalizeGuid)(c,"roleId"):void 0}function Ioe(e){var t,r;return{teams:((t=e?.teams)!==null&&t!==void 0?t:[]).map(n=>(0,Tt.normalizeGuid)(n,"teamId")),users:((r=e?.users)!==null&&r!==void 0?r:[]).map(n=>(0,Tt.normalizeGuid)(n,"userId"))}}function UF(e){return e.map(t=>({entity:t.entity,privilegeName:t.privilegeName,privilegeType:t.privilegeType,scope:t.scope}))}async function BF(e,t){var r,n;let i=(r=t.name)===null||r===void 0?void 0:r.trim();if(!i)throw new zr.InvalidArgumentError("createSecurityRole: a non-empty role name is required.");let o=t.businessUnitId?(0,Tt.normalizeGuid)(t.businessUnitId,"businessUnitId"):await _oe(e),a=await MF(e,(n=t.privileges)!==null&&n!==void 0?n:[]),s=Ioe(t.assignTo),l=await $F(e,i,o),u=l!==void 0;if(!l){let d="/roles",f={name:i,description:Jt.SDK_ROLE_MARKER,"[email protected]":`/businessunits(${o})`};try{let p=(0,Ln.ensureSuccess)(await e.post(d,f),e.apiUrl(d));l=(0,Tt.normalizeGuid)((0,Ln.requireCreatedId)(p,"roleid","role"),"roleId")}catch(p){let m;try{m=await $F(e,i,o)}catch{m=void 0}if(!m)throw p;l=m}}await Toe(e,l,a,u);let c=await Doe(e,l,s);return{roleId:l,name:i,reused:u,appliedPrivileges:UF(a),assignedTeams:c.teams,assignedUsers:c.users}}Jt.createSecurityRole=BF;async function Ooe(e,t){var r,n;let i=(r=t.persona)===null||r===void 0?void 0:r.trim();if(!i)throw new zr.InvalidArgumentError("createPersonaRole: a non-empty persona name is required.");let o=[...t.jobs.flatMap(a=>{var s;return(s=a.privileges)!==null&&s!==void 0?s:[]}),...(n=t.additionalPrivileges)!==null&&n!==void 0?n:[]];return BF(e,{name:i,businessUnitId:t.businessUnitId,privileges:o,assignTo:t.assignTo})}Jt.createPersonaRole=Ooe;async function Poe(e,t){let n=`/roles(${(0,Tt.normalizeGuid)(t,"roleId")})`;(0,Ln.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Jt.deleteSecurityRole=Poe;async function Roe(e,t,r){let n=(0,Tt.normalizeGuid)(t,"roleId");if(r.length===0)throw new zr.InvalidArgumentError("addEntityPrivilegesToRole requires at least one entity privilege (an empty grant would be a silent no-op).");let i=await MF(e,r),o={Privileges:i.map(s=>({Depth:$v[s.scope],PrivilegeId:s.privilegeId}))},a=`/roles(${n})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;return(0,Ln.ensureSuccess)(await e.post(a,o),e.apiUrl(a)),UF(i)}Jt.addEntityPrivilegesToRole=Roe;var Loe=new Map(Object.keys(Hp).map(e=>[Hp[e],e]));async function koe(e,t){return(await FF(e,t)).map(n=>{let i=Object.keys(xv).filter(a=>n[xv[a]]!==!1),o=Loe.get(n.PrivilegeType);return{name:n.Name,privilegeId:n.PrivilegeId,privilegeType:n.PrivilegeType,...o?{access:o}:{},scopes:i}})}Jt.getEntityPrivileges=koe});var iM=v(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});dr.createMakerSdk=dr.MakerSdk=dr.PUSH_NOT_ATTEMPTED_CODE=dr.ALREADY_EXISTS_CODE=void 0;var VF=Sm(),GF=Kr(),Z=Q(),hn=Fa(),xoe=CC(),eM=DC(),cl=kC(),$oe=_m(),Foe=tE(),dl=iE(),Moe=bE(),Uoe=SE(),Boe=tA(),WF=YA(),Dt=sd(),Fv=pg(),zF=nN(),Kp=Zl(),zi=Nd(),Jp=cN(),fl=Id(),qoe=Pd(),Yt=mg(),Voe=Cg(),Goe=Ig(),jF=Eg(),Woe=pF(),Yp=lt(),zoe=Ko(),ui=Nb(),gn=Pm(),Mv=cv(),joe=3e5,cr=ye(),Pa=ue(),pl=_F(),HF=IF(),Hoe=PF(),Koe=By(),pc=qF(),tM=Symbol("cds-maker-sdk.committedWrite");function Joe(e){return typeof e=="object"&&e!==null&&(e[tM]=!0),e}function Yoe(e){return typeof e=="object"&&e!==null&&e[tM]===!0}var Qoe={fileConcurrency:1},Uv="SOLUTION_COMPONENT_UNCLASSIFIED",Xoe=2,Zoe=4,eae="This table is in the solution with ALL its subcomponents. Those are members the solution does not list one by one, so fetchSolution did not enumerate or fetch them: none of its forms, views, charts or dashboards were fetched here. To fetch them, read the table's logical name from its metadata (EntityDefinitions(<componentId>), $select=LogicalName), list each kind with fetchArtifactList \u2014 'form' with formTypes Main, QuickView, QuickCreate and Card; 'view'; 'chart'; 'dashboard' \u2014 passing { entityLogicalName }, and fetch each listed id with fetchArtifact: listing returns ids and names only.";function KF(e){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"unsupported",...e.includesAllSubcomponents?{detail:eae}:{}}}function JF(e,t){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"failed",error:Po(t)}}function YF(e,t,r){let n=r;return{type:e,id:t.objectId,name:typeof n.name=="string"?n.name:t.objectId,entityLogicalName:typeof n.entityLogicalName=="string"?n.entityLogicalName:void 0,lastFetched:(0,cr.nowIso)(),isDirty:!1}}var tae=new Set(["entity","appmodule","dashboard","uxagentproject"]);function rae(e){var t;let r={entity:[],appmodule:[],dashboard:[],uxagentproject:[]},n=new Set,i=(s,l)=>{let u=`${s}\0${l.toLowerCase()}`;n.has(u)||(n.add(u),r[s].push(l))};for(let{scope:s}of e)if(s?.envelope==="entity")s.entityLogicalName&&i("entity",s.entityLogicalName);else if(s&&s.envelope!=="webresource")for(let l of(t=s.targetIds)!==null&&t!==void 0?t:[])i(s.envelope,l);let o=(s,l,u)=>u.length>0?`<${s}>${u.map(c=>`<${l}>${(0,Pa.xmlText)(c)}</${l}>`).join("")}</${s}>`:"",a=o("entities","entity",r.entity)+o("appmodules","appmodule",r.appmodule)+o("dashboards","dashboard",r.dashboard)+o("uxagentprojects","uxagentproject",r.uxagentproject);return a?`<importexportxml>${a}</importexportxml>`:void 0}function nae(e){let t=e.workspaceStorage;if(t==null)throw new Error("createMakerSdk requires a workspaceStorage. Node callers can build one with `createNodeWorkspaceStorage(path)` from '@maker-studio/cds-maker-sdk/node'; a host with no filesystem implements WorkspaceStorage directly.");return new eM.WorkspaceManager(oae,e.instanceUrl,(0,$oe.assertStorageContract)(t))}dr.ALREADY_EXISTS_CODE="ARTIFACT_ALREADY_EXISTS";var iae="this build answers a replayed create with HTTP 404, and the unpublished read of an existing row is not authoritative after another writer's save on it, so the row cannot be proven to be what this create wrote";dr.PUSH_NOT_ATTEMPTED_CODE="PUSH_NOT_ATTEMPTED";var oae="<injected workspaceStorage>",Qp=class{constructor(t){var r,n;if(this.artifactLocks=new Map,this.observedGenerations=new Map,this.baselineObserved=new Map,this.generationHighWater=new Map,this.entityMetadataLoads=new Map,this.entityMetadataLoadEpochs=new WeakMap,this.schemaWrites=new Map,this.undroppedMetadata=new Set,this.metadataPublications=new Set,t.createRecovery!==void 0&&t.createRecovery!=="adoptExact")throw new Z.InvalidArgumentError(`createRecovery must be 'adoptExact' or omitted (got '${String(t.createRecovery)}').`);this.createRecovery=t.createRecovery,this.readConcurrency=(0,Mv.resolveReadConcurrency)(t.readConcurrency),this.languageCode=(r=t.languageCode)!==null&&r!==void 0?r:zoe.DEFAULT_LCID,this.cacheStalenessMs=(n=t.cacheStalenessMs)!==null&&n!==void 0?n:joe,this.compiler={load:(0,Voe.createGenPageTypeScriptLoader)(t.typescript)},this.workspace=nae(t),this.versions=new cl.VersionManager(this.workspace),this.dataverse=new Foe.DataverseClient(t.instanceUrl,t.httpClient,t.solutionUniqueName,this.readConcurrency),this.connectivity=new Boe.ConnectivityRouter(this.dataverse,t.instanceUrl,{powerAppsServiceClient:t.powerAppsServiceClient,powerPlatformApiClient:t.powerPlatformApiClient,connectorRuntimeClient:t.connectorRuntimeClient}),this.registrations=(0,Woe.buildRegistrations)(this.languageCode)}async initWorkspace(){await this.workspace.init()}async getManifest(){return this.workspace.getManifest()}async cleanWorkspace(){await this.workspace.clean()}withArtifactLock(t,r,n){var i;let o=this.artifactKey(t,r),s=((i=this.artifactLocks.get(o))!==null&&i!==void 0?i:Promise.resolve()).then(n,n),l=s.then(()=>{},()=>{});return this.artifactLocks.set(o,l),l.then(()=>{this.artifactLocks.get(o)===l&&this.artifactLocks.delete(o)}),s}async fetchArtifact(t,r,n){return this.withArtifactLock(t,r,async()=>{let i=await this.fetchArtifactUnlocked(t,r,n);return await this.acknowledgeRefresh(t,r),i})}async fetchArtifactUnlocked(t,r,n){let i=this.requireRegistration(t,"fetchArtifact"),o=await i.api.get(this.dataverse,r);return this.applyFetchedArtifactUnlocked(t,r,i,o,n)}async applyFetchedArtifactUnlocked(t,r,n,i,o){var a,s,l;let{raw:u,etag:c,memberEtags:d,siblingEtags:f}=i,p=n.adapter.fromApiResponse(u);if(!o?.overwrite&&await this.versions.isDirty(t,r)){let h=(s=(a=await this.versions.getMeta(t,r))===null||a===void 0?void 0:a.etag)!==null&&s!==void 0?s:null;if(h&&c&&h!==c)throw new Z.LocalEditsWouldBeLostError(t,r,h,c);let g=await this.workspace.readArtifact(t,r);if(g){let b=await this.versions.getMeta(t,r);if(b&&!b.etag&&c){if(!(0,gn.deepEqual)(b.snapshot,p))throw new Z.LocalEditsWouldBeLostError(t,r,h,c);await this.versions.storeMeta(t,r,{...b,etag:c,fetchedAt:(0,cr.nowIso)()},b)}return(0,ui.cloneJson)(g)}}await this.workspace.writeArtifact(t,r,p);let m=await this.versions.getMeta(t,r);return await this.versions.storeMeta(t,r,{etag:c,languageCode:this.languageCode,projectionVersion:cl.PROJECTION_VERSION,fetchedAt:(0,cr.nowIso)(),snapshot:(0,ui.cloneJson)(p),...d?{memberEtags:d}:{},...f?{siblingEtags:f}:{},...m?.refreshGeneration?{refreshGeneration:m.refreshGeneration,observedGeneration:(l=m.observedGeneration)!==null&&l!==void 0?l:0}:{}},m),(0,ui.cloneJson)(p)}async fetchArtifactList(t,r){return this.requireRegistration(t,"fetchArtifactList").api.list(this.dataverse,r)}async fetchSolution(t){await this.workspace.ensureReady();let r=await(0,Yt.fetchSolutionComponents)(this.dataverse,t),n=[],i=[];if(this.readConcurrency>1)await this.fetchComponentsOverlapped(r,n,i);else for(let o of r)try{let a=await this.resolveComponentType(o);if(!a){i.push(KF(o));continue}let s=await this.fetchArtifact(a,o.objectId);n.push(YF(a,o,s))}catch(a){i.push(JF(o,a))}return await this.workspace.updateManifest({lastSyncAt:(0,cr.nowIso)()}),{summaries:n,skipped:i}}async fetchComponentsOverlapped(t,r,n){await(0,Mv.readEveryInOrder)(t,this.readConcurrency,i=>this.beginComponentRead(i),async(i,o)=>{try{if(!i.ok)throw i.error;let a=i.value;if(a.kind==="unsupported"){n.push(KF(o));return}let s=await this.applyFetchedArtifactUnlocked(a.type,o.objectId,a.reg,a.fetched);await this.acknowledgeRefresh(a.type,o.objectId),r.push(YF(a.type,o,s))}catch(a){n.push(JF(o,a))}})}async beginComponentRead(t){let r=await this.resolveComponentType(t);return r?this.lockedRead(r,t.objectId,async()=>{let n=this.requireRegistration(r,"fetchArtifact"),i=await n.api.get(this.dataverse,t.objectId,Qoe);return{kind:"artifact",type:r,reg:n,fetched:i}}):(0,Mv.plainRead)(async()=>({kind:"unsupported"}))}lockedRead(t,r,n){let i,o=new Promise(u=>{i=u}),a,s=new Promise(u=>{a=u}),l=this.withArtifactLock(t,r,async()=>{try{i({ok:!0,value:await n()})}catch(c){i({ok:!1,error:c})}let u=await s;await u?.()});return{outcome:o,finish:u=>(a(u),l),discard:async()=>{a(void 0),await l}}}async fetchEntityMetadata(t){let r=t.toLowerCase(),n=this.schemaEpoch(r),i=await(0,dl.fetchEntityMetadataFromApi)(this.dataverse,t);if(this.schemaEpoch(r)!==n)return i;let o=this.workspace.writeEntityMetadata(t,i),a={key:r,settled:o.then(()=>{},()=>{})};this.metadataPublications.add(a);try{await o}finally{this.metadataPublications.delete(a)}return this.schemaEpoch(r)===n&&this.undroppedMetadata.delete(r),i}schemaEpoch(t){var r,n;return`${(r=this.schemaWrites.get("*"))!==null&&r!==void 0?r:0}:${(n=this.schemaWrites.get(t.toLowerCase()))!==null&&n!==void 0?n:0}`}async schemaWrite(t,r){try{return await r()}finally{await this.forgetEntityMetadata(t)}}async forgetEntityMetadata(t){let r=i=>{var o;this.schemaWrites.set(i,((o=this.schemaWrites.get(i))!==null&&o!==void 0?o:0)+1)};if(t===void 0){r("*"),await this.publicationsSettled(void 0),await this.dropCachedMetadata(void 0);return}let n=[...new Set(t.filter(i=>typeof i=="string"&&i!=="").map(i=>i.toLowerCase()))];n.forEach(r),await this.publicationsSettled(n);for(let i of n)await this.dropCachedMetadata(i)}async publicationsSettled(t){let r=t===void 0?void 0:new Set(t);await Promise.all([...this.metadataPublications].filter(n=>r===void 0||r.has(n.key)).map(n=>n.settled))}async dropCachedMetadata(t){try{await this.workspace.dropEntityMetadata(t)}catch(r){r instanceof Z.WorkspaceNotInitializedError||r instanceof Z.WorkspaceOrgMismatchError||this.undroppedMetadata.add(t??"*");return}t===void 0?this.undroppedMetadata.clear():this.undroppedMetadata.delete(t)}async readCachedEntityMetadata(t){let r=t.toLowerCase();return this.undroppedMetadata.has("*")&&await this.dropCachedMetadata(void 0),this.undroppedMetadata.has(r)&&await this.dropCachedMetadata(r),this.undroppedMetadata.has("*")||this.undroppedMetadata.has(r)?null:this.workspace.readEntityMetadata(t)}loadMissedEntityMetadata(t){let r=this.schemaEpoch(t),n=this.entityMetadataLoads.get(t);if(n&&this.entityMetadataLoadEpochs.get(n)===r)return n;let i=this.fetchEntityMetadata(t).then(()=>{});this.entityMetadataLoads.set(t,i),this.entityMetadataLoadEpochs.set(i,r);let o=()=>{this.entityMetadataLoads.get(t)===i&&this.entityMetadataLoads.delete(t)};return i.then(o,o),i}generateGenPageRuntimeTypes(t,r){return(0,Moe.generateGenPageRuntimeTypes)(n=>this.fetchEntityMetadata(n),t,r)}findTables(t,r){return(0,dl.findTables)(this.dataverse,t,r)}getEnvironmentLanguages(){return(0,Uoe.getEnvironmentLanguages)(this.dataverse)}listConnections(){return this.connectivity.listConnections()}listConnectorOperations(t){return this.connectivity.listConnectorOperations(t)}getConnectorOperationSchema(t,r){return this.connectivity.getConnectorOperationSchema(t,r)}listConnectorTables(t,r,n){return this.connectivity.listConnectorTables(t,r,n)}getConnectorTableSchema(t,r,n,i){return this.connectivity.getConnectorTableSchema(t,r,n,i)}findColumns(t,r,n){return(0,dl.findColumns)(this.dataverse,t,r,n)}createTable(t){return this.schemaWrite([t.schemaName],()=>(0,Dt.createTable)(this.dataverse,t))}createColumn(t,r){return this.schemaWrite([t],()=>(0,Dt.createColumn)(this.dataverse,t,r))}createColumns(t,r){return this.schemaWrite([t],()=>(0,Dt.createColumns)(this.dataverse,t,r))}updateColumn(t,r,n){return this.schemaWrite([t],()=>(0,Dt.updateColumn)(this.dataverse,t,r,n))}deleteColumn(t,r){return this.schemaWrite([t],()=>(0,Dt.deleteColumn)(this.dataverse,t,r))}setFormSecurityRoles(t,r){return(0,Fv.setFormSecurityRoles)(this.dataverse,t,r)}getFormSecurityRoles(t){return(0,Fv.getFormSecurityRoles)(this.dataverse,t)}setColumnVisualization(t,r,n){return(0,Dt.setColumnVisualization)(this.dataverse,t,r,n)}getColumnVisualization(t,r){return(0,Dt.getColumnVisualization)(this.dataverse,t,r)}createCustomerColumn(t,r){return this.schemaWrite([t,"account","contact"],()=>(0,Dt.createCustomerColumn)(this.dataverse,t,r))}insertStatusValue(t,r){return this.schemaWrite([t],()=>(0,Dt.insertStatusValue)(this.dataverse,t,r))}updateTable(t,r){return this.schemaWrite([t],()=>(0,Dt.updateTable)(this.dataverse,t,r))}async setEntityIcon(t,r){if(await this.schemaWrite([t],()=>(0,Dt.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,Pa.xmlText)(t)}</entity></entities></importexportxml>`;(0,cr.ensureSuccess)(await this.dataverse.post("/PublishXml",{ParameterXml:n}),this.dataverse.apiUrl("/PublishXml"))}}createAlternateKey(t,r){return(0,Dt.createAlternateKey)(this.dataverse,t,r)}deleteAlternateKey(t,r){return(0,Dt.deleteAlternateKey)(this.dataverse,t,r)}createRelationship(t){let r=t.type==="ManyToMany"?[t.entity1,t.entity2]:[t.referencedEntity,t.referencingEntity];return this.schemaWrite(r,()=>(0,Dt.createRelationship)(this.dataverse,t))}deleteRelationship(t){return this.schemaWrite(void 0,()=>(0,Dt.deleteRelationship)(this.dataverse,t))}createGlobalOptionSet(t){return(0,Dt.createGlobalOptionSet)(this.dataverse,t)}deleteGlobalOptionSet(t){return(0,Dt.deleteGlobalOptionSet)(this.dataverse,t)}deleteTable(t){return this.schemaWrite(void 0,()=>(0,Dt.deleteTable)(this.dataverse,t))}createSecurityRole(t){return(0,pc.createSecurityRole)(this.dataverse,t)}createPersonaRole(t){return(0,pc.createPersonaRole)(this.dataverse,t)}deleteSecurityRole(t){return(0,pc.deleteSecurityRole)(this.dataverse,t)}addEntityPrivilegesToRole(t,r){return(0,pc.addEntityPrivilegesToRole)(this.dataverse,t,r)}getEntityPrivileges(t){return(0,pc.getEntityPrivileges)(this.dataverse,t)}createRecord(t,r){return(0,zi.createRecord)(this.dataverse,t,r)}createRecordsBulk(t,r){return(0,zi.createRecordsBulk)(this.dataverse,t,r)}updateRecord(t,r,n){return(0,zi.updateRecord)(this.dataverse,t,r,n)}upsertRecord(t,r,n){return(0,zi.upsertRecord)(this.dataverse,t,r,n)}deleteRecord(t,r){return(0,zi.deleteRecord)(this.dataverse,t,r)}getRecord(t,r,n){return(0,zi.getRecord)(this.dataverse,t,r,n)}queryRecords(t,r){return(0,zi.queryRecords)(this.dataverse,t,r)}seedRecordGraph(t,r){return(0,Hoe.seedRecordGraph)(this.dataverse,t,r)}resolveArtifact(t,r){return(0,HF.resolveArtifact)(this.dataverse,t,r)}findArtifact(t,r){return(0,HF.findArtifact)(this.dataverse,t,r)}async deleteAppCascade(t,r){await this.workspace.ensureReady();let n=await(0,Goe.deleteAppCascade)(this.dataverse,t,r),i=(0,Pa.normalizeGuid)(t,"appModuleId");return await this.workspace.readArtifact("app",i)&&await this.workspace.deleteArtifact("app",i),n}associateRecords(t,r,n){return(0,zi.associateRecords)(this.dataverse,t,r,n)}disassociateRecords(t,r,n,i){return(0,zi.disassociateRecords)(this.dataverse,t,r,n,i)}createWebResource(t){return(0,Jp.createWebResource)(this.dataverse,t)}updateWebResource(t,r){return(0,Jp.updateWebResource)(this.dataverse,t,r)}getWebResource(t){return(0,Jp.getWebResource)(this.dataverse,t)}deleteWebResource(t){return(0,Jp.deleteWebResource)(this.dataverse,t)}getAppSettings(t){return(0,fl.readAppSettings)(this.dataverse,t)}setAppSetting(t,r,n){return(0,fl.setAppSetting)(this.dataverse,t,r,n)}setHeaderAndNavigationRefresh(t,r){if(typeof r!="boolean")throw new Z.ValidationError("app",t,[{pointer:"/headerAndNavigationRefresh",rule:qoe.HEADER_NAV_BOOLEAN_RULE,message:`enabled must be a boolean, got ${typeof r}`}]);return(0,fl.setAppSetting)(this.dataverse,t,fl.HEADER_AND_NAVIGATION_REFRESH,r?fl.APP_SETTING_ON:fl.APP_SETTING_OFF)}getSolution(t){return(0,Yt.getSolution)(this.dataverse,t)}createPublisher(t){return(0,Yt.createPublisher)(this.dataverse,t)}createSolution(t){return(0,Yt.createSolution)(this.dataverse,t)}setSolutionVersion(t,r){return(0,Yt.setSolutionVersion)(this.dataverse,t,r)}addSolutionComponent(t){return(0,Yt.addSolutionComponent)(this.dataverse,t)}removeSolutionComponent(t,r,n){return(0,Yt.removeSolutionComponent)(this.dataverse,t,r,n)}exportSolution(t){return(0,Yt.exportSolution)(this.dataverse,t)}importSolution(t){return this.schemaWrite(void 0,()=>(0,Yt.importSolution)(this.dataverse,t))}getDeploymentSettingsTemplate(t){return(0,Yt.getDeploymentSettingsTemplate)(this.dataverse,t)}deleteSolution(t){return this.schemaWrite(void 0,()=>(0,Yt.deleteSolution)(this.dataverse,t))}async getArtifact(t,r){return this.withArtifactLock(t,r,async()=>{let{artifact:n,meta:i}=await this.readWhole(t,r);return await this.acknowledgeRefresh(t,r,i),n})}async getArtifactUnlocked(t,r){return this.readRaw(t,r)}async readWhole(t,r){let{meta:n}=await this.revalidate(t,r);return{artifact:await this.readLocal(t,r),meta:n}}async acknowledgeRefresh(t,r,n){var i,o,a;let s=this.artifactKey(t,r),l=n===void 0?await this.versions.getMeta(t,r):n;this.baselineObserved.has(s)||this.baselineObserved.set(s,(i=l?.observedGeneration)!==null&&i!==void 0?i:0);let u=(o=l?.refreshGeneration)!==null&&o!==void 0?o:0;this.raiseGenerationHighWater(s,u),l&&u!==((a=l.observedGeneration)!==null&&a!==void 0?a:0)&&await this.versions.storeMeta(t,r,{...l,observedGeneration:u},l),this.observedGenerations.set(s,u)}raiseGenerationHighWater(t,r){var n;r>((n=this.generationHighWater.get(t))!==null&&n!==void 0?n:0)&&this.generationHighWater.set(t,r)}async observedAtInvocation(t,r,n){var i,o;if(n!==void 0)return n;let a=this.baselineObserved.get(this.artifactKey(t,r));return a!==void 0?a:(o=(i=await this.versions.getMeta(t,r))===null||i===void 0?void 0:i.observedGeneration)!==null&&o!==void 0?o:0}artifactKey(t,r){return`${t}\0${(0,eM.canonicalArtifactId)(r)}`}nextRefreshGeneration(t,r,n){var i,o,a;let s=this.artifactKey(t,r),l=Math.max((i=n?.refreshGeneration)!==null&&i!==void 0?i:0,(o=n?.observedGeneration)!==null&&o!==void 0?o:0,(a=this.generationHighWater.get(s))!==null&&a!==void 0?a:0)+1;return this.raiseGenerationHighWater(s,l),l}async readRaw(t,r){return await this.revalidateIfStale(t,r),this.readLocal(t,r)}async readForMutation(t,r,n,i){var o,a;let s=await this.observedAtInvocation(t,r,i);if(((a=(o=await this.versions.getMeta(t,r))===null||o===void 0?void 0:o.refreshGeneration)!==null&&a!==void 0?a:0)>s)throw new Z.StaleArtifactError(t,r,n,"pushed");if(await this.revalidateIfStale(t,r)==="refreshed-changed")throw new Z.StaleArtifactError(t,r,n);return this.readLocal(t,r)}async readLocal(t,r){let n=await this.workspace.readArtifact(t,r);if(!n)throw new Z.ArtifactNotFoundError(t,r);return n}async revalidateIfStale(t,r){return(await this.revalidate(t,r)).outcome}async revalidate(t,r){let n=await this.versions.getMeta(t,r);if(!n)return{outcome:"skipped",meta:null};let i=n.fetchedAt?Date.parse(n.fetchedAt):NaN,o=Date.now()-i;if(!Number.isNaN(i)&&this.cacheStalenessMs>0&&o<=this.cacheStalenessMs)return{outcome:"fresh",meta:n};if(await this.versions.isDirty(t,r,n))return{outcome:"skipped",meta:n};let a=await this.workspace.readArtifact(t,r);await this.fetchArtifactUnlocked(t,r);let s=await this.workspace.readArtifact(t,r);return{outcome:(0,gn.deepEqual)(a,s)?"refreshed-unchanged":"refreshed-changed"}}async queryTree(t,r,n){return this.withArtifactLock(t,r,async()=>{let{artifact:i,meta:o}=await this.readWhole(t,r),a=hn.JsonPointer.resolve(i,n);if(a===void 0)throw new Z.PathNotFoundError(t,r,n);return n===""&&await this.acknowledgeRefresh(t,r,o),a})}async findElements(t,r,n){return this.withArtifactLock(t,r,async()=>(0,xoe.findElements)(await this.getArtifactUnlocked(t,r),n))}async withDirtyFlags(t){let r=[];for(let n of t)r.push({...n,isDirty:await this.versions.isDirty(n.type,n.id)});return r}async listArtifacts(t,r){return this.withDirtyFlags(await this.workspace.listArtifacts(t,r))}async getEntityMetadata(t){let r=await this.readCachedEntityMetadata(t);if(!r)throw new Z.ArtifactNotFoundError("entityMetadata",t);return r}async getFieldMetadata(t,r){let i=(await this.getEntityMetadata(t)).attributes.find(o=>o.logicalName===r);if(!i)throw new Z.PathNotFoundError("entityMetadata",t,r);return i}async updateElement(t,r,n,i){let o=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let a=await this.readForMutation(t,r,n,o),s=hn.JsonPointer.resolve(a,n);if(s===void 0)throw new Z.PathNotFoundError(t,r,n);let l=ji(s)&&ji(i)?{...s,...i}:i;return hn.JsonPointer.set(a,n,(0,ui.cloneJson)(l)),this.assertStructurallyValid(t,r,a,n),await this.workspace.writeArtifact(t,r,a),this.getArtifactUnlocked(t,r)})}async addElement(t,r,n,i,o){let a=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let s=await this.readForMutation(t,r,n,a),l=hn.JsonPointer.resolve(s,n);if(l===void 0)throw new Z.PathNotFoundError(t,r,n);if(!Array.isArray(l)){if(!ji(l)||!ji(i))throw new Z.ValidationError(t,r,n,"parent must be an array, or an object with an object of properties to add");if(o?.position!==void 0)throw new Z.ValidationError(t,r,n,"position is not supported for an object parent");let d={};for(let f of Object.keys(i)){if(f==="id")throw new Z.ValidationError(t,r,n,"refusing to write 'id' \u2014 that re-keys the node rather than adding a property");let p=(0,ui.cloneJson)(i[f]),m=(0,Yp.isValueMapKey)(f)||(0,Yp.pointerTouchesValueMap)(n);d[f]=m?p:Array.isArray(p)?p.map(h=>ji(h)?this.assignMissingIds(t,h):h):ji(p)?this.assignMissingIds(t,p):p}for(let f of Object.keys(d))hn.JsonPointer.set(s,hn.JsonPointer.append(n,f),d[f]);return this.assertStructurallyValid(t,r,s,n),await this.workspace.writeArtifact(t,r,s),this.getArtifactUnlocked(t,r)}let u=(0,Yp.pointerTouchesValueMap)(n)?(0,ui.cloneJson)(i):this.assignMissingIds(t,(0,ui.cloneJson)(i)),c=uae(l,o?.position);return l.splice(c,0,u),this.assertStructurallyValid(t,r,s,n),await this.workspace.writeArtifact(t,r,s),this.getArtifactUnlocked(t,r)})}async moveElement(t,r,n,i,o){let a=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{var s;let l=await this.readForMutation(t,r,n,a),u=hn.JsonPointer.resolve(l,n);if(u===void 0)throw new Z.PathNotFoundError(t,r,n);let c=hn.JsonPointer.resolve(l,i);if(c===void 0)throw new Z.PathNotFoundError(t,r,i);if(!Array.isArray(c))throw new Z.ValidationError(t,r,i,"move target must be an array");if(i===n||i.startsWith(`${n}/`))throw new Z.ValidationError(t,r,i,"cannot move an element into its own subtree");hn.JsonPointer.remove(l,n);let d=(s=o?.index)!==null&&s!==void 0?s:c.length;c.splice(Math.max(0,Math.min(d,c.length)),0,u),ZF(c);let f=hn.JsonPointer.resolve(l,XF(n));return Array.isArray(f)&&f!==c&&ZF(f),this.assertStructurallyValid(t,r,l,i),await this.workspace.writeArtifact(t,r,l),this.getArtifactUnlocked(t,r)})}async removeElement(t,r,n){let i=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let o=await this.readForMutation(t,r,n,i);if(hn.JsonPointer.resolve(o,n)===void 0)throw new Z.PathNotFoundError(t,r,n);return hn.JsonPointer.remove(o,n),this.assertStructurallyValid(t,r,o,XF(n)),await this.workspace.writeArtifact(t,r,o),this.getArtifactUnlocked(t,r)})}assertStructurallyValid(t,r,n,i){var o,a,s;let l=this.registrations.get(t),u=(s=(a=l==null?void 0:(o=l.adapter).validate)===null||a===void 0?void 0:a.call(o,n,i))!==null&&s!==void 0?s:[];if(u.length>0)throw new Z.ValidationError(t,r,u)}retrieveSetting(t,r){return(0,pl.retrieveSetting)(this.dataverse,t,r)}saveSettingValue(t,r,n){return(0,pl.saveSettingValue)(this.dataverse,t,r,n)}getAiReadiness(t){return(0,pl.getAiReadiness)(this.dataverse,t)}setAppAiFeatures(t,r,n){return(0,pl.setAppAiFeatures)(this.dataverse,t,r,n)}configureRowSummary(t,r){return(0,pl.configureRowSummary)(this.dataverse,t,r)}removeRowSummary(t){return(0,pl.removeRowSummary)(this.dataverse,t)}async enrichDefaultViews(t,r,n={}){let i=await(0,Koe.findDefaultViews)(this.dataverse,t,{excludeViewIds:n.excludeViewIds}),o=n.publish===!1,a=[],s=[],l=()=>({updated:[...a],results:[...s],pendingPublish:a.length>0?[{scope:(0,GF.boundEntityPublishScope)({entityLogicalName:t}),artifacts:a.map(c=>({type:"view",id:c}))}]:[]}),u;try{for(let c of i){await this.fetchArtifact("view",c.id),await this.updateElement("view",c.id,"/columns",r),u=c.id;let d=await this.pushArtifact("view",c.id);u=void 0,s.push(d),d.saved&&a.push(c.id)}}catch(c){throw u&&Yoe(c)&&a.push(u),o?(0,Z.withPartialEnrichment)(c,l()):c}if(o)return l();if(a.length){let c=await this.publishArtifact("view",a[0]);if(c.publish.kind==="failed")throw new Z.SdkError("ENRICH_DEFAULT_VIEWS_PUBLISH_FAILED",`enrichDefaultViews: ${a.length} view(s) on '${t}' were saved but the publish FAILED, so none of them is live (${c.publish.error.message}). Re-publish the entity to make them visible; the saves themselves are unaffected.`)}return{updated:a}}async createArtifact(t,r){let n=this.requireRegistration(t,"createArtifact"),i=n.adapter.assignMissingIds(n.adapter.createDefault(r)),o=i.id;if(!o)throw new Z.ValidationError(t,"(new)","/id","created artifact must have an id");return this.withArtifactLock(t,o,async()=>(await this.workspace.writeArtifact(t,o,i),(0,ui.cloneJson)(i)))}async deleteArtifact(t,r){return this.withArtifactLock(t,r,async()=>{await this.workspace.deleteArtifact(t,r)})}async deleteRemoteArtifact(t,r){return this.withArtifactLock(t,r,async()=>{let n=this.requireRegistration(t,"deleteRemoteArtifact");await this.workspace.ensureReady(),await n.api.delete(this.dataverse,r),await this.workspace.readArtifact(t,r)&&await this.workspace.deleteArtifact(t,r)})}async publishArtifact(t,r,n){let{result:i,siblings:o}=await this.withArtifactLock(t,r,()=>this.publishArtifactUnlocked(t,r,n));for(let a of o)await this.withArtifactLock(a.type,a.id,()=>this.adoptBracket(a));return i}async publishArtifacts(t,r){var n,i;let o=new Map;for(let m of t){let h=this.artifactKey(m.type,m.id);o.has(h)||o.set(h,{type:m.type,id:m.id})}let a=[];for(let[m,h]of o)a.push(await this.withArtifactLock(h.type,h.id,()=>this.preparePublish(m,h.type,h.id)));let s=new Set(o.keys()),l=[],u=new Set;for(let m of a){let h=((n=m.scope)===null||n===void 0?void 0:n.envelope)==="entity"?(i=m.scope.entityLogicalName)===null||i===void 0?void 0:i.toLowerCase():void 0;m.scope&&h&&!u.has(h)&&(u.add(h),l.push(m.scope))}let c=await this.captureSiblings(l,s),d=rae(a),f;if(d)try{await(0,GF.publishXml)(this.dataverse,d)}catch(m){f=Po(m)}let p=new Map;for(let m of a)p.set(m.key,await this.withArtifactLock(m.type,m.id,()=>this.settlePublish(m,f,r)));for(let m of c)await this.withArtifactLock(m.type,m.id,()=>this.adoptBracket(m));return t.map(m=>({...p.get(this.artifactKey(m.type,m.id))}))}async preparePublish(t,r,n){var i;let o=await this.readRaw(r,n),a=this.registrations.get(r);if(!a?.publish)return{key:t,type:r,id:n,artifact:o,notApplicable:!0};let s=(i=a.publishScope)===null||i===void 0?void 0:i.call(a,n,o);if(!s||!tae.has(s.envelope))throw new Z.InvalidArgumentError(`publishArtifacts: ${r} '${n}' publishes through ${s?`a '${s.envelope}'`:"no declared"} scope, which one PublishXml envelope cannot carry. Publish it with publishArtifact.`);let l=a.rebaselineAfterPublish==="bracket"?await this.captureBracket(a,r,n):void 0;return{key:t,type:r,id:n,artifact:o,reg:a,scope:s,...l?{own:l}:{}}}async settlePublish(t,r,n){let{type:i,id:o}=t;if(t.notApplicable||!t.reg)return{type:i,id:o,shipped:!1,publish:{kind:"notApplicable"}};let a=t.scope?{publishScope:t.scope}:{};if(t.reg.rebaselineAfterPublish==="snapshot"&&await this.rebaselineAfterPublish(t.reg,i,o),t.own&&await this.adoptBracket(t.own),r)return{type:i,id:o,shipped:!1,publish:{kind:"failed",error:r},...a};if(!n?.verify)return{type:i,id:o,shipped:!1,publish:{kind:"submitted"},...a};let s=await this.workspace.readArtifact(i,o).catch(()=>null);if(!s||!(0,gn.deepEqual)(s,t.artifact))return{type:i,id:o,shipped:!1,publish:{kind:"unverifiable",reason:`the local ${i} was ${s?"edited":"deleted"} while the publish was in flight, so what shipped cannot be told from what is local now; verify it with publishArtifact`},...a};let l=await this.verifyPublished(i,o,t.artifact);return{type:i,id:o,shipped:l.kind==="verified",publish:l,...a}}async publishArtifactUnlocked(t,r,n){var i;let o=await this.readRaw(t,r),a=this.registrations.get(t);if(!a?.publish)return{result:{type:t,id:r,shipped:!1,publish:{kind:"notApplicable"}},siblings:[]};let s=(i=a.publishScope)===null||i===void 0?void 0:i.call(a,r,o),l=a.rebaselineAfterPublish==="bracket"?await this.captureBracket(a,t,r):void 0,u=s?await this.captureSiblings([s],new Set([this.artifactKey(t,r)])):[];try{await a.publish(this.dataverse,r,o)}catch(d){return{result:{type:t,id:r,shipped:!1,publish:{kind:"failed",error:Po(d)},...s?{publishScope:s}:{}},siblings:[]}}if(a.rebaselineAfterPublish==="snapshot"&&await this.rebaselineAfterPublish(a,t,r),l&&await this.adoptBracket(l),!n?.verify)return{result:{type:t,id:r,shipped:!1,publish:{kind:"submitted"},...s?{publishScope:s}:{}},siblings:u};let c=await this.verifyPublished(t,r,o);return{result:{type:t,id:r,shipped:c.kind==="verified",publish:c,...s?{publishScope:s}:{}},siblings:u}}async captureBracket(t,r,n){try{let i=await this.versions.getMeta(r,n),o=i?.etag;if(!(0,cr.isVersionToken)(o)||!t.api.readContentThenToken)return;let{raw:a,etag:s,siblingEtags:l}=await t.api.readContentThenToken(this.dataverse,n),u=i?.siblingEtags;return s!==o||!sae(u,l)?void 0:{type:r,id:n,reg:t,heldEtag:o,...u?{heldSiblings:u}:{},content:this.bracketContent(t,a)}}catch{return}}async captureSiblings(t,r){var n,i,o;let a=new Map;for(let u of t){let c=u.envelope==="entity"?(n=u.entityLogicalName)===null||n===void 0?void 0:n.toLowerCase():void 0;c&&!a.has(c)&&a.set(c,[])}if(a.size===0)return[];let s;try{s=await this.workspace.listArtifacts()}catch{return[]}for(let u of s){let c=this.registrations.get(u.type);if(!(r.has(this.artifactKey(u.type,u.id))||c?.rebaselineAfterPublish!=="bracket"||!c.publishScope))try{let d=await this.workspace.readArtifact(u.type,u.id),f=d?c.publishScope(u.id,d):void 0,p=f?.envelope==="entity"?(i=f.entityLogicalName)===null||i===void 0?void 0:i.toLowerCase():void 0;p!==void 0&&((o=a.get(p))===null||o===void 0||o.push(u))}catch{continue}}let l=[];for(let u of a.values())for(let c of u){let d=this.registrations.get(c.type),f=d?await this.captureBracket(d,c.type,c.id):void 0;f&&l.push(f)}return l}async adoptBracket(t){var r;try{let n=await this.versions.getMeta(t.type,t.id);if(!n||n.etag!==t.heldEtag||!(0,gn.deepEqual)((r=n.siblingEtags)!==null&&r!==void 0?r:void 0,t.heldSiblings))return;let{raw:i,etag:o,siblingEtags:a}=await t.reg.api.get(this.dataverse,t.id);if(!(0,cr.isVersionToken)(o)||!rM(a,t.heldSiblings)||!nM(a)||!(o!==t.heldEtag||!(0,gn.deepEqual)(a??void 0,t.heldSiblings))||!(0,gn.deepEqual)(this.bracketContent(t.reg,i),t.content))return;await this.versions.storeMeta(t.type,t.id,{...n,etag:o,...t.heldSiblings?{siblingEtags:{...a}}:{},fetchedAt:(0,cr.nowIso)()},n)}catch{}}bracketContent(t,r){var n,i,o;let a=t.adapter.fromApiResponse(r);return(o=(i=(n=t.adapter).baselineContent)===null||i===void 0?void 0:i.call(n,a))!==null&&o!==void 0?o:a}adoptReadBack(t,r){try{return{artifact:t.adapter.fromApiResponse(r)}}catch(n){return{warning:`The write was saved, but the record read back after it could not be read into the local copy (${Po(n).message}). The SDK holds no version for it now, so the next push is refused: re-fetch before editing again.`}}}adoptedAsSent(t,r,n,i){try{let o={...n,...i},a=t.adapter.fromApiResponse(t.adapter.completeAsStored?t.adapter.completeAsStored(o,n):o);return(0,gn.deepEqual)(r,a)}catch{return!1}}async rebaselineAfterPublish(t,r,n){try{let i=await this.versions.getMeta(r,n);if(!i)return;let{raw:o,etag:a,memberEtags:s,siblingEtags:l}=t.api.getForRebaseline?await t.api.getForRebaseline(this.dataverse,n):await t.api.get(this.dataverse,n),u=t.adapter.fromApiResponse(o),c=d=>{var f,p,m;return(m=(p=(f=t.adapter).baselineContent)===null||p===void 0?void 0:p.call(f,d))!==null&&m!==void 0?m:d};if(!a||!(0,gn.deepEqual)(c(i.snapshot),c(u)))return;await this.versions.storeMeta(r,n,{...i,etag:a,fetchedAt:(0,cr.nowIso)(),...s?{memberEtags:s}:{},...l?{siblingEtags:l}:{}},i)}catch{}}async verifyPublished(t,r,n){var i,o,a,s,l;if(t!=="app"){let u=this.registrations.get(t);return u?.api.getPublished?this.verifyPublishedContent(u,t,r,n):{kind:"unverifiable",reason:`published-projection verification is not characterised for '${t}'; the publish was submitted`}}try{let u=`/appmodules(${(0,Pa.normalizeGuid)(r,"id")})${(0,Pa.odataQuery)([["$select","appmoduleid,name,description"]])}`,c=await this.dataverse.get(u);if(c.status>=200&&c.status<300){let d=(i=c.body)!==null&&i!==void 0?i:{},f=n;if(!f)return{kind:"unverifiable",reason:"there is no local copy of the app to compare the published projection with"};let p=[];return((o=f.name)!==null&&o!==void 0?o:"")!==((a=d.name)!==null&&a!==void 0?a:"")&&p.push("name"),((s=f.description)!==null&&s!==void 0?s:"")!==((l=d.description)!==null&&l!==void 0?l:"")&&p.push("description"),p.length>0?{kind:"unverifiable",reason:`the published projection does not yet match the saved app (${p.join(", ")} still differ). PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}:{kind:"verified"}}return{kind:"unverifiable",reason:`the published projection answered HTTP ${c.status}`}}catch(u){return{kind:"unverifiable",reason:Po(u).message}}}async verifyPublishedContent(t,r,n,i){var o,a,s;try{let l=f=>{var p,m,h;return(h=(m=(p=t.adapter).baselineContent)===null||m===void 0?void 0:m.call(p,f))!==null&&h!==void 0?h:f},u=l(i),c=(o=await this.versions.getMeta(r,n))===null||o===void 0?void 0:o.snapshot;if(c===void 0||!(0,gn.deepEqual)(u,l(c)))return{kind:"unverifiable",reason:`the local ${r} holds edits that were never pushed, so no publish could have shipped them \u2014 push, then publish again`};let d=await((s=(a=t.api).getPublished)===null||s===void 0?void 0:s.call(a,this.dataverse,n));return d?(0,gn.deepEqual)(u,l(t.adapter.fromApiResponse(d.raw)))?{kind:"verified"}:{kind:"unverifiable",reason:"the published projection does not show what was pushed. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists"}:{kind:"unverifiable",reason:`the ${r} is not in the published projection yet. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}}catch(l){return{kind:"unverifiable",reason:Po(l).message}}}async pushArtifact(t,r){return this.withArtifactLock(t,r,()=>this.pushArtifactUnlocked(t,r))}async prepareArtifactUnlocked(t,r,n){var i,o;let a=this.requireRegistration(t,"pushArtifact"),s=await this.workspace.readArtifactWithText(t,r);if(!s)throw new Z.ArtifactNotFoundError(t,r);let l=s.artifact,u=s.text,c=(o=(i=a.adapter).normalize)===null||o===void 0?void 0:o.call(i,l);c&&c!==l&&(await this.workspace.writeArtifact(t,r,c),l=c,u=void 0);let d=await this.versions.getMeta(t,r);this.assertLanguageMatches(t,r,d,a),this.assertProjectionMatches(t,r,d);let f=await this.buildMetadataContext(a.adapter,l,d?.snapshot),p=await a.adapter.toApiPayload(l,d?.snapshot,f);return await this.assertSemanticallyComplete(a,t,r,l,d===null,d?.everActivated,n),{type:t,id:r,reg:a,json:l,...u!==void 0?{storedText:u}:{},meta:d,payload:p}}async assertSemanticallyComplete(t,r,n,i,o,a,s){let l=t.adapter.issuesBlockingPush;if(!l)return;let u=i.entityLogicalName,d=(u?await this.columnsForCheck(t,u,i,s):[]).map(p=>({logicalName:p.logicalName,displayName:p.displayName,attributeType:p.attributeType,isCustomAttribute:p.isCustomAttribute,...p.maxLength!==void 0?{maxLength:p.maxLength}:{},...p.options?{options:p.options.map(m=>({value:m.value,label:m.label}))}:{},...p.targets?{targets:p.targets}:{}})),f=l.call(t.adapter,i,d,{isCreate:o,everActivated:a});if(f.length>0)throw new Z.ValidationError(r,n,f)}columnsForCheck(t,r,n,i){var o,a,s;let l=(s=(a=(o=t.adapter).columnsCheckedAtPush)===null||a===void 0?void 0:a.call(o,n))!==null&&s!==void 0?s:[],u=async()=>{let f=await this.readCachedEntityMetadata(r);if(f)return f.attributes;try{return await(0,dl.readCheckColumns)(this.dataverse,r,l)}catch{return[]}};if(!i)return u();let c=[r,...[...new Set(l)].sort()].join("\0"),d=i.get(c);return d||(d=u(),i.set(c,d)),d}async pushArtifactUnlocked(t,r,n){return this.executePrepared(await this.prepareArtifactUnlocked(t,r,n))}async executePrepared(t){var r,n,i,o,a,s,l,u,c;let{type:d,id:f,reg:p,json:m,meta:h,payload:g}=t,b=!1;try{let w;if(h)w=await p.api.update(this.dataverse,f,g,h.etag,h.memberEtags,h.siblingEtags);else{let O=await this.createWithMintedId(p,d,f,g,m);if("adopted"in O)return await this.persistAdoption(d,f,m,O.adopted);w=O.written}b=!0;let E=f;h||(w.serverIdentity&&p.adapter.applyServerIdentity&&p.adapter.applyServerIdentity(m,w.serverIdentity),w.id&&w.id!==f&&(m.id=w.id,await this.workspace.deleteArtifact(d,f),E=w.id));let A=h&&w.readBack!==void 0?this.adoptReadBack(p,w.readBack):void 0,L=A?.artifact?{artifact:A.artifact,baseline:A.artifact}:p.adapter.committed?p.adapter.committed(m,g,{intentPending:w.intentPending===!0}):{artifact:m,baseline:m};await this.workspace.writeArtifact(d,E,L.artifact,h&&E===f?t.storedText:void 0);let R=A?.artifact!==void 0&&!(0,gn.deepEqual)(A.artifact,m),I=R?this.nextRefreshGeneration(d,E,h):(r=h?.refreshGeneration)!==null&&r!==void 0?r:0,D=[...(n=w.warnings)!==null&&n!==void 0?n:[],...A?.warning?[A.warning]:[],...A?.artifact!==void 0&&!this.adoptedAsSent(p,A.artifact,w.readBack,g)?[`Saved, but the server holds something other than what was pushed (another writer saved in between, or the platform rewrote something the SDK does not model \u2014 a label in a language the org does not provision, a hand-written fragment); the local ${d} now holds the server's version. Read it (getArtifact) before the next edit: a mutation whose pointer was derived from the earlier copy is refused (StaleArtifactError).`]:[]];return await this.versions.storeMeta(d,E,{etag:A&&!A.artifact?null:w.etag,...I>0?{refreshGeneration:I,observedGeneration:(i=h?.observedGeneration)!==null&&i!==void 0?i:0}:{},languageCode:this.languageCode,projectionVersion:cl.PROJECTION_VERSION,fetchedAt:(0,cr.nowIso)(),snapshot:(0,ui.cloneJson)(L.baseline),...w.memberEtags?{memberEtags:w.memberEtags}:{},...w.siblingEtags?{siblingEtags:w.siblingEtags}:{}},E===f?h:void 0),{type:d,id:E,saved:!0,shipped:!1,publish:(o=w.publish)!==null&&o!==void 0?o:{kind:"notRequested"},...w.publish&&w.publish.kind!=="notRequested"?(()=>{var O;let $=(O=p.publishScope)===null||O===void 0?void 0:O.call(p,E,m);return $?{publishScope:$}:{}})():{},...R?{refreshed:!0}:{},...D.length>0?{warnings:D}:{}}}catch(w){let E=(0,Z.readPartialTokens)(w);if(E&&h){let A={...(a=h.memberEtags)!==null&&a!==void 0?a:{},...(s=E.memberEtags)!==null&&s!==void 0?s:{}},L={...(l=h.siblingEtags)!==null&&l!==void 0?l:{},...(u=E.siblingEtags)!==null&&u!==void 0?u:{}};await this.versions.storeMeta(d,f,{...h,...Object.keys(A).length>0?{memberEtags:A}:{},...Object.keys(L).length>0?{siblingEtags:L}:{}},h)}if(w instanceof Z.SdkError&&w.code===dr.ALREADY_EXISTS_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===VF.WFOM_API_UNAVAILABLE_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===VF.BUSINESS_RULE_LEFT_DEACTIVATED_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===cr.VERSION_CONFLICT_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:(0,jF.isFailureAfterPrimaryWrite)(w)?w:new Z.VersionConflictError(d,f,(c=h?.etag)!==null&&c!==void 0?c:null,null,w.message)};throw b?Joe(w):w}}assertLanguageMatches(t,r,n,i){if(i?.languageSensitive&&!(n?.languageCode===void 0||n.languageCode===this.languageCode))throw new Z.SdkError("ARTIFACT_LANGUAGE_MISMATCH",`Refusing to push ${t} '${r}': it was fetched with languageCode ${n.languageCode} but this SDK is configured with ${this.languageCode}. Pushing would rewrite labels read in one language as labels in another. Re-fetch with languageCode ${this.languageCode}, or create the SDK with languageCode ${n.languageCode}.`)}assertProjectionMatches(t,r,n){var i;if(n&&n.projectionVersion!==cl.PROJECTION_VERSION)throw new Z.SdkError("ARTIFACT_PROJECTION_STALE",`Refusing to push ${t} '${r}': its workspace copy was produced by projection version ${(i=n.projectionVersion)!==null&&i!==void 0?i:"unknown (pre-versioning)"}, but this SDK produces version ${cl.PROJECTION_VERSION}. The parsers changed in between, so an unedited part of this artifact can no longer be told apart from an edited one and pushing could overwrite server content the caller never touched. Re-fetch it with fetchArtifact('${t}', '${r}') and re-apply any local edits.`)}async createWithMintedId(t,r,n,i,o){try{return{written:await t.api.create(this.dataverse,i,n)}}catch(a){let s=r==="form"?(0,Fv.readPrimaryCreateRefusal)(a):void 0;if(s?.status===404&&await(0,zF.formExistsAtId)(()=>t.api.get(this.dataverse,n),s.sent.formid)){let u=`the platform answered the create with ${a.message} \u2014 this build refuses a replayed create that way \u2014 but a read of that id finds the record`;throw(0,Z.attachCause)(new Z.SdkError(dr.ALREADY_EXISTS_CODE,Bv(r,n,u)+(this.createRecovery==="adoptExact"?` ${QF(iae)}`:"")),a)}if(!(a instanceof Z.SdkError)||a.code!==cr.VERSION_CONFLICT_CODE||(0,jF.isFailureAfterPrimaryWrite)(a))throw a;if(this.createRecovery==="adoptExact"&&s?.status===412){let l=await(0,zF.recoverFormCreate)({client:this.dataverse,read:()=>t.api.get(this.dataverse,n),sent:s.sent,authoredFormType:o.formType,project:u=>t.adapter.fromApiResponse(u)});if("adopted"in l)return{adopted:l.adopted};throw new Z.SdkError(dr.ALREADY_EXISTS_CODE,`${Bv(r,n)} ${QF(l.refused)}`)}throw new Z.SdkError(dr.ALREADY_EXISTS_CODE,Bv(r,n))}}async persistAdoption(t,r,n,i){let{artifact:o,etag:a}=i,s=!(0,gn.deepEqual)(o,n);return await this.versions.storeMeta(t,r,{etag:a,...s?{refreshGeneration:this.nextRefreshGeneration(t,r,null),observedGeneration:0}:{},languageCode:this.languageCode,projectionVersion:cl.PROJECTION_VERSION,fetchedAt:(0,cr.nowIso)(),snapshot:(0,ui.cloneJson)(o)},null),s&&await this.workspace.writeArtifact(t,r,o),{type:t,id:r,saved:!1,adoptedExisting:!0,shipped:!1,publish:{kind:"notRequested"},...s?{refreshed:!0}:{}}}async buildMetadataContext(t,r,n){var i,o,a,s;let l=(o=(i=t.metadataNeeds)===null||i===void 0?void 0:i.call(t,r,n))!==null&&o!==void 0?o:[],u=new Set(l.map(R=>R.entityLogicalName).filter(R=>!!R)),c=new Set(l.filter(R=>R.needsColumnDetail).map(R=>R.entityLogicalName)),d=new Set(l.filter(R=>R.needsColumnDetail||!R.fieldName).map(R=>R.entityLogicalName)),f=R=>l.filter(I=>I.entityLogicalName===R).every(I=>I.fetchRequired===!1),p=new Map,m=new Map;for(let R of u){let I=await this.readCachedEntityMetadata(R);if(I&&c.has(R)&&(I.columnDetailComplete!==!0||!(typeof I.columnDetailVersion=="number"&&I.columnDetailVersion>=dl.COLUMN_DETAIL_VERSION)||I.attributes.some(D=>typeof D.attributeTypeName!="string"))&&(I=null),!I&&!d.has(R)){if(!f(R)){let D=l.filter(O=>O.entityLogicalName===R).map(O=>O.fieldName);try{let O=await(0,dl.readColumnHints)(this.dataverse,R,D);m.set(R,new Map(O.map($=>[$.logicalName,$])))}catch{}}continue}if(!I&&!f(R))try{await this.loadMissedEntityMetadata(R),I=await this.readCachedEntityMetadata(R)}catch{}I&&p.set(R,I)}let h=(R,I)=>{var D,O,$;return(O=(D=p.get(R))===null||D===void 0?void 0:D.attributes.find(K=>K.logicalName===I))!==null&&O!==void 0?O:($=m.get(R))===null||$===void 0?void 0:$.get(I)},g=this.languageCode,w=l.some(R=>{if(!R.needsLabel||!R.fieldName)return!1;let I=h(R.entityLogicalName,R.fieldName);return I?.localizedDisplayName!==void 0&&!I.localizedDisplayName[g]})?await this.readBaseLanguage():void 0,E=!((a=t.needsBaseLanguage)===null||a===void 0)&&a.call(t,r)?await this.readBaseLanguage():void 0,A=(s=t.customControlNeeds)===null||s===void 0?void 0:s.call(t,r,n),L=A&&(A.controls.length>0||A.columns.length>0)?await this.readPcfNeeds(A):void 0;return{resolveField:(R,I)=>{let D=h(R,I);return D?{displayName:lae(D,g,w),attributeType:D.attributeType}:void 0},resolveEntity:R=>p.get(R),loadTypeScript:()=>this.compiler.load(),...E!==void 0?{baseLanguageCode:E}:{},...L?{pcf:L}:{}}}async readPcfNeeds(t){let r=new Map;for(let i of t.controls)r.set(i,await(0,WF.readControlManifest)(this.dataverse,i));let n=new Map;for(let i of t.columns)n.set(i,await(0,WF.readPcfColumn)(this.dataverse,t.entityLogicalName,i,t.requireCreateEligibility?{requireCreateEligibility:!0}:void 0));return{control:i=>r.get(i),column:(i,o)=>i===t.entityLogicalName?n.get(o):void 0}}readBaseLanguage(){if(!this.baseLanguage){let t=(async()=>{var r,n,i;try{let o=await this.dataverse.get("/organizations?$select=languagecode");if(o.status<200||o.status>=300)return;let a=Number((i=(n=(r=o.body)===null||r===void 0?void 0:r.value)===null||n===void 0?void 0:n[0])===null||i===void 0?void 0:i.languagecode);return Number.isInteger(a)&&a>0?a:void 0}catch{return}})();this.baseLanguage=t,t.then(r=>{r===void 0&&this.baseLanguage===t&&(this.baseLanguage=void 0)})}return this.baseLanguage}async pushAll(){let t=await this.getDirtyArtifacts();await this.warmBatchMetadata(t);let r=new Map,n=new Map;for(let o=0;o<t.length;o+=1){let a=t[o];try{await this.withArtifactLock(a.type,a.id,()=>this.prepareArtifactUnlocked(a.type,a.id,r))}catch(s){n.set(o,{type:a.type,id:a.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:Po(s)})}}if(n.size>0)return t.map((o,a)=>{var s;return(s=n.get(a))!==null&&s!==void 0?s:{type:o.type,id:o.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:new Z.SdkError(dr.PUSH_NOT_ATTEMPTED_CODE,`Not attempted: ${n.size} artifact(s) in this batch could not be prepared, so no writes were issued. Fix the reported failures and push again.`)}});let i=[];for(let o of t)try{i.push(await this.withArtifactLock(o.type,o.id,()=>this.pushArtifactUnlocked(o.type,o.id,r)))}catch(a){i.push({type:o.type,id:o.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:Po(a)})}return i}async warmBatchMetadata(t){var r,n,i;let o=new Set;for(let a of t){let s=this.registrations.get(a.type);if(!s)continue;let l;try{l=await this.readLocal(a.type,a.id)}catch{continue}let u=l.entityLogicalName;u&&o.add(u);for(let c of(i=(n=(r=s.adapter).metadataNeeds)===null||n===void 0?void 0:n.call(r,l))!==null&&i!==void 0?i:[])c.entityLogicalName&&o.add(c.entityLogicalName)}for(let a of o)if(!await this.readCachedEntityMetadata(a))try{await this.loadMissedEntityMetadata(a)}catch{}}async getDirtyArtifacts(){return(await this.withDirtyFlags(await this.workspace.listArtifacts())).filter(r=>r.isDirty)}async diffArtifact(t,r){return this.versions.diff(t,r)}assignMissingIds(t,r){let n=this.registrations.get(t);return n?n.adapter.assignMissingIds(r):(0,Yp.assignMissingIds)(r)}async resolveComponentType(t){if(t.genPage)return"genPage";switch(t.componentType){case Yt.SolutionComponentType.SavedQuery:return"view";case Yt.SolutionComponentType.SavedQueryVisualization:return"chart";case Yt.SolutionComponentType.AppModule:return"app";case Yt.SolutionComponentType.Workflow:return this.workflowArtifactType(t);case Yt.SolutionComponentType.SystemForm:return this.systemFormArtifactType(t.objectId);default:return}}async systemFormArtifactType(t){let r=await(0,Kp.readSystemFormType)(this.dataverse,t);if(Number.isNaN(r))throw new Z.SdkError(Uv,`System form '${t}' answered without a readable type, so whether it is a form or a dashboard cannot be told.`);return(0,Kp.systemFormKindOf)(r)}async workflowArtifactType(t){let r=(0,Pa.normalizeGuid)(t.objectId,"workflowId"),n=`/workflows(${r})${(0,Pa.odataQuery)([["$select","category,businessprocesstype"]])}`,o=(0,cr.ensureSuccess)(await this.dataverse.get(n),this.dataverse.apiUrl(n)).body,a=(0,Kp.decodeCode)(o?.category);if(Number.isNaN(a))throw new Z.SdkError(Uv,`Workflow '${r}' answered without a readable category, so its kind cannot be told.`);if(t.workflowCategory=a,a===Xoe)return"businessRule";if(a===Zoe){let s=(0,Kp.decodeCode)(o?.businessprocesstype);if(Number.isNaN(s))throw new Z.SdkError(Uv,`Workflow '${r}' (category 4) answered without a readable businessprocesstype, so whether it is a business process flow or a task flow cannot be told.`);return s===0?"bpf":void 0}}requireRegistration(t,r){let n=this.registrations.get(t);if(!n)throw new Z.NotImplementedError(r,`no adapter registered for artifact type '${t}'`);return n}};dr.MakerSdk=Qp;function aae(e){return new Qp(e)}dr.createMakerSdk=aae;function Po(e){return e instanceof Error?e:new Error(String(e))}function rM(e,t){let r=Object.keys(e??{}),n=Object.keys(t??{});return r.length===n.length&&r.every(i=>Object.prototype.hasOwnProperty.call(t??{},i))}function nM(e){return Object.values(e??{}).every(cr.isVersionToken)}function sae(e,t){return rM(e,t)&&nM(e)&&Object.keys(e??{}).every(r=>t?.[r]===e?.[r])}function QF(e){return`createRecovery 'adoptExact' did not adopt it: ${e}.`}function Bv(e,t,r){return`Cannot create ${e} '${t}': a record already exists at that id${r?` (${r})`:""}, so an earlier push of this artifact committed before its local version metadata was saved. No duplicate was created. Run fetchArtifact('${e}', '${t}', { overwrite: true }) to adopt the existing record's identity, etag and snapshot \u2014 the overwrite is required, because this local copy has never been pushed, so a plain fetch keeps it and adopts nothing; it REPLACES the local copy, so keep any outstanding local changes aside first \u2014 then re-apply them and push again: a conditional update, provided the adopted record is complete. If the earlier push committed only PART of a multi-row artifact (e.g. an app's appmodule without its sitemap), that update refuses, naming what is missing and how to remove the partial record. This is not done automatically because the only recovery available here would be an UNCONDITIONAL overwrite, which would destroy any edit made to the record in the meantime.`}function lae(e,t,r){let n=e.localizedDisplayName;return n?.[t]||(r===void 0?void 0:n?.[r])||e.displayName}function ji(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function XF(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function ZF(e){e.length===0||!e.every(t=>ji(t)&&typeof t.order=="number")||e.forEach((t,r)=>{t.order=r})}function uae(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=>ji(i)&&i.id===t.before);return n<0?e.length:n}let r=e.findIndex(n=>ji(n)&&n.id===t.after);return r<0?e.length:r+1}});var oM=v(Xp=>{"use strict";Object.defineProperty(Xp,"__esModule",{value:!0});Xp.ARTIFACT_TYPES=void 0;Xp.ARTIFACT_TYPES=["form","view","businessRule","app","command","chart","dashboard","genPage","bpf"]});var sM=v(aM=>{"use strict";Object.defineProperty(aM,"__esModule",{value:!0})});var uM=v(lM=>{"use strict";Object.defineProperty(lM,"__esModule",{value:!0})});var dM=v(cM=>{"use strict";Object.defineProperty(cM,"__esModule",{value:!0})});var pM=v(fM=>{"use strict";Object.defineProperty(fM,"__esModule",{value:!0})});var hM=v(mM=>{"use strict";Object.defineProperty(mM,"__esModule",{value:!0})});var yM=v(gM=>{"use strict";Object.defineProperty(gM,"__esModule",{value:!0})});var vM=v(bM=>{"use strict";Object.defineProperty(bM,"__esModule",{value:!0})});var CM=v(wM=>{"use strict";Object.defineProperty(wM,"__esModule",{value:!0})});var AM=v(EM=>{"use strict";Object.defineProperty(EM,"__esModule",{value:!0})});var NM=v(SM=>{"use strict";Object.defineProperty(SM,"__esModule",{value:!0})});var TM=v(_M=>{"use strict";Object.defineProperty(_M,"__esModule",{value:!0})});var IM=v(DM=>{"use strict";Object.defineProperty(DM,"__esModule",{value:!0})});var PM=v(OM=>{"use strict";Object.defineProperty(OM,"__esModule",{value:!0})});var LM=v(RM=>{"use strict";Object.defineProperty(RM,"__esModule",{value:!0})});var xM=v(kM=>{"use strict";Object.defineProperty(kM,"__esModule",{value:!0})});var FM=v($M=>{"use strict";Object.defineProperty($M,"__esModule",{value:!0})});var UM=v(MM=>{"use strict";Object.defineProperty(MM,"__esModule",{value:!0})});var qM=v(BM=>{"use strict";Object.defineProperty(BM,"__esModule",{value:!0})});var GM=v(VM=>{"use strict";Object.defineProperty(VM,"__esModule",{value:!0})});var zM=v(WM=>{"use strict";Object.defineProperty(WM,"__esModule",{value:!0})});var HM=v(jM=>{"use strict";Object.defineProperty(jM,"__esModule",{value:!0})});var JM=v(ce=>{"use strict";var cae=ce&&ce.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),qe=ce&&ce.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&cae(t,e,r)};Object.defineProperty(ce,"__esModule",{value:!0});ce.projectConnectorOperationSchema=ce.projectConnectorOperations=ce.createMakerSdk=void 0;var dae=iM();Object.defineProperty(ce,"createMakerSdk",{enumerable:!0,get:function(){return dae.createMakerSdk}});qe(oM(),ce);qe(sM(),ce);qe(uM(),ce);qe(dM(),ce);qe(pM(),ce);qe(hM(),ce);qe(yM(),ce);qe(vM(),ce);qe(CM(),ce);qe(AM(),ce);qe(NM(),ce);qe(TM(),ce);qe(IM(),ce);qe(PM(),ce);qe(LM(),ce);qe(Pd(),ce);qe(xM(),ce);qe(FM(),ce);qe(UM(),ce);qe(qM(),ce);qe(GM(),ce);qe(zM(),ce);qe(HM(),ce);qe(Q(),ce);var KM=Al();Object.defineProperty(ce,"projectConnectorOperations",{enumerable:!0,get:function(){return KM.projectConnectorOperations}});Object.defineProperty(ce,"projectConnectorOperationSchema",{enumerable:!0,get:function(){return KM.projectConnectorOperationSchema}})});var Vv=v(ci=>{"use strict";var fae=ci&&ci.__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]})),pae=ci&&ci.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),XM=ci&&ci.__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)&&fae(t,e,r);return pae(t,e),t};Object.defineProperty(ci,"__esModule",{value:!0});ci.NodeFileSystemStorage=void 0;var mt=XM(require("fs")),Qt=XM(require("path")),YM=Q(),QM=Tm();async function ZM(e){let t;try{t=await mt.promises.lstat(e)}catch{return}if(t.isSymbolicLink()){try{await mt.promises.unlink(e)}catch{await mt.promises.rmdir(e)}return}if(!t.isDirectory()){await mt.promises.unlink(e);return}for(let r of await mt.promises.readdir(e))await ZM(Qt.join(e,r));await mt.promises.rmdir(e)}var qv=class{constructor(t){this.root=t}getRoot(){return this.root}pathFor(t,r=!0){return this.assertWithinRoot(Qt.join(this.root,...t),r)}realPathThroughNearestAncestor(t){let r=t,n=[];for(;!mt.existsSync(r);){n.unshift(Qt.basename(r));let i=Qt.dirname(r);if(i===r)return Qt.resolve(t);r=i}return Qt.resolve(mt.realpathSync(r),...n)}assertWithinRoot(t,r){let n=Qt.resolve(this.root),i=Qt.resolve(t);if(i!==n&&!i.startsWith(n+Qt.sep))throw new YM.PathTraversalError(t,this.root);let o=this.realPathThroughNearestAncestor(n),a=r?this.realPathThroughNearestAncestor(i):Qt.resolve(this.realPathThroughNearestAncestor(Qt.dirname(i)),Qt.basename(i));if(a!==o&&!a.startsWith(o+Qt.sep))throw new YM.PathTraversalError(t,this.root);return i}async readText(t){let r=this.pathFor(t);if(!mt.existsSync(r))return null;try{return await(0,QM.retryTransientIoAsync)(()=>mt.promises.readFile(r,"utf8"))}catch(n){if(n.code==="ENOENT")return null;throw n}}async writeTextAtomic(t,r){let n=this.pathFor(t),i=Qt.dirname(n);await mt.promises.mkdir(i,{recursive:!0});let o=Qt.join(i,`.${Qt.basename(n)}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);try{await mt.promises.writeFile(o,r,"utf8"),await(0,QM.retryTransientIoAsync)(()=>mt.promises.rename(o,n))}catch(a){try{mt.existsSync(o)&&await mt.promises.unlink(o)}catch{}throw a}}async deleteFile(t){let r=this.pathFor(t);mt.existsSync(r)&&await mt.promises.unlink(r)}async deleteByPrefix(t){await ZM(this.pathFor(t,!1))}async ensureContainer(t){await mt.promises.mkdir(this.pathFor(t),{recursive:!0})}async exists(t){return mt.existsSync(this.pathFor(t))}};ci.NodeFileSystemStorage=qv});var eU=v(Lr=>{"use strict";var mae=Lr&&Lr.__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]})),hae=Lr&&Lr.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),gae=Lr&&Lr.__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)&&mae(t,e,r);return hae(t,e),t};Object.defineProperty(Lr,"__esModule",{value:!0});Lr.loadNodeTypeScript=Lr.createNodeWorkspaceStorage=Lr.NodeFileSystemStorage=void 0;var yae=Vv(),bae=Vv();Object.defineProperty(Lr,"NodeFileSystemStorage",{enumerable:!0,get:function(){return bae.NodeFileSystemStorage}});function vae(e){return new yae.NodeFileSystemStorage(e)}Lr.createNodeWorkspaceStorage=vae;async function wae(){return await Promise.resolve().then(()=>gae(require("typescript")))}Lr.loadNodeTypeScript=wae});var Hi={};module.exports=kr(Hi);Ki(Hi,we(JM()),module.exports);Ki(Hi,we(eU()),module.exports);+`),a=e.apiUrl("/$batch"),s=i.map((m,p)=>String(p+1)),l;try{l=await(0,ge.resendWhile)(m=>Zz(m,s),()=>e.postBatch(o,r),ge.DEADLOCK_BACKOFF_MS)}catch(m){return{kind:"unknown",error:m}}let u=FT(l,a);if(u.kind!=="deleted")return u;let c=`app '${t[0].path}'`;if(typeof l.body!="string"||l.body.length===0)return{kind:"unknown",error:new _e.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`)};let d=(0,PT.parseChangeSetStatuses)(l.body,s);if(d===void 0)return{kind:"unknown",error:new _e.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`)};let f=d.find(m=>m<200||m>=300);return f!==void 0?{kind:"refused",error:new _e.ConnectionError(a,f,`atomic delete of ${c} was rolled back: the change set reported HTTP ${f}`)}:d.length!==i.length?{kind:"unknown",error:new _e.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response reported ${d.length} operation result(s), expected exactly ${i.length}`)}:{kind:"deleted"}}async function vf(e,t){try{let r=await e.get(`/sitemaps(${t})?$select=sitemapid`);return r.status<200||r.status>=300?null:(0,ge.readEtag)(r)}catch{return null}}async function TT(e,t){let r=`/appmodules(${t})?$select=appmoduleid`,n=await e.get(r);if(n.status!==404)return(0,ge.ensureSuccess)(n,e.apiUrl(r)),(0,ge.readEtag)(n)}async function C0(e,t,r,n){if(!n)return null;let i=await vf(e,t);if(!i)return null;try{let o=await e.get(Cf(t,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"));if(o.status<200||o.status>=300)return null;let a=_u(o);return!a||!Ef(a.sitemapid,t)||a.sitemapnameunique!==n||a.sitemapxml!==r.sitemapxml||a.sitemapname!==r.sitemapname?null:i}catch{return null}}function UT(e){return e>=400&&e<500&&e!==408&&e!==429}function DT(e,t,r){if(!e)throw new _e.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 BT(e,t,r){let n=`/appmodules(${t})`,i=r.draft?void 0:DT(r.appEtag,t,"app");if(!r.sitemapId){if(r.draft){(0,ge.ensureSuccess)(await(0,ge.resendAppSearchIndexRace)(()=>e.delete(n)),e.apiUrl(n));return}await ej(e,n,i);return}if(!e.supportsAtomicBatch)throw new _e.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 Xz(e,[{path:n,etag:i},{path:`/sitemaps(${r.sitemapId})`,etag:DT(r.sitemapEtag,t,"sitemap")}])}async function ej(e,t,r){(0,ge.ensureSuccess)(await(0,ge.resendAppSearchIndexRace)(()=>e.delete(t,{headers:{"If-Match":r}})),e.apiUrl(t))}async function IT(e,t){if(!/GenPageId/i.test(t))return;let r;try{r=[...new Set((0,Rz.collectGenPageIds)(t))]}catch(i){throw new _e.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 (${Gi(i)}).`)}if(r.length===0)return;let n=await(0,Lz.findMissingGenPages)(e,r,"sitemap generative-page preflight");if(n.length>0)throw new _e.SdkError("SITEMAP_TARGET_NOT_FOUND",`Refusing to push the app: its sitemap navigates to generative page(s) ${n.map(i=>`'${i}'`).join(", ")} that do not exist in this environment. Push the page before the app that links to it.`)}function tj(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")}async function OT(e,t,r){var n;let i=(0,Ae.normalizeGuid)(t,"id"),o=r==="tokens-first",a=o?await TT(e,i):null,s=S0(A0,i),l=(0,ge.ensureSuccess)(await e.get(s),e.apiUrl(s)),u=(n=_u(l))!==null&&n!==void 0?n:{};if(!u.appmoduleid)throw new _e.SdkError("APP_NOT_FOUND",`App '${i}' was not found (checked the unpublished-aware projection, which includes drafts).`);let c=await RT(e,u.uniquename),d=c?(0,Ae.normalizeGuid)(c,"sitemapId"):void 0,f=null;if(d){o&&(f=await vf(e,d));let p=Cf(d,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"),h=(0,ge.ensureSuccess)(await e.get(p),e.apiUrl(p)),g=_u(h),b=w=>{throw new _e.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': its sitemap '${d}' was located by unique name, but ${w}, so the sitemap cannot be read. Persisting the app without it would misreport it as having no sitemap, or write an empty one over its navigation. Retry.`)};if(!g)return b("the by-id read returned no row");if(g.sitemapnameunique!==u.uniquename)throw new _e.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': sitemap '${d}' now carries sitemapnameunique '${String(g.sitemapnameunique)}', not '${String(u.uniquename)}', so it is no longer this app's sitemap. Retry.`);if(!Ef(g.sitemapid,d))return b(`the by-id read returned a row carrying sitemapid '${String(g.sitemapid)}'`);if(typeof g.sitemapxml!="string")return b("the by-id read returned no sitemapxml");u.$sitemap=g,o||(f=await vf(e,d))}o||(a=await TT(e,i));let m=a??Fz(u);return{raw:u,etag:f,...u.appmoduleid?{siblingEtags:{[(0,Ae.normalizeGuid)(u.appmoduleid,"appmoduleid")]:m}}:{}}}li.appApi={get(e,t){return OT(e,t,"tokens-first")},readContentThenToken(e,t){return OT(e,t,"content-first")},async list(e,t){let r=S0(A0);return(await(0,$s.collectPages)(e,r,"listArtifacts('app')")).map(i=>{var o,a;return{type:"app",id:(o=i.appmoduleid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",isDirty:!1}})},async create(e,t,r){let n=t;await IT(e,n.sitemapxml);let i=await ST(e,n,n.appModuleId),o=n.iconWebResourceId?void 0:await Uz(e),a=n.iconWebResourceId||o?.id;if(!a)throw new _e.SdkError("APP_ICON_UNRESOLVED",`Cannot create app '${n.appModuleName}': its icon (\`appmodule.webresourceid\`) is a REQUIRED attribute and this environment has no image web resource to use. Pass \`iconWebResourceId\` explicitly, or add an image (PNG/JPG/GIF/ICO/SVG) web resource to the environment.`);let s=null;o?.managed&&(s=`No unmanaged image web resource was available, so the app icon resolved to a MANAGED one (${o.id}). That creates a cross-solution dependency which can fail to import into an environment without the owning managed solution. Pass \`iconWebResourceId\` with an in-solution image to avoid it.`);let l=n.appModuleUniqueName||Mz(n.appModuleId),u={name:n.appModuleName,uniquename:l,clienttype:4,formfactor:1,navigationtype:0};n.appModuleDescription&&(u.description=n.appModuleDescription),n.appModuleAiDescription&&(u.aiappdescription=n.appModuleAiDescription),a&&(u.webresourceid=a);let c="/appmodules",d=(0,ge.ensureSuccess)(await(0,ge.resendDeadlockVictim)(()=>e.post(c,(0,ge.withClientMintedId)(u,"appmoduleid",r))),e.apiUrl(c)),f=(0,ge.resolveCreatedId)(d,"appmoduleid","app module",r),m=null,p=null,h=[];s&&h.push(s);let g={kind:"notRequested"},b=n.sitemapId?(0,Ae.normalizeGuid)(n.sitemapId,"sitemapId"):(0,E0.newId)(),w=!1,C={sitemapxml:n.sitemapxml,sitemapname:n.sitemapname};try{let O="/sitemaps",L=(0,ge.echoWrite)("sitemapid"),I=await e.post(`${O}${L.query}`,{sitemapid:b,sitemapnameunique:l,...C},L.options);w=UT(I.status);let D=(0,ge.ensureSuccess)(I,e.apiUrl(O));p=(0,ge.readEtag)(D),m=p??await C0(e,b,C,l);let P=await ET(e,n,i);h.push(...P.warnings);let x=P.components;x.unshift({"@odata.type":"Microsoft.Dynamics.CRM.sitemap",sitemapid:b}),await NT(e,f,x);let K=bf(e,f);await _T(e,f,P.tables,K),i&&await zz(e,f,i,K);let Le=await Bz(e,f);Le&&h.push(Le),n.appSettings&&Object.keys(n.appSettings).length>0&&h.push(...await(0,kz.applyAppSettings)(e,f,n.appSettings)),n.published!==!1&&(await(0,bT.publishAppModule)(e,f),g={kind:"submitted"})}catch(O){let L=await Hz(e,f,{sitemapId:b,sitemapNameUnique:l,serverRefusedSitemap:w,sitemapWriteToken:p});throw(0,$z.failedAfterPrimaryWrite)(Kz(O,L,{appId:f,sitemapId:b,uniqueName:l}))}let S=null;if(g.kind==="submitted")try{let O=await e.get(`/appmodules(${f})?$select=appmoduleid`);O.status>=200&&O.status<300&&(S=(0,ge.readEtag)(O))}catch{}return{id:f,etag:m,serverIdentity:{sitemapId:b},siblingEtags:{[f]:S},publish:g,...h.length>0?{warnings:h}:{}}},async update(e,t,r,n,i,o){var a,s,l,u,c,d,f,m,p;let h=r,g=(0,Ae.normalizeGuid)(t,"id");if(await IT(e,h.sitemapxml),!h.sitemapId)throw new _e.ValidationError("app",g,[{pointer:"/sitemapId",rule:"app-sitemap-identity-missing",message:`missing sitemap identity \u2014 re-fetch the app before pushing edits: fetchArtifact('app', '${g}', { overwrite: true }) (it REPLACES the local copy \u2014 keep outstanding changes aside), push that refreshed copy UNTOUCHED, then re-apply your changes and push again. If the untouched push is refused with this same rule, the app has NO sitemap on the server \u2014 an earlier create committed its appmodule but not its sitemap \u2014 and it can be neither updated, published nor removed with deleteRemoteArtifact (an unpublished app reads back 404). Only for an app you have confirmed is your own abandoned partial create, with nothing else provisioning it: remove its appmodule row with deleteRecord('appmodule', '${g}'), clear the local copy with deleteArtifact('app', '${g}'), then author the app again and push.`}]);let b=(0,Ae.normalizeGuid)(h.sitemapId,"sitemapId");if(!(0,ge.isVersionToken)(n))throw new _e.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${g}': ${n?`the concurrency token held for its sitemap row ('${n}') is not a version`:"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 ST(e,h,g),C=await ET(e,h,w),S=`/appmodules(${g})`,O=(a=o?.[g])!==null&&a!==void 0?a:null,L=!0,I;try{let Bt=S0(A0,g),Ni=await e.get(Bt);if(Ni.status>=200&&Ni.status<300){let Ha=(s=_u(Ni))!==null&&s!==void 0?s:{};I=typeof Ha.uniquename=="string"&&Ha.uniquename?Ha.uniquename:void 0,L=String((l=Ha.name)!==null&&l!==void 0?l:"")!==String((u=h.appModuleName)!==null&&u!==void 0?u:"")||String((c=Ha.description)!==null&&c!==void 0?c:"")!==String((d=h.appModuleDescription)!==null&&d!==void 0?d:"")||h.appModuleAiDescription!==void 0&&String((f=Ha.aiappdescription)!==null&&f!==void 0?f:"")!==String(h.appModuleAiDescription)}}catch{}let D=O;if(L){if(!(0,ge.isVersionToken)(O))throw new _e.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${g}': ${O?`the concurrency token held for its appmodule header ('${O}') is not a version`:"no concurrency token is held for its appmodule header"}, so its header edit could not be made conditional and would silently overwrite a concurrent edit. Nothing was modified. Re-fetch the app (fetchArtifact('app', '${g}', { overwrite: true })) and re-apply the change.`);let Bt=(0,ge.echoWrite)("appmoduleid",{"If-Match":O}),Ni=await e.patch(`${S}${Bt.query}`,{name:h.appModuleName,description:h.appModuleDescription,...h.appModuleAiDescription!==void 0?{aiappdescription:h.appModuleAiDescription}:{}},Bt.options);if(tj(Ni))throw new _e.SdkError("APP_DRAFT_HEADER_NOT_WRITABLE",`Refusing to update app '${g}': its appmodule row is UNPUBLISHED, and Dataverse cannot resolve version numbers for a draft appmodule (HTTP 400). A draft header cannot be PATCHed at all \u2014 a plain retry fails too, as an upsert-create ("webresourceid cannot be NULL"). Publish the app first, then push the header edit. Nothing was modified by this call.`);(0,ge.ensureSuccess)(Ni,e.apiUrl(S)),D=(0,ge.readEtag)(Ni)}let P={sitemapxml:h.sitemapxml,sitemapname:h.sitemapname},x=I||h.appModuleUniqueName||void 0,K=(0,ge.echoWrite)("sitemapid",{"If-Match":n}),Le=`/sitemaps(${b})`,lr;try{lr=(0,ge.ensureSuccess)(await e.patch(`${Le}${K.query}`,{...P},K.options),e.apiUrl(Le))}catch(Bt){throw(0,_e.withPartialTokens)(Bt,{siblingEtags:{[g]:D}})}let Ge=[...C.warnings],Ut=bf(e,g);try{await NT(e,g,C.components),await _T(e,g,C.tables,Ut)}catch(Bt){Ge.push(`App '${g}': one or more components were not pinned (${Bt.message}). Navigation may reference content not included in the app; re-push to retry.`)}w&&Ge.push(...await jz(e,g,w,Ut));let de={kind:"notRequested"},Ke=D,ur=(m=(0,ge.readEtag)(lr))!==null&&m!==void 0?m:await C0(e,b,P,x);if(h.published===!0){try{await(0,bT.publishAppModule)(e,g),de={kind:"submitted"}}catch(Bt){de={kind:"failed",error:Bt},Ge.push(`App '${g}': saved, but publishing failed (${Bt.message}). The app remains unpublished; re-push to retry.`)}if(de.kind==="submitted"){Ke=null;try{let Bt=await e.get(`/appmodules(${g})?$select=appmoduleid`);Bt.status>=200&&Bt.status<300&&(Ke=(0,ge.readEtag)(Bt)),ur=(p=await C0(e,b,P,x))!==null&&p!==void 0?p:ur}catch{}}}return{id:g,etag:ur,siblingEtags:{[g]:Ke},publish:de,...Ge.length>0?{warnings:Ge}:{}}},async delete(e,t){let r=(0,Ae.normalizeGuid)(t,"id");await BT(e,r,await xT(e,r))}}});var T0=v(xs=>{"use strict";Object.defineProperty(xs,"__esModule",{value:!0});xs.deleteAppCascade=xs.collectGenPageIds=void 0;var rj=Af(),nj=Q(),D0=oe(),ij=ys();function qT(e){let t=[],r=s=>l=>t.push(`${s}: ${l}`),n=new ij.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml"),i=n?.documentElement;if(!i||t.length>0)throw new nj.InvalidArgumentError(`The app sitemap xml could not be parsed cleanly, so its generative-page children cannot be determined${t.length>0?` (${t[0]})`:""}`);let o=[],a=s=>{if(s.nodeName==="SubArea"){let u=s.getAttribute("GenPageId");u&&o.push((0,D0.normalizeGuid)(u,"GenPageId"))}let l=s.childNodes;for(let u=0;u<l.length;u+=1){let c=l[u];c.nodeType===1&&a(c)}};return a(i),o}xs.collectGenPageIds=qT;async function oj(e,t,r){let n=(0,D0.normalizeGuid)(t,"appModuleId");(0,D0.normalizeGuid)(r,"appModuleIdUnique");let i=[],o=[],a=[];await(0,rj.deleteAppResolvingOnce)(e,n,l=>{l!==void 0&&a.push(...qT(l))}),i.push({type:"app",id:n});let s=[...new Set(a)].map(l=>({type:"genPage",id:l}));return{success:o.length===0,deleted:i,failures:o,retained:s}}xs.deleteAppCascade=oj});var VT={};nn(VT,{Guid:()=>U});var U,vt=k(()=>{"use strict";U=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 q,rr=k(()=>{"use strict";dt();q=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(!R.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 R.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 GT={};nn(GT,{ScriptUtilities:()=>R});var R,dt=k(()=>{"use strict";vt();rr();R=class e{static IsNullOrUndefined(t){return t==null||t===void 0}static IsMacMachine(){return navigator.platform.indexOf("Mac")!==-1}static IsNullOrEmptyGuid(t){return q.IsNullOrEmpty(t.ToString())?!0:U.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:q.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 Sf,Nf,ha,_f,I0,Tf,O0=k(()=>{"use strict";(function(e){e[e.FormElementNodeChange=0]="FormElementNodeChange",e[e.FormElementAttributeChange=1]="FormElementAttributeChange"})(Sf||(Sf={}));Nf=class{type;targetNode;constructor(t,r){this.type=t,this.targetNode=r}},ha=class extends Nf{key;oldValue;newValue;constructor(t,r,n,i){super(Sf.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)}},_f=class extends Nf{property;oldValue;newValue;constructor(t,r,n,i){super(Sf.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)}},I0=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()})}},Tf=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 I0(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 WT={};nn(WT,{ChartGridMode:()=>hn,ColumnLayoutWidths:()=>cj,ComponentCategory:()=>If,ComponentType:()=>P0,ControlLayoutTypes:()=>M0,DisplayConditionsInfo:()=>lj,ElementNames:()=>E,ElementProperties:()=>y,ElementType:()=>L0,EntityAttributeProperty:()=>k0,EventType:()=>Tu,FormActivationState:()=>F0,FormCanvasServiceScope:()=>Ej,FormDesignerSideBarTab:()=>R0,FormPresentation:()=>$0,FormState:()=>Df,FormType:()=>wt,HeaderDensityType:()=>Do,LookUpTable:()=>ui,MORE_TAB_PREFIX:()=>fj,NavBarChildElementType:()=>x0,PREVIEW_ID_HEADER_FLYOUT:()=>gj,PREVIEW_ID_HEADER_OVERFLOW_BUTTON:()=>bj,PREVIEW_ID_NAVIGATION_AREA:()=>mj,PREVIEW_ID_QUICKCREATE_ROOT:()=>wj,PREVIEW_ID_TAB:()=>vj,PREVIEW_ID_TAB_LIST:()=>yj,PREVIEW_ID_TAB_PANEL:()=>hj,PropertyModelKeys:()=>q0,PropertyModelSectionKeys:()=>dj,RELATED_TAB_ID:()=>V0,RELATED_TAB_PREFIX:()=>pj,SectionDefaultProperties:()=>uj,SectionLayoutTypes:()=>je,TabContentType:()=>U0,TabDefaultProperties:()=>Io,TabLayoutTypes:()=>ze,TelemetryPropertyNames:()=>Cj,UnboundControlPropertyKeys:()=>B0,compositeAddressFields:()=>sj,compositeFieldNames:()=>Zr,compositeFields:()=>aj});var wt,P0,R0,E,y,L0,Zr,aj,sj,k0,ui,Df,Do,$0,lj,x0,F0,ze,uj,Io,je,M0,U0,cj,B0,q0,dj,Tu,hn,V0,fj,pj,mj,hj,gj,yj,bj,vj,wj,Cj,If,Ej,le=k(()=>{"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"})(wt||(wt={}));(function(e){e[e.Form=0]="Form",e[e.Dialog=1]="Dialog"})(P0||(P0={}));(function(e){e[e.Components=0]="Components",e[e.Properties=1]="Properties",e[e.Relationship=2]="Relationship",e[e.BusinessRules=3]="BusinessRules"})(R0||(R0={}));(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"})(E||(E={}));y={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"})(L0||(L0={}));Zr={fullname:"fullname",yomifullname:"yomifullname",address1_composite:"address1_composite",address2_composite:"address2_composite",address3_composite:"address3_composite",billto:"billto_composite",shipto:"shipto_composite"},aj=[Zr.fullname,Zr.yomifullname,Zr.address1_composite,Zr.address2_composite,Zr.address3_composite,Zr.billto,Zr.shipto],sj=[Zr.address1_composite,Zr.address2_composite,Zr.address3_composite,Zr.billto,Zr.shipto];(function(e){e[e.IsValidForForm=0]="IsValidForForm",e[e.IsValidForCreate=1]="IsValidForCreate"})(k0||(k0={}));(function(e){e[e.DependencyFieldTable=0]="DependencyFieldTable",e[e.LockedFieldTable=1]="LockedFieldTable"})(ui||(ui={}));(function(e){e[e.Published=0]="Published",e[e.Draft=1]="Draft",e[e.New=2]="New",e[e.SaveAs=3]="SaveAs"})(Df||(Df={}));(function(e){e.Low="Low",e.HighReadOnlyValues="HighReadOnlyValues",e.HighWithControls="HighWithControls"})(Do||(Do={}));(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})($0||($0={}));lj={TopOrderFormId:"topOrderFormId",NextDisplayOrder:"nextDisplayOrder"};(function(e){e[e.NavBarRelationShipItem=0]="NavBarRelationShipItem",e[e.NavBarItem=1]="NavBarItem"})(x0||(x0={}));(function(e){e[e.InActive=0]="InActive",e[e.Active=1]="Active"})(F0||(F0={}));(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"})(ze||(ze={}));uj={ShowLabel:"false",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_"},Io={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"})(je||(je={}));(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"})(M0||(M0={}));(function(e){e.cardSections="cardSections",e.singleComponent="singleComponent",e.default="default",e.expandAvailableSpace="expandAvailableSpace"})(U0||(U0={}));cj={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"})(B0||(B0={}));(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"})(q0||(q0={}));dj={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"})(Tu||(Tu={}));(function(e){e.All="All",e.Chart="Chart",e.Grid="Grid"})(hn||(hn={}));V0="tab_related3b554255-7717-4d17-bb7f-9936fb1e75ca",fj="more_tab_",pj="related_tab_",mj="preview_id_navigation_area",hj="tab-section",gj="headerFieldsFlyout",yj="tablist",bj="header_overflowButton",vj="tab",wj="quickCreateRoot",Cj={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"})(If||(If={}));Ej="CellCanvasServiceScope"});var zT={};nn(zT,{Attribute:()=>Of,FormElementNode:()=>re});var Of,re,kt=k(()=>{"use strict";dt();rr();O0();le();vt();Of=class{key;value;constructor(t,r){this.key=t,this.value=r}},re=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-${U.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(E.form);r&&r.raiseMetadataChange(t)}trackPropertyAddition(t,r){this.trackPropertyCollectionChange(()=>{this.properties.push(new Of(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 ha(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 ha(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 ha(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 _f(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 ha(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){R.IsNullOrUndefined(t)||(t.trackParentNodeChange(()=>{t.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(r,0,t)}))}moveChild(t,r){let n=this.childrenNodes.indexOf(t);if(n<0)return!1;let i=Math.min(Math.max(0,n+r),this.childrenNodes.length-1);return n!==i&&this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(i,0,this.childrenNodes.splice(n,1)[0])}),!0}getChildren(t){let r=[];for(let n of this.childrenNodes)n.nodeName===t&&r.push(n);return r}getFirstChild(t){for(let r of this.childrenNodes)if(r.nodeName===t)return r;return null}getAllGrandChildren(t){let r=this.getChildren(t),n=null;return r.length===0?new Array:(n=r[0],n.childrenNodes)}deleteChild(t){if(R.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:q.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=R.IsNullOrUndefined(r)?this.childrenNodes.length:r,this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(t,r)})}deleteGrandChildren(t,r,n){this.getChildren(t)[0].deleteChildren(r,n)}addGrandChild(t,r){let n=this.getChildren(t),i=null;n.length===0?(i=new e(t,this),this.addChild(i)):i=n[0],i.addChild(r)}addGrandChildAtIndex(t,r,n){let i=this.getChildren(t),o=null;i.length===0?(o=new e(t,this),this.addChild(o)):o=i[0],o.insertChildAtIndex(r,n)}GetPropertyByParameter(t){return this.getProperty(t)}getSemanticParent(){switch(this.getNodeName()){case E.formCell:let t=this.getAncestor(E.formSection);return t||(t=this.getAncestor(E.formHeader),t)||(t=this.getAncestor(E.formFooter),t)?t:null;case E.formSection:return this.getAncestor(E.formTab);case E.formTab:return this.getAncestor(E.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(E.form);return t?t.changeTracker():null}}});var jT={};nn(jT,{ControlClassId:()=>N,ControlNamePrefixes:()=>Pf,getControlDisplayNames:()=>Aj});function Aj(e){return{[N.AccessPrivilegeControl]:e("controls.controlNames.accessPrivilege"),[N.AccessTeamTablePickerControl]:e("controls.controlNames.accessTeamTablePicker"),[N.ACIControl]:e("controls.controlNames.aci"),[N.ActivitiesContainerControl]:e("controls.controlNames.activitiesContainer"),[N.ActivitiesWallControl]:e("controls.controlNames.activitiesWall"),[N.AppliedFiltersControl]:e("controls.controlNames.appliedFilters"),[N.ArticleContentControl]:e("controls.controlNames.articleContent"),[N.BooleanControl]:e("controls.controlNames.twoOption"),[N.ButtonControl]:e("controls.controlNames.button"),[N.CheckboxControl]:e("controls.controlNames.checkbox"),[N.CompositionLinkControl]:e("controls.controlNames.compositionLink"),[N.ConnectionControl]:e("controls.controlNames.connection"),[N.ConnectionRoleObjectTypeListControl]:e("controls.controlNames.connectionRoleObjectTypeList"),[N.CoverageChoiceControl]:e("controls.controlNames.coverageChoice"),[N.DashboardControl]:e("controls.controlNames.dashboard"),[N.DynamicPropertyListControl]:e("controls.controlNames.dynamicPropertyList"),[N.EditFilterControl]:e("controls.controlNames.editFilter"),[N.ErrorStatusControl]:e("controls.controlNames.errorStatus"),[N.GlobalFilterControl]:e("controls.controlNames.globalFilter"),[N.HiddenInputControl]:e("controls.controlNames.hiddenInput"),[N.KBViewerControl]:e("controls.controlNames.kbViewer"),[N.LabelControl]:e("controls.controlNames.label"),[N.MailMergeLanguagePickerControl]:e("controls.controlNames.mailMergeLanguagePicker"),[N.MapLinkControl]:e("controls.controlNames.mapLink"),[N.OrgInsightsControl]:e("controls.controlNames.orgInsights"),[N.ChoiceLookupControl]:e("controls.controlNames.choiceLookup"),[N.PowerBIControl]:e("controls.controlNames.powerBI"),[N.ProcessControl]:e("controls.controlNames.process"),[N.RelatedInformationControl]:e("controls.controlNames.relatedInformation"),[N.RelationshipRoleChoiceControl]:e("controls.controlNames.relationshipRoleChoice"),[N.ReportControl]:e("controls.controlNames.report"),[N.StreamsControl]:e("controls.controlNames.streams"),[N.WebResourceSilverlightControl]:e("controls.controlNames.webResourceSilverlight"),[N.CurrencyControl]:e("controls.controlNames.currency"),[N.DateTimeControl]:e("controls.controlNames.dateAndTime"),[N.DecimalControl]:e("controls.controlNames.decimal"),[N.DurationControl]:e("controls.controlNames.duration"),[N.EmailAddressControl]:e("controls.controlNames.email"),[N.FileControl]:e("controls.controlNames.file"),[N.FloatingNumberControl]:e("controls.controlNames.floatingNumber"),[N.IframeControl]:e("controls.controlNames.iframe"),[N.ImageControl]:e("controls.controlNames.image"),[N.LookupControl]:e("controls.controlNames.lookup"),[N.MapsControl]:e("controls.controlNames.maps"),[N.PhoneNumberControl]:e("controls.controlNames.phoneNumber"),[N.ChoiceControl]:e("controls.controlNames.choice"),[N.QuickViewControl]:e("controls.controlNames.quickView"),[N.QuickFormControl]:e("controls.controlNames.quickForm"),[N.CustomControl]:e("controls.controlNames.customControl"),[N.SearchWidgetControl]:e("controls.controlNames.searchWidget"),[N.SocialInsightsControl]:e("controls.controlNames.socialInsights"),[N.SubgridControl]:e("controls.controlNames.subgrid"),[N.TextAreaControl]:e("controls.controlNames.textArea"),[N.TextboxControl]:e("controls.controlNames.textBox"),[N.TickerControl]:e("controls.controlNames.ticker"),[N.UrlControl]:e("controls.controlNames.url"),[N.WebResourceHTMLControl]:e("controls.controlNames.webResourceHTML"),[N.WebResourceImageControl]:e("controls.controlNames.webResourceImage"),[N.IntegerControl]:e("controls.controlNames.integer"),[N.TimerControl]:e("controls.controlNames.timer"),[N.TimelineControl]:e("controls.controlNames.timeline"),[N.EmailBodyControl]:e("controls.controlNames.emailBody"),[N.PartyListControl]:e("controls.controlNames.partyList"),[N.TimezoneControl]:e("controls.controlNames.timezone"),[N.LanguageControl]:e("controls.controlNames.language"),[N.ChoiceStatusControl]:e("controls.controlNames.choiceStatus"),[N.ChoicesControl]:e("controls.controlNames.choices"),[N.RegardingControl]:e("controls.controlNames.regarding"),[N.EmailEngagementActionsControl]:e("controls.controlNames.emailEngagementActions"),[N.EmailRecipientActivityControl]:e("controls.controlNames.emailRecipientActivity"),[N.ReferencePanelSearchWidgetControl]:e("controls.controlNames.referencePanelSearchWidget"),[N.ReferencePanelQuickViewControl]:e("controls.controlNames.referencePanelQuickView"),[N.ReferencePanelSubgridControl]:e("controls.controlNames.referencePanelSubgrid"),[N.KBEditorControl]:e("controls.controlNames.KBEditor"),[N.LinkControl]:e("controls.controlNames.link")}}var N,Pf,ga=k(()=>{"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"})(N||(N={}));Pf={[N.WebResourceHTMLControl]:"WebResource",[N.WebResourceImageControl]:"WebResource",[N.IframeControl]:"IFRAME",[N.SearchWidgetControl]:"Search widget",[N.SubgridControl]:"Subgrid",[N.TimelineControl]:"Timeline",[N.QuickViewControl]:"QuickviewControl"}});var ya=v((Ade,KT)=>{var Du=new Proxy(function(){return Du},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Du},apply:function(){return Du},construct:function(){return{}}}),HT=function(){return Du};Object.setPrototypeOf(HT,Du);KT.exports=HT});var hr,Wi,JT,YT,Fs=k(()=>{"use strict";hr="cds-designer-models",Wi="FormCustomControl",JT="FormCell",YT="Form"});var ba,G0=k(()=>{"use strict";su();le();ba=class e{static lockedFieldCount=new dr;static dependencyFieldCount=new dr;static getNecessaryLookUpTable(t){switch(t){case ui.DependencyFieldTable:return e.dependencyFieldCount;case ui.LockedFieldTable:return e.lockedFieldCount}}static initCanvasLockedFieldLookUp(t){switch(t){case ui.DependencyFieldTable:e.dependencyFieldCount=new dr;case ui.LockedFieldTable:e.lockedFieldCount=new dr}}}});var Rf,QT=k(()=>{"use strict";vt();dt();le();kt();Rf=class extends re{constructor(t){super(E.controlDescription,t)}get forControl(){let t=this.getProperty(y.ForControl);return R.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t))}set forControl(t){this.setProperty(y.ForControl,`{${t.ToString()}}`)}get customControls(){return this.getChildren(E.customControl)}set customControls(t){this.deleteAllChildren();for(let r of t)this.addChild(r)}get DefaultControlClassId(){for(let t of this.customControls)if(!R.IsNullOrUndefined(t.id))return t.id;return null}get DefaultCustomControl(){for(let t of this.customControls)if(!R.IsNullOrUndefined(t.id))return t;return null}get DefaultCustomControls(){let t=[];for(let r of this.customControls)R.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}}});function zi(){return ci||(ci=window._makerConfig,ci&&window?.location?.search?.indexOf("useProductionConfig")>-1&&(ci={...ci,region:"prod",graphQLEndpoint:"https://graph.make.powerapps.com/"}),ci?.region==="prod"&&(ci={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/"}}},...ci}),ci||{aadClientId:"a8f7a65c-f5ba-4859-b2d6-df772c264e9d",location:"cus",region:"test",publicPath:"/",graphQLEndpoint:"https://graph.make.test.powerapps.com/"})}var ci,Lf=k(()=>{"use strict";});function XT(e,t,r){if(!e)return kf.has(e)||(window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoIsEmpty"}),kf.add("")),!1;if(e){if(e=e.toLowerCase(),kf.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}}),kf.add(e),!1}return!0}function Sj(e){return XT(e,W0,"Location dictionary")?W0[e.toLowerCase()]:"us"}function Nj(){let e=zi().location.toLowerCase();return XT(e,W0,"Current location dictionary")?e:"us"}var kf,W0,xde,ZT=k(()=>{"use strict";Lf();kf=new Set,W0={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"};xde=Sj(Nj())});var Y,Mde,eD=k(()=>{"use strict";Y={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"},Mde={[Y.USWest]:{geoName:"us",regionShortName:"wus"},[Y.USCentral]:{geoName:"us",regionShortName:"cus"},[Y.USEast]:{geoName:"us",regionShortName:"eus"},[Y.USEast2]:{geoName:"us",regionShortName:"eus2"},[Y.USWestCentral]:{geoName:"us",regionShortName:"wcus"},[Y.USWest2]:{geoName:"us",regionShortName:"wus2"},[Y.USSouthCentral]:{geoName:"br",regionShortName:"scus"},[Y.BrazilSouth]:{geoName:"br",regionShortName:"sbr"},[Y.UKSouth]:{geoName:"uk",regionShortName:"suk"},[Y.UKWest]:{geoName:"uk",regionShortName:"wuk"},[Y.JapanEast]:{geoName:"jp",regionShortName:"ejp"},[Y.JapanWest]:{geoName:"jp",regionShortName:"wjp"},[Y.IndiaCentral]:{geoName:"in",regionShortName:"cin"},[Y.IndiaSouth]:{geoName:"in",regionShortName:"sin"},[Y.ItalyNorth]:{geoName:"it",regionShortName:"nit"},[Y.GermanyWestCentral]:{geoName:"de",regionShortName:"wcde"},[Y.GermanyNorth]:{geoName:"de",regionShortName:"nde"},[Y.EuropeNorth]:{geoName:"eu",regionShortName:"neu"},[Y.EuropeWest]:{geoName:"eu",regionShortName:"weu"},[Y.AustraliaEast]:{geoName:"au",regionShortName:"eau"},[Y.AustraliaSouthEast]:{geoName:"au",regionShortName:"seau"},[Y.AsiaSouthEast]:{geoName:"as",regionShortName:"seas"},[Y.AsiaEast]:{geoName:"as",regionShortName:"eas"},[Y.CanadaCentral]:{geoName:"ca",regionShortName:"cca"},[Y.CanadaEast]:{geoName:"ca",regionShortName:"eca"},[Y.SouthAfricaNorth]:{geoName:"za",regionShortName:"nza"},[Y.SouthAfricaWest]:{geoName:"za",regionShortName:"wza"},[Y.FranceCentral]:{geoName:"fr",regionShortName:"cfr"},[Y.FranceSouth]:{geoName:"fr",regionShortName:"sfr"},[Y.UAENorth]:{geoName:"ae",regionShortName:"nae"},[Y.UAECentral]:{geoName:"ae",regionShortName:"cae"},[Y.SwedenCentral]:{geoName:"se",regionShortName:"cse"},[Y.SwitzerlandNorth]:{geoName:"ch",regionShortName:"nch"},[Y.SwitzerlandWest]:{geoName:"ch",regionShortName:"wch"},[Y.NorwayEast]:{geoName:"no",regionShortName:"eno"},[Y.NorwayWest]:{geoName:"no",regionShortName:"wno"},[Y.KoreaCentral]:{geoName:"kr",regionShortName:"ckr"},[Y.KoreaSouth]:{geoName:"kr",regionShortName:"skr"},[Y.SingaporeSouthEast]:{geoName:"sg",regionShortName:"seas"},[Y.PolandCentral]:{geoName:"pl",regionShortName:"cpl"},[Y.QatarCentral]:{geoName:"qa",regionShortName:"cqa"},[Y.NewZealandNorth]:{geoName:"nz",regionShortName:"nnz"},[Y.GovernmentUSTexas]:{geoName:"us",regionShortName:"ugtx"},[Y.GovernmentUSVirginia]:{geoName:"us",regionShortName:"ugva"},[Y.GovernmentUSDodCentral]:{regionShortName:"udc"},[Y.GovernmentUSDodEast]:{regionShortName:"ude"},[Y.ChinaEast]:{regionShortName:"cne"},[Y.ChinaEast2]:{regionShortName:"cne2"},[Y.ChinaEast3]:{regionShortName:"cne3"},[Y.ChinaNorth]:{regionShortName:"cnn"},[Y.ChinaNorth2]:{regionShortName:"cnn2"},[Y.ChinaNorth3]:{regionShortName:"cnn3"},[Y.UssecEast]:{geoName:"us",regionShortName:"erx"},[Y.UssecWest]:{geoName:"us",regionShortName:"wrx"},[Y.UsnatEast]:{geoName:"us",regionShortName:"eex"},[Y.UsnatWest]:{geoName:"us",regionShortName:"wex"}}});var tD=k(()=>{"use strict";Lf();});var Iu=k(()=>{"use strict";Lf();ZT();eD();tD();});function Ou(e,t){return rD?rD.isOverridden(e,t):{overridden:!1}}var rD,Pu=k(()=>{"use strict";});var z0=k(()=>{"use strict";Iu();Pu();});function _j(e,t){let{region:r}=zi();return()=>{let n=e.settings[t];if(n.allowOverrides){let s=Ou(e.packageName,t);if(s.overridden)return typeof s.value=="string"?Tj(s.value):s.value}let o=n.values,a=process.env.SETTINGS_FALLBACK_REGION?.[r];return o[r]!==void 0?o[r]:a&&o[a]!==void 0?o[a]:o.default}}function Tj(e){return isNaN(Number(e))?e==="true"?!0:e==="false"?!1:e:Number(e)}function Dj(e){let t=e.packageName;if($f.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=>H0(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=>!Ff(i))){let i=`error parsing settings config for package ${t}, setting ${r} has invalid region`;throw console.error(i),new Error(i)}})}function Ru(e){Dj(e);let t={};return Object.keys(e.settings).forEach(r=>{t[r]={enumerable:!0,get:_j(e,r)}}),$f.set(e.packageName,e),Object.defineProperties({},t)}function j0(e,t){return $f.has(e)?!!$f.get(e).settings[t]:!1}var $f,xf=k(()=>{"use strict";Iu();Pu();K0();Lu();$f=new Map});function nD(e,t){let{region:r}=zi();return()=>{let n=Ou(e.packageName,t);if(n.overridden)return n.value.toString()==="true";let i=e.features[t].enabledFor,o=process.env.SETTINGS_FALLBACK_REGION?.[r];return i[r]!==void 0?!!i[r]:o&&i[o]!==void 0?!!i[o]:!1}}function Ij(e){let t=e.packageName;if(Mf.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=>j0(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=>!Ff(i))){let i=`error parsing feature gates config for package ${t}, feature ${r} has invalid region`;throw console.error(i),new Error(i)}})}function J0(e){Ij(e);let t={};Object.keys(e.features).forEach(i=>{t[i]={enumerable:!0,configurable:!0,get:nD(e,i)}});let r={},n=new Set;return t.dangerouslySet={enumerable:!1,value:(i,o)=>{n.add(i),Object.defineProperty(r,i,{enumerable:!0,configurable:!0,value:o})}},t.dangerouslyReset={enumerable:!1,value:()=>{let i={};n.forEach(o=>{i[o.toString()]={enumerable:!0,configurable:!0,get:nD(e,o.toString())}}),Object.defineProperties(r,i),n.clear()}},Mf.set(e.packageName,e),Object.defineProperties(r,t)}function H0(e,t){return Mf.has(e)?!!Mf.get(e).features[t]:!1}var Mf,K0=k(()=>{"use strict";Iu();Lu();Pu();xf();Mf=new Map});var oD=v((ufe,iD)=>{"use strict";iD.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 lD=v(Y0=>{"use strict";var Oj=Object.prototype.hasOwnProperty,Pj;function aD(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch{return null}}function sD(e){try{return encodeURIComponent(e)}catch{return null}}function Rj(e){for(var t=/([^=?#&]+)=?([^&]*)/g,r={},n;n=t.exec(e);){var i=aD(n[1]),o=aD(n[2]);i===null||o===null||i in r||(r[i]=o)}return r}function Lj(e,t){t=t||"";var r=[],n,i;typeof t!="string"&&(t="?");for(i in e)if(Oj.call(e,i)){if(n=e[i],!n&&(n===null||n===Pj||isNaN(n))&&(n=""),i=sD(i),n=sD(n),i===null||n===null)continue;r.push(i+"="+n)}return r.length?t+r.join("&"):""}Y0.stringify=Lj;Y0.parse=Rj});var Z0=v((dfe,mD)=>{"use strict";var cD=oD(),Uf=lD(),dD=/[\n\r\t]/g,kj=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,$j=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,xj=/^[a-zA-Z]:/,Fj=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;function X0(e){return(e||"").toString().replace(Fj,"")}var Q0=[["#","hash"],["?","query"],function(t,r){return di(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]],uD={hash:1,query:1};function fD(e){var t;typeof window<"u"?t=window:typeof global<"u"?t=global:typeof self<"u"?t=self:t={};var r=t.location||{};e=e||r;var n={},i=typeof e,o;if(e.protocol==="blob:")n=new fi(unescape(e.pathname),{});else if(i==="string"){n=new fi(e,{});for(o in uD)delete n[o]}else if(i==="object"){for(o in e)o in uD||(n[o]=e[o]);n.slashes===void 0&&(n.slashes=kj.test(e.href))}return n}function di(e){return e==="file:"||e==="ftp:"||e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function pD(e,t){e=X0(e),e=e.replace(dD,""),t=t||{};var r=$j.exec(e),n=r[1]?r[1].toLowerCase():"",i=!!r[2],o=!!r[3],a=0,s;return i?o?(s=r[2]+r[3]+r[4],a=r[2].length+r[3].length):(s=r[2]+r[4],a=r[2].length):o?(s=r[3]+r[4],a=r[3].length):s=r[4],n==="file:"?a>=2&&(s=s.slice(2)):di(n)?s=r[4]:n?i&&(s=s.slice(2)):a>=2&&di(t.protocol)&&(s=r[4]),{protocol:n,slashes:i||di(n),slashesCount:a,rest:s}}function Mj(e,t){if(e==="")return t;for(var r=(t||"/").split("/").slice(0,-1).concat(e.split("/")),n=r.length,i=r[n-1],o=!1,a=0;n--;)r[n]==="."?r.splice(n,1):r[n]===".."?(r.splice(n,1),a++):a&&(n===0&&(o=!0),r.splice(n,1),a--);return o&&r.unshift(""),(i==="."||i==="..")&&r.push(""),r.join("/")}function fi(e,t,r){if(e=X0(e),e=e.replace(dD,""),!(this instanceof fi))return new fi(e,t,r);var n,i,o,a,s,l,u=Q0.slice(),c=typeof t,d=this,f=0;for(c!=="object"&&c!=="string"&&(r=t,t=null),r&&typeof r!="function"&&(r=Uf.parse),t=fD(t),i=pD(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||xj.test(e))||!i.slashes&&(i.protocol||i.slashesCount<2||!di(d.protocol)))&&(u[3]=[/(.*)/,"pathname"]);f<u.length;f++){if(a=u[f],typeof a=="function"){e=a(e,d);continue}o=a[0],l=a[1],o!==o?d[l]=e:typeof o=="string"?(s=o==="@"?e.lastIndexOf(o):e.indexOf(o),~s&&(typeof a[2]=="number"?(d[l]=e.slice(0,s),e=e.slice(s+a[2])):(d[l]=e.slice(s),e=e.slice(0,s)))):(s=o.exec(e))&&(d[l]=s[1],e=e.slice(0,s.index)),d[l]=d[l]||n&&a[3]&&t[l]||"",a[4]&&(d[l]=d[l].toLowerCase())}r&&(d.query=r(d.query)),n&&t.slashes&&d.pathname.charAt(0)!=="/"&&(d.pathname!==""||t.pathname!=="")&&(d.pathname=Mj(d.pathname,t.pathname)),d.pathname.charAt(0)!=="/"&&di(d.protocol)&&(d.pathname="/"+d.pathname),cD(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:"&&di(d.protocol)&&d.host?d.protocol+"//"+d.host:"null",d.href=d.toString()}function Uj(e,t,r){var n=this;switch(e){case"query":typeof t=="string"&&t.length&&(t=(r||Uf.parse)(t)),n[e]=t;break;case"port":n[e]=t,cD(t,n.protocol)?t&&(n.host=n.hostname+":"+t):(n.host=n.hostname,n[e]="");break;case"hostname":n[e]=t,n.port&&(t+=":"+n.port),n.host=t;break;case"host":n[e]=t,/:\d+$/.test(t)?(t=t.split(":"),n.port=t.pop(),n.hostname=t.join(":")):(n.hostname=t,n.port="");break;case"protocol":n.protocol=t.toLowerCase(),n.slashes=!r;break;case"pathname":case"hash":if(t){var i=e==="pathname"?"/":"#";n[e]=t.charAt(0)!==i?i+t:t}else n[e]=t;break;case"username":case"password":n[e]=encodeURIComponent(t);break;case"auth":var o=t.indexOf(":");~o?(n.username=t.slice(0,o),n.username=encodeURIComponent(decodeURIComponent(n.username)),n.password=t.slice(o+1),n.password=encodeURIComponent(decodeURIComponent(n.password))):n.username=encodeURIComponent(decodeURIComponent(t))}for(var a=0;a<Q0.length;a++){var s=Q0[a];s[4]&&(n[s[1]]=n[s[1]].toLowerCase())}return n.auth=n.password?n.username+":"+n.password:n.username,n.origin=n.protocol!=="file:"&&di(n.protocol)&&n.host?n.protocol+"//"+n.host:"null",n.href=n.toString(),n}function Bj(e){(!e||typeof e!="function")&&(e=Uf.stringify);var t,r=this,n=r.host,i=r.protocol;i&&i.charAt(i.length-1)!==":"&&(i+=":");var o=i+(r.protocol&&r.slashes||di(r.protocol)?"//":"");return r.username?(o+=r.username,r.password&&(o+=":"+r.password),o+="@"):r.password?(o+=":"+r.password,o+="@"):r.protocol!=="file:"&&di(r.protocol)&&!n&&r.pathname!=="/"&&(o+="@"),n[n.length-1]===":"&&(n+=":"),o+=n+r.pathname,t=typeof r.query=="object"?e(r.query):r.query,t&&(o+=t.charAt(0)!=="?"?"?"+t:t),r.hash&&(o+=r.hash),o}fi.prototype={set:Uj,toString:Bj};fi.extractProtocol=pD;fi.location=fD;fi.trimLeft=X0;fi.qs=Uf;mD.exports=fi});var qj,hD=k(()=>{"use strict";qj=Ce(Z0());});function ey(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 Bf=k(()=>{"use strict";});var ty,ry,ny=k(()=>{"use strict";Bf();ty=class{features=new Map;register(t,r){let n=ey(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()}},ry=new ty});var iy=k(()=>{"use strict";});function Ff(e){return Vj.has(e)}var Vj,Lu=k(()=>{"use strict";z0();K0();xf();Pu();z0();hD();ny();Bf();iy();Vj=new Set(["tie","test","prod","preview","preprod","gov","high","dod","mooncake","ex","rx"])});var Gj,gD=k(()=>{"use strict";Lu();Gj=Ru({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 wD,ay,Ms,va,oy,qf,Us,ji,qe,yD,bD,vD,kn=k(()=>{"use strict";wD={ThreeEqColumn_FirstColumn:34,ThreeEqColumn_SecondColumn:33,ThreeEqColumn_ThirdColumn:33,FiveEqColumn:20},ay={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"})(Ms||(Ms={}));(function(e){e.Left="Left",e.Right="Right",e.Center="Center"})(va||(va={}));(function(e){e[e.Mobile=0]="Mobile",e[e.Tablet=1]="Tablet",e[e.Web=2]="Web"})(oy||(oy={}));qf=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"})(Us||(Us={}));ji=class{static StartTag="<"},qe={ShowLabel:"true",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_",labelAlignment:va.Left,labelPosition:Us.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"})(yD||(yD={}));(function(e){e.TabWithLockedFieldRemoval="TabWithLockedFieldRemoval",e.SectionWithLockedFieldRemoval="SectionWithLockedFieldRemoval",e.LockedSectionRemoval="LockedSectionRemoval",e.LockedFieldRemoval="LockedFieldRemoval",e.RequiredFieldRemoval="RequiredFieldRemoval",e.LastRemainingTab="LastRemainingTab",e.UnknownRemoval="UnknownRemoval"})(bD||(bD={}));(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"})(vD||(vD={}))});var sy,CD=k(()=>{"use strict";(function(e){e.DefaultValue="defaultValue",e.Loaded="loaded"})(sy||(sy={}))});var SD,Wj,ED,ape,spe,ku,AD,lpe,upe,ND=k(()=>{"use strict";SD=Ce(ya());dt();Fs();gD();vs();kn();oa();le();Wj=Ce(lo());CD();(function(e){e.Model="Model",e.Canvas="Canvas",e.CustomPages="CustomPages"})(ED||(ED={}));ape={Read:go.Read,Edit:go.Edit,Both:go.Both,Container:go.Container},spe={input:ia.Input,bound:ia.Bound,output:ia.Output};(function(e){e[e.dataset=0]="dataset",e[e.property=1]="property",e[e.groups=2]="groups",e[e.group=3]="group"})(ku||(ku={}));(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"})(AD||(AD={}));lpe=new Set([F.Currency,F.Decimal,F.FP,F.Multiple,F.SingleLineEmail,F.SingleLinePhone,F.SingleLineText,F.SingleLineTextArea,F.SingleLineURL,F.SingleLineTickerSymbol,F.WholeNone,F.WholeDuration,F.WholeLanguage,F.WholeTimeZone,F.Enum,F.LookupSimple,F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.TwoOptions,F.Boolean,F.PowerBIReport,F.DateAndTimeDateAndTime,F.DateAndTimeDateOnly,F.OptionSet,F.MultiSelectOptionSet,F.CardForm]),upe={numbers:[F.WholeNone,F.FP,F.Decimal,F.Currency],text:[F.SingleLineText,F.SingleLineTextArea,F.Multiple],lookup:[F.LookupSimple,F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding],dates:[F.DateAndTimeDateOnly,F.DateAndTimeDateAndTime],allFields:[F.TwoOptions,F.DateAndTimeDateOnly,F.DateAndTimeDateAndTime,F.FP,F.Decimal,F.WholeNone,F.WholeDuration,F.WholeTimeZone,F.WholeLanguage,F.LookupSimple,F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.Multiple,F.OptionSet,F.SingleLineText,F.SingleLineTextArea,F.SingleLineEmail,F.SingleLineURL,F.SingleLineTickerSymbol,F.SingleLinePhone]}});var $n,Vf,_D=k(()=>{"use strict";$n=Ce(ya());vt();dt();rr();Fs();oa();ND();vs();le();kt();kn();Vf=class extends re{constructor(t){super(E.customControl,t)}customControlId;get id(){let t=this.getProperty(y.id);return R.IsNullOrUndefined(t)?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new U(t.substr(1,t.length-2)):new U(t)}getParameters(){let t=new Map,r=this.getAllChildren();if(r&&r.length!==0&&r[0]){let n=r[0].getAllChildren();if(n!=null){for(let i of n)if(i&&i.getAllChildren().length>0){let o=i.getNodeName();t.get(o)?t.get(o).push(i):t.set(o,[i])}}}return t}getFormComponentValueByParameterName(t){let r=this.getParameters()?.get(Xt.value);if(r?.length>0){let n=r[0],i=n?.getAllChildren()?.length>0?n.getAllChildren().find(a=>a.getNodeName()===t):null,o=i?.getAllChildren()?.length>0?i.getAllChildren()[0].getNodeName():"";return this.normalizePropertyValue(o)}}getParameterValue(t){let r=this.getParameterNodeChild(t);return r&&this.normalizePropertyValue(r.getNodeName())}getParameterNodeChild(t){let r=this.getParameters().get(t);return r?.length>0&&r[0].getAllChildren()?.length>0?r[0].getAllChildren()[0]:null}getDatasetName(t){return t.getAllProperties().find(r=>r.key===Xt.name)?.value}getParameterChildrenValues(t,r,n){if(this.isDataSet(t)){let i=r.find(u=>u.key===Xt.name)?.value,o={Name:i,Type:F.Grid,Columns:[]},l=this.getParameters().get(Xt.dataset).find(u=>this.getDatasetName(u)===i).getAllChildren();for(let u of l){let c=u.getNodeName();if(u&&u.getAllChildren().length>0){let d=this.normalizePropertyValue(u.getAllChildren()[0].getNodeName());o[c]=d}}return o}}getParameterIsStatic(t){let r=!1,n=this.getParameters().get(t)[0],i=n&&n.getAllProperties();if(i){for(let o of i)if(o.key===y.static&&o.value==="true"){r=!0;break}}return r}get name(){return this.getProperty(y.Name)}get formFactor(){return this.getProperty(y.formFactor)}set formFactor(t){this.setProperty(y.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(ji.StartTag)&&(t=t.substring(1)),t}async parametersToJSON(t){let r=[];if(!this.name)return r;try{let n=await t.formModelService.customControlDiscoveryService.getCustomControlMetadata(this.name);if(n)if(n.configurations){let i=n.configurations,o=this.getParameters();for(let[a,s]of o)if(this.isDataSet(a))for(let l of o.get(a)){let u=l.getAllProperties(),c=this.getDatasetName(l),d=i.get(c),f=await this.parameterJSON(a,u,d,t);r.push({Name:c,Value:f})}else if(this.isGroups(s))r.push({Name:a,Value:{Type:hg.GroupDefinition,Value:this.normalizePropertyValue(this.getParameterNodeChild(s[0].NodeName).NodeName)}}),i.get(a).groupSet?.forEach(u=>{u.groupConfigurableProperties.forEach(async c=>{let d=c.name;c.propertyType===ku.dataset?o.get(Xt.dataset)?.some(m=>this.getDatasetName(m)===d)||r.push({Name:d,Value:{Name:d,Columns:[],Type:F.Grid}}):c.propertyType===ku.property&&(o.has(d)||r.push({Name:d,Value:{Usage:c.usage}}))})});else{let l=s[0].getAllProperties(),u=i.get(a),c=await this.parameterJSON(a,l,u,t);if(c)r.push({Name:a,Value:c});else{(0,$n.trackInfoTrace)(hr,{eventName:`${Wi}/parametersToJSON`,eventData:{message:`Configuration metadata for custom control parameter ${a} is not available for custom control : ${this.name}.`}}),r=[];break}}}else(0,$n.trackErrorTrace)(hr,{eventName:`${Wi}/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,$n.trackErrorTrace)(hr,{eventName:`${Wi}/parametersToJSON`,eventData:{message:"Custom Control Manifest not found"}},new Error(`No custom control manifest found for ${this.name}`))}catch(n){(0,$n.trackErrorTrace)(hr,{eventName:`${Wi}/parametersToJSON`,eventData:{message:"parameters to json failed"}},n)}return r}async parameterJSON(t,r,n,i){if(this.isDataSet(t)){let o=n,a=r.find(s=>s.key===Xt.name)?.value;if(o)return this.getParameterChildrenValues(t,r);{let s=new Error(`No dataset manifest info for ${a}`);(0,$n.trackErrorTrace)(hr,{eventName:`${Wi}/parameterJSON`,eventData:{message:"Missing custom control manifest dataset info"}},s)}}else{let o=n,a=r&&r.find(l=>l.key===y.Type),s=o&&!o.ofTypeGroup.every(l=>!Od.includes(l));if(this.isLookupType(a?.value)||this.isLookupType(o?.ofType)||s)if(o){let l=o.usage,u=this.getParameterIsStatic(t),c=o.isPrimary;if(this.name===Mi.FormComponent){let d=this.getFormComponentValueByParameterName(y.bindAttribute),f=await i.formModelService.loadLookupModel(d),m=f.lookupColumn,p=this.getLookupDataTypeFromAttributeMetadata(m);return{Name:t,Type:p,Usage:l,Static:u,Primary:c,EntityName:f.primaryTableName,Value:d,ViewId:this.getFormComponentValueByParameterName(mg.DefaultViewId),TargetEntityType:m.targets[0],FilterRelationshipName:this.getFormComponentValueByParameterName(y.FilterRelationshipName),AvailableViewIds:this.getFormComponentValueByParameterName(y.AvailableViewIds),DependentAttributeName:this.getFormComponentValueByParameterName(y.DependentAttributeName),DependentAttributeType:this.getFormComponentValueByParameterName(y.DependentAttributeType),AllowFilterOff:q.IsStrictTrue(this.getFormComponentValueByParameterName(y.AllowFilterOff)),DisableQuickFind:q.IsStrictTrue(this.getFormComponentValueByParameterName(y.DisableQuickFind)),EnableViewPicker:!q.IsStrictTrue(this.getFormComponentValueByParameterName(y.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,$n.trackErrorTrace)(hr,{eventName:`${Wi}/parameterJSON`,eventData:{message:"Missing custom control manifest lookup property info"}},l)}if(o){let l=o.usage,u=this.getParameterIsStatic(t),c=this.getParameterValue(t),d=o.isPrimary;if(a){let m=a.value;return{Type:m,Static:u,Usage:l,Value:this.isNumberTypeProperty(o,m)&&Number(c)?Number(c):c,Primary:d}}if(o.ofType)return{Type:o.ofType,Static:u,Usage:l,Value:c,Primary:!0};if(o.ofTypeGroup)return{Static:u,Usage:l,Value:c,Primary:!0};let f=new Error(`No property type info for ${t}`);(0,$n.trackErrorTrace)(hr,{eventName:`${Wi}/parameterJSON`,eventData:{message:"Missing property type info"}},f)}else{let l=new Error(`No property manifest info for ${t}`);(0,$n.trackWarningTrace)(hr,{eventName:`${Wi}/parameterJSON`,eventData:{message:"Missing custom control manifest property info"}},l)}}return null}getLookupDataTypeFromAttributeMetadata(t){let{attributeType:r,format:n}=t;switch(r){case $.Customer:return F.LookupCustomer;case $.Owner:return F.LookupOwner;case $.PartyList:return F.LookupPartyList;default:return n===W.Regarding?F.LookupRegarding:F.LookupSimple}}isLookupType(t){return Od.includes(t)}isNumberTypeProperty(t,r){return Pd.includes(r)||t.ofTypeGroup.some(n=>Pd.includes(n))}isDataSet(t){return Xt.dataset===t}isGroups(t){return!!t[0].getAllProperties().find(n=>n.key==="isGroup"&&n.value==="true")}}});var ee,ly=k(()=>{"use strict";ee=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 TD={};nn(TD,{CustomControlUniqueId:()=>wa,DeprecatedControlClassIds:()=>G,FieldControlTypes:()=>ft,mapFieldTypeToControl:()=>zj});function zj(e,t){switch(e){case $.TwoOptions:return N.BooleanControl;case $.Customer:case $.CustomerType:return N.LookupControl;case $.DateTime:return t===W.DateAndTime?N.DateTimeControl:N.DateTimeControl;case $.DecimalNumber:return N.DecimalControl;case $.FloatingPointNumber:return N.FloatingNumberControl;case $.WholeNumber:return t===W.Duration?N.DurationControl:t===W.Language?N.LanguageControl:t===W.TimeZone?N.TimezoneControl:N.IntegerControl;case $.CustomerType:case $.Lookup:case $.LookupType:return t===W.Regarding?N.RegardingControl:N.LookupControl;case $.MultipleLineofText:return t===W.Email?N.EmailBodyControl:N.TextAreaControl;case $.Currency:return N.CurrencyControl;case $.Owner:case $.OwnerType:return N.LookupControl;case $.PartyList:case $.PartyListType:return N.PartyListControl;case $.Status:case $.OptionSet:return N.ChoiceControl;case $.SingleLineofText:return t===W.Email?N.EmailAddressControl:t===W.Phone?N.PhoneNumberControl:t===W.Text?N.TextboxControl:t===W.TextArea?N.TextAreaControl:t===W.TickerSymbol?N.TickerControl:t===W.Url?N.UrlControl:t===W.PhoneticGuide?N.TextboxControl:N.TextboxControl;case $.MultiSelectOptionSet:return N.ChoicesControl;case $.Image:return N.ImageControl;case $.File:return N.FileControl;case $.State:return N.ChoiceControl;case $.Status:return N.ChoiceStatusControl;default:throw new Error(`Cannot get base control for ${e} field type`)}}var G,wa,ft,$u=k(()=>{"use strict";vt();su();dt();rr();vs();ga();ly();kn();G=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"}};wa=class{static get RelationshipAssistant(){return"3ff9a528-dd50-4aca-8f10-2e5ed73513ad"}static get PredictiveLeadScoring(){return"6f503f2a-d033-4106-b62c-f8f2e5f01a57"}},ft=class e{static FieldControlIds=e.initializeFieldControls();static UnboundControlIds=e.initializeUnboundControls();static ControlsAllowedForReferencePanel=e.initializeReferencePanelControls();static ControlsAllowedForFooter=e.initializeFooterControls();static CustomControlIdMap=new dr;static initializeFieldControls(){let t=new dr,r=e.getControlName($.SingleLineofText,W.Phone);t.add(r,new U(G.PhoneNumberControl));let n=e.getControlName($.SingleLineofText,W.TextArea);t.add(n,new U(G.TextAreaControl));let i=e.getControlName($.SingleLineofText,W.Text);t.add(i,new U(G.TextBoxControl));let o=e.getControlName($.SingleLineofText,W.Email);t.add(o,new U(G.EmailAddressControl));let a=e.getControlName($.SingleLineofText,W.Url);t.add(a,new U(G.UrlControl));let s=e.getControlName($.SingleLineofText,W.TickerSymbol);t.add(s,new U(G.TickerControl));let l=e.getControlName($.SingleLineofText,W.PhoneticGuide);t.add(l,new U(G.TextBoxControl));let u=e.getControlName($.WholeNumber,W.Duration);t.add(u,new U(G.DurationControl));let c=e.getControlName($.WholeNumber,W.Language);t.add(c,new U(G.LanguagePickerControl));let d=e.getControlName($.WholeNumber,W.TimeZone);t.add(d,new U(G.TimeZonePicklistControl));let f=e.getControlName($.WholeNumber,W.None);t.add(f,new U(G.IntegerControl));let m=e.getControlName($.DateTime,W.DateOnly);t.add(m,new U(G.DateTimeControl));let p=e.getControlName($.DateTime,W.DateAndTime);t.add(p,new U(G.DateTimeControl));let h=e.getControlName($.LookupType,W.None);t.add(h,new U(G.LookupControl));let g=e.getControlName($.CustomerType,W.None);t.add(g,new U(G.LookupControl));let b=e.getControlName($.FloatingPointNumber,W.None);t.add(b,new U(G.FloatControl));let w=e.getControlName($.DecimalNumber,W.None);t.add(w,new U(G.DecimalControl));let C=e.getControlName($.Currency,W.None);t.add(C,new U(G.MoneyControl));let S=e.getControlName($.MultipleLineofText,W.None);t.add(S,new U(G.TextAreaControl));let O=e.getControlName($.MultipleLineofText,W.Text);t.add(O,new U(G.TextAreaControl));let L=e.getControlName($.MultipleLineofText,W.TextArea);t.add(L,new U(G.TextAreaControl));let I=e.getControlName($.MultipleLineofText,W.Email);t.add(I,new U(G.EmailBodyControl));let D=e.getControlName($.OptionSet,W.None);t.add(D,new U(G.PicklistControl));let P=e.getControlName($.TwoOptions,W.None);t.add(P,new U(G.RadioControl));let x=e.getControlName($.Image,W.None);t.add(x,new U(G.WebResourceImageControl));let K=e.getControlName($.Image,W.None);t.add(K,new U(G.WebResourceHtmlControl));let Le=e.getControlName($.TwoOptions,"Radio");t.add(Le,new U(G.RadioControl));let lr=e.getControlName($.TwoOptions,"CheckBox");t.add(lr,new U(G.CheckBoxControl));let Ge=e.getControlName($.TwoOptions,"List");t.add(Ge,new U(G.PicklistControl));let Ut=e.getControlName($.State,W.None);t.add(Ut,new U(G.PicklistControl));let de=e.getControlName($.Status,W.None);t.add(de,new U(G.PicklistStatusControl));let Ke=e.getControlName($.OwnerType,W.None);t.add(Ke,new U(G.LookupControl));let ur=e.getControlName($.PartyListType,W.None);t.add(ur,new U(G.PartyListControl));let Bt=e.getControlName($.LookupType,W.Regarding);t.add(Bt,new U(G.RegardingControl));let Ni=e.getControlName($.MultiSelectOptionSet,W.None);return t.add(Ni,new U(G.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(!R.IsNullOrEmptyGuid(t)){let r=e.getTypeAndFormatByControlOrUniqueId(t.guidString.toLowerCase());return r=R.IsNullOrUndefined(r)?e.getUnboundControlNameFromIdentifier(t):r.substring(0,r.indexOf("_")),r}return null}static isCustomControl(t){return R.IsNullOrUndefined(t.control)||R.IsNullOrUndefined(t.control.ClassId)||t.control.ClassId.guidString===G.CustomControl}static initializeUnboundControls(){let t=new dr;return t.add(G.ACIControl,ee.ACIControl),t.add(G.IframeControl,ee.IframeControl),t.add(G.SearchWidgetControl,ee.SearchWidgetControl),t.add(G.MapsControl,ee.MapsControl),t.add(G.QuickFormCollectionControl,ee.QuickFormCollectionControl),t.add(G.GridControl,ee.SubGridControl),t.add(G.WebResourceImageControl,ee.WebResourceImageControl),t.add(G.WebResourceHtmlControl,ee.WebResourceHtmlControl),t.add(G.ReferencePanelSearchWidget,ee.SearchWidgetControl),t.add(G.ReferencePanelQuickFormCollectionControl,ee.QuickFormCollectionControl),t.add(G.ReferencePanelSubgridControl,ee.SubGridControl),t.add(G.TimerControl,ee.TimerControl),t.add(G.TimeLineControl,ee.NotesControl),t.add(G.TimeLineControlUC,ee.NotesControl),t.add(G.SocialInsightControl,ee.SocialInsightControl),t.add(wa.RelationshipAssistant,ee.CustomControl),t}static initializeReferencePanelControls(){let t=new dr;return t.add(G.IframeControl,ee.IframeControl),t.add(G.ReferencePanelSearchWidget,ee.SearchWidgetControl),t.add(G.ReferencePanelQuickFormCollectionControl,ee.QuickFormCollectionControl),t.add(G.ReferencePanelSubgridControl,ee.SubGridControl),t.add(G.WebResourceHtmlControl,ee.WebResourceHtmlControl),t.add(G.WebResourceImageControl,ee.WebResourceHtmlControl),t}static initializeFooterControls(){let t=new bs;return t.add(Ms.IFRAME,!0),t.add(Ms.SPACER,!0),t.add(Ms.WEB_RESOURCE_HTML,!0),t}static isUnboundFormControl(t){if(R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.control)||R.IsNullOrUndefined(t.control.ClassId))return!1;let r=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.containsKey(r.guidString)}static isReferencePanelSection(t){return!R.IsNullOrUndefined(t)&&!R.IsNullOrUndefined(t.Name)&&t.Name.indexOf(qe.referencePanelNamePrefix)===0}static isUnboundFormControlByIdentifier(t){return R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.guidString)?!1:e.UnboundControlIds.containsKey(t.guidString)}static getUnboundFormControlName(t){let r=q.EmptyString;if(R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.control)||R.IsNullOrUndefined(t.control.ClassId))return r;let n=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.getValue(n.guidString).toString()}static getUnboundControlNameFromIdentifier(t){return R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.guidString)?q.EmptyString:e.UnboundControlIds.getValue(t.guidString).toString()}static isSpacerControl(t){return t===G.SpacerControl}static GetRowSpan(t){let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===G.CustomControl&&!R.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}switch(e.UnboundControlIds.getValue(r.guidString)){case ee.IframeControl:case ee.ACIControl:case ee.SocialInsightControl:return 6;case ee.SubGridControl:case ee.CustomControl:return 4;case ee.WebResourceImageControl:return 15;case ee.WebResourceHtmlControl:return 15;case ee.MapsControl:return 8;case ee.SearchWidgetControl:return 10;case ee.NotesControl:case ee.TimeLineControl:return 15;case ee.TimerControl:return 2;default:}}static isLookUpControl(t){return!R.IsNullOrUndefined(t)&&t.ClassId.guidString===G.LookupControl}static isRelationshipAssistantOrLeadScoringControl(t){return!R.IsNullOrUndefined(t)&&e.isRelationshipAssistantOrLeadScoring(t.UniqueId)}static isRelationshipAssistantOrLeadScoring(t){return!R.IsNullOrUndefined(t)&&(t.guidString===wa.RelationshipAssistant||t.guidString===wa.PredictiveLeadScoring)}static isRelationshipAssistantControl(t){return!R.IsNullOrUndefined(t)&&e.isRelationshipAssistant(t.UniqueId)}static isRelationshipAssistant(t){return!R.IsNullOrUndefined(t)&&t.guidString===wa.RelationshipAssistant}static getUniqueIdentifierForControl(t){if(R.IsNullOrUndefined(t))return null;let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===G.CustomControl&&!R.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}return r}}});var Gf,DD=k(()=>{"use strict";Gf=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 Ca,Bs,ID,OD,Oo,PD,RD,uy=k(()=>{"use strict";(function(e){e[e.Center=0]="Center",e[e.Left=1]="Left",e[e.Right=2]="Right"})(Ca||(Ca={}));(function(e){e[e.Left=0]="Left",e[e.Top=1]="Top"})(Bs||(Bs={}));(function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle"})(ID||(ID={}));(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"})(OD||(OD={}));(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"})(Oo||(Oo={}));(function(e){e[e.None=0]="None",e[e.SystemRequired=1]="SystemRequired",e[e.ApplicationRequired=2]="ApplicationRequired",e[e.Recommended=3]="Recommended"})(PD||(PD={}));(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"})(RD||(RD={}))});var qs,LD=k(()=>{"use strict";Lu();qs=J0({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 kD(e){return{...e,extractConfig:t=>jj(t,Object.keys(e.fallback))}}function jj(e,t){let r={};for(let n of t)typeof e[n]<"u"&&(r[n]=e[n]);return r}var cy=k(()=>{"use strict";});var dy=v((xpe,xD)=>{var xu=new Proxy(function(){return xu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:xu},apply:function(){return xu},construct:function(){return{}}}),$D=function(){return xu};Object.setPrototypeOf($D,xu);xD.exports=$D});var UD=v((Fpe,MD)=>{var Fu=new Proxy(function(){return Fu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Fu},apply:function(){return Fu},construct:function(){return{}}}),FD=function(){return Fu};Object.setPrototypeOf(FD,Fu);MD.exports=FD});var fy=v((Mpe,qD)=>{var Mu=new Proxy(function(){return Mu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Mu},apply:function(){return Mu},construct:function(){return{}}}),BD=function(){return Mu};Object.setPrototypeOf(BD,Mu);qD.exports=BD});var GD=v((Upe,VD)=>{function Hj(){this.__data__=[],this.size=0}VD.exports=Hj});var Vs=v((Bpe,WD)=>{function Kj(e,t){return e===t||e!==e&&t!==t}WD.exports=Kj});var Uu=v((qpe,zD)=>{var Jj=Vs();function Yj(e,t){for(var r=e.length;r--;)if(Jj(e[r][0],t))return r;return-1}zD.exports=Yj});var HD=v((Vpe,jD)=>{var Qj=Uu(),Xj=Array.prototype,Zj=Xj.splice;function e7(e){var t=this.__data__,r=Qj(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():Zj.call(t,r,1),--this.size,!0}jD.exports=e7});var JD=v((Gpe,KD)=>{var t7=Uu();function r7(e){var t=this.__data__,r=t7(t,e);return r<0?void 0:t[r][1]}KD.exports=r7});var QD=v((Wpe,YD)=>{var n7=Uu();function i7(e){return n7(this.__data__,e)>-1}YD.exports=i7});var ZD=v((zpe,XD)=>{var o7=Uu();function a7(e,t){var r=this.__data__,n=o7(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}XD.exports=a7});var Bu=v((jpe,eI)=>{var s7=GD(),l7=HD(),u7=JD(),c7=QD(),d7=ZD();function Gs(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])}}Gs.prototype.clear=s7;Gs.prototype.delete=l7;Gs.prototype.get=u7;Gs.prototype.has=c7;Gs.prototype.set=d7;eI.exports=Gs});var rI=v((Hpe,tI)=>{var f7=Bu();function p7(){this.__data__=new f7,this.size=0}tI.exports=p7});var iI=v((Kpe,nI)=>{function m7(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}nI.exports=m7});var aI=v((Jpe,oI)=>{function h7(e){return this.__data__.get(e)}oI.exports=h7});var lI=v((Ype,sI)=>{function g7(e){return this.__data__.has(e)}sI.exports=g7});var py=v((Qpe,uI)=>{var y7=typeof global=="object"&&global&&global.Object===Object&&global;uI.exports=y7});var xn=v((Xpe,cI)=>{var b7=py(),v7=typeof self=="object"&&self&&self.Object===Object&&self,w7=b7||v7||Function("return this")();cI.exports=w7});var qu=v((Zpe,dI)=>{var C7=xn(),E7=C7.Symbol;dI.exports=E7});var hI=v((eme,mI)=>{var fI=qu(),pI=Object.prototype,A7=pI.hasOwnProperty,S7=pI.toString,Vu=fI?fI.toStringTag:void 0;function N7(e){var t=A7.call(e,Vu),r=e[Vu];try{e[Vu]=void 0;var n=!0}catch{}var i=S7.call(e);return n&&(t?e[Vu]=r:delete e[Vu]),i}mI.exports=N7});var yI=v((tme,gI)=>{var _7=Object.prototype,T7=_7.toString;function D7(e){return T7.call(e)}gI.exports=D7});var Ea=v((rme,wI)=>{var bI=qu(),I7=hI(),O7=yI(),P7="[object Null]",R7="[object Undefined]",vI=bI?bI.toStringTag:void 0;function L7(e){return e==null?e===void 0?R7:P7:vI&&vI in Object(e)?I7(e):O7(e)}wI.exports=L7});var Hi=v((nme,CI)=>{function k7(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}CI.exports=k7});var Wf=v((ime,EI)=>{var $7=Ea(),x7=Hi(),F7="[object AsyncFunction]",M7="[object Function]",U7="[object GeneratorFunction]",B7="[object Proxy]";function q7(e){if(!x7(e))return!1;var t=$7(e);return t==M7||t==U7||t==F7||t==B7}EI.exports=q7});var SI=v((ome,AI)=>{var V7=xn(),G7=V7["__core-js_shared__"];AI.exports=G7});var TI=v((ame,_I)=>{var my=SI(),NI=(function(){var e=/[^.]+$/.exec(my&&my.keys&&my.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function W7(e){return!!NI&&NI in e}_I.exports=W7});var hy=v((sme,DI)=>{var z7=Function.prototype,j7=z7.toString;function H7(e){if(e!=null){try{return j7.call(e)}catch{}try{return e+""}catch{}}return""}DI.exports=H7});var OI=v((lme,II)=>{var K7=Wf(),J7=TI(),Y7=Hi(),Q7=hy(),X7=/[\\^$.*+?()[\]{}|]/g,Z7=/^\[object .+?Constructor\]$/,eH=Function.prototype,tH=Object.prototype,rH=eH.toString,nH=tH.hasOwnProperty,iH=RegExp("^"+rH.call(nH).replace(X7,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function oH(e){if(!Y7(e)||J7(e))return!1;var t=K7(e)?iH:Z7;return t.test(Q7(e))}II.exports=oH});var RI=v((ume,PI)=>{function aH(e,t){return e?.[t]}PI.exports=aH});var Po=v((cme,LI)=>{var sH=OI(),lH=RI();function uH(e,t){var r=lH(e,t);return sH(r)?r:void 0}LI.exports=uH});var zf=v((dme,kI)=>{var cH=Po(),dH=xn(),fH=cH(dH,"Map");kI.exports=fH});var Gu=v((fme,$I)=>{var pH=Po(),mH=pH(Object,"create");$I.exports=mH});var MI=v((pme,FI)=>{var xI=Gu();function hH(){this.__data__=xI?xI(null):{},this.size=0}FI.exports=hH});var BI=v((mme,UI)=>{function gH(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}UI.exports=gH});var VI=v((hme,qI)=>{var yH=Gu(),bH="__lodash_hash_undefined__",vH=Object.prototype,wH=vH.hasOwnProperty;function CH(e){var t=this.__data__;if(yH){var r=t[e];return r===bH?void 0:r}return wH.call(t,e)?t[e]:void 0}qI.exports=CH});var WI=v((gme,GI)=>{var EH=Gu(),AH=Object.prototype,SH=AH.hasOwnProperty;function NH(e){var t=this.__data__;return EH?t[e]!==void 0:SH.call(t,e)}GI.exports=NH});var jI=v((yme,zI)=>{var _H=Gu(),TH="__lodash_hash_undefined__";function DH(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=_H&&t===void 0?TH:t,this}zI.exports=DH});var KI=v((bme,HI)=>{var IH=MI(),OH=BI(),PH=VI(),RH=WI(),LH=jI();function Ws(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])}}Ws.prototype.clear=IH;Ws.prototype.delete=OH;Ws.prototype.get=PH;Ws.prototype.has=RH;Ws.prototype.set=LH;HI.exports=Ws});var QI=v((vme,YI)=>{var JI=KI(),kH=Bu(),$H=zf();function xH(){this.size=0,this.__data__={hash:new JI,map:new($H||kH),string:new JI}}YI.exports=xH});var ZI=v((wme,XI)=>{function FH(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}XI.exports=FH});var Wu=v((Cme,eO)=>{var MH=ZI();function UH(e,t){var r=e.__data__;return MH(t)?r[typeof t=="string"?"string":"hash"]:r.map}eO.exports=UH});var rO=v((Eme,tO)=>{var BH=Wu();function qH(e){var t=BH(this,e).delete(e);return this.size-=t?1:0,t}tO.exports=qH});var iO=v((Ame,nO)=>{var VH=Wu();function GH(e){return VH(this,e).get(e)}nO.exports=GH});var aO=v((Sme,oO)=>{var WH=Wu();function zH(e){return WH(this,e).has(e)}oO.exports=zH});var lO=v((Nme,sO)=>{var jH=Wu();function HH(e,t){var r=jH(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}sO.exports=HH});var jf=v((_me,uO)=>{var KH=QI(),JH=rO(),YH=iO(),QH=aO(),XH=lO();function zs(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])}}zs.prototype.clear=KH;zs.prototype.delete=JH;zs.prototype.get=YH;zs.prototype.has=QH;zs.prototype.set=XH;uO.exports=zs});var dO=v((Tme,cO)=>{var ZH=Bu(),eK=zf(),tK=jf(),rK=200;function nK(e,t){var r=this.__data__;if(r instanceof ZH){var n=r.__data__;if(!eK||n.length<rK-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new tK(n)}return r.set(e,t),this.size=r.size,this}cO.exports=nK});var gy=v((Dme,fO)=>{var iK=Bu(),oK=rI(),aK=iI(),sK=aI(),lK=lI(),uK=dO();function js(e){var t=this.__data__=new iK(e);this.size=t.size}js.prototype.clear=oK;js.prototype.delete=aK;js.prototype.get=sK;js.prototype.has=lK;js.prototype.set=uK;fO.exports=js});var mO=v((Ime,pO)=>{var cK="__lodash_hash_undefined__";function dK(e){return this.__data__.set(e,cK),this}pO.exports=dK});var gO=v((Ome,hO)=>{function fK(e){return this.__data__.has(e)}hO.exports=fK});var bO=v((Pme,yO)=>{var pK=jf(),mK=mO(),hK=gO();function Hf(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new pK;++t<r;)this.add(e[t])}Hf.prototype.add=Hf.prototype.push=mK;Hf.prototype.has=hK;yO.exports=Hf});var wO=v((Rme,vO)=>{function gK(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}vO.exports=gK});var EO=v((Lme,CO)=>{function yK(e,t){return e.has(t)}CO.exports=yK});var yy=v((kme,AO)=>{var bK=bO(),vK=wO(),wK=EO(),CK=1,EK=2;function AK(e,t,r,n,i,o){var a=r&CK,s=e.length,l=t.length;if(s!=l&&!(a&&l>s))return!1;var u=o.get(e),c=o.get(t);if(u&&c)return u==t&&c==e;var d=-1,f=!0,m=r&EK?new bK:void 0;for(o.set(e,t),o.set(t,e);++d<s;){var p=e[d],h=t[d];if(n)var g=a?n(h,p,d,t,e,o):n(p,h,d,e,t,o);if(g!==void 0){if(g)continue;f=!1;break}if(m){if(!vK(t,function(b,w){if(!wK(m,w)&&(p===b||i(p,b,r,n,o)))return m.push(w)})){f=!1;break}}else if(!(p===h||i(p,h,r,n,o))){f=!1;break}}return o.delete(e),o.delete(t),f}AO.exports=AK});var by=v(($me,SO)=>{var SK=xn(),NK=SK.Uint8Array;SO.exports=NK});var _O=v((xme,NO)=>{function _K(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}NO.exports=_K});var DO=v((Fme,TO)=>{function TK(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}TO.exports=TK});var LO=v((Mme,RO)=>{var IO=qu(),OO=by(),DK=Vs(),IK=yy(),OK=_O(),PK=DO(),RK=1,LK=2,kK="[object Boolean]",$K="[object Date]",xK="[object Error]",FK="[object Map]",MK="[object Number]",UK="[object RegExp]",BK="[object Set]",qK="[object String]",VK="[object Symbol]",GK="[object ArrayBuffer]",WK="[object DataView]",PO=IO?IO.prototype:void 0,vy=PO?PO.valueOf:void 0;function zK(e,t,r,n,i,o,a){switch(r){case WK:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case GK:return!(e.byteLength!=t.byteLength||!o(new OO(e),new OO(t)));case kK:case $K:case MK:return DK(+e,+t);case xK:return e.name==t.name&&e.message==t.message;case UK:case qK:return e==t+"";case FK:var s=OK;case BK:var l=n&RK;if(s||(s=PK),e.size!=t.size&&!l)return!1;var u=a.get(e);if(u)return u==t;n|=LK,a.set(e,t);var c=IK(s(e),s(t),n,i,o,a);return a.delete(e),c;case VK:if(vy)return vy.call(e)==vy.call(t)}return!1}RO.exports=zK});var $O=v((Ume,kO)=>{function jK(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}kO.exports=jK});var Ro=v((Bme,xO)=>{var HK=Array.isArray;xO.exports=HK});var MO=v((qme,FO)=>{var KK=$O(),JK=Ro();function YK(e,t,r){var n=t(e);return JK(e)?n:KK(n,r(e))}FO.exports=YK});var BO=v((Vme,UO)=>{function QK(e,t){for(var r=-1,n=e==null?0:e.length,i=0,o=[];++r<n;){var a=e[r];t(a,r,e)&&(o[i++]=a)}return o}UO.exports=QK});var VO=v((Gme,qO)=>{function XK(){return[]}qO.exports=XK});var zO=v((Wme,WO)=>{var ZK=BO(),eJ=VO(),tJ=Object.prototype,rJ=tJ.propertyIsEnumerable,GO=Object.getOwnPropertySymbols,nJ=GO?function(e){return e==null?[]:(e=Object(e),ZK(GO(e),function(t){return rJ.call(e,t)}))}:eJ;WO.exports=nJ});var HO=v((zme,jO)=>{function iJ(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}jO.exports=iJ});var Lo=v((jme,KO)=>{function oJ(e){return e!=null&&typeof e=="object"}KO.exports=oJ});var YO=v((Hme,JO)=>{var aJ=Ea(),sJ=Lo(),lJ="[object Arguments]";function uJ(e){return sJ(e)&&aJ(e)==lJ}JO.exports=uJ});var wy=v((Kme,ZO)=>{var QO=YO(),cJ=Lo(),XO=Object.prototype,dJ=XO.hasOwnProperty,fJ=XO.propertyIsEnumerable,pJ=QO((function(){return arguments})())?QO:function(e){return cJ(e)&&dJ.call(e,"callee")&&!fJ.call(e,"callee")};ZO.exports=pJ});var tP=v((Jme,eP)=>{function mJ(){return!1}eP.exports=mJ});var Kf=v((zu,Hs)=>{var hJ=xn(),gJ=tP(),iP=typeof zu=="object"&&zu&&!zu.nodeType&&zu,rP=iP&&typeof Hs=="object"&&Hs&&!Hs.nodeType&&Hs,yJ=rP&&rP.exports===iP,nP=yJ?hJ.Buffer:void 0,bJ=nP?nP.isBuffer:void 0,vJ=bJ||gJ;Hs.exports=vJ});var Jf=v((Yme,oP)=>{var wJ=9007199254740991,CJ=/^(?:0|[1-9]\d*)$/;function EJ(e,t){var r=typeof e;return t=t??wJ,!!t&&(r=="number"||r!="symbol"&&CJ.test(e))&&e>-1&&e%1==0&&e<t}oP.exports=EJ});var Cy=v((Qme,aP)=>{var AJ=9007199254740991;function SJ(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=AJ}aP.exports=SJ});var lP=v((Xme,sP)=>{var NJ=Ea(),_J=Cy(),TJ=Lo(),DJ="[object Arguments]",IJ="[object Array]",OJ="[object Boolean]",PJ="[object Date]",RJ="[object Error]",LJ="[object Function]",kJ="[object Map]",$J="[object Number]",xJ="[object Object]",FJ="[object RegExp]",MJ="[object Set]",UJ="[object String]",BJ="[object WeakMap]",qJ="[object ArrayBuffer]",VJ="[object DataView]",GJ="[object Float32Array]",WJ="[object Float64Array]",zJ="[object Int8Array]",jJ="[object Int16Array]",HJ="[object Int32Array]",KJ="[object Uint8Array]",JJ="[object Uint8ClampedArray]",YJ="[object Uint16Array]",QJ="[object Uint32Array]",xe={};xe[GJ]=xe[WJ]=xe[zJ]=xe[jJ]=xe[HJ]=xe[KJ]=xe[JJ]=xe[YJ]=xe[QJ]=!0;xe[DJ]=xe[IJ]=xe[qJ]=xe[OJ]=xe[VJ]=xe[PJ]=xe[RJ]=xe[LJ]=xe[kJ]=xe[$J]=xe[xJ]=xe[FJ]=xe[MJ]=xe[UJ]=xe[BJ]=!1;function XJ(e){return TJ(e)&&_J(e.length)&&!!xe[NJ(e)]}sP.exports=XJ});var cP=v((Zme,uP)=>{function ZJ(e){return function(t){return e(t)}}uP.exports=ZJ});var fP=v((ju,Ks)=>{var eY=py(),dP=typeof ju=="object"&&ju&&!ju.nodeType&&ju,Hu=dP&&typeof Ks=="object"&&Ks&&!Ks.nodeType&&Ks,tY=Hu&&Hu.exports===dP,Ey=tY&&eY.process,rY=(function(){try{var e=Hu&&Hu.require&&Hu.require("util").types;return e||Ey&&Ey.binding&&Ey.binding("util")}catch{}})();Ks.exports=rY});var Yf=v((ehe,hP)=>{var nY=lP(),iY=cP(),pP=fP(),mP=pP&&pP.isTypedArray,oY=mP?iY(mP):nY;hP.exports=oY});var Ay=v((the,gP)=>{var aY=HO(),sY=wy(),lY=Ro(),uY=Kf(),cY=Jf(),dY=Yf(),fY=Object.prototype,pY=fY.hasOwnProperty;function mY(e,t){var r=lY(e),n=!r&&sY(e),i=!r&&!n&&uY(e),o=!r&&!n&&!i&&dY(e),a=r||n||i||o,s=a?aY(e.length,String):[],l=s.length;for(var u in e)(t||pY.call(e,u))&&!(a&&(u=="length"||i&&(u=="offset"||u=="parent")||o&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||cY(u,l)))&&s.push(u);return s}gP.exports=mY});var Qf=v((rhe,yP)=>{var hY=Object.prototype;function gY(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||hY;return e===r}yP.exports=gY});var Sy=v((nhe,bP)=>{function yY(e,t){return function(r){return e(t(r))}}bP.exports=yY});var wP=v((ihe,vP)=>{var bY=Sy(),vY=bY(Object.keys,Object);vP.exports=vY});var EP=v((ohe,CP)=>{var wY=Qf(),CY=wP(),EY=Object.prototype,AY=EY.hasOwnProperty;function SY(e){if(!wY(e))return CY(e);var t=[];for(var r in Object(e))AY.call(e,r)&&r!="constructor"&&t.push(r);return t}CP.exports=SY});var Ku=v((ahe,AP)=>{var NY=Wf(),_Y=Cy();function TY(e){return e!=null&&_Y(e.length)&&!NY(e)}AP.exports=TY});var NP=v((she,SP)=>{var DY=Ay(),IY=EP(),OY=Ku();function PY(e){return OY(e)?DY(e):IY(e)}SP.exports=PY});var TP=v((lhe,_P)=>{var RY=MO(),LY=zO(),kY=NP();function $Y(e){return RY(e,kY,LY)}_P.exports=$Y});var OP=v((uhe,IP)=>{var DP=TP(),xY=1,FY=Object.prototype,MY=FY.hasOwnProperty;function UY(e,t,r,n,i,o){var a=r&xY,s=DP(e),l=s.length,u=DP(t),c=u.length;if(l!=c&&!a)return!1;for(var d=l;d--;){var f=s[d];if(!(a?f in t:MY.call(t,f)))return!1}var m=o.get(e),p=o.get(t);if(m&&p)return m==t&&p==e;var h=!0;o.set(e,t),o.set(t,e);for(var g=a;++d<l;){f=s[d];var b=e[f],w=t[f];if(n)var C=a?n(w,b,f,t,e,o):n(b,w,f,e,t,o);if(!(C===void 0?b===w||i(b,w,r,n,o):C)){h=!1;break}g||(g=f=="constructor")}if(h&&!g){var S=e.constructor,O=t.constructor;S!=O&&"constructor"in e&&"constructor"in t&&!(typeof S=="function"&&S instanceof S&&typeof O=="function"&&O instanceof O)&&(h=!1)}return o.delete(e),o.delete(t),h}IP.exports=UY});var RP=v((che,PP)=>{var BY=Po(),qY=xn(),VY=BY(qY,"DataView");PP.exports=VY});var kP=v((dhe,LP)=>{var GY=Po(),WY=xn(),zY=GY(WY,"Promise");LP.exports=zY});var xP=v((fhe,$P)=>{var jY=Po(),HY=xn(),KY=jY(HY,"Set");$P.exports=KY});var MP=v((phe,FP)=>{var JY=Po(),YY=xn(),QY=JY(YY,"WeakMap");FP.exports=QY});var jP=v((mhe,zP)=>{var Ny=RP(),_y=zf(),Ty=kP(),Dy=xP(),Iy=MP(),WP=Ea(),Js=hy(),UP="[object Map]",XY="[object Object]",BP="[object Promise]",qP="[object Set]",VP="[object WeakMap]",GP="[object DataView]",ZY=Js(Ny),eQ=Js(_y),tQ=Js(Ty),rQ=Js(Dy),nQ=Js(Iy),Aa=WP;(Ny&&Aa(new Ny(new ArrayBuffer(1)))!=GP||_y&&Aa(new _y)!=UP||Ty&&Aa(Ty.resolve())!=BP||Dy&&Aa(new Dy)!=qP||Iy&&Aa(new Iy)!=VP)&&(Aa=function(e){var t=WP(e),r=t==XY?e.constructor:void 0,n=r?Js(r):"";if(n)switch(n){case ZY:return GP;case eQ:return UP;case tQ:return BP;case rQ:return qP;case nQ:return VP}return t});zP.exports=Aa});var eR=v((hhe,ZP)=>{var Oy=gy(),iQ=yy(),oQ=LO(),aQ=OP(),HP=jP(),KP=Ro(),JP=Kf(),sQ=Yf(),lQ=1,YP="[object Arguments]",QP="[object Array]",Xf="[object Object]",uQ=Object.prototype,XP=uQ.hasOwnProperty;function cQ(e,t,r,n,i,o){var a=KP(e),s=KP(t),l=a?QP:HP(e),u=s?QP:HP(t);l=l==YP?Xf:l,u=u==YP?Xf:u;var c=l==Xf,d=u==Xf,f=l==u;if(f&&JP(e)){if(!JP(t))return!1;a=!0,c=!1}if(f&&!c)return o||(o=new Oy),a||sQ(e)?iQ(e,t,r,n,i,o):oQ(e,t,l,r,n,i,o);if(!(r&lQ)){var m=c&&XP.call(e,"__wrapped__"),p=d&&XP.call(t,"__wrapped__");if(m||p){var h=m?e.value():e,g=p?t.value():t;return o||(o=new Oy),i(h,g,r,n,o)}}return f?(o||(o=new Oy),aQ(e,t,r,n,i,o)):!1}ZP.exports=cQ});var iR=v((ghe,nR)=>{var dQ=eR(),tR=Lo();function rR(e,t,r,n,i){return e===t?!0:e==null||t==null||!tR(e)&&!tR(t)?e!==e&&t!==t:dQ(e,t,r,n,rR,i)}nR.exports=rR});var aR=v((yhe,oR)=>{var fQ=iR();function pQ(e,t){return fQ(e,t)}oR.exports=pQ});var Py=v((bhe,sR)=>{var mQ=Po(),hQ=(function(){try{var e=mQ(Object,"defineProperty");return e({},"",{}),e}catch{}})();sR.exports=hQ});var Zf=v((vhe,uR)=>{var lR=Py();function gQ(e,t,r){t=="__proto__"&&lR?lR(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}uR.exports=gQ});var Ry=v((whe,cR)=>{var yQ=Zf(),bQ=Vs();function vQ(e,t,r){(r!==void 0&&!bQ(e[t],r)||r===void 0&&!(t in e))&&yQ(e,t,r)}cR.exports=vQ});var fR=v((Che,dR)=>{function wQ(e){return function(t,r,n){for(var i=-1,o=Object(t),a=n(t),s=a.length;s--;){var l=a[e?s:++i];if(r(o[l],l,o)===!1)break}return t}}dR.exports=wQ});var mR=v((Ehe,pR)=>{var CQ=fR(),EQ=CQ();pR.exports=EQ});var vR=v((Ju,Ys)=>{var AQ=xn(),bR=typeof Ju=="object"&&Ju&&!Ju.nodeType&&Ju,hR=bR&&typeof Ys=="object"&&Ys&&!Ys.nodeType&&Ys,SQ=hR&&hR.exports===bR,gR=SQ?AQ.Buffer:void 0,yR=gR?gR.allocUnsafe:void 0;function NQ(e,t){if(t)return e.slice();var r=e.length,n=yR?yR(r):new e.constructor(r);return e.copy(n),n}Ys.exports=NQ});var ER=v((Ahe,CR)=>{var wR=by();function _Q(e){var t=new e.constructor(e.byteLength);return new wR(t).set(new wR(e)),t}CR.exports=_Q});var SR=v((She,AR)=>{var TQ=ER();function DQ(e,t){var r=t?TQ(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}AR.exports=DQ});var _R=v((Nhe,NR)=>{function IQ(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}NR.exports=IQ});var IR=v((_he,DR)=>{var OQ=Hi(),TR=Object.create,PQ=(function(){function e(){}return function(t){if(!OQ(t))return{};if(TR)return TR(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})();DR.exports=PQ});var Ly=v((The,OR)=>{var RQ=Sy(),LQ=RQ(Object.getPrototypeOf,Object);OR.exports=LQ});var RR=v((Dhe,PR)=>{var kQ=IR(),$Q=Ly(),xQ=Qf();function FQ(e){return typeof e.constructor=="function"&&!xQ(e)?kQ($Q(e)):{}}PR.exports=FQ});var kR=v((Ihe,LR)=>{var MQ=Ku(),UQ=Lo();function BQ(e){return UQ(e)&&MQ(e)}LR.exports=BQ});var FR=v((Ohe,xR)=>{var qQ=Ea(),VQ=Ly(),GQ=Lo(),WQ="[object Object]",zQ=Function.prototype,jQ=Object.prototype,$R=zQ.toString,HQ=jQ.hasOwnProperty,KQ=$R.call(Object);function JQ(e){if(!GQ(e)||qQ(e)!=WQ)return!1;var t=VQ(e);if(t===null)return!0;var r=HQ.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&$R.call(r)==KQ}xR.exports=JQ});var ky=v((Phe,MR)=>{function YQ(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}MR.exports=YQ});var $y=v((Rhe,UR)=>{var QQ=Zf(),XQ=Vs(),ZQ=Object.prototype,eX=ZQ.hasOwnProperty;function tX(e,t,r){var n=e[t];(!(eX.call(e,t)&&XQ(n,r))||r===void 0&&!(t in e))&&QQ(e,t,r)}UR.exports=tX});var qR=v((Lhe,BR)=>{var rX=$y(),nX=Zf();function iX(e,t,r,n){var i=!r;r||(r={});for(var o=-1,a=t.length;++o<a;){var s=t[o],l=n?n(r[s],e[s],s,r,e):void 0;l===void 0&&(l=e[s]),i?nX(r,s,l):rX(r,s,l)}return r}BR.exports=iX});var GR=v((khe,VR)=>{function oX(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}VR.exports=oX});var zR=v(($he,WR)=>{var aX=Hi(),sX=Qf(),lX=GR(),uX=Object.prototype,cX=uX.hasOwnProperty;function dX(e){if(!aX(e))return lX(e);var t=sX(e),r=[];for(var n in e)n=="constructor"&&(t||!cX.call(e,n))||r.push(n);return r}WR.exports=dX});var xy=v((xhe,jR)=>{var fX=Ay(),pX=zR(),mX=Ku();function hX(e){return mX(e)?fX(e,!0):pX(e)}jR.exports=hX});var KR=v((Fhe,HR)=>{var gX=qR(),yX=xy();function bX(e){return gX(e,yX(e))}HR.exports=bX});var e2=v((Mhe,ZR)=>{var JR=Ry(),vX=vR(),wX=SR(),CX=_R(),EX=RR(),YR=wy(),QR=Ro(),AX=kR(),SX=Kf(),NX=Wf(),_X=Hi(),TX=FR(),DX=Yf(),XR=ky(),IX=KR();function OX(e,t,r,n,i,o,a){var s=XR(e,r),l=XR(t,r),u=a.get(l);if(u){JR(e,r,u);return}var c=o?o(s,l,r+"",e,t,a):void 0,d=c===void 0;if(d){var f=QR(l),m=!f&&SX(l),p=!f&&!m&&DX(l);c=l,f||m||p?QR(s)?c=s:AX(s)?c=CX(s):m?(d=!1,c=vX(l,!0)):p?(d=!1,c=wX(l,!0)):c=[]:TX(l)||YR(l)?(c=s,YR(s)?c=IX(s):(!_X(s)||NX(s))&&(c=EX(l))):d=!1}d&&(a.set(l,c),i(c,l,n,o,a),a.delete(l)),JR(e,r,c)}ZR.exports=OX});var Fy=v((Uhe,r2)=>{var PX=gy(),RX=Ry(),LX=mR(),kX=e2(),$X=Hi(),xX=xy(),FX=ky();function t2(e,t,r,n,i){e!==t&&LX(t,function(o,a){if(i||(i=new PX),$X(o))kX(e,t,a,r,t2,n,i);else{var s=n?n(FX(e,a),o,a+"",e,t,i):void 0;s===void 0&&(s=o),RX(e,a,s)}},xX)}r2.exports=t2});var My=v((Bhe,n2)=>{function MX(e){return e}n2.exports=MX});var o2=v((qhe,i2)=>{function UX(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)}i2.exports=UX});var l2=v((Vhe,s2)=>{var BX=o2(),a2=Math.max;function qX(e,t,r){return t=a2(t===void 0?e.length-1:t,0),function(){for(var n=arguments,i=-1,o=a2(n.length-t,0),a=Array(o);++i<o;)a[i]=n[t+i];i=-1;for(var s=Array(t+1);++i<t;)s[i]=n[i];return s[t]=r(a),BX(e,this,s)}}s2.exports=qX});var c2=v((Ghe,u2)=>{function VX(e){return function(){return e}}u2.exports=VX});var p2=v((Whe,f2)=>{var GX=c2(),d2=Py(),WX=My(),zX=d2?function(e,t){return d2(e,"toString",{configurable:!0,enumerable:!1,value:GX(t),writable:!0})}:WX;f2.exports=zX});var h2=v((zhe,m2)=>{var jX=800,HX=16,KX=Date.now;function JX(e){var t=0,r=0;return function(){var n=KX(),i=HX-(n-r);if(r=n,i>0){if(++t>=jX)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}m2.exports=JX});var y2=v((jhe,g2)=>{var YX=p2(),QX=h2(),XX=QX(YX);g2.exports=XX});var v2=v((Hhe,b2)=>{var ZX=My(),eZ=l2(),tZ=y2();function rZ(e,t){return tZ(eZ(e,t,ZX),e+"")}b2.exports=rZ});var C2=v((Khe,w2)=>{var nZ=Vs(),iZ=Ku(),oZ=Jf(),aZ=Hi();function sZ(e,t,r){if(!aZ(r))return!1;var n=typeof t;return(n=="number"?iZ(r)&&oZ(t,r.length):n=="string"&&t in r)?nZ(r[t],e):!1}w2.exports=sZ});var Uy=v((Jhe,E2)=>{var lZ=v2(),uZ=C2();function cZ(e){return lZ(function(t,r){var n=-1,i=r.length,o=i>1?r[i-1]:void 0,a=i>2?r[2]:void 0;for(o=e.length>3&&typeof o=="function"?(i--,o):void 0,a&&uZ(r[0],r[1],a)&&(o=i<3?void 0:o,i=1),t=Object(t);++n<i;){var s=r[n];s&&e(t,s,n,o)}return t})}E2.exports=cZ});var S2=v((Yhe,A2)=>{var dZ=Fy(),fZ=Uy(),pZ=fZ(function(e,t,r,n){dZ(e,t,r,n)});A2.exports=pZ});var gn,Yu=k(()=>{"use strict";(function(e){e[e.NotLoaded=0]="NotLoaded",e[e.Initialized=1]="Initialized",e[e.ConfigsLoaded=2]="ConfigsLoaded",e[e.Error=3]="Error"})(gn||(gn={}))});function _2(e,t,r="PROD"){let n=i=>`ShellSettings_ECS_ClientCache_${e}_${N2.EcsConfigType[i]}_${r}`;return{getData:i=>{let o=t.getItem(n(i));return Promise.resolve(o?JSON.parse(o):void 0)},putData:(i,o)=>(t.setItem(n(i),JSON.stringify(o)),Promise.resolve())}}var N2,mZ,T2=k(()=>{"use strict";N2=Ce(fy()),mZ=Ce(dy());});var By,D2=k(()=>{"use strict";xf();By=Ru({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 O2,P2,R2,L2,qy,hZ,ep,I2,Vy=k(()=>{"use strict";O2=Ce(dy()),P2=Ce(UD()),R2=Ce(fy()),L2=Ce(aR()),qy=Ce(S2());Yu();T2();D2();hZ=60*1e3,ep=class{clientName;logger;ecsEndpoint;resolveLoadingPromise;loadingPromise=new Promise(t=>this.resolveLoadingPromise=t);_status=gn.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"?By.prodEcsEndpoint:By.integrationEcsEndpoint}client=new P2.default;init=async({clientVersion:t,getFilters:r,cacheStorage:n=O2.StorageHelper.transientWithGlobalFallback,updateIntervalInMinutes:i,overrideEcsInitParams:o})=>{this.client.telemetryEventAdded.subscribe(this.logger.logEvent),this.client.configUpdated.subscribe(this.handleConfigUpdated);let a=(async()=>{let s=await r();return this.logEvent("FeaturesClient/configRequested",{ecsClientName:this.clientName,filters:s}),s});try{await this.client.initialize({clientName:this.clientName,clientVersion:t??"1.0.0.0",configsToFetch:[R2.EcsConfigType.Default],hosts:[this.ecsEndpoint],initialAppActiveState:!0,getEcsParameters:a,databaseInterface:_2(this.clientName,n,this.endpointType),...o}),this.client.requestUpdate(),this._status===gn.NotLoaded&&(this._status=gn.Initialized)}catch(s){this._status=gn.Error,this.resolveLoadingPromise(),this.logEvent("FeaturesClient/initializationFailed",{ecsClientName:this.clientName,error:s},"Error")}i&&window.setInterval(()=>this.client.requestUpdate(),i*hZ)};getConfig=t=>{let r=this.getMergedClientConfigByTeamName(t.teamName),n=r?t.extractConfig(r):{};return(0,qy.default)({},t.fallback,n,t.override,I2)};getAllConfigs=()=>this.getMergedClientConfig();getAllConfigsByTeamName=t=>this.getMergedClientConfigByTeamName(t);requestConfigUpdate=()=>{this.client.requestUpdate()};subscribe=(t,r)=>{let n=this.getConfig(t),i=this.client.configUpdated.subscribe(()=>{let o=this.getConfig(t);(0,L2.default)(o,n)||(n={...o},r(o))});return{unsubscribe:()=>i.unsubscribe()}};waitUntilLoaded=async t=>{if(t!==void 0){let r,n=new Promise((i,o)=>{r=window.setTimeout(()=>{o(new Error("Timed out waiting for configuration to load"))},t)});await Promise.race([this.loadingPromise,n]),clearTimeout(r)}else await this.loadingPromise};overrideClientConfig(t){this.logger.logEvent("FeaturesClient/overrideClientConfig",{clientConfigOverride:t}),this.clientConfigOverride=t}undoClientConfigOverride(){this.clientConfigOverride=void 0,this.logger.logEvent("FeaturesClient/undoClientConfigOverride")}getMergedClientConfig=()=>(0,qy.default)({},this.client.getConfig()?.config,this.clientConfigOverride,I2);getMergedClientConfigByTeamName=t=>this.getMergedClientConfig()?.[t];handleConfigUpdated=()=>{let t=this.client.getConfig();if(t===void 0)return;this.resolveLoadingPromise(),this._status=gn.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})}},I2=(e,t)=>{if(Array.isArray(t))return t}});var $2=v((oge,k2)=>{"use strict";var gZ=()=>{let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e};k2.exports=gZ});var Gy=v((age,F2)=>{var Qu=new Proxy(function(){return Qu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Qu},apply:function(){return Qu},construct:function(){return{}}}),x2=function(){return Qu};Object.setPrototypeOf(x2,Qu);F2.exports=x2});var B2=v((sge,U2)=>{var Xu=new Proxy(function(){return Xu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Xu},apply:function(){return Xu},construct:function(){return{}}}),M2=function(){return Xu};Object.setPrototypeOf(M2,Xu);U2.exports=M2});var H2=v((lge,j2)=>{"use strict";var Wy=B2(),yZ={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},bZ={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},vZ={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},W2={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},zy={};zy[Wy.ForwardRef]=vZ;zy[Wy.Memo]=W2;function q2(e){return Wy.isMemo(e)?W2:zy[e.$$typeof]||yZ}var wZ=Object.defineProperty,CZ=Object.getOwnPropertyNames,V2=Object.getOwnPropertySymbols,EZ=Object.getOwnPropertyDescriptor,AZ=Object.getPrototypeOf,G2=Object.prototype;function z2(e,t,r){if(typeof t!="string"){if(G2){var n=AZ(t);n&&n!==G2&&z2(e,n,r)}var i=CZ(t);V2&&(i=i.concat(V2(t)));for(var o=q2(e),a=q2(t),s=0;s<i.length;++s){var l=i[s];if(!bZ[l]&&!(r&&r[l])&&!(a&&a[l])&&!(o&&o[l])){var u=EZ(t,l);try{wZ(e,l,u)}catch{}}}}return e}j2.exports=z2});function J2(e,t,r){let[n,i]=(0,Qs.useState)(e.getConfig(t));return(0,Qs.useEffect)(()=>{if(!r?.subscribe&&e.status===gn.ConfigsLoaded)return;let o=e.subscribe(t,a=>{i(a),r?.subscribe||o.unsubscribe()});return o?.unsubscribe},[]),n}function Y2(e){return function(t,r){return J2(e,t,r)}}function Q2(e,t,r,n){let i=o=>{let a=J2(e,t,n),s={...o,...a};return Qs.default.createElement(r,{...s})};return(0,K2.default)(i,r),i.displayName=`WithFeature(${r.name})`,i}function X2(e,t,r,n){return t.reduce((i,o)=>Q2(e,o,i,n),r)}function Z2(e){return function(t,r,n){return Q2(e,t,r,n)}}var K2,Qs,jy=k(()=>{"use strict";K2=Ce(H2()),Qs=Ce(Gy());Yu();});var t1=v((dge,e1)=>{var SZ=Fy(),NZ=Uy(),_Z=NZ(function(e,t,r){SZ(e,t,r)});e1.exports=_Z});var tp=v((fge,r1)=>{var TZ=Ea(),DZ=Lo(),IZ="[object Symbol]";function OZ(e){return typeof e=="symbol"||DZ(e)&&TZ(e)==IZ}r1.exports=OZ});var i1=v((pge,n1)=>{var PZ=Ro(),RZ=tp(),LZ=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,kZ=/^\w*$/;function $Z(e,t){if(PZ(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||RZ(e)?!0:kZ.test(e)||!LZ.test(e)||t!=null&&e in Object(t)}n1.exports=$Z});var s1=v((mge,a1)=>{var o1=jf(),xZ="Expected a function";function Hy(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(xZ);var r=function(){var n=arguments,i=t?t.apply(this,n):n[0],o=r.cache;if(o.has(i))return o.get(i);var a=e.apply(this,n);return r.cache=o.set(i,a)||o,a};return r.cache=new(Hy.Cache||o1),r}Hy.Cache=o1;a1.exports=Hy});var u1=v((hge,l1)=>{var FZ=s1(),MZ=500;function UZ(e){var t=FZ(e,function(n){return r.size===MZ&&r.clear(),n}),r=t.cache;return t}l1.exports=UZ});var d1=v((gge,c1)=>{var BZ=u1(),qZ=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,VZ=/\\(\\)?/g,GZ=BZ(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(qZ,function(r,n,i,o){t.push(i?o.replace(VZ,"$1"):n||r)}),t});c1.exports=GZ});var p1=v((yge,f1)=>{function WZ(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}f1.exports=WZ});var v1=v((bge,b1)=>{var m1=qu(),zZ=p1(),jZ=Ro(),HZ=tp(),KZ=1/0,h1=m1?m1.prototype:void 0,g1=h1?h1.toString:void 0;function y1(e){if(typeof e=="string")return e;if(jZ(e))return zZ(e,y1)+"";if(HZ(e))return g1?g1.call(e):"";var t=e+"";return t=="0"&&1/e==-KZ?"-0":t}b1.exports=y1});var C1=v((vge,w1)=>{var JZ=v1();function YZ(e){return e==null?"":JZ(e)}w1.exports=YZ});var A1=v((wge,E1)=>{var QZ=Ro(),XZ=i1(),ZZ=d1(),eee=C1();function tee(e,t){return QZ(e)?e:XZ(e,t)?[e]:ZZ(eee(e))}E1.exports=tee});var N1=v((Cge,S1)=>{var ree=tp(),nee=1/0;function iee(e){if(typeof e=="string"||ree(e))return e;var t=e+"";return t=="0"&&1/e==-nee?"-0":t}S1.exports=iee});var D1=v((Ege,T1)=>{var oee=$y(),aee=A1(),see=Jf(),_1=Hi(),lee=N1();function uee(e,t,r,n){if(!_1(e))return e;t=aee(t,e);for(var i=-1,o=t.length,a=o-1,s=e;s!=null&&++i<o;){var l=lee(t[i]),u=r;if(l==="__proto__"||l==="constructor"||l==="prototype")return e;if(i!=a){var c=s[l];u=n?n(c,l,s):void 0,u===void 0&&(u=_1(c)?c:see(t[i+1])?[]:{})}oee(s,l,u),s=s[l]}return e}T1.exports=uee});var O1=v((Age,I1)=>{var cee=D1();function dee(e,t,r){return e==null?e:cee(e,t,r)}I1.exports=dee});function k1(e){let{query:t}=(0,L1.default)(window.location.href,!0);return pee(e,t),e}function pee(e,t){let r=fee+e.clientName,n=Object.keys(t).filter(o=>o.startsWith(r));if(!n)return;let i={};n.forEach(o=>{let a=t[o];if(a)try{let s=JSON.parse(a),l=r+$1,u={};if(o===r)u=s;else if(o.startsWith(l)){let c=o.substring(l.length);(0,R1.default)(u,c,s)}(0,P1.default)(i,u)}catch{}}),Object.keys(i).length>0&&e.overrideClientConfig(i)}var P1,R1,L1,$1,fee,x1=k(()=>{"use strict";P1=Ce(t1()),R1=Ce(O1()),L1=Ce(Z0());$1=".",fee="ecs"+$1});function np(e,t,r){let n=k1(new ep(e,t,r));function i(o){(0,rp.useEffect)(()=>{n.init(o)},[])}return{featuresClient:n,createFeature:hee(n),useFeaturesClientInitParams:i,withFeatures:(o,a,s)=>X2(n,o,a,s)}}function hee(e){let t=Y2(e),r=Z2(e);return function(i){let o=kD(i);return o.getConfig=()=>e.getConfig(o),o.isLoaded=()=>e.status===gn.ConfigsLoaded,ry.register(o,e.clientName),{useFeature:a=>t(o,a),withFeature:(a,s)=>r(o,a,s),feature:o}}}var mee,rp,Ky=k(()=>{"use strict";mee=Ce($2()),rp=Ce(Gy());cy();Vy();Yu();jy();x1();ny();});var F1=k(()=>{"use strict";cy();Vy();Ky();Yu();jy();Bf();iy();});function ip(e){return{logEvent:(t,r,n)=>{switch(n){case"Error":(0,Xs.trackErrorTrace)(e,{eventName:t,eventData:r});break;case"Warning":(0,Xs.trackWarningTrace)(e,{eventName:t,eventData:r});break;default:(0,Xs.trackInfoTrace)(e,{eventName:t,eventData:r});break}}}}var Xs,Jy=k(()=>{"use strict";Xs=Ce(ya());});var Gge,Wge,zge,M1=k(()=>{"use strict";F1();Jy();({featuresClient:Gge,createFeature:Wge,useFeaturesClientInitParams:zge}=np("PowerApps-Shell-Test",ip("shell-features")))});var q1=v((Hge,B1)=>{var Zu=new Proxy(function(){return Zu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Zu},apply:function(){return Zu},construct:function(){return{}}}),U1=function(){return Zu};Object.setPrototypeOf(U1,Zu);B1.exports=U1});var gee,yee,V1=k(()=>{"use strict";Iu();gee=Ce(q1()),yee=Ce(ya());});var G1=k(()=>{"use strict";M1();Jy();V1();});var r0e,Zs,n0e,W1=k(()=>{"use strict";G1();Ky();({featuresClient:r0e,createFeature:Zs,useFeaturesClientInitParams:n0e}=np("PowerApps-MakerPortal",ip("powerapps-features")))});var z1,j1,s0e,l0e,u0e,c0e,Yy=k(()=>{"use strict";LD();W1();({feature:z1}=Zs({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:qs.enableAutoInsertionOfCellInRow}})),{feature:j1}=Zs({teamName:"MakerPortal",owners:["aansu"],description:"Enable the one grid events for form designer",createdOn:"08/21/2024",fallback:{enableOneGridEventsForFormDesigner:qs.enableOneGridEvents}}),{feature:s0e}=Zs({teamName:"MakerPortal",owners:["adekulkarni"],description:"Disables PBI components and cleans them up from the form",createdOn:"01/03/2023",fallback:{enableFallbackFormTemplate:qs.disablePBIComponents}}),{feature:l0e}=Zs({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:qs.enableAgentResponse}}),{feature:u0e,useFeature:c0e}=Zs({teamName:"MakerPortal",owners:["aansu"],description:"Enables delayed localization of custom control",createdOn:"06/08/2025",fallback:{enableDelayedLocalizationForCustomControls:qs.enableDelayedLocalizationForCustomControls}})});var J1=v((f0e,K1)=>{var ec=new Proxy(function(){return ec},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:ec},apply:function(){return ec},construct:function(){return{}}}),H1=function(){return ec};Object.setPrototypeOf(H1,ec);K1.exports=H1});var nr,ko=k(()=>{"use strict";vt();dt();rr();$u();le();kt();nr=class extends re{static HighestUsedIndexByClass=new Map;get colspan(){let t=this.getProperty(y.colspan);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}set colspan(t){R.IsNullOrUndefined(t)||this.setProperty(y.colspan,String(t))}constructor(t,r){super(t,r)}get id(){let t=this.getProperty(y.id);return t==null?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new U(t.substr(1,t.length-2)):new U(t)}set id(t){this.setProperty(y.id,`{${t.ToString()}}`)}set labelId(t){this.setProperty(y.labelId,`{${t.ToString()}}`)}get labelId(){let t=this.getProperty(y.labelId);return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new U(t.substr(1,t.length-2)):new U(t)}get Name(){return this.getProperty(y.Name)}set Name(t){this.setProperty(y.Name,t)}setDisplayName(t,r){for(let i of this.getAllLabels())if(+i.getProperty(y.languagecode)===r){i.setProperty(y.description,t);return}let n=new re(E.formLabel,null);n.setProperty(y.description,t),n.setProperty(y.languagecode,String(r)),this.addGrandChild("labels",n)}getDisplayName(t){for(let r of this.getAllLabels())if(+r.getProperty(y.languagecode)===t)return r.getProperty(y.description)}getAllLabels(){let t=this.getChildren("labels");return t.length!==1?[]:t[0].getChildren("label")}get isLocked(){return+this.getProperty(y.locklevel)==1}set isLocked(t){!this.IsUnboundControl&&this.setProperty(y.locklevel,t?"1":"0")}get availableforphone(){return this.getProcessedValue(y.availableforphone)}set availableforphone(t){R.IsNullOrUndefined(t)||!this.IsAllowedUBCForAvailableOnPhone()||this.setProperty(y.availableforphone,String(t))}get visible(){return this.getProcessedValue(y.visible)}set visible(t){R.IsNullOrUndefined(t)||!this.IsAllowedUBCForVisibleByDefault()||this.setProperty(y.visible,String(t))}isLockLevelSettable(){return!this.IsUnboundControl}get showlabel(){return this.getProcessedValue(y.showlabel)}set showlabel(t){R.IsNullOrUndefined(t)||this.setProperty(y.showlabel,String(t))}isAvailableForPhoneSettable(){return this.IsAllowedUBCForAvailableOnPhone()}isVisibleSettable(){return this.IsAllowedUBCForVisibleByDefault()}getProcessedValue(t){let r=this.getProperty(t);return R.IsNullOrUndefined(r)||this.getProperty(t)==="true"}get readonly(){let t=this.getFirstChild(E.formControl);return t?t.disabled:!1}set readonly(t){let r=this.getFirstChild(E.formControl);r&&(r.disabled=t)}get allowfilteroff(){let t=this.getFirstChild(E.formControl);if(t)return t.getParam(y.AllowFilterOff)==="true"}set allowfilteroff(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AllowFilterOff,t)}get autoresolve(){let t=this.getFirstChild(E.formControl);if(t)return t.getParam(y.AutoResolve)==="true"}set autoresolve(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AutoResolve,t)}get defaultviewid(){let t=this.getFirstChild(E.formControl);return t?t.getParam(y.DefaultViewId):q.EmptyString}set defaultviewid(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DefaultViewId,t)}get dependentattributename(){let t=this.getFirstChild(E.formControl);return t?t.getParam(y.DependentAttributeName):q.EmptyString}set dependentattributename(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DependentAttributeName,t)}get dependentattributetype(){let t=this.getFirstChild(E.formControl);return t?t.getParam(y.DependentAttributeType):q.EmptyString}set dependentattributetype(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DependentAttributeType,t)}get disablequickfind(){let t=this.getFirstChild(E.formControl);if(t)return t.getParam(y.DisableQuickFind)==="true"}set disablequickfind(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DisableQuickFind,t)}get disableviewpicker(){let t=this.getFirstChild(E.formControl);if(t)return t.getParam(y.DisableViewPicker)==="true"}set disableviewpicker(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DisableViewPicker,t)}get filterrelationshipname(){let t=this.getFirstChild(E.formControl);return t?t.getParam(y.FilterRelationshipName):q.EmptyString}set filterrelationshipname(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.FilterRelationshipName,t)}get availableviewids(){let t=this.getFirstChild(E.formControl);return t?t.getParam(y.AvailableViewIds):q.EmptyString}set availableviewids(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AvailableViewIds,t)}get IsUnboundControl(){let t=this.getFirstChild(E.formControl);if(t&&t.ClassId){let r=ft.getUniqueIdentifierForControl(t);return!R.IsNullOrUndefined(r)&&ft.isUnboundFormControlByIdentifier(r)}else return!1}IsAllowedUBCForAvailableOnPhone(){let t=this.getFirstChild(E.formControl);if(t){let n=ft.getUniqueIdentifierForControl(t).guidString,i=n===G.GridControl||n===G.TimeLineControl||n===G.TimeLineControlUC;return this.IsUnboundControl?i:!0}return this.NodeName===E.formSection||this.NodeName===E.formTab}IsAllowedUBCForVisibleByDefault(){let t=this.getFirstChild(E.formControl);if(t){let n=ft.getUniqueIdentifierForControl(t).guidString,i=n===G.MapsControl||n===G.WebResourceHtmlControl||n===G.WebResourceImageControl||n===G.IframeControl||n===G.SocialInsightControl;return this.IsUnboundControl?i:!0}else return!0}get events(){let t=this.getChildren(E.formEvents);return t.length===1?t[0].getAllChildren():[]}addEvent(t){this.addGrandChild(E.formEvents,t)}getUsedNodeNameSet(t){return null}getHighestIndexById(t,r){return null}}});var el,Qy=k(()=>{"use strict";rr();le();kt();el=class extends re{constructor(t,r){super(E.dependency,t),q.IsNullOrEmpty(r)||this.setDefaultProperties(r)}set id(t){this.setProperty(y.id,t)}get id(){return this.getProperty(y.id)}setDefaultProperties(t){this.id=t}}});var Y1,tl,Xy=k(()=>{"use strict";dt();Qy();le();kt();ko();(function(e){e[e.Form=0]="Form",e[e.Cell=1]="Cell",e[e.Tab=2]="Tab",e[e.Control=3]="Control"})(Y1||(Y1={}));tl=class extends nr{constructor(t,r){super(E.formEvent,t),r&&(this.eventName=r,this.application="false",this.active="false")}set eventName(t){this.setProperty(y.Name,t)}get eventName(){return this.getProperty(y.Name)}set application(t){this.setProperty(y.application,t)}get application(){return this.getProperty(y.application)}set attribute(t){this.setProperty(y.EventAttribute,t)}get attribute(){return this.getProperty(y.EventAttribute)}set relationship(t){this.setProperty(y.Relationship,t)}get relationship(){return this.getProperty(y.Relationship)}set control(t){this.setProperty(y.Control,t)}get control(){return this.getProperty(y.Control)}set active(t){this.setProperty(y.EventActive,t)}get active(){return this.getProperty(y.EventActive)}getAllHandlers(){let t=this.getChildren(E.EventHandlers);return t&&t.length?t[0].getChildren(E.handler):[]}getAllDependencies(){let t=this.getChildren(E.formDependencies);return t.length===0?[]:t[0].getAllChildren()}setDependencies(t){let r=this.getFirstChild(E.formDependencies);if(R.IsNullOrUndefined(r)){if(t.length===0)return;this.addChild(new re(E.formDependencies,this)),r=this.getFirstChild(E.formDependencies)}if(t.length===0)r.getParentNode().deleteChild(r);else{r.deleteAllChildren();for(let n of t)r.addChild(new el(r,n.toString()))}}}});var Fn,tc=k(()=>{"use strict";vt();su();dt();ga();le();kt();kn();Fn=class extends re{previewVersion;constructor(t){super(E.formControl,t)}updatePreview(){this.previewVersion=Date.now()}get ClassId(){let t=this.getProperty(y.classid);return t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t)}set ClassId(t){this.setProperty(y.classid,`{${t.ToString()}}`)}get dataFieldName(){return this.getProperty(y.datafieldname)}set dataFieldName(t){this.setProperty(y.datafieldname,t)}set id(t){this.setProperty(y.id,t)}get id(){return this.getProperty(y.id)}get UniqueId(){let t=this.getProperty(y.uniqueid);return R.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t))}set UniqueId(t){this.setProperty(y.uniqueid,`{${t.ToString()}}`)}get isRequired(){return this.getProperty(y.isRequired)==="true"}set isRequired(t){R.IsNullOrUndefined(t)||this.setProperty(y.isRequired,String(t))}get disableMru(){return this.getParam(y.DisableMru)==="true"}set disableMru(t){R.IsNullOrUndefined(t)||this.setParameter(y.DisableMru,t)}get useMFDForCreate(){return this.getParam(y.UseMFDForCreate)==="true"}set useMFDForCreate(t){R.IsNullOrUndefined(t)||this.setParameter(y.UseMFDForCreate,t)}get useMFDForEdit(){return this.getParam(y.UseMFDForEdit)==="true"}set useMFDForEdit(t){R.IsNullOrUndefined(t)||this.setParameter(y.UseMFDForEdit,t)}get disabled(){return this.getProperty(y.disabled)==="true"}set disabled(t){R.IsNullOrUndefined(t)||this.setProperty(y.disabled,String(t))}get indicationOfSubgrid(){return this.getProperty(y.indicationOfSubgrid)==="true"}set indicationOfSubgrid(t){this.setProperty(y.indicationOfSubgrid,String(t))}getAllParameters(){let t=new dr,r=this.getFirstChild(y.parameters);return r&&r.getAllChildren().forEach(n=>{if(n){let i=n.getAllChildren(),o=i&&i.length>0&&i[0];o&&t.add(n.getNodeName(),o.getNodeName())}}),t}setParameter(t,r){let n=!1;r===null&&(n=!0);let i=(ji.StartTag+r).toString(),o=this.parametersNode;if(o){let a=o.findFirst(s=>s&&s.getNodeName()===t);if(a)if(n){this.deleteFirstGrandChildOfName(E.controlParameters,a);return}else{let s=a.getAllChildren();s&&s.length>0&&s[0]?s[0].setNodeName(i):a.addChild(new re(i,a))}else n||(a=new re(t,o),a.addChild(new re(i,a)),o.addChild(a))}else if(!n){o=new re("parameters",this);let a=new re(t,o);a.addChild(new re(i,a)),o.addChild(a),this.addChild(o)}}getParam(t){if(this.parametersNode){let r=this.parametersNode.findFirst(n=>n&&n.getNodeName()===t);if(r){let n=r.getAllChildren(),i=n&&n.length>0&&n[0];if(i){let o=i.getNodeName();return o.charAt(0)===ji.StartTag?o.substring(1):o}}}return null}get parametersNode(){let t=this.getChildren(y.parameters);return t.length===0?null:t[0]}async serializeParameters(t,r){let n=new dr;switch(this.ClassId.guidString.toUpperCase()){case N.LookupControl:if(t&&t.getKeys())if(t.getKeys().forEach(a=>{n.add(a,this.getParam(a))}),t&&t.containsKey("DefaultViewId")){let a=this.getParam("DefaultViewId").replace("{","").replace("}","");n.upsert("DefaultViewId",a)}else{let a=this.getParent(),s=await r.formModelService.lookupControlService.populateDefaultView(this,a.getParentForm().entityName);s&&s.id&&n.upsert("DefaultViewId",s.id.replace("{","").replace("}",""))}break;default:t&&t.getKeys()&&t.getKeys().forEach(a=>{n.add(a,this.getParam(a))});break}let i=n.getInternalObject(),o=[];for(let a in i)i.hasOwnProperty(a)&&o.push({Name:a,Value:i[a]});return o}getIsUnbound(){return this.getProperty(y.isUnbound)==="true"}getAttributeTypeFromClassId(t){if(t)switch(t.toUpperCase()){case N.BooleanControl:case N.CheckboxControl:return 0;case N.DateTimeControl:return 2;case N.DecimalControl:return 3;case N.FloatingNumberControl:return 4;case N.IntegerControl:case N.DurationControl:case N.LanguageControl:case N.TimezoneControl:return 5;case N.LookupControl:return 6;case N.CurrencyControl:return 8;case N.PartyListControl:return 10;case N.ChoiceControl:case N.RelationshipRoleChoiceControl:return 11;case N.ChoiceStatusControl:return 13;case N.TextAreaControl:case N.TextboxControl:case N.LabelControl:case N.EmailAddressControl:case N.UrlControl:case N.TickerControl:case N.ButtonControl:case N.PhoneNumberControl:return 14;case N.ChoicesControl:return 24;default:return}return 14}async toJSON(t){let r=this.getParent(),n=t&&t.formModelService&&t.formModelService.getFormType()===wt.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 rl,Zy=k(()=>{"use strict";rr();oa();tc();le();kt();rl=class extends Fn{constructor(t){super(t)}get targetEntityType(){return this.getParam(y.targetEntityType)||q.EmptyString}set targetEntityType(t){this.setParameter(y.targetEntityType,t)}get viewId(){return q.StripBraces(this.getParam(y.viewId))||q.EmptyString}set viewId(t){this.setParameter(y.viewId,q.AddBraces(t))}get viewIds(){return this.getParam(y.viewIds)||q.EmptyString}set viewIds(t){this.setParameter(y.viewIds,t)}get relationshipName(){return this.getParam(y.RelationshipName)||q.EmptyString}set relationshipName(t){this.setParameter(y.RelationshipName,t)}get isUserView(){return q.IsStrictTrue(this.getParam(y.isUserView))}set isUserView(t){this.setParameter(y.isUserView,t.toString())}get enableViewPicker(){return q.IsStrictTrue(this.getParam(y.enableViewPicker))}set enableViewPicker(t){this.setParameter(y.enableViewPicker,t)}get autoExpand(){return this.getParent().autoexpand&&this.getParam(y.autoExpand)===y.Auto}set autoExpand(t){let r=this.getParent();this.setParameter(y.autoExpand,t?y.Auto:y.Fixed),r.autoexpand=t}get recordsPerPage(){return this.getParam(y.recordsPerPage)?Number(this.getParam(y.recordsPerPage)):Number(y.RecordsPerPageRAControlDefault)}set recordsPerPage(t){this.setParameter(y.recordsPerPage,String(t))}get enableQuickFind(){return q.IsStrictTrue(this.getParam(y.enableQuickFind))}set enableQuickFind(t){this.setParameter(y.enableQuickFind,t)}get teamTemplateId(){return q.StripBraces(this.getParam(y.teamTemplateId))||q.EmptyString}set teamTemplateId(t){this.setParameter(y.teamTemplateId,q.AddBraces(t))}get chartId(){return this.getParam(y.visualizationId)||q.EmptyString}set chartId(t){this.setParameter(y.visualizationId,t)}get enableChartPicker(){return q.IsStrictTrue(this.getParam(y.enableChartPicker))}set enableChartPicker(t){this.setParameter(y.enableChartPicker,t)}get chartGridMode(){switch(this.getParam(y.chartGridMode)){case hn.Chart:return hn.Chart;case hn.Grid:return hn.Grid;default:return hn.All}}set chartGridMode(t){this.setParameter(y.chartGridMode,t)}updateChartGridMode(t){t?this.chartGridMode=hn.Chart:this.chartGridMode=this.enableChartPicker?hn.All:hn.Grid}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case y.targetEntityType:n.getAllChildren()[0].setNodeName("<"+r.targetEntityType);break;case y.viewId:n.getAllChildren()[0].setNodeName("<"+q.AddBraces(r.viewId));break;case y.isUserView:n.getAllChildren()[0].setNodeName("<"+r.isUserView);break;case y.enableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.enableViewPicker);break;case y.RelationshipName:let i=n.getAllChildren(),o="<"+r.relationshipName;i.length?n.getAllChildren()[0].setNodeName(o):n.addChild(new re(o,n));break;default:break}}updateControlDescription(t){let r=t.getControlDescriptionByForControl(this.UniqueId);if(r){let n=r.customControls;for(let i=0;i<n.length;i++){let o=n[i].getParameters().get(Xt.dataset)?n[i].getParameters().get(Xt.dataset)[0]:null;if(o){let a=o.getAllChildren();this.updateDefaultProperties(a,this)}else{let a=n[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(a,this)}}}}}});var nl,eb=k(()=>{"use strict";rr();oa();tc();le();nl=class extends Fn{constructor(t){super(t)}get defaultViewId(){return q.StripBraces(this.getParam(y.DefaultViewId))||q.EmptyString}set defaultViewId(t){this.setParameter(y.DefaultViewId,q.AddBraces(t))}get autoResolve(){return q.IsStrictTrue(this.getParam(y.AutoResolve))}set autoResolve(t){this.setParameter(y.AutoResolve,t)}get disableQuickFind(){return q.IsStrictTrue(this.getParam(y.DisableQuickFind))}set disableQuickFind(t){this.setParameter(y.DisableQuickFind,t)}get disableViewPicker(){return q.IsStrictTrue(this.getParam(y.DisableViewPicker))}set disableViewPicker(t){this.setParameter(y.DisableViewPicker,t)}get allowFilterOff(){return q.IsStrictTrue(this.getParam(y.AllowFilterOff))}set allowFilterOff(t){this.setParameter(y.AllowFilterOff,t)}get disableMru(){return q.IsStrictTrue(this.getParam(y.DisableMru))}set disableMru(t){this.setParameter(y.DisableMru,t)}get dependentAttributeName(){return this.getParam(y.DependentAttributeName)||q.EmptyString}set dependentAttributeName(t){this.setParameter(y.DependentAttributeName,t)}get dependentAttributeType(){return this.getParam(y.DependentAttributeType)||q.EmptyString}set dependentAttributeType(t){this.setParameter(y.DependentAttributeType,t)}get filterRelationshipName(){return this.getParam(y.FilterRelationshipName)||q.EmptyString}set filterRelationshipName(t){this.setParameter(y.FilterRelationshipName,t)}get availableViewIds(){return this.getParam(y.AvailableViewIds)||q.EmptyString}set availableViewIds(t){this.setParameter(y.AvailableViewIds,t)}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case y.datafieldname:case y.bindAttribute:n.getAllChildren()[0].setNodeName("<"+r.dataFieldName);break;case y.DefaultViewId:n.getAllChildren()[0].setNodeName("<"+q.AddBraces(r.defaultViewId));break;case y.AllowFilterOff:n.getAllChildren()[0].setNodeName("<"+r.allowFilterOff);break;case y.DisableQuickFind:n.getAllChildren()[0].setNodeName("<"+r.disableQuickFind);break;case y.DisableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.disableViewPicker);break;case y.FilterRelationshipName:n.getAllChildren()[0].setNodeName("<"+r.filterRelationshipName);break;case y.DependentAttributeName:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeName);break;case y.DependentAttributeType:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeType);break;case y.AvailableViewIds:n.getAllChildren()[0].setNodeName("<"+r.availableViewIds);break;case y.DisableMru:n.getAllChildren()[0].setNodeName("<"+r.disableMru);break;case y.AutoResolve:n.getAllChildren()[0].setNodeName("<"+r.autoResolve);break;default:break}}updateControlDescription(t){let r=t.getControlDescriptionByForControl(this.UniqueId);if(r){let n=r.customControls;for(let i=0;i<n.length;i++){let o=n[i].getParameters().get(Xt.value)?n[i].getParameters().get(Xt.value)[0]:null;if(o){let a=o.getAllChildren();this.updateDefaultProperties(a,this)}else{let a=n[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(a,this)}}}}}});var Q1,tb,kr,rc=k(()=>{"use strict";Q1=Ce(J1());ko();le();dt();vt();Xy();tc();$u();ly();G0();kn();ga();Fs();Zy();eb();rb();vs();tb="_",kr=class e extends nr{fieldPlaceholder;fieldRequiredLevel;isNewField;cellColType;dependentFields=[];constructor(t){super(E.formCell,t),this.isNewField=!1}get cellType(){return this.cellColType}set cellType(t){this.cellColType=t}setDefaultProperties(t){this.showlabel=t,this.isLocked=!1,R.IsNullOrUndefined(this.getProperty(y.id))&&(this.id=new U(U.NewGuid()))}addControl(t,r,n,i,o,a,s){n instanceof Fn?this.addChild(n):n instanceof U&&this.addChild(this.getControlWithControlSpecificProperties(t,r,n,i,o,a,s))}removeControl(){return this.deleteChild(this.control)>=0}get isIndependent(){if(!R.IsNullOrUndefined(this.control))return R.IsNullOrUndefined(this.control.dataFieldName)?R.IsNullOrUndefined(this.control.id)?!0:!ba.dependencyFieldCount.containsKey(this.control.id):!ba.dependencyFieldCount.containsKey(this.control.dataFieldName)}createOnLoadEvent(){this.addEvent(new tl(this,Tu.onLoad))}get dependencies(){let t=this.getChildren(E.formEvents);for(let r of t){let n=r.getChildren(E.formEvent);for(let i of n)this.buildDependencyList(i,this.dependentFields)}return this.dependentFields}getNextAvailableControlName(t,r,n,i){let o;if(i&&Pf[i])o=Pf[i].replace(/ /g,tb)+tb;else{o="Control_";let u=new Error("Control class id does not exist or is undefined");(0,Q1.trackErrorTrace)(hr,{eventName:`${JT}/getNextAvailableControlName`},u)}let a="new_",s=this.getHighestIndexById(t,i)+1,l=`${o}${a}${s}`;for(;n.has(l);)s++,l=`${o}${a}${s}`;return l}getUnboundControlProperties(t){e.prototype.setProperty.call(t,y.isUnbound,"true"),e.prototype.setProperty.call(t,y.isRequired,"false")}getControlWithControlSpecificProperties(t,r,n,i,o,a,s){let l;o===yn.Grid?(l=new rl(this),l.indicationOfSubgrid=!0):o===yn.Lookup?l=new nl(this):l=new Fn(this);let u=n.guidString,c=a||this.getNextAvailableControlName(t,i,this.getUsedNodeNameSet(t),u);if(e.prototype.setProperty.call(l,y.id,c),l.ClassId=n,!R.IsNullOrUndefined(s)&&(l.UniqueId=s),!a&&r)this.getUnboundControlProperties(l);else{let d=ft.getUniqueIdentifierForControl(l);R.IsNullOrUndefined(d)||(ft.getControlDataTypeByControlOrUniqueId(d)===ee.QuickFormCollectionControl||!ft.isUnboundFormControlByIdentifier(d)?o!==yn.Grid&&a&&u!==N.IframeControl&&u!==N.SubgridControl&&u!==N.ReferencePanelSubgridControl&&(l.dataFieldName=a,e.prototype.setProperty.call(l,y.disabled,"false")):(this.rowspan=ft.GetRowSpan(l),(ft.getControlDataTypeByControlOrUniqueId(d)===ee.NotesControl||ft.getControlDataTypeByControlOrUniqueId(d)===ee.TimeLineControl)&&(e.prototype.setProperty.call(l,y.disabled,"false"),l.id=ee.NotesControl)),(ft.getUnboundControlNameFromIdentifier(n)===ee.SubGridControl||ft.getUnboundControlNameFromIdentifier(n)===ee.NotesControl||ft.getUnboundControlNameFromIdentifier(n)===ee.TimeLineControl)&&(this.availableforphone=!0))}return l}buildDependencyList(t,r){if(R.IsNullOrUndefined(t))return;let n=t.getAllChildren();for(let i of n){let o=i.getAllChildren();for(let a of o){let s=a.GetPropertyByParameter(y.id);a.getNodeName()===E.dependency&&s?r.push(s):this.buildDependencyList(a,r)}}}get control(){return this.getFirstChild(E.formControl)}set rowspan(t){this.setProperty(y.rowspan,String(t))}get rowspan(){let t=this.getProperty(y.rowspan);return R.IsNullOrUndefined(t)?1:parseInt(t,10)}set autoexpand(t){this.setProperty(y.auto,String(t))}get autoexpand(){return this.getProperty(y.auto)==="true"}set colspan(t){let r=Number(ay.ONE_COLUMN),n=Number(ay.FOUR_COLUMN);R.IsNullOrUndefined(t)||t>n||t<r||this.setProperty(y.colspan,String(t))}get colspan(){let t=this.getProperty(y.colspan);return R.IsNullOrUndefined(t)?1:parseInt(t,10)}getParentRow(){return this.getAncestor(E.formRow)}getParentSection(){return this.getAncestor(E.formSection)}getParentTab(){return this.getAncestor(E.formTab)}getParentForm(){return this.getAncestor(E.form)}isInHeader(){let t=this.getAncestor(E.formHeader);return!R.IsNullOrUndefined(t)}isInFooter(){let t=this.getAncestor(E.formFooter);return!R.IsNullOrUndefined(t)}isEmpty(){return R.IsNullOrUndefined(this.control)&&!this.IsUserSpacer}getHeaderFooter(){return this.isInHeader()?this.getAncestor(E.formHeader):this.isInFooter()?this.getAncestor(E.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(y.userspacer);return R.IsNullOrUndefined(t)?!1:t==="true"}SetUserSpacer(){this.setProperty(y.userspacer,"true")}ClearUserSpacer(){this.setProperty(y.userspacer,"false")}get columns(){let t=this.getProperty(y.columnName);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}getColumnLayoutValue(t){let r;switch(t){case je.TWO_COLUMN:r="11";break;case je.THREE_COLUMN:r="111";break;case je.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(!R.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();R.IsNullOrUndefined(t)||(t.autoExpandCell=this,t.tabContainsAutoExpandControl=!0)}isCellRequiredOrLocked(t,r,n){let i=this.getParentForm();if(this?.control){if(this.IsUserSpacer)return!1;{if(this.isLocked||r().has(this.control.dataFieldName))return!0;let o=i.isDuplicateCell(this,n),a=this.getRequiredLevel(t);if((a===yo.ApplicationRequired||a===yo.SystemRequired)&&!o||this.isCellLockedByExternal(t)&&!o)return!0}}return!1}getRequiredLevel(t){return!this.control?.dataFieldName||!this.control?.id||this.IsNewField||!this.control?.ClassId?yo.None:t.getEntityAttributeByName(this.control.dataFieldName)?.requiredLevel?.toString()??yo.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()===E.formCell){let i=n;i.control&&i!==this&&r.add(n.control.id)}return!1}),r}getHighestIndexById(t,r){let n=t.findAll(o=>o.getNodeName()===E.formCell&&o.control&&o.control.ClassId.guidString===r),i=0;return n.forEach(o=>{i=Math.max(this.parseControlNameIndex(o.control.id),i)}),i}parseControlNameIndex(t){let r=t.length-1,n=0;for(;r>0&&parseInt(t.charAt(r),10);)r--;return r>0&&r!==t.length-1&&t.charAt(r)===tb&&(r++,n=parseInt(t.substr(r,t.length-r),10)),n}}});var il,nb=k(()=>{"use strict";rr();le();kt();il=class extends re{isInternal;constructor(t,r,n,i){super(E.library,t),this.isInternal=!!i,q.IsNullOrEmpty(n)||(this.name=r,this.libraryUniqueId=n)}get libraryUniqueId(){let t=this.getProperty(y.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(y.libraryUniqueId,t)}get name(){return this.getProperty(y.libraryName)}set name(t){this.setProperty(y.libraryName,t)}get displayName(){return this.getProperty(y.displayName)}set displayName(t){this.setProperty(y.displayName,t)}get description(){return this.getProperty(y.description)}set description(t){this.setProperty(y.description,t)}}});var Sa,ib=k(()=>{"use strict";dt();rc();le();kt();Sa=class extends re{isRowAddedOnDragOver;constructor(t){super(E.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 R.IsNullOrUndefined(t)?!1:this.deleteChild(t)>=0}insertCellAtIndex(t,r){return R.IsNullOrUndefined(t)?!1:(this.insertChildAtIndex(t,r),!0)}isEmpty(){return!this.cells||this.cells.every(t=>t.isEmpty())}getParentSection(){return this.getAncestor(E.formSection)}insertPaddingCellAtIndex(t){let r=new kr(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(E.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 bee(e){switch(e){case va.Left:return Ca.Left;case va.Right:return Ca.Right;case va.Center:return Ca.Center;default:return Ca.Left}}function vee(e){switch(e){case Us.Left:return Bs.Left;case Us.Top:return Bs.Top;default:return Bs.Left}}function X1(e){switch(e){case 1:return 1;case 2:return 11;case 3:return 111;case 4:return 1111;default:return 1}}var wee,pi,nc=k(()=>{"use strict";uy();vt();dt();rr();Yy();rc();le();kn();ko();ib();wee=115,pi=class e extends nr{colSpan=1;constructor(t,r){super(t,r)}getSectionType(){let t;switch(this.columns){case 1:t=je.ONE_COLUMN;break;case 11:t=je.TWO_COLUMN;break;case 111:t=je.THREE_COLUMN;break;case 1111:t=je.FOUR_COLUMN;break;default:t=this.colSpan-1}return t}setUniqueName(){let t=this.getParentTab(),r=qe.namePrefix;if(t){let n=t.Name,i=t.TotalSectionsCount+1;r=n+qe.namePrefix+i.toString()}else r+=Math.floor(Math.random()*1e3);this.setProperty(y.Name,r)}initializeDefaultProperties(t,r,n){if(n===je.REFERENCE_PANEL){this.addProperty(y.rowheight,"25");let i=`${qe.referencePanelNamePrefix}${U.NewGuid()}${qe.namePrefix}`;this.addProperty(y.Name,i)}else this.setUniqueName();if(this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.IsUserDefined,qe.IsUserDefined),this.addProperty(y.locklevel,qe.LockLevel),this.addProperty(y.showlabel,qe.ShowLabel),this.addProperty(y.showbar,qe.ShowBar),this.addProperty(y.layout,qe.Layout),this.addProperty(y.Fieldlabelalignment,qe.labelAlignment),this.addProperty(y.Fieldlabelposition,qe.labelPosition),R.IsNullOrUndefined(n))this.addProperty(y.columnName,qe.columns);else{let i=this.getColumnLayoutValue(n);this.addProperty(y.columnName,i)}this.addProperty(y.LabelWidth,qe.LabelWidth),this.setDisplayName(r,t)}getColumnLayoutValue(t){let r;switch(t){case je.TWO_COLUMN:r="11";break;case je.THREE_COLUMN:r="111";break;case je.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 R.IsNullOrUndefined(this.columns)?t=this.ColSpan:this.columns.toString().split(q.EmptyString).forEach(r=>{t+=parseInt(r,10)}),t}get ColSpan(){return this.colSpan}initializeRow(t){if(t>0&&t<5){let r=new Sa(null);if(this.addGrandChild(E.formRows,r),z1.getConfig().enableAutoInsertionOfCellInRow)for(let n=0;n<t;n++){let i=new kr(r);i.setDefaultProperties(!1),r.addCell(i)}}}initialize(t,r,n){this.initializeDefaultProperties(t,r,n),n===je.REFERENCE_PANEL&&(n=je.ONE_COLUMN),this.initializeRow(n+1)}setColSpan(t){this.colSpan=t}appendRow(t){this.addGrandChild(E.formRows,t)}insertRowAtIndex(t,r){this.addGrandChildAtIndex(E.formRows,t,r)}insertRowsAtIndex(t,r){if(t&&t.length>0)for(let n=0;n<t.length;n++)this.addGrandChildAtIndex(E.formRows,t[n],r+n)}indexOfRow(t){return this.rows.indexOf(t)}deleteRow(t){return this.deleteFirstGrandChildOfName(E.formRows,t)}deleteRows(t,r){this.deleteGrandChildren(E.formRows,t,r)}get rows(){return this.getRows()}getRows(){let t=this.getChildren(E.formRows);return t.length===0?[]:t[0].getChildren(E.formRow)}get columns(){let t=this.getProperty(y.columnName),r=R.IsNullOrUndefined(t)?NaN:parseInt(t,10);if(isNaN(r)){let n=1;for(let i of this.rows)n=Math.max(n,i.cells.length);return X1(n)}return r}set columns(t){R.IsNullOrUndefined(t)||this.setProperty(y.columnName,String(t))}get rowHeight(){let t=this.getProperty(y.rowheight);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}set rowHeight(t){this.setProperty(y.rowheight,String(t))}set autoexpand(t){this.setProperty(y.autoExpand.toLowerCase(),String(t))}get autoexpand(){return this.getProperty(y.autoExpand.toLowerCase())==="true"}get isUserDefined(){return+this.getProperty(y.IsUserDefined)!=0}set isUserDefined(t){t?this.setProperty(y.IsUserDefined,"1"):this.setProperty(y.IsUserDefined,"0")}getParentColumn(){return this.getAncestor(E.formColumn)}getParentTab(){return this.getAncestor(E.formTab)}get hasMultiColumnRow(){return this.getColumnCountValue()>1}get showlabel(){return this.getProperty(y.showlabel)==="true"}set showlabel(t){R.IsNullOrUndefined(t)||this.setProperty(y.showlabel,String(t))}get fieldLabelAlignment(){let t=qe.labelAlignment,r=this.getProperty(y.Fieldlabelalignment);return R.IsNullOrUndefined(r)?t:r}set fieldLabelAlignment(t){R.IsNullOrUndefined(t)||this.setProperty(y.Fieldlabelalignment,t)}get fieldLabelPosition(){let t=this.getProperty(y.Fieldlabelposition);return R.IsNullOrUndefined(t)?qe.labelPosition:t}set fieldLabelPosition(t){R.IsNullOrUndefined(t)||this.setProperty(y.Fieldlabelposition,String(t))}get showbar(){return this.getProperty(y.showbar)==="true"}set showbar(t){R.IsNullOrUndefined(t)||this.setProperty(y.showbar,String(t))}get labelwidth(){let t=+this.getProperty(y.LabelWidth);return t===0?wee:t}set labelwidth(t){R.IsNullOrUndefined(t)||t>283&&t<57||this.setProperty(y.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:bee(this.fieldLabelAlignment),Position:vee(this.fieldLabelPosition)},Columns:X1(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()===E.formSection){let i=n;i.Name&&!q.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}isReferencePanelSection(){return!R.IsNullOrUndefined(this)&&!R.IsNullOrUndefined(this.Name)&&this.Name.indexOf(qe.referencePanelNamePrefix)===0}getAllMultiRowCells(){return this.findAll(t=>{if(t.getNodeName()===E.formCell){let r=t;return!r.isEmpty()&&r.rowspan>1}return!1})}isHeaderOrFooterSection(){return this.NodeName===E.formFooter||this.NodeName===E.formHeader}}});var $o,op=k(()=>{"use strict";le();kt();nc();$o=class e extends re{constructor(t){super(E.formColumn,t)}initializeDefaultProperties(t){this.addProperty(y.width,t.toString()+"%")}insertSectionAtIndex(t,r){this.addGrandChildAtIndex(E.formSections,t,r)}static createAndInitNewSection(t,r,n){let i=new pi(E.formSection,null);return i.initialize(t,r,n),i}addSectionAtIndex(t,r){this.addGrandChildAtIndex(E.formSections,t,r)}initialize(t,r,n,i=je.ONE_COLUMN){this.initializeDefaultProperties(t);let o=e.createAndInitNewSection(r,n,i);this.addSectionAtIndex(o,this.sections.length),o.setUniqueName()}get parentTab(){return this.getAncestor(E.formTab)}get sections(){let t=this.getChildren("sections");return t.length!==1?[]:t[0].getChildren(E.formSection)}get width(){return this.getProperty(y.width)}set width(t){this.setProperty(y.width,t)}deleteSection(t){return this.deleteFirstGrandChildOfName(E.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(y.Name),Id:this.getProperty(y.id),Label:null,ShowLabel:!1,Visible:!0,LabelId:null,PreviewId:this.getProperty(y.id),Sections:await this.getSectionsJSON(t),Width:this.width}}}});var ap,Z1=k(()=>{"use strict";vt();le();kn();nc();ap=class extends pi{initializeNavArea(t,r,n){this.initializeNavAreaProps(t,r,n)}get AreaName(){return this.Name}initializeNavAreaProps(t,r,n){this.addProperty(y.Name,n),this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.columnName,qe.columns),this.setDisplayName(r,t)}}});var sp,eL=k(()=>{"use strict";op();le();Z1();sp=class extends $o{addAndIntializeNavBarSection(t,r,n,i){let o=new ap(E.formSection,null);return o.initializeNavArea(t,r,i),this.addGrandChildAtIndex(E.formSections,o,n),o}}});var Ki,lp=k(()=>{"use strict";vt();dt();rr();op();le();kt();ko();Ki=class extends nr{tabContainsAutoExpandControl;autoExpandCell;constructor(t,r){super(E.formTab,t),this.tabContainsAutoExpandControl=!1}getParentForm(){return this.getAncestor(E.form)}getTabLayoutType(){let t;switch(this.columns.length){case 1:t=ze.ONE_COLUMN;break;case 2:if(parseInt(this.columns[0].width,10)===50&&parseInt(this.columns[1].width,10)===50){t=ze.TWO_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===67&&parseInt(this.columns[1].width,10)===33){t=ze.TWO_COLUMN_WIDER_LEFT;break}if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===66){t=ze.TWO_COLUMN_WIDER_RIGHT;break}t=ze.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=ze.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=ze.THREE_COLUMN_WIDER_MID;break}t=ze.THREE_COLUMN_CUSTOM_LAYOUT;break;default:}return t}initializeProperties(t,r,n){this.addProperty(y.Name,Io.namePrefix+t.toString()),this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.IsUserDefined,Io.IsUserDefined),this.addProperty(y.locklevel,Io.LockLevel),this.addProperty(y.showlabel,Io.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=je.ONE_COLUMN,o=!0,a){let s=this.getChildren(E.formColumns)[0],l=[];switch(t){case ze.ONE_COLUMN:l.push(100);break;case ze.TWO_COLUMN_EQUAL:l.push(50),l.push(50);break;case ze.TWO_COLUMN_WIDER_LEFT:l.push(67),l.push(33);break;case ze.TWO_COLUMN_WIDER_RIGHT:l.push(34),l.push(66);break;case ze.THREE_COLUMN_EQUAL:l.push(34),l.push(33),l.push(33);break;case ze.THREE_COLUMN_WIDER_MID:l.push(28),l.push(44),l.push(28);break;default:}for(let u of l){let c=new $o(s);c.initialize(u,r,n,i),this.addGrandChild(E.formColumns,c)}}initialize(t,r,n,i,o,a=je.ONE_COLUMN,s=!0,l){this.addChild(new re(E.formColumns,this)),this.initializeProperties(r,n,i),this.initializeColumns(t,n,o,a,s,l)}get columns(){let t=this.getChildren(E.formColumns);return t.length!==1?[]:t[0].getChildren(E.formColumn)}get expanded(){return this.getProcessedValue(y.expanded)}set expanded(t){R.IsNullOrUndefined(t)||this.setProperty(y.expanded,String(t))}get groupName(){return this.getProperty(y.groupName)}get contentType(){return this.getProperty(y.contentType)}set contentType(t){this.setProperty(y.contentType,t)}insertNewColumnAtIndex(t,r,n,i,o){t.initialize(n,i,o),this.addGrandChildAtIndex(E.formColumns,t,r)}insertColumnAtIndex(t,r){this.addGrandChildAtIndex(E.formColumns,t,r)}deleteColumn(t){return this.deleteFirstGrandChildOfName(E.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()===E.formTab){let i=n;i.Name&&!q.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}}});var Na,ob=k(()=>{"use strict";vt();le();kt();kn();eL();lp();Na=class extends Ki{constructor(t,r,n){super(t,ze.THREE_COLUMN_EQUAL),this.setDisplayName(r,n),this.id=new U(U.NewGuid())}initializeDefaultProps(){this.addChild(new re(E.formColumns,this)),this.initializeFiveColumns()}get columns(){let t=this.getChildren("columns");return t.length!==1?[]:t[0].getChildren(E.formColumn)}getNavSectionForArea(t){for(let r of this.columns)for(let n of r.sections)if(n.AreaName===t)return n;return null}getNavCellFromNavId(t){for(let r of this.columns)for(let n of r.sections)for(let i of n.rows)for(let o of i.cells)if(o.NavId===t)return o;return null}initializeFiveColumns(){for(let t=0;t<qf.FIVE_COLUMN;t++){let r=new sp(this.getChildren(E.formColumns)[0]);r.initializeDefaultProperties(wD.FiveEqColumn),this.addGrandChild(E.formColumns,r)}}}});function Eee(e){switch(e){case wt.Main:return Oo.Main;case wt.QuickCreate:return Oo.QuickCreate;case wt.QuickViewForm:return Oo.Quick;case wt.Dialog:return Oo.Dialog;default:return Oo.None}}function Aee(e,t){if(t===wt.Main){if(e)switch(e.toLowerCase()){case"low":return Do.Low;case"highreadonlyvalues":return Do.HighReadOnlyValues;default:return Do.HighWithControls}return Do.Low}}var cp,Cee,up,tL=k(()=>{"use strict";DD();cp=Ce(ya());uy();dt();rr();Fs();Yy();le();oa();O0();ga();rc();le();ko();nb();ob();lp();Cee="1920";up=class e extends nr{_formUniqueName;isHeaderDefaulted;consistencyStrong=!1;_formId;_rawFormXml;_entityName;_entityDisplayName;_status;_formName;_langCode;_description;_formType;_formPresentation;parameters=[];_formactivationstate;_changeTracker;_metadataChangeEvent;_etag;constructor(t,r,n,i,o,a,s,l,u){super(E.form,null),this._formUniqueName=o,this._formId=t,this._entityName=r,this._status=n,this._formName=i,this._description=l,this._formType=a,this._formPresentation=s,this._formactivationstate=u,this._changeTracker=new Tf,this._metadataChangeEvent=new Gf}get FormLibraries(){let t=this.getFirstChild(E.formLibraries),r=t?t.getAllChildren():[],n=this._getInternalLibraries();return r.concat(n)}getAllEvents(){let t=[],r=this.events;r&&(t=t.concat(r));for(let n of this.tabs){let i=n.events;i&&(t=t.concat(i)),n.findAll(o=>o instanceof kr).forEach(o=>{let a=o.events;a&&(t=t.concat(a))})}return t}getEventsForNode(t){if(t instanceof e){let r=t.events;return r?r.filter(n=>!n.control&&!n.attribute):null}else if(t instanceof kr){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()===E.internalLibraries),r=[],n="src";return t.length>0&&(r=t.map(i=>{let o=i.GetPropertyByParameter(n).replace("$webresource:",""),a=new il(void 0,void 0,"",!0);return a.name=o,a.displayName=o,a})),r}getDependentFields(){let t=this.getAllEvents(),r=new Set;return t.forEach(n=>{try{n.getAllDependencies().forEach(o=>{r.add(o.id)})}catch(i){throw(0,cp.trackErrorTrace)(YT,{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 q.IsNullOrEmpty(this.getProperty(y.ShowImage))?!0:this.getProperty(y.ShowImage)!=="false"}set ShowImagecheck(t){t?this.setProperty(y.ShowImage,String(t)):this.setProperty(y.ShowImage,"false")}get ShowNavigation(){return q.IsNullOrEmpty(this.getProperty(y.ShowNavigationbar))?!0:this.getProperty(y.ShowNavigationbar)!=="false"}set ShowNavigation(t){t?this.setProperty(y.ShowNavigationbar,String(t)):this.setProperty(y.ShowNavigationbar,"false")}get MaxWidth(){return q.IsNullOrEmpty(this.getProperty(y.MaxWidth))?Cee:this.getProperty(y.MaxWidth)}set MaxWidth(t){this.setProperty(y.MaxWidth,t)}get headerDensityType(){return this.getProperty(y.HeaderDensityType)}set headerDensityType(t){t&&this.formType===wt.Main?this.setProperty(y.HeaderDensityType,t):this.formType!==wt.Main&&this.headerDensityType&&this.removeProperty(y.HeaderDensityType)}IsMainOrQuickCreateForm(){return this.formType===wt.Main||this.formType===wt.QuickCreate}get FormPresentation(){return this._formPresentation}get LanguageCode(){return this._langCode}set LanguageCode(t){this._langCode=t}get header(){let t=this.getChildren(E.formHeader);return t.length!==1?null:t[0]}set header(t){R.IsNullOrUndefined(t)||(this.deleteChild(this.header),this.addChild(t))}getAllDependencies(){return this.getChildren(E.quickFormDependencies).length===0?[]:this.ConvertModelToArray(this.getChildren(E.quickFormDependencies)[0].getAllChildren())}ConvertModelToArray(t){let r=[];return R.IsNullOrUndefined(t)||t.forEach(n=>{r.push(n.id)}),r}get footer(){let t=this.getChildren(E.formFooter);return t.length!==1?null:t[0]}set footer(t){R.IsNullOrUndefined(t)||(this.deleteChild(this.footer),this.addChild(t))}createAndInitNewTab(t,r,n){let i=new Ki(null,t),o=this.getNextTabCounter(this.tabs.length+1);return i.initialize(t,o,this.LanguageCode,r,n),i}addTabAtIndex(t,r){this.addGrandChildAtIndex(E.formTabs,t,r)}createAndInitNewTabWithMarginalControl(t,r,n,i,o){let a=new Ki(null,ze.ONE_COLUMN),s=this.getNextTabCounter(this.tabs.length+1);a.initialize(ze.ONE_COLUMN,s,this.LanguageCode,r,n,o,!1),this.addGrandChildAtIndex(E.formTabs,a,i);let l=a.columns[0].sections[0];for(let u=0;u<t.rows.length;u++)l.appendRow(t.rows[u])}getNextTabCounter(t){for(let r=0;r<this.tabs.length;r++)if(this.tabs[r].Name===Io.namePrefix+t.toString())return this.getNextTabCounter(t+1);return t}get allTabs(){let t=this.getChildren(E.formTabs);return t.length!==1?[]:t[0].getChildren(E.formTab)}get CanvasNavigationTab(){if(this.tabs.length>0){let t=this.tabs[this.tabs.length-1];if(t instanceof Na)return t}return null}get NavigationNode(){let t=this.getChildren(E.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(E.formTabs,t)}insertTabAtIndex(t,r){this.addGrandChildAtIndex(E.formTabs,t,r)}insertRelatedTab(t){let r=this.getAllGrandChildren(E.formTabs);if(!R.IsNullOrUndefined(r)){let n=r.length;this.insertTabAtIndex(t,n)}}get isfooterPresent(){return this.getChildren(E.formFooter).length>0}get displayCondition(){let t=this.getChildren(E.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(E.formTabs).indexOf(t)}get ControlDescriptions(){return this.getAllGrandChildren(E.controlDescriptions)}addControlDescriptionNode(t){this.addGrandChild(E.controlDescriptions,t)}deleteControlDescByForControlId(t){let r=this.getControlDescriptionByForControl(t);R.IsNullOrUndefined(r)||this.deleteFirstGrandChildOfName(E.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 kr))return!1;let o=!0;return r==="Tab"?o=i.getParentTab()!==t.getParentTab():r==="Section"?o=i.getParentSection()!==t.getParentSection():o=i!==t,i instanceof kr&&i.control&&t.control&&o&&i.control.dataFieldName===t.control.dataFieldName})}isCellEditableGridControl(t){return!t?.control?.indicationOfSubgrid||t.control.ClassId.guidString.toUpperCase()!==N.CustomControl?!1:this.cellHasCustomControlWithName(t,Mi.EditableGridControl)||j1.getConfig()?.enableOneGridEventsForFormDesigner&&this.cellHasCustomControlWithName(t,Mi.PowerAppsOneGrid)}isCellCanvasAppControl(t){return t?.control?.ClassId.guidString.toUpperCase()===N.CustomControl&&this.cellHasCustomControlWithName(t,Mi.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()===E.formCell){let i=n;return i&&i.control&&i.control.ClassId.guidString===t}return!1}):null}async getTabsJSON(t){let r=this.tabs,n=[],i=[];if(r){for(let o of r)if(!(o instanceof Na)){let a=o.toJSON(t);n.push(a)}for(let o of n)i.push(await o)}return i}async getControlDescriptionsToJSON(t){let r=[];for(let n of this.ControlDescriptions){let i=await n.toJSON(t);i&&r.push(i)}return r}async toJSON(t){let r=[];r=await this.getControlDescriptionsToJSON(t);let n=this.NavigationNode&&await this.NavigationNode.toJSON(t);return{Id:this._formId.guidString,Name:this.formName,Label:this.getDisplayName(t.langCode),ShowLabel:this.showlabel,Visible:this.visible,LabelId:this.labelId&&this.labelId.guidString,PreviewId:this._formId.guidString,PreviewSessionId:(0,cp.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===wt.Main?{HeaderDensity:Aee(this.headerDensityType,this.formType)}:{},InlineEditGridRow:[],InlineQuickForms:[],QuickFormEntities:[],EventHandlers:[],LinkControlSections:[],FormType:Eee(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 dp,ab,rL=k(()=>{"use strict";vt();dt();le();kt();ko();dp=class extends nr{constructor(t){super(E.formDisplayConditions,t)}get Order(){let t=this.getProperty(y.Order);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}set Order(t){this.setProperty(y.Order,t.toString())}get FallbackForm(){return this.getProperty(y.FallbackForm)==="true"}set FallbackForm(t){this.setProperty(y.FallbackForm,t.toString())}addRoles(t){this.deleteAllChildren();for(let r=0;r<t.length;r++)this.addChild(t[r])}isRoleEveryone(){return!!(this.getChildren(E.formEveryOne)&&this.getChildren(E.formEveryOne)[0])}setRoleEveryone(){this.deleteAllChildren(),this.addChild(new ab(this))}},ab=class extends re{constructor(t){super(E.formEveryOne,t)}}});var fp,nL=k(()=>{"use strict";le();kt();fp=class extends re{constructor(t,r){super(E.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(y.HandlerUniqueId)}set HandlerUniqueID(t){this.setProperty(y.HandlerUniqueId,t)}get FunctionName(){return this.getProperty(y.functionName)}set FunctionName(t){this.setProperty(y.functionName,t)}get LibraryName(){return this.getProperty(y.libraryNameEventHandler)}set LibraryName(t){this.setProperty(y.libraryNameEventHandler,t)}get Enabled(){return this.getProperty(y.enabledForField)}set Enabled(t){this.setProperty(y.enabledForField,t)}get PassExecutionContext(){return this.getProperty(y.passExecutionContext)}set PassExecutionContext(t){this.setProperty(y.passExecutionContext,t)}get Parameters(){return this.getProperty(y.parameters)}set Parameters(t){this.setProperty(y.parameters,t)}}});var ol,sb=k(()=>{"use strict";le();nc();ol=class extends pi{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(E.formCell);for(let o of i)r.push(o)}}return r}get occupiedCells(){return this.cells.filter(t=>!t.isEmpty())}get maxColumns(){return super.getColumnCountValue()}}});var ic,iL=k(()=>{"use strict";le();sb();ic=class extends ol{_customFooter;constructor(t,r){super(E.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 oc,oL=k(()=>{"use strict";le();sb();oc=class extends ol{_customHeader;constructor(t,r){super(E.formHeader,t),this._customHeader=r}get customHeader(){return this._customHeader}set customHeader(t){this._customHeader=t}get showCommandBar(){return this.getProcessedValue(y.showCommandBar)}set showCommandBar(t){t!=null&&this.setProperty(y.showCommandBar,String(t))}get showBody(){return this.getProcessedValue(y.showBody)}set showBody(t){t!=null&&this.setProperty(y.showBody,String(t))}get showTabNavigator(){return this.getProcessedValue(y.showTabNavigator)}set showTabNavigator(t){t!=null&&this.setProperty(y.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 $r,_a=k(()=>{"use strict";vt();rr();le();ko();$r=class e extends nr{constructor(t,r){super(t,r)}getTitle(t){for(let r of this.getAllTitles())if(+r.getProperty(y.LCID)===t)return r.getProperty(y.text);return null}getAllTitles(){let t=this.getChildren(E.Titles);return t.length===0?[]:t[0].getChildren(E.Title)}setTitle(t,r){for(let i of this.getAllTitles())if(+i.getProperty(y.LCID)===r){i.setProperty(y.text,t);return}let n=new e(E.Title,null);n.setProperty(y.text,t),n.setProperty(y.LCID,String(r)),this.addGrandChild(E.Titles,n)}get Sequence(){return+this.getProperty(y.Sequence)}set Sequence(t){this.setProperty(y.Sequence,t.toString())}get Area(){return this.getProperty(y.Area)}set Area(t){this.setProperty(y.Area,t)}set Id(t){this.setProperty(y.Id,t)}get Id(){return this.getProperty(y.Id)}get id(){return new U(this.Id??"",!0)}set id(t){this.Id=t.guidString}get Show(){return!0}get Icon(){return this.getProperty(y.icon)}set Icon(t){t=t||q.EmptyString,this.setProperty(y.icon,t)}updateCommonProperties(t,r){this.Area=t.Area,this.Sequence=t.Sequence,this.setTitle(t.getDisplayName(r),r)}}});var ac,aL=k(()=>{"use strict";(function(e){e[e.NavLinkNotAvailable=-1]="NavLinkNotAvailable",e[e.NavLinkIdConflict=-2]="NavLinkIdConflict",e[e.NavBarNotAvailable=-3]="NavBarNotAvailable"})(ac||(ac={}))});var pp,sL=k(()=>{"use strict";dt();le();_a();aL();pp=class extends $r{constructor(t){super(E.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 R.IsNullOrUndefined(r)?ac.NavLinkNotAvailable:r.length===1?this.deleteChild(r[0]):ac.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 Fe,See,lL,tve,al,lb=k(()=>{"use strict";vt();le();_a();(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"})(Fe||(Fe={}));See=new Map([[Fe.Info,"Info"],[Fe.Sales,"Sales"],[Fe.Service,"Service"],[Fe.Marketing,"Marketing"],[Fe.ProcessCenter,"ProcessCenter"]]),lL=new Map([["Info",Fe.Info],["Sales",Fe.Sales],["Service",Fe.Service],["Marketing",Fe.Marketing],["ProcessCenter",Fe.ProcessCenter]]),tve=new Map([[Fe.Info,9e3],[Fe.Sales,9200],[Fe.Service,9400],[Fe.Marketing,9600],[Fe.ProcessCenter,9800],[Fe.InternetMarketing,1e4],[Fe.Async,10200]]),al=class extends $r{constructor(t,r){super(E.formNavBarArea,r)}setDefaultPropertiesByType(t,r,n){this.AreaId=See.get(t);let i=n?.(`navBarArea.title.${this.AreaId}`)??this.AreaId;this.setTitle(i,r)}get ParentNavigation(){return this.getAncestor(E.formNavigation)}get AreaId(){return this.getProperty(y.Id)}set AreaId(t){this.setProperty(y.Id,t)}get id(){return new U(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 sl,ub=k(()=>{"use strict";le();_a();sl=class extends $r{constructor(t,r){super(E.formNavBarAreas,r)}get AllNavBarAreaItems(){return this.getChildren(E.formNavBarArea)}get ParentNavigation(){return this.getAncestor(E.formNavigation)}addNavBarArea(t){this.addChild(t)}}});var mp,uL=k(()=>{"use strict";dt();le();_a();mp=class extends $r{RelationshipNameUCIRuntime;constructor(t){super(E.formNavBarByRelationshipItem,t)}get RelationshipName(){return this.getProperty(y.RelationshipName)}set RelationshipName(t){this.setProperty(y.RelationshipName,t)}set Show(t){this.setProperty(y.Show,String(t))}get Show(){let t=this.getProperty(y.Show);return R.IsNullOrUndefined(t)||t==="true"}get TitleResourceId(){return this.getProperty(y.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 hp,cL=k(()=>{"use strict";le();_a();hp=class extends $r{constructor(t){super(E.formNavBarItem,t)}get Url(){return this.getProperty(y.url)}set Url(t){this.setProperty(y.url,t)}}});var gp,dL=k(()=>{"use strict";vt();le();lb();ub();_a();gp=class extends $r{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(E.formNavBarAreas)}setDefaultNavBarAreas(t,r){let n=[Fe.Info,Fe.Sales,Fe.Service,Fe.Marketing,Fe.ProcessCenter];if(this.navBarAreas){let i=this.navBarAreas?.AllNavBarAreaItems;if(i&&i.length>0){let o=new Set(i.map(a=>lL.get(a.AreaId)));n=n.filter(a=>!o.has(a))}}else{let i=new sl(E.formNavBarAreas,this);i.isTransient=!0,this.addChild(i)}return n.length>0?(n.forEach(i=>{let o=new al(E.formNavBarArea,this.navBarAreas);o.setDefaultPropertiesByType(i,t,r),this.navBarAreas.addNavBarArea(o)}),!0):!1}get navBar(){return this.getFirstChild(E.formNavBar)}get id(){return new U(V0,!0)}replaceNavAreaToGivenIndex(t,r){this.navBarAreas?.AllNavBarAreaItems.indexOf(r)!==-1&&(this.deleteFirstGrandChildOfName(E.formNavBarAreas,r),this.addGrandChildAtIndex(E.formNavBarAreas,r,t))}async getNavBarAreasJSON(t){let r=[],n=[];if(this.navBarAreas?.AllNavBarAreaItems){for(let o of this.navBarAreas.AllNavBarAreaItems)n.push(o.toJSON(t));r=await Promise.all(n)}return r}async getNavBarRelationshipItemsJSON(t){let r=[],n=[];if(this.navBar?.AllRelationShipItems){for(let i of this.navBar.AllRelationShipItems)n.push(i.toJSON(t));r=await Promise.all(n)}return r}async toJSON(t){let r=await this.getNavBarAreasJSON(t),n=await this.getNavBarRelationshipItemsJSON(t);return{NavBarAreas:{NavBarAreas:r},NavBarByRelationshipItems:n,NavBarItems:[],NavPaneIsvItems:{NavBarIsvItems:[]},ShowEmptyNavBarAreas:t.formModelService.showHiddenElements}}}});var fL={};nn(fL,{ControlType:()=>yn,DeserializationService:()=>fb,DeserializationServiceScope:()=>db,DeserializedFormElementNode:()=>xr});var cb,xr,db,yn,fb,rb=k(()=>{"use strict";cb=Ce(ya());vt();dt();rr();Fs();G0();ga();QT();_D();$u();tL();rc();op();tc();Qy();le();le();rL();kt();kn();Xy();nL();iL();Zy();eb();oL();nb();ib();nc();lp();sL();lb();ub();uL();cL();dL();xr=class extends re{constructor(t,r){super(t,r)}insertProperty(t,r){this.addProperty(t,r)}insertChild(t){this.addChild(t)}},db="DeserializationService";(function(e){e.Grid="Grid",e.Lookup="Lookup",e.Base="Base"})(yn||(yn={}));fb=class{lcid;constructor(t){this.lcid=t}deSerializeFormXml(t,r,n,i,o,a,s,l,u,c){if(!t)throw new Error("Formxml could not be parsed.");let d=t.getElementsByTagName("form");if(d.length!==1){let m="";throw d.length===0?m="FormXml has no form node.":m="FormXml has multiple form nodes.",(0,cb.trackErrorTrace)(hr,{eventName:db,eventData:{error:m}}),new Error(m)}let f=this.createFormModel(d.item(0),r,n,i,o,a,s,l,u,c);return R.IsNullOrUndefined(f.displayCondition)&&s!==wt.Dialog&&this.appendDefaultDisplayCondition(f),f}upsertFieldCount(t,r){let n=ba.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(!R.IsNullOrUndefined(t)){let n=R.ParseXml(r);n!==null&&this.populateElementChildren(t,n.childNodes)}}createFormModel(t,r,n,i,o,a,s,l,u,c){let d=new up(r,n,i,o,a,s,l,u,c);return this.populateElementProperties(d,t.attributes),this.populateElementChildren(d,t.childNodes),s===wt.Main&&(this.insertHeaderFooterElementProperties(E.formHeader,d,d.header),this.insertHeaderFooterElementProperties(E.formFooter,d,d.footer)),d}insertHeaderFooterElementProperties(t,r,n){if(R.IsNullOrUndefined(n)){let i=t===E.formHeader?new oc(r,!0):new ic(r,!0);xr.prototype.insertProperty.call(i,y.id,"{"+U.NewGuid()+"}"),xr.prototype.insertProperty.call(i,y.Fieldlabelposition,"Top"),xr.prototype.insertProperty.call(i,y.columnName,qe.MarginalControlColumns),xr.prototype.insertProperty.call(i,y.LabelWidth,qe.LabelWidth),xr.prototype.insertProperty.call(i,y.Fieldlabelalignment,"Left");let o=null,a=new Sa(o);for(let s=0;s<i.maxColumns;s++){let l=new kr(a);xr.prototype.insertProperty.call(l,y.id,"{"+U.NewGuid()+"}"),l.setDisplayName(q.EmptyString,this.lcid),xr.prototype.insertProperty.call(l,y.showlabel,"false"),a.addCell(l)}i.appendRow(a),t===E.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 xr(`<${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,cb.trackErrorTrace)(hr,{eventName:db,eventData:{error:n}}),new Error(n)}for(let n=0;n<r.length;n++){let i=r.item(n);i&&(xr.prototype.insertProperty.call(t,i.name,i.value),t.getNodeName()===E.formCell&&i.name===y.auto&&i.value==="true"&&t.setAutoExpandDetailsForTab())}}populateElementChildren(t,r){for(let n=0;n<r.length;n++){let i=r.item(n),o=this.deSerializeFormXmlNode(i,t);o&&xr.prototype.insertChild.call(t,o)}}createModelNode(t,r){switch(t.nodeName){case E.form:throw new Error("Form node shouldn't be created using this method");case E.formTab:return new Ki(r);case E.formColumn:return new $o(r);case E.formHeader:return new oc(r,!1);case E.formFooter:return new ic(r,!1);case E.formSection:return new pi(E.formSection,r);case E.formRow:return new Sa(r);case E.formCell:return new kr(r);case E.formControl:let n=t.attributes,i=t.childNodes.length>0?t.childNodes[0].childNodes:null,o;for(let s=0;s<n.length;s++){let l=n.item(s);if(l.name===y.indicationOfSubgrid&&l.value==="true"||l.name===y.classid&&(l.value?.toLocaleUpperCase()===`{${N.SubgridControl}}`||l.value?.toLocaleUpperCase()===`{${N.ReferencePanelSubgridControl}}`))o=yn.Grid;else if(l.name===y.classid&&l.value?.toLocaleUpperCase()===`{${N.LookupControl}}`)o=yn.Lookup;else if(l.name===y.classid&&l.value?.toLocaleUpperCase()===`{${N.CustomControl}}`)for(let u=0;u<i?.length;u++)i[u].nodeName===y.DefaultViewId&&(o=yn.Lookup)}return o===yn.Grid?new rl(r):o===yn.Lookup?new nl(r):new Fn(r);case E.formEvent:return new tl(r,q.EmptyString);case E.dependency:return this.populateDependencyTable(t),new el(r,q.EmptyString);case E.Handler:let a=[];return new fp(a,r);case E.formNavigation:return new gp(t.nodeName,r);case E.formNavBarArea:return new al(t.nodeName,r);case E.formNavBarAreas:return new sl(t.nodeName,r);case E.formNavBar:return new pp(r);case E.formNavBarByRelationshipItem:return new mp(r);case E.formNavBarItem:return new hp(r);case E.formDisplayConditions:return new dp(r);case E.library:return new il(r,q.EmptyString,q.EmptyString);case E.controlDescription:return new Rf(r);case E.customControl:return this.populateCustomControlConfigurationId(t),new Vf(r);default:return new xr(t.nodeName,r)}}populateDependencyTable(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);i.name===y.id&&this.upsertFieldCount(i.value,ui.DependencyFieldTable)}}populateCustomControlConfigurationId(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);if(i.name===y.id){let o=new U(i.value.substr(1,i.value.length-2));for(let a=0;a<t.parentNode.attributes.length;a++){let s=t.parentNode.attributes.item(a);if(s.name===y.ForControl){let l=s.value.substr(1,i.value.length-2);ft.CustomControlIdMap.upsert(l,o);break}}break}}}}});var pL={};nn(pL,{SerializationService:()=>pb,SerializationServiceScope:()=>Nee,SerializedFormElementNode:()=>ll});var Nee,ll,pb,mL=k(()=>{"use strict";rr();kt();kn();ob();Nee="SerializationService",ll=class extends re{fetchNodeName(){return this.getNodeName()}enumerateProperties(){return this.getAllProperties()}enumerateChildren(){return this.getAllChildren()}},pb=class{langCode;constructor(t){this.langCode=t}serializeFormXmlNode(t){let r=ll.prototype.fetchNodeName.call(t);if(r.charAt(0)===ji.StartTag)return q.EscapeXml(r.substr(1),!1);if(t.isTransient&&!t.isDirty())return q.EmptyString;let n=ll.prototype.enumerateProperties.call(t),i=ll.prototype.enumerateChildren.call(t);if(!(t instanceof Na)){let o=`<${r}`;if(n.length!==0&&(o+=` ${this.getPropertiesString(n)}`),i.length===0)o+=" />";else{let a=q.EmptyString;for(let s of i)a+=this.serializeFormXmlNode(s);o+=`>${a}</${r}>`}return o}return q.EmptyString}getPropertiesString(t){let r=q.EmptyString;return t.forEach((n,i)=>{i!==0&&(r+=" "),r+=`${n.key}="${q.EscapeXml(n.value,!0)}"`}),r}}});var yb=v(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});ul.completeRecordAsStored=ul.completeLabelsAsStored=void 0;var mb=Eo(),_ee="E7A81278-8635-4D9E-8D4D-59480B391C5B",Tee=new Set(["tab","section","cell"]);function Mn(e){let t=[];for(let r=e.firstChild;r;r=r.nextSibling)r.nodeType===1&&t.push(r);return t}function xo(e,t){return Mn(e).find(r=>r.tagName===t)}function gL(e,t){return e.length===t.length&&e.every((r,n)=>r.tagName===t[n].tagName)}function hb(e){let t=xo(e,"control");return t?(t.getAttribute("datafieldname")||"")!==""?!0:(t.getAttribute("classid")||"").replace(/[{}]/g,"").toUpperCase()===_ee:!1}function gb(e,t){var r,n;let i=((r=xo(e,"control"))===null||r===void 0?void 0:r.getAttribute("id"))||"";return i!==""&&i===(((n=xo(t,"control"))===null||n===void 0?void 0:n.getAttribute("id"))||"")}function Dee(e,t){if(xo(e,"labels"))return;let r=Mn(e),n=Mn(t),i=n[0];if(!i||i.tagName!=="labels"||n.length!==r.length+1||!gL(r,n.slice(1)))return;let o=Mn(i);if(!(o.length===0||o.some(s=>s.tagName!=="label"||!s.hasAttribute("description")||!s.hasAttribute("languagecode"))||!(e.tagName==="cell"&&hb(e)&&gb(e,t))&&o.some(s=>s.getAttribute("description")!=="")))return i}function Iee(e,t){let r=Oee(e.ownerDocument,t),n=Mn(e)[0];n?e.insertBefore(r,n):e.appendChild(r)}function Oee(e,t){let r=e.createElement("labels");for(let n of Mn(t))r.appendChild(yL(e,n));return r}function yL(e,t){let r=e.createElement("label");for(let n=0;n<t.attributes.length;n+=1){let{name:i,value:o}=t.attributes[n];(i==="description"||i==="languagecode")&&r.setAttribute(i,o)}return r}function hL(e,t){let r=xo(e,"labels");return r?Mn(r).find(n=>n.tagName==="label"&&n.getAttribute("languagecode")===String(t)):void 0}function Pee(e,t,r){if(e.tagName!=="cell"||!hb(e)||!gb(e,t))return!1;let n=hL(e,r),i=hL(t,r),o=i?.getAttribute("description")||"";return!n||!n.hasAttribute("description")||(n.getAttribute("description")||"")!==""||o===""?!1:(n.setAttribute("description",o),!0)}function Ree(e,t){if(e.tagName!=="cell"||!hb(e)||!gb(e,t))return;let r=xo(e,"labels"),n=xo(t,"labels");if(!r||!n)return;let i=Mn(r),o=Mn(n),a=f=>f.tagName==="label"&&f.hasAttribute("description")&&f.hasAttribute("languagecode");if(o.length<=i.length||!i.every(a)||!o.every(a))return;let s=new Map(i.map(f=>[f.getAttribute("languagecode")||"",f]));if(s.size!==i.length)return;let l=new Set,u=0,c=[],d=[];for(let f of o){let m=f.getAttribute("languagecode")||"";if(l.has(m))return;l.add(m);let p=s.get(m);if(!p){d.push(f);continue}if((p.getAttribute("description")||"")!==(f.getAttribute("description")||""))return;u+=1,c.push(...d.map(h=>({label:h,before:p}))),d=[]}return c.push(...d.map(f=>({label:f}))),u===i.length?c:void 0}function bL(e,t,r,n){if(e.tagName!==t.tagName)return;if(Tee.has(e.tagName)){let a=Dee(e,t);a&&(Iee(e,a),n.changed=!0),Pee(e,t,r)&&(n.changed=!0);let s=Ree(e,t),l=xo(e,"labels");if(s&&l){for(let{label:u,before:c}of s){let d=yL(e.ownerDocument,u);c?l.insertBefore(d,c):l.appendChild(d)}n.changed=!0}}let i=Mn(e),o=Mn(t);gL(i,o)&&i.forEach((a,s)=>bL(a,o[s],r,n))}function vL(e,t,r){if(e===t)return e;let n,i;try{n=(0,mb.parseXmlRoot)(e,""),i=(0,mb.parseXmlRoot)(t,"")}catch{return e}let o={changed:!1};return bL(n,i,r,o),o.changed?(0,mb.serializeNode)(n):e}ul.completeLabelsAsStored=vL;function Lee(e,t,r){let n=e?.formxml,i=t?.formxml;if(typeof n!="string"||typeof i!="string")return e;let o=vL(n,i,r);return o===n?e:{...e,formxml:o}}ul.completeRecordAsStored=Lee});var UL=v(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.pcfReadIssues=ue.pcfBindingIssues=ue.commitPcfState=ue.mayCommitPcfState=ue.reconcilePcfDescriptions=ue.customControlNeeds=ue.mintPcfIdentity=ue.planPcfBinding=ue.projectPcfBindings=ue.supportsPcfFormType=ue.storedBindingOf=ue.hasCustomControl=ue.sameAsStored=ue.readPcfDescription=ue.newPcfDescription=ue.editorText=ue.nativeClassFor=ue.pcfEntryLayout=void 0;var kee=($u(),zr(TD)),$ee=Q(),wL=ct(),V=zd(),xee=cu(),we=cn(),Qi=["web","phone","tablet"],sc={web:"2",phone:"0",tablet:"1"},NL=new Map([["2","web"],["0","phone"],["1","tablet"]]),Fee=["phone","web","tablet"];function bp(e){let t=new Set(e),r=Fee.filter(n=>!t.has(n));return{defaults:r.length===0?[null]:r,named:Qi.filter(n=>t.has(n))}}ue.pcfEntryLayout=bp;function gr(e){return Array.isArray(e)?e:[]}function pt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function lc(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function vb(e){return{n:`<${e}`,a:[],c:[]}}function _L(e){return typeof e?.n=="string"&&e.n.startsWith("<")}function CL(e){let t=gr(e.c);return t.length===1&&_L(t[0])&&(0,V.rawText)(e)!==""?(0,V.rawText)(e):void 0}function vn(e,t){return JSON.stringify(e)===JSON.stringify(t)}function TL(e){return`{${e.replace(/^\{|\}$/g,"").toUpperCase()}}`}function wb(e){try{let t=(0,kee.mapFieldTypeToControl)(e.attributeTypeName,e.format);return t?TL(String(t)):void 0}catch{return}}ue.nativeClassFor=wb;var Cb=new Map([["Whole.None",{digits:0,min:-2147483648,max:2147483647}],["Whole.Duration",{digits:0,min:0,max:2147483647}],["Decimal",{digits:7,min:-922337203685477,max:922337203685477}],["FP",{digits:5,min:-1e11,max:1e11}],["Currency",{digits:4,min:-1e11,max:1e11}]]),DL=new Set(["TwoOptions","Boolean"]),IL=new Set(["SingleLine.Text","SingleLine.TextArea","SingleLine.Email","SingleLine.Phone","SingleLine.URL","SingleLine.Ticker","Multiple"]),Mee=new Map([...[...IL].map(e=>[e,100]),["SingleLine.TextArea",2e3],["Multiple",1048576]]),Uee=/^[A-Za-z_][A-Za-z0-9_.-]*$/;function OL(e){return Uee.test(e)&&e!=="__proto__"}function Eb(e){return e!==void 0&&(e==="Enum"||Cb.has(e)||DL.has(e)||IL.has(e))}function PL(e){return typeof e=="number"?e:e!==""&&!Number.isNaN(Number(e))?Number(e):void 0}function uc(e,t){let r=e!==void 0?Cb.get(e):void 0;if(r&&typeof t!="boolean"){let n=PL(t);if(n!==void 0)return n.toFixed(r.digits)}return typeof t=="boolean"?t?"true":"false":String(t)}ue.editorText=uc;function Bee(e,t,r){var n;let i=[];for(let o of e.properties){let a=o.name,s;if(o.isPrimary?s=t:o.usage==="input"&&lc(r,a)?s=uc(o.defaultType,r[a]):s=(n=o.defaultValue)!==null&&n!==void 0?n:"",s==="")continue;let l=[];o.defaultType&&l.push(["type",o.defaultType]),!o.isPrimary&&(o.defaultType==="Enum"||o.usage==="input")&&l.push(["static","true"]),i.push({n:a,a:l,c:[vb(s)]})}return i}function RL(e,t,r,n,i){var o,a;let s=(o=n.formFactors)!==null&&o!==void 0?o:Qi.filter(d=>Ab(i).has(d)),l=bp(s),u=Bee(i,t,(a=n.parameters)!==null&&a!==void 0?a:{}),c=d=>JSON.parse(JSON.stringify(d));return{n:"controlDescription",a:[["forControl",e]],c:[...l.defaults.map(d=>({n:"customControl",a:d===null?[["id",r]]:[["id",r],["formFactor",sc[d]]],c:[{n:"parameters",a:[],c:[{n:"datafieldname",a:[],c:[vb(t)]}]}]})),...l.named.map(d=>({n:"customControl",a:[["name",n.name],["formFactor",sc[d]]],c:[{n:"parameters",a:[],c:c(u)}]}))]}}ue.newPcfDescription=RL;function Ab(e){return new Set(Qi.filter(t=>e.availableOn[t]))}function yp(e){var t;let r=gr(e.c);if(r.length!==1||((t=r[0])===null||t===void 0?void 0:t.n)!=="parameters"||gr(r[0].a).length>0)return;let n=gr(r[0].c);return n.every(i=>pt(i)&&!_L(i))?n:void 0}function Ta(e){let t=gr(e?.c);if(t.length===0||!t.every(p=>pt(p)&&p.n==="customControl"))return;let r=t.findIndex(p=>(0,V.rawAttr)(p,"name")!==void 0);if(r<=0)return;let n=t.slice(r),i=(0,V.rawAttr)(n[0],"name"),o=[];for(let p of n){let h=gr(p.a),g=h.length===2?NL.get(h[1][1]):void 0;if(!g||h[0][0]!=="name"||h[0][1]!==i||h[1][0]!=="formFactor"||o.includes(g))return;o.push(g)}let a=bp(o);if(!vn(a.named,o)||i==="")return;let s=yp(n[0]);if(!s||!n.every(p=>vn(yp(p),s)))return;let l=t.slice(0,r);if(l.length!==a.defaults.length)return;let u=(0,V.rawAttr)(l[0],"id"),c;for(let p=0;p<l.length;p+=1){let h=a.defaults[p],g=h===null?[["id",u??""]]:[["id",u??""],["formFactor",sc[h]]],b=yp(l[p]),w=b?.length===1&&b[0].n==="datafieldname"&&gr(b[0].a).length===0?CL(b[0]):void 0;if(!u||!vn(gr(l[p].a),g)||w===void 0||c!==void 0&&w!==c)return;c=w}let d={},f={},m;for(let p of s){let h=gr(p.a),g=CL(p),b=h.map(w=>w[0]);if(g===void 0||!OL(p.n)||lc(d,p.n)||p.n===m)return;if((0,V.rawAttr)(p,"static")===void 0){if(m!==void 0||g!==c||!(b.length===0||vn(b,["type"])))return;m=p.n;continue}if((0,V.rawAttr)(p,"static")!=="true"||!(vn(b,["static"])||vn(b,["type","static"])))return;d[p.n]=g,f[p.n]=(0,V.rawAttr)(p,"type")}if(!(m===void 0||c===void 0||u===void 0))return{binding:{name:i,...Object.keys(d).length>0?{parameters:d}:{},...o.length===Qi.length?{}:{formFactors:o}},fieldName:c,nativeClass:u,parameterTypes:f,boundProperty:m}}ue.readPcfDescription=Ta;function LL(e,t,r){return e===t?!0:typeof e!="string"&&(t===String(e)||t===uc(r,e))}function kL(e){let t=e.formFactors;return t===void 0?[...Qi]:Array.isArray(t)?Qi.filter(r=>t.includes(r)):[]}function bb(e,t){var r,n,i;if(e.name!==t.binding.name||!vn(kL(e),(r=t.binding.formFactors)!==null&&r!==void 0?r:Qi))return!1;let o=(n=e.parameters)!==null&&n!==void 0?n:{},a=(i=t.binding.parameters)!==null&&i!==void 0?i:{},s=Object.keys(o);return s.length!==Object.keys(a).length?!1:s.every(l=>lc(a,l)&&LL(o[l],a[l],t.parameterTypes[l]))}ue.sameAsStored=bb;function Ct(e){return pt(e)&&e.customControl!==void 0}ue.hasCustomControl=Ct;function Yi(e,t){var r;return t?gr((r=(0,V.descriptionsRegion)(e))===null||r===void 0?void 0:r.node.c).filter(n=>n?.n==="controlDescription"&&(0,V.normGuid)((0,V.rawAttr)(n,"forControl"))===t):[]}function Sb(e,t){let r=Yi(e.bag,(0,V.controlUniqueId)(t));return r.length===1?Ta(r[0]):void 0}ue.storedBindingOf=Sb;function Nb(e){let t=(0,V.effectiveFormType)(e);return t==="Main"||t==="QuickCreate"}ue.supportsPcfFormType=Nb;function qee(e){if(!Nb(e))return;let t=(0,V.controlUniqueIds)(e);for(let{cell:r}of(0,V.typedCellSites)(e)){let n=r.control;if(!pt(n)||!n.fieldName||!Ji(n.classId)||t.get((0,V.controlUniqueId)(n))!==1)continue;let i=Sb(e,n);i&&i.fieldName===n.fieldName&&(n.customControl=JSON.parse(JSON.stringify(i.binding)))}}ue.projectPcfBindings=qee;function Ji(e){return typeof e=="string"&&e.replace(/^\{|\}$/g,"").toUpperCase()===V.CUSTOM_CONTROL_CLASS_ID}var bn=(e,t)=>({kind:"refused",rule:e,message:t});function Vee(e){let t=e.replace(/^\{|\}$/g,"");return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)&&!Ji(e)}function EL(e,t,r){var n,i;let o=Ta(r);if(!o)return bn("pcf-binding-other-control","the control already has a description the SDK cannot read as a binding; adding would replace it");if(o.fieldName!==e.fieldName)return bn("pcf-binding-rebind",`the binding is filed for "${o.fieldName}": remove it, push, then bind the new column`);if(t.name!==o.binding.name)return bn("pcf-binding-control-swap",`the binding uses "${o.binding.name}": to use another control, remove customControl, push, then add it`);let a=pt(t.parameters)?t.parameters:{},s=(n=o.binding.parameters)!==null&&n!==void 0?n:{},l=Object.keys(a).sort();if(!vn(l,Object.keys(s).sort()))return bn("pcf-binding-edit-parameter-set",`an edit changes parameter values only \u2014 the binding stores exactly ${Object.keys(s).sort().map(g=>`"${g}"`).join(", ")||"none"}: to add or remove one, remove the binding, push, then add it`);let u=l.filter(g=>!LL(a[g],s[g],o.parameterTypes[g])),c=u.find(g=>uc(o.parameterTypes[g],a[g]).trim()==="");if(c!==void 0)return bn("pcf-binding-edit-parameter-set",`"${c}" cannot be cleared in place \u2014 an empty value is not written, which removes the parameter: remove the binding, push, then add it`);let d=kL(t),f=(i=o.binding.formFactors)!==null&&i!==void 0?i:[...Qi],m=d.filter(g=>!f.includes(g)),p=f.filter(g=>!d.includes(g));if(u.length===0&&m.length===0&&p.length===0)return{kind:"unchanged"};let h=u.find(g=>!Eb(o.parameterTypes[g]));if(h!==void 0){let g=o.parameterTypes[h];return bn("pcf-binding-edit-stored-type",`"${h}" is stored ${g===void 0?"with no type":`as type "${g}"`}, which the property editor does not write: remove the binding, push, then add it`)}return(m.length>0||p.length>0)&&!Vee(o.nativeClass)?bn("pcf-binding-edit-fallback",`the factors the control leaves fall back to "${o.nativeClass}", which is not a native control class: remove the binding, push, then add it`):{kind:"edit",description:r,stored:o,changed:u,factors:d,added:m,removed:p}}function Gee(e,t){return t&&(0,V.typedCellSites)(e).find(({cell:n})=>Ct(n.control)&&(0,V.controlUniqueId)(n.control)===t)?{descriptions:Yi(e.bag,t)}:void 0}function $L(e,t){let r=new Map,n=Wee(e),i=new Set,o=new Map,a=u=>{let c=o.get(u);return c||(c={before:[],now:[]},o.set(u,c)),c},s=(u,c)=>({cell:Hee(u),uid:(0,V.controlUniqueId)(c),bound:Ct(c)});for(let{cell:u}of(0,V.typedCellSites)(e)){let c=u.control;pt(c)&&typeof c.id=="string"&&c.id&&a(c.id).now.push({...s(u,c),control:c})}for(let{cell:u}of(0,V.typedCellSites)(t)){let c=u.control;if(!pt(c))continue;let d=s(u,c);d.bound&&d.uid&&i.add(d.uid),typeof c.id=="string"&&c.id&&a(c.id).before.push(d)}let l=(u,c)=>{let d=u.filter(f=>f.cell===c);return d.length===1?d[0]:void 0};for(let[u,{before:c,now:d}]of o){let f=c.filter(D=>D.bound&&D.uid!==""&&!n.has(D.uid));if(f.length===0||d.length===0)continue;let m=[...c],p=D=>{let P=m.findIndex(D);return P<0?void 0:m.splice(P,1)[0]},g=d.filter(D=>!D.bound||D.uid===""?!0:p(P=>P.bound&&P.uid===D.uid)!==void 0?!1:!i.has(D.uid)).filter(D=>{let P=D.cell?l(c,D.cell):void 0;return!P||!l(d,D.cell)||!m.includes(P)?!0:(m.splice(m.indexOf(P),1),f.includes(P)&&D.uid!==P.uid&&AL(D.control)&&r.set(D.control,SL(P.uid)),!1)}),b=[],w=(D,P)=>{let x=D.uid===""?void 0:p(K=>K.uid===D.uid&&(!P||K.bound===D.bound));return x&&f.includes(x)&&b.push(x),x!==void 0},S=g.filter(D=>!w(D,!0)).filter(D=>!w(D,!1)&&AL(D.control)),O=f.filter(D=>m.includes(D));if(S.length===0||O.length===0&&b.length===0)continue;let L=[...O,...b],I=O.length===1&&S.length===1&&m.length===1?SL(O[0].uid):`the controls with id "${u}" cannot all be matched to those last synced \u2014 their cells do not tell them apart \u2014 and ${L.map(D=>`{${D.uid}}`).join(", ")} no longer ${L.length===1?"names":"name"} a control: which control held ${L.length===1?"that binding":"those bindings"} is ambiguous. Re-fetch the form; to drop a bound control, remove its customControl and push before removing the control`;for(let D of S)r.set(D.control,I)}return r}function Wee(e){let t=(0,V.controlUniqueIds)(e),r=new Map;for(let{cell:i}of(0,V.typedCellSites)(e)){let o=pt(i.control)?(0,V.controlUniqueId)(i.control):"";o&&!r.has(o)&&r.set(o,i.control)}let n=new Set;for(let[i,o]of t){let a=r.get(i);(a===void 0||Ct(a)||o>1)&&n.add(i)}return n}function AL(e){return Ct(e)||e.genPage===void 0&&Ji((0,V.effectiveClassId)(e))}function zee(e,t){let r=o=>(0,V.typedCellSites)(o).flatMap(({cell:a,pointer:s})=>{let l=a.control;if(!pt(l)||Ct(l)||l.genPage!==void 0||!Ji((0,V.effectiveClassId)(l)))return[];let u=(0,V.controlUniqueId)(l);return u===""||Yi(o.bag,u).length===0?[{control:l,pointer:`${s}/control`}]:[]}),n=o=>`${String(o.id)}\0${(0,V.controlUniqueId)(o)}`,i=r(t).map(({control:o})=>n(o));return r(e).filter(({control:o})=>{let a=i.indexOf(n(o));return a<0?!0:(i.splice(a,1),!1)})}var jee="this control would keep the custom-control class with no binding (its customControl and uniqueid are gone): remove the binding from an unchanged copy \u2014 keep its uniqueid, and the native control comes back \u2014 or set classId to the column's native control";function SL(e){return`this control's uniqueid changed since it was last synced (it was {${e}}), and a binding is linked to its description by it: restore it (re-fetch the form), or remove the binding, push, then add the new one`}function Hee(e){let t=typeof e.id=="string"?e.id.trim():"";return(0,V.normGuid)(t)||t.toLowerCase()}function cc(e,t,r,n){let i=t.customControl,o=(0,V.controlUniqueId)(t),a=Yi(e.bag,o),s=r?$L(e,r).get(t):void 0;if(s!==void 0)return bn("pcf-binding-unique-id",s);let l=r?Gee(r,o):void 0;if(l){let c=l.descriptions,d=c.length===1?Ta(c[0]):void 0;if(d&&d.fieldName!==t.fieldName)return bn("pcf-binding-rebind",`the binding is filed for "${d.fieldName}": remove it, push, then bind the new column`);if(c.length===1&&a.length===1&&vn(c[0],a[0]))return EL(t,i,a[0]);let f=a.length===1?Ta(a[0]):void 0;return d&&f&&f.fieldName===t.fieldName&&bb(i,d)&&bb(i,f)?{kind:"unchanged"}:bn("pcf-binding-edit-changed-description","the binding\u2019s description changed since it was last synced (edited in the bag, re-keyed or deleted): re-fetch the form before changing the binding")}if(a.length===0)return{kind:"new"};if(a.length>1)return bn("pcf-binding-other-control","the control already has a description the SDK cannot read as a binding; adding would replace it");let u=EL(t,i,a[0]);return n&&(u.kind==="edit"||u.kind==="unchanged")?u.kind==="unchanged"?u:bn("pcf-binding-edit","this binding\u2019s description was never synced from the server (no baseline): changing it in place is not supported \u2014 remove customControl, push, then add the new one"):u}ue.planPcfBinding=cc;function xL(e){return e.kind==="edit"&&(e.changed.length>0||e.added.length>0)}function Kee(e){let t=n=>Ct(n.control)&&(!n.control.id||!n.id||(0,V.authoredUniqueId)(n.control)===void 0);if(!(0,V.typedCellSites)(e).some(({cell:n})=>t(n)))return e;let r=JSON.parse(JSON.stringify(e));for(let{cell:n}of(0,V.typedCellSites)(r)){if(!t(n))continue;let i=n.control;i.id||(i.id=(0,wL.newId)()),n.id||(n.id=(0,wL.newId)()),(0,V.authoredUniqueId)(i)===void 0&&(0,V.setUniqueId)(i)}return r}ue.mintPcfIdentity=Kee;function Jee(e,t){let r=new Set,n=new Set;for(let{cell:i}of(0,V.typedCellSites)(e)){let o=i.control;if(!Ct(o)||!pt(o.customControl))continue;let a=o.customControl.name;if(typeof a!="string"||a===""||typeof o.fieldName!="string"||!o.fieldName)continue;let s=cc(e,o,t,!0);s.kind==="new"?(r.add(a),n.add(o.fieldName)):xL(s)&&r.add(a)}return{controls:[...r],columns:[...n],...n.size>0&&(0,V.effectiveFormType)(e)==="QuickCreate"?{requireCreateEligibility:!0}:{}}}ue.customControlNeeds=Jee;function Yee(e,t,r){var n,i,o,a,s,l;let u=e.bag,c=new Map;for(let{cell:f,pointer:m}of(0,V.typedCellSites)(e)){let p=f.control;if(!Ct(p)||!pt(p.customControl))continue;let h=(0,V.controlUniqueId)(p);h&&Yi(u,h).length>0&&c.set(p,{plan:cc(e,p,t,!0),pointer:`${m}/control/customControl`})}let d=(0,V.descriptionsRegion)(u);if(d&&t){let f=(0,V.controlUniqueIds)(e),m=new Set,p=new Map;for(let{cell:h}of(0,V.typedCellSites)(e)){let g=pt(h.control)?(0,V.controlUniqueId)(h.control):"";g&&!p.has(g)&&p.set(g,h.control)}for(let{cell:h}of(0,V.typedCellSites)(t)){let g=h.control;if(!Ct(g))continue;let b=(0,V.controlUniqueId)(g),w=Yi(t.bag,b),C=Yi(u,b);if(w.length!==1||C.length!==1||!vn(w[0],C[0])||!Ta(C[0]))continue;let S=p.get(b);if(S&&!Ct(S)){if(((n=f.get(b))!==null&&n!==void 0?n:0)>1)continue;let O=(o=(i=Ta(C[0]))===null||i===void 0?void 0:i.nativeClass)!==null&&o!==void 0?o:"";S.classId=O.replace(/^\{|\}$/g,"").toUpperCase(),Qee(S,"uniqueid"),m.add(b)}else!S&&!f.has(b)&&m.add(b)}m.size>0&&(d.node.c=gr(d.node.c).filter(h=>!(h?.n==="controlDescription"&&m.has((0,V.normGuid)((0,V.rawAttr)(h,"forControl"))))))}for(let{cell:f}of(0,V.typedCellSites)(e)){let m=f.control;if(!Ct(m)||!pt(m.customControl))continue;Ji(m.classId)||(m.classId=V.CUSTOM_CONTROL_CLASS_ID);let p=(0,V.controlUniqueId)(m);if(!p){if((0,V.authoredUniqueId)(m)!==void 0)continue;p=(0,V.setUniqueId)(m)}let h=c.get(m);if(h){if(h.plan.kind==="refused")throw new $ee.ValidationError("form",e.id,[(0,we.issue)(h.pointer,h.plan.rule,h.plan.message)]);h.plan.kind==="edit"&&Xee(h.plan,m.customControl);continue}let g=r?.control(m.customControl.name),b=r?.column(e.entityLogicalName,m.fieldName),w=b?.kind==="found"?wb(b.value):void 0;if(g?.kind!=="found"||!w)continue;d||(d={i:(0,V.embedAppendIndex)(u),node:{n:"controlDescriptions",a:[],c:[]}},u.c.push(d));let C=((l=(s=gr((a=m.bag)===null||a===void 0?void 0:a.a).find(O=>O[0]==="uniqueid"))===null||s===void 0?void 0:s[1])!==null&&l!==void 0?l:"").trim(),S=C.startsWith("{")?C:`{${p}}`;d.node.c.push(RL(S,m.fieldName,w,m.customControl,g.value))}}ue.reconcilePcfDescriptions=Yee;function Qee(e,t){pt(e.bag)&&(e.bag.a=gr(e.bag.a).filter(r=>r[0]!==t))}function Xee(e,t){var r,n;let i=gr(e.description.c),o=i.findIndex(g=>(0,V.rawAttr)(g,"name")!==void 0),a=i.slice(0,o),s=i.slice(o),l=(r=t.parameters)!==null&&r!==void 0?r:{};for(let g of s)for(let b of(n=yp(g))!==null&&n!==void 0?n:[])e.changed.includes(b.n)&&(b.c=[vb(uc(e.stored.parameterTypes[b.n],l[b.n]))]);if(e.added.length===0&&e.removed.length===0)return;let u=g=>JSON.parse(JSON.stringify(g)),c=g=>{var b;let w=(0,V.rawAttr)(g,"formFactor");return w===void 0?null:(b=NL.get(w))!==null&&b!==void 0?b:null},d=(0,V.rawAttr)(a[0],"id"),f=(0,V.rawAttr)(s[0],"name"),m=bp(e.factors),p=m.defaults.map(g=>{let b=a.find(C=>c(C)===g);if(b)return b;let w=u(a[0]);return w.a=g===null?[["id",d]]:[["id",d],["formFactor",sc[g]]],w}),h=m.named.map(g=>{let b=s.find(C=>c(C)===g);if(b)return b;let w=u(s[0]);return w.a=[["name",f],["formFactor",sc[g]]],w});e.description.c=[...p,...h]}function Zee(e){return(0,V.typedCellSites)(e).some(({cell:t})=>Ct(t.control))}ue.mayCommitPcfState=Zee;function ete(e,t){var r;let n=JSON.parse(JSON.stringify(e)),i=!1;for(let{cell:o}of(0,V.typedCellSites)(n)){let a=o.control;if(!Ct(a))continue;let s=Sb(n,a);if(!s||s.fieldName!==a.fieldName)continue;let l=t(V.CUSTOM_CONTROL_CLASS_ID),u=gr((r=a.bag)===null||r===void 0?void 0:r.a).find(c=>c[0]==="classid");(!Ji(a.classId)||a.type!==l||u!==void 0&&!Ji(u[1])||!vn(a.customControl,s.binding))&&(Ji(a.classId)||(a.classId=V.CUSTOM_CONTROL_CLASS_ID),a.type=l,u&&!Ji(u[1])&&(u[1]=TL(V.CUSTOM_CONTROL_CLASS_ID)),a.customControl=JSON.parse(JSON.stringify(s.binding)),i=!0)}return i?n:e}ue.commitPcfState=ete;var tte=new Set(["name","parameters","formFactors"]);function rte(e,t,r){let n=[],i=(0,V.controlUniqueIds)(e);for(let{cell:o,pointer:a}of(0,V.typedCellSites)(e)){let s=o.control;Ct(s)&&ite(e,s,`${a}/control`,i,n,t,r?.atPush===!0)}return t&&ote(e,t,n),n}ue.pcfBindingIssues=rte;function nte(e,t,r){let n=r.length;if(!pt(e))return r.push((0,we.issue)(t,"pcf-binding-shape","customControl must be an object")),!1;for(let i of Object.keys(e))tte.has(i)||r.push((0,we.issue)(`${t}/${i}`,"pcf-binding-unknown-key",`customControl has no "${i}"`));if((typeof e.name!="string"||e.name.trim()==="")&&r.push((0,we.issue)(`${t}/name`,"pcf-binding-shape","name must be the control's non-empty customcontrols name")),e.parameters!==void 0)if(!pt(e.parameters))r.push((0,we.issue)(`${t}/parameters`,"pcf-binding-shape","parameters must be an object"));else for(let[i,o]of Object.entries(e.parameters))typeof o=="string"||typeof o=="boolean"||typeof o=="number"&&Number.isFinite(o)||r.push((0,we.issue)(`${t}/parameters/${i}`,"pcf-binding-shape","a parameter must be a string, a finite number or a boolean"));if(e.formFactors!==void 0){let i=e.formFactors;Array.isArray(i)&&i.length>0&&i.every(a=>typeof a=="string"&&Qi.includes(a))&&new Set(i).size===i.length||r.push((0,we.issue)(`${t}/formFactors`,"pcf-binding-shape","formFactors must be distinct 'web', 'phone' and 'tablet', at least one"))}return r.length===n}function ite(e,t,r,n,i,o,a){var s;let l=`${r}/customControl`,u=nte(t.customControl,l,i);t.fieldName||i.push((0,we.issue)(l,"pcf-binding-unbound","a PCF binding needs a control bound to a column (fieldName)")),t.genPage!==void 0&&i.push((0,we.issue)(l,"pcf-binding-with-genpage","a control cannot embed a page and bind a PCF control")),Nb(e)||i.push((0,we.issue)(l,"pcf-binding-form-type","PCF bindings are supported on Main and Quick Create forms only (not Quick View or Card)")),t.classId!==void 0&&typeof t.classId!="string"&&i.push((0,we.issue)(`${r}/classId`,"pcf-binding-class-id","classId must be a string"));let c=(0,V.authoredUniqueId)(t),d=(0,V.controlUniqueId)(t);if(c!==void 0&&!d?i.push((0,we.issue)(`${r}/bag`,"pcf-binding-unique-id","the control's uniqueid must be a GUID")):d&&((s=n.get(d))!==null&&s!==void 0?s:0)>1&&i.push((0,we.issue)(`${r}/bag`,"pcf-binding-unique-id","another control carries the same uniqueid")),!u)return;let f=cc(e,t,o,a);f.kind==="refused"&&i.push((0,we.issue)(l,f.rule,f.message))}function ote(e,t,r){var n;let i=new Map,o=$L(e,t);for(let{cell:l,pointer:u}of(0,V.typedCellSites)(e)){let c=pt(l.control)?(0,V.controlUniqueId)(l.control):"";if(c&&!i.has(c)&&i.set(c,{control:l.control,pointer:`${u}/control`}),pt(l.control)&&!Ct(l.control)){let d=o.get(l.control);d!==void 0&&r.push((0,we.issue)(`${u}/control`,"pcf-binding-unique-id",d))}}let a=(0,V.controlUniqueIds)(e);for(let{cell:l}of(0,V.typedCellSites)(t)){if(!Ct(l.control))continue;let u=(0,V.controlUniqueId)(l.control),c=i.get(u);!c||Ct(c.control)||(((n=a.get(u))!==null&&n!==void 0?n:0)>1?r.push((0,we.issue)(c.pointer,"pcf-binding-unique-id","another control carries this binding\u2019s uniqueid; removing the binding would delete its description too")):vn(Yi(t.bag,u),Yi(e.bag,u))?c.control.fieldName!==l.control.fieldName&&r.push((0,we.issue)(c.pointer,"pcf-binding-rebind","remove the binding, push, then bind the new column")):r.push((0,we.issue)(c.pointer,"pcf-binding-removed-changed","the binding changed since it was last pushed; remove it from an unchanged copy (re-fetch)")))}let s=new Set(r.map(l=>l.pointer));for(let{pointer:l}of zee(e,t))s.has(l)||r.push((0,we.issue)(l,"pcf-binding-unique-id",jee))}var ate=new Set(["Form.Card"]),ste="MscrmControls.ModelForm.ModelFormControl";function FL(e,t){var r;if(e.hasDataset||e.hasGroups)return"it has a data-set or groups";if(!e.isBound)return"its first property is not bound to a column";let n=e.properties;if(n.filter(s=>s.usage==="bound").length!==1)return"it has more than one bound property";let i=n.map(s=>s.name);if(i.some(s=>!s)||new Set(i).size!==i.length)return"a property has no name, or two share one";let o=i.find(s=>!OL(s));if(o!==void 0)return`the property name "${o}" cannot be written as an element`;if(t===ste||n.some(s=>s.defaultType!==void 0&&ate.has(s.defaultType)))return"a property needs a special encoding";if(n.some(s=>s.usage==="output"&&s.defaultValue!==null&&s.defaultValue!==""))return"an output property has a default";let a=n.find(s=>s.usage==="input"&&!Eb(s.defaultType));return a?`input "${a.name}" has a type the property editor does not write as text (${(r=a.defaultType)!==null&&r!==void 0?r:"none"})`:void 0}function lte(e){return e.ofType!==null?[e.ofType]:e.ofTypeGroup}function ML(e,t,r=e.defaultType){if(r==="Enum")return e.enumValues.some(o=>o.value===String(t))?void 0:`must be one of ${e.enumValues.map(o=>`"${o.value}"`).join(", ")}`;let n=r!==void 0?Cb.get(r):void 0;if(n){let o=typeof t=="boolean"?void 0:PL(t);return o===void 0||o<n.min||o>n.max?`must be a number from ${n.min.toFixed(n.digits)} through ${n.max.toFixed(n.digits)}`:void 0}if(r!==void 0&&DL.has(r))return t===!0||t===!1||t==="true"||t==="false"?void 0:"must be true or false";let i=r!==void 0?Mee.get(r):void 0;return i!==void 0&&String(t).length>i?`must be at most ${i} characters`:e.required&&String(t)===""?"is required":void 0}function ute(e,t,r){var n,i,o,a;let s={issues:[]},l=s.issues;for(let{cell:u,pointer:c}of(0,V.typedCellSites)(e)){let d=u.control;if(!Ct(d)||!d.fieldName)continue;let f=d.customControl;if(!pt(f)||typeof f.name!="string")continue;let m=`${c}/control/customControl`,p=cc(e,d,r,!0);if(p.kind==="edit"){xL(p)&&fte(p,f,m,t,s);continue}if(p.kind!=="new")continue;let h=t?.control(f.name),g=t?.column((n=e.entityLogicalName)!==null&&n!==void 0?n:"",d.fieldName);if(!h||h.kind==="unavailable"){(i=s.unavailable)!==null&&i!==void 0||(s.unavailable={code:"PCF_MANIFEST_UNAVAILABLE",message:`the manifest of "${f.name}" could not be read`,...h?.kind==="unavailable"?{cause:h.error}:{}});continue}if(h.kind!=="found"){l.push((0,we.issue)(`${m}/name`,"PCF_CONTROL_NOT_FOUND",`no single installed control is named "${f.name}" (${h.kind})`));continue}if(!g||g.kind==="unavailable"){(o=s.unavailable)!==null&&o!==void 0||(s.unavailable={code:"PCF_COLUMN_UNAVAILABLE",message:`the column "${d.fieldName}" could not be read`,...g?.kind==="unavailable"?{cause:g.error}:{}});continue}let b=FL(h.value,f.name);if(b){l.push((0,we.issue)(`${m}/name`,"pcf-binding-unsupported-control",`"${f.name}" is not supported: ${b}`));continue}let w=h.value.properties.find(x=>x.isPrimary),C=g.kind==="found"?g.value:void 0,S=C?(a=(0,xee.manifestTypesForColumn)(C.attributeTypeName,C.format,C.formatName))!==null&&a!==void 0?a:[]:[];C!==void 0&&!C.isPrimaryId&&C.isValidForForm&&wb(C)!==void 0&<e(w).some(x=>S.includes(x))?(0,V.effectiveFormType)(e)==="QuickCreate"&&C?.isValidForCreate!==!0&&l.push((0,we.issue)(m,"pcf-binding-quick-create-column",`"${d.fieldName}" cannot be set when a record is created, so a Quick Create form cannot bind it`)):l.push((0,we.issue)(m,"pcf-binding-incompatible-column",`"${f.name}" cannot be bound to "${d.fieldName}"`));let L=new Map(h.value.properties.filter(x=>x.usage==="input").map(x=>[x.name,x])),I=pt(f.parameters)?f.parameters:{};for(let[x,K]of Object.entries(I)){let Le=L.get(x);if(!Le){l.push((0,we.issue)(`${m}/parameters/${x}`,"pcf-binding-unknown-parameter",`"${f.name}" has no input "${x}"`));continue}let lr=ML(Le,K);lr&&l.push((0,we.issue)(`${m}/parameters/${x}`,"pcf-binding-parameter-value",`"${x}" ${lr}`))}for(let x of L.values())x.required&&!lc(I,x.name)&&!x.defaultValue&&l.push((0,we.issue)(`${m}/parameters`,"pcf-binding-missing-parameter",`"${x.name}" is required`));let D=Ab(h.value),P=Array.isArray(f.formFactors)?f.formFactors:void 0;(P?P.some(x=>!D.has(x)):D.size===0)&&l.push((0,we.issue)(`${m}/formFactors`,"pcf-binding-form-factor",`"${f.name}" is available on ${D.size===0?"no form factor":[...D].join(", ")}`))}return s}ue.pcfReadIssues=ute;function cte(e,t){return t===void 0||!Eb(t)?!1:e.ofType!==null?e.ofType===t:e.ofTypeGroup.includes(t)}function dte(e,t,r){var n,i;let o=FL(e,t);if(o)return`it is no longer supported (${o})`;let a=e.properties.find(d=>d.isPrimary);if(a?.name!==r.boundProperty)return`its bound property is now "${(n=a?.name)!==null&&n!==void 0?n:"none"}", not "${r.boundProperty}"`;let s=(i=r.binding.parameters)!==null&&i!==void 0?i:{},l=new Set(e.properties.filter(d=>d.usage==="input").map(d=>d.name)),u=Object.keys(s).find(d=>!l.has(d));if(u!==void 0)return`"${u}" is no longer one of its inputs`;let c=e.properties.find(d=>d.usage==="input"&&d.required&&!d.defaultValue&&!lc(s,d.name));return c?`it now requires "${c.name}", which the binding does not store`:void 0}function fte(e,t,r,n,i){var o,a,s;let l=i.issues,u=n?.control(t.name);if(!u||u.kind==="unavailable"){(o=i.unavailable)!==null&&o!==void 0||(i.unavailable={code:"PCF_MANIFEST_UNAVAILABLE",message:`the manifest of "${t.name}" could not be read`,...u?.kind==="unavailable"?{cause:u.error}:{}});return}if(u.kind!=="found"){l.push((0,we.issue)(`${r}/name`,"PCF_CONTROL_NOT_FOUND",`no single installed control is named "${t.name}" (${u.kind})`));return}let c=dte(u.value,t.name,e.stored);if(c){l.push((0,we.issue)(r,"pcf-binding-edit-manifest-changed",`"${t.name}" changed since this binding was written: ${c} \u2014 remove the binding, push, then add it`));return}let d=new Map(u.value.properties.filter(h=>h.usage==="input").map(h=>[h.name,h])),f=l.length;for(let h of Object.keys((a=e.stored.binding.parameters)!==null&&a!==void 0?a:{})){let g=e.stored.parameterTypes[h];cte(d.get(h),g)||l.push((0,we.issue)(`${r}/parameters/${h}`,"pcf-binding-edit-stored-type",`"${h}" is stored ${g===void 0?"with no type":`as type "${g}"`}, which "${t.name}" does not take for it now: remove the binding, push, then add it`))}if(l.length>f)return;let m=(s=t.parameters)!==null&&s!==void 0?s:{};for(let h of e.changed){let g=ML(d.get(h),m[h],e.stored.parameterTypes[h]);g&&l.push((0,we.issue)(`${r}/parameters/${h}`,"pcf-binding-parameter-value",`"${h}" ${g}`))}let p=Ab(u.value);e.added.some(h=>!p.has(h))&&l.push((0,we.issue)(`${r}/formFactors`,"pcf-binding-form-factor",`"${t.name}" is available on ${p.size===0?"no form factor":[...p].join(", ")}`))}});var tk=v(Mr=>{"use strict";Object.defineProperty(Mr,"__esModule",{value:!0});Mr.classIdForAttributeType=Mr.QUICK_VIEW_CLASS_ID=Mr.NOTES_CLASS_ID=Mr.SUBGRID_CLASS_ID=Mr.formRegistration=Mr.FormAdapter=void 0;var Xi=(vt(),zr(VT)),BL=(dt(),zr(GT)),pte=(kt(),zr(zT)),Et=(le(),zr(WT)),ot=(ga(),zr(jT)),mte=(rb(),zr(fL)),hte=(mL(),zr(pL)),At=wo(),qL=jr(),Fr=cn(),gte=e0(),dl=ct(),yte=yb(),ir=zd(),mi=UL(),cl=Q(),Pb=oe(),_b=Co(),HL=sa(),bte={[Et.FormType.Main]:"Main",[Et.FormType.QuickCreate]:"QuickCreate",[Et.FormType.QuickViewForm]:"QuickView",[Et.FormType.Card]:"Card"},vp={Main:Et.FormType.Main,QuickCreate:Et.FormType.QuickCreate,QuickView:Et.FormType.QuickViewForm,Card:Et.FormType.Card},vte=new Map(Object.entries(ot.ControlClassId).map(([e,t])=>[String(t).toUpperCase(),e]));function Rb(e){var t;return e&&(t=vte.get(e.toUpperCase()))!==null&&t!==void 0?t:"Unknown"}function dc(e){return e.getAllProperties().map(t=>[t.key,t.value])}function Da(e){let t=new Map;for(let r of e.getAllProperties())t.has(r.key)||t.set(r.key,r.value);return t}function KL(e,t){return e.getAllChildren().find(r=>r.getNodeName()===t)}function Lb(e,t){var r,n;let i=KL(e,"labels");if(!i)return"";let o=i.getAllChildren().filter(s=>s.getNodeName()==="label"),a=(r=o.find(s=>Da(s).get("languagecode")===String(t)))!==null&&r!==void 0?r:o[0];return a&&(n=Da(a).get("description"))!==null&&n!==void 0?n:""}function wte(e){let t=KL(e,"parameters"),r={};if(!t)return r;for(let n of t.getAllChildren()){let i=n.getNodeName();if(i.charAt(0)==="<"||i.charAt(0)==="#")continue;let o=n.getAllChildren()[0],a=o?o.getNodeName():"";a.charAt(0)==="<"&&(a=a.substring(1)),r[i]=a}return r}function JL(e){return/^1+$/.test(e)&&e.length>=1&&e.length<=4?e.length:1}function Tb(e){let t=Math.min(Math.max(Math.trunc(e),1),4);return"1".repeat(t)}function fc(e){return String(e??"").replace(/[{}]/g,"")}function Db(e){return`{${fc(e)}}`}function Ib(e,t){if(e===void 0||e==="")return t;let r=Number(e);return Number.isNaN(r)?t:r}function Cp(e,t,r){let n=e.getAllChildren(),i=n.findIndex(u=>u.getNodeName()===t),o=[];if(n.forEach((u,c)=>{c!==i&&o.push({i:c,node:(0,At.rawFromNode)(u)})}),i<0)return{modeled:[],bag:{a:dc(e),c:o}};let a=n[i],s=[],l=[];return a.getAllChildren().forEach((u,c)=>{u.getNodeName()===r?s.push(u):l.push({i:c,node:(0,At.rawFromNode)(u)})}),{modeled:s,bag:{a:dc(e),c:o,w:{n:a.getNodeName(),a:dc(a),c:l}}}}function YL(e,t,r){let n=[],i=[];return e.getAllChildren().forEach((o,a)=>{o.getNodeName()===t&&(!r||n.length===0)?n.push(o):i.push({i:a,node:(0,At.rawFromNode)(o)})}),{modeled:n,bag:{a:dc(e),c:i}}}function VL(e,t){let{modeled:r,bag:n}=Cp(e,"tabs","tab");return{tabs:r.map(i=>Cte(i,t)),bag:n}}function Cte(e,t){var r,n;let i=Da(e),{modeled:o,bag:a}=Cp(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:Lb(e,t),expanded:i.get("expanded")==="true",visible:i.has("visible")?i.get("visible")==="true":!0,columns:o.map(s=>Ete(s,t)),bag:a}}function Ete(e,t){let r=Da(e),{modeled:n,bag:i}=Cp(e,"sections","section");return{width:r.get("width"),sections:n.map(o=>Ate(o,t)),bag:i}}function Ate(e,t){var r,n,i;let o=Da(e),{modeled:a,bag:s}=Cp(e,"rows","row");return{id:(r=o.get("id"))!==null&&r!==void 0?r:"",name:(n=o.get("name"))!==null&&n!==void 0?n:"",label:Lb(e,t),visible:o.has("visible")?o.get("visible")==="true":!0,showLabel:o.get("showlabel")==="true",columns:JL((i=o.get("columns"))!==null&&i!==void 0?i:"1"),rows:a.map(l=>Ste(l,t)),bag:s}}function Ste(e,t){let{modeled:r,bag:n}=YL(e,"cell",!1);return{cells:r.map(i=>Nte(i,t)),bag:n}}function Nte(e,t){var r;let n=Da(e),{modeled:i,bag:o}=YL(e,"control",!0),a=Lb(e,t),s=n.get("showlabel")==="true",l=i[0]?_te(i[0],a,s):null;return{id:(r=n.get("id"))!==null&&r!==void 0?r:"",visible:n.has("visible")?n.get("visible")==="true":!0,colspan:Ib(n.get("colspan"),1),rowspan:Ib(n.get("rowspan"),1),control:l,bag:o}}function _te(e,t,r){var n,i;let o=Da(e),a=fc((n=o.get("classid"))!==null&&n!==void 0?n:""),s=o.get("datafieldname");return{id:(i=o.get("id"))!==null&&i!==void 0?i:"",classId:a,fieldName:s||null,type:Rb(a),isRequired:o.get("isrequired")==="true",isReadOnly:o.get("disabled")==="true",label:t,showLabel:r,parameters:wte(e),bag:{a:dc(e),c:e.getAllChildren().map((l,u)=>({i:u,node:(0,At.rawFromNode)(l)}))}}}function Uo(e){return e.a.length===0&&e.c.length===0&&!e.w}function QL(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function Ia(e,t){var r;let n=new Set(e.a.map(a=>a[0])),i=Uo(e),o=[];for(let a of t)if(n.has(a.key)){let s=(r=QL(e,a.key))!==null&&r!==void 0?r:"";a.matches(s)||o.push([a.key,a.render()])}else i?o.push([a.key,a.render()]):a.matches(a.absentDefault)||o.push([a.key,a.render()]);return(0,At.mergeAttrs)(e.a,o)}var Fo=(e,t)=>({key:e,matches:r=>r===t,render:()=>t,absentDefault:""}),Mo=(e,t,r=!1)=>({key:e,matches:n=>n==="true"===t,render:()=>String(t),absentDefault:String(r)}),GL=(e,t,r=1)=>({key:e,matches:n=>Ib(n,r)===t,render:()=>String(t),absentDefault:String(r)});function kb(e,t){return{n:"labels",a:[],c:[{n:"label",a:[["description",e],["languagecode",String(t)]],c:[]}]}}function Ob(e){return{n:"parameters",a:[],c:Object.keys(e).map(t=>{var r;return{n:(0,Pb.assertXmlName)(t,"Form control parameter name"),a:[],c:[{n:`<${(r=e[t])!==null&&r!==void 0?r:""}`,a:[],c:[]}]}})}}function Tte(e,t){var r,n;let i=e.c.find(a=>a.n==="label"&&a.a.some(s=>s[0]==="languagecode"&&s[1]===String(t))),o=i??e.c.find(a=>a.n==="label");return(n=(r=o?.a.find(a=>a[0]==="description"))===null||r===void 0?void 0:r[1])!==null&&n!==void 0?n:""}function Dte(e,t,r){let n=!1,i=e.c.map(o=>o.n!=="label"||!o.a.some(s=>s[0]==="languagecode"&&s[1]===String(r))?o:(n=!0,{...o,a:o.a.map(s=>s[0]==="description"?["description",t]:s)}));return n||i.push({n:"label",a:[["description",t],["languagecode",String(r)]],c:[]}),{...e,c:i}}function $b(e,t,r){let n=e.c.findIndex(o=>o.node.n==="labels");if(n<0){if(!t||Uo(e))return e;let a=e.c.some(s=>s.i===0)?e.c.map(s=>({...s,i:s.i+1})):e.c;return{...e,c:[{i:0,node:kb(t,r)},...a]}}if(Tte(e.c[n].node,r)===t)return e;let i=Dte(e.c[n].node,t,r);return{...e,c:e.c.map((o,a)=>a===n?{...o,node:i}:o)}}function Ite(e){let t={};for(let r of e.c){let n=r.n;if(n.charAt(0)==="<"||n.charAt(0)==="#")continue;let i=r.c[0],o=i?i.n:"";o.charAt(0)==="<"&&(o=o.substring(1)),t[n]=o}return t}function Ote(e,t){let r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every(i=>e[i]===t[i])}function Pte(e,t){return e.a.some(r=>r[0]===t)?{...e,a:e.a.filter(r=>r[0]!==t)}:e}function Rte(e,t){let r=e.c.findIndex(i=>i.node.n==="parameters");if(r<0){if(Object.keys(t).length===0||Uo(e))return e;let i=e.c.reduce((o,a)=>a.i>o?a.i:o,-1);return{...e,c:[...e.c,{i:i+1,node:Ob(t)}]}}if(Ote(Ite(e.c[r].node),t))return e;let n=Ob(t);return{...e,c:e.c.map((i,o)=>o===r?{...i,node:n}:i)}}function Ep(e,t,r,n){if(e.w){let a={n:e.w.n,a:e.w.a.map(s=>[s[0],s[1]]),c:(0,At.spliceChildren)(e.w.c,r)};return(0,At.spliceChildren)(e.c,[a])}let i=n(),o={n:t,a:[],c:r};return e.c.length===0?[...i,o]:(0,At.spliceChildren)(e.c,[...i,o])}function Lte(e,t){let r=e.tabs.map(n=>kte(n,t));return{n:"form",a:Ia(e.bag,[]),c:e.tabs.length===0&&Uo(e.bag)?[]:Ep(e.bag,"tabs",r,()=>[])}}function XL(e,t,r){return t&&!e.c.some(n=>n.node.n==="labels")?[kb(t,r)]:[]}function kte(e,t){let r=[Fo("id",e.id),Fo("name",e.name),Mo("expanded",e.expanded),Mo("visible",e.visible,!0)],n=e.columns.map(o=>$te(o,t)),i=$b(e.bag,e.label,t);return{n:"tab",a:Ia(i,r),c:Ep(i,"columns",n,()=>XL(i,e.label,t))}}function $te(e,t){let r=e.width!==void 0?[Fo("width",e.width)]:[],n=e.sections.map(i=>xte(i,t));return{n:"column",a:Ia(e.bag,r),c:Ep(e.bag,"sections",n,()=>[])}}function xte(e,t){let r=[Fo("id",e.id),Fo("name",e.name),Mo("showlabel",e.showLabel),Mo("visible",e.visible,!0),{key:"columns",matches:o=>JL(o)===e.columns,render:()=>Tb(e.columns),absentDefault:Tb(1)}],n=e.rows.map(o=>Fte(o,t)),i=$b(e.bag,e.label,t);return{n:"section",a:Ia(i,r),c:Ep(i,"rows",n,()=>XL(i,e.label,t))}}function Fte(e,t){let r=e.cells.map(n=>Mte(n,t));return{n:"row",a:Ia(e.bag,[]),c:Uo(e.bag)?r:(0,At.assembleChildren)(e.bag,r)}}function Mte(e,t){let r=e.control?e.control.showLabel:QL(e.bag,"showlabel")==="true",n=[Fo("id",e.id),Mo("showlabel",r),Mo("visible",e.visible,!0),GL("colspan",e.colspan),GL("rowspan",e.rowspan)],i=e.control?[Ute(e.control)]:[],o;if(Uo(e.bag))o=[...e.control&&e.control.label?[kb(e.control.label,t)]:[],...i];else{let a=e.control?$b(e.bag,e.control.label,t):e.bag;o=(0,At.assembleChildren)(a,i)}return{n:"cell",a:Ia(e.bag,n),c:o}}function Ute(e){let t=[Fo("id",e.id),{key:"classid",matches:i=>fc(i)===e.classId,render:()=>Db(e.classId||String(ot.ControlClassId.TextboxControl)),absentDefault:""}];e.fieldName!==null&&t.push(Fo("datafieldname",e.fieldName)),t.push(Mo("disabled",e.isReadOnly)),t.push(Mo("isrequired",e.isRequired));let r=e.fieldName===null?Pte(e.bag,"datafieldname"):e.bag,n;return Uo(r)?n=Object.keys(e.parameters).length>0?[Ob(e.parameters)]:[]:n=(0,At.assembleChildren)(Rte(r,e.parameters),[]),{n:"control",a:Ia(r,t),c:n}}var Bte={make:(e,t)=>new pte.FormElementNode(e,t),setProp:(e,t,r)=>e.setProperty(t,r),addChild:(e,t)=>e.addChild(t)};function WL(e,t,r,n){(0,_b.installDomShim)();let i=Vte(e,r);(0,ir.reconcileEmbedDescriptions)(i,n),(0,mi.reconcilePcfDescriptions)(i,n,r?.pcf);let o=(0,At.rebuildRaw)(Lte(i,t),Bte,null);return new hte.SerializationService(t).serializeFormXmlNode(o)}function qte(e){return JSON.parse(JSON.stringify(e))}function Vte(e,t){let r=qte(e);r.bag||(r.bag=(0,At.emptyBag)()),r.tabs||(r.tabs=[]),Yte(r.bag),t&&Gte(r,t);for(let n of r.tabs)Wte(n);return r}function Gte(e,t){var r;let n=(r=e.entityLogicalName)!==null&&r!==void 0?r:"";xb(e,i=>{let o=i.fieldName,a=i;if(!o||a.label!==void 0&&a.classId!==void 0)return;let s=t.resolveField(n,o);s&&(a.label===void 0&&s.displayName&&(a.label=s.displayName),a.classId===void 0&&s.attributeType&&(a.classId=ek(s.attributeType)))})}function zL(e){let t=[];return xb(e,r=>t.push(r)),t}function xb(e,t){var r,n,i,o,a;for(let s of(r=e.tabs)!==null&&r!==void 0?r:[])for(let l of(n=s.columns)!==null&&n!==void 0?n:[])for(let u of(i=l.sections)!==null&&i!==void 0?i:[])for(let c of(o=u.rows)!==null&&o!==void 0?o:[])for(let d of(a=c.cells)!==null&&a!==void 0?a:[])d.control&&t(d.control)}function Wte(e){e.id||(e.id=Xi.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)zte(t);e.bag||(e.bag=(0,At.emptyBag)())}function zte(e){e.sections||(e.sections=[]);for(let t of e.sections)jte(t);e.bag||(e.bag=(0,At.emptyBag)()),e.width===void 0&&Uo(e.bag)&&(e.width="100%")}function jte(e){e.id||(e.id=Xi.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)Hte(t);e.bag||(e.bag=(0,At.emptyBag)())}function Hte(e){e.cells||(e.cells=[]);for(let t of e.cells)Kte(t);e.bag||(e.bag=(0,At.emptyBag)())}function Kte(e){(0,ir.hasGenPage)(e.control)&&(0,ir.applyEmbedCellDefaults)(e),e.id||(e.id=Xi.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&&Jte(e.control),e.bag||(e.bag=(0,At.emptyBag)())}function Jte(e){var t;(0,ir.hasGenPage)(e)&&(0,ir.applyEmbedControlDefaults)(e),e.id||(e.id=Xi.Guid.NewGuid()),(e.classId===void 0||e.classId===null)&&(e.classId=String(ot.ControlClassId.TextboxControl)),e.fieldName===void 0&&(e.fieldName=null),e.type===void 0&&(e.type=e.fieldName?"Field":Rb(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,Pb.assertXmlName)(r,"Form control parameter name");e.bag||(e.bag=(0,At.emptyBag)())}function Yte(e){for(let t of e.c){let r=t.node;if(r.n==="events"){for(let n of r.c)if(n.n==="event"){for(let i of n.c)if(i.n==="Handlers")for(let o of i.c)o.n==="Handler"&&!jL(o,"handlerUniqueId")&&o.a.push(["handlerUniqueId",Db(Xi.Guid.NewGuid())])}}else if(r.n==="formLibraries")for(let n of r.c)n.n==="Library"&&!jL(n,"libraryUniqueId")&&n.a.push(["libraryUniqueId",Db(Xi.Guid.NewGuid())])}}var wp=class{constructor(t=HL.DEFAULT_LCID){this.lcid=t}toArtifact(t,r){var n,i,o;let{tabs:a,bag:s}=VL(t,this.lcid),l={id:t.formId?t.formId.guidString:"",name:(n=t.formName)!==null&&n!==void 0?n:"",entityLogicalName:(i=t.entityName)!==null&&i!==void 0?i:"",formType:(o=bte[t.formType])!==null&&o!==void 0?o:"Main",status:this.readActivationStatus(t),...r!==void 0&&r!==""?{description:r}:{},tabs:a,bag:s};return(0,ir.projectGenPageEmbeds)(l),(0,mi.projectPcfBindings)(l),l}fromArtifact(t){var r;return this.deserialize({formxml:WL(t,this.lcid),formid:t.id||(0,dl.newId)(),objecttypecode:t.entityLogicalName,type:vp[t.formType],name:t.name,uniquename:t.name,description:(r=t.description)!==null&&r!==void 0?r:"",formpresentation:Et.FormPresentation.AirForm,formactivationstate:t.status==="Active"?Et.FormActivationState.Active:Et.FormActivationState.InActive})}fromApiResponse(t){var r,n,i,o,a,s,l;let u=t,c=(r=u.formxml)!==null&&r!==void 0?r:"",d={formxml:c,formid:(n=u.formid)!==null&&n!==void 0?n:(0,dl.newId)(),objecttypecode:(i=u.objecttypecode)!==null&&i!==void 0?i:"",type:u.type,name:(o=u.name)!==null&&o!==void 0?o:"",uniquename:(a=u.uniquename)!==null&&a!==void 0?a:"",description:(s=u.description)!==null&&s!==void 0?s:"",formpresentation:u.formpresentation,formactivationstate:u.formactivationstate};(0,_b.installDomShim)();let f=BL.ScriptUtilities.ParseXml(c),m=Qte(f),p=this.deserializeDocument(d,f);return Xte(this.toArtifact(p,(l=u.description)!==null&&l!==void 0?l:void 0),m)}toApiPayload(t,r,n){let i=(0,ir.genPageEmbedIssues)(t);if(i.length>0)throw new cl.ValidationError("form",t.id,i);let o=(0,mi.pcfBindingIssues)(t,r,{atPush:!0});if(o.length>0)throw new cl.ValidationError("form",t.id,o);let a=(0,mi.pcfReadIssues)(t,n?.pcf,r);if(a.unavailable)throw(0,cl.attachCause)(new cl.SdkError(a.unavailable.code,a.unavailable.message),a.unavailable.cause);if(a.issues.length>0)throw new cl.ValidationError("form",t.id,a.issues);return{formxml:WL(t,this.lcid,n,r),name:t.name,type:vp[t.formType],objecttypecode:t.entityLogicalName,...t.description!==void 0?{description:t.description}:{}}}metadataNeeds(t){let r=t.entityLogicalName;if(!r)return[];let n=new Map;return xb(t,i=>{var o;let a=i.fieldName,s=i;if(!a||s.label!==void 0&&s.classId!==void 0)return;let l=(o=n.get(a))!==null&&o!==void 0?o:{entityLogicalName:r,fieldName:a};s.label===void 0&&(l.needsLabel=!0),n.set(a,l)}),[...n.values()]}customControlNeeds(t,r){var n;return{entityLogicalName:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",...(0,mi.customControlNeeds)(t,r)}}createDefault(t){var r,n,i,o,a,s,l,u,c,d,f,m;let p=[...(0,ir.genPageEmbedIssues)(t),...(0,mi.pcfBindingIssues)(t)];if(p.length>0)throw new cl.ValidationError("form",t.id||"(new)",p);let h=t.tabs&&t.tabs.length>0?void 0:lre(this.lcid),g=h!==void 0?h:t.tabs.map(C=>Zte(C,this.lcid)).join(""),b=this.deserialize({formxml:`<form><tabs>${g}</tabs></form>`,formid:t.id||(0,dl.newId)(),objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",type:vp[(n=t.formType)!==null&&n!==void 0?n:"Main"],name:(i=t.name)!==null&&i!==void 0?i:"New Form",uniquename:(o=t.name)!==null&&o!==void 0?o:"New Form",description:(a=t.description)!==null&&a!==void 0?a:"",formpresentation:Et.FormPresentation.AirForm,formactivationstate:((s=t.status)!==null&&s!==void 0?s:"Active")==="Active"?Et.FormActivationState.Active:Et.FormActivationState.InActive});(l=b.displayCondition)===null||l===void 0||l.removeProperty(Et.ElementProperties.Order);let w=this.toArtifact(b,t.description);if(t.tabs&&t.tabs.length>0){let C=zL(t);zL(w).forEach((S,O)=>{C[O]&&C[O].label===void 0&&delete S.label,C[O]&&C[O].genPage!==void 0&&(S.genPage=JSON.parse(JSON.stringify(C[O].genPage))),C[O]&&C[O].customControl!==void 0&&(S.customControl=JSON.parse(JSON.stringify(C[O].customControl)))})}return{id:(u=t.id)!==null&&u!==void 0?u:w.id,name:(c=t.name)!==null&&c!==void 0?c:"New Form",entityLogicalName:(d=t.entityLogicalName)!==null&&d!==void 0?d:"",formType:(f=t.formType)!==null&&f!==void 0?f:"Main",status:(m=t.status)!==null&&m!==void 0?m:"Active",...t.description!==void 0?{description:t.description}:{},tabs:w.tabs,bag:w.bag}}assignMissingIds(t){return(0,dl.assignMissingIds)(t)}completeAsStored(t,r){return(0,yte.completeRecordAsStored)(t,r,this.lcid)}normalize(t){return(0,mi.mintPcfIdentity)((0,ir.mintEmbedIdentity)(t))}committed(t,r){var n,i,o,a,s,l;let u=r?.formxml;if(typeof u!="string"||!((0,ir.mayCommitEmbedState)(t)||(0,mi.mayCommitPcfState)(t)))return{artifact:t,baseline:t};let c=this.deserialize({formxml:u,formid:t.id||(0,dl.newId)(),objecttypecode:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",type:vp[(i=t.formType)!==null&&i!==void 0?i:"Main"],name:(o=t.name)!==null&&o!==void 0?o:"",uniquename:(a=t.name)!==null&&a!==void 0?a:"",description:(s=t.description)!==null&&s!==void 0?s:"",formpresentation:Et.FormPresentation.AirForm,formactivationstate:Et.FormActivationState.Active}),{bag:d}=VL(c,this.lcid),f=(0,mi.commitPcfState)((0,ir.commitEmbedState)(t,(l=(0,ir.descriptionsRegion)(d))===null||l===void 0?void 0:l.node),Rb);return{artifact:f,baseline:f}}validate(t){return yre(t)}deserialize(t){return(0,_b.installDomShim)(),this.deserializeDocument(t,BL.ScriptUtilities.ParseXml(t.formxml))}deserializeDocument(t,r){let n=new mte.DeserializationService(this.lcid).deSerializeFormXml(r,new Xi.Guid(t.formid),t.objecttypecode,Et.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===Et.FormActivationState.InActive?"Inactive":"Active"}};Mr.FormAdapter=wp;var ZL=["header","footer","DisplayConditions"];function Qte(e){var t;let r=e?.getElementsByTagName("form")[0],n=new Set;for(let i=(t=r?.firstChild)!==null&&t!==void 0?t:null;i;i=i.nextSibling)i.nodeType===1&&ZL.includes(i.nodeName)&&n.add(i.nodeName);return n}function Xte(e,t){var r;if(!(!((r=e.bag)===null||r===void 0)&&r.c))return e;let n=ZL.filter(o=>!t.has(o)),i=e.bag.c.filter(o=>{var a;return n.includes((a=o?.node)===null||a===void 0?void 0:a.n)}).map(o=>o.i);return i.length>0&&(e.bag.c=e.bag.c.filter(o=>{var a;return!n.includes((a=o?.node)===null||a===void 0?void 0:a.n)}).map(o=>({...o,i:o.i-i.filter(a=>a<o.i).length}))),e}function Un(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Fb(e,t){return e?`<labels><label description="${Un(e)}" languagecode="${t}" /></labels>`:""}function Mb(e){return e&&e.length>0?fc(e):(0,dl.newId)()}function Zte(e,t){var r,n,i,o;let a=(r=e.columns)!==null&&r!==void 0?r:[],s=(a.length>0?a:[sre()]).map(l=>ere(l,t)).join("");return`<tab id="{${Un(Mb(e.id))}}" name="${Un((n=e.name)!==null&&n!==void 0?n:"")}" expanded="${(i=e.expanded)!==null&&i!==void 0?i:!0}" visible="${(o=e.visible)!==null&&o!==void 0?o:!0}">${Fb(e.label,t)}<columns>${s}</columns></tab>`}function ere(e,t){var r,n;let i=((r=e.sections)!==null&&r!==void 0?r:[]).map(o=>tre(o,t)).join("");return`<column width="${Un((n=e.width)!==null&&n!==void 0?n:"100%")}"><sections>${i}</sections></column>`}function tre(e,t){var r,n,i,o,a;let s=((r=e.rows)!==null&&r!==void 0?r:[]).map(l=>rre(l,t)).join("");return`<section id="{${Un(Mb(e.id))}}" name="${Un((n=e.name)!==null&&n!==void 0?n:"")}" showlabel="${(i=e.showLabel)!==null&&i!==void 0?i:!1}" visible="${(o=e.visible)!==null&&o!==void 0?o:!0}" columns="${Tb((a=e.columns)!==null&&a!==void 0?a:1)}">${Fb(e.label,t)}<rows>${s}</rows></section>`}function rre(e,t){var r;return`<row>${((r=e.cells)!==null&&r!==void 0?r:[]).map(n=>nre(n,t)).join("")}</row>`}function nre(e,t){var r,n,i,o,a;let s=ire(e),l=s.control,u=l?Fb((r=l.label)!==null&&r!==void 0?r:"",t):"",c=l?ore(l):"";return`<cell id="{${Un(Mb(s.id))}}" showlabel="${l?(n=l.showLabel)!==null&&n!==void 0?n:!0:!1}" visible="${(i=s.visible)!==null&&i!==void 0?i:!0}" colspan="${(o=s.colspan)!==null&&o!==void 0?o:1}" rowspan="${(a=s.rowspan)!==null&&a!==void 0?a:1}">${u}${c}</cell>`}function ire(e){if(!(0,ir.hasGenPage)(e.control))return e;let t={...e.control};(0,ir.applyEmbedControlDefaults)(t);let r={...e,control:t};return(0,ir.applyEmbedCellDefaults)(r),r}function ore(e){var t,r,n;let i=e.fieldName?` datafieldname="${Un(e.fieldName)}"`:"",o=are(e.parameters),a=e.classId?fc(e.classId):String(ot.ControlClassId.TextboxControl);return`<control id="${Un((t=e.id)!==null&&t!==void 0?t:"")}" classid="{${Un(a)}}"${i} disabled="${(r=e.isReadOnly)!==null&&r!==void 0?r:!1}" isrequired="${(n=e.isRequired)!==null&&n!==void 0?n:!1}">${o}</control>`}function are(e){let t=Object.keys(e??{});return t.length===0?"":(t.forEach(n=>(0,Pb.assertXmlName)(n,"Form control parameter name")),`<parameters>${t.map(n=>`<${n}>${Un(e[n])}</${n}>`).join("")}</parameters>`)}function sre(){return{width:"100%",sections:[],bag:{a:[],c:[]}}}function lre(e){return`<tab id="{${Xi.Guid.NewGuid()}}" name="tab_general" expanded="true" visible="true"><labels><label description="General" languagecode="${e}" /></labels><columns><column width="100%"><sections><section id="{${Xi.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 ure(e=HL.DEFAULT_LCID){return{adapter:new wp(e),api:gte.formApi,languageSensitive:!0,publish:(t,r,n)=>(0,qL.publishBoundEntity)(t,n),publishScope:(t,r)=>(0,qL.boundEntityPublishScope)(r),rebaselineAfterPublish:"bracket"}}Mr.formRegistration=ure;var cre=new Set(["id","name","label","expanded","visible","columns","bag"]),dre=new Set(["id","width","sections","bag"]),fre=new Set(["id","name","label","visible","showLabel","columns","rows","bag"]),pre=new Set(["id","cells","bag"]),mre=new Set(["id","visible","colspan","rowspan","control","bag"]),hre=new Set(["id","classId","fieldName","type","isRequired","isReadOnly","label","showLabel","parameters","genPage","customControl","bag"]),gre={elsewhere:{isReadOnly:"control",isRequired:"control",fieldName:"control",classId:"control",label:"control",showLabel:"control",parameters:"control"},unsupported:{createOnly:"FormXml has no create-only concept; gate the field with a business rule instead. Raise it with the SDK owners if you need it modeled.",updateOnly:"FormXml has no update-only concept; gate the field with a business rule instead. Raise it with the SDK owners if you need it modeled."}};function yre(e){let t=[];return(0,Fr.childObjects)(e,"tabs","","tab",t).forEach(({node:n,index:i})=>{let o=`/tabs/${i}`;(0,Fr.rejectUnknownKeys)(n,cre,o,"tab",t),(0,Fr.childObjects)(n,"columns",o,"column",t).forEach(({node:s,index:l})=>{let u=`${o}/columns/${l}`;(0,Fr.rejectUnknownKeys)(s,dre,u,"column",t),(0,Fr.childObjects)(s,"sections",u,"section",t).forEach(({node:d,index:f})=>{let m=`${u}/sections/${f}`;(0,Fr.rejectUnknownKeys)(d,fre,m,"section",t),(0,Fr.childObjects)(d,"rows",m,"row",t).forEach(({node:h,index:g})=>{let b=`${m}/rows/${g}`;(0,Fr.rejectUnknownKeys)(h,pre,b,"row",t),(0,Fr.childObjects)(h,"cells",b,"cell",t).forEach(({node:C,index:S})=>{let O=`${b}/cells/${S}`;(0,Fr.rejectUnknownKeys)(C,mre,O,"cell",t,gre);let L=C.control;L!=null&&!(0,Fr.isJsonObject)(L)?t.push((0,Fr.issue)(`${O}/control`,"control-must-be-object-or-null",`a cell control must be a JSON object or null, got ${typeof L}`)):(0,Fr.isJsonObject)(L)&&(0,Fr.rejectUnknownKeys)(L,hre,`${O}/control`,"control",t)})})})})}),t.push(...(0,ir.genPageEmbedIssues)(e)),t.push(...(0,mi.pcfBindingIssues)(e)),t}Mr.SUBGRID_CLASS_ID=ot.ControlClassId.SubgridControl;Mr.NOTES_CLASS_ID=ot.ControlClassId.TimelineControl;Mr.QUICK_VIEW_CLASS_ID=ot.ControlClassId.QuickViewControl;var bre={Lookup:String(ot.ControlClassId.LookupControl),Customer:String(ot.ControlClassId.LookupControl),Owner:String(ot.ControlClassId.LookupControl),PartyList:String(ot.ControlClassId.PartyListControl),Boolean:String(ot.ControlClassId.BooleanControl),DateTime:String(ot.ControlClassId.DateTimeControl),Decimal:String(ot.ControlClassId.DecimalControl),Double:String(ot.ControlClassId.FloatingNumberControl),Money:String(ot.ControlClassId.CurrencyControl),Integer:String(ot.ControlClassId.IntegerControl),BigInt:String(ot.ControlClassId.IntegerControl),Memo:String(ot.ControlClassId.TextAreaControl),String:String(ot.ControlClassId.TextboxControl)},vre="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE";function ek(e){return e==="Picklist"||e==="State"||e==="Status"?vre:e&&bre[e]||String(ot.ControlClassId.TextboxControl)}Mr.classIdForAttributeType=ek;function jL(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}});var Ub=v(fl=>{"use strict";Object.defineProperty(fl,"__esModule",{value:!0});fl.viewApi=fl.findDefaultViews=void 0;var ok=Tt(),yr=fe(),Bn=oe(),wre=ys(),rk="savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault",Cre="savedqueryid,name,returnedtypecode,querytype,isdefault",Ere=60*1e3;function Ap(e){return(e.localName||e.nodeName).toLowerCase()}function pc(e,t){let r;for(let n=0;n<e.attributes.length;n+=1){let i=e.attributes[n];i.nodeName.toLowerCase()===t&&(r=r===void 0?i.value:null)}return r}function Are(e){if(!e)return;let t=!0,r=()=>{t=!1},n=new wre.DOMParser({errorHandler:{warning:r,error:r,fatalError:r}}).parseFromString(e,"text/xml").documentElement;return t&&n&&Ap(n)==="fetch"?n:void 0}function Sre(e){for(let t=e.parentNode;t;t=t.parentNode)if(Ap(t)==="link-entity")return!0;return!1}function nk(e,t){var r,n,i;if(((r=e.canbedeleted)===null||r===void 0?void 0:r.Value)!==!1)return!1;let o=Are(e.fetchxml);if(!o)return!1;let a=Array.from(o.getElementsByTagName("*")),s=a.filter(u=>Ap(u)==="condition"),l=s.length===1?s[0]:void 0;return l!==void 0&&a.filter(u=>Ap(u)==="link-entity").every(u=>{var c;return((c=pc(u,"link-type"))===null||c===void 0?void 0:c.toLowerCase())==="outer"})&&!Sre(l)&&pc(l,"entityname")===void 0&&((n=pc(l,"attribute"))===null||n===void 0?void 0:n.toLowerCase())==="statecode"&&((i=pc(l,"operator"))===null||i===void 0?void 0:i.toLowerCase())==="eq"&&pc(l,"value")===String(t)}function Nre(e,t){let r=String(e??"").trim().toLowerCase().split(/\s+/).filter(i=>i!==""),n=String(t??"").trim().toLowerCase().split(/\s+/).filter(i=>i!=="");return r.length===n.length&&r.filter((i,o)=>i!==n[o]).length===1}function _re(e){var t,r;let n=e.filter(a=>nk(a,0)),i=e.filter(a=>nk(a,1)),o=[];for(let a of n)for(let s of i)Math.abs(Date.parse(String((t=s.createdon)!==null&&t!==void 0?t:""))-Date.parse(String((r=a.createdon)!==null&&r!==void 0?r:"")))<=Ere&&Nre(a.name,s.name)&&o.push({active:a,inactive:s});return o.length===1?o[0]:void 0}async function Tre(e,t,r={}){var n;let i=new Set(((n=r.excludeViewIds)!==null&&n!==void 0?n:[]).filter(Boolean)),o=`returnedtypecode eq '${(0,Bn.odataLiteral)(t)}' and querytype eq 0`,a=`/savedqueries${(0,Bn.odataQuery)([["$select","savedqueryid,name,canbedeleted,fetchxml,createdon"],["$filter",o]])}`,s=await(0,ok.collectPages)(e,a,`findDefaultViews('${t}')`),l=_re(s),u=new Set(l?[l.active,l.inactive]:[]);return s.filter(c=>c.savedqueryid&&!i.has(c.savedqueryid)&&u.has(c)).map(c=>{var d;return{id:String(c.savedqueryid),name:String((d=c.name)!==null&&d!==void 0?d:"")}})}fl.findDefaultViews=Tre;async function Dre(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,Bn.odataPathLiteral)(t)}')${(0,Bn.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status>=200&&i.status<300){let o=(r=i.body)===null||r===void 0?void 0:r.ObjectTypeCode;return typeof o=="number"?o:void 0}}async function ik(e,t,r){if(!r||!/<grid\b/.test(t)||/<grid[^>]*\bobject=/.test(t))return t;let n=await Dre(e,r);return n===void 0?t:t.replace(/<grid\b/,`<grid object="${n}"`)}fl.viewApi={async get(e,t){let r=(0,Bn.normalizeGuid)(t,"id"),n=await(0,yr.readRowEtag)(e,"savedqueries","savedqueryid",r),i=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Bn.odataQuery)([["$select",rk]]);return{raw:(0,yr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},async readContentThenToken(e,t){let r=(0,Bn.normalizeGuid)(t,"id"),n=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Bn.odataQuery)([["$select",rk]]),i=(0,yr.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=await(0,yr.readRowEtag)(e,"savedqueries","savedqueryid",r);return{raw:i.body,etag:o}},async list(e,t){let r=`/savedqueries${(0,Bn.odataQuery)([["$select",Cre],["$filter",t?.entityLogicalName?`returnedtypecode eq '${(0,Bn.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,ok.collectPages)(e,r,"listArtifacts('view')")).map(i=>{var o,a;return{type:"view",id:(o=i.savedqueryid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",entityLogicalName:i.returnedtypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,yr.echoWrite)("savedqueryid"),o=`/savedqueries${i.query}`,a=await ik(e,n.layoutxml,n.returnedtypecode),s=Object.freeze((0,yr.withClientMintedId)({name:n.name,description:n.description,fetchxml:n.fetchxml,layoutxml:a,returnedtypecode:n.returnedtypecode,querytype:n.querytype,isdefault:n.isdefault},"savedqueryid",r)),l=(0,yr.ensureSuccess)(await(0,yr.resendDeadlockVictim)(()=>e.post(o,{...s},i.options)),e.apiUrl(o));return{id:(0,yr.resolveCreatedId)(l,"savedqueryid","view",r),etag:(0,yr.readEtag)(l)}},async update(e,t,r,n){let i=r,o=(0,Bn.normalizeGuid)(t,"id"),a=(0,yr.echoWrite)("savedqueryid",{"If-Match":(0,yr.requireEtag)(n,"view",o)}),s=`/savedqueries(${o})${a.query}`,l=await ik(e,i.layoutxml,i.returnedtypecode),u=(0,yr.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,fetchxml:i.fetchxml,layoutxml:l},a.options),e.apiUrl(s));return{id:o,etag:(0,yr.readEtag)(u)}},delete(e,t){return(0,yr.deleteRecord)(e,"savedqueries",t)}}});var Ck=v(pl=>{"use strict";Object.defineProperty(pl,"__esModule",{value:!0});pl.viewRegistration=pl.ViewAdapter=void 0;var fk=Q(),en=cn(),Bb=wo(),Oa=Eo(),ak=jr(),Ire=Ub(),qb=Co(),Ore=ct(),pk=100,Np=class{toArtifact(t){var r,n,i,o,a,s,l,u;(0,qb.installDomShim)();let c=(r=t.fetchxml)!==null&&r!==void 0?r:"",d=(n=t.layoutxml)!==null&&n!==void 0?n:"",f=(0,Oa.parseXmlRoot)(c,"<fetch/>"),m=(0,Oa.parseXmlRoot)(d,"<grid/>"),p=hk(f);return{id:(i=t.savedqueryid)!==null&&i!==void 0?i:"",name:(o=t.name)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",entityLogicalName:(s=t.returnedtypecode)!==null&&s!==void 0?s:Rre(f),queryType:(l=t.querytype)!==null&&l!==void 0?l:0,isDefault:(u=t.isdefault)!==null&&u!==void 0?u:!1,columns:mk(m,f),filters:yk(f),sort:gk(f),...p.length>0?{linkEntities:p}:{},fetchBag:c?(0,Oa.projectElementBag)(f):void 0,layoutBag:d?(0,Oa.projectElementBag)(m):void 0}}fromArtifact(t){(0,qb.installDomShim)();let{fetchxml:r,layoutxml:n}=sk(t);return{savedqueryid:t.id,name:t.name,description:t.description,returnedtypecode:t.entityLogicalName,querytype:t.queryType,isdefault:t.isDefault,fetchxml:r,layoutxml:n}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){var r,n,i,o,a;(0,qb.installDomShim)();let{fetchxml:s,layoutxml:l}=sk(t);return{name:(r=t.name)!==null&&r!==void 0?r:"",description:(n=t.description)!==null&&n!==void 0?n:"",fetchxml:s,layoutxml:l,returnedtypecode:(i=t.entityLogicalName)!==null&&i!==void 0?i:"",querytype:(o=t.queryType)!==null&&o!==void 0?o:0,isdefault:(a=t.isDefault)!==null&&a!==void 0?a:!1}}createDefault(t){var r,n,i,o,a,s,l,u;let c=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,Ore.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New View",description:(o=t.description)!==null&&o!==void 0?o:"",entityLogicalName:c,queryType:(a=t.queryType)!==null&&a!==void 0?a:0,isDefault:(s=t.isDefault)!==null&&s!==void 0?s:!1,columns:t.columns&&t.columns.length>0?t.columns:[{name:`${c}id`,width:300,order:0}],filters:(l=t.filters)!==null&&l!==void 0?l:{type:"and",conditions:[],groups:[]},sort:(u=t.sort)!==null&&u!==void 0?u:[],...t.linkEntities&&t.linkEntities.length>0?{linkEntities:t.linkEntities}:{}}}assignMissingIds(t){return t}validate(t){let r=[],n=t;(0,en.childObjects)(n,"columns","","column",r),(0,en.childObjects)(n,"sort","","sort",r),(0,en.childObjects)(n,"linkEntities","","linkEntity",r),Pre(n.linkEntities,r);let i=n.filters;return i!=null&&((0,en.isJsonObject)(i)?Vb(i,"/filters",r):r.push((0,en.issue)("/filters","filters-must-be-object",`filters must be a JSON object, got ${typeof i}`))),r}};pl.ViewAdapter=Np;function Pre(e,t){Array.isArray(e)&&e.forEach((r,n)=>{if(!(0,en.isJsonObject)(r))return;for(let o of["name","from","to"]){let a=r[o];(typeof a!="string"||a.trim()==="")&&t.push((0,en.issue)(`/linkEntities/${n}/${o}`,"linkentity-needs-keys",`a join needs a non-empty '${o}' \u2014 'from'/'to' are what DEFINE the relationship, and a link without them is unresolvable. Got ${JSON.stringify(a)}.`))}let i=r.filters;i!=null&&((0,en.isJsonObject)(i)?Vb(i,`/linkEntities/${n}/filters`,t):t.push((0,en.issue)(`/linkEntities/${n}/filters`,"filters-must-be-object",`filters must be a JSON object, got ${typeof i}`)))})}function Vb(e,t,r){(0,en.childObjects)(e,"conditions",t,"condition",r),(0,en.childObjects)(e,"groups",t,"filterGroup",r).forEach(({node:i,index:o})=>Vb(i,`${t}/groups/${o}`,r))}function Rre(e){var t;let r=e.getElementsByTagName("entity")[0];return(t=r?.getAttribute("name"))!==null&&t!==void 0?t:""}function mk(e,t){var r;let n=_p(t),i=e.getElementsByTagName("cell"),o=[],a=0;for(let s=0;s<i.length;s+=1){let l=i[s];if(l.getAttribute("ishidden")==="1")continue;let u=l.getAttribute("name");if(!u)continue;let c=parseInt((r=l.getAttribute("width"))!==null&&r!==void 0?r:"",10),d={name:u,width:Number.isNaN(c)?pk:c,order:a},f=n.get(u);f&&(d.relatedEntity=f.linkKey,f.attributeName&&f.attributeName!==u&&(d.sourceAttribute=f.attributeName)),a+=1,o.push(d)}return o}function _p(e){let t=new Map,r=e.getElementsByTagName("link-entity");for(let n=0;n<r.length;n+=1){let i=r[n],o=i.getAttribute("name");if(!o)continue;let a=i.getElementsByTagName("attribute");for(let s=0;s<a.length;s+=1){let l=a[s],u=l.getAttribute("name")||"",c=l.getAttribute("alias")||u;c&&t.set(c,{linkKey:i.getAttribute("alias")||o,linkName:o,attributeName:u,link:i})}}return t}function hk(e){let t=e.getElementsByTagName("entity")[0];if(!t)return[];let r=[];for(let n of Wt(t,"link-entity")){let i=n.getAttribute("name"),o=n.getAttribute("from"),a=n.getAttribute("to");if(!i||!o||!a)continue;let s=n.getAttribute("alias"),l=n.getAttribute("link-type"),u=Wt(n,"filter").find(c=>!Tp(c));r.push({name:i,from:o,to:a,...s?{alias:s}:{},...l==="inner"||l==="outer"?{linkType:l}:{},...u?{filters:Gb(u)}:{}})}return r}function gk(e){var t;let r=e.getElementsByTagName("entity")[0];if(!r)return[];let n=[],i=r.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];if(a.nodeType===1&&a.tagName==="order"){let s=a.getAttribute("attribute");s&&n.push({attribute:s,descending:((t=a.getAttribute("descending"))!==null&&t!==void 0?t:"").toLowerCase()==="true",entityname:a.getAttribute("entityname")||""})}}return n}function yk(e){let t=e.getElementsByTagName("entity")[0],r={type:"and",conditions:[],groups:[]};if(!t)return r;let n=Wt(t,"filter").filter(i=>!Tp(i)).map(Gb);return n.length===0?r:n.length===1?n[0]:{type:"and",conditions:[],groups:n}}function Tp(e){if(e.getAttribute("isquickfindfields")==="1"||bk(e))return!0;if(Wt(e,"filter").length>0)return!1;let t=Wt(e,"condition");return t.length===0?!1:t.some(r=>r.getAttribute("isquickfindfields")==="1"||Wt(r,"value").length>0||kre(r))}function bk(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r];if(n.nodeType===1&&(n.tagName==="filter"?bk(n):n.tagName!=="condition"))return!0}return!1}var Lre=new Set(["attribute","operator","value","entityname","uiname","uitype"]);function kre(e){var t;let r=e.attributes;for(let n=0;n<r.length;n+=1){let i=(t=r[n])===null||t===void 0?void 0:t.name;if(i&&!Lre.has(i))return!0}return!1}function Gb(e){var t,r;let n=((t=e.getAttribute("type"))!==null&&t!==void 0?t:"and").toLowerCase()==="or"?"or":"and",i=[],o=[],a=e.childNodes;for(let s=0;s<a.length;s+=1){let l=a[s];if(l.nodeType===1)if(l.tagName==="condition"){if(l.getAttribute("isquickfindfields")==="1")continue;let u=l.getAttribute("attribute");if(!u)continue;let c={attribute:u,operator:(r=l.getAttribute("operator"))!==null&&r!==void 0?r:""};l.hasAttribute("value")&&(c.value=l.getAttribute("value")||"");let d=l.getAttribute("entityname")||"";d&&(c.entityname=d),i.push(c)}else l.tagName==="filter"&&o.push(Gb(l))}return{type:n,conditions:i,groups:o}}function Wt(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName===t&&r.push(o)}return r}var Wb=e=>{var t,r;return`${(t=e.relatedEntity)!==null&&t!==void 0?t:""}::${(r=e.sourceAttribute)!==null&&r!==void 0?r:e.name}`};function $re(e,t){let r=_p(e),n=new Map;for(let i of t){if(!i.relatedEntity)continue;let o=r.get(i.name);if(o){let a=Wb(i),s=n.get(a);s?s.push(o.link):n.set(a,[o.link])}}return n}function xre(e,t,r,n){if(!n||n.size===0)return;let i=new Set,o=t.getElementsByTagName("link-entity");for(let s=0;s<o.length;s+=1)i.add(o[s]);let a=r.filter(s=>{if(!s.relatedEntity)return!1;let l=n.get(Wb(s));return!!l&&l.some(u=>!i.has(u))});if(a.length!==0)throw new fk.ValidationError("view",e.id,a.map(s=>(0,en.issue)(`/columns/${r.indexOf(s)}`,"view-column-orphaned-by-join-removal",`column '${s.name}' came from a join this push REMOVED. Another join matching '${s.relatedEntity}' still exists, but nothing can say whether it is the one the column belonged to \u2014 re-attaching it there would silently change the data the column shows. Remove the column too, keep the join it came from, or point the column at the join you want by setting relatedEntity to that join's alias.`)))}function sk(e){var t,r;let n=Fre(e.columns),i=(t=e.sort)!==null&&t!==void 0?t:[],o=(r=e.filters)!==null&&r!==void 0?r:{type:"and",conditions:[],groups:[]};if(!lk(e.fetchBag)||!lk(e.layoutBag))return{fetchxml:Yre({...e,columns:n,sort:i,filters:o}),layoutxml:Qre({...e,columns:n},`${e.entityLogicalName}id`)};let a=new DOMParser().parseFromString("<root/>","text/xml"),s=uk(e.fetchBag,"fetch",a),l=uk(e.layoutBag,"grid",a),u=mk(l,s),c=!Sp(n,u),d=!Sp(i,gk(s)),f=!Sp(o,yk(s)),m=e.linkEntities,p=m!==void 0&&!Sp(m,hk(s)),h=p?$re(s,u):void 0;return p&&Hre(a,s,m),p&&(Jre(e,s,n,h),xre(e,s,n,h)),c?(ck(a,s,n,u),Vre(a,l,n)):p&&ck(a,s,n,u),d&&zre(a,s,i),f&&jre(a,s,o),{fetchxml:(0,Oa.serializeNode)(s),layoutxml:(0,Oa.serializeNode)(l)}}function Fre(e){return(e??[]).map((t,r)=>{var n,i;return{name:String(t.name).toLowerCase(),width:(n=t.width)!==null&&n!==void 0?n:pk,order:(i=t.order)!==null&&i!==void 0?i:r,...t.relatedEntity?{relatedEntity:t.relatedEntity}:{},...t.sourceAttribute?{sourceAttribute:String(t.sourceAttribute).toLowerCase()}:{}}})}function lk(e){return!!e&&(e.c.length>0||e.a.length>0)}function uk(e,t,r){let n={n:t,a:(0,Bb.mergeAttrs)(e.a,[]),c:(0,Bb.spliceChildren)(e.c,[])};return(0,Bb.rebuildRaw)(n,(0,Oa.domEngine)(r),null)}function ck(e,t,r,n){var i,o,a;let s=t.getElementsByTagName("entity")[0];if(!s)return;let l=p=>{var h,g;return`${(h=p.relatedEntity)!==null&&h!==void 0?h:""}:${p.name}:${(g=p.sourceAttribute)!==null&&g!==void 0?g:p.name}`},u=new Set(r.map(l)),c=new Set(r.map(p=>p.name)),d=_p(t);for(let p of n)u.has(l(p))||(Ure(s,p),p.relatedEntity&&c.has(p.name)&&Mre((i=d.get(p.name))===null||i===void 0?void 0:i.link,p.name));let f=_p(t),m=new Set(Wt(s,"attribute").map(p=>p.getAttribute("name")).filter(p=>!!p));for(let p of[...r].sort((h,g)=>h.order-g.order))if(p.relatedEntity){let h=f.get(p.name);if(h&&h.attributeName===((o=p.sourceAttribute)!==null&&o!==void 0?o:p.name)&&(h.linkKey===p.relatedEntity||h.linkName===p.relatedEntity||!wk(s,p.relatedEntity)))continue;let g=Bre(e,s,p.relatedEntity),b=e.createElement("attribute");vk(b,p),g.appendChild(b),f.set(p.name,{linkKey:p.relatedEntity,linkName:g.getAttribute("name")||p.relatedEntity,attributeName:(a=p.sourceAttribute)!==null&&a!==void 0?a:p.name,link:g})}else{if(m.has(p.name))continue;let h=e.createElement("attribute");h.setAttribute("name",p.name),qre(s,h),m.add(p.name)}}function vk(e,t){if(t.sourceAttribute&&t.sourceAttribute!==t.name){e.setAttribute("name",t.sourceAttribute),e.setAttribute("alias",t.name);return}e.setAttribute("name",t.name)}function Mre(e,t){if(e){for(let r of Wt(e,"attribute"))if((r.getAttribute("alias")||r.getAttribute("name"))===t){e.removeChild(r);return}}}function Ure(e,t){if(t.relatedEntity){for(let r of Wt(e,"link-entity"))if(!(r.getAttribute("alias")!==t.relatedEntity&&r.getAttribute("name")!==t.relatedEntity)){for(let n of Wt(r,"attribute"))if((n.getAttribute("alias")||n.getAttribute("name"))===t.name){r.removeChild(n);return}}return}for(let r of Wt(e,"attribute"))if(r.getAttribute("name")===t.name){e.removeChild(r);return}}function wk(e,t,r=!1){let n=o=>o.getAttribute("alias")===t||o.getAttribute("name")===t;for(let o of Wt(e,"link-entity"))if(n(o))return o;if(r)return;let i=e.getElementsByTagName("link-entity");for(let o=0;o<i.length;o+=1)if(n(i[o]))return i[o]}function Bre(e,t,r){let n=wk(t,r);if(n)return n;let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function qre(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 Vre(e,t,r){let n=t.getElementsByTagName("row")[0];if(!n)return;let i=[...r].sort((s,l)=>s.order-l.order),o=Gre(n);if(Wre(o,i)){for(let s=0;s<i.length;s+=1){let l=String(i[s].width);o[s].getAttribute("width")!==l&&o[s].setAttribute("width",l)}return}let a=new Map;for(let s of o){let l=s.getAttribute("name");l&&a.set(l,s),n.removeChild(s)}for(let s of i){let l=a.get(s.name);l||(l=e.createElement("cell"),l.setAttribute("name",s.name)),l.setAttribute("width",String(s.width)),n.appendChild(l)}}function Gre(e){return Wt(e,"cell").filter(t=>!!t.getAttribute("name")&&t.getAttribute("ishidden")!=="1")}function Wre(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 zre(e,t,r){let n=t.getElementsByTagName("entity")[0];if(!n)return;let i=(m,p)=>`${m.toLowerCase()}\0${p.toLowerCase()}`,o=new Map,a=new Map,s=(m,p,h)=>{let g=m.get(p);g?g.push(h):m.set(p,[h])},l=null;for(let m of Wt(n,"order")){let p=m.getAttribute("attribute")||"";p&&(l||(l=e.createTextNode(""),n.insertBefore(l,m)),s(o,i(m.getAttribute("entityname")||"",p),m),s(a,p.toLowerCase(),m),n.removeChild(m))}let u=new Set,c=(m,p)=>{let h=m.get(p);for(;h&&h.length>0;){let g=h.shift();if(!u.has(g))return u.add(g),g}},d=m=>{var p;let h=a.get(m.toLowerCase());if(!h)return;let g=h.filter(w=>!u.has(w)),b=(p=g.find(w=>!w.getAttribute("entityname")))!==null&&p!==void 0?p:g[0];return b&&u.add(b),b},f=r.map(m=>{let p=String(m.attribute);return m.entityname===void 0?{expression:m,element:void 0}:{expression:m,element:c(o,i(m.entityname,p))}});for(let m of f)m.expression.entityname===void 0&&(m.element=d(String(m.expression.attribute)));for(let{expression:m,element:p}of f){let h=p??e.createElement("order");h.setAttribute("attribute",m.attribute),h.setAttribute("descending",String(m.descending)),m.entityname?h.setAttribute("entityname",m.entityname):m.entityname===""&&h.removeAttribute("entityname"),n.insertBefore(h,l)}l&&n.removeChild(l)}function jre(e,t,r){let n=t.getElementsByTagName("entity")[0];if(n){for(let i of Wt(n,"filter"))Tp(i)||n.removeChild(i);(r.conditions.length>0||r.groups.length>0)&&n.appendChild(mc(e,r))}}function Sp(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Hre(e,t,r){var n;let i=t.getElementsByTagName("entity")[0];if(!i)return;let o=Wt(i,"link-entity").filter(p=>p.getAttribute("name")&&p.getAttribute("from")&&p.getAttribute("to")),a=(p,h)=>p.getAttribute(h)||"",s=new Array(r.length),l=new Set,u=p=>{r.forEach((h,g)=>{if(s[g])return;let b=o.filter(S=>!l.has(S)&&p(S,h));if(b.length!==1)return;let w=b[0];r.some((S,O)=>O!==g&&!s[O]&&p(w,S))||(s[g]=w,l.add(w))})};u((p,h)=>!!h.alias&&a(p,"name")===h.name&&a(p,"alias")===h.alias),u((p,h)=>a(p,"name")===h.name&&a(p,"from")===h.from&&a(p,"to")===h.to),u((p,h)=>a(p,"name")===h.name&&a(p,"from")===h.from),u((p,h)=>a(p,"name")===h.name&&a(p,"to")===h.to),u((p,h)=>a(p,"name")===h.name);let c=r.map((p,h)=>h).filter(p=>!s[p]),d=o.filter(p=>!l.has(p)),f=new Map;for(let p of d){let h=f.get(a(p,"name"));h?h.push(p):f.set(a(p,"name"),[p])}let m=new Map;for(let p of c){let h=m.get(r[p].name);h?h.push(p):m.set(r[p].name,[p])}for(let[p,h]of m){let g=(n=f.get(p))!==null&&n!==void 0?n:[];g.length===h.length&&h.forEach((b,w)=>{s[b]=g[w],l.add(g[w])})}r.forEach((p,h)=>{let g=s[h];if(g){dk(e,g,p);return}let b=e.createElement("link-entity");dk(e,b,p),i.appendChild(b)});for(let p of o)l.has(p)||i.removeChild(p)}var Kre=new Set(["inner","outer"]);function Jre(e,t,r,n){if(!t.getElementsByTagName("entity")[0])return;let o=new Set,a=t.getElementsByTagName("link-entity");for(let c=0;c<a.length;c+=1){let d=a[c],f=d.getAttribute("name"),m=d.getAttribute("alias");f&&o.add(f),m&&o.add(m)}let s=new Set;for(let c=0;c<a.length;c+=1)s.add(a[c]);let l=c=>{let d=n?.get(Wb(c));return!!d&&d.every(f=>s.has(f))},u=r.filter(c=>c.relatedEntity&&!o.has(c.relatedEntity)&&!l(c));if(u.length!==0)throw new fk.ValidationError("view",e.id,u.map(c=>{var d;let f=((d=e.linkEntities)!==null&&d!==void 0?d:[]).some(m=>m.name===c.relatedEntity||m.alias===c.relatedEntity);return(0,en.issue)(`/columns/${r.indexOf(c)}`,"view-column-dangling-link",`column '${c.name}' has relatedEntity '${c.relatedEntity}', but no matching join remains in linkEntities. `+(f?"Remove the column too, or keep the join.":"That join is NESTED (a join off a join), which the typed layer does not model, so it cannot be re-declared in linkEntities \u2014 it only survives while the join above it does. Remove the column, or restore the parent join this push replaced."))}))}function dk(e,t,r){t.setAttribute("name",r.name),t.setAttribute("from",r.from),t.setAttribute("to",r.to),r.alias?t.setAttribute("alias",r.alias):t.removeAttribute("alias"),r.linkType?t.setAttribute("link-type",r.linkType):Kre.has(t.getAttribute("link-type")||"")&&t.removeAttribute("link-type");let n=Wt(t,"filter").find(o=>!Tp(o)),i=r.filters&&(r.filters.conditions.length>0||r.filters.groups.length>0)?mc(e,r.filters):null;n&&i?t.replaceChild(i,n):n?t.removeChild(n):i&&t.appendChild(i)}function Yre(e){var t;let r=new DOMParser().parseFromString("<fetch/>","text/xml"),n=r.documentElement;n.setAttribute("version","1.0"),n.setAttribute("mapping","logical");let i=r.createElement("entity");i.setAttribute("name",e.entityLogicalName),n.appendChild(i);let o=new Map;for(let a of(t=e.linkEntities)!==null&&t!==void 0?t:[]){let s=r.createElement("link-entity");s.setAttribute("name",a.name),s.setAttribute("from",a.from),s.setAttribute("to",a.to),a.alias&&s.setAttribute("alias",a.alias),a.linkType&&s.setAttribute("link-type",a.linkType),a.filters&&(a.filters.conditions.length>0||a.filters.groups.length>0)&&s.appendChild(mc(r,a.filters)),i.appendChild(s);for(let l of[a.alias||a.name,a.name])o.has(l)||o.set(l,s)}for(let a of[...e.columns].sort((s,l)=>s.order-l.order)){let s=r.createElement("attribute");if(a.relatedEntity){vk(s,a);let l=o.get(a.relatedEntity);l||(l=r.createElement("link-entity"),l.setAttribute("name",a.relatedEntity),i.appendChild(l),o.set(a.relatedEntity,l)),l.appendChild(s)}else s.setAttribute("name",a.name),i.appendChild(s)}for(let a of e.sort){let s=r.createElement("order");s.setAttribute("attribute",a.attribute),s.setAttribute("descending",String(a.descending)),a.entityname&&s.setAttribute("entityname",a.entityname),i.appendChild(s)}return(e.filters.conditions.length>0||e.filters.groups.length>0)&&i.appendChild(mc(r,e.filters)),new XMLSerializer().serializeToString(r)}function mc(e,t){let r=e.createElement("filter");r.setAttribute("type",t.type);for(let n of t.conditions){let i=e.createElement("condition");i.setAttribute("attribute",n.attribute),i.setAttribute("operator",n.operator),n.entityname&&i.setAttribute("entityname",n.entityname),n.value!==void 0&&i.setAttribute("value",n.value),r.appendChild(i)}for(let n of t.groups)r.appendChild(mc(e,n));return r}function Qre(e,t){var r;let n=new DOMParser().parseFromString("<grid/>","text/xml"),i=n.documentElement,o=[...e.columns].sort((s,l)=>s.order-l.order);i.setAttribute("name","resultset"),i.setAttribute("jump",((r=o[0])===null||r===void 0?void 0:r.name)||t||`${e.entityLogicalName}id`),i.setAttribute("select","1"),i.setAttribute("icon","1"),i.setAttribute("preview","1");let a=n.createElement("row");a.setAttribute("name","result"),a.setAttribute("id",t||`${e.entityLogicalName}id`),i.appendChild(a);for(let s of o){let l=n.createElement("cell");l.setAttribute("name",s.name),l.setAttribute("width",String(s.width)),a.appendChild(l)}return new XMLSerializer().serializeToString(n)}function Xre(){return{adapter:new Np,api:Ire.viewApi,publish:(e,t,r)=>(0,ak.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,ak.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}pl.viewRegistration=Xre});function Dp(e,t){return e==="SetFieldValue"&&t!==void 0&&Zre.has(t.attributeType)&&(t.requiredLevel==="None"||t.requiredLevel==="Recommended")}var Zre,zb=k(()=>{"use strict";Zre=new Set(["Integer","Double","Decimal","Money","String","Memo","DateTime","Picklist","Lookup"])});function Ek(e){return e!=="Entity"&&e!=="AllForms"&&typeof e=="string"&&e.trim()!==""}function jb(e){return e==="AllForms"||Ek(e)?1:2}function Hb(e){return Ek(e)?e:null}function Ak(e,t){return{"@odata.type":"#Microsoft.Dynamics.CRM.workflow",name:e.name,description:e.description,workflowid:t,ondemand:!1,subprocess:!1,triggeroncreate:!1,triggerondelete:!1,category:ml.WorkflowCategory.BusinessRule,type:ml.WorkflowTypeCode.Definition,mode:1,scope:ml.WorkflowScope.Organization,primaryentity:e.entityLogicalName,iscrmuiworkflow:!0,processtriggerscope:jb(e.scope),processtriggerformid:Hb(e.scope)}}var ml,Sk=k(()=>{"use strict";ml=Ce(lo());});function Nk(e,t=0){return(zt[e[t+0]]+zt[e[t+1]]+zt[e[t+2]]+zt[e[t+3]]+"-"+zt[e[t+4]]+zt[e[t+5]]+"-"+zt[e[t+6]]+zt[e[t+7]]+"-"+zt[e[t+8]]+zt[e[t+9]]+"-"+zt[e[t+10]]+zt[e[t+11]]+zt[e[t+12]]+zt[e[t+13]]+zt[e[t+14]]+zt[e[t+15]]).toLowerCase()}var zt,_k=k(()=>{zt=[];for(let e=0;e<256;++e)zt.push((e+256).toString(16).slice(1))});function Kb(){return Ip>Op.length-16&&((0,Tk.randomFillSync)(Op),Ip=0),Op.slice(Ip,Ip+=16)}var Tk,Op,Ip,Dk=k(()=>{Tk=require("crypto"),Op=new Uint8Array(256),Ip=Op.length});var Ik,Jb,Ok=k(()=>{Ik=require("crypto"),Jb={randomUUID:Ik.randomUUID}});function ene(e,t,r){if(Jb.randomUUID&&!t&&!e)return Jb.randomUUID();e=e||{};let n=e.random??e.rng?.()??Kb();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 Nk(n)}var br,Pk=k(()=>{Ok();Dk();_k();br=ene});var Yb=k(()=>{Pk()});var Rk=k(()=>{"use strict";});function Lk(e){return e!=null&&tne.has(e)}function Pp(e){if(e==null)return!1;let t=e.trim();if(!/^[+-]?\d+$/.test(t))return!1;let r=Number(t);return Number.isInteger(r)&&r>=-2147483648&&r<=2147483647}var tne,Qb=k(()=>{"use strict";tne=new Set(["Picklist","State","Status"])});var Rp=v(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.WorkflowConditionOperator=wn.WorkflowAttributeType=wn.SystemStep=wn.FieldRequiredLevelTypes=wn.AttributeDateTimeBehavior=void 0;wn.AttributeDateTimeBehavior={None:0,Dynamic:1,DateOnly:2,StaticTimeZoneInvariant:3,UserLocal:4};wn.FieldRequiredLevelTypes={None:"0",Required:"1",Recommended:"2"};wn.SystemStep={IdentifyContact:"IdentifyContact",IdentifyAccount:"IdentifyAccount",IdentifyCustomer:"IdentifyCustomer",IdentifyCase:"IdentifyCase",Solution:"Solution",Resolve:"Resolve"};wn.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"};wn.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 Lp(e){return e!=null&&$k.includes(e)}function Xb(e){return e===ae.WorkflowAttributeType.Integer}function Zb(e,t){return t===ae.WorkflowConditionOperator.Equal||t===ae.WorkflowConditionOperator.NotEqual?e:rne.includes(t)?$k.includes(e)||e===ae.WorkflowAttributeType.DateTime?e:ae.WorkflowAttributeType.String:t===ae.WorkflowConditionOperator.On||t===ae.WorkflowConditionOperator.NotOn?e===ae.WorkflowAttributeType.DateTime?e:ae.WorkflowAttributeType.String:ae.WorkflowAttributeType.String}function xk(e){let t=e.leftWorkflowType??e.valueWorkflowType??ae.WorkflowAttributeType.String,r=hc[e.operator]??ae.WorkflowConditionOperator.Equal;return Zb(t,r)}function Fk(e,t){let r=e.trim(),i=(r.startsWith("+")||r.startsWith("-")?r.slice(1):r).split(".");if(i.length>2)return!1;let[o,a=""]=i;return o.length===0&&a.length===0||!kk.test(o)||!kk.test(a)||o.length>1&&o.startsWith("0")||o.length>nne?!1:t!==ae.WorkflowAttributeType.Integer||i.length===1}var ae,hc,$k,rne,kk,nne,ev=k(()=>{"use strict";ae=Ce(Rp());hc={Equals:ae.WorkflowConditionOperator.Equal,DoesNotEqual:ae.WorkflowConditionOperator.NotEqual,IsGreaterThan:ae.WorkflowConditionOperator.GreaterThan,IsLessThan:ae.WorkflowConditionOperator.LessThan,IsGreaterThanEqualTo:ae.WorkflowConditionOperator.GreaterThanOrEqual,IsLessThanEqualTo:ae.WorkflowConditionOperator.LessThanOrEqual,Contains:ae.WorkflowConditionOperator.Contains,DoesNotContain:ae.WorkflowConditionOperator.DoesNotContain,BeginsWith:ae.WorkflowConditionOperator.BeginsWith,DoesNotBeginWith:ae.WorkflowConditionOperator.DoesNotBeginWith,EndsWith:ae.WorkflowConditionOperator.EndsWith,DoesNotEndWith:ae.WorkflowConditionOperator.DoesNotEndWith,On:ae.WorkflowConditionOperator.On,NotOn:ae.WorkflowConditionOperator.NotOn,ContainsData:ae.WorkflowConditionOperator.NotNull,DoesNotContainData:ae.WorkflowConditionOperator.IsNull},$k=[ae.WorkflowAttributeType.Decimal,ae.WorkflowAttributeType.Float,ae.WorkflowAttributeType.Integer,ae.WorkflowAttributeType.Money],rne=[ae.WorkflowConditionOperator.GreaterThan,ae.WorkflowConditionOperator.GreaterThanOrEqual,ae.WorkflowConditionOperator.LessThan,ae.WorkflowConditionOperator.LessThanOrEqual];kk=/^\d*$/,nne=28});var Mk=k(()=>{"use strict";});function qn(e){return!ine.has(e)}function tv(e){return e==="Equals"||e==="DoesNotEqual"}function kp(e){return Bk.has(e)?one:cne.has(e)?ane:qk.has(e)?sne:fne.has(e)?une:lne}function Vk(e){return kp(e)[0]}function Gk(e,t){return kp(t).includes(e)}function Uk(e){return Bk.has(e)?"string":e==="Money"?"money":e==="Integer"||e==="BigInt"?"integer":e==="Decimal"||e==="Double"?"decimal":qk.has(e)?"date":dne.has(e)?"boolean":"other"}function $p(e,t){let r=Uk(e),n=Uk(t);return r==="other"||n==="other"?e===t:r===n}var ine,one,ane,sne,lne,une,Bk,cne,qk,dne,fne,xp=k(()=>{"use strict";Mk();ine=new Set(["ContainsData","DoesNotContainData"]);one=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],ane=["Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],sne=["On","NotOn","Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],lne=["Equals","DoesNotEqual","ContainsData","DoesNotContainData"],une=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],Bk=new Set(["String","Memo","EntityName"]),cne=new Set(["Integer","BigInt","Money","Decimal","Double"]),qk=new Set(["DateTime"]),dne=new Set(["Boolean"]),fne=new Set(["Lookup","Owner","Customer"])});function Hk(e){switch(e){case"Boolean":return Me.WorkflowAttributeType.Boolean;case"Customer":return Me.WorkflowAttributeType.Customer;case"DateTime":return Me.WorkflowAttributeType.DateTime;case"Decimal":return Me.WorkflowAttributeType.Decimal;case"Double":return Me.WorkflowAttributeType.Float;case"Integer":return Me.WorkflowAttributeType.Integer;case"Lookup":return Me.WorkflowAttributeType.Lookup;case"Money":return Me.WorkflowAttributeType.Money;case"Owner":return Me.WorkflowAttributeType.Owner;case"Picklist":return Me.WorkflowAttributeType.Picklist;case"State":return Me.WorkflowAttributeType.State;case"Status":return Me.WorkflowAttributeType.Status;case"Uniqueidentifier":case"UniqueIdentifier":return Me.WorkflowAttributeType.UniqueIdentifier;case"BigInt":return Me.WorkflowAttributeType.BigType;default:return Me.WorkflowAttributeType.String}}function e$(e){return e&&e!==Me.WorkflowAttributeType.String?e:void 0}function hne(e){return{__class:Zk,parameterName:"primaryEntity",entityName:e}}function Wk(e){return{__class:nv,type:rv,typeSet:!1,behavior:Me.AttributeDateTimeBehavior.None,method:Kk,parameters:[e]}}function zk(e,t,r=Me.WorkflowAttributeType.String){return{__class:Yk,type:r,behavior:Me.AttributeDateTimeBehavior.None,typeSet:!1,entity:hne(t),attributeName:e}}function gne(e,t=Me.WorkflowAttributeType.String){return{__class:Qk,type:t,behavior:Me.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function yne(e){return{__class:Xk,type:rv,typeSet:!1,behavior:Me.AttributeDateTimeBehavior.None,days:e,hours:"0",minutes:"0",months:"0",years:"0"}}function t$(e,t){let r=pne[e.operator],n=Wk(zk(e.leftField,t,e.leftWorkflowType)),i;e.dateArithmetic?i=yne(e.right.value??"0"):e.right.kind==="field"?i=zk(e.right.field??"",t,e.right.workflowType):i=gne(e.right.value??"",e.right.workflowType??e.leftWorkflowType);let o=Wk(i);return{__class:nv,type:rv,typeSet:!1,behavior:Me.AttributeDateTimeBehavior.None,method:Jk,parameters:[r,n,o]}}function r$(e){return typeof e=="object"&&e.__class===nv}function bne(e){return typeof e=="object"&&e.__class===Xk}function Fp(e){return r$(e)&&e.method===Kk&&e.parameters.length>0?Fp(e.parameters[0]):e}function jk(e){if(typeof e!="object"||e.__class!==Yk)return null;let t=e.entity;if(t&&t.__class&&t.__class!==Zk)return null;let r=e.attributeName;return r?{field:r,workflowType:e$(e.type)}:null}function n$(e){if(!e)return null;let t=Fp(e);if(!r$(t)||t.method!==Jk||t.parameters.length!==3)return null;let r=t.parameters[0],n=mne[String(r)];if(!n)return null;let i=jk(Fp(t.parameters[1]));if(!i)return null;let o=Fp(t.parameters[2]);if(bne(o))return n!=="+"&&n!=="-"?null:{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:String(o.days??"")},dateArithmetic:!0};let a=jk(o);if(a)return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"field",field:a.field,workflowType:a.workflowType}};if(typeof o=="object"&&o.__class===Qk){let s=o.primitiveValue;return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:s!=null?String(s):"",workflowType:e$(o.type)}}}return null}function ov(e){let t=(e??"").trim();if(!/^\d+$/.test(t))return!1;let r=Number(t);return Number.isSafeInteger(r)&&r>=iv&&r<=hl}function Pa(e){if(!e||!e.leftField)return"incomplete";if(e.right.kind==="field")return e.right.field&&e.right.field.trim()?null:"incomplete";let t=e.right.value;return!t||!t.trim()?"incomplete":e.dateArithmetic&&!ov(t)?"invalidDayCount":null}function gl(e){return Pa(e)===null}var Me,Kk,Jk,rv,Yk,Qk,nv,Xk,Zk,pne,mne,iv,hl,gc=k(()=>{"use strict";Me=Ce(Rp());xp();Kk="0",Jk="3",rv="0",Yk="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",Qk="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",nv="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",Xk="TimeSpanExpression:#Microsoft.Crm.Workflow.Expressions",Zk="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions";pne={"+":0,"-":1,"*":2,"/":3},mne={0:"+",1:"-",2:"*",3:"/"};iv=0,hl=2147483647});function wne(e){return e.startsWith("__")&&!vne.has(e)}function Cne(e){let t=Object.create(null);return Object.keys(e).forEach(r=>{wne(r)&&(t[r]=e[r])}),Object.keys(t).length>0?t:void 0}function y$(e){return e.__class==="BinaryExpression:#Microsoft.Crm.Workflow.Expressions"}function La(e){return e.__class==="UnaryExpression:#Microsoft.Crm.Workflow.Expressions"}function Mp(e){return y$(e)||La(e)}function Ene(e){return e.__class==="ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel"}function yc(){return{list:[]}}function av(e,t,r){return e&&e.list.length>0?{list:[{...e.list[0],description:t},...e.list.slice(1)]}:{list:[{labelId:br(),languageCode:r,description:t}]}}function lv(e){return{__class:"PrimaryEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:"primaryEntity",entityName:e}}function Vp(e,t,r,n=z.AttributeDateTimeBehavior.None){return{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:n,typeSet:!1,entity:lv(t),attributeName:e}}function Ra(e,t,r=z.AttributeDateTimeBehavior.None){return{__class:"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",type:t,behavior:r,typeSet:!1,primitiveValue:e}}function Nne(e){return e.bpfField==="StageCategory"?e.stageType==="SelectedStage"?w$:v$:b$}function C$(e){return e.bpfField==="StageCategory"?z.WorkflowAttributeType.BpfStageCategory:z.WorkflowAttributeType.BpfProcess}function _ne(e,t){let r=C$(e),n=e.bpfField==="StageCategory"?{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,entity:{__class:"RelatedEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:`related_${o$}_${i$}`,entityName:i$,relatedAttributeName:o$},attributeName:Sne}:Vp(Ane,t,r);return{__class:"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,method:dv,parameters:[Nne(e),n]}}function E$(e){let t=e;if(t.__class!=="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"||String(t.method)!==dv)return null;let r=(t.parameters??[])[0];if(typeof r!="string")return null;let n=r.replace(/^"+|"+$/g,"");return n===v$?{bpfField:"StageCategory",stageType:"ActiveStage"}:n===w$?{bpfField:"StageCategory",stageType:"SelectedStage"}:n===b$?{bpfField:"ProcessName"}:null}function Up(e){if(!e)return!1;let t=e;if(t.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"&&String(t.method)===dv){let r=(t.parameters??[])[0];if(typeof r=="string"&&Tne.has(r.replace(/^"+|"+$/g,"")))return!0}return La(e)?Up(e.operand):y$(e)?Up(e.left)||(e.right??[]).some(Up):!1}function A$(e){if(e?.__class!=="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions")return!1;let t=e.entity;return t==null||t.__class==="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions"}function Dne(e){if(e?.__class!=="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions")return!1;let t=e.primitiveValue;return t===!0||typeof t=="string"&&t.toLowerCase()==="true"}function a$(e){if(!e)return!1;switch(e.__class){case"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions":return A$(e);case"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions":return e.primitiveValue!=null||e.type!==void 0;case"LookupExpression:#Microsoft.Crm.Workflow.Expressions":case"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions":return!0;default:return!1}}function Ine(e){let t=cv[e.conditionOperatoroperator];if(!t)return!1;let r=t==="ContainsData"||t==="DoesNotContainData";if(La(e))return r&&s$(e.operand,!0);let n=e.right??[];return n.length!==(r?0:1)?!1:s$(e.left,r,n[0])}function s$(e,t,r){return E$(e)||A$(e)?t||a$(r):!1}function uv(e){if(!e||!Mp(e))return!1;let t=e.conditionOperatoroperator;if(!La(e)&&(t===z.WorkflowConditionOperator.LogicalAnd||t===z.WorkflowConditionOperator.LogicalOr)){let r=e.right??[];return r.length>0&&uv(e.left)&&r.every(uv)}return Ine(e)}function l$(e){return!e||Dne(e)?!1:Up(e)||!uv(e)}function S$(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:Ra(e.id.replace(/[{}]/g,""),z.WorkflowAttributeType.UniqueIdentifier)}}function Pne(e){return e===z.WorkflowAttributeType.DateTime?z.AttributeDateTimeBehavior.DateOnly:z.AttributeDateTimeBehavior.None}function Rne(e,t){if(t!==z.WorkflowAttributeType.DateTime)return z.AttributeDateTimeBehavior.None;let r=e.leftDateTimeBehavior;return r!==void 0&&r!==z.AttributeDateTimeBehavior.None?r:Pne(t)}function Lne(e,t,r){if(t!==z.WorkflowAttributeType.DateTime)return z.AttributeDateTimeBehavior.None;let n=e.valueFieldDateTimeBehavior;return n!==void 0&&n!==z.AttributeDateTimeBehavior.None?n:r}function $ne(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return"1";if(t==="false"||t==="0")return"0"}function Gne(e){let t=Vne.exec(e);if(t)return`${t[1]}T${t[2]}`;let r=qne.exec(e);if(!r)return;let[,n,i,o,a,s,l]=r,u=Bne.indexOf(i.toLowerCase());if(u<0)return;let c=String(u+1).padStart(2,"0");return`${o}-${c}-${n}T${a}:${s}:${l}`}function Wne(e){let t=Gne(e.trim());return t!==void 0&&N$(t)?t:e}function N$(e){let t=e.trim(),r=t.indexOf("T")>=0?"T":" ",n=t.indexOf(r),i=n>=0?t.slice(0,n):t,o=n>=0?t.slice(n+1):"";if(!xne.test(i)||o.length>0&&!Fne.test(o)&&!Mne.test(o)&&!Une.test(o))return!1;let[a,s,l]=i.split("-"),u=new Date(`${a}-${s}-${l}T00:00:00Z`);return!Number.isNaN(u.getTime())&&u.getUTCFullYear()===Number(a)&&u.getUTCMonth()+1===Number(s)&&u.getUTCDate()===Number(l)}function zne(e,t){let r={value:e,type:z.WorkflowAttributeType.String};if(t===z.WorkflowAttributeType.String||kne.includes(t)||e.trim().length===0)return r;if(t===z.WorkflowAttributeType.Boolean){let n=$ne(e);return n==null?r:{value:n,type:t}}return One.includes(t)?Pp(e)?{value:e.trim(),type:t}:r:Lp(t)?{value:e.trim(),type:t}:t===z.WorkflowAttributeType.DateTime&&N$(e)?{value:e.trim(),type:t}:r}function u$(e){return e==="ContainsData"||e==="DoesNotContainData"}function c$(e){return jne.has(e)}function d$(e,t){return{__class:"UnaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:t,operand:e}}function f$(e,t){let r=e.leftWorkflowType??e.valueWorkflowType??z.WorkflowAttributeType.String,n=hc[e.operator]??z.WorkflowConditionOperator.Equal,i=Rne(e,r),o=Zb(r,n);if(e.source==="BusinessProcess"){let l=_ne(e,t);if(u$(e.operator))return d$(l,n);let u=C$(e);return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:l,right:[Ra(e.value??"",u)]}}let a=Vp(e.field,t,r,i);if(u$(e.operator))return d$(a,n);let s;if(e.valueType==="Field"&&e.valueField){let l=c$(o)&&c$(e.valueFieldWorkflowType??"")?e.valueFieldWorkflowType:o;s=[Vp(e.valueField,t,l,Lne(e,l,i))]}else if(e.valueType==="Lookup"){if(!e.lookupValue)throw new Error("Lookup condition is missing its record value.");s=[S$(e.lookupValue)]}else if(e.valueType==="Clear")s=[Ra(null,z.WorkflowAttributeType.String,i)];else if(e.valueType==="Expression")s=[qp(e.valueType,e.value,e.valueField,t,e.expression,e.rawExpression)];else{let l=zne(e.value??"",o);s=[Ra(l.value,l.type,i)]}return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:a,right:s}}function Hne(){return Ra(!0,z.WorkflowAttributeType.Boolean)}function Kne(e,t,r){if(e.length===0)return null;let n=f$(e[0],r);for(let i=1;i<e.length;i++){let o=e[i].connector??t;n={__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:o==="AND"?z.WorkflowConditionOperator.LogicalAnd:z.WorkflowConditionOperator.LogicalOr,left:n,right:[f$(e[i],r)]}}return n}function Bp(e){if(!e)return{valueType:"Value",value:""};if(e.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions")return{valueType:"Field",valueField:e.attributeName,valueFieldWorkflowType:e.type};if(e.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"){if(e.primitiveValue==null)return{valueType:"Clear",valueWorkflowType:e.type};let t=String(e.primitiveValue);if(e.type===z.WorkflowAttributeType.Boolean){let r=t.trim().toLowerCase();if(r==="1"||r==="true")return{valueType:"Value",value:"true",valueWorkflowType:e.type};if(r==="0"||r==="false")return{valueType:"Value",value:"false",valueWorkflowType:e.type}}return e.type===z.WorkflowAttributeType.DateTime?{valueType:"Value",value:Wne(t),valueWorkflowType:e.type}:{valueType:"Value",value:t,valueWorkflowType:e.type}}if(e.__class==="LookupExpression:#Microsoft.Crm.Workflow.Expressions"){let t=e.staticValue,r=typeof t=="object"&&t?.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"?t.primitiveValue:t;return{valueType:"Lookup",lookupValue:{entityType:e.entityType,id:String(r??""),label:e.label,...e.type!==z.WorkflowAttributeType.Lookup?{workflowType:e.type}:{}}}}if(e.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"){let t=n$(e);return t?{valueType:"Expression",expression:t}:{valueType:"Expression",rawExpression:e}}return{valueType:"Value",value:""}}function Jne(e){let t=cv[e.conditionOperatoroperator]??"Equals",r=t==="ContainsData"||t==="DoesNotContainData",n=La(e)?e.operand:e.left,i=La(e)?[]:e.right??[],o=E$(n);if(o){let g=i[0];return{id:br(),field:"",fieldDisplayName:"",source:"BusinessProcess",bpfField:o.bpfField,...o.stageType?{stageType:o.stageType}:{},operator:t,valueType:"Value",value:g?.primitiveValue!=null&&!r?String(g.primitiveValue):""}}let a=n.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",s=n.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"?n.attributeName:"",l=a?n.type:void 0,u=r?{valueType:"Value"}:Bp(i[0]),c=l,d=a&&n.type===z.WorkflowAttributeType.DateTime&&n.behavior!==z.AttributeDateTimeBehavior.None?n.behavior:void 0,f=u.valueWorkflowType??l,m=r?void 0:i[0],h=m?.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"&&m.type===z.WorkflowAttributeType.DateTime&&m.behavior!==z.AttributeDateTimeBehavior.None?m.behavior:void 0;return{id:br(),field:s,fieldDisplayName:s,operator:t,...u,...f?{valueWorkflowType:f}:{},...c?{leftWorkflowType:c}:{},...d!==void 0?{leftDateTimeBehavior:d}:{},...h!==void 0?{valueFieldDateTimeBehavior:h}:{}}}function p$(e){if(!e||!Mp(e))return{clauses:[],logic:"AND"};let t=[],r=(o,a)=>{let s=o.conditionOperatoroperator;if(La(o)||s!==z.WorkflowConditionOperator.LogicalAnd&&s!==z.WorkflowConditionOperator.LogicalOr){t.push({...Jne(o),...a?{connector:a}:{}});return}let l=s===z.WorkflowConditionOperator.LogicalAnd?"AND":"OR";Mp(o.left)&&r(o.left,a),(o.right??[]).filter(Mp).forEach(u=>r(u,l))};r(e,void 0);let i=t.slice(1).map(o=>o.connector??"AND")[0]??"AND";return{clauses:t,logic:i}}function qp(e,t,r,n,i,o,a,s){if(e==="Field"&&r)return Vp(r,n,z.WorkflowAttributeType.String);if(e==="Expression"){if(i)return t$(i,n);if(o!=null)return o}return e==="Lookup"&&a?S$(a):e==="Clear"?Ra(null,s??z.WorkflowAttributeType.String):Ra(t??"",z.WorkflowAttributeType.String)}function sv(e,t){return{propertyName:e,propertyValueExpr:t}}function yl(e){return`Step_${e.value++}`}function Cn(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 m$(e,t,r){return e&&!r.used.has(e)?(r.used.add(e),e):Cn(t,r)}function Yne(e){return e===g$.StateCode.Activated?"Active":"Draft"}function Qne(e){let t={},r=e;typeof r.ismanaged=="boolean"&&(t.isManaged=r.ismanaged);let n=r.iscustomizable;return typeof n=="boolean"?t.isCustomizable=n:n!==null&&typeof n=="object"&&typeof n.Value=="boolean"&&(t.isCustomizable=n.Value),t}function Xne(e,t){let r=e.processtriggerscope,n=e.processtriggerformid;return r===1?n&&n.trim()!==""?n:"AllForms":r===2?"Entity":t??"Entity"}function _$(e,t=1033){return new bl({languageCode:t}).serialize(e)}function T$(e){return new bl().deserialize(e)}var g$,z,vne,cv,dv,b$,v$,w$,Ane,Sne,i$,o$,Tne,One,kne,xne,Fne,Mne,Une,Bne,qne,Vne,jne,fv,bl,pv=k(()=>{"use strict";Yb();g$=Ce(lo());Rk();Qb();ev();gc();z=Ce(Rp());vne=new Set(["__class"]);cv={};for(let e of Object.keys(hc))cv[hc[e]]=e;dv="23",b$="BpfProcess",v$="ActiveStageCategory",w$="SelectedStageCategory",Ane="processid",Sne="stagecategory",i$="processstage",o$="stageid";Tne=new Set(["ActiveStage","SelectedStage","Stage"]);One=[z.WorkflowAttributeType.Picklist,z.WorkflowAttributeType.State,z.WorkflowAttributeType.Status];kne=[z.WorkflowAttributeType.Lookup,z.WorkflowAttributeType.Customer,z.WorkflowAttributeType.Owner];xne=/^\d{4}-\d{2}-\d{2}$/,Fne=/^\d{2}:\d{2}$/,Mne=/^\d{2}:\d{2}:\d{2}$/,Une=/^\d{2}:\d{2}:\d{2}\.\d{1,7}$/,Bne=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],qne=/^[A-Za-z]{3}, (\d{2}) ([A-Za-z]{3}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/,Vne=/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}:\d{2}\.\d{1,7}|\d{2}:\d{2}:\d{2}|\d{2}:\d{2})Z$/;jne=new Set([z.WorkflowAttributeType.Lookup,z.WorkflowAttributeType.Owner,z.WorkflowAttributeType.Customer]);fv={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"};bl=class{resolveLabel;languageCode;entityName="";stepCounter={value:0};idCounter={counts:{},used:new Set};constructor(t={}){this.resolveLabel=t.resolveLabel??(r=>fv[r]),this.languageCode=t.languageCode??1033}label(t){return this.resolveLabel(t)}serialize(t){let r=t.wfomRoot;this.entityName=t.entityLogicalName,this.stepCounter={value:r?Number(r.nextStepIndex):1},this.idCounter={counts:{},used:new Set};let n=t.scope!=="Entity"&&t.scope!=="AllForms"?t.scope:null,i=t.rootCondition?[this.serializeConditionNode(t.rootCondition)]:[],o={...r?.reservedProperties??{},__class:"WorkflowStep:#Microsoft.Crm.Workflow.ObjectModel",id:r?.id??t.ruleId??br(),name:r?.name??"Step_0",description:r!==void 0?r.description:t.description||null,stepLabels:yc(),argumentsArray:[],primaryEntityName:r?.primaryEntityName??this.entityName,nextStepIndex:String(this.stepCounter.value),isCrmUIWorkflow:!0,category:r?.category??"2",businessProcessType:r?.businessProcessType??"0",mode:r?.mode??"0",title:r?.title??t.name,formId:n,workflowEntityId:r?.workflowEntityId??t.ruleId??"",variables:r?.variables??[],inputs:r?.inputs??[],steps:{list:i}};return JSON.stringify(o)}makeApplyActionStep(t){return{__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",id:Cn("SetAttributeValueStep",this.idCounter),description:t.displayName||"New Action",name:t.stepName??yl(this.stepCounter),stepLabels:{list:[]},specification:sv(t.field,qp(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType)),entity:lv(this.entityName)}}makeRecommendationActionStep(t,r,n){let i=r.map(l=>this.makeApplyActionStep(l)),o=t??"",a=n?.stepLabels,s=av(a,o,this.languageCode);return{__class:"ActionStep:#Microsoft.Crm.Workflow.ObjectModel",id:m$(n?.id,"ActionStep",this.idCounter),name:n?.name??yl(this.stepCounter),description:n?.description??"Action step",stepLabels:s,steps:{list:i},actionId:null,actionType:n?.actionType??"4",processId:n?.processId??br(),uniqueName:n?.uniqueName??`id_${br().replace(/-/g,"")}ActionStep`}}serializeAction(t){let r=lv(this.entityName),n=t.stepName??yl(this.stepCounter),i=t.stepLabels??yc(),o={name:n,stepLabels:i,description:t.displayName},a=t.type;switch(a){case"SetFieldValue":return{...o,id:Cn("SetAttributeValueStep",this.idCounter),__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:sv(t.field,qp(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"SetDefaultValue":return{...o,id:Cn("SetDefaultValueStep",this.idCounter),__class:"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:sv(t.field,qp(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"LockUnlock":return{...o,id:Cn("SetDisplayModeStep",this.idCounter),__class:"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isReadOnly:t.lock,entity:r};case"SetBusinessRequired":return{...o,id:Cn("SetFieldRequiredLevelStep",this.idCounter),__class:"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",requiredLevel:t.required?z.FieldRequiredLevelTypes.Required:z.FieldRequiredLevelTypes.None,entity:r};case"SetVisibility":return{...o,id:Cn("SetVisibilityStep",this.idCounter),__class:"SetVisibilityStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isVisible:t.visible,entity:r};case"ShowErrorMessage":{let s=t.errorMessage||t.displayName,l=av(t.stepLabels,s,this.languageCode);return{...o,id:Cn("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=av(t.stepLabels,s,this.languageCode),u={list:[this.makeRecommendationActionStep(t.acceptanceText,t.applyActions??[],t.recommendationActionStepMeta)]};return{...o,id:Cn("SetMessageStep",this.idCounter),__class:"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel",stepLabels:l,description:t.recommendationTitle||t.displayName,controlId:t.field,entity:r,level:"RECOMMENDATION",actionSteps:u}}default:throw new Error(`Unsupported action type: ${a}`)}}serializeConditionNode(t){let r=t.stepName??yl(this.stepCounter),n=Cn("ConditionStep",this.idCounter),i=[],o=t,a=!0;for(;o;){let s=o.rawConditionExpression??Kne(o.clauses,o.logic,this.entityName),l=a?o.branchName??yl(this.stepCounter):yl(this.stepCounter),c={__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:a?m$(o.branchId,"ConditionBranchStep",this.idCounter):Cn("ConditionBranchStep",this.idCounter),name:l,description:o.displayName,stepLabels:yc(),conditionExpression:s??(a?Hne():void 0),steps:{list:o.trueBranch.map(f=>this.serializeBranchItem(f))}};i.push(c);let d=o.falseBranch;if(d.length===1&&d[0].kind==="condition"){o=d[0],a=!1;continue}d.length>0&&i.push(this.makeTerminalElseBranch(d)),o=void 0}return{__class:"ConditionStep:#Microsoft.Crm.Workflow.ObjectModel",id:n,name:r,description:"",stepLabels:yc(),containsElsebranch:i.length>1,steps:{list:i}}}makeTerminalElseBranch(t){return{__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:Cn("ConditionBranchStep",this.idCounter),name:"Else",description:null,stepLabels:yc(),conditionExpression:void 0,steps:{list:t.map(r=>this.serializeBranchItem(r))}}}serializeBranchItem(t){return t.kind==="condition"?this.serializeConditionNode(t):this.serializeAction(t)}deserialize(t){let r=t,n=null,i;if(t.wfomJson)try{let o=JSON.parse(t.wfomJson);i={id:o.id==="WorkflowStep0"||!o.id?t.workflowid??br():o.id,name:o.name,description:o.description,nextStepIndex:o.nextStepIndex,category:o.category==="0"||o.category===0?"2":o.category,businessProcessType:o.businessProcessType,mode:o.mode,title:o.title||t.name||"",primaryEntityName:o.primaryEntityName==="1"||!o.primaryEntityName?t.primaryentity??"":o.primaryEntityName,workflowEntityId:o.workflowEntityId==="00000000-0000-0000-0000-000000000000"||!o.workflowEntityId?t.workflowid??"":o.workflowEntityId,formId:o.formId,variables:o.variables,inputs:o.inputs,reservedProperties:Cne(o)};let s=(o.steps?.list??[]).find(l=>l.__class==="ConditionStep:#Microsoft.Crm.Workflow.ObjectModel");s&&(n=this.deserializeConditionStep(s))}catch{}return{ruleId:t.workflowid??null,name:t.name??"",description:t.description??"",entityLogicalName:t.primaryentity??"",scope:Xne(r,i?.formId),status:Yne(t.statecode),rootCondition:n,wfomRoot:i,...Qne(t)}}deserializeConditionStep(t){let r=(t.steps?.list??[]).filter(Ene);return this.buildConditionNodeFromBranches(r,t,!0)}buildConditionNodeFromBranches(t,r,n){let[i,...o]=t,{clauses:a,logic:s}=p$(i?.conditionExpression),l=this.deserializeBranch(i?.steps?.list??[]),u=this.deserializeElseChain(o,r),c=i?.description||i?.name||r.description||r.name||this.label("condition");return{kind:"condition",id:(n?r.id:i?.id)??br(),displayName:c,clauses:a,logic:s,trueBranch:l,falseBranch:u,isCollapsed:!1,stepName:n?r.name:void 0,branchId:n?i?.id:void 0,branchName:n?i?.name:void 0,...l$(i?.conditionExpression)?{rawConditionExpression:i?.conditionExpression}:{}}}deserializeElseChain(t,r){if(t.length===0)return[];let[n]=t,{clauses:i}=p$(n.conditionExpression);return i.length===0&&!l$(n.conditionExpression)?this.deserializeBranch(n.steps?.list??[]):[this.buildConditionNodeFromBranches(t,r,!1)]}deserializeBranch(t){return t.map(r=>r.__class==="ConditionStep:#Microsoft.Crm.Workflow.ObjectModel"?this.deserializeConditionStep(r):this.deserializeAction(r)).filter(r=>r!==null)}parseRecommendationApplyActions(t){let n=(t?.list??[])[0];if(!n)return{applyActions:[]};let i={id:n.id,name:n.name,description:n.description??void 0,stepLabels:n.stepLabels,processId:n.processId,uniqueName:n.uniqueName,actionType:n.actionType},o=n.stepLabels?.list,a=o&&o.length>0?o[0].description??"":"";return{applyActions:(n.steps?.list??[]).filter(l=>l.__class==="SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel").map(l=>{let u=l.specification;return{id:l.id||br(),field:u?.propertyName??"",stepName:l.name??void 0,displayName:l.description??void 0,...Bp(u?.propertyValueExpr)}}),meta:i,acceptanceText:a}}deserializeAction(t){switch(t.__class){case"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=Bp(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=Bp(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:o,acceptanceText:a}=this.parseRecommendationApplyActions(t.actionSteps);return{kind:"action",id:t.id,type:"Recommendation",displayName:t.description||this.label("recommendation"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,recommendationTitle:t.description||"",messageText:n,acceptanceText:a,applyActions:i,recommendationActionStepMeta:o}}return{kind:"action",id:t.id,type:"ShowErrorMessage",displayName:t.description||this.label("showErrorMessage"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,errorMessage:n||t.name||"",messageLevel:t.level??void 0,messageActionSteps:t.actionSteps}}case"ActionStep:#Microsoft.Crm.Workflow.ObjectModel":{let{applyActions:r,meta:n,acceptanceText:i}=this.parseRecommendationApplyActions({list:[t]});return{kind:"action",id:t.id,type:"Recommendation",displayName:t.name||this.label("recommendation"),stepName:t.name,stepLabels:t.stepLabels,field:t.actionControl?.controlId??"",recommendationTitle:t.name||"",messageText:t.description||"",acceptanceText:i,applyActions:r,recommendationActionStepMeta:n}}default:return null}}}});var D$=k(()=>{"use strict";});function nie(e){return typeof e=="object"&&e!==null?e:null}function vl(e){let t=nie(e);if(!t)return!1;if(t.__class===tie){let r=t;return String(r.method)===rie?!0:Array.isArray(r.parameters)&&r.parameters.some(vl)}if(t.__class===eie)return vl(t.operand);if(t.__class===Zne){let r=t;return vl(r.left)||Array.isArray(r.right)&&r.right.some(vl)}return!1}var Zne,eie,tie,rie,I$=k(()=>{"use strict";D$();Zne="BinaryExpression:#Microsoft.Crm.Workflow.Expressions",eie="UnaryExpression:#Microsoft.Crm.Workflow.Expressions",tie="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",rie="23"});function yv(e){return iie.has(e.type)}function mv(e,t,r,n,i,o,a){let s=i.get(r);!s||!R$.has(s.attributeType)||n!=="Value"||a?.operator&&!tv(a.operator)||o.push({nodeId:e,kind:"INVALID_VALUE_TYPE_FOR_FIELD",message:`${t}: please select a record for this lookup field; a typed text value cannot be saved.`,target:a?.target,itemId:a?.itemId,messageKey:"Validation.InvalidValueTypeForField",messageParams:{label:t}})}function oie(e,t){let r=t.get(e.field);return!!r&&R$.has(r.attributeType)&&tv(e.operator)}function hv(e){return!!(e?.entityType?.trim()&&e.id?.trim())}function gv(e,t,r){return{nodeId:e,kind:"INVALID_DAY_COUNT",message:`Please enter a whole number of days between 0 and ${hl}.`,target:t,itemId:r,messageKey:"Validation.InvalidDayCount",messageParams:{max:hl}}}function O$(e,t,r,n,i,o,a,s){if(i!=="Clear")return;let l=o.get(n);Dp(r,l)||a.push({nodeId:e,kind:"INVALID_CLEAR_FOR_FIELD",message:`${t}: Clear is only supported for optional fields with a legacy-compatible type.`,target:s?.target,itemId:s?.itemId,messageKey:"Validation.InvalidClearForField",messageParams:{label:t}})}function Wp(e){if(!e)return!1;for(let t of[...e.trueBranch,...e.falseBranch])if(t.kind==="action"){if(yv(t))return!0}else if(Wp(t))return!0;return!1}function bv(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=bv(r,t);if(n)return n}}return null}function aie(e){if(!e||typeof e!="object")return!1;let{__class:t,primitiveValue:r}=e;return t!=="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"?!1:r===!0||typeof r=="string"&&r.toLowerCase()==="true"}function sie(e){return e.clauses.length===0&&(e.rawConditionExpression===void 0||aie(e.rawConditionExpression))}function uie(e){return!!e.clauses?.some(t=>t.source==="BusinessProcess")||vl(e.rawConditionExpression)}function wl(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=wl(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=wl(n,t);if(i)return i}}return null}function vv(e,t){return{...e,trueBranch:P$(e.trueBranch,t),falseBranch:P$(e.falseBranch,t)}}function P$(e,t){return e.filter(r=>r.id!==t).map(r=>r.kind==="condition"?vv(r,t):r)}function Bo(e,t,r){return e.id===t?r(e):{...e,trueBranch:e.trueBranch.map(n=>n.kind==="condition"?Bo(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="condition"?Bo(n,t,r):n)}}function Gp(e,t,r){return{...e,trueBranch:e.trueBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?Gp(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?Gp(n,t,r):n)}}function L$(e,t,r,n){return Bo(e,t,i=>({...i,trueBranch:r==="true"?[...i.trueBranch,n]:i.trueBranch,falseBranch:r==="false"?[...i.falseBranch,n]:i.falseBranch}))}function wv(e){return e.length===1&&e[0].kind==="condition"}function die(e){let t=0,r=e??void 0;for(;r;){t+=1;let{falseBranch:n}=r;if(wv(n)){r=n[0];continue}n.length>0&&(t+=1),r=void 0}return t}function fie(e){return!!e&&die(e)<cie}function pie(e,t){if(!e)return;let r=(n,i)=>{if(n.id===t)return i;let o=[];if(wv(n.falseBranch)){let a=r(n.falseBranch[0],i);if(a)return a}else o.push(...n.falseBranch.filter(a=>a.kind==="condition"));o.push(...n.trueBranch.filter(a=>a.kind==="condition"));for(let a of o){let s=r(a,a);if(s)return s}};return r(e,e)}function k$(e,t,r){let n=pie(e,t);return!n||!fie(n)?e:Bo(e,t,i=>$$(i,r))}function $$(e,t){if(wv(e.falseBranch))return{...e,falseBranch:[$$(e.falseBranch[0],t)]};let r=Cv(t);return r.falseBranch=e.falseBranch,{...e,falseBranch:[r]}}function x$(e,t){let r=wl(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 Bo(e,r.node.id,o=>({...o,falseBranch:i}))}function F$(e,t,r){let n=wl(e,t);if(!n)return e;let i=o=>{let a=[...o],s=a[n.index+r];return s?(a[n.index+r]=a[n.index],a[n.index]=s,a):o};return Bo(e,n.node.id,o=>({...o,trueBranch:n.branch==="true"?i(o.trueBranch):o.trueBranch,falseBranch:n.branch==="false"?i(o.falseBranch):o.falseBranch}))}function Cv(e){return{kind:"condition",id:br(),displayName:e??"New Condition",clauses:[],logic:"AND",trueBranch:[],falseBranch:[],isCollapsed:!1}}function M$(e,t){let r={kind:"action",id:br(),type:e,displayName:t??`New ${e}`};switch(e){case"Recommendation":return{...r,type:"Recommendation",field:"",recommendationTitle:"",messageText:"",applyActions:[{id:br(),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 U$(e){if(!e)return[];let t=[];return B$(e,t),[...new Set(t)]}function B$(e,t){e.clauses.forEach(r=>{r.field&&t.push(r.field)}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"?B$(r,t):"field"in r&&r.field&&t.push(r.field)})}function q$(e,t=[],r){if(!e)return[{nodeId:"root",kind:"NO_CONDITION",message:"A business rule must include at least one condition.",target:"node"}];let n=[],i=new Map(t.map(o=>[o.logicalName,o]));return G$(e,n,i,!0),r==="Entity"&&V$(e,n),Wp(e)||n.push({nodeId:"root",kind:"NO_ACTION",message:"A business rule must include at least one action step.",target:"node"}),n}function V$(e,t){uie(e)&&t.push({nodeId:e.id,kind:"BPF_IN_ENTITY_SCOPE",message:"Process based conditions are not allowed in Entity scope.",target:"node",messageKey:"Validation.ProcessConditionNotAllowedInEntityScope"}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"&&V$(r,t)})}function G$(e,t,r,n=!1){let i=n&&sie(e),o=!!e.rawConditionExpression;e.clauses.length===0&&!n&&!o&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Add at least one clause to this condition.",target:"node",messageKey:"Validation.AddClause"}),i&&e.falseBranch.length>0&&t.push({nodeId:e.id,kind:"UNREACHABLE_ELSE",message:"Add a condition to the IF clause, or delete the ELSE clause it can never reach.",target:"node",messageKey:"Validation.UnreachableElse"}),e.clauses.forEach(a=>{if(o)return;if(a.source==="BusinessProcess"){a.bpfField?a.value||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:a.id}):t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a business process field for this clause.",target:"clauseField",itemId:a.id,messageKey:"Validation.SelectBusinessProcessField"});return}let s=a.valueType==="Expression"&&!a.rawExpression?Pa(a.expression):null;if(!a.field)t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a field for this clause.",target:"clauseField",itemId:a.id});else if(qn(a.operator)&&a.valueType==="Value"&&!a.value&&!oie(a,r))t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:a.id});else if(qn(a.operator)&&a.valueType==="Value"&&a.value){let u=r.get(a.field);u?.maxLength&&a.value.length>u.maxLength&&t.push({nodeId:e.id,kind:"CLAUSE_VALUE_TOO_LONG",message:`Value exceeds the field's maximum length of ${u.maxLength} characters.`,target:"clauseValue",itemId:a.id,messageParams:{maxLength:u.maxLength}})}else qn(a.operator)&&a.valueType==="Expression"&&!a.rawExpression&&!gl(a.expression)?t.push(s==="invalidDayCount"?gv(e.id,"clauseValue",a.id):{nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please complete the formula for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.CompleteClauseFormula"}):qn(a.operator)&&a.valueType==="Field"&&!a.valueField&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a field to compare to for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.EmptyClauseCompareField"});qn(a.operator)&&a.valueType==="Value"&&a.value&&Lk(r.get(a.field)?.attributeType)&&!Pp(a.value)&&t.push({nodeId:e.id,kind:"INVALID_CLAUSE_OPTION_VALUE",message:"Please enter a whole number option value for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.InvalidClauseOptionValue"});let l=xk(a);qn(a.operator)&&a.valueType==="Value"&&a.value&&Lp(l)&&!Fk(a.value,l)&&t.push({nodeId:e.id,kind:"INVALID_CLAUSE_NUMERIC_VALUE",message:Xb(l)?"Please enter a whole number for this clause.":"Please enter a valid number for this clause.",target:"clauseValue",itemId:a.id,messageKey:Xb(l)?"Validation.InvalidClauseWholeNumberValue":"Validation.InvalidClauseNumericValue"}),qn(a.operator)&&a.valueType==="Lookup"&&(hv(a.lookupValue)||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a lookup record for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.EmptyClauseLookupValue"})),qn(a.operator)&&mv(e.id,"Condition",a.field,a.valueType,r,t,{operator:a.operator,target:"clauseValue",itemId:a.id})}),i&&e.trueBranch.forEach(a=>{a.kind==="action"&&lie.has(a.type)&&t.push({nodeId:a.id,kind:"ACTION_REQUIRES_CONDITION",message:"Set field value, Show error message, and Recommendation actions require a condition. Add a condition to the IF clause, or use a different action.",target:"node",messageKey:"Validation.ActionRequiresCondition",messageParams:{actionType:a.type}})}),[...e.trueBranch,...e.falseBranch].forEach(a=>{if(a.kind==="condition")G$(a,t,r);else{if(!("field"in a)||!a.field)t.push({nodeId:a.id,kind:"EMPTY_ACTION_FIELD",message:`${a.type}: a target field is required.`,target:"actionField",messageParams:{actionType:a.type}});else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&(a.valueType??"Value")==="Value"&&!a.value?.trim())t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please provide a value.`,target:"actionValue",messageParams:{actionType:a.type}});else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Value"&&a.value){let s=r.get(a.field);s?.maxLength&&a.value.length>s.maxLength&&t.push({nodeId:a.id,kind:"ACTION_VALUE_TOO_LONG",message:`${a.type}: value exceeds the field's maximum length of ${s.maxLength} characters.`,target:"actionValue",messageParams:{actionType:a.type,maxLength:s.maxLength}})}else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Field"){if(!a.valueField)t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please select a field to copy from.`,target:"actionValue",messageKey:"Validation.SelectActionSourceField",messageParams:{actionType:a.type}});else if(r.size>0){let s=r.get(a.field),l=r.get(a.valueField);s&&l&&!$p(s.attributeType,l.attributeType)&&t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: the source field's type is not compatible with the target field.`,target:"actionValue",messageKey:"Validation.IncompatibleActionSourceField",messageParams:{actionType:a.type}})}}else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Expression"){let s=a.rawExpression?null:Pa(a.expression);!a.rawExpression&&!gl(a.expression)&&t.push(s==="invalidDayCount"?gv(a.id,"actionValue"):{nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please complete the formula.`,target:"actionValue",messageKey:"Validation.CompleteActionFormula",messageParams:{actionType:a.type}})}else(a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Lookup"&&!hv(a.lookupValue)&&t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please complete the lookup record.`,target:"actionValue",messageKey:"Validation.EmptyActionLookupValue",messageParams:{actionType:a.type}});if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.field&&(mv(a.id,a.type,a.field,a.valueType,r,t,{target:"actionValue"}),O$(a.id,a.type,a.type,a.field,a.valueType,r,t,{target:"actionValue"})),a.type==="ShowErrorMessage"&&!a.errorMessage?.trim()&&t.push({nodeId:a.id,kind:"EMPTY_ACTION_MESSAGE",message:"Show error message: please enter an error message.",target:"actionMessage"}),a.type==="Recommendation"){let s=a.applyActions??[];a.recommendationTitle?.trim()||t.push({nodeId:a.id,kind:"EMPTY_RECOMMENDATION_TITLE",message:"Recommendation: please enter a recommendation title.",target:"recommendationTitle"}),a.messageText?.trim()||t.push({nodeId:a.id,kind:"EMPTY_RECOMMENDATION_MESSAGE",message:"Recommendation: please enter a recommendation message.",target:"recommendationMessage"}),s.length===0&&t.push({nodeId:a.id,kind:"RECOMMENDATION_NO_APPLY_ACTION",message:"Recommendation: add at least one action to apply.",target:"node"}),s.forEach(l=>{if(!l.field)t.push({nodeId:a.id,kind:"EMPTY_ACTION_FIELD",message:"Recommendation: a target field is required for each action to apply.",target:"applyActionField",itemId:l.id,messageKey:"Validation.RecommendationApplyField"});else if(l.valueType==="Field")l.valueField||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please select a field to copy from.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplySourceField"});else if(l.valueType==="Expression"){let u=l.rawExpression?null:Pa(l.expression);!l.rawExpression&&!gl(l.expression)&&t.push(u==="invalidDayCount"?gv(a.id,"applyActionValue",l.id):{nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the formula.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplyFormula"})}else l.valueType==="Lookup"?hv(l.lookupValue)||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the lookup record.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplyLookupValue"}):l.valueType==="Clear"||l.value?.trim()||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please enter a value for each action to apply.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplyValue"});l.field&&(mv(a.id,"Recommendation",l.field,l.valueType,r,t,{target:"applyActionValue",itemId:l.id}),O$(a.id,"Recommendation","SetFieldValue",l.field,l.valueType,r,t,{target:"applyActionValue",itemId:l.id}))})}}})}var iie,R$,lie,cie,Ev=k(()=>{"use strict";Yb();zb();xp();gc();I$();ev();Qb();iie=new Set(["LockUnlock","ShowErrorMessage","Recommendation","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]);R$=new Set(["Lookup","Customer","Owner"]);lie=new Set(["SetFieldValue","ShowErrorMessage","Recommendation"]);cie=10});var W$={};nn(W$,{DAY_COUNT_MAX:()=>hl,DAY_COUNT_MIN:()=>iv,DEFAULT_DESERIALIZE_LABELS:()=>fv,WorkflowJsonMapper:()=>bl,addElseIfInTree:()=>k$,appendToBranch:()=>L$,areFieldKindsCompatible:()=>$p,attributeTypeToWorkflowType:()=>Hk,buildWorkflowEntity:()=>Ak,collectUsedFields:()=>U$,createEmptyAction:()=>M$,createEmptyCondition:()=>Cv,deserializeWorkflowJson:()=>T$,findNode:()=>bv,findParent:()=>wl,getDefaultOperatorForFieldType:()=>Vk,getExpressionModelIssue:()=>Pa,getOperatorsForFieldType:()=>kp,hasAnyTriggerGeneratingAction:()=>Wp,isDayCountValid:()=>ov,isExpressionModelComplete:()=>gl,isOperatorCompatible:()=>Gk,isTriggerGeneratingAction:()=>yv,moveBranchItemInTree:()=>F$,operatorNeedsValue:()=>qn,processTriggerFormIdFromScope:()=>Hb,processTriggerScopeFromScope:()=>jb,removeElseIfInTree:()=>x$,removeNodeFromTree:()=>vv,serializeToWorkflowJson:()=>_$,supportsClearForActionType:()=>Dp,updateActionInTree:()=>Gp,updateConditionInTree:()=>Bo,validateBusinessRule:()=>q$});var z$=k(()=>{"use strict";zb();Sk();pv();pv();Ev();Ev();xp();gc();gc();});var Av=v(zp=>{"use strict";Object.defineProperty(zp,"__esModule",{value:!0});zp.cloneJson=void 0;function mie(e){return JSON.parse(JSON.stringify(e))}zp.cloneJson=mie});var nx=v(qo=>{"use strict";Object.defineProperty(qo,"__esModule",{value:!0});qo.BUSINESS_RULE_NULL_GUID=qo.businessRuleRegistration=qo.BusinessRuleAdapter=void 0;var j$=ct(),bc=(z$(),zr(W$)),H$=jr(),K$=Q(),hie=Av(),hi=cn(),gie=dh(),yie=ct(),bie=sa(),vie=new Set(["ShowErrorMessage","Recommendation"]);function X$(e){var t,r;return e?[...(t=e.trueBranch)!==null&&t!==void 0?t:[],...(r=e.falseBranch)!==null&&r!==void 0?r:[]].some(n=>Array.isArray(n.trueBranch)||Array.isArray(n.falseBranch)?X$(n):vie.has(String(n.type))):!1}function wie(e){return Z$((0,hie.cloneJson)(e))}function Z$(e){var t,r;let n=i=>(i??[]).map(o=>Cie(o)?Z$(o):o);return{...e,logic:(t=e.logic)!==null&&t!==void 0?t:"AND",clauses:(r=e.clauses)!==null&&r!==void 0?r:[],trueBranch:n(e.trueBranch),falseBranch:n(e.falseBranch)}}function Cie(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 Eie(e){var t;if(e===null||typeof e!="object"||Array.isArray(e))throw new K$.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 K$.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 Aie="00000000-0000-0000-0000-000000000000";qo.BUSINESS_RULE_NULL_GUID=Aie;var Sie=new Set(["Recommendation","LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]),Nie=["ruleId","name","description","entityLogicalName","scope","status","rootCondition"],_ie=["kind","id","displayName","logic","clauses","trueBranch","falseBranch"],Tie=["id","field","fieldDisplayName","operator","valueType","value","valueField","lookupValue","expression","rawExpression","valueWorkflowType"];function Vn(e,t){return e===void 0?t:{...e,...t}}var ka=["kind","id","type","displayName","field","stepName","stepLabels"],J$=["valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression"],Die={Recommendation:[...ka,"recommendationTitle","messageText","acceptanceText","applyActions","recommendationActionStepMeta"],LockUnlock:[...ka,"lock"],ShowErrorMessage:[...ka,"errorMessage","messageLevel","messageActionSteps"],SetFieldValue:[...ka,...J$],SetDefaultValue:[...ka,...J$],SetBusinessRequired:[...ka,"required"],SetVisibility:[...ka,"visible"]};function ne(e,t){return t===void 0?{}:{[e]:t}}function ex(e){var t;return e==null?void 0:{...e,label:(t=e.label)!==null&&t!==void 0?t:""}}function Sv(e){return{valueType:e.valueType,...ne("valueWorkflowType",e.valueWorkflowType),...ne("value",e.value),...ne("valueField",e.valueField),...ne("lookupValue",ex(e.lookupValue)),...ne("expression",e.expression),...ne("rawExpression",e.rawExpression)}}function tx(e,t){let r=new Set(t),n={};for(let[i,o]of Object.entries(e))r.has(i)||o!==void 0&&(n[i]=o);return Object.keys(n).length>0?n:void 0}var Iie=["id","field","valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression","stepName","displayName"];function Oie(e){return Vn(e.bag,{id:e.id,field:e.field,...Sv(e),...ne("stepName",e.stepName),...ne("displayName",e.displayName)})}function Pie(e){let t=tx(e,Iie);return{id:e.id,field:e.field,valueType:e.valueType,...ne("valueWorkflowType",e.valueWorkflowType),...ne("value",e.value),...ne("valueField",e.valueField),...ne("lookupValue",e.lookupValue),...ne("expression",e.expression),...ne("rawExpression",e.rawExpression),...ne("stepName",e.stepName),...ne("displayName",e.displayName),...ne("bag",t)}}function Y$(e){return{valueType:e.valueType,...ne("valueWorkflowType",e.valueWorkflowType),...ne("value",e.value),...ne("valueField",e.valueField),...ne("lookupValue",e.lookupValue),...ne("expression",e.expression),...ne("rawExpression",e.rawExpression)}}function Q$(e){throw new Error(`Unsupported business-rule action type: ${e.type}`)}var Rie=new Set(["INVALID_CLEAR_FOR_FIELD","INVALID_VALUE_TYPE_FOR_FIELD","CLAUSE_VALUE_TOO_LONG","ACTION_VALUE_TOO_LONG"]),Lie=new Set,kie="INVALID_CLEAR_FOR_FIELD";function $ie(e){let t=n=>{var i;return(0,hi.isJsonObject)(n)&&(n.label===""||n.label===void 0)?{...n,label:String((i=n.id)!==null&&i!==void 0?i:"")}:n},r=n=>{if(!(0,hi.isJsonObject)(n))return n;let i={...n};"lookupValue"in i&&(i.lookupValue=t(i.lookupValue)),Array.isArray(i.applyActions)&&(i.applyActions=i.applyActions.map(r));for(let o of["clauses","trueBranch","falseBranch"])Array.isArray(i[o])&&(i[o]=i[o].map(r));return i};return r(e)}var jp=class{toArtifact(t){let r=this.residualBag(t,Nie),n={id:t.ruleId,name:t.name,description:t.description,entityLogicalName:t.entityLogicalName,scope:t.scope,status:t.status,rootCondition:t.rootCondition?this.conditionToJson(t.rootCondition):null};return r&&(n.bag=r),n}fromArtifact(t){let r=t.rootCondition?this.conditionFromJson(t.rootCondition):null;return Vn(t.bag,{ruleId:t.id,name:t.name,description:t.description,entityLogicalName:t.entityLogicalName,scope:t.scope,status:t.status,rootCondition:r})}fromApiResponse(t){var r;let n=t??{},i={...(r=n.Entity)!==null&&r!==void 0?r:{},wfomJson:n.WfomJson},o=(0,bc.deserializeWorkflowJson)(i);return this.toArtifact(o)}needsBaseLanguage(t){return X$(t.rootCondition)}toApiPayload(t,r,n){var i,o;let a=this.fromArtifact(t);a.wfomRoot&&(a.wfomRoot={...a.wfomRoot,name:t.name,title:t.name,primaryEntityName:t.entityLogicalName||a.wfomRoot.primaryEntityName},a.entityLogicalName=a.wfomRoot.primaryEntityName);let s=(0,bc.serializeToWorkflowJson)(a,(i=n?.baseLanguageCode)!==null&&i!==void 0?i:bie.DEFAULT_LCID),l=(o=a.ruleId)!==null&&o!==void 0?o:(0,j$.newId)();return{Entity:this.buildWorkflowEntity(a,l),WfomJson:s,status:t.status}}createDefault(t){var r,n,i,o,a,s;let l={ruleId:(r=t.id)!==null&&r!==void 0?r:null,name:(n=t.name)!==null&&n!==void 0?n:"New business rule",description:(i=t.description)!==null&&i!==void 0?i:"",entityLogicalName:(o=t.entityLogicalName)!==null&&o!==void 0?o:"",scope:(a=t.scope)!==null&&a!==void 0?a:"Entity",status:(s=t.status)!==null&&s!==void 0?s:"Draft",rootCondition:t.rootCondition===void 0?(0,bc.createEmptyCondition)():t.rootCondition===null?null:this.conditionFromJson(wie(Eie(t.rootCondition)))},u=this.toArtifact(l);return u.id||(u.id=(0,j$.newId)()),u}assignMissingIds(t){return(0,yie.assignMissingIds)(t)}validate(t){let r=[],n=t.rootCondition;return n==null?r:(0,hi.isJsonObject)(n)?(rx(n,"/rootCondition",r),r):(r.push((0,hi.issue)("/rootCondition","condition-must-be-object",`rootCondition must be a JSON object or null, got ${typeof n}`)),r)}semanticIssues(t,r=[]){let n;try{n=this.fromArtifact(t)}catch(a){return[(0,hi.issue)("/rootCondition","rule-not-representable",a instanceof Error?a.message:String(a))]}let i=n.rootCondition===null?null:$ie(n.rootCondition),o;return r.length===0?o=Rie:r.some(a=>a.requiredLevel!==void 0)?o=Lie:o=new Set([kie]),(0,bc.validateBusinessRule)(i,r).filter(a=>!o.has(a.kind)).map(a=>(0,hi.issue)(`/rootCondition (${a.nodeId})`,`business-rule-${a.kind}`,a.message))}issuesBlockingPush(t,r=[],n){return this.semanticIssues(t,r)}columnsCheckedAtPush(t){let r;try{r=this.fromArtifact(t)}catch{return[]}let n=new Set,i=a=>{a&&n.add(a)},o=a=>{var s;for(let l of a.clauses)i(l.field),i(l.valueField);for(let l of[...a.trueBranch,...a.falseBranch]){if(l.kind==="condition"){o(l);continue}if(i(l.field),l.type==="SetFieldValue"||l.type==="SetDefaultValue")i(l.valueField);else if(l.type==="Recommendation")for(let u of(s=l.applyActions)!==null&&s!==void 0?s:[])i(u.field),i(u.valueField)}};return r.rootCondition&&o(r.rootCondition),[...n]}residualBag(t,r){return tx(t,r)}buildWorkflowEntity(t,r){return(0,bc.buildWorkflowEntity)(t,r)}conditionToJson(t){let r=this.residualBag(t,_ie),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,Tie),n={id:t.id,field:t.field,fieldDisplayName:t.fieldDisplayName,operator:t.operator,valueType:t.valueType,...t.value!==void 0?{value:t.value}:{},...t.valueField!==void 0?{valueField:t.valueField}:{},...t.lookupValue!==void 0?{lookupValue:t.lookupValue}:{},...t.expression!==void 0?{expression:t.expression}:{},...t.rawExpression!==void 0?{rawExpression:t.rawExpression}:{},...t.valueWorkflowType!==void 0?{valueWorkflowType:t.valueWorkflowType}:{}};return r&&(n.bag=r),n}branchItemToJson(t){return t.kind==="condition"?this.conditionToJson(t):this.actionToJson(t)}actionToJson(t){let r=this.residualBag(t,Die[t.type]),n={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...ne("stepName",t.stepName),...ne("stepLabels",t.stepLabels),...ne("bag",r)};switch(t.type){case"Recommendation":return{...n,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...ne("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(Pie),...ne("recommendationActionStepMeta",t.recommendationActionStepMeta)};case"LockUnlock":return{...n,type:"LockUnlock",lock:t.lock};case"ShowErrorMessage":return{...n,type:"ShowErrorMessage",errorMessage:t.errorMessage,...ne("messageLevel",t.messageLevel),...ne("messageActionSteps",t.messageActionSteps)};case"SetFieldValue":return{...n,type:"SetFieldValue",...Y$(t)};case"SetDefaultValue":return{...n,type:"SetDefaultValue",...Y$(t)};case"SetBusinessRequired":return{...n,type:"SetBusinessRequired",required:t.required};case"SetVisibility":return{...n,type:"SetVisibility",visible:t.visible};default:return Q$(t)}}conditionFromJson(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:{};return Vn(n,{kind:"condition",isCollapsed:typeof n.isCollapsed=="boolean"?n.isCollapsed:!1,id:t.id,displayName:t.displayName,logic:t.logic,clauses:t.clauses.map(i=>this.clauseFromJson(i)),trueBranch:t.trueBranch.map(i=>this.branchItemFromJson(i)),falseBranch:t.falseBranch.map(i=>this.branchItemFromJson(i))})}clauseFromJson(t){var r;return Vn(t.bag,{id:t.id,field:t.field,fieldDisplayName:(r=t.fieldDisplayName)!==null&&r!==void 0?r:t.field,operator:t.operator,valueType:t.valueType,...ne("value",t.value),...ne("valueField",t.valueField),...ne("lookupValue",ex(t.lookupValue)),...ne("expression",t.expression),...ne("rawExpression",t.rawExpression),...ne("valueWorkflowType",t.valueWorkflowType)})}branchItemFromJson(t){return this.isConditionJson(t)?this.conditionFromJson(t):this.actionFromJson(t)}actionFromJson(t){if(!Sie.has(t.type))throw new Error(`Unsupported business-rule action type: ${t.type}`);Fie(t);let r={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...ne("stepName",t.stepName),...ne("stepLabels",t.stepLabels)};switch(t.type){case"Recommendation":return Vn(t.bag,{...r,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...ne("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(Oie),...ne("recommendationActionStepMeta",t.recommendationActionStepMeta)});case"LockUnlock":return Vn(t.bag,{...r,type:"LockUnlock",lock:t.lock});case"ShowErrorMessage":return Vn(t.bag,{...r,type:"ShowErrorMessage",errorMessage:t.errorMessage,...ne("messageLevel",t.messageLevel),...ne("messageActionSteps",t.messageActionSteps)});case"SetFieldValue":return Vn(t.bag,{...r,type:"SetFieldValue",...Sv(t)});case"SetDefaultValue":return Vn(t.bag,{...r,type:"SetDefaultValue",...Sv(t)});case"SetBusinessRequired":return Vn(t.bag,{...r,type:"SetBusinessRequired",required:t.required});case"SetVisibility":return Vn(t.bag,{...r,type:"SetVisibility",visible:t.visible});default:return Q$(t)}}isConditionJson(t){return Object.prototype.hasOwnProperty.call(t,"clauses")&&Object.prototype.hasOwnProperty.call(t,"logic")&&!Object.prototype.hasOwnProperty.call(t,"type")}};qo.BusinessRuleAdapter=jp;function rx(e,t,r){(0,hi.optionalEnum)(e,"logic",["AND","OR"],t,"condition-logic-invalid",r),(0,hi.childObjects)(e,"clauses",t,"clause",r);for(let n of["trueBranch","falseBranch"])(0,hi.childObjects)(e,n,t,"branchItem",r).forEach(({node:o,index:a})=>{"clauses"in o||"trueBranch"in o||"falseBranch"in o?rx(o,`${t}/${n}/${a}`,r):xie(o,`${t}/${n}/${a}`,r)})}function xie(e,t,r){e.type==="SetDefaultValue"&&e.valueType==="Clear"&&r.push((0,hi.issue)(`${t}/valueType`,"clear-only-set-field-value","Clear is only supported for SetFieldValue actions."))}function Fie(e){if(e.type==="SetDefaultValue"&&e.valueType==="Clear")throw new Error("Clear is only supported for SetFieldValue actions.")}function Mie(){return{adapter:new jp,api:gie.businessRuleApi,publish:(e,t,r)=>(0,H$.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,H$.boundEntityPublishScope)(t)}}qo.businessRuleRegistration=Mie});var Cx=v(Vo=>{"use strict";Object.defineProperty(Vo,"__esModule",{value:!0});Vo.appRegistration=Vo.AppAdapter=Vo.HEADER_NAV_BOOLEAN_RULE=void 0;var Zi=cn(),$t=wo(),wc=Eo(),Uie=jr(),px=Af(),Nv=tf(),_v=Co(),Bie=ct(),qie=oe(),mx=sa(),hx=Q(),gx=nf();Object.defineProperty(Vo,"HEADER_NAV_BOOLEAN_RULE",{enumerable:!0,get:function(){return gx.HEADER_NAV_BOOLEAN_RULE}});var Yp="7.0.0.0",ix=`<SiteMap IntroducedVersion="${Yp}"></SiteMap>`,ox="/_imgs/imagestrips/transparent_spacer.gif",ax="/_imgs/TableIconsFluentV9/document_one_page_sparkle.svg",yx=["Entity","Url","DefaultDashboard","Page","GenPageId"],vc="sitemapId",sx="sitemapName",Vie="sitemapNameUnique",lx="aiDescription",ux="[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}",Gie=new RegExp(`^(?:\\{${ux}\\}|${ux})$`);function cx(e,t){if(!Gie.test(e.trim()))throw new hx.ValidationError("app",t,[{pointer:"/sitemapId",rule:"app-sitemapid-guid",message:`sitemapId must be a GUID; received '${e}'.`}]);return e.trim()}function dx(e,t,r){if(e===void 0)return r;if(typeof e!="boolean")throw new hx.ValidationError("app",t,[bx(e)]);return e}function bx(e){return(0,Zi.issue)("/headerAndNavigationRefresh",gx.HEADER_NAV_BOOLEAN_RULE,`headerAndNavigationRefresh must be a boolean, got ${typeof e}`)}function Wie(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,qie.normalizeGuid)(i,n)}catch{return}};switch(e.type){case"Entity":return t("entity")&&`Entity:${t("entity").toLowerCase()}`;case"URL":return t("url")&&`URL:${t("url").toLowerCase()}`;case"DashBoard":return r("dashboardId")&&`DashBoard:${r("dashboardId")}`;case"CustomPage":return t("page")&&`CustomPage:${t("page").toLowerCase()}`;case"GenPage":return r("genPageId")&&`GenPage:${r("genPageId")}`;default:return}}function zie(e){var t,r,n,i;let o=[];for(let a of(r=(t=e.siteMap)===null||t===void 0?void 0:t.areas)!==null&&r!==void 0?r:[])for(let s of(n=a.groups)!==null&&n!==void 0?n:[])for(let l of(i=s.subAreas)!==null&&i!==void 0?i:[])l.type==="Entity"&&l.entity&&o.push(l.entity);return o}var Qp=class{constructor(t=mx.DEFAULT_LCID){this.lcid=t}toArtifact(t){let{bag:r,modeledEls:n}=Hp(t,"Area");return{id:"",name:"",uniqueName:"",description:"",siteMap:{areas:n.map(i=>this.areaToJson(i)),bag:r},bag:(0,$t.emptyBag)()}}fromArtifact(t){(0,_v.installDomShim)();let r=this.assignMissingIds(JSON.parse(JSON.stringify(t))),n=new DOMParser().parseFromString("<root/>","text/xml"),i=this.rootToRaw(r);return(0,$t.rebuildRaw)(i,(0,wc.domEngine)(n),null)}fromApiResponse(t){var r,n,i,o,a,s,l,u,c,d,f;(0,_v.installDomShim)();let m=t??{},p=(r=m.$sitemap)!==null&&r!==void 0?r:m,h=(0,wc.parseXmlRoot)((n=p.sitemapxml)!==null&&n!==void 0?n:ix,ix),g=this.toArtifact(h);return g.id=(i=m.appmoduleid)!==null&&i!==void 0?i:"",g.name=(o=m.name)!==null&&o!==void 0?o:"",g.uniqueName=(a=m.uniquename)!==null&&a!==void 0?a:"",g.description=(s=m.description)!==null&&s!==void 0?s:"",m.aiappdescription&&(g.aiDescription=m.aiappdescription),g.bag={a:[[vc,(u=(l=p.sitemapid)!==null&&l!==void 0?l:m._sitemapid_value)!==null&&u!==void 0?u:""],[sx,(c=p.sitemapname)!==null&&c!==void 0?c:""],[Vie,(d=p.sitemapnameunique)!==null&&d!==void 0?d:""],[lx,(f=m.aiappdescription)!==null&&f!==void 0?f:""]],c:[]},g}toApiPayload(t,r){var n,i,o,a,s,l,u,c,d,f,m,p,h,g,b;(0,_v.installDomShim)();let w=(0,wc.serializeNode)(this.fromArtifact(t)),C=[],S=[];for(let L of(i=(n=t.siteMap)===null||n===void 0?void 0:n.areas)!==null&&i!==void 0?i:[])for(let I of(o=L.groups)!==null&&o!==void 0?o:[])for(let D of(a=I.subAreas)!==null&&a!==void 0?a:[])D.type==="Entity"&&D.entity?C.push(D.entity):D.type==="DashBoard"&&D.dashboardId&&S.push(D.dashboardId);let O=(s=t.bag)!==null&&s!==void 0?s:(0,$t.emptyBag)();return{sitemapId:Dv(O,vc)||(t.sitemapId?cx(t.sitemapId,t.id):""),sitemapxml:w,sitemapname:Dv(O,sx)||t.name,appModuleId:t.id,appModuleName:t.name,appModuleDescription:t.description,...t.aiDescription!==void 0&&t.aiDescription!==(r?r.aiDescription:Dv(O,lx))?{appModuleAiDescription:t.aiDescription}:{},appModuleUniqueName:t.uniqueName,...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},...t.headerAndNavigationRefresh===void 0?{}:{appSettings:{[Nv.HEADER_AND_NAVIGATION_REFRESH]:dx(t.headerAndNavigationRefresh,(l=t.id)!==null&&l!==void 0?l:"(unknown)",!0)?Nv.APP_SETTING_ON:Nv.APP_SETTING_OFF}},...typeof t.published=="boolean"?{published:t.published}:{},entities:C,components:{forms:(c=(u=t.components)===null||u===void 0?void 0:u.forms)!==null&&c!==void 0?c:[],views:(f=(d=t.components)===null||d===void 0?void 0:d.views)!==null&&f!==void 0?f:[],charts:(p=(m=t.components)===null||m===void 0?void 0:m.charts)!==null&&p!==void 0?p:[],dashboards:[...(g=(h=t.components)===null||h===void 0?void 0:h.dashboards)!==null&&g!==void 0?g:[],...S],...((b=t.components)===null||b===void 0?void 0:b.mainFormsByTable)!==void 0?{mainFormsByTable:t.components.mainFormsByTable}:{}}}}createDefault(t){var r,n,i,o,a,s;let l=!((r=t.siteMap)===null||r===void 0)&&r.areas&&t.siteMap.areas.length>0?t.siteMap.areas:[{id:"",title:"Area",groups:[{id:"",title:"Group",subAreas:[]}]}],u=(n=t.id)!==null&&n!==void 0?n:(0,Bie.newId)();return{id:u,name:(i=t.name)!==null&&i!==void 0?i:"New App",uniqueName:(o=t.uniqueName)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",...t.aiDescription?{aiDescription:t.aiDescription}:{},siteMap:{areas:l},...t.sitemapId?{sitemapId:cx(t.sitemapId,u)}:{},...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},headerAndNavigationRefresh:dx(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(Ov):Array.isArray(r.areas)?r.areas.forEach(Ov):Array.isArray(r.groups)?Ov(r):Array.isArray(r.subAreas)?wx(r):"type"in r&&Xp(r,"subarea"),t}validate(t){let r=[],n=t.published;n!==void 0&&typeof n!="boolean"&&r.push((0,Zi.issue)("/published","published-must-be-boolean",`published must be a boolean, got ${typeof n}`));let i=t.siteMap,o=t.headerAndNavigationRefresh;if(o!==void 0&&typeof o!="boolean"&&r.push(bx(o)),i==null)return r;if(!(0,Zi.isJsonObject)(i))return r.push((0,Zi.issue)("/siteMap","sitemap-must-be-object",`siteMap must be a JSON object, got ${typeof i}`)),r;let a=(0,Zi.childObjects)(i,"areas","/siteMap","area",r),s=new Map;return a.forEach(({node:l,index:u})=>{let c=`/siteMap/areas/${u}`;(0,Zi.childObjects)(l,"groups",c,"group",r).forEach(({node:f,index:m})=>{let p=`${c}/groups/${m}`;(0,Zi.childObjects)(f,"subAreas",p,"subArea",r).forEach(({node:g,index:b})=>{let w=`${p}/subAreas/${b}`;(0,Zi.optionalEnum)(g,"type",["Entity","URL","DashBoard","CustomPage","GenPage"],w,"subarea-type-invalid",r);let C=Wie(g);if(!C)return;let S=s.get(C);if(S===void 0){s.set(C,w);return}r.push((0,Zi.issue)(w,"subarea-duplicate-target",`the sitemap already navigates to this target at ${S}; a duplicate SubArea would pin it twice and a single removeElement would leave one behind`))})})}),r}issuesBlockingPush(t){var r;return(0,px.mainFormSetShapeIssues)((r=t.components)===null||r===void 0?void 0:r.mainFormsByTable,zie(t))}applyServerIdentity(t,r){let n=r[vc];if(!n)return;t.bag||(t.bag=(0,$t.emptyBag)());let i=t.bag.a.find(o=>o[0]===vc);i?i[1]=n:t.bag.a.push([vc,n])}areaToJson(t){var r;let{bag:n,modeledEls:i}=Hp(t,"Group"),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:Tv(t,this.lcid),groups:i.map(l=>this.groupToJson(l)),bag:n},a=t.getAttribute("Icon");a&&(o.icon=a);let s=t.getAttribute("VectorIcon");return s&&(o.vectorIcon=s),o}groupToJson(t){var r;let{bag:n,modeledEls:i}=Hp(t,"SubArea");return{id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:Tv(t,this.lcid),subAreas:i.map(o=>this.subAreaToJson(o)),bag:n}}subAreaToJson(t){var r;let{bag:n}=Hp(t,null),i=jie(t),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",type:i,title:Tv(t,this.lcid),bag:n};if(i==="Entity"){let l=t.getAttribute("Entity");l&&(o.entity=l)}else if(i==="DashBoard"){let l=t.getAttribute("DefaultDashboard");l&&(o.dashboardId=l);let u=t.getAttribute("Url");u&&(o.dashboardUrl=u)}else if(i==="CustomPage"){let l=t.getAttribute("Page");l&&(o.page=l)}else if(i==="GenPage"){let l=t.getAttribute("GenPageId");l&&(o.genPageId=l)}else{let l=t.getAttribute("Url");l&&(o.url=l)}let a=t.getAttribute("Icon");a&&a!==ox&&(o.icon=a);let s=t.getAttribute("VectorIcon");return s&&(o.vectorIcon=s),o}rootToRaw(t){var r,n,i,o;let a=(n=(r=t.siteMap)===null||r===void 0?void 0:r.bag)!==null&&n!==void 0?n:(0,$t.emptyBag)(),l=Kp(a)?[["IntroducedVersion",Yp]]:[],u=((o=(i=t.siteMap)===null||i===void 0?void 0:i.areas)!==null&&o!==void 0?o:[]).map(c=>this.areaToRaw(c));return{n:"SiteMap",a:(0,$t.mergeAttrs)(a.a,l),c:(0,$t.spliceChildren)(a.c,u)}}areaToRaw(t){var r,n;let i=(r=t.bag)!==null&&r!==void 0?r:(0,$t.emptyBag)(),o=Kp(i),a=[],s=[];t.id&&a.push(["Id",t.id]),o&&a.push(["ShowGroups","true"],["ResourceId","SitemapDesigner.NewTitle"],["DescriptionResourceId","SitemapDesigner.NewTitle"],["IntroducedVersion",Yp]),t.icon!==void 0?a.push(["Icon",t.icon]):Jp(i.a,"Icon")&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):Jp(i.a,"VectorIcon")&&s.push("VectorIcon");let l=((n=t.groups)!==null&&n!==void 0?n:[]).map(c=>this.groupToRaw(c)),u=Iv((0,$t.spliceChildren)(i.c,l),t.title,o,this.lcid);return{n:"Area",a:(0,$t.mergeAttrs)(i.a,a,s),c:u}}groupToRaw(t){var r,n;let i=(r=t.bag)!==null&&r!==void 0?r:(0,$t.emptyBag)(),o=Kp(i),a=[];t.id&&a.push(["Id",t.id]),o&&a.push(["ResourceId","SitemapDesigner.NewGroup"],["DescriptionResourceId","SitemapDesigner.NewGroup"],["ToolTipResourseId","SitemapDesigner.Unknown"],["IntroducedVersion",Yp],["IsProfile","false"]);let s=((n=t.subAreas)!==null&&n!==void 0?n:[]).map(u=>this.subAreaToRaw(u)),l=Iv((0,$t.spliceChildren)(i.c,s),t.title,o,this.lcid);return{n:"Group",a:(0,$t.mergeAttrs)(i.a,a),c:l}}subAreaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,$t.emptyBag)(),i=Kp(n),o=Kie(n.a,t.type),a=[],s=[];t.id&&a.push(["Id",t.id]);let l=!i&&!n.a.some(([c])=>yx.includes(c));Yie(a,t,l),i?(a.push(["ResourceId","SitemapDesigner.NewSubArea"],["Client","All,Outlook,OutlookLaptopClient,OutlookWorkstationClient,Web"],["Sku","All,OnPremise,Live,SPLA"],["AvailableOffline","true"],["PassParams","false"]),t.icon&&a.push(["Icon",t.icon])):t.icon!==void 0?a.push(["Icon",t.icon]):Jp(o,"Icon",ox)&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):Jp(o,"VectorIcon")?t.type==="GenPage"?a.push(["VectorIcon",ax]):s.push("VectorIcon"):t.type==="GenPage"&&!Hie(o,"VectorIcon")&&a.push(["VectorIcon",ax]);let u=Iv((0,$t.spliceChildren)(n.c,[]),t.title,i,this.lcid);return{n:"SubArea",a:(0,$t.mergeAttrs)(o,a,s),c:u}}};Vo.AppAdapter=Qp;function Hp(e,t){let r=(0,wc.nodeLikeFromDom)(e).getAllProperties().map(s=>[s.key,s.value]),n=[],i=[],o=e.childNodes,a=0;for(let s=0;s<o.length;s+=1){let l=o[s];l.nodeType!==1&&l.nodeType!==3||(l.nodeType===1&&t!==null&&l.tagName===t?i.push(l):n.push({i:a,node:(0,$t.rawFromNode)((0,wc.nodeLikeFromDom)(l))}),a+=1)}return{bag:{a:r,c:n},modeledEls:i}}function fx(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName===t&&r.push(o)}return r}function Tv(e,t){var r;let n=fx(e,"Titles")[0];if(!n)return"";let o=fx(n,"Title").find(a=>a.getAttribute("LCID")===String(t));return o&&(r=o.getAttribute("Title"))!==null&&r!==void 0?r:""}function jie(e){return e.getAttribute("GenPageId")?"GenPage":e.getAttribute("Entity")?"Entity":e.getAttribute("Page")?"CustomPage":e.getAttribute("DefaultDashboard")?"DashBoard":"URL"}function Kp(e){return e.a.length===0&&e.c.length===0}function Hie(e,t){return e.some(([r])=>r===t)}function Jp(e,t,r){let n=e.find(([o])=>o===t),i=n?.[1];return!!i&&i!==r}function Dv(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function Kie(e,t){let r=Jie(t);return e.filter(([n])=>!yx.includes(n)||r.has(n)).map(n=>[n[0],n[1]])}function Jie(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 Yie(e,t,r){var n,i,o,a,s;switch(t.type){case"Entity":e.push(["Entity",(n=t.entity)!==null&&n!==void 0?n:""]);break;case"URL":(t.url!==void 0||!r)&&e.push(["Url",(i=t.url)!==null&&i!==void 0?i:""]);break;case"DashBoard":e.push(["DefaultDashboard",(o=t.dashboardId)!==null&&o!==void 0?o:""]),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",(s=t.genPageId)!==null&&s!==void 0?s:""]);break;default:break}}function Iv(e,t,r,n){if(!t)return e;let i=e.findIndex(o=>o.n==="Titles");if(i>=0){let o=e.slice();return o[i]=Qie(e[i],t,n),o}return r?[Xie(t,n),...e]:e}function Qie(e,t,r){let n=!1,i=e.c.map(o=>!n&&o.n==="Title"&&Zie(o,"LCID")===String(r)?(n=!0,{n:o.n,a:(0,$t.mergeAttrs)(o.a,[["Title",t]]),c:o.c}):o);return n||i.unshift(vx(t,r)),{n:e.n,a:e.a.map(o=>[o[0],o[1]]),c:i}}function Xie(e,t){return{n:"Titles",a:[],c:[vx(e,t)]}}function vx(e,t){return{n:"Title",a:[["LCID",String(t)],["Title",e]],c:[]}}function Zie(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function eoe(e){let t="0123456789abcdef",r="";for(let n=0;n<e;n+=1)r+=t[Math.floor(Math.random()*t.length)];return r}function Xp(e,t){e&&(typeof e.id!="string"||e.id.length===0)&&(e.id=`${t}_${eoe(8)}`)}function Ov(e){var t;Xp(e,"area");for(let r of(t=e.groups)!==null&&t!==void 0?t:[])wx(r)}function wx(e){var t;Xp(e,"group");for(let r of(t=e.subAreas)!==null&&t!==void 0?t:[])Xp(r,"subarea")}function toe(e=mx.DEFAULT_LCID){return{adapter:new Qp(e),api:px.appApi,languageSensitive:!0,publish:(t,r)=>(0,Uie.publishAppModule)(t,r),publishScope:t=>({envelope:"appmodule",targetIds:[t]}),rebaselineAfterPublish:"bracket"}}Vo.appRegistration=toe});var Ex={};nn(Ex,{ActionType:()=>Rv,AppActionOrigin:()=>Bv,AppActionVisibilityType:()=>Uv,ButtonType:()=>kv,CannotUpdateAppActionColumns:()=>roe,Context:()=>xv,IconType:()=>Lv,Location:()=>$v,OnClickEventType:()=>Mv,Scope:()=>Fv,VisibilityType:()=>Pv});var Pv,Rv,Lv,kv,$v,xv,Fv,Mv,Uv,Bv,roe,Ax=k(()=>{"use strict";(function(e){e[e.NotSupported=0]="NotSupported",e[e.Show=1]="Show",e[e.ClassicRules=2]="ClassicRules",e[e.Expression=3]="Expression"})(Pv||(Pv={}));(function(e){e[e.NotSupported=0]="NotSupported",e[e.None=1]="None",e[e.JavaScript=2]="JavaScript",e[e.Expression=3]="Expression"})(Rv||(Rv={}));(function(e){e[e.NoIcon=0]="NoIcon",e[e.UseIcon=1]="UseIcon",e[e.UseWebResource=2]="UseWebResource"})(Lv||(Lv={}));(function(e){e[e.Standard=0]="Standard",e[e.Dropdown=1]="Dropdown",e[e.Split=2]="Split",e[e.Group=3]="Group"})(kv||(kv={}));(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"})($v||($v={}));(function(e){e[e.All=0]="All",e[e.Entity=1]="Entity"})(xv||(xv={}));(function(e){e[e.App=0]="App",e[e.Entity=1]="Entity",e[e.Global=2]="Global"})(Fv||(Fv={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.JavaScript=2]="JavaScript"})(Mv||(Mv={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.ClassicRules=2]="ClassicRules"})(Uv||(Uv={}));(function(e){e[e.Default=0]="Default",e[e.Migrated=1]="Migrated",e[e.MigratedClone=2]="MigratedClone"})(Bv||(Bv={}));roe=["appactionid","appmoduleid","context","contextvalue","location","name","type","uniquename","isdisabled","origin"]});var Ox=v(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.assertOneWritePerRow=xt.commandApi=xt.COMMAND_DUPLICATE_ROW_CODE=xt.COMMAND_ROW_NOT_IN_BAR_CODE=xt.COMMAND_TABLE_MISMATCH_CODE=void 0;var qv=Tt(),Ur=fe(),eo=Q(),Br=oe();xt.COMMAND_TABLE_MISMATCH_CODE="COMMAND_TABLE_MISMATCH";xt.COMMAND_ROW_NOT_IN_BAR_CODE="COMMAND_ROW_NOT_IN_BAR";xt.COMMAND_DUPLICATE_ROW_CODE="COMMAND_DUPLICATE_ROW";var noe="OnClickEventJavaScriptWebResourceId($select=name,webresourceid),IconWebResourceId($select=name,webresourceid)";async function Vv(e,t){let r=`/EntityDefinitions(LogicalName='${(0,Br.odataPathLiteral)(t)}')${(0,Br.odataQuery)([["$select","MetadataId"]])}`,i=(0,Ur.ensureSuccess)(await e.get(r),e.apiUrl(r)).body,o=i?.MetadataId;return o?(0,Br.normalizeGuid)(o,"entityMetadataId"):""}function Gv(e,t){return t?`_contextentity_value eq ${t}`:`contextvalue eq '${(0,Br.odataLiteral)(e)}'`}function Cc(e){return`Nothing was written. Re-fetch the command with fetchArtifact('command', '${e}', { overwrite: true }) \u2014 this discards local edits \u2014 and re-apply the change.`}function Sx(e,t){let r=e.entityLogicalName;if(t===void 0)return r;if(typeof r!="string"||r.toLowerCase()!==t.toLowerCase())throw new eo.SdkError(xt.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': its JSON names table '${String(r)}'. A command's id is its table, so the push would write another table's command bar. Nothing was written. Fix its entityLogicalName, or push it under that table's id.`);return t}async function Nx(e,t,r){let n=await Vv(e,t);if(r){let i=(0,Br.normalizeGuid)(r,"entityMetadataId");if(i!==n)throw new eo.SdkError(xt.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': it was fetched for table id ${i}, but table '${t}' is ${n||"not resolvable"} on the server \u2014 the table was re-created, or the local copy edited. `+Cc(t))}return n}xt.commandApi={async get(e,t){let r=t,n=await Vv(e,r),i=Gv(r,n),o=`/appactions${(0,Br.odataQuery)([["$expand",noe],["$filter",i]])}`,a,s=await(0,qv.collectPages)(e,o,"fetchArtifact('command')",c=>{a=c}),l={entityLogicalName:r,entityMetadataId:n,appActions:s},u={};for(let c of s){let d=typeof c.appactionid=="string"?c.appactionid:void 0;if(d){let f=c["@odata.etag"];u[(0,Br.normalizeGuid)(d,"appactionid")]=typeof f=="string"?f:null}}return{raw:l,etag:a?(0,Ur.readEtag)(a):null,memberEtags:u}},async list(e,t){let r=t?.entityLogicalName;return r?[{type:"command",id:r,name:`${r} commands`,entityLogicalName:r,isDirty:!1}]:[]},async create(e,t,r){let n=t,i=Sx(n,r),o=await Nx(e,i,n.entityMetadataId);return _x(e,i,{...n,entityMetadataId:o},!1)},async update(e,t,r,n,i){let o=r,a=Sx(o,t),s=await Nx(e,a,o.entityMetadataId);return _x(e,a,{...o,entityMetadataId:s},!0,i)},async delete(e,t){let r=await Vv(e,t),n=`/appactions${(0,Br.odataQuery)([["$select","appactionid"],["$filter",Gv(t,r)]])}`,i=await(0,qv.collectPages)(e,n,"deleteArtifact('command')");for(let o of i)o.appactionid&&await(0,Ur.deleteRecord)(e,"appactions",o.appactionid)}};async function _x(e,t,r,n,i){let o=r.entityMetadataId?(0,Br.normalizeGuid)(r.entityMetadataId,"entityMetadataId"):"",a=await ooe(e,t,r,o,n,i),s={};try{await soe(e,a,o,s)}catch(l){throw(0,eo.withPartialTokens)(l,{memberEtags:s})}return{id:r.entityLogicalName,etag:null,memberEtags:s}}function Wv(e){return e.replace(/[{}]/g,"").toLowerCase()}function Ix(e,t){var r;let n=new Map,i=[...t.rows.map(o=>[o.appactionid,"written"]),...((r=t.deletedRowIds)!==null&&r!==void 0?r:[]).map(o=>[o,"deleted"])];for(let[o,a]of i){let s=Wv(o),l=n.get(s);if(l===void 0){n.set(s,a);continue}throw new eo.SdkError(xt.COMMAND_DUPLICATE_ROW_CODE,l===a?`Refusing to push command '${e}': app action '${s}' appears twice in it \u2014 two of its controls or groups carry that id, as one copied together with its id or bag does \u2014 so one would silently replace or remove the other. Nothing was written. Remove the id and the bag from the copy, so it is created as a new one, and push again.`:`Refusing to push command '${e}': app action '${s}' would be both written and deleted \u2014 one of its controls or groups spells that id differently (case or braces) than the copy last fetched or pushed \u2014 so the delete would remove what the write saved. Nothing was written. Spell the id as it was, and push again.`)}}xt.assertOneWritePerRow=Ix;var ioe={entities:/^\/entities\(([^()]+)\)$/,appactions:/^\/appactions\(([^()]+)\)$/};function Tx(e,t){let r=ioe[t].exec(e);return r?Wv(r[1]):void 0}async function ooe(e,t,r,n,i,o){var a,s;Ix(t,r);let l=loe(r.rows),u=new Set(l.map(f=>Wv(f.appactionid))),c={writes:[],deletes:[]};for(let f of l){let m=f.body["[email protected]"];if(m!==void 0&&!(typeof m=="string"&&n!==""&&Tx(m,"entities")===n))throw new eo.SdkError(xt.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': app action '${f.appactionid}' binds to ${typeof m=="string"?`'${m}'`:String(m)}, not to table '${t}' (${n?`/entities(${n})`:"whose id is not resolvable"}). `+Cc(t));let p=f.body["[email protected]"];if(typeof p=="string"){let h=Tx(p,"appactions");if(h===void 0||!u.has(h))throw new eo.SdkError(xt.COMMAND_ROW_NOT_IN_BAR_CODE,`Refusing to push command '${t}': app action '${f.appactionid}' would be placed under '${p}', which is not a row of this command. `+Cc(t))}if(i&&f.exists){let h=(0,Br.normalizeGuid)(f.appactionid,"id"),g=(a=o?.[h])!==null&&a!==void 0?a:f.etag;if(!(0,Ur.isVersionToken)(g))throw Dx(t,h,"update",g);c.writes.push({kind:"patch",row:f,id:h,token:g})}else{if(m===void 0&&!n)throw new eo.SdkError("COMMAND_CONTEXT_ENTITY_UNRESOLVED",`Cannot create app action '${f.appactionid}' for entity '${r.entityLogicalName}': the entity MetadataId could not be resolved, so the required ContextEntity bind cannot be set. A row written without it is created but is permanently unreadable \u2014 commandApi.get filters on _contextentity_value. Verify the entity logical name exists and is readable, then retry.`);c.writes.push({kind:"post",row:f})}}for(let f of(s=r.deletedRowIds)!==null&&s!==void 0?s:[]){let m=(0,Br.normalizeGuid)(f,"id"),p=o?.[m];if(!(0,Ur.isVersionToken)(p))throw Dx(t,m,"delete",p);c.deletes.push({id:m,token:p})}let d=[...c.writes.flatMap(f=>f.kind==="patch"?[{id:f.id,verb:"update"}]:[]),...c.deletes.map(f=>({id:f.id,verb:"delete"}))];if(d.length>0){let f=await aoe(e,t,n),m=d.find(p=>!f.has(p.id));if(m)throw new eo.SdkError(xt.COMMAND_ROW_NOT_IN_BAR_CODE,`Refusing to push command '${t}': it would ${m.verb} app action '${m.id}', which is not in table '${t}''s command bar on the server \u2014 a row of another table, or one deleted since the fetch. `+Cc(t))}return c}function Dx(e,t,r,n){return new eo.SdkError(Ur.UPDATE_NO_ETAG_CODE,`Refusing to push command '${e}': ${typeof n=="string"&&n!==""?`the token held for app action '${t}' ('${n}') is not a version`:`no token is held for app action '${t}'`}, so its ${r} could not be made conditional and would overwrite or remove a concurrent edit. `+Cc(e))}async function aoe(e,t,r){let n=`/appactions${(0,Br.odataQuery)([["$select","appactionid"],["$filter",Gv(t,r)]])}`,i=await(0,qv.collectPages)(e,n,"pushArtifact('command') bar membership"),o=new Set;for(let a of i)typeof a.appactionid=="string"&&o.add((0,Br.normalizeGuid)(a.appactionid,"appactionid"));return o}async function soe(e,t,r,n){for(let i of t.writes)if(i.kind==="patch"){let o=(0,Ur.echoWrite)("appactionid",{"If-Match":i.token}),a=`/appactions(${i.id})${o.query}`,s=(0,Ur.ensureSuccess)(await e.patch(a,i.row.body,o.options),e.apiUrl(a));n[i.id]=(0,Ur.readEtag)(s)}else{let o=(0,Ur.echoWrite)("appactionid"),a=`/appactions${o.query}`,s={...i.row.body};s["[email protected]"]===void 0&&(s["[email protected]"]=`/entities(${r})`);let l=(0,Ur.ensureSuccess)(await e.post(a,s,o.options),e.apiUrl(a)),u=(0,Ur.readCreatedId)(l,"appactionid");u&&(n[(0,Br.normalizeGuid)(u,"appactionid")]=(0,Ur.readEtag)(l))}for(let{id:i,token:o}of[...t.deletes].reverse())await(0,Ur.deleteRecord)(e,"appactions",i,o),delete n[i]}function loe(e){let t=new Map(e.map(o=>[o.appactionid,o])),r=new Set,n=[],i=o=>{if(r.has(o.appactionid))return;let a=o.body["[email protected]"];if(typeof a=="string"){let s=/\(([^)]+)\)/.exec(a),l=s?t.get(s[1]):void 0;l&&i(l)}r.add(o.appactionid),n.push(o)};return e.forEach(i),n}});var jx=v(Cl=>{"use strict";Object.defineProperty(Cl,"__esModule",{value:!0});Cl.commandRegistration=Cl.CommandAdapter=void 0;var mt=(Ax(),zr(Ex)),Px=jr(),St=cn(),kx=Ox(),$x=ct(),El=oe(),xx=Q(),Hv="$ClientSvg:",Kv=".svg",uoe=2,coe=1,doe=1,Fx="entityMetadataId",foe=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"]),Zp=class{toArtifact(t){var r,n,i,o,a,s,l;let u=(r=t.appActions)!==null&&r!==void 0?r:[],c=(n=t.entityLogicalName)!==null&&n!==void 0?n:"",d=u.find(h=>typeof h.appactionid!="string"||h.appactionid==="");if(d)throw new xx.InvalidArgumentError(`Cannot read the command bar of '${c}': app action row '${String((i=d.name)!==null&&i!==void 0?i:"")}' has no appactionid (its primary key), so it cannot be placed in the bar or written back.`);let f=new Map;for(let h of u){let g=typeof h._parentappactionid_value=="string"&&h._parentappactionid_value?h._parentappactionid_value:"",b=(o=f.get(g))!==null&&o!==void 0?o:[];b.push(h),f.set(g,b)}let m=new Map;for(let h of(a=f.get(""))!==null&&a!==void 0?a:[]){let g=yoe(h.location),b=(s=m.get(g))!==null&&s!==void 0?s:[];b.push(h),m.set(g,b)}let p=[];for(let[h,g]of m)p.push({location:h,groups:moe(g,f,qx(h),c)});return{id:c,entityLogicalName:c,commandBars:goe(p),bag:{a:[[Fx,(l=t.entityMetadataId)!==null&&l!==void 0?l:""]]}}}fromArtifact(t){return{entityLogicalName:t.entityLogicalName,entityMetadataId:Yv(t),appActions:zv(t).map(r=>r.row)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t,r){let n=new Set(r?zv(r).map(l=>l.appactionid):[]),i=zv(t,new Set([...n].map(l=>l.toLowerCase()))),o=new Set(i.map(l=>l.appactionid)),a=i.map(l=>{let u=l.exists||n.has(l.appactionid);return{appactionid:l.appactionid,exists:u,etag:l.etag,body:u?Ooe(l.row):zx(l.row)}}),s=[...n].filter(l=>!o.has(l));return(0,kx.assertOneWritePerRow)(t.entityLogicalName,{rows:a,deletedRowIds:s}),{entityLogicalName:t.entityLogicalName,entityMetadataId:Yv(t),rows:a,...s.length>0?{deletedRowIds:s}:{}}}createDefault(t){var r,n,i,o;let a=(n=(r=t.entityLogicalName)!==null&&r!==void 0?r:t.id)!==null&&n!==void 0?n:"";return{id:(i=t.id)!==null&&i!==void 0?i:a,entityLogicalName:a,commandBars:(o=t.commandBars)!==null&&o!==void 0?o:[]}}assignMissingIds(t){return(0,$x.assignMissingIds)(t)}normalize(t){let r=Coe(t),n=!1,i=(Array.isArray(t.commandBars)?t.commandBars:[]).map(o=>{let a=(0,St.isJsonObject)(o)&&Array.isArray(o.groups)?o.groups:void 0;if(!a)return o;let s=!1,l=a.map(u=>{let c=(0,St.isJsonObject)(u)&&Array.isArray(u.controls)?u.controls:void 0;if(!c)return u;let d=c.map(f=>Gx(f,r));return d.every((f,m)=>f===c[m])?u:(s=!0,{...u,controls:d})});return s?(n=!0,{...o,groups:l}):o});return n?{...t,commandBars:i}:t}validate(t){let r=[];return(0,St.childObjects)(t,"commandBars","","commandBar",r).forEach(({node:i,index:o})=>{let a=`/commandBars/${o}`;(0,St.optionalEnum)(i,"location",["MainTab","ContextualTab","HomeTab"],a,"bar-location-invalid",r),(0,St.childObjects)(i,"groups",a,"group",r).forEach(({node:l,index:u})=>{let c=`${a}/groups/${u}`;rm(l.bag)||((0,St.optionalGuidId)(l,"id",c,"group-id-invalid",r),typeof l.title=="string"&&l.title.length>0&&r.push({pointer:`${c}/title`,rule:"group-toplevel-title-unsupported",message:"a new top-level command group cannot have a title: Dataverse rejects a Group row with no parent (0x80040265). Leave the title empty to hold the commands without creating a group row, or nest them under a FlyoutAnchor control, which supplies the parent a group needs."})),Mx((0,St.childObjects)(l,"controls",c,"control",r),`${c}/controls`,r)})}),r}};Cl.CommandAdapter=Zp;function rm(e){let t=e?.a;return Array.isArray(t)&&t.length>0}function Mx(e,t,r){e.forEach(({node:n,index:i})=>{let o=`${t}/${i}`;rm(n.bag)||(0,St.optionalGuidId)(n,"id",o,"control-id-invalid",r),(0,St.optionalEnum)(n,"type",["Button","FlyoutAnchor","SplitButton"],o,"control-type-invalid",r);let a=n.location;a!==void 0&&(typeof a!="number"||!Number.isInteger(a)||a<0||a>6)&&r.push((0,St.issue)(`${o}/location`,"control-location-invalid",`location must be an integer 0-6 when present, got ${JSON.stringify(a)}`)),n.action!==void 0&&n.action!==null&&((0,St.isJsonObject)(n.action)?(0,St.optionalEnum)(n.action,"type",["javascript"],`${o}/action`,"action-type-invalid",r):r.push((0,St.issue)(`${o}/action`,"control-action-must-be-object",`a control action must be a JSON object when present, got ${typeof n.action}`)));let s=(0,St.childObjects)(n,"children",o,"control",r);s.length>0&&Mx(s,`${o}/children`,r)})}function Jv(e){return{a:Object.entries(e)}}function poe(e){return Object.fromEntries(e.a)}function Ec(e,t){if(e){for(let[r,n]of e.a)if(r===t)return n}}function Yv(e){let t=Ec(e.bag,Fx);return typeof t=="string"?t:""}function moe(e,t,r,n){var i,o;let a=[],s=[];for(let l of tm(e))l.type===mt.ButtonType.Group?a.push({id:Bx(l.name,n),title:typeof l.grouptitle=="string"?l.grouptitle:"",controls:tm((o=t.get((i=l.appactionid)!==null&&i!==void 0?i:""))!==null&&o!==void 0?o:[]).map(u=>em(u,t,r,n)),bag:Jv(l)}):s.push(em(l,t,r,n));return s.length>0&&a.unshift({id:Ioe(n,r),title:"",controls:s}),a}function Qv(e){let t=e.bag?Ec(e.bag,"appactionid"):void 0;return typeof t=="string"&&t.trim()!==""?t:e.id}function em(e,t,r,n){var i,o,a,s,l;let u=Bx(e.name,n),c={id:u,type:boe(e.type),label:typeof e.buttonlabeltext=="string"?e.buttonlabeltext:"",command:typeof e.appactionid=="string"?e.appactionid:u,bag:Jv(e)},d=Ux(e);d&&(c.icon=d);let f=hoe(e);f&&(c.action=f),typeof e.hidden=="boolean"&&(c.hidden=e.hidden),typeof e.isdisabled=="boolean"&&(c.disabled=e.isdisabled),typeof e.location=="number"&&e.location!==r&&(c.location=e.location);let m=t.get((i=e.appactionid)!==null&&i!==void 0?i:"");if(m&&m.length>0){let p=[],h=[];for(let g of tm(m))if(g.type===mt.ButtonType.Group){let b=(o=g.appactionid)!==null&&o!==void 0?o:"",w=Jv(g);c.flyoutGroupId===void 0&&(c.flyoutGroupId=(a=g.appactionid)!==null&&a!==void 0?a:void 0,c.flyoutGroupBag=w);let C=[];for(let S of tm((l=t.get((s=g.appactionid)!==null&&s!==void 0?s:""))!==null&&l!==void 0?l:[])){let O=em(S,t,r,n);p.push(O),C.push(Qv(O))}h.push({id:b,bag:w,childIds:C})}else p.push(em(g,t,r,n));c.children=p,h.length>1&&(c.flyoutGroups=h)}return c}function Ux(e){var t;if(!((t=e.IconWebResourceId)===null||t===void 0)&&t.name)return e.IconWebResourceId.name;if(e.fonticon)return e.fonticon.startsWith(Hv)?e.fonticon.slice(Hv.length)+Kv:e.fonticon}function hoe(e){var t;let r=e.onclickeventjavascriptfunctionname;if(typeof r!="string"||!r)return;let n=e.OnClickEventJavaScriptWebResourceId,i=e._onclickeventjavascriptwebresourceid_value,o={type:"javascript",webResourceId:(t=typeof i=="string"?i:n?.webresourceid)!==null&&t!==void 0?t:"",functionName:r};n?.name&&(o.libraryName=n.name);let a=e.onclickeventjavascriptparameters;return typeof a=="string"&&a&&(o.parameters=a),o}function Rx(e){return typeof e.sequence=="number"?e.sequence:typeof e.buttonsequencepriority=="number"?e.buttonsequencepriority:0}function tm(e){return[...e].sort((t,r)=>Rx(t)-Rx(r))}function goe(e){let t={MainTab:0,ContextualTab:1,HomeTab:2};return[...e].sort((r,n)=>{var i,o;return((i=t[r.location])!==null&&i!==void 0?i:9)-((o=t[n.location])!==null&&o!==void 0?o:9)})}function Bx(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 yoe(e){switch(e){case mt.Location.Form:case mt.Location.QuickForm:return"MainTab";case mt.Location.HomePageGrid:case mt.Location.Dashboard:return"HomeTab";default:return"ContextualTab"}}function qx(e){switch(e){case"MainTab":return mt.Location.Form;case"HomeTab":return mt.Location.HomePageGrid;default:return mt.Location.SubGridStandard}}function boe(e){switch(e){case mt.ButtonType.Dropdown:return"FlyoutAnchor";case mt.ButtonType.Split:return"SplitButton";default:return"Button"}}function voe(e){switch(e){case"FlyoutAnchor":return mt.ButtonType.Dropdown;case"SplitButton":return mt.ButtonType.Split;default:return mt.ButtonType.Standard}}function woe(e){var t;return e.bag&&e.bag.a.length>0?!0:((t=e.title)!==null&&t!==void 0?t:"").length>0}function Vx(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 zv(e,t=new Set){var r,n,i,o;let a=[],s=Yv(e);for(let l of(r=e.commandBars)!==null&&r!==void 0?r:[]){let u=qx(l.location),c=((n=l.groups)!==null&&n!==void 0?n:[]).flatMap(m=>{var p;return(p=m.controls)!==null&&p!==void 0?p:[]}),d=c.length>0&&c.every(m=>!Vx(m,t)),f=0;for(let m of(i=l.groups)!==null&&i!==void 0?i:[]){let p;if(woe(m)){let h=Aoe(m,u,void 0,e,s);a.push(h),p=h.appactionid}for(let h of(o=m.controls)!==null&&o!==void 0?o:[])Wx(h,u,p,e,s,a,d?f:void 0,t),f+=1}}return a}function Gx(e,t){if(!(0,St.isJsonObject)(e))return e;let r=e.children,n=r,i=!1;Array.isArray(r)&&(n=r.map(s=>Gx(s,t)),i=n.some((s,l)=>s!==r[l]));let o=!rm(e.bag)&&(typeof e.id!="string"||e.id.trim()==="");if(!o&&!i)return e;let a;if(o){do a=(0,$x.newId)();while(t.has(a));t.add(a)}return{...e,...a!==void 0?{id:a}:{},...i?{children:n}:{}}}function Coe(e){let t=new Set,r=(o,...a)=>{if((0,St.isJsonObject)(o))for(let s of[...a.map(l=>o[l]),rm(o.bag)?Ec(o.bag,"appactionid"):void 0])typeof s=="string"&&s.trim()!==""&&t.add(s.toLowerCase())},n=o=>{(0,St.isJsonObject)(o)&&(r(o,"id","flyoutGroupId"),r({bag:o.flyoutGroupBag}),(Array.isArray(o.flyoutGroups)?o.flyoutGroups:[]).forEach(a=>r(a,"id")),(Array.isArray(o.children)?o.children:[]).forEach(n))},i=e.commandBars;return(Array.isArray(i)?i:[]).forEach(o=>{let a=(0,St.isJsonObject)(o)?o.groups:void 0;(Array.isArray(a)?a:[]).forEach(s=>{r(s,"id");let l=(0,St.isJsonObject)(s)?s.controls:void 0;(Array.isArray(l)?l:[]).forEach(n)})}),t}function Wx(e,t,r,n,i,o,a,s=new Set){var l;let u=Eoe(e,t,r,n,i,a);o.push(u);let c=(l=e.children)!==null&&l!==void 0?l:[];if(c.length===0&&!(e.flyoutGroups&&e.flyoutGroups.length>0))return;let d=c.every(h=>!Vx(h,s)),f=(h,g,b)=>{Wx(h,t,g,n,i,o,d?b:void 0,s)},m=e.flyoutGroups;if(m&&m.length>0){let h=new Map(c.map(S=>[Qv(S),S])),g=new Set,b=0,w;for(let[S,O]of m.entries()){let L=O.id||(S===0?jv(u.appactionid):Zv("flyout-group",`${u.appactionid}#${S}`)),I=Lx(L,t,u.appactionid,n,i,O.bag);o.push(I);let D=I.appactionid;w===void 0&&(w=D);for(let P of O.childIds){let x=h.get(P);!x||g.has(P)||(g.add(P),f(x,D,b),b+=1)}}let C=w??jv(u.appactionid);for(let S of c){let O=Qv(S);g.has(O)||(g.add(O),f(S,C,b),b+=1)}return}let p=e.flyoutGroupId||jv(u.appactionid);o.push(Lx(p,t,u.appactionid,n,i,e.flyoutGroupBag));for(let[h,g]of c.entries())f(g,p,h)}function Eoe(e,t,r,n,i,o){let a=Xv(e,t,r,n,i),s=a.row;o!==void 0&&typeof s.sequence!="number"&&(s.sequence=o);let l=Ux(s);return e.location!==void 0&&(s.location=e.location),s.type=voe(e.type),s.buttonlabeltext=e.label,Noe(s,e.icon,l),Toe(s,e.action),_oe(s),e.hidden!==void 0&&(s.hidden=e.hidden),e.disabled!==void 0&&(s.isdisabled=e.disabled),{...a,row:s}}function Aoe(e,t,r,n,i){let o=Xv(e,t,r,n,i);return o.row.type=mt.ButtonType.Group,o.row.grouptitle=e.title,o}function Lx(e,t,r,n,i,o){let a=Xv({id:e,bag:o},t,r,n,i),s=a.row;return s["[email protected]"]=`/appactions(${(0,El.normalizeGuid)(r,"Command flyout group id")})`,s.type=mt.ButtonType.Group,s.grouptitle===void 0&&(s.grouptitle=""),s.isgrouptitlehidden===void 0&&(s.isgrouptitlehidden=!0),a}function Xv(e,t,r,n,i){let o,a,s,l;if(e.bag&&e.bag.a.length>0){o=poe(e.bag),a=!0;let u=Ec(e.bag,"@odata.etag");s=typeof u=="string"?u:null;let c=Ec(e.bag,"appactionid");l=typeof c=="string"&&c?c:e.id}else{if(typeof e.id!="string"||e.id.trim()==="")throw new xx.InvalidArgumentError(`Cannot serialize command '${n.entityLogicalName}': a new control has no id. Its primary key is minted once, before the first push, by normalize() \u2014 serialize the normalized artifact.`);l=e.id,o=Soe(l,t,n,i),a=!1,s=null}return r?o["[email protected]"]=`/appactions(${(0,El.normalizeGuid)(r,"Command parent appaction id")})`:a&&typeof o._parentappactionid_value=="string"&&o._parentappactionid_value&&o.type!==mt.ButtonType.Group&&(o["[email protected]"]=null),delete o._parentappactionid_value,{appactionid:l,exists:a,etag:s,row:o}}function Soe(e,t,r,n){let i={appactionid:e,name:`${e}!${e.replace(/-/g,"").slice(0,32)}`,uniquename:"",location:t,context:mt.Context.Entity,contextvalue:r.entityLogicalName,scope:mt.Scope.Entity};return n&&(i["[email protected]"]=`/entities(${(0,El.normalizeGuid)(n,"Command context entity metadata id")})`),i}function Noe(e,t,r){if(t===r){let n=e._iconwebresourceid_value;typeof n=="string"&&n&&!e.fonticon&&(e["[email protected]"]=`/webresourceset(${(0,El.normalizeGuid)(n,"Command icon web resource id")})`);return}if(t===void 0){e.fonticon="",e.IconWebResourceId=null;return}e.fonticon=t.toLowerCase().endsWith(Kv)?Hv+t.slice(0,t.length-Kv.length):t,e.IconWebResourceId=null}function _oe(e){let t=(n,i)=>{let o=e[n];if(typeof o!="string"||o.length===0||e[`${i}@odata.bind`]!==void 0)return;let a=(0,El.normalizeGuid)(o,`Command ${i}`);e[`${i}@odata.bind`]=`/canvasapps(${a})`};e.onclickeventtype===coe&&t("_onclickeventformulacomponentlibraryid_value","OnClickEventFormulaComponentLibraryId");let r=e.visibilitytype;(!r||r===doe)&&t("_visibilityformulacomponentlibraryid_value","VisibilityFormulaComponentLibraryId")}function Toe(e,t){if(!(!t||t.type!=="javascript")){if(e.onclickeventtype=uoe,t.webResourceId){let r=(0,El.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 Doe(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 Zv(e,t){let r="";for(let n=0;n<4;n+=1)r+=Doe(`${n}:${e}:${t}`).toString(16).padStart(8,"0");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`}function jv(e){return Zv("flyout-group",e)}function Ioe(e,t){return Zv("loose-group",`${e}|${t}`)}function zx(e){let t={...e};for(let r of foe)delete t[r];return t}function Ooe(e){let t=zx(e);for(let r of mt.CannotUpdateAppActionColumns)delete t[r];return t}function Poe(){return{adapter:new Zp,api:kx.commandApi,publish:(e,t,r)=>(0,Px.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,Px.boundEntityPublishScope)(t)}}Cl.commandRegistration=Poe});var Kx=v(nm=>{"use strict";Object.defineProperty(nm,"__esModule",{value:!0});nm.chartApi=void 0;var Roe=Tt(),qr=fe(),$a=oe(),Hx="savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault",Loe="savedqueryvisualizationid,name,primaryentitytypecode,charttype,isdefault";nm.chartApi={async get(e,t){let r=(0,$a.normalizeGuid)(t,"id"),n=await(0,qr.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r),i=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,$a.odataQuery)([["$select",Hx]]);return{raw:(0,qr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},async readContentThenToken(e,t){let r=(0,$a.normalizeGuid)(t,"id"),n=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,$a.odataQuery)([["$select",Hx]]),i=(0,qr.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=await(0,qr.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r);return{raw:i.body,etag:o}},async list(e,t){let r=`/savedqueryvisualizations${(0,$a.odataQuery)([["$select",Loe],["$filter",t?.entityLogicalName?`primaryentitytypecode eq '${(0,$a.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,Roe.collectPages)(e,r,"listArtifacts('chart')")).map(i=>{var o,a;return{type:"chart",id:(o=i.savedqueryvisualizationid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",entityLogicalName:i.primaryentitytypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,qr.echoWrite)("savedqueryvisualizationid"),o=`/savedqueryvisualizations${i.query}`,a=(0,qr.ensureSuccess)(await e.post(o,(0,qr.withClientMintedId)({name:n.name,description:n.description,datadescription:n.datadescription,presentationdescription:n.presentationdescription,primaryentitytypecode:n.primaryentitytypecode,charttype:n.charttype,isdefault:n.isdefault},"savedqueryvisualizationid",r),i.options),e.apiUrl(o));return{id:(0,qr.resolveCreatedId)(a,"savedqueryvisualizationid","chart",r),etag:(0,qr.readEtag)(a)}},async update(e,t,r,n){let i=r,o=(0,$a.normalizeGuid)(t,"id"),a=(0,qr.echoWrite)("savedqueryvisualizationid",{"If-Match":(0,qr.requireEtag)(n,"chart",o)}),s=`/savedqueryvisualizations(${o})${a.query}`,l=(0,qr.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,datadescription:i.datadescription,presentationdescription:i.presentationdescription},a.options),e.apiUrl(s));return{id:o,etag:(0,qr.readEtag)(l)}},delete(e,t){return(0,qr.deleteRecord)(e,"savedqueryvisualizations",t)}}});var dF=v(Sl=>{"use strict";Object.defineProperty(Sl,"__esModule",{value:!0});Sl.chartRegistration=Sl.ChartAdapter=void 0;var ew=wo(),Jx=cn(),gi=Eo(),Yx=jr(),koe=Kx(),tw=Co(),$oe=ct(),xoe=["Column","StackedColumn","StackedColumn100","Bar","StackedBar","StackedBar100","Area","StackedArea","StackedArea100","Line","Pie","Doughnut","Funnel","Tag"],Foe=new Map(xoe.map(e=>[e.toLowerCase(),e]));function tF(e){var t;return e&&(t=Foe.get(e.toLowerCase()))!==null&&t!==void 0?t:"Column"}function Moe(){return'<Chart Palette="BrightPastel"><Series><Series ChartType="Column" ChartArea="Default" /></Series><ChartAreas><ChartArea Name="Default" /></ChartAreas><Legends><Legend Name="Default" /></Legends></Chart>'}function Uoe(e){var t,r;let n=e.entityLogicalName,i=e.series.map((h,g)=>({alias:`agg_${g}`,series:h})),o=e.categories.map((h,g)=>({alias:`grp_${g}`,category:h})),a=h=>`<attribute alias="${h.alias}" name="${Al(h.series.attribute)}" aggregate="${Al(h.series.aggregate)}" />`,s=h=>`<attribute alias="${h.alias}" name="${Al(h.category.attribute)}" groupby="true"${h.category.dateGrouping?` dategrouping="${Al(h.category.dateGrouping)}"`:""} />`,l=[],u=new Map,c=(h,g)=>{if(!h){l.push(g);return}let b=u.get(h);b?b.push(g):u.set(h,[g])};i.forEach(h=>c(h.series.relatedEntity,a(h))),o.forEach(h=>c(h.category.relatedEntity,s(h)));let d=[...u.entries()].map(([h,g])=>`<link-entity name="${Al(h)}">${g.join("")}</link-entity>`).join(""),f=l.join("")+d,m=i.map(h=>`<measurecollection><measure alias="${h.alias}" /></measurecollection>`).join(""),p=(r=(t=o[0])===null||t===void 0?void 0:t.alias)!==null&&r!==void 0?r:"";return`<datadefinition><fetchcollection><fetch mapping="logical" aggregate="true"><entity name="${Al(n)}">${f}</entity></fetch></fetchcollection><categorycollection><category alias="${p}">${m}</category></categorycollection></datadefinition>`}var im=class{toArtifact(t){var r,n,i,o,a,s,l;(0,tw.installDomShim)();let u=(r=t.datadescription)!==null&&r!==void 0?r:"",c=(n=t.presentationdescription)!==null&&n!==void 0?n:"",d=(0,gi.parseXmlRoot)(u,"<datadefinition/>"),f=(0,gi.parseXmlRoot)(c,"<Chart/>");return{id:(i=t.savedqueryvisualizationid)!==null&&i!==void 0?i:"",name:(o=t.name)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",entityLogicalName:(s=t.primaryentitytypecode)!==null&&s!==void 0?s:"",chartType:om(f),isDefault:(l=t.isdefault)!==null&&l!==void 0?l:!1,series:iF(d),categories:oF(d),presentation:rF(f),dataBag:u?(0,gi.projectElementBag)(d):void 0,presentationBag:c?(0,gi.projectElementBag)(f):void 0,rowBag:Boe(t.charttype,t.type)}}fromArtifact(t){(0,tw.installDomShim)();let{datadescription:r,presentationdescription:n}=qoe(t);return{savedqueryvisualizationid:t.id,name:t.name,description:t.description,primaryentitytypecode:t.entityLogicalName,datadescription:r,presentationdescription:n,charttype:Qx(t.rowBag,"charttype"),type:Qx(t.rowBag,"type"),isdefault:t.isDefault}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){var r,n,i,o,a,s,l;let u=this.fromArtifact(t);return{name:(r=u.name)!==null&&r!==void 0?r:"",description:(n=u.description)!==null&&n!==void 0?n:"",datadescription:(i=u.datadescription)!==null&&i!==void 0?i:"",presentationdescription:(o=u.presentationdescription)!==null&&o!==void 0?o:"",primaryentitytypecode:(a=u.primaryentitytypecode)!==null&&a!==void 0?a:"",charttype:(s=u.charttype)!==null&&s!==void 0?s:0,isdefault:(l=u.isdefault)!==null&&l!==void 0?l:!1}}createDefault(t){var r,n,i,o,a,s,l;(0,tw.installDomShim)();let u=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,$oe.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New Chart",description:(o=t.description)!==null&&o!==void 0?o:"",entityLogicalName:u,chartType:(a=t.chartType)!==null&&a!==void 0?a:"Column",isDefault:(s=t.isDefault)!==null&&s!==void 0?s:!1,series:t.series&&t.series.length>0?t.series:[{attribute:"createdon",aggregate:"count"}],categories:t.categories&&t.categories.length>0?t.categories:[{attribute:"createdon",dateGrouping:"month"}],presentation:(l=t.presentation)!==null&&l!==void 0?l:{palette:"BrightPastel",showLegend:!0}}}assignMissingIds(t){return t}validate(t){let r=[],n=t;return(0,Jx.childObjects)(n,"series","","series",r),(0,Jx.childObjects)(n,"categories","","category",r),r}};Sl.ChartAdapter=im;function Boe(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 Qx(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 om(e){let t=e.getElementsByTagName("Series");for(let r=0;r<t.length;r+=1)if(t[r].getAttribute("ChartType"))return tF(t[r].getAttribute("ChartType"));return"Column"}function rF(e){var t;let r={showLegend:e.getElementsByTagName("Legend").length>0},n=e.getAttribute("Palette");n&&(r.palette=n);let i=e.getElementsByTagName("Title")[0],o=((t=i?.textContent)!==null&&t!==void 0?t:"").trim();return o&&(r.title=o),r}function am(e){return e.getElementsByTagName("fetch")[0]}function nF(e){let t=new Map;if(!e)return t;let r=e.getElementsByTagName("link-entity");for(let n=0;n<r.length;n+=1){let i=r[n],o=i.getAttribute("name");if(!o)continue;let a=i.getElementsByTagName("attribute");for(let s=0;s<a.length;s+=1){let l=a[s],u=l.getAttribute("alias")||l.getAttribute("name");u&&t.set(u,o)}}return t}function iF(e){let t=am(e);if(!t)return[];let r=nF(t),n=t.getElementsByTagName("attribute"),i=[];for(let o=0;o<n.length;o+=1){let a=n[o],s=a.getAttribute("aggregate");if(!s)continue;let l=a.getAttribute("name");if(!l)continue;let u={attribute:l,aggregate:s},c=a.getAttribute("charttype");c&&(u.seriesType=tF(c));let d=a.getAttribute("alias");d&&(u.alias=d);let f=d||l,m=r.get(f);m&&(u.relatedEntity=m),i.push(u)}return i}function oF(e){var t;let r=am(e);if(!r)return[];let n=nF(r),i=r.getElementsByTagName("attribute"),o=[];for(let a=0;a<i.length;a+=1){let s=i[a];if(((t=s.getAttribute("groupby"))!==null&&t!==void 0?t:"").toLowerCase()!=="true")continue;let l=s.getAttribute("name");if(!l)continue;let u={attribute:l},c=s.getAttribute("dategrouping");c&&(u.dateGrouping=c);let d=s.getAttribute("alias");d&&(u.alias=d);let f=d||l,m=n.get(f);m&&(u.relatedEntity=m),o.push(u)}return o}function qoe(e){var t,r;let n=(t=e.series)!==null&&t!==void 0?t:[],i=(r=e.categories)!==null&&r!==void 0?r:[];if(!Xx(e.dataBag)||!Xx(e.presentationBag)){let c=Uoe({...e,series:n,categories:i});return{datadescription:c,presentationdescription:aae(e,c)}}let o=new DOMParser().parseFromString("<root/>","text/xml"),a=Zx(e.dataBag,"datadefinition",o),s=Zx(e.presentationBag,"Chart",o),l=e.chartType||om(s),u=iF(a);if(!rw(n,u)){let c=nw(a);Voe(o,a,n);let d=nw(a),f=d.length>0?d:n.map(()=>"");aF(o,s,f,c,l)}return rw(i,oF(a))||Goe(o,a,i),e.chartType&&e.chartType!==om(s)&&uF(s,e.chartType),e.presentation&&!rw(e.presentation,rF(s))&&cF(s,e.presentation),{datadescription:(0,gi.serializeNode)(a),presentationdescription:(0,gi.serializeNode)(s)}}function Xx(e){return!!e&&(e.c.length>0||e.a.length>0)}function aF(e,t,r,n,i){let o,a=t.childNodes;for(let d=0;d<a.length;d+=1)if(a[d].nodeType===1&&a[d].tagName==="Series"){o=a[d];break}o||(o=e.createElement("Series"),t.insertBefore(o,t.firstChild));let s=[],l=o.childNodes;for(let d=0;d<l.length;d+=1)l[d].nodeType===1&&l[d].tagName==="Series"&&s.push(l[d]);let u=new Map;n.forEach((d,f)=>{let m=s[f];if(!m)return;let p=u.get(d);p?p.push(m):u.set(d,[m])});let c=r.map(d=>{let f=u.get(d),m=f&&f.length>0?f.shift():void 0;if(m)return m;let p=e.createElement("Series");p.setAttribute("ChartType",i);let h=s.length>0?s[0].getAttribute("ChartArea"):null;return h&&p.setAttribute("ChartArea",h),p});for(let d of s)o.removeChild(d);for(let d of c)o.appendChild(d)}function nw(e){let t=[],r=e.getElementsByTagName("measure");for(let n=0;n<r.length;n+=1)t.push(r[n].getAttribute("alias")||"");return t}function Zx(e,t,r){let n={n:t,a:(0,ew.mergeAttrs)(e.a,[]),c:(0,ew.spliceChildren)(e.c,[])};return(0,ew.rebuildRaw)(n,(0,gi.domEngine)(r),null)}function Voe(e,t,r){let n=am(t),i=n?.getElementsByTagName("entity")[0];!n||!i||sF(e,t,i,Yoe(n),r,Xoe,{aliasPrefix:"aggregate_column",addRef:joe,removeRef:Joe})}function Goe(e,t,r){let n=am(t),i=n?.getElementsByTagName("entity")[0];!n||!i||sF(e,t,i,Qoe(n),r,Zoe,{aliasPrefix:"groupby_column",addRef:Hoe,removeRef:Koe})}function sF(e,t,r,n,i,o,a){let s=new Map;for(let m of n){let p=m.getAttribute("alias");p&&s.set(p,m)}let l=new Set,u=[],c=(m,p)=>{var h;let g=eae(r,m),b=p.relatedEntity;(g??void 0)!==(b??void 0)&&((h=m.parentNode)===null||h===void 0||h.removeChild(m),eF(e,r,m,b))};for(let m of i){let p=m.alias?s.get(m.alias):void 0;p&&!l.has(p)?(o(p,m),c(p,m),l.add(p)):u.push(m)}let d=n.filter(m=>!l.has(m)),f=0;for(let m of u)if(f<d.length){let p=d[f];o(p,m),c(p,m),l.add(p),f+=1}else{let p=e.createElement("attribute"),h=m.alias||zoe(t,a.aliasPrefix);p.setAttribute("alias",h),o(p,m),eF(e,r,p,m.relatedEntity),a.addRef(e,t,h)}for(let m of n)if(!l.has(m)){let p=m.getAttribute("alias");p&&a.removeRef(t,p),rae(m)}}function Woe(e){let t=new Set;for(let r of["attribute","measure","category"]){let n=e.getElementsByTagName(r);for(let i=0;i<n.length;i+=1){let o=n[i].getAttribute("alias");o&&t.add(o)}}return t}function zoe(e,t){let r=Woe(e);if(!r.has(t))return t;for(let n=2;;n+=1){let i=`${t}_${n}`;if(!r.has(i))return i}}function lF(e,t){let r=t.getElementsByTagName("categorycollection")[0];if(r)return r;let n=e.createElement("categorycollection");return t.appendChild(n),n}function joe(e,t,r){let n=lF(e,t),i=n.getElementsByTagName("category")[0];i||(i=e.createElement("category"),n.appendChild(i));let o=e.createElement("measurecollection"),a=e.createElement("measure");a.setAttribute("alias",r),o.appendChild(a),i.appendChild(o)}function Hoe(e,t,r){let n=lF(e,t),i=e.createElement("category");i.setAttribute("alias",r),n.appendChild(i)}function Koe(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 Joe(e,t){var r;let n=e.getElementsByTagName("measure"),i=[];for(let o=0;o<n.length;o+=1)n[o].getAttribute("alias")===t&&i.push(n[o]);for(let o of i){let a=o.parentNode;a?.removeChild(o),a&&a.tagName==="measurecollection"&&!iae(a)&&((r=a.parentNode)===null||r===void 0||r.removeChild(a))}}function Yoe(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 Qoe(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 Xoe(e,t){e.setAttribute("name",t.attribute),e.setAttribute("aggregate",t.aggregate),t.seriesType&&e.setAttribute("charttype",t.seriesType)}function Zoe(e,t){e.setAttribute("name",t.attribute),e.setAttribute("groupby","true"),t.dateGrouping?e.setAttribute("dategrouping",t.dateGrouping):e.hasAttribute("dategrouping")&&e.removeAttribute("dategrouping")}function eae(e,t){let r=t.parentNode;for(;r&&r!==e;){let n=r;if(n.nodeType===1&&n.tagName==="link-entity")return n.getAttribute("name")||void 0;r=n.parentNode}}function eF(e,t,r,n){n?tae(e,t,n).appendChild(r):t.appendChild(r)}function tae(e,t,r){let n=t.getElementsByTagName("link-entity");for(let o=0;o<n.length;o+=1)if(n[o].getAttribute("name")===r)return n[o];let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function rae(e){let t=e.parentNode;if(t&&(t.removeChild(e),t.tagName==="link-entity"&&!nae(t))){let r=t.parentNode;r&&r.removeChild(t)}}function nae(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 iae(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1)if(t[r].nodeType===1)return!0;return!1}function uF(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(!oae(r[i])){r[i].setAttribute("ChartType",t);return}}}function oae(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 cF(e,t){var r;let n=e.ownerDocument;if(t.palette!==void 0&&e.setAttribute("Palette",t.palette),t.showLegend!==void 0){let i=e.getElementsByTagName("Legend").length>0;if(t.showLegend&&!i){let o=e.getElementsByTagName("Legends")[0];o||(o=n.createElement("Legends"),e.appendChild(o));let a=n.createElement("Legend");a.setAttribute("Name","Default"),o.appendChild(a)}else if(!t.showLegend)for(let o of["Legends","Legend"]){let a=[],s=e.getElementsByTagName(o);for(let l=0;l<s.length;l+=1)a.push(s[l]);for(let l of a)(r=l.parentNode)===null||r===void 0||r.removeChild(l)}}if(t.title!==void 0){let i=e.getElementsByTagName("Title")[0];i&&(i.textContent=t.title)}}function aae(e,t){let r=(0,gi.parseXmlRoot)(Moe(),"<Chart/>"),n=e.chartType||om(r);uF(r,n),e.presentation&&cF(r,e.presentation);let i=nw((0,gi.parseXmlRoot)(t,"<datadefinition/>"));return i.length>0&&aF(r.ownerDocument,r,i,i.slice(0,1),n),(0,gi.serializeNode)(r)}function rw(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Al(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function sae(){return{adapter:new im,api:koe.chartApi,publish:(e,t,r)=>(0,Yx.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,Yx.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}Sl.chartRegistration=sae});var hF=v(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.dashboardApi=xa.dashboardEntity=void 0;var lae=Tt(),Go=fe(),Nl=oe(),uae=Jg(),fF=vu();function pF(e){return e&&e.toLowerCase()!=="none"?e:void 0}xa.dashboardEntity=pF;var mF="formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber",cae={select:mF,required:["name","type","objecttypecode","istabletenabled"]},dae="formid,name,type,objecttypecode",fae=0,pae=10;xa.dashboardApi={async get(e,t){let r=(0,Nl.normalizeGuid)(t,"id"),n=`/systemforms(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Nl.odataQuery)([["$select",mF]]),i=(0,Go.ensureSuccess)(await e.get(n),e.apiUrl(n));return(0,fF.assertSystemFormRecordKind)(i.body,r,"dashboard","fetch"),{raw:i.body,etag:(0,Go.readEtag)(i)}},async list(e,t){let r=[`(type eq ${fae} or type eq ${pae})`];t?.entityLogicalName&&r.push(`objecttypecode eq '${(0,Nl.odataLiteral)(t.entityLogicalName)}'`);let n=`/systemforms${(0,Nl.odataQuery)([["$select",dae],["$filter",r.join(" and ")]])}`;return(await(0,lae.collectPages)(e,n,"listArtifacts('dashboard')")).map(o=>{var a,s;let l=pF(o.objecttypecode);return{type:"dashboard",id:(a=o.formid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",...l?{entityLogicalName:l}:{},isDirty:!1}})},async create(e,t,r){let n=t,i=(0,Go.echoWrite)("formid"),o=`/systemforms${i.query}`,a={name:n.name,description:n.description,formxml:n.formxml,istabletenabled:n.istabletenabled,type:n.type};n.objecttypecode&&(a.objecttypecode=n.objecttypecode);let s=(0,Go.ensureSuccess)(await e.post(o,(0,Go.withClientMintedId)(a,"formid",r),i.options),e.apiUrl(o));return{id:(0,Go.resolveCreatedId)(s,"formid","dashboard",r),etag:(0,Go.readEtag)(s)}},async update(e,t,r,n){let i=r;return(0,uae.patchSystemForm)(e,(0,Nl.normalizeGuid)(t,"id"),"dashboard",{name:i.name,description:i.description,formxml:i.formxml,istabletenabled:i.istabletenabled},n,cae)},readContentThenToken(e,t){return xa.dashboardApi.get(e,t)},async delete(e,t){let r=(0,Nl.normalizeGuid)(t,"id");return await(0,fF.assertSystemFormKind)(e,r,"dashboard"),(0,Go.deleteRecord)(e,"systemforms",r)}}});var DF=v(yi=>{"use strict";Object.defineProperty(yi,"__esModule",{value:!0});yi.dashboardRegistration=yi.TILE_CLASS_ID=yi.DashboardAdapter=void 0;var Sc=wo(),En=Eo(),iw=jr(),Ac=cn(),CF=hF(),ow=Co(),Fa=ct(),EF=oe(),AF=sa(),mae=yb(),gF="0",aw="10",hae=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"]]),gae="{3FF9A528-DD50-4ACA-8F10-2E5ED73513AD}",lm=class{constructor(t=AF.DEFAULT_LCID){this.lcid=t}toArtifact(t){var r,n,i,o,a;(0,ow.installDomShim)();let s=(r=t.formxml)!==null&&r!==void 0?r:"",l=(0,En.parseXmlRoot)(s,"<form/>");return{id:(n=t.formid)!==null&&n!==void 0?n:"",name:(i=t.name)!==null&&i!==void 0?i:"",description:(o=t.description)!==null&&o!==void 0?o:"",dashboardType:yae(t.type),entityLogicalName:(a=(0,CF.dashboardEntity)(t.objecttypecode))!==null&&a!==void 0?a:null,enabledForMobile:!!t.istabletenabled,layoutType:bae(l),components:yF(l,this.lcid),bag:(0,En.projectElementBag)(l)}}fromArtifact(t){var r;return(0,ow.installDomShim)(),{formid:t.id,name:t.name,description:t.description,type:t.dashboardType==="Interactive"?aw:gF,objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",istabletenabled:t.enabledForMobile,formxml:bF(t,this.lcid)}}fromApiResponse(t){return this.toArtifact(t??{})}completeAsStored(t,r){return(0,mae.completeRecordAsStored)(t,r,this.lcid)}toApiPayload(t){return{name:t.name,description:t.description,formxml:bF(t,this.lcid),istabletenabled:t.enabledForMobile,type:t.dashboardType==="Interactive"?aw:gF,objecttypecode:t.entityLogicalName}}createDefault(t){var r,n,i,o,a,s,l,u;(0,ow.installDomShim)();let c=(0,En.parseXmlRoot)(Pae(),"<form/>");return{id:(r=t.id)!==null&&r!==void 0?r:(0,Fa.newId)(),name:(n=t.name)!==null&&n!==void 0?n:"New Dashboard",description:(i=t.description)!==null&&i!==void 0?i:"",dashboardType:(o=t.dashboardType)!==null&&o!==void 0?o:"Standard",entityLogicalName:(a=t.entityLogicalName)!==null&&a!==void 0?a:null,enabledForMobile:(s=t.enabledForMobile)!==null&&s!==void 0?s:!1,layoutType:(l=t.layoutType)!==null&&l!==void 0?l:0,components:(u=t.components)!==null&&u!==void 0?u:yF(c,this.lcid),bag:(0,En.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,Fa.newId)())}return t}validate(t){let r=[],n=(0,Ac.childObjects)(t,"components","","component",r),i=new Set;return n.forEach(({node:o,index:a})=>{let s=`/components/${a}`;for(let l of["position","parameters"]){let u=o[l];u!==void 0&&!(0,Ac.isJsonObject)(u)&&r.push((0,Ac.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,Ac.isJsonObject)(o.position)){let l=Nc(o.position);i.has(l)?r.push((0,Ac.issue)(`${s}/position`,"component-position-collision",`two components occupy the same dashboard position (${l}); move one to a free cell`)):i.add(l)}}),r}};yi.DashboardAdapter=lm;function yae(e){return String(e??"")===aw?"Interactive":"Standard"}function bae(e){let t=e?.getAttribute("formLayout")||e?.getAttribute("layoutType"),r=parseInt(t??"",10);return Number.isNaN(r)?0:r}function se(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName.toLowerCase()===t&&r.push(o)}return r}function yF(e,t){let r=[];return se(e,"tabs").flatMap(i=>se(i,"tab")).forEach((i,o)=>{se(i,"columns").flatMap(s=>se(s,"column")).forEach((s,l)=>{se(s,"sections").flatMap(c=>se(c,"section")).forEach((c,d)=>{vae(c,{tabIndex:o,columnIndex:l,sectionIndex:d},r,t)})})}),r}function vae(e,t,r,n){se(e,"rows").flatMap(o=>se(o,"row")).forEach((o,a)=>{se(o,"cell").forEach((s,l)=>{let u=wae(s,{...t,rowIndex:a,cellIndex:l},n);u&&r.push(u)})})}function wae(e,t,r){var n,i;let o=_F((n=e.getAttribute("id"))!==null&&n!==void 0?n:"");if(o.toLowerCase().startsWith("spacer"))return null;let a=se(e,"control")[0];if(!a)return null;let s=(i=a.getAttribute("classid"))!==null&&i!==void 0?i:"",l=Aae(a),u=Sae(s,l,a),c=Cae(a);return{id:a.getAttribute("id")||o,type:u,name:NF(e,r),classId:s,position:t,colspan:um(e,"colspan",1),rowspan:um(e,"rowspan",1),parameters:l,bag:(0,En.projectElementBag)(e),...c?{icProperties:c}:{}}}function SF(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 Cae(e){let t=SF(e);return t?(0,En.serializeNode)(t):void 0}function Eae(e,t,r){let n=SF(t);if(!r){n&&t.removeChild(n);return}let i=new DOMParser().parseFromString(r,"text/xml").documentElement,o=(0,Sc.rebuildRaw)((0,Sc.rawFromNode)((0,En.nodeLikeFromDom)(i)),(0,En.domEngine)(e),null);n&&(0,En.serializeNode)(n)===(0,En.serializeNode)(o)||(n?t.replaceChild(o,n):t.appendChild(o))}function NF(e,t){var r,n;let i=se(e,"labels")[0];if(!i)return"";let o=se(i,"label"),a=(r=o.find(s=>s.getAttribute("languagecode")===String(t)))!==null&&r!==void 0?r:o[0];return(n=a?.getAttribute("description"))!==null&&n!==void 0?n:""}function Aae(e){var t;let r={},n=se(e,"parameters")[0];if(!n)return r;let i=n.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];a.nodeType===1&&(r[a.tagName]=((t=a.textContent)!==null&&t!==void 0?t:"").trim())}return r}function Sae(e,t,r){var n;let i=hae.get(e.toUpperCase());return i?i==="chart"?t.ChartGridMode==="Chart"?"chart":"list":i==="assistant"?((n=r.getAttribute("uniqueid"))!==null&&n!==void 0?n:"").toUpperCase()===gae?"assistant":t.ChartGridMode!==void 0||r.getAttribute("indicationOfSubgrid")==="true"?t.ChartGridMode==="Chart"?"chart":"list":"unknown":i:"unknown"}function um(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 _F(e){return e.replace(/^\{/,"").replace(/\}$/,"")}function Nae(e,t){let r={n:"form",a:(0,Sc.mergeAttrs)(e.bag.a,[]),c:(0,Sc.spliceChildren)(e.bag.c,[])};return(0,Sc.rebuildRaw)(r,(0,En.domEngine)(t),null)}function bF(e,t){let r=new DOMParser().parseFromString("<root/>","text/xml"),n=Nae(e,r);return Dae(r,n,e.components,t),_ae(r,n,e.components,t),(0,En.serializeNode)(n)}function _ae(e,t,r,n){let i=TF(t);for(let o of r)i.has(Nc(o.position))||Tae(e,t,o,n)}function Tae(e,t,r,n){var i,o,a,s;let l=(o=(i=r.position)===null||i===void 0?void 0:i.sectionIndex)!==null&&o!==void 0?o:0,u=Rae(t,e,l);for(let x of se(u,"row"))se(x,"cell").some(K=>se(K,"control").length>0)||u.removeChild(x);let c=r.classId||yi.TILE_CLASS_ID[r.type]||yi.TILE_CLASS_ID.iframe,d=r.rowspan&&r.rowspan>0?r.rowspan:4,f=r.bag&&vF(r.bag,"id")?String(vF(r.bag,"id")):sm((0,Fa.newId)()),m=r.id?sm(r.id):sm((0,Fa.newId)()),p=u.parentNode,h=Math.max(1,parseInt(p&&p.getAttribute&&p.getAttribute("columns")||"1",10)||1),g=Math.min(Math.max(1,r.colspan&&r.colspan>0?r.colspan:1),h),b=se(u,"row"),w=b[b.length-1],C=w?se(w,"cell").reduce((x,K)=>x+um(K,"colspan",1),0):0;(!w||C+g>h)&&(w=e.createElement("row"),u.appendChild(w));let S=e.createElement("cell");S.setAttribute("id",f),S.setAttribute("colspan",String(g)),S.setAttribute("rowspan",String(d)),S.setAttribute("showlabel","true");let O=e.createElement("labels"),L=e.createElement("label");L.setAttribute("description",(a=r.name)!==null&&a!==void 0?a:""),L.setAttribute("languagecode",String(n)),O.appendChild(L),S.appendChild(O);let I=e.createElement("control");I.setAttribute("id",m),I.setAttribute("classid",sm(c));let D=e.createElement("parameters"),P=(s=r.parameters)!==null&&s!==void 0?s:{};for(let x of Object.keys(P)){let K=(0,EF.createSafeXmlElement)(e,x,"dashboard tile parameter");K.textContent=P[x],D.appendChild(K)}I.appendChild(D),S.appendChild(I),w.appendChild(S)}function vF(e,t){if(!e)return;let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function Dae(e,t,r,n){var i;let o=TF(t),a=new Set(r.map(s=>Nc(s.position)));for(let s of r){let l=o.get(Nc(s.position));if(!l)continue;let u=se(l,"control")[0];u&&(Iae(e,l,s.name,n),Oae(e,u,s.parameters),wF(l,"colspan",s.colspan),wF(l,"rowspan",s.rowspan),s.icProperties!==void 0&&Eae(e,u,s.icProperties))}for(let[s,l]of o)a.has(s)||(i=l.parentNode)===null||i===void 0||i.removeChild(l)}function TF(e){let t=new Map;return se(e,"tabs").flatMap(n=>se(n,"tab")).forEach((n,i)=>{se(n,"columns").flatMap(a=>se(a,"column")).forEach((a,s)=>{se(a,"sections").flatMap(u=>se(u,"section")).forEach((u,c)=>{se(u,"rows").flatMap(f=>se(f,"row")).forEach((f,m)=>{se(f,"cell").forEach((p,h)=>{var g;_F((g=p.getAttribute("id"))!==null&&g!==void 0?g:"").toLowerCase().startsWith("spacer")||se(p,"control")[0]&&t.set(Nc({tabIndex:i,columnIndex:s,sectionIndex:c,rowIndex:m,cellIndex:h}),p)})})})})}),t}function Nc(e){let t=e??{};return`${t.tabIndex}.${t.columnIndex}.${t.sectionIndex}.${t.rowIndex}.${t.cellIndex}`}function Iae(e,t,r,n){if(r===NF(t,n))return;let i=se(t,"labels")[0];i||(i=e.createElement("labels"),t.appendChild(i));let o=se(i,"label").find(a=>a.getAttribute("languagecode")===String(n));o||(o=e.createElement("label"),o.setAttribute("languagecode",String(n)),i.appendChild(o)),o.setAttribute("description",r)}function Oae(e,t,r){var n;if(!r)return;let i=Object.keys(r);if(i.length===0)return;let o=se(t,"parameters")[0];o||(o=e.createElement("parameters"),t.appendChild(o));let a=new Map,s=o.childNodes;for(let l=0;l<s.length;l+=1){let u=s[l];u.nodeType===1&&a.set(u.tagName,u)}for(let l of i){let u=r[l],c=a.get(l);if(c)((n=c.textContent)!==null&&n!==void 0?n:"")!==u&&(c.textContent=u);else{let d=(0,EF.createSafeXmlElement)(e,l,"dashboard component parameter");d.textContent=u,o.appendChild(d)}}}function wF(e,t,r){um(e,t,1)!==r&&e.setAttribute(t,String(r))}function Pae(e=2){let t=`{${(0,Fa.newId)()}}`,r=`{${(0,Fa.newId)()}}`,n=`{${(0,Fa.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>`}yi.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 sm(e){return`{${e.replace(/[{}]/g,"")}}`}function Rae(e,t,r){var n;let i=se(e,"tabs").flatMap(u=>se(u,"tab"))[0];if(!i)throw new Error("addDashboardTile: dashboard formxml has no <tab>");let o=se(i,"columns").flatMap(u=>se(u,"column"))[0];if(!o)throw new Error("addDashboardTile: dashboard formxml has no <column>");let a=se(o,"sections").flatMap(u=>se(u,"section")),s=(n=a[r])!==null&&n!==void 0?n:a[0];if(!s)throw new Error("addDashboardTile: dashboard formxml has no <section>");let l=se(s,"rows")[0];return l||(l=t.createElement("rows"),s.appendChild(l)),l}function Lae(e=AF.DEFAULT_LCID){return{adapter:new lm(e),api:CF.dashboardApi,languageSensitive:!0,publish:(t,r,n)=>n?.entityLogicalName?(0,iw.publishBoundEntity)(t,n):(0,iw.publishDashboardById)(t,r),publishScope:(t,r)=>r?.entityLogicalName?(0,iw.boundEntityPublishScope)(r):{envelope:"dashboard",targetIds:[t]},rebaselineAfterPublish:"bracket"}}yi.dashboardRegistration=Lae});var lw=v(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.readEveryInOrder=Vr.readInOrder=Vr.plainRead=Vr.resolveReadConcurrency=Vr.MAX_READ_CONCURRENCY=void 0;var IF=Q();Vr.MAX_READ_CONCURRENCY=8;function kae(e){if(e===void 0)return 1;if(typeof e!="number"||!Number.isInteger(e)||e<1||e>Vr.MAX_READ_CONCURRENCY)throw new IF.InvalidArgumentError(`readConcurrency must be a whole number from 1 to ${Vr.MAX_READ_CONCURRENCY} (got ${typeof e=="string"?`'${e}'`:String(e)})`);return e}Vr.resolveReadConcurrency=kae;var $ae=e=>({ok:!0,value:e}),sw=e=>({ok:!1,error:e});function xae(e){let t=(async()=>e())().then($ae,sw);return{outcome:t,finish:async r=>{await r()},discard:async()=>{await t}}}Vr.plainRead=xae;async function OF(e,t,r,n,i){if(!Number.isInteger(t)||t<1)throw new IF.InvalidArgumentError(`a read window holds a whole number of reads, at least 1 (got ${String(t)})`);let o=new Map,a=0,s=Promise.resolve(),l=!1,u=0,c,d=async f=>{if(l)return{refusal:new Error("The read was not started: an earlier read had already failed.")};try{let m=await r(e[f],f),p=m.outcome.catch(sw);return i==="stop"&&p.then(h=>{l=l||!h.ok}),{read:m,outcome:p}}catch(m){return l=l||i==="stop",{refusal:m}}};try{for(let f=0;f<e.length;f+=1){for(;a<e.length&&a<f+t;){let g=a;a+=1;let b=s.then(()=>d(g));o.set(g,b),s=b}let m=await o.get(f),p="read"in m?await m.outcome:sw(m.refusal);if(!p.ok&&i==="stop"){c={error:p.error};break}u=f+1,o.delete(f);let h=()=>n(p,e[f],f);"read"in m?await m.read.finish(h):await h()}}finally{l=!0;for(let f=u;f<a;f+=1){let m=await o.get(f);"read"in m&&await m.read.discard().catch(()=>{})}}if(c)throw c.error}function Fae(e,t,r,n){return OF(e,t,r,(i,o,a)=>n(i.value,o,a),"stop")}Vr.readInOrder=Fae;function Mae(e,t,r,n){return OF(e,t,r,n,"continue")}Vr.readEveryInOrder=Mae});var HF=v(dm=>{"use strict";Object.defineProperty(dm,"__esModule",{value:!0});dm.genPageApi=void 0;var cm=Tt(),VF=Es(),Ve=fe(),be=oe(),Gn=pa(),Qe=Q(),GF=ct(),PF=lw();function Uae(e){if(ArrayBuffer.isView(e)){let r=e;return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}if(Object.prototype.toString.call(e)==="[object ArrayBuffer]")return new Uint8Array(e);let t=globalThis;if(t.Buffer&&t.Buffer.isBuffer(e)){let r=e;return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}}var bi="uxagentprojects",Ua="uxagentprojectfiles",Dc="agentconversationmessages",Ic="uxagentprojectid",jt="uxagentprojectfileid",Ba="agentconversationmessageid",_c=`${Ic},name`,Bae=`${jt},filename,filetype`,WF=2e8,zF=200000001,qa={"MSCRM.IncludeUnpublished":"true"},uw={};function Ma(e,t){return{"MSCRM.VersioningChangeset":e,...qa,...t}}async function fw(e,t,r,n){var i;let o=`/${t}(${r})`+(0,be.odataQuery)([["$select",n]]),a=(0,Ve.ensureSuccess)(await e.get(o,{headers:{...qa}}),e.apiUrl(o));return{row:(i=a.body)!==null&&i!==void 0?i:{},etag:(0,Ve.readEtag)(a)}}async function Oc(e,t,r=qa){let n=`/${Ua}(${t})/filecontent/$value`,i=await e.get(n,{headers:{...r}});if(i.status===404)return{status:"unavailable",reason:"missing"};(0,Ve.ensureSuccess)(i,e.apiUrl(n));let o=i.body,a=Uae(o);if(a)return{status:"available",data:(0,Gn.bytesToBase64)(a)};if(typeof o=="string")return{status:"available",data:(0,Gn.utf8ToBase64)(o)};throw new Qe.SdkError("GENPAGE_CONTENT_UNREADABLE",`Read the content of file '${t}' but the injected HttpClient returned a body this SDK cannot encode (${typeof o}). Return the response as a string, Uint8Array, Buffer, or ArrayBuffer; a byte-returning transport is required to round-trip non-UTF8 assets.`)}function jF(e){let t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}async function qae(e,t,r,n,i,o){if(!e.supportsBinaryPatch)throw new Qe.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED",`Refusing to push generative-page file '${t}': its content cannot be written because the injected HttpClient does not implement patchRaw(). A Dataverse File column is not writable through a JSON body, so saving the row without its bytes would report success for a page whose source never uploaded.`);let a=`/${Ua}(${t})/filecontent`,s=(0,Gn.base64ToBytes)(n);(0,be.assertNoControlChars)(r,"generative-page file name"),(0,Ve.ensureSuccess)(await e.patchRaw(a,s,{headers:Ma(i,{"Content-Type":"application/octet-stream","Content-Length":String(s.byteLength),"x-ms-file-name":jF(r),...o?{"If-Match":"*"}:{}})}),e.apiUrl(a))}async function Tc(e,t,r=qa){let n=`/${Ua}`+(0,be.odataQuery)([["$select",Bae],["$filter",`_${Ic}_value eq ${t}`]]);return(await(0,cm.collectPages)(e,n,"fetchArtifact('genPage')",void 0,{headers:{...r}})).map(o=>({row:o,etag:typeof o["@odata.etag"]=="string"?o["@odata.etag"]:null}))}async function cw(e,t){let r=`/${Dc}`+(0,be.odataQuery)([["$select",`${Ba},message,messagesender,createdon`],["$filter",`_regardingobjectid_value eq ${t}`],["$orderby","createdon asc,versionnumber asc"]]);return(0,cm.collectPages)(e,r,"fetchArtifact('genPage')",void 0,{headers:{...qa}})}async function RF(e,t){var r,n,i;let{row:o,etag:a}=await fw(e,bi,t,_c),s=new Map;for(let{row:l,etag:u}of await Tc(e,t))s.set((0,be.normalizeGuid)(String((r=l[jt])!==null&&r!==void 0?r:""),jt),{filename:String((n=l.filename)!==null&&n!==void 0?n:""),filetype:Number(l.filetype),etag:u});return{name:String((i=o.name)!==null&&i!==void 0?i:""),etag:a,rows:s}}function LF(e,t,r){var n,i,o,a,s;let l=[];r||l.push({kind:"createProject",name:t.name});let u=new Set;for(let c of(n=t.files)!==null&&n!==void 0?n:[]){let d=(0,be.normalizeGuid)(c.id,"file id");u.add(d);let f=r?.rows.get(d);if(c.content.status==="retain"){if(!r)throw new Qe.SdkError("GENPAGE_RETAIN_ON_CREATE",`Refusing to create generative page '${e}': file '${c.name}' asks to keep content the page does not have yet. This is an SDK defect \u2014 the page's rows were not written.`);if(!f)throw new Qe.SdkError("GENPAGE_RETAINED_ROW_MISSING",`Refusing to write generative page '${e}': file '${c.name}' was to be kept unchanged but is not on the server. Re-fetch the page and retry.`);continue}f&&c.unchanged||(f?(f.filename!==c.name||f.filetype!==c.fileType)&&l.push({kind:"renameRow",file:c}):l.push({kind:"createRow",file:c}),c.content.status==="available"&&l.push({kind:"content",file:c,data:c.content.data,existing:f!==void 0}))}for(let c of(i=r?.rows.keys())!==null&&i!==void 0?i:[])u.has(c)||l.push({kind:"deleteRow",fileId:c});(!r||l.length>0||r.name!==t.name||((a=(o=t.messages)===null||o===void 0?void 0:o.length)!==null&&a!==void 0?a:0)>0)&&l.push({kind:"patchProject",name:t.name});for(let c of(s=t.messages)!==null&&s!==void 0?s:[])l.push({kind:"message",turn:c});return l}function pw(e){let t=(0,Gn.base64ToUtf8)(e);return(0,Gn.utf8ToBase64)(t)===(0,Gn.bytesToBase64)((0,Gn.base64ToBytes)(e))?t:void 0}function Vae(e,t,r,n){var i,o,a,s,l,u,c,d;let f=t.sender==="user"?{changeSet:n,dataSources:(o=(i=r.messageContext)===null||i===void 0?void 0:i.dataSources)!==null&&o!==void 0?o:[],model:(s=(a=r.messageContext)===null||a===void 0?void 0:a.model)!==null&&s!==void 0?s:"",enabledTools:(u=(l=r.messageContext)===null||l===void 0?void 0:l.enabledTools)!==null&&u!==void 0?u:[],configurableTools:(d=(c=r.messageContext)===null||c===void 0?void 0:c.configurableTools)!==null&&d!==void 0?d:[]}:{changeSet:n};return{...t.id?{[Ba]:(0,be.normalizeGuid)(t.id,"message id")}:{},"[email protected]":`/${bi}(${e})`,message:t.message,messagecontext:JSON.stringify(f),messagesender:t.sender==="user"?WF:zF}}async function Gae(e,t,r){var n,i,o,a;let s=((n=r.messages)!==null&&n!==void 0?n:[]).map(f=>f.id).filter(f=>typeof f=="string"&&f!=="").map(f=>(0,be.normalizeGuid)(f,"message id"));if(s.length===0)return r;let l=`/${Dc}`+(0,be.odataQuery)([["$select",`${Ba},message,messagesender,_regardingobjectid_value`],["$filter",s.map(f=>`${Ba} eq ${f}`).join(" or ")]]),u=await(0,cm.collectPages)(e,l,"pushArtifact('genPage')",void 0,{headers:{...qa}});if(u.length===0)return r;let c=new Map(u.map(f=>{var m;return[String((m=f[Ba])!==null&&m!==void 0?m:"").toLowerCase(),f]})),d=[];for(let f of(i=r.messages)!==null&&i!==void 0?i:[]){let m=f.id?c.get((0,be.normalizeGuid)(f.id,"message id")):void 0;if(!m){d.push(f);continue}if(!(String((o=m.message)!==null&&o!==void 0?o:"")===f.message&&Number(m.messagesender)===(f.sender==="user"?WF:zF)&&String((a=m._regardingobjectid_value)!==null&&a!==void 0?a:"").toLowerCase()===t))throw new Qe.SdkError("GENPAGE_TURN_CONFLICT",`Refusing to push generative page '${t}': its pending turn's identity is already recorded \u2014 as a DIFFERENT ${f.sender} message. An earlier push of this turn did commit (its response was lost), and the turn was changed since. Nothing was written, and the turn is still pending. To record it as a new turn, remove '/newTurn/id' (a new identity is minted on the next push); to keep only what was recorded, remove '/newTurn'.`)}return{...r,messages:d}}function dw(e,t,r,n){switch(t.kind){case"createProject":return{method:"POST",path:`/${bi}`,body:(0,Ve.withClientMintedId)({name:t.name},Ic,e),headers:Ma(n)};case"createRow":return{method:"POST",path:`/${Ua}`,body:(0,Ve.withClientMintedId)({filename:t.file.name,filetype:t.file.fileType,[`${Ic}@odata.bind`]:`/${bi}(${e})`},jt,(0,be.normalizeGuid)(t.file.id,"file id")),headers:Ma(n)};case"renameRow":return{method:"PATCH",path:`/${Ua}(${(0,be.normalizeGuid)(t.file.id,"file id")})`,body:{filename:t.file.name,filetype:t.file.fileType},headers:Ma(n,{"If-Match":"*"})};case"content":{let i=pw(t.data);if(i===void 0)throw new Qe.SdkError("GENPAGE_CONTENT_NOT_TEXT",`File '${t.file.name}' is not UTF-8 text and cannot ride in a change set.`);return(0,be.assertNoControlChars)(t.file.name,"generative-page file name"),{method:"PATCH",path:`/${Ua}(${(0,be.normalizeGuid)(t.file.id,"file id")})/filecontent`,rawBody:i,contentType:"application/octet-stream; charset=utf-8",headers:Ma(n,{"x-ms-file-name":jF(t.file.name),...t.existing?{"If-Match":"*"}:{}})}}case"deleteRow":return{method:"DELETE",path:`/${Ua}(${t.fileId})`,headers:Ma(n,{"If-Match":"*"})};case"patchProject":return{method:"PATCH",path:`/${bi}(${e})`,body:{name:t.name},headers:Ma(n,{"If-Match":"*"})};case"message":return{method:"POST",path:`/${Dc}`,body:Vae(e,t.turn,r,n)};default:{let i=t;throw new Qe.SdkError("GENPAGE_WRITE_UNKNOWN",`Unknown generative-page write: ${JSON.stringify(i)}`)}}}function kF(e,t){return e.supportsAtomicBatch&&t.every(r=>r.kind!=="content"||pw(r.data)!==void 0)}async function $F(e,t,r,n,i){await(0,VF.postChangeSet)(e,r.map(o=>dw(t,o,n,i)),`generative page '${t}' (${r.length} operation(s))`)}async function xF(e,t,r,n,i){var o;let a=[];for(let s of r){if(s.kind==="message"){a.push(s);continue}if(s.kind==="content"){await qae(e,(0,be.normalizeGuid)(s.file.id,"file id"),s.file.name,s.data,i,s.existing);continue}let l=dw(t,s,n,i),u={headers:(o=l.headers)!==null&&o!==void 0?o:{}},c=l.method==="POST"?await e.post(l.path,l.body,u):l.method==="PATCH"?await e.patch(l.path,l.body,u):await e.delete(l.path,u);(0,Ve.ensureSuccess)(c,e.apiUrl(l.path))}if(a.length===0)return{warnings:[],turnRecorded:!0};try{let s=a.map(l=>dw(t,l,n,i));if(e.supportsAtomicBatch)await(0,VF.postChangeSet)(e,s,`the conversation turn of generative page '${t}'`);else for(let l of s)(0,Ve.ensureSuccess)(await e.post(l.path,l.body),e.apiUrl(l.path));return{warnings:[],turnRecorded:!0}}catch(s){return{warnings:[`Generative page '${t}' was saved, but its conversation turn could not be recorded (${s instanceof Error?s.message:String(s)}). The turn is kept: the next push of the page records it.`],turnRecorded:!1}}}async function FF(e,t,r,n,i,o,a){var s;let l=u=>({id:t,etag:null,memberEtags:{},warnings:[...a,u]});try{let u=await RF(e,t),c=new Map;for(let C of r)(C.kind==="createRow"||C.kind==="renameRow"||C.kind==="content")&&c.set((0,be.normalizeGuid)(C.file.id,"file id"),C.file);let d=[];u.name!==n.name&&d.push(`the page is named '${u.name}', not '${n.name}'`);for(let[C,S]of c){let O=u.rows.get(C);O&&(O.filename!==S.name||O.filetype!==S.fileType)&&d.push(`file '${S.name}' is stored as '${O.filename}' (type ${O.filetype})`)}for(let C of r){if(C.kind!=="content")continue;let S=await Oc(e,(0,be.normalizeGuid)(C.file.id,"file id")),O=(0,Gn.bytesToBase64)((0,Gn.base64ToBytes)(C.data));(S.status!=="available"||S.data!==O)&&d.push(S.status==="available"?`file '${C.file.name}' holds ${(0,Gn.base64ToBytes)(S.data).byteLength} byte(s) that differ from the ${(0,Gn.base64ToBytes)(O).byteLength} written`:`file '${C.file.name}' holds no content`)}let f=new Set(r.filter(C=>C.kind==="content").map(C=>(0,be.normalizeGuid)(C.file.id,"file id")));for(let[C,S]of c)!f.has(C)&&(await Oc(e,C)).status==="available"&&d.push(`file '${S.name}' holds content this push did not write`);if(d.length>0)return l(`Generative page '${t}' was written, but reading it back does not match what was sent: ${d.join("; ")}. The local baseline is now unusable: re-fetch the page to see what the server holds \u2014 the next push will refuse rather than overwrite blind.`);let m=await RF(e,t),p=[...m.rows.keys()],h=m.etag!==u.etag||m.rows.size!==u.rows.size||p.some(C=>{var S,O;return((S=u.rows.get(C))===null||S===void 0?void 0:S.etag)!==((O=m.rows.get(C))===null||O===void 0?void 0:O.etag)}),g=p.length!==i.size||p.some(C=>!i.has(C)),b={},w=[];for(let[C,S]of m.rows){let O=c.has(C)||!o?S.etag:(s=o.get(C))!==null&&s!==void 0?s:null;b[C]=O,O!==S.etag&&w.push(S.filename)}return h||g||!m.etag||Object.values(b).some(C=>!C)?l(`Generative page '${t}' was written, but its files changed on the server while the write was in progress, so the new concurrency tokens cannot be trusted. The local baseline is now unusable: re-fetch the page before editing it again \u2014 the next push will refuse rather than overwrite blind.`):Wae({id:t,etag:m.etag,memberEtags:b},[...a,...w.map(C=>`Generative page '${t}' was written, but its file '${C}' changed on the server while this push ran \u2014 another writer edited it. This push did not touch that file, so the next one refuses until you re-fetch the page and see their change.`)])}catch(u){return l(`The generative page was written, but reading it back failed (${u instanceof Error?u.message:String(u)}). The local baseline is unusable: re-fetch the page before editing it \u2014 the next push will refuse rather than overwrite blind.`)}}async function MF(e,t,r,n=e.readConcurrency){var i;let o=(0,be.normalizeGuid)(t,"id"),{row:a,etag:s}=await fw(e,bi,o,_c),l=await Tc(e,o),u={},c=[];if(n>1)await(0,PF.readInOrder)(l,n,({row:f})=>{var m;let p=(0,be.normalizeGuid)(String((m=f[jt])!==null&&m!==void 0?m:""),jt);return(0,PF.plainRead)(async()=>({fileId:p,content:await Oc(e,p)}))},({fileId:f,content:m},{row:p,etag:h})=>{u[f]=h,c.push({...p,content:m})});else for(let{row:f,etag:m}of l){let p=(0,be.normalizeGuid)(String((i=f[jt])!==null&&i!==void 0?i:""),jt);u[p]=m;let h=await Oc(e,p);c.push({...f,content:h})}return{raw:r?{project:a,files:c,conversation:await cw(e,o)}:{project:a,files:c},etag:s,memberEtags:u}}dm.genPageApi={get(e,t,r){return MF(e,t,!0,r?.fileConcurrency)},getForRebaseline(e,t){return MF(e,t,!1)},async getPublished(e,t){var r,n;let i=(0,be.normalizeGuid)(t,"id"),o=`/${bi}(${i})`+(0,be.odataQuery)([["$select",_c]]),a=await e.get(o);if(a.status===404)return null;(0,Ve.ensureSuccess)(a,e.apiUrl(o));let s=(r=a.body)!==null&&r!==void 0?r:{},l={},u=[],c=await Tc(e,i,uw);for(let{row:g,etag:b}of c){let w=(0,be.normalizeGuid)(String((n=g[jt])!==null&&n!==void 0?n:""),jt);l[w]=b,u.push({...g,content:await Oc(e,w,uw)})}let d=g=>g.map(({row:b,etag:w})=>`${String(b[jt])}@${String(w)}`).sort().join("|"),f=()=>new Qe.SdkError("GENPAGE_PUBLISHED_READ_MOVED",`The published projection of generative page '${i}' changed while it was being read, so what was read is not one published state. PublishXml is asynchronous \u2014 re-read shortly.`),m=await e.get(o);if(m.status===404)throw f();(0,Ve.ensureSuccess)(m,e.apiUrl(o));let p=await Tc(e,i,uw);if([(0,Ve.readEtag)(a),(0,Ve.readEtag)(m),...[...c,...p].map(g=>g.etag)].some(g=>!g))throw new Qe.SdkError("GENPAGE_PUBLISHED_READ_UNVERSIONED",`The published projection of generative page '${i}' answered without a version token for the page or one of its rows, so what was read cannot be proven to be one published state.`);if((0,Ve.readEtag)(m)!==(0,Ve.readEtag)(a)||d(p)!==d(c))throw f();return{raw:{project:s,files:u,conversation:[]},etag:(0,Ve.readEtag)(a),memberEtags:l}},async list(e,t){let r=`/${bi}`+(0,be.odataQuery)([["$select",_c]]);return(await(0,cm.collectPages)(e,r,"listArtifacts('genPage')",void 0,{headers:{...qa}})).map(i=>{var o,a;return{type:"genPage",id:String((o=i[Ic])!==null&&o!==void 0?o:""),name:String((a=i.name)!==null&&a!==void 0?a:""),isDirty:!1}})},async create(e,t,r){var n;let i=t,o=r?(0,be.normalizeGuid)(r,"id"):(0,GF.newId)(),a=LF(o,i,void 0);qF(e,a),BF(e,o,i);let s=UF(),l=[],u=!0;kF(e,a)?await $F(e,o,a,i,s):{warnings:l,turnRecorded:u}=await xF(e,o,a,i,s);let c=new Set(((n=i.files)!==null&&n!==void 0?n:[]).map(f=>(0,be.normalizeGuid)(f.id,"file id"))),d=await FF(e,o,a,i,c,void 0,l);return u?d:{...d,intentPending:!0}},async update(e,t,r,n,i){var o,a;let s=r,l=(0,be.normalizeGuid)(t,"id");if(!Array.isArray(s.files))throw new Qe.SdkError("GENPAGE_FILES_REQUIRED",`Refusing to update generative page '${l}': its payload has no files list. A page's files are its complete set of rows \u2014 a row the list omits is deleted \u2014 so an omitted list would delete every row of the page. Nothing was written.`);let u=await Gae(e,l,s);BF(e,l,u);let c=await Tc(e,l),{row:d,etag:f}=await fw(e,bi,l,_c);if(n&&f&&n!==f)throw new Qe.SdkError(Ve.VERSION_CONFLICT_CODE,`Generative page '${l}' changed on the server after it was fetched (baseline ${n}, server ${f}) \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||!f)throw new Qe.SdkError(Ve.VERSION_CONFLICT_CODE,`Cannot verify generative page '${l}' before writing: ${n?"the server did not return the page's current token":"no baseline token was recorded"}. This entity accepts no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let m=new Map(c.map(({row:I})=>{var D,P;return[(0,be.normalizeGuid)(String((D=I[jt])!==null&&D!==void 0?D:""),jt),{filename:String((P=I.filename)!==null&&P!==void 0?P:""),filetype:Number(I.filetype)}]})),p=new Set(m.keys()),h=new Set(((o=u.files)!==null&&o!==void 0?o:[]).map(I=>(0,be.normalizeGuid)(I.id,"file id")));if(!i)throw new Qe.SdkError(Ve.VERSION_CONFLICT_CODE,`Cannot verify the files of generative page '${l}' before writing: no child baseline was recorded. These rows accept no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let g=new Set(Object.keys(i).map(I=>I.toLowerCase()));for(let I of h)if(!p.has(I)&&g.has(I))throw new Qe.SdkError(Ve.VERSION_CONFLICT_CODE,`Generative-page file '${I}' existed when this page was fetched but is gone from the server now \u2014 another writer deleted it. Refusing to recreate it, because a blind re-create would undo that delete. Re-fetch the page and re-apply the edit.`);for(let I of p)if(!g.has(I))throw new Qe.SdkError(Ve.VERSION_CONFLICT_CODE,`Generative-page file '${I}' is on the server but absent from this page's baseline \u2014 another writer added it after the page was fetched, so its contents cannot be verified. Refusing to write over or delete it. Re-fetch the page so the addition is part of your baseline.`);let b=new Map(c.map(({row:I,etag:D})=>{var P;return[(0,be.normalizeGuid)(String((P=I[jt])!==null&&P!==void 0?P:""),jt),D]}));for(let[I,D]of Object.entries(i)){let P=I.toLowerCase();if(!p.has(P))continue;let x=b.get(P);if(!D||!x)throw new Qe.SdkError(Ve.VERSION_CONFLICT_CODE,`Cannot verify generative-page file '${P}' before writing: ${D?"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(D!==x)throw new Qe.SdkError(Ve.VERSION_CONFLICT_CODE,`Generative-page file '${P}' changed on the server after this page was fetched (baseline ${D}, server ${x}) \u2014 another writer edited it. A file row accepts no If-Match validator, so this push would silently overwrite that change. Re-fetch the page and re-apply the edit.`)}let w=LF(l,u,{rows:m,name:String((a=d.name)!==null&&a!==void 0?a:"")});if(qF(e,w),w.length===0)return{id:l,etag:f,memberEtags:Object.fromEntries(c.map(({row:I,etag:D})=>{var P;return[(0,be.normalizeGuid)(String((P=I[jt])!==null&&P!==void 0?P:""),jt),D]}))};let C=UF(),S=[],O=!0;kF(e,w)?await $F(e,l,w,u,C):{warnings:S,turnRecorded:O}=await xF(e,l,w,u,C);let L=await FF(e,l,w,u,h,b,S);return O?L:{...L,intentPending:!0}},async delete(e,t){var r;let n=(0,be.normalizeGuid)(t,"id"),i=await cw(e,n);await(0,Ve.deleteRecord)(e,bi,n);let o=new Set(i.map(l=>{var u;return String((u=l[Ba])!==null&&u!==void 0?u:"")}).filter(l=>l!=="")),a=!1;try{for(let l of await cw(e,n)){let u=String((r=l[Ba])!==null&&r!==void 0?r:"");u!==""&&o.add(u)}}catch{a=!0}let s=[];for(let l of o)try{await(0,Ve.deleteRecord)(e,Dc,l)}catch(u){u instanceof Qe.ConnectionError&&u.statusCode===404||s.push(l)}if(s.length>0||a)throw new Qe.SdkError("GENPAGE_HISTORY_NOT_DELETED",`Generative page '${n}' was deleted, but its conversation history was not fully removed`+(s.length>0?` \u2014 ${s.length} of ${o.size} message(s) could not be (${s.join(", ")})`:"")+(a?" \u2014 and re-reading it after the delete failed, so a late turn may remain":"")+`. They no longer belong to any page; delete them as ${Dc} rows regarding '${n}'.`)}};function UF(){return`uxagentproject_${(0,GF.newId)()}`}function Wae(e,t){var r;return t.length===0?e:{...e,warnings:[...(r=e.warnings)!==null&&r!==void 0?r:[],...t]}}function BF(e,t,r){var n,i;if(((i=(n=r.messages)===null||n===void 0?void 0:n.length)!==null&&i!==void 0?i:0)>1&&!e.supportsAtomicBatch)throw new Qe.SdkError("GENPAGE_TURN_NOT_ATOMIC",`Refusing to write generative page '${t}': its new turn has a prompt AND a reply, which must be recorded together, and the injected HttpClient does not implement postRaw() \u2014 one request at a time, a failure between the two would leave half a turn. Implement postRaw(), or record the prompt alone (omit newTurn.agentMessage). Nothing was written.`)}function qF(e,t){let r=t.filter(i=>i.kind==="content");if(r.length>0&&!e.supportsBinaryPatch&&!e.supportsAtomicBatch)throw new Qe.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: it has file content to upload, but the injected HttpClient implements neither patchRaw() nor postRaw(). A Dataverse File column is not writable through a JSON body, so proceeding would create the page and its rows and then fail, leaving a page whose source never uploaded.");if(r.some(i=>pw(i.data)===void 0)&&!e.supportsBinaryPatch)throw new Qe.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: a file's content is not UTF-8 text, which only the binary channel can carry, and the injected HttpClient does not implement patchRaw().")}});var cM=v(Tl=>{"use strict";Object.defineProperty(Tl,"__esModule",{value:!0});Tl.genPageRegistration=Tl.GenPageAdapter=void 0;var zae=HF(),jae=jr(),Ie=cn(),gm=ct(),ym=pa(),Hae=oe(),Va=Q(),iM=v0(),mw=Oh(),Wo=2e8,oM=200000001,ro={source:{name:"src/pages/page.tsx",fileType:Wo},output:{name:"src/pages/page.compiled",fileType:oM},config:{name:"config.json",fileType:Wo},prompt:{name:"firstPrompt.json",fileType:Wo}},aM=Object.keys(ro),Kae=["dataSources","model","connectorBindings","actionBindings"],Jae=["userMessage","agentMessage"],KF=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Yae={source:"6f1c2a4e9b3d47a1b85c0e2f7d914a63",output:"a8e53d17c2f64b09a1d7e4b8c3f2069d",config:"3b97f0c64e2a4d8f95b1c7a0e6d3f814",prompt:"d24e8b51f7a34c6e8b09d5f1a2c7e3b6"},Qae="9c3e7a15d2b84f6e8a01c5d7b3f9e240";function sM(e,t,r){let n=(0,Hae.normalizeGuid)(e,r).replace(/-/g,""),i=[];for(let a=0;a<32;a+=1)i.push(parseInt(n[a],16)^parseInt(t[a],16));i[12]=4,i[16]=i[16]&3|8;let o=i.map(a=>a.toString(16)).join("");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}function fm(e,t){return sM(e,Yae[t],"id")}function Xae(e,t){let r=sM(e,Qae,"newTurn.id"),n=parseInt(r.slice(24),16)%2**47+(t==="agent"?1:0);return`${r.slice(0,24)}${n.toString(16).padStart(12,"0")}`}function JF(e){return typeof e=="string"&&e.trim()!==""?e:(0,gm.newId)()}function to(e){return(0,Ie.isJsonObject)(e)?e:{}}function _l(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function pm(e){return JSON.parse(JSON.stringify(e))}function Zae(e){let t=to(e);return t.status==="available"&&typeof t.data=="string"?{status:"available",data:t.data}:{status:"unavailable",reason:t.reason==="unpublished"?"unpublished":"missing"}}function Rc(e){if(!e||e.status!=="available")return;let t=(0,ym.base64ToUtf8)(e.data);return(0,ym.utf8ToBase64)(t)===e.data?t:void 0}function lM(e,t,r){var n,i,o,a;return e.source!==void 0&&t!==void 0&&t?.source===e.source&&_l((n=t?.dataSources)!==null&&n!==void 0?n:[],(i=e.dataSources)!==null&&i!==void 0?i:[])&&((a=(o=e.bag)===null||o===void 0?void 0:o.rows)!==null&&a!==void 0?a:{}).output!==void 0&&(0,iM.isLoadableGenPageOutput)(r)}function ese(e,t){var r;try{return lM(e,t,Rc((r=e.bag)===null||r===void 0?void 0:r.output))}catch{return!1}}function mm(e){if(e!==void 0)try{let t=JSON.parse(e.replace(/^\uFEFF/,""));return(0,Ie.isJsonObject)(t)?t:void 0}catch{return}}function YF(e,t){if(t===Wo&&e.includes("page.tsx"))return"source";if(t===oM&&e.includes(".compiled"))return"output";if(t===Wo&&e===ro.config.name)return"config";if(t===Wo&&e===ro.prompt.name)return"prompt"}function QF(e){let t=e.toLowerCase();return aM.some(r=>ro[r].name.toLowerCase()===t)}function hw(e){return Object.fromEntries(e)}function uM(e,t,r,n){let i=[],o=new Set,a=new Set(t),s=l=>{if(o.has(l))return;let u=a.has(l)?e[l]:r&&Object.prototype.hasOwnProperty.call(r,l)?r[l]:void 0;u!==void 0&&(o.add(l),i.push([l,u]))};return(n??[]).forEach(s),t.forEach(s),Object.keys(r??{}).forEach(s),hw(i)}function XF(e){var t,r,n;return uM({dataSources:(t=e.dataSources)!==null&&t!==void 0?t:[],model:e.model,connectorBindings:e.connectorBindings,actionBindings:e.actionBindings},Kae,(r=e.bag)===null||r===void 0?void 0:r.config,(n=e.bag)===null||n===void 0?void 0:n.configKeys)}function ZF(e){var t,r;return uM({userMessage:e.firstPrompt,agentMessage:e.firstAgentMessage},Jae,(t=e.bag)===null||t===void 0?void 0:t.prompt,(r=e.bag)===null||r===void 0?void 0:r.promptKeys)}function eM(e,t,r){let n=[];for(let[i,o]of Object.entries(r))if(i==="dataSources"){if(!Array.isArray(o)||!o.every(a=>typeof a=="string"))return!1;e.dataSources=o}else if(i==="model"){if(typeof o!="string")return!1;e.model=o}else i==="connectorBindings"?e.connectorBindings=o:i==="actionBindings"?e.actionBindings=o:n.push([i,o]);return t.configKeys=Object.keys(r),n.length>0&&(t.config=hw(n)),!0}function tM(e,t,r){let n=[];for(let[i,o]of Object.entries(r))if(i==="userMessage"||i==="agentMessage"){if(typeof o!="string")return!1;i==="userMessage"?e.firstPrompt=o:e.firstAgentMessage=o}else n.push([i,o]);return t.promptKeys=Object.keys(r),n.length>0&&(t.prompt=hw(n)),!0}function Lc(e){var t,r;return e.source!==void 0||Object.keys((r=(t=e.bag)===null||t===void 0?void 0:t.rows)!==null&&r!==void 0?r:{}).length>0}var tse=["dataSources","model","connectorBindings","actionBindings","firstPrompt","firstAgentMessage"];function rM(e){return Lc(e)?[]:tse.filter(t=>e[t]!==void 0).map(t=>(0,Ie.issue)(`/${t}`,"genpage-raw-structured-field",`${t} cannot be applied: this page is in raw-file mode \u2014 it has no source and no managed rows, so a push writes its files[] exactly as they are, and ${t} nowhere. Set source to make the page managed (the SDK then writes config.json and firstPrompt.json from the typed fields; a file in files[] holding one of those names must be removed first), or change the file that stores the value in files[] directly.`))}function nM(){return(0,Ie.issue)("/source","genpage-source-required","the page's source cannot be removed: its source row still exists, and a page without one cannot run. Set a new source, or delete the page with deleteRemoteArtifact.")}function hm(e){return{status:"available",data:(0,ym.utf8ToBase64)(e)}}function Pc(e,t){var r,n;return{id:String((r=e.uxagentprojectid)!==null&&r!==void 0?r:""),name:String((n=e.name)!==null&&n!==void 0?n:""),files:t}}var bm=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){let r=t,n=to(r?.project),i=(Array.isArray(r?.files)?r.files:[]).map(g=>{var b,w,C;let S=to(g);return{id:String((b=S.uxagentprojectfileid)!==null&&b!==void 0?b:""),name:String((w=S.filename)!==null&&w!==void 0?w:""),fileType:Number((C=S.filetype)!==null&&C!==void 0?C:Wo),content:Zae(S.content)}}),o=Array.isArray(r?.conversation)?r.conversation.map(g=>{var b,w;let C=to(g);return{sender:Number(C.messagesender)===200000001?"agent":"user",message:String((b=C.message)!==null&&b!==void 0?b:""),createdOn:String((w=C.createdon)!==null&&w!==void 0?w:"")}}):void 0,a=g=>o?{...g,conversation:o}:g,s=new Map,l=[],u=!0;for(let g of i){let b=YF(g.name,g.fileType);b?((s.has(b)||g.name!==ro[b].name)&&(u=!1),s.set(b,g)):(QF(g.name)&&(u=!1),l.push(g))}if(!u||s.size===0)return a(Pc(n,i));let c=Pc(n,l),d={rows:{}};for(let[g,b]of s)d.rows[g]=b.id;let f=s.get("source");if(f){let g=Rc(f.content);if(g===void 0)return a(Pc(n,i));c.source=g}let m=s.get("output");m&&(d.output=m.content);let p=s.get("config");if(p){let g=mm(Rc(p.content));if(!g||!eM(c,d,g))return a(Pc(n,i))}let h=s.get("prompt");if(h){let g=mm(Rc(h.content));if(!g||!tM(c,d,g))return a(Pc(n,i))}return c.bag=d,a(c)}async toApiPayload(t,r,n){var i,o,a,s,l,u,c,d,f,m,p,h,g;if(r&&!_l((i=t.conversation)!==null&&i!==void 0?i:[],(o=r.conversation)!==null&&o!==void 0?o:[]))throw new Va.ValidationError("genPage",t.id,[(0,Ie.issue)("/conversation","genpage-conversation-read-only","conversation is the page's recorded history and cannot be edited. Record a new turn with newTurn; revert the edit to conversation before pushing.")]);let b=rM(t);if(b.length>0)throw new Va.ValidationError("genPage",t.id,b);let w=[],C=r===void 0,S=C&&t.firstPrompt===void 0&&t.newTurn?{...t,firstPrompt:t.newTurn.prompt,...t.newTurn.agentMessage!==void 0?{firstAgentMessage:t.newTurn.agentMessage}:{}}:t;if(Lc(S)){let I=(s=(a=S.bag)===null||a===void 0?void 0:a.rows)!==null&&s!==void 0?s:{},D=Ge=>{var Ut;return(Ut=I[Ge])!==null&&Ut!==void 0?Ut:fm(S.id,Ge)},P=(Ge,Ut,de)=>{w.push({id:D(Ge),name:ro[Ge].name,fileType:ro[Ge].fileType,content:Ut,unchanged:de})};if(S.source!==void 0){P("source",hm(S.source),!C&&r?.source===S.source&&I.source!==void 0);let Ge=Rc((l=S.bag)===null||l===void 0?void 0:l.output);lM(S,r,Ge)?P("output",{status:"retain"},!0):P("output",hm(await this.compile(S,S.source,n)),!1)}else{if(I.source!==void 0)throw new Va.ValidationError("genPage",S.id,[nM()]);if(I.output!==void 0){if(!C&&!_l((u=r?.dataSources)!==null&&u!==void 0?u:[],(c=S.dataSources)!==null&&c!==void 0?c:[]))throw new Va.ValidationError("genPage",S.id,[(0,Ie.issue)("/dataSources","genpage-source-required","the page has no source row, so its output cannot be recompiled for new data sources; set a source to change them.")]);P("output",{status:"retain"},!0)}}let x=XF(S),K=!C&&r!==void 0&&_l(XF(r),x);(C||I.config!==void 0||!K)&&P("config",hm(JSON.stringify(x)),K&&I.config!==void 0);let Le=ZF(S),lr=!C&&r!==void 0&&_l(ZF(r),Le);(I.prompt!==void 0||Object.keys(Le).length>0&&!lr)&&P("prompt",hm(JSON.stringify(Le)),lr&&I.prompt!==void 0)}for(let I of(d=S.files)!==null&&d!==void 0?d:[]){let D=(f=r?.files)===null||f===void 0?void 0:f.find(P=>P.id===I.id);w.push({id:I.id,name:I.name,fileType:I.fileType,content:I.content,unchanged:D!==void 0&&_l(D,I)})}let O=[];if(S.newTurn){let I=S.newTurn.id,D=P=>I?{id:Xae(I,P)}:{};O.push({...D("user"),sender:"user",message:S.newTurn.prompt}),S.newTurn.agentMessage&&O.push({...D("agent"),sender:"agent",message:S.newTurn.agentMessage})}let L=(p=(m=S.bag)===null||m===void 0?void 0:m.config)!==null&&p!==void 0?p:{};return{name:S.name,files:w,...O.length>0?{messages:O,messageContext:{dataSources:(h=S.dataSources)!==null&&h!==void 0?h:[],model:(g=S.model)!==null&&g!==void 0?g:"",enabledTools:Array.isArray(L.enabledTools)?L.enabledTools:[],configurableTools:Array.isArray(L.configurableTools)?L.configurableTools:[]}}:{}}}committed(t,r,n={intentPending:!1}){let i=this.serverState(t,r);return n.intentPending&&t.newTurn!==void 0?{artifact:{...i,newTurn:pm(t.newTurn)},baseline:i}:{artifact:i,baseline:i}}serverState(t,r){var n,i,o,a,s,l;if(!Lc(t)&&!t.newTurn)return t;let u=pm(t);if(delete u.newTurn,!Lc(t))return u;let c={...(n=u.bag)!==null&&n!==void 0?n:{},rows:{...(o=(i=u.bag)===null||i===void 0?void 0:i.rows)!==null&&o!==void 0?o:{}}};for(let d of(a=r.files)!==null&&a!==void 0?a:[]){let f=aM.find(p=>ro[p].name===d.name&&ro[p].fileType===d.fileType);if(!f||u.files.some(p=>p.id===d.id)||(c.rows[f]=d.id,d.content.status!=="available"))continue;let m=(0,ym.base64ToUtf8)(d.content.data);f==="output"?c.output={status:"available",data:d.content.data}:f==="config"?(delete c.config,delete u.dataSources,delete u.model,delete u.connectorBindings,delete u.actionBindings,eM(u,c,(s=mm(m))!==null&&s!==void 0?s:{})):f==="prompt"&&(delete c.prompt,delete u.firstPrompt,delete u.firstAgentMessage,tM(u,c,(l=mm(m))!==null&&l!==void 0?l:{}))}return u.bag=c,u}baselineContent(t){var r;let n={...t};return delete n.conversation,delete n.newTurn,n.files=[...(r=t.files)!==null&&r!==void 0?r:[]].sort((i,o)=>i.id<o.id?-1:i.id>o.id?1:0),n}normalize(t){let r=t.newTurn;return!(0,Ie.isJsonObject)(r)||typeof r.id=="string"&&KF.test(r.id)?t:{...t,newTurn:{...r,id:(0,gm.newId)()}}}async compile(t,r,n){var i;let o=(i=t.dataSources)!==null&&i!==void 0?i:[],a=[],s=[];if(o.forEach((f,m)=>{var p;let h=(p=n?.resolveEntity)===null||p===void 0?void 0:p.call(n,f);h&&h.columnDetailComplete===!0?a.push(h):s.push((0,Ie.issue)(`/dataSources/${m}`,h?"genpage-data-source-incomplete":"genpage-data-source-unresolved",h?`the column metadata of data source '${f}' could not be read completely (a choice or lookup read failed, or returned options with no label), so the page cannot be compiled with its enums. Retry the push.`:`the metadata of data source '${f}' could not be read, so the page cannot be compiled with its enums. Check the table's logical name and that it exists in this environment.`))}),s.length>0)throw new Va.ValidationError("genPage",t.id,s);if(!n?.loadTypeScript)throw new Va.ValidationError("genPage",t.id,[(0,Ie.issue)("/source","genpage-compiler-unavailable","no TypeScript compiler is available to compile the page")]);let l=await n.loadTypeScript(),u=a.length>0?(0,mw.buildGenPageRuntimeTypes)(a):void 0,c=a.length>0?(0,mw.buildGenPageLegacyEnums)(a):void 0,d=(0,iM.compileGenPage)(l,r,u,c);if(d.diagnostics.length>0)throw new Va.ValidationError("genPage",t.id,d.diagnostics.map(rse));return d.code}metadataNeeds(t,r){if(t.source===void 0||!Array.isArray(t.dataSources))return[];let n=ese(t,r)?{fetchRequired:!1}:{};return t.dataSources.filter(i=>typeof i=="string"&&i!=="").map(i=>({entityLogicalName:i,fieldName:"",needsColumnDetail:!0,...n}))}createDefault(t){var r,n;let i=JF(t.id),o={id:i,name:(r=t.name)!==null&&r!==void 0?r:"New page",files:((n=t.files)!==null&&n!==void 0?n:[]).map(a=>{var s,l,u;return{id:JF(a.id),name:(s=a.name)!==null&&s!==void 0?s:"index.tsx",fileType:(l=a.fileType)!==null&&l!==void 0?l:Wo,content:(u=a.content)!==null&&u!==void 0?u:{status:"available",data:""}}})};t.source!==void 0&&(o.source=t.source),t.dataSources!==void 0&&(o.dataSources=[...t.dataSources]);for(let a of["model","firstPrompt","firstAgentMessage"])t[a]!==void 0&&(o[a]=t[a]);return t.newTurn!==void 0&&(o.newTurn={...t.newTurn}),t.connectorBindings!==void 0&&(o.connectorBindings=pm(t.connectorBindings)),t.actionBindings!==void 0&&(o.actionBindings=pm(t.actionBindings)),o.source!==void 0&&(o.bag={rows:{source:fm(i,"source"),output:fm(i,"output"),config:fm(i,"config")}}),o}assignMissingIds(t){if(t==null)return{id:(0,gm.newId)()};if(!(0,Ie.isJsonObject)(t))return t;let r=t;return(Object.keys(r).length===0||"id"in r||"content"in r||"fileType"in r||Array.isArray(r.files))&&(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,gm.newId)()),r}validate(t){let r=[],n=t;for(let s of["source","model","firstPrompt","firstAgentMessage"])n[s]!==void 0&&typeof n[s]!="string"&&r.push((0,Ie.issue)(`/${s}`,"genpage-field-type",`${s} must be a string, got ${typeof n[s]}`));if(n.source===void 0&&to(to(n.bag).rows).source!==void 0&&r.push(nM()),r.push(...rM(t)),n.newTurn!==void 0){let s=to(n.newTurn);(!(0,Ie.isJsonObject)(n.newTurn)||typeof s.prompt!="string"||s.prompt.trim()==="")&&r.push((0,Ie.issue)("/newTurn/prompt","genpage-turn-prompt","newTurn needs a non-empty prompt")),s.agentMessage!==void 0&&typeof s.agentMessage!="string"&&r.push((0,Ie.issue)("/newTurn/agentMessage","genpage-field-type","newTurn.agentMessage must be a string")),s.id!==void 0&&(typeof s.id!="string"||!KF.test(s.id))&&r.push((0,Ie.issue)("/newTurn/id","genpage-turn-id","newTurn.id is the turn's identity, which the SDK mints \u2014 remove it, or keep the GUID it minted"))}if(n.dataSources!==void 0)if(!Array.isArray(n.dataSources))r.push((0,Ie.issue)("/dataSources","genpage-data-sources-array","dataSources must be an array of table logical names"));else{let s=new Set;n.dataSources.forEach((l,u)=>{typeof l!="string"||!mw.TABLE_LOGICAL_NAME.test(l)?r.push((0,Ie.issue)(`/dataSources/${u}`,"genpage-data-source-name",`a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(l)}'`)):s.has(l)?r.push((0,Ie.issue)(`/dataSources/${u}`,"genpage-data-source-duplicate",`data source '${l}' is listed twice`)):s.add(l)})}n.conversation!==void 0&&!Array.isArray(n.conversation)&&r.push((0,Ie.issue)("/conversation","genpage-conversation-array","conversation must be an array"));let i=n.files;if(i!==void 0&&!Array.isArray(i))return r.push((0,Ie.issue)("/files","files-must-be-array",`files must be an array, got ${typeof i}`)),r;let o=Lc(t),a=new Map;return(Array.isArray(i)?i:[]).forEach((s,l)=>{let u=`/files/${l}`,c=to(s),d=typeof c.id=="string"?c.id.trim().toLowerCase():"";if(d==="")r.push((0,Ie.issue)(u,"file-id-required","a generative-page file needs an id"));else{let g=a.get(d);g!==void 0?r.push((0,Ie.issue)(u,"file-id-duplicate",`two files share the id '${c.id}' (also at /files/${g}); a file's id is its identity, so a duplicate makes an edit ambiguous`)):a.set(d,l)}let f=typeof c.name=="string"?c.name:"",m=f.split("/");f===""||/[\u0000-\u001F\u007F]/.test(f)||f.includes("\\")||m.some(g=>g===""||g==="."||g==="..")?r.push((0,Ie.issue)(u+"/name","file-name-invalid",`a file name must be a relative path of non-empty '/'-separated segments (no '.', '..', backslash or control character \u2014 its last segment is sent as an HTTP header); got '${f}'`)):o&&(QF(f)||YF(f,Number(c.fileType))!==void 0)&&r.push((0,Ie.issue)(u+"/name","file-name-reserved",`'${f}' would be read by the maker portal as one of the page's managed rows (its source, output, config or first prompt), which the SDK writes from source and the configuration fields; it cannot also be a file in files[]`));let p=c.content;if(p===void 0){r.push((0,Ie.issue)(u+"/content","file-content-required","content is required: omitting it is indistinguishable from an empty file, and the two have opposite effects on the next push"));return}let h=to(p);h.status==="available"?typeof h.data!="string"&&r.push((0,Ie.issue)(u+"/content/data","file-content-data-invalid","available content needs base64 `data`")):h.status!=="unavailable"&&r.push((0,Ie.issue)(u+"/content/status","file-content-status-invalid",`content.status must be 'available' or 'unavailable', got ${String(h.status)}`))}),r}};Tl.GenPageAdapter=bm;function rse(e){let t=`line ${e.line}, column ${e.column}`;return e.rule==="genpage-source-syntax"?(0,Ie.issue)("/source",e.rule,`${t}: ${e.message} (TS${e.code}) \u2014 the page cannot run, so it was not pushed`):(0,Ie.issue)("/source",e.rule,`${t}: ${e.message}`)}function nse(){return{adapter:new bm,api:zae.genPageApi,publish:(e,t)=>(0,jae.publishGenPageById)(e,t),publishScope:e=>({envelope:"uxagentproject",targetIds:[e]}),rebaselineAfterPublish:"snapshot"}}Tl.genPageRegistration=nse});var fM=v(wm=>{"use strict";Object.defineProperty(wm,"__esModule",{value:!0});wm.reconcileBpfSecurityRoles=void 0;var dM=Tt(),yw=Q(),vm=fe(),kc=oe(),ise="Global",gw={create:"Create",read:"Read",write:"Write",delete:"Delete"};async function ose(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,kc.odataPathLiteral)(t)}')?$select=LogicalName,Privileges`,i=(0,vm.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.Privileges;if(!Array.isArray(o))throw new yw.ConnectionError(e.apiUrl(n),i.status,`reading the privileges of business process flow table '${t}' returned no 'Privileges' array (got ${(0,dM.describeMalformedValue)(o)}), so which access it can grant is unknown.`);let a=o,s={},l=new Set;return Object.keys(gw).forEach(u=>{let c=a.find(d=>d.PrivilegeType===gw[u]);if(c){let d=(0,kc.normalizeGuid)(c.PrivilegeId,"PrivilegeId");s[u]=d,l.add(d)}}),{byAccess:s,all:l}}async function ase(e,t){var r;let n=`/RetrieveRolePrivilegesRole(RoleId=${t})`,i=(0,vm.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.RolePrivileges;if(!Array.isArray(o))throw new yw.ConnectionError(e.apiUrl(n),i.status,`reading the privileges of role '${t}' returned no 'RolePrivileges' array (got ${(0,dM.describeMalformedValue)(o)}), so what it holds is unknown.`);return new Set(o.map(a=>(0,kc.normalizeGuid)(a.PrivilegeId,"PrivilegeId")))}async function sse(e,t,r){if(r.length===0)return;let n={Privileges:r.map(o=>({Depth:ise,PrivilegeId:o}))},i=`/roles(${t})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;(0,vm.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function lse(e,t,r){let n={Privilege:{"@odata.type":"Microsoft.Dynamics.CRM.privilege",privilegeid:r}},i=`/roles(${t})/Microsoft.Dynamics.CRM.RemovePrivilegeRole`;(0,vm.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function use(e,t,r){var n,i,o;if(!r||r.length===0)return;let a=await ose(e,t.toLowerCase());for(let s of r){let l=(0,kc.normalizeGuid)(s.roleId,"roleId"),u=((n=s.access)!==null&&n!==void 0?n:[]).find(c=>!a.byAccess[c]);if(u!==void 0)throw new yw.InvalidArgumentError(`Cannot grant '${u}' access to role '${l}' on business process flow table '${t.toLowerCase()}': its metadata lists no '${(i=gw[u])!==null&&i!==void 0?i:u}' privilege. No security role was changed.`)}for(let s of r){let l=(0,kc.normalizeGuid)(s.roleId,"roleId"),u=new Set(((o=s.access)!==null&&o!==void 0?o:[]).map(p=>a.byAccess[p]).filter(p=>!!p)),c=await ase(e,l),d=new Set([...c].filter(p=>a.all.has(p))),f=[...u].filter(p=>!d.has(p)),m=[...d].filter(p=>!u.has(p));await sse(e,l,f);for(let p of m)await lse(e,l,p)}}wm.reconcileBpfSecurityRoles=use});var NM=v(Em=>{"use strict";Object.defineProperty(Em,"__esModule",{value:!0});Em.bpfApi=void 0;var vr=lo(),pM=Es(),cse=Tt(),Xe=Q(),ht=fe(),An=oe(),dse=fM(),fse=lh(),$c=ch(),pse={"Content-Type":"application/json",Accept:"application/json"},vw={...pse,Prefer:"return=representation"},mse=`category eq ${vr.WorkflowCategory.BusinessProcessFlow} and type eq ${vr.WorkflowTypeCode.Definition} and businessprocesstype eq ${vr.BusinessProcessType.BusinessFlow}`,hse="workflowid,name,description,primaryentity,statecode,category,type,businessprocesstype,processorder",gse="workflowid,name,uniquename,description,primaryentity,statecode,statuscode,category,type,businessprocesstype,processorder,xaml,clientdata",yse=["xaml","name","description","processorder"];async function bw(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,dse.reconcileBpfSecurityRoles)(e,n,t.securityRoles)}async function Cw(e,t,r){let n={statecode:vr.StateCode.Activated,statuscode:vr.StatusCode.Activated},i=`/workflows(${t})`,{response:o,resent:a}=await SM(e,i,n,r,null);try{return(0,ht.ensureSuccess)(o,e.apiUrl(i))}catch(s){throw a?EM(s):s}}var CM=new WeakSet;function EM(e){return typeof e=="object"&&e!==null&&CM.add(e),e}function AM(e){return typeof e=="object"&&e!==null&&CM.has(e)}function mM(e){return e instanceof Xe.ConnectionError&&(e.statusCode===0||ht.AMBIGUOUS_WRITE_STATUSES.has(e.statusCode))}async function SM(e,t,r,n,i){let o=n??i,a=0;try{return{response:await(0,ht.resendWhile)(ht.isConcurrencyLockRefusal,()=>{a+=1;let l=a===1?n:o,u={...vw};return l&&(u["If-Match"]=l),e.patch(t,r,{headers:u})},o?ht.LOCK_BACKOFF_MS:[]),resent:a>1}}catch(s){throw a>1?EM(s):s}}async function hM(e,t,r){return(0,ht.readEtag)(await Cw(e,t,r))}function gM(e,t){return new Xe.SdkError("BPF_WRITE_NOT_ECHOED",`The ${t} of business process flow '${e}' was applied, but the server returned no concurrency token for it (this environment did not honour 'Prefer: return=representation'), so the next step could not be conditioned on a token this push produced and was NOT sent. `+Cm(e))}async function xc(e,t){var r;let n=`/workflows(${t})${(0,An.odataQuery)([["$select","statecode"]])}`,i=(0,ht.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.statecode,a=Number(o);if(o==null||o===""||!Number.isFinite(a))throw new Xe.SdkError("BPF_STATE_UNREADABLE",`Reading the state of business process flow '${t}' answered HTTP ${i.status} without a usable statecode, so whether it is Active cannot be decided.`);return a}async function ww(e,t,r,n,i=null){if((n??await xc(e,t))!==vr.StateCode.Activated)return{deactivated:!1,etag:null};let o={statecode:vr.StateCode.Draft,statuscode:vr.StatusCode.Draft},a=`/workflows(${t})`,s,l;try{({response:s,resent:l}=await SM(e,a,o,r,i))}catch(c){return await yM(e,t,c,AM(c))}if(ht.AMBIGUOUS_WRITE_STATUSES.has(s.status))return await yM(e,t,new Xe.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",`Deactivating business process flow '${t}' answered HTTP ${s.status} from an intermediary, so whether it committed is unknown.`),l);let u=(0,ht.ensureSuccess)(s,e.apiUrl(a));return{deactivated:!0,etag:(0,ht.readEtag)(u)}}async function yM(e,t,r,n){let i;try{i=await xc(e,t)}catch{i=void 0}if(i===vr.StateCode.Draft&&!n)return{deactivated:!0,etag:null,uncertainCause:r};if(i===vr.StateCode.Activated)throw r;let o=new Xe.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",i===vr.StateCode.Draft?`Deactivating business process flow '${t}' waited for the platform's concurrency lock, and its last attempt ended without a definitive answer. The process now reads Draft, but whether this deactivate or another writer's change put it there is unknown \u2014 the row may even have been replaced at the same id \u2014 so nothing more was sent: no edit, no re-activation, no delete. It MAY be left DISABLED: read it before retrying. Original failure: ${r instanceof Error?r.message:String(r)}`:`Deactivating business process flow '${t}' did not complete, and its state could not be re-read \u2014 it MAY be left DISABLED and needs reconciling. Original failure: ${r instanceof Error?r.message:String(r)}`);throw(0,Xe.attachCause)(o,r),o}async function bse(e,t){let r=(0,An.normalizeGuid)(t,"workflowid");try{return await Cw(e,r,null),"restored"}catch{return Ew(e,r)}}async function vse(e,t,r){let n=(0,An.normalizeGuid)(t,"workflowid");try{return await Cw(e,n,r),"restored"}catch(i){return i instanceof Xe.SdkError&&i.code===ht.VERSION_CONFLICT_CODE?"changed":Ew(e,n)}}async function Ew(e,t){try{let r=await xc(e,t);return r===vr.StateCode.Activated?"restored":r===vr.StateCode.Draft?"disabled":"unknown"}catch{return"unknown"}}async function bM(e,t,r,n){return r?{outcome:await vse(e,t,r),attempted:!0}:n?{outcome:await Ew(e,(0,An.normalizeGuid)(t,"workflowid")),attempted:!1}:{outcome:await bse(e,t),attempted:!0}}function wse(e,t){let r=new Xe.SdkError($c.WORKFLOW_DELETE_UNSETTLED_CODE,`Deleting business process flow '${e}' failed${(0,$c.failedAfterResend)(t)?" after it was re-sent":""}, and re-activating the process this delete had deactivated was refused (HTTP 412): the row at that id is no longer the version this delete deactivated \u2014 it was edited, or deleted and re-created at the same id \u2014 so it was NOT re-activated, and it MAY be left DISABLED. Read the row before deleting it again. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Xe.attachCause)(r,t),r}function vM(e,t,r,n,i=!0){let o=`Original failure: ${n instanceof Error?n.message:String(n)}`,a="it was NOT re-activated: it waited for the platform's concurrency lock, and no write of this operation proves the row is still its own, so a re-activation could have enabled another writer's edit",s;return r==="changed"?s=new Xe.SdkError("BPF_REACTIVATE_OUTCOME_UNKNOWN",`Business process flow '${e}' was deactivated ${t}, and re-activating it was refused (HTTP 412): the row is no longer the version this operation last wrote \u2014 another writer changed it, or replaced it at the same id \u2014 so it was NOT re-activated, and it MAY be left DISABLED. Read it before retrying. ${o}`):r==="disabled"?s=new Xe.SdkError("BPF_LEFT_DEACTIVATED",i?`Business process flow '${e}' was deactivated ${t}, and it could NOT be reactivated \u2014 it is left DISABLED. ${o}`:`Business process flow '${e}' was deactivated ${t}, and ${a} \u2014 it is left DISABLED. ${o}`):s=new Xe.SdkError("BPF_REACTIVATE_OUTCOME_UNKNOWN",i?`Business process flow '${e}' was deactivated ${t}, and whether it was reactivated could not be confirmed \u2014 it MAY be left DISABLED and needs checking. ${o}`:`Business process flow '${e}' was deactivated ${t}, and ${a}; its state could not be read \u2014 it MAY be left DISABLED and needs checking. ${o}`),(0,Xe.attachCause)(s,n),s}async function Cse(e,t){try{return await xc(e,t),"survived"}catch(r){return r instanceof Xe.ConnectionError&&r.statusCode===404?"removed":"unknown"}}async function Ese(e,t,r){if(r)try{let{deactivated:n,etag:i}=await ww(e,t,r),o=n?i:r;if(o)return await(0,$c.deleteWorkflowResending)(e,t,{bindingToken:o,kindName:"business process flow",resendDeadlockVictim:!0,ifMatchOnFirst:!0}),"removed"}catch{}return Cse(e,t)}function Cm(e){return`Adopt the server's copy with fetchArtifact('bpf', '${e}', { overwrite: true }) \u2014 it REPLACES the local copy, so keep any outstanding local changes aside first \u2014 then re-apply them and push.`}function wM(e,t){return new Xe.SdkError("BPF_CREATE_NO_TOKEN",`Created business process flow '${e}' but the server returned no concurrency token for it (this environment did not honour 'Prefer: return=representation'), so the next push would have nothing to condition on. ${t} It was NOT rolled back: deleting it without a token could remove an edit made since. ${Cm(e)}`)}function Ase(e,t){let r=new Xe.SdkError("BPF_CREATE_NOT_ROLLED_BACK",`Creating business process flow '${e}' failed part-way, and the rollback could NOT remove it \u2014 it still EXISTS, possibly Active and half-configured. (The rollback deletes only on a token this create produced, so a row somebody has since edited is left in place on purpose; a delete the platform refused or failed leaves it too.) ${Cm(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Xe.attachCause)(r,t),r}function Sse(e,t){let r=new Xe.SdkError("BPF_CREATE_ROLLBACK_OUTCOME_UNKNOWN",`Creating business process flow '${e}' failed part-way, and whether its rollback removed the process could not be confirmed \u2014 it MAY still exist, possibly Active and half-configured. ${Cm(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Xe.attachCause)(r,t),r}function Nse(e,t){let r=new Xe.SdkError("BPF_CREATE_REMOVED_AFTER_CONFLICT",`Creating business process flow '${e}' was interrupted: another writer changed it right after it was created, so this push's next step was refused rather than overwrite or activate their edit \u2014 and the process has since been removed. Nothing is left behind and there is nothing to fetch. If the removal was deliberate, stop here; otherwise push again to re-create it at the same id. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Xe.attachCause)(r,t),r}function Aw(e){let t={};for(let r of yse)e[r]!==void 0&&(t[r]=e[r]);return t}var _se=["name,processorder","description,name,processorder"];function Tse(e){let{xaml:t,...r}=Aw(e);return typeof t=="string"&&_se.includes(Object.keys(r).sort().join(","))}async function Dse(e,t,r,n){let{xaml:i,...o}=Aw(r),[,a]=await(0,pM.sendChangeSet)(e,[{method:"PATCH",path:`/workflows(${t})`,body:o,etag:n},{method:"PATCH",path:`/workflows(${t})${(0,An.odataQuery)([["$select","workflowid"]])}`,body:{xaml:i},headers:{Prefer:"return=representation"}}],`business process flow '${t}'`);return(0,ht.readEtag)((0,pM.partResponse)(a))}Em.bpfApi={async get(e,t){let n=`/workflows(${(0,An.normalizeGuid)(t,"id")})${(0,An.odataQuery)([["$select",gse]])}`,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=[mse];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,An.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,An.odataQuery)([["$select",hse],["$filter",r.join(" and ")]])}`;return(await(0,cse.collectPages)(e,n,"listArtifacts('bpf')")).map(o=>{var a,s;return{type:"bpf",id:(a=o.workflowid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",entityLogicalName:o.primaryentity,isDirty:!1}})},async create(e,t){let r=t,n=(0,An.normalizeGuid)(r.record.workflowid,"workflowid"),i="/workflows",o=(0,ht.ensureSuccess)(await e.post(i,r.record,{headers:vw}),e.apiUrl(i)),a=(0,ht.readEtag)(o);if(!a)throw wM(n,r.status==="Active"?"The process EXISTS as Draft and was NOT activated \u2014 an activation that cannot be conditioned on our own write could activate somebody else's edit.":"The process EXISTS as Draft.");let s=a;try{r.status==="Active"&&(s=await hM(e,n,a)),await bw(e,r)}catch(l){let u=await Ese(e,n,s);throw u==="survived"?Ase(n,l):u==="unknown"?Sse(n,l):l instanceof Xe.SdkError&&l.code===ht.VERSION_CONFLICT_CODE?Nse(n,l):l}if(!s)throw wM(n,"The process EXISTS and IS Active, but its activation returned no token.");return{id:n,etag:s}},async update(e,t,r,n){let i=r,o=(0,An.normalizeGuid)(t,"id"),a=(0,ht.requireEtag)(n,"bpf",o),s=await xc(e,o);if(s===vr.StateCode.Activated&&i.status==="Active"&&e.supportsAtomicBatch&&Tse(i.record)){let m=await Dse(e,o,i.record,a);return await bw(e,i),{id:o,etag:m}}let{deactivated:l,etag:u,uncertainCause:c}=await ww(e,o,a,s),d=u,f=!1;try{if(c!==void 0)throw c;let m=a;if(l){if(!u)throw gM(o,"deactivation");m=u}let p=`/workflows(${o})`,h;try{h=(0,ht.ensureSuccess)(await e.patch(p,Aw(i.record),{headers:{...vw,"If-Match":m}}),e.apiUrl(p))}catch(b){throw mM(b)&&(d=null),b}let g=(0,ht.readEtag)(h);if(d=g,i.status==="Active"){if(!g)throw gM(o,"definition write");try{g=await hM(e,o,g)}catch(b){throw mM(b)&&(d=null),b}f=!0}return await bw(e,i),{id:o,etag:g}}catch(m){if(l&&!f){let{outcome:p,attempted:h}=await bM(e,o,d,AM(m));if(p!=="restored")throw vM(o,"to apply an edit, the edit failed",p,m,h)}throw m}},async delete(e,t){let r=(0,An.normalizeGuid)(t,"id"),n=await(0,fse.assertWorkflowKind)(e,r,vr.WorkflowCategory.BusinessProcessFlow),{deactivated:i,etag:o}=await ww(e,r,null,void 0,n);try{await(0,$c.deleteWorkflowResending)(e,r,{bindingToken:i?o:n,kindName:"business process flow",deactivated:i,resendDeadlockVictim:!0})}catch(a){if(i&&!(0,$c.isWorkflowDeleteUnsettled)(a)){let{outcome:s,attempted:l}=await bM(e,r,o,!1);if(s==="changed")throw wse(r,a);if(s!=="restored")throw vM(r,"so it could be deleted, the delete failed",s,a,l)}throw a}}}});var lU=v(Il=>{"use strict";Object.defineProperty(Il,"__esModule",{value:!0});Il.bpfRegistration=Il.BpfAdapter=void 0;var Am=lo(),Ise=NM(),Sw=wo(),Ga=Eo(),MM=Co(),tn=cn(),Gr=ct(),Wn=Q(),Ose=100,Nw='<?xml version="1.0" encoding="utf-16"?>',_M=1033,UM="mxswa:Workflow",Pse="mxswa:ActivityReference.Properties",Rse="mcwo:StepLabel",Lse="mcwb:Control",TM="mcwb:Control.ControlDisplayName",BM="mcwb:Control.DataFieldName",qM="DataFieldName",DM="ControlDisplayName",VM="Literal",Nm="x:Null",IM="x:String",_w="x:Key",Tw="DisplayName",Tm="Activities",kse="StepLabels",GM="StageId",WM="StageCategory",zM="NextStageId",jM="ProcessStepId",Sm="IsProcessRequired",HM="EntityComposite",KM="StageComposite",JM="StepComposite";function Fc(e){return(0,tn.isJsonObject)(e)?e:{}}function wi(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 Wa(e,t){var r;return(r=wi(e).find(n=>n.tagName===t))!==null&&r!==void 0?r:null}function Ei(e){return Wa(e,Pse)}function wr(e,t){var r;return(r=wi(e).find(n=>n.getAttribute(_w)===t))!==null&&r!==void 0?r:null}function Dl(e,t){var r;return((r=e.getAttribute("AssemblyQualifiedName"))!==null&&r!==void 0?r:"").includes(t)}function Ci(e){var t;return!e||!e.firstChild?"":(t=e.firstChild.nodeValue)!==null&&t!==void 0?t:""}function YM(e,t,r){e.firstChild?e.firstChild.nodeValue=r:e.appendChild(t.createTextNode(r))}function Mc(e){var t;let r=(t=e.getAttribute(Tw))!==null&&t!==void 0?t:"",n=r.indexOf(": ");return n>=0?r.slice(n+2):r}function QM(e,t){var r;let n=(r=e.getAttribute(Tw))!==null&&r!==void 0?r:"",i=n.indexOf(": ");e.setAttribute(Tw,i>=0?n.slice(0,i+2)+t:t)}function XM(e,t){let r=wr(e,kse),n=Wa(r,Rse);n&&n.setAttribute("Description",t)}function $se(e){let t=wr(e,WM);if(!t||t.tagName===Nm)return;let r=Ci(t).trim();return r===""?void 0:Number(r)}function xse(e){let t=wr(e,zM);if(!t||t.tagName===Nm)return;let r=Ci(t).trim();return r===""?void 0:r}function ZM(e){let t=eU(e);if(!t)return;let r=rU(t,qM,BM);return r===""?void 0:r}function Dw(e,t){let r=wi(e);for(;r.length>0;){let n=r.pop();if(n.tagName===t)return n;for(let i of wi(n))r.push(i)}return null}function eU(e){let t=wr(Ei(e),Tm);return t?Dw(t,Lse):null}function tU(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 rU(e,t,r){var n;return tU(e,t)?(n=e.getAttribute(t))!==null&&n!==void 0?n:"":qse(e,r)}function OM(e,t,r,n){if(tU(e,t)){e.setAttribute(t,n);return}if(Wa(e,r)){Fse(e,r,n);return}throw new Wn.InvalidArgumentError(`BPF step control exposes neither a '${t}' attribute nor a <${r}> wrapper to bind a column`)}function Fse(e,t,r){let n=Wa(e,t),i=n?Dw(n,VM):null;if(!i)throw new Wn.InvalidArgumentError(`BPF step control's <${t}> wrapper holds no <Literal> to bind a column`);i.setAttribute("Value",r)}function nU(e){return Mc(e)}function Dm(e){let t=Wa(e,UM),r=[];for(let n of wi(t).filter(i=>Dl(i,HM))){let i=wr(Ei(n),Tm);for(let o of wi(i).filter(a=>Dl(a,KM)))r.push({el:o,entity:nU(n)})}return r}function Iw(e){let t=wr(Ei(e),Tm);return wi(t).filter(r=>Dl(r,JM))}function Mse(e){let t=Ei(e),r=Ci(wr(t,Sm)).trim().toLowerCase(),n=ZM(e),i={id:Ci(wr(t,jM)),name:Mc(e)};return n!==void 0&&(i.fieldName=n),r==="true"&&(i.required=!0),i}function Use(e,t){let r=Ei(e),n=$se(r),i=xse(r),o={id:Ci(wr(r,GM)),name:Mc(e),entityLogicalName:t,steps:Iw(e).map(Mse)};return n!==void 0&&(o.category=n),i!==void 0&&(o.nextStageId=i),o}function Bse(e){return Dm(e).map(({el:t,entity:r})=>Use(t,r))}function vi(e){return new Wn.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 qse(e,t){var r;let n=Wa(e,t),i=n?Dw(n,VM):null;return(r=i?.getAttribute("Value"))!==null&&r!==void 0?r:""}function Ow(e,t){var r;let n=e.createElement(t.tagName),i=t.attributes;for(let a=0;a<i.length;a+=1)n.setAttribute(i[a].name,i[a].value);let o=t.childNodes;for(let a=0;a<o.length;a+=1){let s=o[a];s.nodeType===1?n.appendChild(Ow(e,s)):s.nodeType===3&&n.appendChild(e.createTextNode((r=s.nodeValue)!==null&&r!==void 0?r:""))}return n}function iU(e){return wr(Ei(e),Tm)}function Vse(e,t,r){var n;let i=t.entityLogicalName&&t.entityLogicalName.trim()!==""?t.entityLogicalName:r,o=!((n=t.steps[0])===null||n===void 0)&&n.id&&t.steps[0].id.trim()!==""?t.steps[0].id:(0,Gr.newId)(),{body:a}=Im(Pw(i,(0,Gr.newId)(),t.id,o));return Ow(e,Dm((0,Ga.parseXmlRoot)(a,"<Activity/>"))[0].el)}function Gse(e,t){let{body:r}=Im(Pw("account",(0,Gr.newId)(),(0,Gr.newId)(),t.id));return Ow(e,Iw(Dm((0,Ga.parseXmlRoot)(r,"<Activity/>"))[0].el)[0])}function oU(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);for(let r of t)e.appendChild(r)}function aU(e,t,r,n){let i=wr(e,r);if(!i||!i.parentNode){if(n!==void 0&&n!=="")throw vi(`setting '${r}' on a stage whose xaml does not expose that slot`);return}let o=i.parentNode;if(n===void 0||n===""){if(i.tagName!==Nm&&Ci(i).trim()!==""){let s=t.createElement(Nm);s.setAttribute(_w,r),o.replaceChild(s,i)}return}if(i.tagName===IM){Ci(i).trim()!==n&&YM(i,t,n);return}let a=t.createElement(IM);a.setAttribute(_w,r),a.appendChild(t.createTextNode(n)),o.replaceChild(a,i)}function Wse(e,t,r){aU(e,t,WM,r===void 0?void 0:String(r))}function zse(e,t,r){aU(e,t,zM,r)}function sU(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 PM(e){return Ci(wr(Ei(e),GM))}function RM(e){return Ci(wr(Ei(e),jM))}function LM(e,t,r){var n,i,o,a;let s=Ei(e);r.name!==Mc(e)&&(QM(e,r.name),XM(s,r.name));let l=Ci(wr(s,Sm)).trim().toLowerCase()==="true";if(((n=r.required)!==null&&n!==void 0?n:!1)!==l){let u=wr(s,Sm);if(!u)throw vi(`setting '${Sm}' on a step whose xaml does not expose that slot`);YM(u,t,r.required?"True":"False")}if(((i=r.fieldName)!==null&&i!==void 0?i:"")!==((o=ZM(e))!==null&&o!==void 0?o:"")){let u=eU(e);if(!u)throw new Wn.InvalidArgumentError("BPF step has no <mcwb:Control> element to bind a column to");let c=(a=r.fieldName)!==null&&a!==void 0?a:"";OM(u,qM,BM,c),c!==""&&rU(u,DM,TM)===""&&OM(u,DM,TM,c)}}function kM(e,t,r,n){var i;let o=Ei(e);if(!o)throw new Wn.InvalidArgumentError("BPF stage composite has no <\u2026ActivityReference.Properties>");if(r.name!==Mc(e)&&(QM(e,r.name),XM(o,r.name)),Wse(o,t,r.category),zse(o,t,n),r.relationshipName&&r.relationshipName.trim()!=="")throw vi("a stage relationship / table change (multi-table authoring)");if(r.actions&&r.actions.length>0||r.branch)throw vi("stage actions or conditional branching");let a=iU(e);if(!a)throw new Wn.InvalidArgumentError("BPF stage has no [Activities] collection");let s=(i=r.steps)!==null&&i!==void 0?i:[];if(s.length===0)throw new Wn.InvalidArgumentError(`BPF stage '${r.name}' must have at least one step`);let l=Iw(e);if(sU(l,s.map(d=>d.id),RM)){l.forEach((d,f)=>LM(d,t,s[f]));return}let u=new Map(l.map(d=>[RM(d),d]));if(wi(a).some(d=>!Dl(d,JM)))throw vi("adding, removing or reordering steps on a stage that also contains branching or actions");let c=s.map(d=>{var f;return(f=u.get(d.id))!==null&&f!==void 0?f:Gse(t,d)});oU(a,c),c.forEach((d,f)=>LM(d,t,s[f]))}function jse(e,t,r){let n=Wa(e,UM);if(!n)throw new Wn.InvalidArgumentError("BPF xaml has no <mxswa:Workflow> root activity");if(r.globalActions&&r.globalActions.length>0)throw vi("global (process-completed/abandoned) actions");if(!r.stages||r.stages.length===0)throw new Wn.InvalidArgumentError("a BPF must have at least one stage");let i=Dm(e),o=i.map(f=>f.el);if(sU(o,r.stages.map(f=>f.id),PM)){i.forEach(({el:f,entity:m},p)=>{let h=r.stages[p];if(h.entityLogicalName&&h.entityLogicalName.trim()!==""&&h.entityLogicalName!==m)throw vi(`changing a stage's table ('${h.entityLogicalName}' vs the process's '${m}')`);kM(f,t,h,h.nextStageId)});return}let a=wi(n).filter(f=>Dl(f,HM));if(a.length!==1)throw vi("adding, removing or reordering stages on a multi-table process");let s=a[0],l=nU(s),u=iU(s);if(!u)throw new Wn.InvalidArgumentError("BPF primary entity composite has no [Activities] collection");if(wi(u).some(f=>!Dl(f,KM)))throw vi("adding, removing or reordering stages on a process whose primary composite holds non-stage activities (multi-table nesting or advanced constructs)");for(let f of r.stages)if(f.entityLogicalName&&f.entityLogicalName.trim()!==""&&f.entityLogicalName!==l)throw vi(`a stage on a different table ('${f.entityLogicalName}') than the process primary ('${l}')`);let c=new Map(o.map(f=>[PM(f),f])),d=r.stages.map(f=>{var m;return(m=c.get(f.id))!==null&&m!==void 0?m:Vse(t,f,l)});oU(u,d),d.forEach((f,m)=>{let p=m<d.length-1?r.stages[m+1].id:void 0;kM(f,t,r.stages[m],p)})}function Im(e){let t=e.match(/^<\?xml[^>]*\?>\s*/),r=t?t[0]:"";return{prolog:r,body:e.slice(r.length)}}function Hse(e){var t,r,n,i,o,a;(0,MM.installDomShim)();let s=(t=e.bag)===null||t===void 0?void 0:t.xaml;if(s){let f=new DOMParser().parseFromString("<root/>","text/xml"),m={n:"Activity",a:(0,Sw.mergeAttrs)(s.a,[]),c:(0,Sw.spliceChildren)(s.c,[])};return{root:(0,Sw.rebuildRaw)(m,(0,Ga.domEngine)(f),null),prolog:(n=(r=e.bag)===null||r===void 0?void 0:r.xamlProlog)!==null&&n!==void 0?n:Nw,eol:(o=(i=e.bag)===null||i===void 0?void 0:i.xamlEol)!==null&&o!==void 0?o:"lf"}}let l=e.stages[0],u=(a=l?.steps)===null||a===void 0?void 0:a[0],c=Pw(e.entityLogicalName,(0,Gr.newId)(),l?.id&&l.id.trim()!==""?l.id:(0,Gr.newId)(),u?.id&&u.id.trim()!==""?u.id:(0,Gr.newId)()),{body:d}=Im(c);return{root:(0,Ga.parseXmlRoot)(d,"<Activity/>"),prolog:Nw,eol:"lf"}}function Kse(e){let{root:t,prolog:r,eol:n}=Hse(e);jse(t,t.ownerDocument,e);let i=(0,Ga.serializeNode)(t);return n==="crlf"&&(i=i.replace(/\n/g,`\r+`)),r+i}function Jse(e){return e.uniqueName&&e.uniqueName.trim()!==""?e.uniqueName:`new_${(e.name||"businessprocessflow").toLowerCase().replace(/[^a-z0-9]/g,"")||"businessprocessflow"}`}var _m=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var r,n;(0,MM.installDomShim)();let i=t,o=typeof i.xaml=="string"?i.xaml:"",a={id:i.workflowid?String(i.workflowid):null,name:String((r=i.name)!==null&&r!==void 0?r:""),entityLogicalName:String((n=i.primaryentity)!==null&&n!==void 0?n:""),status:Number(i.statecode)===1?"Active":"Draft",stages:[]};if(i.uniquename&&(a.uniqueName=String(i.uniquename)),i.description!=null&&i.description!==""&&(a.description=String(i.description)),i.processorder!=null&&i.processorder!==""&&(a.order=Number(i.processorder)),o.trim()!==""){let{prolog:s,body:l}=Im(o),u=(0,Ga.parseXmlRoot)(l,"<Activity/>");a.stages=Bse(u),a.bag={xaml:(0,Ga.projectElementBag)(u),xamlProlog:s,xamlEol:/\r\n/.test(o)?"crlf":"lf"}}return a}toApiPayload(t){var r;let n={workflowid:t.id&&t.id.trim()!==""?t.id:(0,Gr.newId)(),name:t.name,uniquename:Jse(t),primaryentity:t.entityLogicalName,xaml:Kse(t),category:Am.WorkflowCategory.BusinessProcessFlow,type:Am.WorkflowTypeCode.Definition,businessprocesstype:Am.BusinessProcessType.BusinessFlow,scope:Am.WorkflowScope.Organization,processorder:(r=t.order)!==null&&r!==void 0?r:Ose};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 Wn.InvalidArgumentError('securityRoles require the BPF to be Active \u2014 the backing table they grant access to is created on activation; set status to "Active" to wire security roles');i.securityRoles=t.securityRoles}return i}createDefault(t){var r,n,i;let o=t.stages&&t.stages.length>0?t.stages.map(xM):[xM({id:(0,Gr.newId)(),name:"New Stage",steps:[]})],a={id:t.id&&t.id.trim()!==""?t.id:(0,Gr.newId)(),name:(r=t.name)!==null&&r!==void 0?r:"New business process flow",entityLogicalName:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",status:(i=t.status)!==null&&i!==void 0?i:"Draft",stages:o};return t.uniqueName&&(a.uniqueName=t.uniqueName),t.description!==void 0&&(a.description=t.description),t.order!==void 0&&(a.order=t.order),t.globalActions!==void 0&&(a.globalActions=t.globalActions),t.securityRoles!==void 0&&(a.securityRoles=t.securityRoles),a}assignMissingIds(t){let r=Fc(t);(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,Gr.newId)());for(let n of["stages","steps","actions","globalActions"]){let i=r[n];Array.isArray(i)&&i.forEach(o=>this.assignMissingIds(o))}return r}validate(t){let r=[],n=t.stages;if(n!==void 0&&!Array.isArray(n))return r.push((0,tn.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,tn.issue)("/stages","too-many-stages",`a BPF allows at most 30 stages, got ${i.length}`));let o=new Set,a=new Map;i.forEach((l,u)=>{let c=`/stages/${u}`,d=Fc(l),f=typeof d.id=="string"?d.id.trim():"";f===""?r.push((0,tn.issue)(`${c}/id`,"stage-id-required","a stage needs an id")):a.has(f.toLowerCase())?r.push((0,tn.issue)(`${c}/id`,"stage-id-duplicate",`two stages share the id '${d.id}' (also at /stages/${a.get(f.toLowerCase())})`)):a.set(f.toLowerCase(),u),typeof d.entityLogicalName=="string"&&d.entityLogicalName!==""&&o.add(d.entityLogicalName);let m=Array.isArray(d.steps)?d.steps:[];m.length===0&&r.push((0,tn.issue)(`${c}/steps`,"stage-needs-step","a BPF stage must have at least one step")),m.length>30&&r.push((0,tn.issue)(`${c}/steps`,"too-many-steps",`a stage allows at most 30 steps, got ${m.length}`));let p=new Map;m.forEach((h,g)=>{let b=`${c}/steps/${g}`,w=typeof Fc(h).id=="string"?h.id.trim():"";w===""?r.push((0,tn.issue)(`${b}/id`,"step-id-required","a step needs an id")):p.has(w.toLowerCase())?r.push((0,tn.issue)(`${b}/id`,"step-id-duplicate",`two steps in this stage share the id '${h.id}'`)):p.set(w.toLowerCase(),g)}),d.branch&&!$M(i,d.branch.nextStageId)&&r.push((0,tn.issue)(`${c}/branch/nextStageId`,"branch-target-unknown",`branch nextStageId '${d.branch.nextStageId}' does not match any stage id`)),typeof d.nextStageId=="string"&&d.nextStageId!==""&&!$M(i,d.nextStageId)&&r.push((0,tn.issue)(`${c}/nextStageId`,"next-stage-unknown",`nextStageId '${d.nextStageId}' does not match any stage id`))}),o.size>5&&r.push((0,tn.issue)("/stages","too-many-tables",`a BPF spans at most 5 tables, got ${o.size}`));let s=Yse(i);return s>=0&&r.push((0,tn.issue)(`/stages/${s}/nextStageId`,"next-stage-cycle","the stage nextStageId links form a cycle; the flow must be acyclic")),r}};Il.BpfAdapter=_m;function Yse(e){let t=new Map(e.map(r=>[Fc(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 $M(e,t){return e.some(r=>Fc(r).id===t)}function xM(e){var t,r;let n=e.steps&&e.steps.length>0?e.steps.map(FM):[FM({id:(0,Gr.newId)(),name:"New Step"})],i={id:e.id&&e.id.trim()!==""?e.id:(0,Gr.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 FM(e){var t;let r={id:e.id&&e.id.trim()!==""?e.id:(0,Gr.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 Pw(e,t,r,n){return`${Nw}<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="${_M}" /></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="${_M}" /></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 Qse(){return{adapter:new _m,api:Ise.bpfApi,languageSensitive:!0}}Il.bpfRegistration=Qse});var uU=v(Om=>{"use strict";Object.defineProperty(Om,"__esModule",{value:!0});Om.buildRegistrations=void 0;var Xse=tk(),Zse=Ck(),ele=nx(),tle=Cx(),rle=jx(),nle=dF(),ile=DF(),ole=cM(),ale=lU();function sle(e){let t=new Map;return t.set("form",(0,Xse.formRegistration)(e)),t.set("view",(0,Zse.viewRegistration)()),t.set("businessRule",(0,ele.businessRuleRegistration)()),t.set("app",(0,tle.appRegistration)(e)),t.set("command",(0,rle.commandRegistration)()),t.set("chart",(0,nle.chartRegistration)()),t.set("dashboard",(0,ile.dashboardRegistration)(e)),t.set("genPage",(0,ole.genPageRegistration)()),t.set("bpf",(0,ale.bpfRegistration)()),t}Om.buildRegistrations=sle});var AU=v(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE=Te.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE=Te.ROW_SUMMARY_MODEL_NOT_DELETED_CODE=Te.removeRowSummary=Te.configureRowSummary=Te.buildGptDynamicPrompt=Te.setAppAiFeatures=Te.getAiReadiness=Te.saveSettingValue=Te.retrieveSetting=Te.AI_GATE=void 0;var za=Tt(),Sn=fe(),He=oe(),cU=ct(),Ze=Q();Te.AI_GATE={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabled",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"EnableNLGridSearch",nlChart:"NLChartVisualizationSetting",summaries:"EnableFormInsights",m365:"m365copilotmodelappenabled"};var gU={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabledOnByDefault",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"NLGridSearchSetting",nlChart:"NLChartDataVisualizationSetting",m365:"m365copilotmodelappenabled"},lle=new Set(Object.entries(Te.AI_GATE).filter(([e,t])=>gU[e]===t).map(([e])=>e)),ule={formFill:{enabled:"2",disabled:"1"},formFillSuggestions:{enabled:"2",disabled:"1"},formFillSmartPaste:{enabled:"2",disabled:"1"},formFillFiles:{enabled:"2",disabled:"1"}};function Rw(e){return ule[e]}var Pm=1e6;function cle(e,t){let r=Rw(t),n=()=>{throw new Ze.InvalidArgumentError(`setAppAiFeatures: '${t}' must be a boolean or an integer between 0 and ${Pm} (e.g. 0, 1, 2); got '${String(e)}'.`)},i=o=>r?o?r.enabled:r.disabled:o?"1":"0";if(typeof e=="boolean")return i(e);if(typeof e=="number")return!Number.isSafeInteger(e)||e<0||e>Pm?n():String(e);if(typeof e=="string"){let o=e.trim(),a=o.toLowerCase();if(a==="true")return i(!0);if(a==="false")return i(!1);if(/^[0-9]+$/.test(o)){let s=o.replace(/^0+(?=[0-9])/,"");return s.length>String(Pm).length||Number(s)>Pm?n():s}}return n()}function dle(e,t){let r=Rw(t);return r?e===r.enabled:e!=="0"}async function fle(e,t){var r,n;let i=`/appmodules${(0,He.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,He.odataLiteral)(t)}'`]])}`,o=await e.get(i);if(o.status<200||o.status>=300)return;let a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new Ze.ConnectionError(e.apiUrl(i),o.status,`the app lookup for '${t}' returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,za.describeMalformedValue)(a)}`);return(n=a[0])===null||n===void 0?void 0:n.appmoduleid}async function ple(e,t){var r,n;let i=`/appmodules${(0,He.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,He.odataLiteral)(t)}'`]])}`,o;try{o=await e.get(i)}catch(l){throw new Ze.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup failed (${l.message}). Retry, or omit appModuleId to verify by name.`)}if(o.status<200||o.status>=300)throw new Ze.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned HTTP ${o.status}. Retry, or omit appModuleId to verify by name.`);let a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new Ze.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a malformed body.`);if(a.length===0)return;let s=(n=a[0])===null||n===void 0?void 0:n.appmoduleid;if(!s)throw new Ze.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a row with no appmoduleid.`);return s}var dU=new WeakMap;async function mle(e,t){var r,n;let i=dU.get(e);if(i||(i=new Map,dU.set(e,i)),i.has(t))return i.get(t);let o=`/settingdefinitions${(0,He.odataQuery)([["$select","settingdefinitionid"],["$filter",`uniquename eq '${(0,He.odataLiteral)(t)}'`]])}`,a=await e.get(o);if(a.status<200||a.status>=300)return;let s=(r=a.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(s))throw new Ze.ConnectionError(e.apiUrl(o),a.status,`the setting definition lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,za.describeMalformedValue)(s)}`);let l=(n=s[0])===null||n===void 0?void 0:n.settingdefinitionid;return l&&i.set(t,l),l}async function hle(e,t,r){var n,i;let o=await mle(e,r);if(!t||!o)return;let a=`/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()${(0,He.odataQuery)([["$select","value,componentstate"],["$filter",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${o}`]])}`,s=await e.get(a);if(s.status<200||s.status>=300)return;let l=(n=s.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(l))throw new Ze.ConnectionError(e.apiUrl(a),s.status,`the app-scope override read returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,za.describeMalformedValue)(l)}`);let u=l;if(u.length===0)return{exists:!1};let c=(i=u.find(d=>d?.componentstate===1))!==null&&i!==void 0?i:u[0];return{exists:!0,value:c.value,pendingPublish:c.componentstate===1}}var gle=4,yle=500,fU=20,pU=3e4;function ble(e){if(e===void 0)return gle;if(!Number.isFinite(e))throw new Ze.InvalidArgumentError(`setAppAiFeatures: verifyAttempts must be a finite integer between 1 and ${fU}; got ${e}.`);return Math.min(fU,Math.max(1,Math.floor(e)))}function vle(e){if(e===void 0)return yle;if(!Number.isFinite(e))throw new Ze.InvalidArgumentError(`setAppAiFeatures: verifyDelayMs must be a finite number between 0 and ${pU}; got ${e}.`);return Math.min(pU,Math.max(0,Math.floor(e)))}async function wle(e,t,r,n,i,o,a){let s,l,u,c=!1;for(let d=0;d<o;d+=1){d>0&&await new Promise(m=>setTimeout(m,a*d));let f;try{let m=await t();m?(f=await hle(e,m,n),f===void 0&&(u="the app-scope override row could not be read (insufficient access or unresolvable ids)")):u=`the app '${r}' could not be resolved to an appmoduleid \u2014 a newly created app is not readable until it is published, so either publish it first or pass \`appModuleId\` in the options to verify without the lookup`}catch(m){f=void 0,u=m.message}c=f!==void 0,l=f?.exists;try{s=(await Rm(e,n,{appUniqueName:r})).value}catch{}if(f?.exists&&f.value===i)return{result:"proven",effectiveValue:f.value,appOverrideExists:!0,...f.pendingPublish?{pendingPublish:!0}:{}}}return c?{result:"absent",effectiveValue:s,appOverrideExists:l}:{result:"unverifiable",effectiveValue:s,appOverrideExists:void 0,reason:u}}function yU(e,t,r){if(t===2)return String(e).toLowerCase()==="true";let n=r?Rw(r):void 0;return n?e===n.enabled:e!=null&&e!=="0"&&e!==""}async function Rm(e,t,r={}){var n;let i=[`SettingName='${(0,He.odataPathLiteral)(t)}'`];r.appUniqueName&&i.push(`AppUniqueName='${(0,He.odataPathLiteral)(r.appUniqueName)}'`);let o=`/RetrieveSetting(${i.join(",")})`,a=(0,Sn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(n=a.body)===null||n===void 0?void 0:n.SettingDetail;if(s===null||typeof s!="object"||Array.isArray(s)||!("Value"in s))throw new Ze.ConnectionError(e.apiUrl(o),a.status,`RetrieveSetting for '${t}' returned a malformed answer \u2014 expected a SettingDetail with a Value`);let{Value:l,DataType:u}=s;return{value:l,dataType:u}}Te.retrieveSetting=Rm;async function bU(e,t,r,n={}){let i={SettingName:t,Value:r};n.appUniqueName&&(i.AppUniqueName=n.appUniqueName),n.solutionUniqueName&&(i.SolutionUniqueName=n.solutionUniqueName),(0,Sn.ensureSuccess)(await e.post("/SaveSettingValue",i),e.apiUrl("/SaveSettingValue"))}Te.saveSettingValue=bU;async function Cle(e,t={}){let r={};for(let[n,i]of Object.entries(Te.AI_GATE)){let{value:o,dataType:a}=await Rm(e,i,t);r[n]={enabled:yU(o,a,n),setting:i,value:o}}return r}Te.getAiReadiness=Cle;async function Ele(e,t,r,n={}){var i;if(!t||!t.trim())throw new Ze.InvalidArgumentError("setAppAiFeatures: a non-empty appUniqueName is required (an empty value would write the setting at organization scope, affecting every app).");let o=ble(n.verifyAttempts),a=vle(n.verifyDelayMs),s=[];for(let[p,h]of Object.entries(r)){if(h===void 0)continue;let g=gU[p];g&&s.push({feature:p,setting:g,requestedValue:cle(h,p)})}let l=[],u=n.appModuleId?(0,He.normalizeGuid)(n.appModuleId,"appModuleId"):void 0;if(u){let p=await ple(e,t);if(p&&(0,He.normalizeGuid)(p,"appModuleId")!==u)throw new Ze.InvalidArgumentError(`setAppAiFeatures: appModuleId '${u}' does not belong to app '${t}' (which resolves to '${p}'). Settings are written by unique name, so verifying against a different app would report success for a write that never landed.`)}let c,d=async()=>u||(c||(c=await fle(e,t)),c),f=new Map,m=async p=>{if(lle.has(p))return;let h=Te.AI_GATE[p];if(h){if(!f.has(h))try{let{value:g,dataType:b}=await Rm(e,h);f.set(h,{enabled:yU(g,b,p),setting:h,value:g})}catch{f.set(h,void 0)}return f.get(h)}};for(let{feature:p,setting:h,requestedValue:g}of s)try{await bU(e,h,g,{appUniqueName:t,solutionUniqueName:n.solutionUniqueName});let b=await wle(e,d,t,h,g,o,a),w={feature:p,setting:h,requestedValue:g,effectiveValue:b.effectiveValue,appOverrideExists:b.appOverrideExists};if(b.result==="proven")l.push({...w,status:"applied",...b.pendingPublish?{pendingPublish:!0}:{}});else if(b.result==="absent"){let C=dle(g,p)?await m(p):void 0;C&&!C.enabled?l.push({...w,status:"skipped",reason:`the write was issued and no app-scope override holding '${g}' was observed for '${h}' after ${o} attempt(s); the org readiness gate '${C.setting}' reads '${C.value}', so an environment admin must enable it before this app can turn the feature on`}):l.push({...w,status:"notPersisted",reason:`the write reported success but no app-scope override holding '${g}' was observed for '${h}' after ${o} attempt(s) \u2014 ${b.effectiveValue===void 0?"the value in effect for this app could not be read":`it reads '${b.effectiveValue}' for this app`} (Dataverse can accept an app-scope write without storing it)`})}else l.push({...w,status:"unverified",reason:`the write was issued but could not be confirmed: ${(i=b.reason)!==null&&i!==void 0?i:"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(b){l.push({feature:p,setting:h,requestedValue:g,status:"failed",reason:b.message})}return{applied:l.filter(p=>p.status==="applied").map(p=>p.feature),skipped:l.filter(p=>p.status==="skipped").map(p=>p.feature),notPersisted:l.filter(p=>p.status==="notPersisted").map(p=>p.feature),unverified:l.filter(p=>p.status==="unverified").map(p=>p.feature),failed:l.filter(p=>p.status==="failed").map(p=>p.feature),outcomes:l}}Te.setAppAiFeatures=Ele;var vU="GptPowerPrompt",Ale='{ "consumptionSource": "Api", "partnerSource": "AIBuilder", "consumptionSourceVersion": "GptApiClient"}';function wU(e){var t,r,n,i;let o=e.entityLogicalName,a=[{type:"literal",text:e.instruction.replace(/\s*$/,"")+" "}];return e.columns.forEach((s,l)=>{a.push({type:"data",id:`${o}.${s.logical}`,text:s.display}),l<e.columns.length-1&&a.push({type:"literal",text:", "})}),{version:"GptDynamicPrompt-2",prompt:a,definitions:{inputs:[{id:"RecordId",text:"RecordId",type:"text"},{id:"LanguageCode",text:"LanguageCode",type:"text"}],formulas:[],data:[{id:o,displayName:o,type:"dataverseTable",filters:[{filterType:"equal",attribute:e.primaryKey,valueType:"inputVariable",value:"RecordId"}]}],output:{formats:[(t=e.outputFormat)!==null&&t!==void 0?t:"text"]}},modelParameters:{modelType:"default",gptParameters:{temperature:(r=e.temperature)!==null&&r!==void 0?r:0}},settings:{recordRetrievalLimit:(n=e.recordRetrievalLimit)!==null&&n!==void 0?n:30,shouldPreserveRecordLinks:null,runtime:null,enableReasoning:(i=e.enableReasoning)!==null&&i!==void 0?i:!0},code:"",signature:""}}Te.buildGptDynamicPrompt=wU;async function Sle(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,He.odataPathLiteral)(t)}')${(0,He.odataQuery)([["$select","MetadataId"]])}`,i=(0,Sn.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.MetadataId;if(typeof o!="string"||o==="")throw new Ze.ConnectionError(e.apiUrl(n),i.status,`the table metadata read for '${t}' returned a malformed answer \u2014 expected a MetadataId but got ${o===""?"an empty string":(0,za.describeMalformedValue)(o)}`);return o}async function CU(e){var t,r;let n=`/msdyn_aitemplates${(0,He.odataQuery)([["$select","msdyn_aitemplateid"],["$filter",`msdyn_uniquename eq '${vU}'`],["$top",1]])}`,i=(0,Sn.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(t=i.body)===null||t===void 0?void 0:t.value;if(!Array.isArray(o))throw new Ze.ConnectionError(e.apiUrl(n),i.status,`the row-summary template lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,za.describeMalformedValue)(o)}`);return((r=o[0])!==null&&r!==void 0?r:{}).msdyn_aitemplateid}function EU(e){return`${e} row summary`}async function Nle(e,t,r){var n;let i=`/msdyn_aimodels(${t})${(0,He.odataQuery)([["$select","msdyn_name,_msdyn_templateid_value"]])}`,o=await e.get(i);if(o.status===404)return!1;let a=(n=(0,Sn.ensureSuccess)(o,e.apiUrl(i)).body)!==null&&n!==void 0?n:{},s=await CU(e);return typeof a.msdyn_name=="string"&&a.msdyn_name.toLowerCase()===EU(r).toLowerCase()&&typeof a._msdyn_templateid_value=="string"&&s!==void 0&&a._msdyn_templateid_value.toLowerCase()===s.toLowerCase()}async function _le(e,t,r={}){var n;let i=`ais_RowSummary_${t.entityLogicalName}`,o=`/aiskillconfigs${(0,He.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,He.odataLiteral)(i)}'`],["$top",1]])}`,a=(0,Sn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(n=a.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(s))throw new Ze.ConnectionError(e.apiUrl(o),a.status,`the existing row-summary skill lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,za.describeMalformedValue)(s)}`);let l=s[0];if(l)return{modelId:l._aimodel_value,aiSkillConfigId:l.aiskillconfigid};let u=await Sle(e,t.entityLogicalName),c=await CU(e);if(c===void 0)throw new Ze.SdkError(Te.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE,`Cannot configure the row summary of '${t.entityLogicalName}': this org has no AI template '${vU}' (msdyn_aitemplates), which a row-summary model is built from. Nothing was written.`);let d=(0,cU.newId)(),f=(0,cU.newId)(),m=JSON.stringify(wU(t)),p={ModelId:d,RunConfigurationId:f,ModelName:EU(t.entityLogicalName),TemplateId:c,CustomConfiguration:m,Source:Ale,RunConfiguration:""};(0,Sn.ensureSuccess)(await e.post("/AIModelPublish",p),e.apiUrl("/AIModelPublish"));try{let h={uniquename:i,description:`${t.entityLogicalName} row summary`,"[email protected]":`/entities(${u})`,"[email protected]":`/msdyn_aimodels(${d})`,aiskill:"RowSummary"},g=(0,Sn.ensureSuccess)(await e.post("/aiskillconfigs",h),e.apiUrl("/aiskillconfigs")),b=(0,Sn.requireCreatedId)(g,"aiskillconfigid","row-summary skill");return{modelId:d,aiSkillConfigId:b}}catch(h){try{await e.delete(`/msdyn_aimodels(${d})`)}catch{}throw h}}Te.configureRowSummary=_le;async function Tle(e,t){var r;let n=`ais_RowSummary_${t.entityLogicalName}`,i=`/aiskillconfigs${(0,He.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,He.odataLiteral)(n)}'`],["$top",1]])}`,o=(0,Sn.ensureSuccess)(await e.get(i),e.apiUrl(i)),a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new Ze.ConnectionError(e.apiUrl(i),o.status,`the row-summary skill lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,za.describeMalformedValue)(a)}`);let s=a[0];if(!s)return;let l=(0,He.normalizeGuid)(s.aiskillconfigid,"aiskillconfigid"),u=s._aimodel_value?(0,He.normalizeGuid)(s._aimodel_value,"_aimodel_value"):void 0,c=u?await Nle(e,u,t.entityLogicalName):!1,d=t.entityLogicalName,f=`/aiskillconfigs(${l})`,m=await mU(e,f,`${f}${(0,He.odataQuery)([["$select","aiskillconfigid"]])}`);if(m.kind==="failed")throw m.stillThere===void 0&&u&&c?(0,Ze.attachCause)(new Ze.SdkError(Te.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE,`Removing the row summary of '${d}' could not be confirmed: deleting its skill row failed (${hU(m.failure)}) and the row could not be read back. If it is gone, its AI model '${u}' is left behind, unreferenced. Retry removeRowSummary: while the skill row exists it removes both; once it is gone, delete that model.`),m.failure):m.failure;if(u&&c){let p=`/msdyn_aimodels(${u})`,h=await mU(e,p,`${p}${(0,He.odataQuery)([["$select","msdyn_aimodelid"]])}`,Ile);if(h.kind==="failed")throw(0,Ze.attachCause)(new Ze.SdkError(Te.ROW_SUMMARY_MODEL_NOT_DELETED_CODE,`The row summary of '${d}' was removed, but its AI model '${u}' ${h.stillThere?"was not deleted":"could not be confirmed deleted"} (${hU(h.failure)}). The model is no longer used by the row summary; delete it before configuring a row summary for '${d}' again, which needs its name.`),h.failure)}}Te.removeRowSummary=Tle;Te.ROW_SUMMARY_MODEL_NOT_DELETED_CODE="ROW_SUMMARY_MODEL_NOT_DELETED";Te.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE="ROW_SUMMARY_REMOVAL_UNCONFIRMED";Te.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE="ROW_SUMMARY_TEMPLATE_NOT_FOUND";var Dle="0x8004f01f";function Ile(e){var t,r;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return e.status===400&&typeof n=="string"&&n.toLowerCase()===Dle}function Ole(e){if(e.status!==400&&e.status!==500||e.body===void 0||e.body===null)return!1;let t=typeof e.body=="string"?e.body:JSON.stringify(e.body);return/chosen as the deadlock victim|\bSql Number:\s*1205\b/i.test(t)}async function mU(e,t,r,n=()=>!1){let i;try{let o=await(0,Sn.resendWhile)(Ole,()=>e.delete(t));if(o.status>=200&&o.status<300||o.status===404)return{kind:"gone"};if(n(o))return{kind:"kept"};try{(0,Sn.ensureSuccess)(o,e.apiUrl(t))}catch(a){i=a}}catch(o){i=o}try{let o=await e.get(r);return o.status===404?{kind:"gone"}:{kind:"failed",failure:i,stillThere:o.status>=200&&o.status<300?!0:void 0}}catch{return{kind:"failed",failure:i,stillThere:void 0}}}function hU(e){return e instanceof Error?e.message:String(e)}});var _U=v(Ol=>{"use strict";Object.defineProperty(Ol,"__esModule",{value:!0});Ol.findArtifact=Ol.resolveArtifact=void 0;var Ht=oe(),no=Zd(),Ple=Af(),Rle=Tt(),Lle=fe(),SU=Q();async function NU(e,t,r){let n="/uxagentprojects"+(0,Ht.odataQuery)([["$select","uxagentprojectid,name"],["$filter",`name eq '${(0,Ht.odataLiteral)(t)}'`],...r!==void 0?[["$top",String(r)]]:[]]);return(await(0,Rle.collectPages)(e,n,"resolveArtifact('genPage')",void 0,{headers:{"MSCRM.IncludeUnpublished":"true"}})).map(o=>({id:String(o.uxagentprojectid),name:String(o.name)}))}async function kle(e,t,r){var n,i,o,a,s,l,u,c,d,f,m,p;switch(t){case"app":{let h=(0,Ple.unpublishedAppModulesQuery)("appmoduleid,name,appmoduleidunique",`uniquename eq '${(0,Ht.odataLiteral)((n=r.uniqueName)!==null&&n!==void 0?n:"")}'`,1),b=(i=(0,Lle.ensureSuccess)(await e.get(h),e.apiUrl(h)).body)===null||i===void 0?void 0:i.value,w=b&&b[0];return w?[{id:String(w.appmoduleid),name:String(w.name),appModuleIdUnique:String(w.appmoduleidunique)}]:[]}case"dashboard":return(await(0,no.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,Ht.odataLiteral)((o=r.name)!==null&&o!==void 0?o:"")}' and type eq 0`,top:10})||[]).map(g=>({id:String(g.formid),name:String(g.name)}));case"command":{if(!r.entity)return[];let h=await(0,no.queryRecords)(e,"appaction",{select:["appactionid","buttonlabeltext"],filter:`contextvalue eq '${(0,Ht.odataLiteral)(r.entity)}'`,top:1});return h&&h.length?[{id:r.entity,entity:r.entity}]:[]}case"form":return(await(0,no.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,Ht.odataLiteral)((a=r.name)!==null&&a!==void 0?a:"")}' and objecttypecode eq '${(0,Ht.odataLiteral)((s=r.entity)!==null&&s!==void 0?s:"")}'`,top:10})||[]).map(g=>({id:String(g.formid),name:String(g.name)}));case"chart":return(await(0,no.queryRecords)(e,"savedqueryvisualization",{select:["savedqueryvisualizationid","name"],filter:`name eq '${(0,Ht.odataLiteral)((l=r.name)!==null&&l!==void 0?l:"")}' and primaryentitytypecode eq '${(0,Ht.odataLiteral)((u=r.entity)!==null&&u!==void 0?u:"")}'`,top:10})||[]).map(g=>({id:String(g.savedqueryvisualizationid),name:String(g.name)}));case"view":return(await(0,no.queryRecords)(e,"savedquery",{select:["savedqueryid","name"],filter:`name eq '${(0,Ht.odataLiteral)((c=r.name)!==null&&c!==void 0?c:"")}' and returnedtypecode eq '${(0,Ht.odataLiteral)((d=r.entity)!==null&&d!==void 0?d:"")}'`,top:10})||[]).map(g=>({id:String(g.savedqueryid),name:String(g.name)}));case"webResource":return(await(0,no.queryRecords)(e,"webresource",{select:["webresourceid","name"],filter:`name eq '${(0,Ht.odataLiteral)((f=r.name)!==null&&f!==void 0?f:"")}'`,top:1})||[]).map(g=>({id:String(g.webresourceid),name:String(g.name)}));case"solution":return(await(0,no.queryRecords)(e,"solution",{select:["solutionid","uniquename"],filter:`uniquename eq '${(0,Ht.odataLiteral)((m=r.uniqueName)!==null&&m!==void 0?m:"")}'`,top:1})||[]).map(g=>({id:String(g.solutionid),name:String(g.uniquename)}));case"genPage":return NU(e,(p=r.name)!==null&&p!==void 0?p:"");default:return[]}}Ol.resolveArtifact=kle;async function $le(e,t,r){var n,i,o,a,s,l;let u=(0,Ht.odataLiteral)((n=r.name)!==null&&n!==void 0?n:""),c=(0,Ht.odataLiteral)((i=r.entity)!==null&&i!==void 0?i:"");if(t==="command"){if(!r.entity)return null;let h=await(0,no.queryRecords)(e,"appaction",{select:["appactionid"],filter:`contextvalue eq '${(0,Ht.odataLiteral)(r.entity)}'`,top:1});return h&&h.length?r.entity:null}if(t==="genPage"){let h=await NU(e,(o=r.name)!==null&&o!==void 0?o:"",2);if(h.length>1)throw new SU.AmbiguousArtifactError(t,(a=r.name)!==null&&a!==void 0?a:"",h.length);return h.length===1?h[0].id:null}let d=xle(t,u,c,r),f=t!=="app",m=await(0,no.queryRecords)(e,d.set,{select:[d.idField],filter:d.filter,top:f?2:1});if(f&&m&&m.length>1)throw new SU.AmbiguousArtifactError(t,(l=(s=r.name)!==null&&s!==void 0?s:r.uniqueName)!==null&&l!==void 0?l:"",m.length);let p=m&&m[0]&&m[0][d.idField];return p!=null?String(p):null}Ol.findArtifact=$le;function xle(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,Ht.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 DU=v(km=>{"use strict";Object.defineProperty(km,"__esModule",{value:!0});km.seedRecordGraph=void 0;var TU=Zd(),Fle=$d(),Lm=oe(),Mle=Q();async function Ule(e,t,r={}){var n,i,o,a,s;let l=(n=r.createdIds)!==null&&n!==void 0?n:{},u=(i=r.entitySetFor)!==null&&i!==void 0?i:(f=>(0,Fle.resolveEntitySetName)(e,f)),c={},d=f=>{var m;return(m=c[f])!==null&&m!==void 0?m:l[f]};for(let f of t){let m=f.entityLogical.toLowerCase(),p=(o=f.matchOn)===null||o===void 0?void 0:o.toLowerCase(),h=[];for(let L of f.records){let I={...L.body};for(let D of(a=L.binds)!==null&&a!==void 0?a:[]){let P=D.parentEntity.toLowerCase(),x=(s=d(P))===null||s===void 0?void 0:s[D.parentIndex];if(!x)throw new Mle.InvalidArgumentError(`Cannot resolve bind '${D.navProperty}' on a '${m}' record: parent '${D.parentEntity}'[${D.parentIndex}] has no created id. Seed the parent group before the child, or supply it via options.createdIds.`);let K=(0,Lm.assertODataName)(await u(P),`entity set for parent '${D.parentEntity}'`),Le=(0,Lm.normalizeGuid)(x,`parent id for bind '${D.navProperty}'`);I[`${D.navProperty}@odata.bind`]=`/${K}(${Le})`}h.push(I)}let g=p?h.map(L=>{let I=L[p];return I!=null&&I!==""?String(I):null}):h.map(()=>null),b=new Map;if(p){let L=(0,Lm.assertODataName)(p,"RecordGraph matchOn key"),I=[...new Set(g.filter(D=>D!==null))];if(I.length){let D=I.map(x=>`${L} eq '${(0,Lm.odataLiteral)(x)}'`).join(" or "),P=await(0,TU.queryRecords)(e,m,{select:[L,`${m}id`],filter:D,top:5e3});for(let x of P??[]){let K=x[L];K!=null&&b.set(String(K).toLowerCase(),String(x[`${m}id`]))}}}let w=[],C=new Map,S=h.map((L,I)=>{let D=g[I];if(D&&b.has(D.toLowerCase()))return null;if(D){let P=D.toLowerCase(),x=C.get(P);if(x!==void 0)return x;let K=w.push(L)-1;return C.set(P,K),K}return w.push(L)-1}),O=w.length?await(0,TU.createRecordsBulk)(e,m,w):[];c[m]=h.map((L,I)=>{let D=g[I];return D&&b.has(D.toLowerCase())?b.get(D.toLowerCase()):O[S[I]]})}return{createdIds:c}}km.seedRecordGraph=Ule});var MU=v(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.getEntityPrivileges=or.addEntityPrivilegesToRole=or.deleteSecurityRole=or.createPersonaRole=or.createSecurityRole=or.SDK_ROLE_MARKER=void 0;var zn=fe(),Ft=oe(),rn=Q(),$m={read:"Read",create:"Create",write:"Write",delete:"Delete",append:"Append",appendTo:"AppendTo",assign:"Assign",share:"Share"},kw={user:"Basic",businessUnit:"Local",parentChild:"Deep",organization:"Global"},IU={user:1,businessUnit:2,parentChild:3,organization:4},Lw={user:"CanBeBasic",businessUnit:"CanBeLocal",parentChild:"CanBeDeep",organization:"CanBeGlobal"};or.SDK_ROLE_MARKER="Authored by @maker-studio/cds-maker-sdk (persona/security role).";function Ble(e){return Object.prototype.hasOwnProperty.call($m,e)?$m[e]:void 0}function qle(e){return Object.prototype.hasOwnProperty.call(kw,e)}var OU=new WeakMap,PU=new WeakMap;async function kU(e,t){var r,n;(0,Ft.assertODataName)(t,"entity logical name");let i=OU.get(e);i||(i=new Map,OU.set(e,i));let o=i.get(t);if(o)return o;let a=`/EntityDefinitions(LogicalName='${(0,Ft.odataPathLiteral)(t)}')${(0,Ft.odataQuery)([["$select","LogicalName,Privileges"]])}`,l=(n=(r=(0,zn.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||r===void 0?void 0:r.Privileges)!==null&&n!==void 0?n:[];if(l.length===0)throw new rn.InvalidArgumentError(`Entity '${t}' exposes no privileges (unknown or non-securable entity).`);return i.set(t,l),l}async function Vle(e){var t,r,n;let i=PU.get(e);if(i)return i;let o=`/businessunits${(0,Ft.odataQuery)([["$select","businessunitid"],["$filter","_parentbusinessunitid_value eq null"],["$top",1]])}`,l=(n=((r=(t=(0,zn.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||t===void 0?void 0:t.value)!==null&&r!==void 0?r:[])[0])===null||n===void 0?void 0:n.businessunitid;if(!l)throw new rn.InvalidArgumentError("Could not resolve the root business unit.");let u=(0,Ft.normalizeGuid)(l,"businessUnitId");return PU.set(e,u),u}async function $U(e,t){var r;let n=new Map;for(let i of t){if(!i.access||i.access.length===0)throw new rn.InvalidArgumentError(`Entity '${i.entity}' privilege request has no access levels.`);let o=(r=i.scope)!==null&&r!==void 0?r:"user";if(!qle(o))throw new rn.InvalidArgumentError(`Unknown privilege scope '${o}' for entity '${i.entity}'.`);let a=await kU(e,i.entity);for(let s of i.access){let l=Ble(s);if(!l)throw new rn.InvalidArgumentError(`Unknown access level '${s}' for entity '${i.entity}'.`);let u=a.find(p=>p.PrivilegeType===l);if(!u)throw new rn.InvalidArgumentError(`Entity '${i.entity}' does not support '${s}' access.`);let c=Lw[o];if(u[c]===!1)throw new rn.InvalidArgumentError(`Privilege '${u.Name}' on '${i.entity}' does not support the '${o}' scope.`);let d=(0,Ft.normalizeGuid)(u.PrivilegeId,"PrivilegeId"),f=n.get(d);if(!f){n.set(d,{privilegeName:u.Name,privilegeType:l,scope:o,entities:new Set([i.entity])});continue}if(f.scope===o){f.entities.add(i.entity);continue}if(!(f.entities.size===1&&f.entities.has(i.entity))){let p=[...f.entities].sort().join(", ");throw new rn.InvalidArgumentError(`Entities '${p}' and '${i.entity}' share the Dataverse privilege '${u.Name}' but request different scopes; a role holds one depth per privilege. Use the same scope for all entities that share this privilege, or split them.`)}f.scope=IU[o]>IU[f.scope]?o:f.scope}}return[...n.entries()].map(([i,o])=>({entity:[...o.entities].sort().join(", "),privilegeId:i,privilegeName:o.privilegeName,privilegeType:o.privilegeType,scope:o.scope}))}async function Gle(e,t,r,n){if(r.length===0&&!n)return;let i={Privileges:r.map(a=>({Depth:kw[a.scope],PrivilegeId:a.privilegeId}))},o=`/roles(${t})/Microsoft.Dynamics.CRM.ReplacePrivilegesRole`;(0,zn.ensureSuccess)(await e.post(o,i),e.apiUrl(o))}async function RU(e,t,r,n,i){var o,a;let s=`/${t}(${r})/${n}${(0,Ft.odataQuery)([["$select","roleid"],["$filter",`roleid eq ${i}`]])}`;return((a=(o=(0,zn.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||o===void 0?void 0:o.value)!==null&&a!==void 0?a:[]).length>0}async function Wle(e,t,r){var n,i;let o=[],a=[],s={"@odata.id":e.apiUrl(`/roles(${t})`)};for(let l of(n=r?.teams)!==null&&n!==void 0?n:[]){let u=(0,Ft.normalizeGuid)(l,"teamId");if(!await RU(e,"teams",u,"teamroles_association",t)){let c=`/teams(${u})/teamroles_association/$ref`;(0,zn.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}o.push(u)}for(let l of(i=r?.users)!==null&&i!==void 0?i:[]){let u=(0,Ft.normalizeGuid)(l,"userId");if(!await RU(e,"systemusers",u,"systemuserroles_association",t)){let c=`/systemusers(${u})/systemuserroles_association/$ref`;(0,zn.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}a.push(u)}return{teams:o,users:a}}async function LU(e,t,r){var n,i;let o=`/roles${(0,Ft.odataQuery)([["$select","roleid,description,ismanaged"],["$filter",`name eq '${(0,Ft.odataLiteral)(t)}' and _businessunitid_value eq ${r}`]])}`,l=((i=(n=(0,zn.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]).filter(d=>!!d.roleid);if(l.length===0)return;let u=d=>{var f;return d.ismanaged!==!0&&((f=d.description)!==null&&f!==void 0?f:"")===or.SDK_ROLE_MARKER};if(l.some(d=>!u(d)))throw new rn.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 rn.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,Ft.normalizeGuid)(c,"roleId"):void 0}function zle(e){var t,r;return{teams:((t=e?.teams)!==null&&t!==void 0?t:[]).map(n=>(0,Ft.normalizeGuid)(n,"teamId")),users:((r=e?.users)!==null&&r!==void 0?r:[]).map(n=>(0,Ft.normalizeGuid)(n,"userId"))}}function xU(e){return e.map(t=>({entity:t.entity,privilegeName:t.privilegeName,privilegeType:t.privilegeType,scope:t.scope}))}async function FU(e,t){var r,n;let i=(r=t.name)===null||r===void 0?void 0:r.trim();if(!i)throw new rn.InvalidArgumentError("createSecurityRole: a non-empty role name is required.");let o=t.businessUnitId?(0,Ft.normalizeGuid)(t.businessUnitId,"businessUnitId"):await Vle(e),a=await $U(e,(n=t.privileges)!==null&&n!==void 0?n:[]),s=zle(t.assignTo),l=await LU(e,i,o),u=l!==void 0;if(!l){let d="/roles",f={name:i,description:or.SDK_ROLE_MARKER,"[email protected]":`/businessunits(${o})`};try{let m=(0,zn.ensureSuccess)(await e.post(d,f),e.apiUrl(d));l=(0,Ft.normalizeGuid)((0,zn.requireCreatedId)(m,"roleid","role"),"roleId")}catch(m){let p;try{p=await LU(e,i,o)}catch{p=void 0}if(!p)throw m;l=p}}await Gle(e,l,a,u);let c=await Wle(e,l,s);return{roleId:l,name:i,reused:u,appliedPrivileges:xU(a),assignedTeams:c.teams,assignedUsers:c.users}}or.createSecurityRole=FU;async function jle(e,t){var r,n;let i=(r=t.persona)===null||r===void 0?void 0:r.trim();if(!i)throw new rn.InvalidArgumentError("createPersonaRole: a non-empty persona name is required.");let o=[...t.jobs.flatMap(a=>{var s;return(s=a.privileges)!==null&&s!==void 0?s:[]}),...(n=t.additionalPrivileges)!==null&&n!==void 0?n:[]];return FU(e,{name:i,businessUnitId:t.businessUnitId,privileges:o,assignTo:t.assignTo})}or.createPersonaRole=jle;async function Hle(e,t){let n=`/roles(${(0,Ft.normalizeGuid)(t,"roleId")})`;(0,zn.ensureSuccess)(await e.delete(n),e.apiUrl(n))}or.deleteSecurityRole=Hle;async function Kle(e,t,r){let n=(0,Ft.normalizeGuid)(t,"roleId");if(r.length===0)throw new rn.InvalidArgumentError("addEntityPrivilegesToRole requires at least one entity privilege (an empty grant would be a silent no-op).");let i=await $U(e,r),o={Privileges:i.map(s=>({Depth:kw[s.scope],PrivilegeId:s.privilegeId}))},a=`/roles(${n})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;return(0,zn.ensureSuccess)(await e.post(a,o),e.apiUrl(a)),xU(i)}or.addEntityPrivilegesToRole=Kle;var Jle=new Map(Object.keys($m).map(e=>[$m[e],e]));async function Yle(e,t){return(await kU(e,t)).map(n=>{let i=Object.keys(Lw).filter(a=>n[Lw[a]]!==!1),o=Jle.get(n.PrivilegeType);return{name:n.Name,privilegeId:n.PrivilegeId,privilegeType:n.PrivilegeType,...o?{access:o}:{},scopes:i}})}or.getEntityPrivileges=Yle});var tB=v(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.createMakerSdk=Er.MakerSdk=Er.PUSH_NOT_ATTEMPTED_CODE=Er.ALREADY_EXISTS_CODE=void 0;var UU=dh(),BU=jr(),Z=Q(),Nn=Xa(),Qle=CE(),QU=DE(),Pl=kE(),Xle=ph(),Zle=tA(),Rl=iA(),eue=bA(),tue=SA(),rue=tS(),qU=QS(),Mt=$d(),$w=e0(),VU=l_(),xm=vu(),io=Zd(),Fm=g_(),Ll=tf(),nue=nf(),ar=Jd(),iue=aT(),oue=v0(),aue=T0(),GU=w0(),sue=uU(),Mm=ct(),lue=sa(),Ai=Av(),_n=bh(),xw=lw(),uue=3e5,Cr=fe(),ja=oe(),kl=AU(),WU=_U(),cue=DU(),due=Ub(),Uc=MU(),XU=Symbol("cds-maker-sdk.committedWrite");function fue(e){return typeof e=="object"&&e!==null&&(e[XU]=!0),e}function pue(e){return typeof e=="object"&&e!==null&&e[XU]===!0}var mue={fileConcurrency:1},Fw="SOLUTION_COMPONENT_UNCLASSIFIED",hue=2,gue=4,yue="This table is in the solution with ALL its subcomponents. Those are members the solution does not list one by one, so fetchSolution did not enumerate or fetch them: none of its forms, views, charts or dashboards were fetched here. To fetch them, read the table's logical name from its metadata (EntityDefinitions(<componentId>), $select=LogicalName), list each kind with fetchArtifactList \u2014 'form' with formTypes Main, QuickView, QuickCreate and Card; 'view'; 'chart'; 'dashboard' \u2014 passing { entityLogicalName }, and fetch each listed id with fetchArtifact: listing returns ids and names only.";function zU(e){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"unsupported",...e.includesAllSubcomponents?{detail:yue}:{}}}function jU(e,t){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"failed",error:zo(t)}}function HU(e,t,r){let n=r;return{type:e,id:t.objectId,name:typeof n.name=="string"?n.name:t.objectId,entityLogicalName:typeof n.entityLogicalName=="string"?n.entityLogicalName:void 0,lastFetched:(0,Cr.nowIso)(),isDirty:!1}}var bue=new Set(["entity","appmodule","dashboard","uxagentproject"]);function vue(e){var t;let r={entity:[],appmodule:[],dashboard:[],uxagentproject:[]},n=new Set,i=(s,l)=>{let u=`${s}\0${l.toLowerCase()}`;n.has(u)||(n.add(u),r[s].push(l))};for(let{scope:s}of e)if(s?.envelope==="entity")s.entityLogicalName&&i("entity",s.entityLogicalName);else if(s&&s.envelope!=="webresource")for(let l of(t=s.targetIds)!==null&&t!==void 0?t:[])i(s.envelope,l);let o=(s,l,u)=>u.length>0?`<${s}>${u.map(c=>`<${l}>${(0,ja.xmlText)(c)}</${l}>`).join("")}</${s}>`:"",a=o("entities","entity",r.entity)+o("appmodules","appmodule",r.appmodule)+o("dashboards","dashboard",r.dashboard)+o("uxagentprojects","uxagentproject",r.uxagentproject);return a?`<importexportxml>${a}</importexportxml>`:void 0}function wue(e){let t=e.workspaceStorage;if(t==null)throw new Error("createMakerSdk requires a workspaceStorage. Node callers can build one with `createNodeWorkspaceStorage(path)` from '@maker-studio/cds-maker-sdk/node'; a host with no filesystem implements WorkspaceStorage directly.");return new QU.WorkspaceManager(Eue,e.instanceUrl,(0,Xle.assertStorageContract)(t))}Er.ALREADY_EXISTS_CODE="ARTIFACT_ALREADY_EXISTS";var Cue="this build answers a replayed create with HTTP 404, and the unpublished read of an existing row is not authoritative after another writer's save on it, so the row cannot be proven to be what this create wrote";Er.PUSH_NOT_ATTEMPTED_CODE="PUSH_NOT_ATTEMPTED";var Eue="<injected workspaceStorage>",Um=class{constructor(t){var r,n;if(this.artifactLocks=new Map,this.observedGenerations=new Map,this.baselineObserved=new Map,this.generationHighWater=new Map,this.entityMetadataLoads=new Map,this.entityMetadataLoadEpochs=new WeakMap,this.schemaWrites=new Map,this.undroppedMetadata=new Set,this.metadataPublications=new Set,t.createRecovery!==void 0&&t.createRecovery!=="adoptExact")throw new Z.InvalidArgumentError(`createRecovery must be 'adoptExact' or omitted (got '${String(t.createRecovery)}').`);this.createRecovery=t.createRecovery,this.readConcurrency=(0,xw.resolveReadConcurrency)(t.readConcurrency),this.languageCode=(r=t.languageCode)!==null&&r!==void 0?r:lue.DEFAULT_LCID,this.cacheStalenessMs=(n=t.cacheStalenessMs)!==null&&n!==void 0?n:uue,this.compiler={load:(0,oue.createGenPageTypeScriptLoader)(t.typescript)},this.workspace=wue(t),this.versions=new Pl.VersionManager(this.workspace),this.dataverse=new Zle.DataverseClient(t.instanceUrl,t.httpClient,t.solutionUniqueName,this.readConcurrency),this.connectivity=new rue.ConnectivityRouter(this.dataverse,t.instanceUrl,{powerAppsServiceClient:t.powerAppsServiceClient,powerPlatformApiClient:t.powerPlatformApiClient,connectorRuntimeClient:t.connectorRuntimeClient}),this.registrations=(0,sue.buildRegistrations)(this.languageCode)}async initWorkspace(){await this.workspace.init()}async getManifest(){return this.workspace.getManifest()}async cleanWorkspace(){await this.workspace.clean()}withArtifactLock(t,r,n){var i;let o=this.artifactKey(t,r),s=((i=this.artifactLocks.get(o))!==null&&i!==void 0?i:Promise.resolve()).then(n,n),l=s.then(()=>{},()=>{});return this.artifactLocks.set(o,l),l.then(()=>{this.artifactLocks.get(o)===l&&this.artifactLocks.delete(o)}),s}async fetchArtifact(t,r,n){return this.withArtifactLock(t,r,async()=>{let i=await this.fetchArtifactUnlocked(t,r,n);return await this.acknowledgeRefresh(t,r),i})}async fetchArtifactUnlocked(t,r,n){let i=this.requireRegistration(t,"fetchArtifact"),o=await i.api.get(this.dataverse,r);return this.applyFetchedArtifactUnlocked(t,r,i,o,n)}async applyFetchedArtifactUnlocked(t,r,n,i,o){var a,s,l;let{raw:u,etag:c,memberEtags:d,siblingEtags:f}=i,m=n.adapter.fromApiResponse(u);if(!o?.overwrite&&await this.versions.isDirty(t,r)){let h=(s=(a=await this.versions.getMeta(t,r))===null||a===void 0?void 0:a.etag)!==null&&s!==void 0?s:null;if(h&&c&&h!==c)throw new Z.LocalEditsWouldBeLostError(t,r,h,c);let g=await this.workspace.readArtifact(t,r);if(g){let b=await this.versions.getMeta(t,r);if(b&&!b.etag&&c){if(!(0,_n.deepEqual)(b.snapshot,m))throw new Z.LocalEditsWouldBeLostError(t,r,h,c);await this.versions.storeMeta(t,r,{...b,etag:c,fetchedAt:(0,Cr.nowIso)()},b)}return(0,Ai.cloneJson)(g)}}await this.workspace.writeArtifact(t,r,m);let p=await this.versions.getMeta(t,r);return await this.versions.storeMeta(t,r,{etag:c,languageCode:this.languageCode,projectionVersion:Pl.PROJECTION_VERSION,fetchedAt:(0,Cr.nowIso)(),snapshot:(0,Ai.cloneJson)(m),...d?{memberEtags:d}:{},...f?{siblingEtags:f}:{},...p?.refreshGeneration?{refreshGeneration:p.refreshGeneration,observedGeneration:(l=p.observedGeneration)!==null&&l!==void 0?l:0}:{}},p),(0,Ai.cloneJson)(m)}async fetchArtifactList(t,r){return this.requireRegistration(t,"fetchArtifactList").api.list(this.dataverse,r)}async fetchSolution(t){await this.workspace.ensureReady();let r=await(0,ar.fetchSolutionComponents)(this.dataverse,t),n=[],i=[];if(this.readConcurrency>1)await this.fetchComponentsOverlapped(r,n,i);else for(let o of r)try{let a=await this.resolveComponentType(o);if(!a){i.push(zU(o));continue}let s=await this.fetchArtifact(a,o.objectId);n.push(HU(a,o,s))}catch(a){i.push(jU(o,a))}return await this.workspace.updateManifest({lastSyncAt:(0,Cr.nowIso)()}),{summaries:n,skipped:i}}async fetchComponentsOverlapped(t,r,n){await(0,xw.readEveryInOrder)(t,this.readConcurrency,i=>this.beginComponentRead(i),async(i,o)=>{try{if(!i.ok)throw i.error;let a=i.value;if(a.kind==="unsupported"){n.push(zU(o));return}let s=await this.applyFetchedArtifactUnlocked(a.type,o.objectId,a.reg,a.fetched);await this.acknowledgeRefresh(a.type,o.objectId),r.push(HU(a.type,o,s))}catch(a){n.push(jU(o,a))}})}async beginComponentRead(t){let r=await this.resolveComponentType(t);return r?this.lockedRead(r,t.objectId,async()=>{let n=this.requireRegistration(r,"fetchArtifact"),i=await n.api.get(this.dataverse,t.objectId,mue);return{kind:"artifact",type:r,reg:n,fetched:i}}):(0,xw.plainRead)(async()=>({kind:"unsupported"}))}lockedRead(t,r,n){let i,o=new Promise(u=>{i=u}),a,s=new Promise(u=>{a=u}),l=this.withArtifactLock(t,r,async()=>{try{i({ok:!0,value:await n()})}catch(c){i({ok:!1,error:c})}let u=await s;await u?.()});return{outcome:o,finish:u=>(a(u),l),discard:async()=>{a(void 0),await l}}}async fetchEntityMetadata(t){let r=t.toLowerCase(),n=this.schemaEpoch(r),i=await(0,Rl.fetchEntityMetadataFromApi)(this.dataverse,t);if(this.schemaEpoch(r)!==n)return i;let o=this.workspace.writeEntityMetadata(t,i),a={key:r,settled:o.then(()=>{},()=>{})};this.metadataPublications.add(a);try{await o}finally{this.metadataPublications.delete(a)}return this.schemaEpoch(r)===n&&this.undroppedMetadata.delete(r),i}schemaEpoch(t){var r,n;return`${(r=this.schemaWrites.get("*"))!==null&&r!==void 0?r:0}:${(n=this.schemaWrites.get(t.toLowerCase()))!==null&&n!==void 0?n:0}`}async schemaWrite(t,r){try{return await r()}finally{await this.forgetEntityMetadata(t)}}async forgetEntityMetadata(t){let r=i=>{var o;this.schemaWrites.set(i,((o=this.schemaWrites.get(i))!==null&&o!==void 0?o:0)+1)};if(t===void 0){r("*"),await this.publicationsSettled(void 0),await this.dropCachedMetadata(void 0);return}let n=[...new Set(t.filter(i=>typeof i=="string"&&i!=="").map(i=>i.toLowerCase()))];n.forEach(r),await this.publicationsSettled(n);for(let i of n)await this.dropCachedMetadata(i)}async publicationsSettled(t){let r=t===void 0?void 0:new Set(t);await Promise.all([...this.metadataPublications].filter(n=>r===void 0||r.has(n.key)).map(n=>n.settled))}async dropCachedMetadata(t){try{await this.workspace.dropEntityMetadata(t)}catch(r){r instanceof Z.WorkspaceNotInitializedError||r instanceof Z.WorkspaceOrgMismatchError||this.undroppedMetadata.add(t??"*");return}t===void 0?this.undroppedMetadata.clear():this.undroppedMetadata.delete(t)}async readCachedEntityMetadata(t){let r=t.toLowerCase();return this.undroppedMetadata.has("*")&&await this.dropCachedMetadata(void 0),this.undroppedMetadata.has(r)&&await this.dropCachedMetadata(r),this.undroppedMetadata.has("*")||this.undroppedMetadata.has(r)?null:this.workspace.readEntityMetadata(t)}loadMissedEntityMetadata(t){let r=this.schemaEpoch(t),n=this.entityMetadataLoads.get(t);if(n&&this.entityMetadataLoadEpochs.get(n)===r)return n;let i=this.fetchEntityMetadata(t).then(()=>{});this.entityMetadataLoads.set(t,i),this.entityMetadataLoadEpochs.set(i,r);let o=()=>{this.entityMetadataLoads.get(t)===i&&this.entityMetadataLoads.delete(t)};return i.then(o,o),i}generateGenPageRuntimeTypes(t,r){return(0,eue.generateGenPageRuntimeTypes)(n=>this.fetchEntityMetadata(n),t,r)}findTables(t,r){return(0,Rl.findTables)(this.dataverse,t,r)}getEnvironmentLanguages(){return(0,tue.getEnvironmentLanguages)(this.dataverse)}listConnections(){return this.connectivity.listConnections()}listConnectorOperations(t){return this.connectivity.listConnectorOperations(t)}getConnectorOperationSchema(t,r){return this.connectivity.getConnectorOperationSchema(t,r)}listConnectorTables(t,r,n){return this.connectivity.listConnectorTables(t,r,n)}getConnectorTableSchema(t,r,n,i){return this.connectivity.getConnectorTableSchema(t,r,n,i)}findColumns(t,r,n){return(0,Rl.findColumns)(this.dataverse,t,r,n)}createTable(t){return this.schemaWrite([t.schemaName],()=>(0,Mt.createTable)(this.dataverse,t))}createColumn(t,r){return this.schemaWrite([t],()=>(0,Mt.createColumn)(this.dataverse,t,r))}createColumns(t,r){return this.schemaWrite([t],()=>(0,Mt.createColumns)(this.dataverse,t,r))}updateColumn(t,r,n){return this.schemaWrite([t],()=>(0,Mt.updateColumn)(this.dataverse,t,r,n))}deleteColumn(t,r){return this.schemaWrite([t],()=>(0,Mt.deleteColumn)(this.dataverse,t,r))}setFormSecurityRoles(t,r){return(0,$w.setFormSecurityRoles)(this.dataverse,t,r)}getFormSecurityRoles(t){return(0,$w.getFormSecurityRoles)(this.dataverse,t)}setColumnVisualization(t,r,n){return(0,Mt.setColumnVisualization)(this.dataverse,t,r,n)}getColumnVisualization(t,r){return(0,Mt.getColumnVisualization)(this.dataverse,t,r)}createCustomerColumn(t,r){return this.schemaWrite([t,"account","contact"],()=>(0,Mt.createCustomerColumn)(this.dataverse,t,r))}insertStatusValue(t,r){return this.schemaWrite([t],()=>(0,Mt.insertStatusValue)(this.dataverse,t,r))}updateTable(t,r){return this.schemaWrite([t],()=>(0,Mt.updateTable)(this.dataverse,t,r))}async setEntityIcon(t,r){if(await this.schemaWrite([t],()=>(0,Mt.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,ja.xmlText)(t)}</entity></entities></importexportxml>`;(0,Cr.ensureSuccess)(await this.dataverse.post("/PublishXml",{ParameterXml:n}),this.dataverse.apiUrl("/PublishXml"))}}createAlternateKey(t,r){return(0,Mt.createAlternateKey)(this.dataverse,t,r)}deleteAlternateKey(t,r){return(0,Mt.deleteAlternateKey)(this.dataverse,t,r)}createRelationship(t){let r=t.type==="ManyToMany"?[t.entity1,t.entity2]:[t.referencedEntity,t.referencingEntity];return this.schemaWrite(r,()=>(0,Mt.createRelationship)(this.dataverse,t))}deleteRelationship(t){return this.schemaWrite(void 0,()=>(0,Mt.deleteRelationship)(this.dataverse,t))}createGlobalOptionSet(t){return(0,Mt.createGlobalOptionSet)(this.dataverse,t)}deleteGlobalOptionSet(t){return(0,Mt.deleteGlobalOptionSet)(this.dataverse,t)}deleteTable(t){return this.schemaWrite(void 0,()=>(0,Mt.deleteTable)(this.dataverse,t))}createSecurityRole(t){return(0,Uc.createSecurityRole)(this.dataverse,t)}createPersonaRole(t){return(0,Uc.createPersonaRole)(this.dataverse,t)}deleteSecurityRole(t){return(0,Uc.deleteSecurityRole)(this.dataverse,t)}addEntityPrivilegesToRole(t,r){return(0,Uc.addEntityPrivilegesToRole)(this.dataverse,t,r)}getEntityPrivileges(t){return(0,Uc.getEntityPrivileges)(this.dataverse,t)}createRecord(t,r){return(0,io.createRecord)(this.dataverse,t,r)}createRecordsBulk(t,r){return(0,io.createRecordsBulk)(this.dataverse,t,r)}updateRecord(t,r,n){return(0,io.updateRecord)(this.dataverse,t,r,n)}upsertRecord(t,r,n){return(0,io.upsertRecord)(this.dataverse,t,r,n)}deleteRecord(t,r){return(0,io.deleteRecord)(this.dataverse,t,r)}getRecord(t,r,n){return(0,io.getRecord)(this.dataverse,t,r,n)}queryRecords(t,r){return(0,io.queryRecords)(this.dataverse,t,r)}seedRecordGraph(t,r){return(0,cue.seedRecordGraph)(this.dataverse,t,r)}resolveArtifact(t,r){return(0,WU.resolveArtifact)(this.dataverse,t,r)}findArtifact(t,r){return(0,WU.findArtifact)(this.dataverse,t,r)}async deleteAppCascade(t,r){await this.workspace.ensureReady();let n=await(0,aue.deleteAppCascade)(this.dataverse,t,r),i=(0,ja.normalizeGuid)(t,"appModuleId");return await this.workspace.readArtifact("app",i)&&await this.workspace.deleteArtifact("app",i),n}associateRecords(t,r,n){return(0,io.associateRecords)(this.dataverse,t,r,n)}disassociateRecords(t,r,n,i){return(0,io.disassociateRecords)(this.dataverse,t,r,n,i)}createWebResource(t){return(0,Fm.createWebResource)(this.dataverse,t)}updateWebResource(t,r){return(0,Fm.updateWebResource)(this.dataverse,t,r)}getWebResource(t){return(0,Fm.getWebResource)(this.dataverse,t)}deleteWebResource(t){return(0,Fm.deleteWebResource)(this.dataverse,t)}getAppSettings(t){return(0,Ll.readAppSettings)(this.dataverse,t)}setAppSetting(t,r,n){return(0,Ll.setAppSetting)(this.dataverse,t,r,n)}setHeaderAndNavigationRefresh(t,r){if(typeof r!="boolean")throw new Z.ValidationError("app",t,[{pointer:"/headerAndNavigationRefresh",rule:nue.HEADER_NAV_BOOLEAN_RULE,message:`enabled must be a boolean, got ${typeof r}`}]);return(0,Ll.setAppSetting)(this.dataverse,t,Ll.HEADER_AND_NAVIGATION_REFRESH,r?Ll.APP_SETTING_ON:Ll.APP_SETTING_OFF)}getSolution(t){return(0,ar.getSolution)(this.dataverse,t)}createPublisher(t){return(0,ar.createPublisher)(this.dataverse,t)}createSolution(t){return(0,ar.createSolution)(this.dataverse,t)}setSolutionVersion(t,r){return(0,ar.setSolutionVersion)(this.dataverse,t,r)}addSolutionComponent(t){return(0,ar.addSolutionComponent)(this.dataverse,t)}removeSolutionComponent(t,r,n){return(0,ar.removeSolutionComponent)(this.dataverse,t,r,n)}exportSolution(t){return(0,ar.exportSolution)(this.dataverse,t)}importSolution(t){return this.schemaWrite(void 0,()=>(0,ar.importSolution)(this.dataverse,t))}getDeploymentSettingsTemplate(t){return(0,ar.getDeploymentSettingsTemplate)(this.dataverse,t)}registerPcfControl(t,r){let n=()=>(0,iue.registerPcfControl)(this.dataverse,t,r);return r?.publishAll===!0?this.schemaWrite(void 0,n):n()}deleteSolution(t){return this.schemaWrite(void 0,()=>(0,ar.deleteSolution)(this.dataverse,t))}async getArtifact(t,r){return this.withArtifactLock(t,r,async()=>{let{artifact:n,meta:i}=await this.readWhole(t,r);return await this.acknowledgeRefresh(t,r,i),n})}async getArtifactUnlocked(t,r){return this.readRaw(t,r)}async readWhole(t,r){let{meta:n}=await this.revalidate(t,r);return{artifact:await this.readLocal(t,r),meta:n}}async acknowledgeRefresh(t,r,n){var i,o,a;let s=this.artifactKey(t,r),l=n===void 0?await this.versions.getMeta(t,r):n;this.baselineObserved.has(s)||this.baselineObserved.set(s,(i=l?.observedGeneration)!==null&&i!==void 0?i:0);let u=(o=l?.refreshGeneration)!==null&&o!==void 0?o:0;this.raiseGenerationHighWater(s,u),l&&u!==((a=l.observedGeneration)!==null&&a!==void 0?a:0)&&await this.versions.storeMeta(t,r,{...l,observedGeneration:u},l),this.observedGenerations.set(s,u)}raiseGenerationHighWater(t,r){var n;r>((n=this.generationHighWater.get(t))!==null&&n!==void 0?n:0)&&this.generationHighWater.set(t,r)}async observedAtInvocation(t,r,n){var i,o;if(n!==void 0)return n;let a=this.baselineObserved.get(this.artifactKey(t,r));return a!==void 0?a:(o=(i=await this.versions.getMeta(t,r))===null||i===void 0?void 0:i.observedGeneration)!==null&&o!==void 0?o:0}artifactKey(t,r){return`${t}\0${(0,QU.canonicalArtifactId)(r)}`}nextRefreshGeneration(t,r,n){var i,o,a;let s=this.artifactKey(t,r),l=Math.max((i=n?.refreshGeneration)!==null&&i!==void 0?i:0,(o=n?.observedGeneration)!==null&&o!==void 0?o:0,(a=this.generationHighWater.get(s))!==null&&a!==void 0?a:0)+1;return this.raiseGenerationHighWater(s,l),l}async readRaw(t,r){return await this.revalidateIfStale(t,r),this.readLocal(t,r)}async readForMutation(t,r,n,i){var o,a;let s=await this.observedAtInvocation(t,r,i);if(((a=(o=await this.versions.getMeta(t,r))===null||o===void 0?void 0:o.refreshGeneration)!==null&&a!==void 0?a:0)>s)throw new Z.StaleArtifactError(t,r,n,"pushed");if(await this.revalidateIfStale(t,r)==="refreshed-changed")throw new Z.StaleArtifactError(t,r,n);return this.readLocal(t,r)}async readLocal(t,r){let n=await this.workspace.readArtifact(t,r);if(!n)throw new Z.ArtifactNotFoundError(t,r);return n}async revalidateIfStale(t,r){return(await this.revalidate(t,r)).outcome}async revalidate(t,r){let n=await this.versions.getMeta(t,r);if(!n)return{outcome:"skipped",meta:null};let i=n.fetchedAt?Date.parse(n.fetchedAt):NaN,o=Date.now()-i;if(!Number.isNaN(i)&&this.cacheStalenessMs>0&&o<=this.cacheStalenessMs)return{outcome:"fresh",meta:n};if(await this.versions.isDirty(t,r,n))return{outcome:"skipped",meta:n};let a=await this.workspace.readArtifact(t,r);await this.fetchArtifactUnlocked(t,r);let s=await this.workspace.readArtifact(t,r);return{outcome:(0,_n.deepEqual)(a,s)?"refreshed-unchanged":"refreshed-changed"}}async queryTree(t,r,n){return this.withArtifactLock(t,r,async()=>{let{artifact:i,meta:o}=await this.readWhole(t,r),a=Nn.JsonPointer.resolve(i,n);if(a===void 0)throw new Z.PathNotFoundError(t,r,n);return n===""&&await this.acknowledgeRefresh(t,r,o),a})}async findElements(t,r,n){return this.withArtifactLock(t,r,async()=>(0,Qle.findElements)(await this.getArtifactUnlocked(t,r),n))}async withDirtyFlags(t){let r=[];for(let n of t)r.push({...n,isDirty:await this.versions.isDirty(n.type,n.id)});return r}async listArtifacts(t,r){return this.withDirtyFlags(await this.workspace.listArtifacts(t,r))}async getEntityMetadata(t){let r=await this.readCachedEntityMetadata(t);if(!r)throw new Z.ArtifactNotFoundError("entityMetadata",t);return r}async getFieldMetadata(t,r){let i=(await this.getEntityMetadata(t)).attributes.find(o=>o.logicalName===r);if(!i)throw new Z.PathNotFoundError("entityMetadata",t,r);return i}async updateElement(t,r,n,i){let o=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let a=await this.readForMutation(t,r,n,o),s=Nn.JsonPointer.resolve(a,n);if(s===void 0)throw new Z.PathNotFoundError(t,r,n);let l=oo(s)&&oo(i)?{...s,...i}:i;return Nn.JsonPointer.set(a,n,(0,Ai.cloneJson)(l)),this.assertStructurallyValid(t,r,a,n),await this.workspace.writeArtifact(t,r,a),this.getArtifactUnlocked(t,r)})}async addElement(t,r,n,i,o){let a=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let s=await this.readForMutation(t,r,n,a),l=Nn.JsonPointer.resolve(s,n);if(l===void 0)throw new Z.PathNotFoundError(t,r,n);if(!Array.isArray(l)){if(!oo(l)||!oo(i))throw new Z.ValidationError(t,r,n,"parent must be an array, or an object with an object of properties to add");if(o?.position!==void 0)throw new Z.ValidationError(t,r,n,"position is not supported for an object parent");let d={};for(let f of Object.keys(i)){if(f==="id")throw new Z.ValidationError(t,r,n,"refusing to write 'id' \u2014 that re-keys the node rather than adding a property");let m=(0,Ai.cloneJson)(i[f]),p=(0,Mm.isValueMapKey)(f)||(0,Mm.pointerTouchesValueMap)(n);d[f]=p?m:Array.isArray(m)?m.map(h=>oo(h)?this.assignMissingIds(t,h):h):oo(m)?this.assignMissingIds(t,m):m}for(let f of Object.keys(d))Nn.JsonPointer.set(s,Nn.JsonPointer.append(n,f),d[f]);return this.assertStructurallyValid(t,r,s,n),await this.workspace.writeArtifact(t,r,s),this.getArtifactUnlocked(t,r)}let u=(0,Mm.pointerTouchesValueMap)(n)?(0,Ai.cloneJson)(i):this.assignMissingIds(t,(0,Ai.cloneJson)(i)),c=_ue(l,o?.position);return l.splice(c,0,u),this.assertStructurallyValid(t,r,s,n),await this.workspace.writeArtifact(t,r,s),this.getArtifactUnlocked(t,r)})}async moveElement(t,r,n,i,o){let a=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{var s;let l=await this.readForMutation(t,r,n,a),u=Nn.JsonPointer.resolve(l,n);if(u===void 0)throw new Z.PathNotFoundError(t,r,n);let c=Nn.JsonPointer.resolve(l,i);if(c===void 0)throw new Z.PathNotFoundError(t,r,i);if(!Array.isArray(c))throw new Z.ValidationError(t,r,i,"move target must be an array");if(i===n||i.startsWith(`${n}/`))throw new Z.ValidationError(t,r,i,"cannot move an element into its own subtree");Nn.JsonPointer.remove(l,n);let d=(s=o?.index)!==null&&s!==void 0?s:c.length;c.splice(Math.max(0,Math.min(d,c.length)),0,u),YU(c);let f=Nn.JsonPointer.resolve(l,JU(n));return Array.isArray(f)&&f!==c&&YU(f),this.assertStructurallyValid(t,r,l,i),await this.workspace.writeArtifact(t,r,l),this.getArtifactUnlocked(t,r)})}async removeElement(t,r,n){let i=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let o=await this.readForMutation(t,r,n,i);if(Nn.JsonPointer.resolve(o,n)===void 0)throw new Z.PathNotFoundError(t,r,n);return Nn.JsonPointer.remove(o,n),this.assertStructurallyValid(t,r,o,JU(n)),await this.workspace.writeArtifact(t,r,o),this.getArtifactUnlocked(t,r)})}assertStructurallyValid(t,r,n,i){var o,a,s;let l=this.registrations.get(t),u=(s=(a=l==null?void 0:(o=l.adapter).validate)===null||a===void 0?void 0:a.call(o,n,i))!==null&&s!==void 0?s:[];if(u.length>0)throw new Z.ValidationError(t,r,u)}retrieveSetting(t,r){return(0,kl.retrieveSetting)(this.dataverse,t,r)}saveSettingValue(t,r,n){return(0,kl.saveSettingValue)(this.dataverse,t,r,n)}getAiReadiness(t){return(0,kl.getAiReadiness)(this.dataverse,t)}setAppAiFeatures(t,r,n){return(0,kl.setAppAiFeatures)(this.dataverse,t,r,n)}configureRowSummary(t,r){return(0,kl.configureRowSummary)(this.dataverse,t,r)}removeRowSummary(t){return(0,kl.removeRowSummary)(this.dataverse,t)}async enrichDefaultViews(t,r,n={}){let i=await(0,due.findDefaultViews)(this.dataverse,t,{excludeViewIds:n.excludeViewIds}),o=n.publish===!1,a=[],s=[],l=()=>({updated:[...a],results:[...s],pendingPublish:a.length>0?[{scope:(0,BU.boundEntityPublishScope)({entityLogicalName:t}),artifacts:a.map(c=>({type:"view",id:c}))}]:[]}),u;try{for(let c of i){await this.fetchArtifact("view",c.id),await this.updateElement("view",c.id,"/columns",r),u=c.id;let d=await this.pushArtifact("view",c.id);u=void 0,s.push(d),d.saved&&a.push(c.id)}}catch(c){throw u&&pue(c)&&a.push(u),o?(0,Z.withPartialEnrichment)(c,l()):c}if(o)return l();if(a.length){let c=await this.publishArtifact("view",a[0]);if(c.publish.kind==="failed")throw new Z.SdkError("ENRICH_DEFAULT_VIEWS_PUBLISH_FAILED",`enrichDefaultViews: ${a.length} view(s) on '${t}' were saved but the publish FAILED, so none of them is live (${c.publish.error.message}). Re-publish the entity to make them visible; the saves themselves are unaffected.`)}return{updated:a}}async createArtifact(t,r){let n=this.requireRegistration(t,"createArtifact"),i=n.adapter.assignMissingIds(n.adapter.createDefault(r)),o=i.id;if(!o)throw new Z.ValidationError(t,"(new)","/id","created artifact must have an id");return this.withArtifactLock(t,o,async()=>(await this.workspace.writeArtifact(t,o,i),(0,Ai.cloneJson)(i)))}async deleteArtifact(t,r){return this.withArtifactLock(t,r,async()=>{await this.workspace.deleteArtifact(t,r)})}async deleteRemoteArtifact(t,r){return this.withArtifactLock(t,r,async()=>{let n=this.requireRegistration(t,"deleteRemoteArtifact");await this.workspace.ensureReady(),await n.api.delete(this.dataverse,r),await this.workspace.readArtifact(t,r)&&await this.workspace.deleteArtifact(t,r)})}async publishArtifact(t,r,n){let{result:i,siblings:o}=await this.withArtifactLock(t,r,()=>this.publishArtifactUnlocked(t,r,n));for(let a of o)await this.withArtifactLock(a.type,a.id,()=>this.adoptBracket(a));return i}async publishArtifacts(t,r){var n,i;let o=new Map;for(let p of t){let h=this.artifactKey(p.type,p.id);o.has(h)||o.set(h,{type:p.type,id:p.id})}let a=[];for(let[p,h]of o)a.push(await this.withArtifactLock(h.type,h.id,()=>this.preparePublish(p,h.type,h.id)));let s=new Set(o.keys()),l=[],u=new Set;for(let p of a){let h=((n=p.scope)===null||n===void 0?void 0:n.envelope)==="entity"?(i=p.scope.entityLogicalName)===null||i===void 0?void 0:i.toLowerCase():void 0;p.scope&&h&&!u.has(h)&&(u.add(h),l.push(p.scope))}let c=await this.captureSiblings(l,s),d=vue(a),f;if(d)try{await(0,BU.publishXml)(this.dataverse,d)}catch(p){f=zo(p)}let m=new Map;for(let p of a)m.set(p.key,await this.withArtifactLock(p.type,p.id,()=>this.settlePublish(p,f,r)));for(let p of c)await this.withArtifactLock(p.type,p.id,()=>this.adoptBracket(p));return t.map(p=>({...m.get(this.artifactKey(p.type,p.id))}))}async preparePublish(t,r,n){var i;let o=await this.readRaw(r,n),a=this.registrations.get(r);if(!a?.publish)return{key:t,type:r,id:n,artifact:o,notApplicable:!0};let s=(i=a.publishScope)===null||i===void 0?void 0:i.call(a,n,o);if(!s||!bue.has(s.envelope))throw new Z.InvalidArgumentError(`publishArtifacts: ${r} '${n}' publishes through ${s?`a '${s.envelope}'`:"no declared"} scope, which one PublishXml envelope cannot carry. Publish it with publishArtifact.`);let l=a.rebaselineAfterPublish==="bracket"?await this.captureBracket(a,r,n):void 0;return{key:t,type:r,id:n,artifact:o,reg:a,scope:s,...l?{own:l}:{}}}async settlePublish(t,r,n){let{type:i,id:o}=t;if(t.notApplicable||!t.reg)return{type:i,id:o,shipped:!1,publish:{kind:"notApplicable"}};let a=t.scope?{publishScope:t.scope}:{};if(t.reg.rebaselineAfterPublish==="snapshot"&&await this.rebaselineAfterPublish(t.reg,i,o),t.own&&await this.adoptBracket(t.own),r)return{type:i,id:o,shipped:!1,publish:{kind:"failed",error:r},...a};if(!n?.verify)return{type:i,id:o,shipped:!1,publish:{kind:"submitted"},...a};let s=await this.workspace.readArtifact(i,o).catch(()=>null);if(!s||!(0,_n.deepEqual)(s,t.artifact))return{type:i,id:o,shipped:!1,publish:{kind:"unverifiable",reason:`the local ${i} was ${s?"edited":"deleted"} while the publish was in flight, so what shipped cannot be told from what is local now; verify it with publishArtifact`},...a};let l=await this.verifyPublished(i,o,t.artifact);return{type:i,id:o,shipped:l.kind==="verified",publish:l,...a}}async publishArtifactUnlocked(t,r,n){var i;let o=await this.readRaw(t,r),a=this.registrations.get(t);if(!a?.publish)return{result:{type:t,id:r,shipped:!1,publish:{kind:"notApplicable"}},siblings:[]};let s=(i=a.publishScope)===null||i===void 0?void 0:i.call(a,r,o),l=a.rebaselineAfterPublish==="bracket"?await this.captureBracket(a,t,r):void 0,u=s?await this.captureSiblings([s],new Set([this.artifactKey(t,r)])):[];try{await a.publish(this.dataverse,r,o)}catch(d){return{result:{type:t,id:r,shipped:!1,publish:{kind:"failed",error:zo(d)},...s?{publishScope:s}:{}},siblings:[]}}if(a.rebaselineAfterPublish==="snapshot"&&await this.rebaselineAfterPublish(a,t,r),l&&await this.adoptBracket(l),!n?.verify)return{result:{type:t,id:r,shipped:!1,publish:{kind:"submitted"},...s?{publishScope:s}:{}},siblings:u};let c=await this.verifyPublished(t,r,o);return{result:{type:t,id:r,shipped:c.kind==="verified",publish:c,...s?{publishScope:s}:{}},siblings:u}}async captureBracket(t,r,n){try{let i=await this.versions.getMeta(r,n),o=i?.etag;if(!(0,Cr.isVersionToken)(o)||!t.api.readContentThenToken)return;let{raw:a,etag:s,siblingEtags:l}=await t.api.readContentThenToken(this.dataverse,n),u=i?.siblingEtags;return s!==o||!Sue(u,l)?void 0:{type:r,id:n,reg:t,heldEtag:o,...u?{heldSiblings:u}:{},content:this.bracketContent(t,a)}}catch{return}}async captureSiblings(t,r){var n,i,o;let a=new Map;for(let u of t){let c=u.envelope==="entity"?(n=u.entityLogicalName)===null||n===void 0?void 0:n.toLowerCase():void 0;c&&!a.has(c)&&a.set(c,[])}if(a.size===0)return[];let s;try{s=await this.workspace.listArtifacts()}catch{return[]}for(let u of s){let c=this.registrations.get(u.type);if(!(r.has(this.artifactKey(u.type,u.id))||c?.rebaselineAfterPublish!=="bracket"||!c.publishScope))try{let d=await this.workspace.readArtifact(u.type,u.id),f=d?c.publishScope(u.id,d):void 0,m=f?.envelope==="entity"?(i=f.entityLogicalName)===null||i===void 0?void 0:i.toLowerCase():void 0;m!==void 0&&((o=a.get(m))===null||o===void 0||o.push(u))}catch{continue}}let l=[];for(let u of a.values())for(let c of u){let d=this.registrations.get(c.type),f=d?await this.captureBracket(d,c.type,c.id):void 0;f&&l.push(f)}return l}async adoptBracket(t){var r;try{let n=await this.versions.getMeta(t.type,t.id);if(!n||n.etag!==t.heldEtag||!(0,_n.deepEqual)((r=n.siblingEtags)!==null&&r!==void 0?r:void 0,t.heldSiblings))return;let{raw:i,etag:o,siblingEtags:a}=await t.reg.api.get(this.dataverse,t.id);if(!(0,Cr.isVersionToken)(o)||!ZU(a,t.heldSiblings)||!eB(a)||!(o!==t.heldEtag||!(0,_n.deepEqual)(a??void 0,t.heldSiblings))||!(0,_n.deepEqual)(this.bracketContent(t.reg,i),t.content))return;await this.versions.storeMeta(t.type,t.id,{...n,etag:o,...t.heldSiblings?{siblingEtags:{...a}}:{},fetchedAt:(0,Cr.nowIso)()},n)}catch{}}bracketContent(t,r){var n,i,o;let a=t.adapter.fromApiResponse(r);return(o=(i=(n=t.adapter).baselineContent)===null||i===void 0?void 0:i.call(n,a))!==null&&o!==void 0?o:a}adoptReadBack(t,r){try{return{artifact:t.adapter.fromApiResponse(r)}}catch(n){return{warning:`The write was saved, but the record read back after it could not be read into the local copy (${zo(n).message}). The SDK holds no version for it now, so the next push is refused: re-fetch before editing again.`}}}adoptedAsSent(t,r,n,i){try{let o={...n,...i},a=t.adapter.fromApiResponse(t.adapter.completeAsStored?t.adapter.completeAsStored(o,n):o);return(0,_n.deepEqual)(r,a)}catch{return!1}}async rebaselineAfterPublish(t,r,n){try{let i=await this.versions.getMeta(r,n);if(!i)return;let{raw:o,etag:a,memberEtags:s,siblingEtags:l}=t.api.getForRebaseline?await t.api.getForRebaseline(this.dataverse,n):await t.api.get(this.dataverse,n),u=t.adapter.fromApiResponse(o),c=d=>{var f,m,p;return(p=(m=(f=t.adapter).baselineContent)===null||m===void 0?void 0:m.call(f,d))!==null&&p!==void 0?p:d};if(!a||!(0,_n.deepEqual)(c(i.snapshot),c(u)))return;await this.versions.storeMeta(r,n,{...i,etag:a,fetchedAt:(0,Cr.nowIso)(),...s?{memberEtags:s}:{},...l?{siblingEtags:l}:{}},i)}catch{}}async verifyPublished(t,r,n){var i,o,a,s,l;if(t!=="app"){let u=this.registrations.get(t);return u?.api.getPublished?this.verifyPublishedContent(u,t,r,n):{kind:"unverifiable",reason:`published-projection verification is not characterised for '${t}'; the publish was submitted`}}try{let u=`/appmodules(${(0,ja.normalizeGuid)(r,"id")})${(0,ja.odataQuery)([["$select","appmoduleid,name,description"]])}`,c=await this.dataverse.get(u);if(c.status>=200&&c.status<300){let d=(i=c.body)!==null&&i!==void 0?i:{},f=n;if(!f)return{kind:"unverifiable",reason:"there is no local copy of the app to compare the published projection with"};let m=[];return((o=f.name)!==null&&o!==void 0?o:"")!==((a=d.name)!==null&&a!==void 0?a:"")&&m.push("name"),((s=f.description)!==null&&s!==void 0?s:"")!==((l=d.description)!==null&&l!==void 0?l:"")&&m.push("description"),m.length>0?{kind:"unverifiable",reason:`the published projection does not yet match the saved app (${m.join(", ")} still differ). PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}:{kind:"verified"}}return{kind:"unverifiable",reason:`the published projection answered HTTP ${c.status}`}}catch(u){return{kind:"unverifiable",reason:zo(u).message}}}async verifyPublishedContent(t,r,n,i){var o,a,s;try{let l=f=>{var m,p,h;return(h=(p=(m=t.adapter).baselineContent)===null||p===void 0?void 0:p.call(m,f))!==null&&h!==void 0?h:f},u=l(i),c=(o=await this.versions.getMeta(r,n))===null||o===void 0?void 0:o.snapshot;if(c===void 0||!(0,_n.deepEqual)(u,l(c)))return{kind:"unverifiable",reason:`the local ${r} holds edits that were never pushed, so no publish could have shipped them \u2014 push, then publish again`};let d=await((s=(a=t.api).getPublished)===null||s===void 0?void 0:s.call(a,this.dataverse,n));return d?(0,_n.deepEqual)(u,l(t.adapter.fromApiResponse(d.raw)))?{kind:"verified"}:{kind:"unverifiable",reason:"the published projection does not show what was pushed. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists"}:{kind:"unverifiable",reason:`the ${r} is not in the published projection yet. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}}catch(l){return{kind:"unverifiable",reason:zo(l).message}}}async pushArtifact(t,r){return this.withArtifactLock(t,r,()=>this.pushArtifactUnlocked(t,r))}async prepareArtifactUnlocked(t,r,n){var i,o;let a=this.requireRegistration(t,"pushArtifact"),s=await this.workspace.readArtifactWithText(t,r);if(!s)throw new Z.ArtifactNotFoundError(t,r);let l=s.artifact,u=s.text,c=(o=(i=a.adapter).normalize)===null||o===void 0?void 0:o.call(i,l);c&&c!==l&&(await this.workspace.writeArtifact(t,r,c),l=c,u=void 0);let d=await this.versions.getMeta(t,r);this.assertLanguageMatches(t,r,d,a),this.assertProjectionMatches(t,r,d);let f=await this.buildMetadataContext(a.adapter,l,d?.snapshot),m=await a.adapter.toApiPayload(l,d?.snapshot,f);return await this.assertSemanticallyComplete(a,t,r,l,d===null,d?.everActivated,n),{type:t,id:r,reg:a,json:l,...u!==void 0?{storedText:u}:{},meta:d,payload:m}}async assertSemanticallyComplete(t,r,n,i,o,a,s){let l=t.adapter.issuesBlockingPush;if(!l)return;let u=i.entityLogicalName,d=(u?await this.columnsForCheck(t,u,i,s):[]).map(m=>({logicalName:m.logicalName,displayName:m.displayName,attributeType:m.attributeType,isCustomAttribute:m.isCustomAttribute,...m.maxLength!==void 0?{maxLength:m.maxLength}:{},...m.options?{options:m.options.map(p=>({value:p.value,label:p.label}))}:{},...m.targets?{targets:m.targets}:{}})),f=l.call(t.adapter,i,d,{isCreate:o,everActivated:a});if(f.length>0)throw new Z.ValidationError(r,n,f)}columnsForCheck(t,r,n,i){var o,a,s;let l=(s=(a=(o=t.adapter).columnsCheckedAtPush)===null||a===void 0?void 0:a.call(o,n))!==null&&s!==void 0?s:[],u=async()=>{let f=await this.readCachedEntityMetadata(r);if(f)return f.attributes;try{return await(0,Rl.readCheckColumns)(this.dataverse,r,l)}catch{return[]}};if(!i)return u();let c=[r,...[...new Set(l)].sort()].join("\0"),d=i.get(c);return d||(d=u(),i.set(c,d)),d}async pushArtifactUnlocked(t,r,n){return this.executePrepared(await this.prepareArtifactUnlocked(t,r,n))}async executePrepared(t){var r,n,i,o,a,s,l,u,c;let{type:d,id:f,reg:m,json:p,meta:h,payload:g}=t,b=!1;try{let w;if(h)w=await m.api.update(this.dataverse,f,g,h.etag,h.memberEtags,h.siblingEtags);else{let P=await this.createWithMintedId(m,d,f,g,p);if("adopted"in P)return await this.persistAdoption(d,f,p,P.adopted);w=P.written}b=!0;let C=f;h||(w.serverIdentity&&m.adapter.applyServerIdentity&&m.adapter.applyServerIdentity(p,w.serverIdentity),w.id&&w.id!==f&&(p.id=w.id,await this.workspace.deleteArtifact(d,f),C=w.id));let S=h&&w.readBack!==void 0?this.adoptReadBack(m,w.readBack):void 0,O=S?.artifact?{artifact:S.artifact,baseline:S.artifact}:m.adapter.committed?m.adapter.committed(p,g,{intentPending:w.intentPending===!0}):{artifact:p,baseline:p};await this.workspace.writeArtifact(d,C,O.artifact,h&&C===f?t.storedText:void 0);let L=S?.artifact!==void 0&&!(0,_n.deepEqual)(S.artifact,p),I=L?this.nextRefreshGeneration(d,C,h):(r=h?.refreshGeneration)!==null&&r!==void 0?r:0,D=[...(n=w.warnings)!==null&&n!==void 0?n:[],...S?.warning?[S.warning]:[],...S?.artifact!==void 0&&!this.adoptedAsSent(m,S.artifact,w.readBack,g)?[`Saved, but the server holds something other than what was pushed (another writer saved in between, or the platform rewrote something the SDK does not model \u2014 a label in a language the org does not provision, a hand-written fragment); the local ${d} now holds the server's version. Read it (getArtifact) before the next edit: a mutation whose pointer was derived from the earlier copy is refused (StaleArtifactError).`]:[]];return await this.versions.storeMeta(d,C,{etag:S&&!S.artifact?null:w.etag,...I>0?{refreshGeneration:I,observedGeneration:(i=h?.observedGeneration)!==null&&i!==void 0?i:0}:{},languageCode:this.languageCode,projectionVersion:Pl.PROJECTION_VERSION,fetchedAt:(0,Cr.nowIso)(),snapshot:(0,Ai.cloneJson)(O.baseline),...w.memberEtags?{memberEtags:w.memberEtags}:{},...w.siblingEtags?{siblingEtags:w.siblingEtags}:{}},C===f?h:void 0),{type:d,id:C,saved:!0,shipped:!1,publish:(o=w.publish)!==null&&o!==void 0?o:{kind:"notRequested"},...w.publish&&w.publish.kind!=="notRequested"?(()=>{var P;let x=(P=m.publishScope)===null||P===void 0?void 0:P.call(m,C,p);return x?{publishScope:x}:{}})():{},...L?{refreshed:!0}:{},...D.length>0?{warnings:D}:{}}}catch(w){let C=(0,Z.readPartialTokens)(w);if(C&&h){let S={...(a=h.memberEtags)!==null&&a!==void 0?a:{},...(s=C.memberEtags)!==null&&s!==void 0?s:{}},O={...(l=h.siblingEtags)!==null&&l!==void 0?l:{},...(u=C.siblingEtags)!==null&&u!==void 0?u:{}};await this.versions.storeMeta(d,f,{...h,...Object.keys(S).length>0?{memberEtags:S}:{},...Object.keys(O).length>0?{siblingEtags:O}:{}},h)}if(w instanceof Z.SdkError&&w.code===Er.ALREADY_EXISTS_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===UU.WFOM_API_UNAVAILABLE_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===UU.BUSINESS_RULE_LEFT_DEACTIVATED_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===Cr.VERSION_CONFLICT_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:(0,GU.isFailureAfterPrimaryWrite)(w)?w:new Z.VersionConflictError(d,f,(c=h?.etag)!==null&&c!==void 0?c:null,null,w.message)};throw b?fue(w):w}}assertLanguageMatches(t,r,n,i){if(i?.languageSensitive&&!(n?.languageCode===void 0||n.languageCode===this.languageCode))throw new Z.SdkError("ARTIFACT_LANGUAGE_MISMATCH",`Refusing to push ${t} '${r}': it was fetched with languageCode ${n.languageCode} but this SDK is configured with ${this.languageCode}. Pushing would rewrite labels read in one language as labels in another. Re-fetch with languageCode ${this.languageCode}, or create the SDK with languageCode ${n.languageCode}.`)}assertProjectionMatches(t,r,n){var i;if(n&&n.projectionVersion!==Pl.PROJECTION_VERSION)throw new Z.SdkError("ARTIFACT_PROJECTION_STALE",`Refusing to push ${t} '${r}': its workspace copy was produced by projection version ${(i=n.projectionVersion)!==null&&i!==void 0?i:"unknown (pre-versioning)"}, but this SDK produces version ${Pl.PROJECTION_VERSION}. The parsers changed in between, so an unedited part of this artifact can no longer be told apart from an edited one and pushing could overwrite server content the caller never touched. Re-fetch it with fetchArtifact('${t}', '${r}') and re-apply any local edits.`)}async createWithMintedId(t,r,n,i,o){try{return{written:await t.api.create(this.dataverse,i,n)}}catch(a){let s=r==="form"?(0,$w.readPrimaryCreateRefusal)(a):void 0;if(s?.status===404&&await(0,VU.formExistsAtId)(()=>t.api.get(this.dataverse,n),s.sent.formid)){let u=`the platform answered the create with ${a.message} \u2014 this build refuses a replayed create that way \u2014 but a read of that id finds the record`;throw(0,Z.attachCause)(new Z.SdkError(Er.ALREADY_EXISTS_CODE,Mw(r,n,u)+(this.createRecovery==="adoptExact"?` ${KU(Cue)}`:"")),a)}if(!(a instanceof Z.SdkError)||a.code!==Cr.VERSION_CONFLICT_CODE||(0,GU.isFailureAfterPrimaryWrite)(a))throw a;if(this.createRecovery==="adoptExact"&&s?.status===412){let l=await(0,VU.recoverFormCreate)({client:this.dataverse,read:()=>t.api.get(this.dataverse,n),sent:s.sent,authoredFormType:o.formType,project:u=>t.adapter.fromApiResponse(u)});if("adopted"in l)return{adopted:l.adopted};throw new Z.SdkError(Er.ALREADY_EXISTS_CODE,`${Mw(r,n)} ${KU(l.refused)}`)}throw new Z.SdkError(Er.ALREADY_EXISTS_CODE,Mw(r,n))}}async persistAdoption(t,r,n,i){let{artifact:o,etag:a}=i,s=!(0,_n.deepEqual)(o,n);return await this.versions.storeMeta(t,r,{etag:a,...s?{refreshGeneration:this.nextRefreshGeneration(t,r,null),observedGeneration:0}:{},languageCode:this.languageCode,projectionVersion:Pl.PROJECTION_VERSION,fetchedAt:(0,Cr.nowIso)(),snapshot:(0,Ai.cloneJson)(o)},null),s&&await this.workspace.writeArtifact(t,r,o),{type:t,id:r,saved:!1,adoptedExisting:!0,shipped:!1,publish:{kind:"notRequested"},...s?{refreshed:!0}:{}}}async buildMetadataContext(t,r,n){var i,o,a,s;let l=(o=(i=t.metadataNeeds)===null||i===void 0?void 0:i.call(t,r,n))!==null&&o!==void 0?o:[],u=new Set(l.map(L=>L.entityLogicalName).filter(L=>!!L)),c=new Set(l.filter(L=>L.needsColumnDetail).map(L=>L.entityLogicalName)),d=new Set(l.filter(L=>L.needsColumnDetail||!L.fieldName).map(L=>L.entityLogicalName)),f=L=>l.filter(I=>I.entityLogicalName===L).every(I=>I.fetchRequired===!1),m=new Map,p=new Map;for(let L of u){let I=await this.readCachedEntityMetadata(L);if(I&&c.has(L)&&(I.columnDetailComplete!==!0||!(typeof I.columnDetailVersion=="number"&&I.columnDetailVersion>=Rl.COLUMN_DETAIL_VERSION)||I.attributes.some(D=>typeof D.attributeTypeName!="string"))&&(I=null),!I&&!d.has(L)){if(!f(L)){let D=l.filter(P=>P.entityLogicalName===L).map(P=>P.fieldName);try{let P=await(0,Rl.readColumnHints)(this.dataverse,L,D);p.set(L,new Map(P.map(x=>[x.logicalName,x])))}catch{}}continue}if(!I&&!f(L))try{await this.loadMissedEntityMetadata(L),I=await this.readCachedEntityMetadata(L)}catch{}I&&m.set(L,I)}let h=(L,I)=>{var D,P,x;return(P=(D=m.get(L))===null||D===void 0?void 0:D.attributes.find(K=>K.logicalName===I))!==null&&P!==void 0?P:(x=p.get(L))===null||x===void 0?void 0:x.get(I)},g=this.languageCode,w=l.some(L=>{if(!L.needsLabel||!L.fieldName)return!1;let I=h(L.entityLogicalName,L.fieldName);return I?.localizedDisplayName!==void 0&&!I.localizedDisplayName[g]})?await this.readBaseLanguage():void 0,C=!((a=t.needsBaseLanguage)===null||a===void 0)&&a.call(t,r)?await this.readBaseLanguage():void 0,S=(s=t.customControlNeeds)===null||s===void 0?void 0:s.call(t,r,n),O=S&&(S.controls.length>0||S.columns.length>0)?await this.readPcfNeeds(S):void 0;return{resolveField:(L,I)=>{let D=h(L,I);return D?{displayName:Nue(D,g,w),attributeType:D.attributeType}:void 0},resolveEntity:L=>m.get(L),loadTypeScript:()=>this.compiler.load(),...C!==void 0?{baseLanguageCode:C}:{},...O?{pcf:O}:{}}}async readPcfNeeds(t){let r=new Map;for(let i of t.controls)r.set(i,await(0,qU.readControlManifest)(this.dataverse,i));let n=new Map;for(let i of t.columns)n.set(i,await(0,qU.readPcfColumn)(this.dataverse,t.entityLogicalName,i,t.requireCreateEligibility?{requireCreateEligibility:!0}:void 0));return{control:i=>r.get(i),column:(i,o)=>i===t.entityLogicalName?n.get(o):void 0}}readBaseLanguage(){if(!this.baseLanguage){let t=(async()=>{var r,n,i;try{let o=await this.dataverse.get("/organizations?$select=languagecode");if(o.status<200||o.status>=300)return;let a=Number((i=(n=(r=o.body)===null||r===void 0?void 0:r.value)===null||n===void 0?void 0:n[0])===null||i===void 0?void 0:i.languagecode);return Number.isInteger(a)&&a>0?a:void 0}catch{return}})();this.baseLanguage=t,t.then(r=>{r===void 0&&this.baseLanguage===t&&(this.baseLanguage=void 0)})}return this.baseLanguage}async pushAll(){let t=await this.getDirtyArtifacts();await this.warmBatchMetadata(t);let r=new Map,n=new Map;for(let o=0;o<t.length;o+=1){let a=t[o];try{await this.withArtifactLock(a.type,a.id,()=>this.prepareArtifactUnlocked(a.type,a.id,r))}catch(s){n.set(o,{type:a.type,id:a.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:zo(s)})}}if(n.size>0)return t.map((o,a)=>{var s;return(s=n.get(a))!==null&&s!==void 0?s:{type:o.type,id:o.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:new Z.SdkError(Er.PUSH_NOT_ATTEMPTED_CODE,`Not attempted: ${n.size} artifact(s) in this batch could not be prepared, so no writes were issued. Fix the reported failures and push again.`)}});let i=[];for(let o of t)try{i.push(await this.withArtifactLock(o.type,o.id,()=>this.pushArtifactUnlocked(o.type,o.id,r)))}catch(a){i.push({type:o.type,id:o.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:zo(a)})}return i}async warmBatchMetadata(t){var r,n,i;let o=new Set;for(let a of t){let s=this.registrations.get(a.type);if(!s)continue;let l;try{l=await this.readLocal(a.type,a.id)}catch{continue}let u=l.entityLogicalName;u&&o.add(u);for(let c of(i=(n=(r=s.adapter).metadataNeeds)===null||n===void 0?void 0:n.call(r,l))!==null&&i!==void 0?i:[])c.entityLogicalName&&o.add(c.entityLogicalName)}for(let a of o)if(!await this.readCachedEntityMetadata(a))try{await this.loadMissedEntityMetadata(a)}catch{}}async getDirtyArtifacts(){return(await this.withDirtyFlags(await this.workspace.listArtifacts())).filter(r=>r.isDirty)}async diffArtifact(t,r){return this.versions.diff(t,r)}assignMissingIds(t,r){let n=this.registrations.get(t);return n?n.adapter.assignMissingIds(r):(0,Mm.assignMissingIds)(r)}async resolveComponentType(t){if(t.genPage)return"genPage";switch(t.componentType){case ar.SolutionComponentType.SavedQuery:return"view";case ar.SolutionComponentType.SavedQueryVisualization:return"chart";case ar.SolutionComponentType.AppModule:return"app";case ar.SolutionComponentType.Workflow:return this.workflowArtifactType(t);case ar.SolutionComponentType.SystemForm:return this.systemFormArtifactType(t.objectId);default:return}}async systemFormArtifactType(t){let r=await(0,xm.readSystemFormType)(this.dataverse,t);if(Number.isNaN(r))throw new Z.SdkError(Fw,`System form '${t}' answered without a readable type, so whether it is a form or a dashboard cannot be told.`);return(0,xm.systemFormKindOf)(r)}async workflowArtifactType(t){let r=(0,ja.normalizeGuid)(t.objectId,"workflowId"),n=`/workflows(${r})${(0,ja.odataQuery)([["$select","category,businessprocesstype"]])}`,o=(0,Cr.ensureSuccess)(await this.dataverse.get(n),this.dataverse.apiUrl(n)).body,a=(0,xm.decodeCode)(o?.category);if(Number.isNaN(a))throw new Z.SdkError(Fw,`Workflow '${r}' answered without a readable category, so its kind cannot be told.`);if(t.workflowCategory=a,a===hue)return"businessRule";if(a===gue){let s=(0,xm.decodeCode)(o?.businessprocesstype);if(Number.isNaN(s))throw new Z.SdkError(Fw,`Workflow '${r}' (category 4) answered without a readable businessprocesstype, so whether it is a business process flow or a task flow cannot be told.`);return s===0?"bpf":void 0}}requireRegistration(t,r){let n=this.registrations.get(t);if(!n)throw new Z.NotImplementedError(r,`no adapter registered for artifact type '${t}'`);return n}};Er.MakerSdk=Um;function Aue(e){return new Um(e)}Er.createMakerSdk=Aue;function zo(e){return e instanceof Error?e:new Error(String(e))}function ZU(e,t){let r=Object.keys(e??{}),n=Object.keys(t??{});return r.length===n.length&&r.every(i=>Object.prototype.hasOwnProperty.call(t??{},i))}function eB(e){return Object.values(e??{}).every(Cr.isVersionToken)}function Sue(e,t){return ZU(e,t)&&eB(e)&&Object.keys(e??{}).every(r=>t?.[r]===e?.[r])}function KU(e){return`createRecovery 'adoptExact' did not adopt it: ${e}.`}function Mw(e,t,r){return`Cannot create ${e} '${t}': a record already exists at that id${r?` (${r})`:""}, so an earlier push of this artifact committed before its local version metadata was saved. No duplicate was created. Run fetchArtifact('${e}', '${t}', { overwrite: true }) to adopt the existing record's identity, etag and snapshot \u2014 the overwrite is required, because this local copy has never been pushed, so a plain fetch keeps it and adopts nothing; it REPLACES the local copy, so keep any outstanding local changes aside first \u2014 then re-apply them and push again: a conditional update, provided the adopted record is complete. If the earlier push committed only PART of a multi-row artifact (e.g. an app's appmodule without its sitemap), that update refuses, naming what is missing and how to remove the partial record. This is not done automatically because the only recovery available here would be an UNCONDITIONAL overwrite, which would destroy any edit made to the record in the meantime.`}function Nue(e,t,r){let n=e.localizedDisplayName;return n?.[t]||(r===void 0?void 0:n?.[r])||e.displayName}function oo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function JU(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function YU(e){e.length===0||!e.every(t=>oo(t)&&typeof t.order=="number")||e.forEach((t,r)=>{t.order=r})}function _ue(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=>oo(i)&&i.id===t.before);return n<0?e.length:n}let r=e.findIndex(n=>oo(n)&&n.id===t.after);return r<0?e.length:r+1}});var rB=v(Bm=>{"use strict";Object.defineProperty(Bm,"__esModule",{value:!0});Bm.ARTIFACT_TYPES=void 0;Bm.ARTIFACT_TYPES=["form","view","businessRule","app","command","chart","dashboard","genPage","bpf"]});var iB=v(nB=>{"use strict";Object.defineProperty(nB,"__esModule",{value:!0})});var aB=v(oB=>{"use strict";Object.defineProperty(oB,"__esModule",{value:!0})});var lB=v(sB=>{"use strict";Object.defineProperty(sB,"__esModule",{value:!0})});var cB=v(uB=>{"use strict";Object.defineProperty(uB,"__esModule",{value:!0})});var fB=v(dB=>{"use strict";Object.defineProperty(dB,"__esModule",{value:!0})});var mB=v(pB=>{"use strict";Object.defineProperty(pB,"__esModule",{value:!0})});var gB=v(hB=>{"use strict";Object.defineProperty(hB,"__esModule",{value:!0})});var bB=v(yB=>{"use strict";Object.defineProperty(yB,"__esModule",{value:!0})});var wB=v(vB=>{"use strict";Object.defineProperty(vB,"__esModule",{value:!0})});var EB=v(CB=>{"use strict";Object.defineProperty(CB,"__esModule",{value:!0})});var SB=v(AB=>{"use strict";Object.defineProperty(AB,"__esModule",{value:!0})});var _B=v(NB=>{"use strict";Object.defineProperty(NB,"__esModule",{value:!0})});var DB=v(TB=>{"use strict";Object.defineProperty(TB,"__esModule",{value:!0})});var OB=v(IB=>{"use strict";Object.defineProperty(IB,"__esModule",{value:!0})});var RB=v(PB=>{"use strict";Object.defineProperty(PB,"__esModule",{value:!0})});var kB=v(LB=>{"use strict";Object.defineProperty(LB,"__esModule",{value:!0})});var xB=v($B=>{"use strict";Object.defineProperty($B,"__esModule",{value:!0})});var MB=v(FB=>{"use strict";Object.defineProperty(FB,"__esModule",{value:!0})});var BB=v(UB=>{"use strict";Object.defineProperty(UB,"__esModule",{value:!0})});var VB=v(qB=>{"use strict";Object.defineProperty(qB,"__esModule",{value:!0})});var WB=v(GB=>{"use strict";Object.defineProperty(GB,"__esModule",{value:!0})});var jB=v(zB=>{"use strict";Object.defineProperty(zB,"__esModule",{value:!0})});var KB=v(ce=>{"use strict";var Tue=ce&&ce.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),Ue=ce&&ce.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&Tue(t,e,r)};Object.defineProperty(ce,"__esModule",{value:!0});ce.projectConnectorOperationSchema=ce.projectConnectorOperations=ce.createMakerSdk=void 0;var Due=tB();Object.defineProperty(ce,"createMakerSdk",{enumerable:!0,get:function(){return Due.createMakerSdk}});Ue(rB(),ce);Ue(iB(),ce);Ue(aB(),ce);Ue(lB(),ce);Ue(cB(),ce);Ue(fB(),ce);Ue(mB(),ce);Ue(gB(),ce);Ue(bB(),ce);Ue(wB(),ce);Ue(EB(),ce);Ue(SB(),ce);Ue(_B(),ce);Ue(DB(),ce);Ue(OB(),ce);Ue(nf(),ce);Ue(RB(),ce);Ue(kB(),ce);Ue(xB(),ce);Ue(MB(),ce);Ue(BB(),ce);Ue(VB(),ce);Ue(WB(),ce);Ue(jB(),ce);Ue(Q(),ce);var HB=Wl();Object.defineProperty(ce,"projectConnectorOperations",{enumerable:!0,get:function(){return HB.projectConnectorOperations}});Object.defineProperty(ce,"projectConnectorOperationSchema",{enumerable:!0,get:function(){return HB.projectConnectorOperationSchema}})});var Bw=v(Si=>{"use strict";var Iue=Si&&Si.__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]})),Oue=Si&&Si.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),QB=Si&&Si.__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)&&Iue(t,e,r);return Oue(t,e),t};Object.defineProperty(Si,"__esModule",{value:!0});Si.NodeFileSystemStorage=void 0;var Nt=QB(require("fs")),sr=QB(require("path")),JB=Q(),YB=mh();async function XB(e){let t;try{t=await Nt.promises.lstat(e)}catch{return}if(t.isSymbolicLink()){try{await Nt.promises.unlink(e)}catch{await Nt.promises.rmdir(e)}return}if(!t.isDirectory()){await Nt.promises.unlink(e);return}for(let r of await Nt.promises.readdir(e))await XB(sr.join(e,r));await Nt.promises.rmdir(e)}var Uw=class{constructor(t){this.root=t}getRoot(){return this.root}pathFor(t,r=!0){return this.assertWithinRoot(sr.join(this.root,...t),r)}realPathThroughNearestAncestor(t){let r=t,n=[];for(;!Nt.existsSync(r);){n.unshift(sr.basename(r));let i=sr.dirname(r);if(i===r)return sr.resolve(t);r=i}return sr.resolve(Nt.realpathSync(r),...n)}assertWithinRoot(t,r){let n=sr.resolve(this.root),i=sr.resolve(t);if(i!==n&&!i.startsWith(n+sr.sep))throw new JB.PathTraversalError(t,this.root);let o=this.realPathThroughNearestAncestor(n),a=r?this.realPathThroughNearestAncestor(i):sr.resolve(this.realPathThroughNearestAncestor(sr.dirname(i)),sr.basename(i));if(a!==o&&!a.startsWith(o+sr.sep))throw new JB.PathTraversalError(t,this.root);return i}async readText(t){let r=this.pathFor(t);if(!Nt.existsSync(r))return null;try{return await(0,YB.retryTransientIoAsync)(()=>Nt.promises.readFile(r,"utf8"))}catch(n){if(n.code==="ENOENT")return null;throw n}}async writeTextAtomic(t,r){let n=this.pathFor(t),i=sr.dirname(n);await Nt.promises.mkdir(i,{recursive:!0});let o=sr.join(i,`.${sr.basename(n)}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);try{await Nt.promises.writeFile(o,r,"utf8"),await(0,YB.retryTransientIoAsync)(()=>Nt.promises.rename(o,n))}catch(a){try{Nt.existsSync(o)&&await Nt.promises.unlink(o)}catch{}throw a}}async deleteFile(t){let r=this.pathFor(t);Nt.existsSync(r)&&await Nt.promises.unlink(r)}async deleteByPrefix(t){await XB(this.pathFor(t,!1))}async ensureContainer(t){await Nt.promises.mkdir(this.pathFor(t),{recursive:!0})}async exists(t){return Nt.existsSync(this.pathFor(t))}};Si.NodeFileSystemStorage=Uw});var ZB=v(Wr=>{"use strict";var Pue=Wr&&Wr.__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]})),Rue=Wr&&Wr.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Lue=Wr&&Wr.__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)&&Pue(t,e,r);return Rue(t,e),t};Object.defineProperty(Wr,"__esModule",{value:!0});Wr.loadNodeTypeScript=Wr.createNodeWorkspaceStorage=Wr.NodeFileSystemStorage=void 0;var kue=Bw(),$ue=Bw();Object.defineProperty(Wr,"NodeFileSystemStorage",{enumerable:!0,get:function(){return $ue.NodeFileSystemStorage}});function xue(e){return new kue.NodeFileSystemStorage(e)}Wr.createNodeWorkspaceStorage=xue;async function Fue(){return await Promise.resolve().then(()=>Lue(require("typescript")))}Wr.loadNodeTypeScript=Fue});var ao={};module.exports=zr(ao);so(ao,Ce(KB()),module.exports);so(ao,Ce(ZB()),module.exports);